You did not post the code generated by the compiler, so there' some guesswork here, but even without having seen it, one can say that this:
test rax, 1
jpe even
... has a 50% chance of mispredicting the branch, and that will come expensive.
The compiler almost certainly does both computations (which costs neglegibly more since the div/mod is quite long latency, so the multiply-add is "free") and follows up with a CMOV. Which, of course, has a zero percent chance of being mispredicted.
It's important to evaluate the different ways you can create an HttpClient, and part of that is understanding HttpClientFactory.
This is not a direct answer I know - but you're better off starting here than ending up with new HttpClient(...)
everywhere.
size_t is 64 bit normally on 64 bit machine
MS SQL 2008 can also use the string version of true or false...
select * from users where active = 'true'
-- or --
select * from users where active = 'false'
Yes, window.onfocus
and window.onblur
should work for your scenario:
http://www.thefutureoftheweb.com/blog/detect-browser-window-focus
You can also use "or" operator,
for( int i = 0 ; i < 100 || someOtherCondition() ; i++ ) {
...
}
try this:
Sub test()
With Application.WorksheetFunction
Cells(.CountA(Columns("A:A")) + 1, 1).Select
End With
End Sub
Hope this works for you.
The first result in your MSDN search said:
The method group identifies the one method to invoke or the set of overloaded methods from which to choose a specific method to invoke
my understanding is that basically because when you just write someInteger.ToString
, it may refer to:
Int32.ToString(IFormatProvider)
or it can refer to:
Int32.ToString()
so it is called a method group.
My friend, you need to create those corresponding branches locally first, in order to check-out to those other two branches, using this line of code
git branch test-branch
and
git branch change-the-title
then only you will be able to do git checkout to those branches
Also after creating each branch, take latest changes of those particular branches by using git pull origin branch_name as shown in below code
git branch test-branch
git checkout test-branch
git pull origin test-branch
and for other branch named change-the-title run following code =>
git branch change-the-title
git checkout change-the-title
git pull origin change-the-title
Happy programming :)
The default value of a char data type is '\u0000' (or 0) and a maximum value of '\uffff' (or 65,535 inclusive).
You can see the info here.
You can just declare a regular array like so:
var arry = [];
Then when you have a pair of values to add to the array, all you need to do is:
arry.push([value_1, value2]);
And yes, the first time you call arry.push
, the pair of values will be placed at index 0.
From the nodejs repl:
> var arry = [];
undefined
> arry.push([1,2]);
1
> arry
[ [ 1, 2 ] ]
> arry.push([2,3]);
2
> arry
[ [ 1, 2 ], [ 2, 3 ] ]
Of course, since javascript is dynamically typed, there will be no type checker enforcing that the array remains 2 dimensional. You will have to make sure to only add pairs of coordinates and not do the following:
> arry.push(100);
3
> arry
[ [ 1, 2 ],
[ 2, 3 ],
100 ]
Very easy, this is how I did it.
.directive('blockOnRender', function ($blockUI) {_x000D_
return {_x000D_
restrict: 'A',_x000D_
link: function (scope, element, attrs) {_x000D_
_x000D_
if (scope.$first) {_x000D_
$blockUI.blockElement($(element).parent());_x000D_
}_x000D_
if (scope.$last) {_x000D_
$blockUI.unblockElement($(element).parent());_x000D_
}_x000D_
}_x000D_
};_x000D_
})
_x000D_
This is @killerT2333 code using the builtin memoization decorator.
from functools import lru_cache
@lru_cache()
def factorial(n):
"""
Calculate the factorial of an input using memoization
:param n: int
:rtype value: int
"""
return 1 if n in (1, 0) else n * factorial(n-1)
@lru_cache()
def ncr(n, k):
"""
Choose k elements from a set of n elements,
n must be greater than or equal to k.
:param n: int
:param k: int
:rtype: int
"""
return factorial(n) / (factorial(k) * factorial(n - k))
print(ncr(6, 3))
I was having serious problems with
.data('property', value);
It was not setting the data-property
attribute.
Started using jQuery's .attr()
:
Get the value of an attribute for the first element in the set of matched elements or set one or more attributes for every matched element.
.attr('property', value)
to set the value and
.attr('property')
to retrieve the value.
Now it just works!
The functions* quit()
, exit()
, and sys.exit()
function in the same way: they raise the SystemExit
exception. So there is no real difference, except that sys.exit()
is always available but exit()
and quit()
are only available if the site
module is imported.
The os._exit()
function is special, it exits immediately without calling any cleanup functions (it doesn't flush buffers, for example). This is designed for highly specialized use cases... basically, only in the child after an os.fork()
call.
Use exit()
or quit()
in the REPL.
Use sys.exit()
in scripts, or raise SystemExit()
if you prefer.
Use os._exit()
for child processes to exit after a call to os.fork()
.
All of these can be called without arguments, or you can specify the exit status, e.g., exit(1)
or raise SystemExit(1)
to exit with status 1. Note that portable programs are limited to exit status codes in the range 0-255, if you raise SystemExit(256)
on many systems this will get truncated and your process will actually exit with status 0.
* Actually, quit()
and exit()
are callable instance objects, but I think it's okay to call them functions.
use /// to begin each line of the comment and have the comment contain the appropriate xml for the meta data reader.
///<summary>
/// this method says hello
///</summary>
public void SayHello();
Although personally, I believe that these comments are usually misguided, unless you are developing classes where the code cannot be read by its consumers.
Google Chrome released the storage API: http://developer.chrome.com/extensions/storage.html
It is pretty easy to use like the other Chrome APIs and you can use it from any page context within Chrome.
// Save it using the Chrome extension storage API.
chrome.storage.sync.set({'foo': 'hello', 'bar': 'hi'}, function() {
console.log('Settings saved');
});
// Read it using the storage API
chrome.storage.sync.get(['foo', 'bar'], function(items) {
message('Settings retrieved', items);
});
To use it, make sure you define it in the manifest:
"permissions": [
"storage"
],
There are methods to "remove", "clear", "getBytesInUse", and an event listener to listen for changed storage "onChanged"
Content scripts run in the context of webpages, not extension pages. Therefore, if you're accessing localStorage from your contentscript, it will be the storage from that webpage, not the extension page storage.
Now, to let your content script to read your extension storage (where you set them from your options page), you need to use extension message passing.
The first thing you do is tell your content script to send a request to your extension to fetch some data, and that data can be your extension localStorage:
contentscript.js
chrome.runtime.sendMessage({method: "getStatus"}, function(response) {
console.log(response.status);
});
background.js
chrome.runtime.onMessage.addListener(function(request, sender, sendResponse) {
if (request.method == "getStatus")
sendResponse({status: localStorage['status']});
else
sendResponse({}); // snub them.
});
You can do an API around that to get generic localStorage data to your content script, or perhaps, get the whole localStorage array.
I hope that helped solve your problem.
To be fancy and generic ...
contentscript.js
chrome.runtime.sendMessage({method: "getLocalStorage", key: "status"}, function(response) {
console.log(response.data);
});
background.js
chrome.runtime.onMessage.addListener(function(request, sender, sendResponse) {
if (request.method == "getLocalStorage")
sendResponse({data: localStorage[request.key]});
else
sendResponse({}); // snub them.
});
git checkout -b NEW_BRANCH_NAME COMMIT_ID
This will create a new branch called 'NEW_BRANCH_NAME' and check it out.
("check out" means "to switch to the branch")
git branch NEW_BRANCH_NAME COMMIT_ID
This just creates the new branch without checking it out.
in the comments many people seem to prefer doing this in two steps. here's how to do so in two steps:
git checkout COMMIT_ID
# you are now in the "detached head" state
git checkout -b NEW_BRANCH_NAME
byte[] bytes = File.ReadAllBytes(filename)
or ...
var bytes = File.ReadAllBytes(filename)
With dplyr
and stringr
you can use mutate_all
:
> df %>% mutate_all(funs(length = str_length(.)))
col1 col2 col1_length col2_length
1 abc adf qqwe 3 8
2 abcd d 4 1
3 a e 1 1
4 abcdefg f 7 1
Try this one. It is working for me.
handler.postDelayed(new Runnable() {
@Override
public void run() {
// Set up the projection (we only need the ID)
String[] projection = { MediaStore.Images.Media._ID };
// Match on the file path
String selection = MediaStore.Images.Media.DATA + " = ?";
String[] selectionArgs = new String[] { imageFile.getAbsolutePath() };
// Query for the ID of the media matching the file path
Uri queryUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
ContentResolver contentResolver = getActivity().getContentResolver();
Cursor c = contentResolver.query(queryUri, projection, selection, selectionArgs, null);
if (c != null) {
if (c.moveToFirst()) {
// We found the ID. Deleting the item via the content provider will also remove the file
long id = c.getLong(c.getColumnIndexOrThrow(MediaStore.Images.Media._ID));
Uri deleteUri = ContentUris.withAppendedId(queryUri, id);
contentResolver.delete(deleteUri, null, null);
} else {
// File not found in media store DB
}
c.close();
}
}
}, 5000);
Here's a demo on JSFiddle and a snippet:
.numberCircle {_x000D_
border-radius: 50%;_x000D_
width: 36px;_x000D_
height: 36px;_x000D_
padding: 8px;_x000D_
_x000D_
background: #fff;_x000D_
border: 2px solid #666;_x000D_
color: #666;_x000D_
text-align: center;_x000D_
_x000D_
font: 32px Arial, sans-serif;_x000D_
}
_x000D_
<div class="numberCircle">30</div>
_x000D_
My answer is a good starting point, some of the other answers provide flexibility for different situations. If you care about IE8, look at the old version of my answer.
On x86/x64 processors, a byte is 8 bits, and there are 256 possible binary states in 8 bits, 0 thru 255. This is how the OS translates your keyboard key strokes into letters on the screen. When you press the 'A' key, the keyboard sends a binary signal equal to the number 97 to the computer, and the computer prints a lowercase 'a' on the screen. You can confirm this in any Windows text editing software by holding an ALT key, typing 97 on the NUMPAD, then releasing the ALT key. If you replace '97' with any number from 0 to 255, you will see the character associated with that number on the system's character code page printed on the screen.
If a character is 8 bits, or 1 byte, then a WORD must be at least 2 characters, so 16 bits or 2 bytes. Traditionally, you might think of a word as a varying number of characters, but in a computer, everything that is calculable is based on static rules. Besides, a computer doesn't know what letters and symbols are, it only knows how to count numbers. So, in computer language, if a WORD is equal to 2 characters, then a double-word, or DWORD, is 2 WORDs, which is the same as 4 characters or bytes, which is equal to 32 bits. Furthermore, a quad-word, or QWORD, is 2 DWORDs, same as 4 WORDs, 8 characters, or 64 bits.
Note that these terms are limited in function to the Windows API for developers, but may appear in other circumstances (eg. the Linux dd command uses numerical suffixes to compound byte and block sizes, where c is 1 byte and w is bytes).
If you want distinct values from only two fields, plus return other fields with them, then the other fields must have some kind of aggregation on them (sum, min, max, etc.), and the two columns you want distinct must appear in the group by clause. Otherwise, it's just as Decker says.
sys.path
. See site
module.A larger list of additional Python file-extensions (mostly rare and unofficial) can be found at http://dcjtech.info/topic/python-file-extensions/
A couple of things:
(?:
not (:?
If you address the first problem, you won't need groups at all.
*That is, a blank or beginning/end of string.
A CLASSPATH entry is either a directory at the head of a package hierarchy of .class files, or a .jar file. If you're expecting ./lib
to include all the .jar files in that directory, it won't. You have to name them explicitly.
if (card1.getRarity() < card2.getRarity()) {
return 1;
However, if card2.getRarity()
is less than card1.getRarity()
you might not return -1.
You similarly miss other cases. I would do this, you can change around depending on your intent:
public int compareTo(Object o) {
if(this == o){
return 0;
}
CollectionItem item = (CollectionItem) o;
Card card1 = CardCache.getInstance().getCard(cardId);
Card card2 = CardCache.getInstance().getCard(item.getCardId());
int comp=card1.getSet() - card2.getSet();
if (comp!=0){
return comp;
}
comp=card1.getRarity() - card2.getRarity();
if (comp!=0){
return comp;
}
comp=card1.getSet() - card2.getSet();
if (comp!=0){
return comp;
}
comp=card1.getId() - card2.getId();
if (comp!=0){
return comp;
}
comp=card1.getCardType() - card2.getCardType();
return comp;
}
}
Ways to insert data into hive table: for demonstration, I am using table name as table1 and table2
1) create table table2 as select * from table1 where 1=1;
or
create table table2 as select * from table1;
2) insert overwrite table table2 select * from table1;
--it will insert data from one to another. Note: It will refresh the target.
3) insert into table table2 select * from table1;
--it will insert data from one to another. Note: It will append into the target.
4) load data local inpath 'local_path' overwrite into table table1;
--it will load data from local into the target table and also refresh the target table.
5) load data inpath 'hdfs_path' overwrite into table table1;
--it will load data from hdfs location iand also refresh the target table.
or
create table table2(
col1 string,
col2 string,
col3 string)
row format delimited fields terminated by ','
location 'hdfs_location';
6) load data local inpath 'local_path' into table table1;
--it will load data from local and also append into the target table.
7) load data inpath 'hdfs_path' into table table1;
--it will load data from hdfs location and also append into the target table.
8) insert into table2 values('aa','bb','cc');
--Lets say table2 have 3 columns only.
9) Multiple insertion into hive table
Here is another way that uses the 2-element data constructor. No functions are needed to initialize it. There is no 3rd party code (Boost), no static functions or objects, no tricks, just simple C++:
#include <map>
#include <string>
typedef std::map<std::string, int> MyMap;
const MyMap::value_type rawData[] = {
MyMap::value_type("hello", 42),
MyMap::value_type("world", 88),
};
const int numElems = sizeof rawData / sizeof rawData[0];
MyMap myMap(rawData, rawData + numElems);
Since I wrote this answer C++11 is out. You can now directly initialize STL containers using the new initializer list feature:
const MyMap myMap = { {"hello", 42}, {"world", 88} };
I usually use AtomicInteger when I need to give Ids to objects that can be accesed or created from multiple threads, and i usually use it as an static attribute on the class that i access in the constructor of the objects.
Since nobody has added the obvious solution yet which works fine for two comparisons, I'll offer it:
if (foobar === foo || foobar === bar) {
//do something
}
And, if you have lots of values (perhaps hundreds or thousands), then I'd suggest making a Set as this makes very clean and simple comparison code and it's fast at runtime:
// pre-construct the Set
var tSet = new Set(["foo", "bar", "test1", "test2", "test3", ...]);
// test the Set at runtime
if (tSet.has(foobar)) {
// do something
}
For pre-ES6, you can get a Set polyfill of which there are many. One is described in this other answer.
Another way would be to use the apply()
function.
If you have the data.frame
df <- data.frame (var1 = c(1:7,NA),
var2 = c(1,2,1,3,4,NA,NA,9),
var3 = c(NA)
)
then you can use apply()
to see which columns fulfill your condition and so you can simply do the same subsetting as in the answer by Musa, only with an apply
approach.
> !apply (is.na(df), 2, all)
var1 var2 var3
TRUE TRUE FALSE
> df[, !apply(is.na(df), 2, all)]
var1 var2
1 1 1
2 2 2
3 3 1
4 4 3
5 5 4
6 6 NA
7 7 NA
8 NA 9
This doesn't explain why it should be like that, but it explains why it could happen. The following byte-code sets -1
to the internal updateCount
flag in the SQLServerStatement
constructor:
// Method descriptor #401 (Lcom/microsoft/sqlserver/jdbc/SQLServerConnection;II)V
// Stack: 5, Locals: 8
SQLServerStatement(
com.microsoft.sqlserver.jdbc.SQLServerConnection arg0, int arg1, int arg2)
throws com.microsoft.sqlserver.jdbc.SQLServerException;
// [...]
34 aload_0 [this]
35 iconst_m1
36 putfield com.microsoft.sqlserver.jdbc.SQLServerStatement.updateCount:int [27]
Now, I will not analyse all possible control-flows, but I'd just say that this is the internal default initialisation value that somehow leaks out to client code. Note, this is also done in other methods:
// Method descriptor #383 ()V
// Stack: 2, Locals: 1
final void resetForReexecute()
throws com.microsoft.sqlserver.jdbc.SQLServerException;
// [...]
10 aload_0 [this]
11 iconst_m1
12 putfield com.microsoft.sqlserver.jdbc.SQLServerStatement.updateCount:int [27]
// Method descriptor #383 ()V
// Stack: 3, Locals: 3
final void clearLastResult();
0 aload_0 [this]
1 iconst_m1
2 putfield com.microsoft.sqlserver.jdbc.SQLServerStatement.updateCount:int [27]
In other words, you're probably safe interpreting -1
as being the same as 0
. If you rely on this result value, maybe stay on the safe side and do your checks as follows:
// No rows affected
if (stmt.executeUpdate() <= 0) {
}
// Rows affected
else {
}
UPDATE: While reading Mark Rotteveel's answer, I tend to agree with him, assuming that -1
is the JDBC-compliant value for "unknown update counts". Even if this isn't documented on the relevant method's Javadoc, it's documented in the JDBC specs, chapter 13.1.2.3 Returning Unknown or Multiple Results. In this very case, it could be said that an IF .. INSERT ..
statement will have an "unknown update count", as this statement isn't SQL-standard compliant anyway.
If your data changes a lot, you can use
mAdapter.notifyItemRangeChanged(0, yourData.size());
or some single items in your data set changes, your can use
mAdapter.notifyItemChanged(pos);
For detailed methods usage, you can refer the doc, in a way, try not to directly use mAdapter.notifyDataSetChanged()
.
You can change colors UITabBarItem by storyboard but if you want to change colors by code it's very easy:
// Use this for change color of selected bar
[[UITabBar appearance] setTintColor:[UIColor blueColor]];
// This for change unselected bar (iOS 10)
[[UITabBar appearance] setUnselectedItemTintColor:[UIColor yellowColor]];
// And this line for change color of all tabbar
[[UITabBar appearance] setBarTintColor:[UIColor whiteColor]];
I'm not sure what you mean by "myself".
Any JavaScript function can be called by an event, but you must have some sort of event to trigger it.
e.g. On page load:
<body onload="myfunction();">
Or on mouseover:
<table onmouseover="myfunction();">
As a result the first question is, "What do you want to do to cause the function to execute?"
After you determine that it will be much easier to give you a direct answer.
$(window).bind('resize', function () {
alert('resize');
});
Run apt-get install build-essential
on your system.
This package depends on other packages considered to be essential for builds and will install them. If you find you have to build packages, this can be helpful to avoid piecemeal resolution of dependencies.
See this page for more info.
Not sure if this is the fastest way, but this is something I stumbled upon (long time ago in high-school) when I was bored and playing with my calculator during math class. At that time, I was really amazed this was working...
public static boolean isIntRoot(int number) {
return isIntRootHelper(number, 1);
}
private static boolean isIntRootHelper(int number, int index) {
if (number == index) {
return true;
}
if (number < index) {
return false;
}
else {
return isIntRootHelper(number - 2 * index, index + 1);
}
}
I don't think you can do this without an explicit or implicit loop, without reading into a char array (or some other container) first and ten constructing the string. If you don't need the other capabilities of a string, it could be done with vector<char>
the same way you are currently using a char *
.
Can also use:
find . -mindepth 1 -mtime +3 -delete
To not delete target directory
To really properly do a merge which takes only input from the branch you are merging you can do
git merge --strategy=ours ref-to-be-merged
git diff --binary ref-to-be-merged | git apply --reverse --index
git commit --amend
There will be no conflicts in any scenario I know of, you don't have to make additional branches, and it acts like a normal merge commit.
This doesn't play nice with submodules however.
When floating elements exist on the page, non-floating elements wrap around the floating elements, similar to how text goes around a picture in a newspaper. From a document perspective (the original purpose of HTML), this is how floats work.
float
vs display:inline
Before the invention of display:inline-block
, websites use float
to set elements beside each other. float
is preferred over display:inline
since with the latter, you can't set the element's dimensions (width and height) as well as vertical paddings (top and bottom) - which floated elements can do since they're treated as block elements.
The main problem is that we're using float
against its intended purpose.
Another is that while float
allows side-by-side block-level elements, floats do not impart shape to its container. It's like position:absolute
, where the element is "taken out of the layout". For instance, when an empty container contains a floating 100px x 100px <div>
, the <div>
will not impart 100px in height to the container.
Unlike position:absolute
, it affects the content that surrounds it. Content after the floated element will "wrap" around the element. It starts by rendering beside it and then below it, like how newspaper text would flow around an image.
What clearfix does is to force content after the floats or the container containing the floats to render below it. There are a lot of versions for clear-fix, but it got its name from the version that's commonly being used - the one that uses the CSS property clear
.
Here are several ways to do clearfix , depending on the browser and use case. One only needs to know how to use the clear
property in CSS and how floats render in each browser in order to achieve a perfect cross-browser clear-fix.
Your provided style is a form of clearfix with backwards compatibility. I found an article about this clearfix. It turns out, it's an OLD clearfix - still catering the old browsers. There is a newer, cleaner version of it in the article also. Here's the breakdown:
The first clearfix you have appends an invisible pseudo-element, which is styled clear:both
, between the target element and the next element. This forces the pseudo-element to render below the target, and the next element below the pseudo-element.
The second one appends the style display:inline-block
which is not supported by earlier browsers. inline-block is like inline but gives you some properties that block elements, like width, height as well as vertical padding. This was targeted for IE-MAC.
This was the reapplication of display:block
due to IE-MAC rule above. This rule was "hidden" from IE-MAC.
All in all, these 3 rules keep the .clearfix
working cross-browser, with old browsers in mind.
The following is based on the answers above (plus a correction for the milliseconds) and emulates datetime.timestamp()
for Python 3 before 3.3 when timezones are used.
def datetime_timestamp(datetime):
'''
Equivalent to datetime.timestamp() for pre-3.3
'''
try:
return datetime.timestamp()
except AttributeError:
utc_datetime = datetime.astimezone(utc)
return timegm(utc_datetime.timetuple()) + utc_datetime.microsecond / 1e6
To strictly answer the question as asked, you'd want:
datetime_timestamp(my_datetime) + 5 * 60
datetime_timestamp
is part of simple-date. But if you were using that package you'd probably type:
SimpleDate(my_datetime).timestamp + 5 * 60
which handles many more formats / types for my_datetime.
Basically, use whatever makes the code most readable. There are definitely places where one or the other constructs makes for cleaner, more readable and more maintainable. This is far more important that perhaps saving a few nanoseconds in JavaScript code.
The sort package provides the building blocks if your slice is sorted or you are willing to sort it.
input := []string{"bird", "apple", "ocean", "fork", "anchor"}
sort.Strings(input)
fmt.Println(contains(input, "apple")) // true
fmt.Println(contains(input, "grow")) // false
...
func contains(s []string, searchterm string) bool {
i := sort.SearchStrings(s, searchterm)
return i < len(s) && s[i] == searchterm
}
SearchString
promises to return the index to insert x if x is not present (it could be len(a))
, so a check of that reveals whether the string is contained the sorted slice.
For smartphone with clipboard, is possible prevent like this.
editText.setFilters(new InputFilter[]{new InputFilter() {
@Override
public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) {
if (source.length() > 1) {
return "";
} return null;
}
}});
Something like this (sounds like you just need to change your SMTP server):
String host = "smtp.gmail.com";
String from = "user name";
Properties props = System.getProperties();
props.put("mail.smtp.host", host);
props.put("mail.smtp.user", from);
props.put("mail.smtp.password", "asdfgh");
props.put("mail.smtp.port", "587"); // 587 is the port number of yahoo mail
props.put("mail.smtp.auth", "true");
Session session = Session.getDefaultInstance(props, null);
MimeMessage message = new MimeMessage(session);
message.setFrom(new InternetAddress(from));
InternetAddress[] to_address = new InternetAddress[to.length];
int i = 0;
// To get the array of addresses
while (to[i] != null) {
to_address[i] = new InternetAddress(to[i]);
i++;
}
System.out.println(Message.RecipientType.TO);
i = 0;
while (to_address[i] != null) {
message.addRecipient(Message.RecipientType.TO, to_address[i]);
i++;
}
message.setSubject("sending in a group");
message.setText("Welcome to JavaMail");
// alternately, to send HTML mail:
// message.setContent("<p>Welcome to JavaMail</p>", "text/html");
Transport transport = session.getTransport("smtp");
transport.connect("smtp.mail.yahoo.co.in", "user name", "asdfgh");
transport.sendMessage(message, message.getAllRecipients());
transport.close();
This is how we would do this in Opal - a pure functional programming language. And, IMHO - doing this recursively only makes sense in that context.
List Reverse(List l)
{
if (IsEmpty(l) || Size(l) == 1) return l;
return reverse(rest(l))::first(l);
}
rest(l) returns a list that is the original list without it's first node. first(l) returns the first element. :: is a concatenation operator.
Remember that when you write:
MyArray = Range("A1:A5000")
you are really writing
MyArray = Range("A1:A5000").Value
You can also use names:
MyArray = Names("MyWSTable").RefersToRange.Value
But Value is not the only property of Range. I have used:
MyArray = Range("A1:A5000").NumberFormat
I doubt
MyArray = Range("A1:A5000").Font
would work but I would expect
MyArray = Range("A1:A5000").Font.Bold
to work.
I do not know what formats you want to copy so you will have to try.
However, I must add that when you copy and paste a large range, it is not as much slower than doing it via an array as we all thought.
Post Edit information
Having posted the above I tried by own advice. My experiments with copying Font.Color and Font.Bold to an array have failed.
Of the following statements, the second would fail with a type mismatch:
ValueArray = .Range("A1:T5000").Value
ColourArray = .Range("A1:T5000").Font.Color
ValueArray must be of type variant. I tried both variant and long for ColourArray without success.
I filled ColourArray with values and tried the following statement:
.Range("A1:T5000").Font.Color = ColourArray
The entire range would be coloured according to the first element of ColourArray and then Excel looped consuming about 45% of the processor time until I terminated it with the Task Manager.
There is a time penalty associated with switching between worksheets but recent questions about macro duration have caused everyone to review our belief that working via arrays was substantially quicker.
I constructed an experiment that broadly reflects your requirement. I filled worksheet Time1 with 5000 rows of 20 cells which were selectively formatted as: bold, italic, underline, subscript, bordered, red, green, blue, brown, yellow and gray-80%.
With version 1, I copied every 7th cells from worksheet "Time1" to worksheet "Time2" using copy.
With version 2, I copied every 7th cells from worksheet "Time1" to worksheet "Time2" by copying the value and the colour via an array.
With version 3, I copied every 7th cells from worksheet "Time1" to worksheet "Time2" by copying the formula and the colour via an array.
Version 1 took an average of 12.43 seconds, version 2 took an average of 1.47 seconds while version 3 took an average of 1.83 seconds. Version 1 copied formulae and all formatting, version 2 copied values and colour while version 3 copied formulae and colour. With versions 1 and 2 you could add bold and italic, say, and still have some time in hand. However, I am not sure it would be worth the bother given that copying 21,300 values only takes 12 seconds.
** Code for Version 1**
I do not think this code includes anything that needs an explanation. Respond with a comment if I am wrong and I will fix.
Sub SelectionCopyAndPaste()
Dim ColDestCrnt As Integer
Dim ColSrcCrnt As Integer
Dim NumSelect As Long
Dim RowDestCrnt As Integer
Dim RowSrcCrnt As Integer
Dim StartTime As Single
Application.ScreenUpdating = False
Application.Calculation = xlCalculationManual
NumSelect = 1
ColDestCrnt = 1
RowDestCrnt = 1
With Sheets("Time2")
.Range("A1:T715").EntireRow.Delete
End With
StartTime = Timer
Do While True
ColSrcCrnt = (NumSelect Mod 20) + 1
RowSrcCrnt = (NumSelect - ColSrcCrnt) / 20 + 1
If RowSrcCrnt > 5000 Then
Exit Do
End If
Sheets("Time1").Cells(RowSrcCrnt, ColSrcCrnt).Copy _
Destination:=Sheets("Time2").Cells(RowDestCrnt, ColDestCrnt)
If ColDestCrnt = 20 Then
ColDestCrnt = 1
RowDestCrnt = RowDestCrnt + 1
Else
ColDestCrnt = ColDestCrnt + 1
End If
NumSelect = NumSelect + 7
Loop
Debug.Print Timer - StartTime
' Average 12.43 secs
Application.Calculation = xlCalculationAutomatic
End Sub
** Code for Versions 2 and 3**
The User type definition must be placed before any subroutine in the module. The code works through the source worksheet copying values or formulae and colours to the next element of the array. Once selection has been completed, it copies the collected information to the destination worksheet. This avoids switching between worksheets more than is essential.
Type ValueDtl
Value As String
Colour As Long
End Type
Sub SelectionViaArray()
Dim ColDestCrnt As Integer
Dim ColSrcCrnt As Integer
Dim InxVLCrnt As Integer
Dim InxVLCrntMax As Integer
Dim NumSelect As Long
Dim RowDestCrnt As Integer
Dim RowSrcCrnt As Integer
Dim StartTime As Single
Dim ValueList() As ValueDtl
Application.ScreenUpdating = False
Application.Calculation = xlCalculationManual
' I have sized the array to more than I expect to require because ReDim
' Preserve is expensive. However, I will resize if I fill the array.
' For my experiment I know exactly how many elements I need but that
' might not be true for you.
ReDim ValueList(1 To 25000)
NumSelect = 1
ColDestCrnt = 1
RowDestCrnt = 1
InxVLCrntMax = 0 ' Last used element in ValueList.
With Sheets("Time2")
.Range("A1:T715").EntireRow.Delete
End With
StartTime = Timer
With Sheets("Time1")
Do While True
ColSrcCrnt = (NumSelect Mod 20) + 1
RowSrcCrnt = (NumSelect - ColSrcCrnt) / 20 + 1
If RowSrcCrnt > 5000 Then
Exit Do
End If
InxVLCrntMax = InxVLCrntMax + 1
If InxVLCrntMax > UBound(ValueList) Then
' Resize array if it has been filled
ReDim Preserve ValueList(1 To UBound(ValueList) + 1000)
End If
With .Cells(RowSrcCrnt, ColSrcCrnt)
ValueList(InxVLCrntMax).Value = .Value ' Version 2
ValueList(InxVLCrntMax).Value = .Formula ' Version 3
ValueList(InxVLCrntMax).Colour = .Font.Color
End With
NumSelect = NumSelect + 7
Loop
End With
With Sheets("Time2")
For InxVLCrnt = 1 To InxVLCrntMax
With .Cells(RowDestCrnt, ColDestCrnt)
.Value = ValueList(InxVLCrnt).Value ' Version 2
.Formula = ValueList(InxVLCrnt).Value ' Version 3
.Font.Color = ValueList(InxVLCrnt).Colour
End With
If ColDestCrnt = 20 Then
ColDestCrnt = 1
RowDestCrnt = RowDestCrnt + 1
Else
ColDestCrnt = ColDestCrnt + 1
End If
Next
End With
Debug.Print Timer - StartTime
' Version 2 average 1.47 secs
' Version 3 average 1.83 secs
Application.Calculation = xlCalculationAutomatic
End Sub
your server should enable the cross origin requests, not the client. To do this, you can check this nice page with implementations and configurations for multiple platforms
remove mysql :
sudo apt -y purge mysql*
sudo apt -y autoremove
sudo rm -rf /etc/mysql
sudo rm -rf /var/lib/mysql*
Restart instance :
sudo shutdown -r now
use this tag {!! description text !!}
Be careful with nulls and checking for inequality in sql server.
For example
select * from foo where bla <> 'something'
will NOT return records where bla is null. Even though logically it should.
So the right way to check would be
select * from foo where isnull(bla,'') <> 'something'
Which of course people often forget and then get weird bugs.
If you happened to run npm install
command on Windows, first make sure you open your command prompt with Administration Privileges. That's what solved the issue for me.
On windows, I just add multiple batch files for different JDK versions to the Maven bin folder like this:
mvn11.cmd
@echo off
setlocal
set "JAVA_HOME=path\to\jdk11"
set "path=%JAVA_HOME%;%path%"
mvn %*
then you can use mvn11
to run Maven in the specified JDK.
You can also check for first DecorView's child bottom padding. It will be set to non-zero value when keyboard is shown.
@Override
protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
View view = getRootView();
if (view != null && (view = ((ViewGroup) view).getChildAt(0)) != null) {
setKeyboardVisible(view.getPaddingBottom() > 0);
}
super.onLayout(changed, left, top, right, bottom);
}
The best way to do this is by running the command:
git diff --name-only --cached
When you check the manual you will likely find the following:
--name-only
Show only names of changed files.
And on the example part of the manual:
git diff --cached
Changes between the index and your current HEAD.
Combined together you get the changes between the index and your current HEAD
and Show only names of changed files.
Update: --staged
is also available as an alias for --cached
above in more recent git versions.
Intent callIntent = new Intent(Intent.ACTION_CALL);
callIntent.setData(Uri.parse("tel:"+number));
startActivity(callIntent);
**Add permission :**
<uses-permission android:name="android.permission.CALL_PHONE" />
Beside of one view model in asp.net you can also make multiple partial views and assign different model view to every view, for example:
@{
Layout = null;
}
@model Person;
<input type="text" asp-for="PersonID" />
<input type="text" asp-for="PersonName" />
then another partial view Model for order model
@{
Layout = null;
}
@model Order;
<input type="text" asp-for="OrderID" />
<input type="text" asp-for="TotalSum" />
then in your main view load both partial view by
<partial name="PersonPartialView" />
<partial name="OrderPartialView" />
I created a simple extension that gives you an unsorted Array
as a property of Set
in Swift 4.0.
extension Set {
var array: [Element] {
return Array(self)
}
}
If you want a sorted array, you can either add an additional computed property, or modify the existing one to suit your needs.
To use this, just call
let array = set.array
Yes, for react,
for
becomes htmlFor
class
becomes className
etc.
see full list of how HTML attributes are changed here:
XAMPP Apache + MariaDB + PHP + Perl (X -any OS)
Open browser and in url type localhost
or 127.0.0.1
By default your port is listing with 80.If you want you can change it to your desired port number in httpd.conf file.(If port 80 is already using with other app then you have to change it).
For example you changed port number 80 to 8090 then you can run as 'localhost:8090' or '127.0.0.1:8090'
Are you meaning?
data2 <- data1[good,]
With
data1[good]
you're selecting columns in a wrong way (using a logical vector of complete rows).
Consider that parameter pollutant
is not used; is it a column name that you want to extract? if so it should be something like
data2 <- data1[good, pollutant]
Furthermore consider that you have to rbind
the data.frame
s inside the for
loop, otherwise you get only the last data.frame (its completed.cases)
And last but not least, i'd prefer generating filenames eg with
id <- 1:322
paste0( directory, "/", gsub(" ", "0", sprintf("%3d",id)), ".csv")
A little modified chunk of ?sprintf
The string fmt
(in our case "%3d"
) contains normal characters, which are passed through to the output string, and also conversion specifications which operate on the arguments provided through ...
. The allowed conversion specifications start with a %
and end with one of the letters in the set aAdifeEgGosxX%
. These letters denote the following types:
d
: integerEg a more general example
sprintf("I am %10d years old", 25)
[1] "I am 25 years old"
^^^^^^^^^^
| |
1 10
For an excellent resource on how bash invocation works, what dotfiles do what, and how you should use/configure them, read this:
As everyone else has mentioned it is better to use the "in" operator, it can also act on lists:
line = "This,is,a,sample,string"
lst = ['This', 'sample']
for i in lst:
i in line
>> True
>> True
According to the Apple Human Interface Guidelines:
@1x : about 25 x 25 (max: 48 x 32)
@2x : about 50 x 50 (max: 96 x 64)
@3x : about 75 x 75 (max: 144 x 96)
The simplest way is to set the background-size
CSS property to cover
:
.jumbotron {
background-image: url("../img/jumbotron_bg.jpg");
background-size: cover;
}
As mentioned by @PSIXO in a comment, this might be the problem with the dependency version of google-services. For me changing,
buildscript {
// ...
dependencies {
// ...
classpath 'com.google.gms:google-services:4.1.0'
}
}
to
buildscript {
// ...
dependencies {
// ...
classpath 'com.google.gms:google-services:4.0.1'
}
}
worked.There might be some problem with 4.1.0 version. Because I wasted many hours on this, I thought to write this as an answer.
If you want to be a little bit fancier you can also create it as an html list to create something like bullets or numbers using ul or ol.
<ul>
<li>Line 1</li>
<li>Line 2</li>
</ul>
May be this is alltime multiple connection open issue, you are somewhere in your code opening connections and not closing them properly. use
using (SqlConnection con = new SqlConnection(connectionString))
{
con.Open();
}
Refer this article: http://msdn.microsoft.com/en-us/library/ms254507(v=vs.80).aspx, The Using block in Visual Basic or C# automatically disposes of the connection when the code exits the block, even in the case of an unhandled exception.
Compatibility Guide for JDK 8 says that in Java 8 the command line flag MaxPermSize
has been removed. The reason is that the permanent generation was removed from the hotspot heap and was moved to native memory.
So in order to remove this message
edit MAVEN_OPTS Environment User Variable:
Java 7
MAVEN_OPTS -Xmx512m -XX:MaxPermSize=128m
Java 8
MAVEN_OPTS -Xmx512m
Can't instantiate an interface but there are few implementations:
JDK2
List<String> list = Arrays.asList("one", "two", "three");
JDK7
//diamond operator
List<String> list = new ArrayList<>();
list.add("one");
list.add("two");
list.add("three");
JDK8
List<String> list = Stream.of("one", "two", "three").collect(Collectors.toList());
JDK9
// creates immutable lists, so you can't modify such list
List<String> immutableList = List.of("one", "two", "three");
// if we want mutable list we can copy content of immutable list
// to mutable one for instance via copy-constructor (which creates shallow copy)
List<String> mutableList = new ArrayList<>(List.of("one", "two", "three"));
Plus there are lots of other ways supplied by other libraries like Guava.
List<String> list = Lists.newArrayList("one", "two", "three");
Random random = new Random();
int max = 10;
int min = 3;
int randomNum = random.nextInt(max) % (max - min + 1) + min;
Using .apply()
with a lambda
conversion function also works in this case:
total_rows['ColumnID'] = total_rows['ColumnID'].apply(lambda x: str(x))
For entire dataframes you can use .applymap()
.
(but in any case probably .astype()
is faster)
If you build apk via command line like me then you can provide signing configuration as arguments.
Add this to your build.gradle
def getStore = { ->
def result = project.hasProperty('storeFile') ? storeFile : "null"
return result
}
def getStorePassword = { ->
def result = project.hasProperty('storePassword') ? storePassword : ""
return result
}
def getKeyAlias = { ->
def result = project.hasProperty('keyAlias') ? keyAlias : ""
return result
}
def getKeyPassword = { ->
def result = project.hasProperty('keyPassword') ? keyPassword : ""
return result
}
Make your signingConfigs
like this
signingConfigs {
release {
storeFile file(getStore())
storePassword getStorePassword()
keyAlias getKeyAlias()
keyPassword getKeyPassword()
}
}
Then you execute gradlew
like this
./gradlew assembleRelease -PstoreFile="keystore.jks" -PstorePassword="password" -PkeyAlias="alias" -PkeyPassword="password"
Objects are eligable for garbage collection once they go out of scope become unreachable (thanks ben!). The memory won't be freed unless the garbage collector believes you are running out of memory.
For managed resources, the garbage collector will know when this is, and you don't need to do anything.
For unmanaged resources (such as connections to databases or opened files) the garbage collector has no way of knowing how much memory they are consuming, and that is why you need to free them manually (using dispose, or much better still the using block)
If objects are not being freed, either you have plenty of memory left and there is no need, or you are maintaining a reference to them in your application, and therefore the garbage collector will not free them (in case you actually use this reference you maintained)
You have ArrayList
all wrong,
add()
method in an arrayRather do this:
List<String> alist = new ArrayList<String>();
alist.add("apple");
alist.add("banana");
alist.add("orange");
String value = alist.get(1); //returns the 2nd item from list, in this case "banana"
Indexing is counted from 0
to N-1
where N
is size()
of list.
check this out A little framework: a complete cookies reader/writer with full Unicode support
/*\
|*|
|*| :: cookies.js ::
|*|
|*| A complete cookies reader/writer framework with full unicode support.
|*|
|*| Revision #1 - September 4, 2014
|*|
|*| https://developer.mozilla.org/en-US/docs/Web/API/document.cookie
|*| https://developer.mozilla.org/User:fusionchess
|*| https://github.com/madmurphy/cookies.js
|*|
|*| This framework is released under the GNU Public License, version 3 or later.
|*| http://www.gnu.org/licenses/gpl-3.0-standalone.html
|*|
|*| Syntaxes:
|*|
|*| * docCookies.setItem(name, value[, end[, path[, domain[, secure]]]])
|*| * docCookies.getItem(name)
|*| * docCookies.removeItem(name[, path[, domain]])
|*| * docCookies.hasItem(name)
|*| * docCookies.keys()
|*|
\*/
var docCookies = {
getItem: function (sKey) {
if (!sKey) { return null; }
return decodeURIComponent(document.cookie.replace(new RegExp("(?:(?:^|.*;)\\s*" + encodeURIComponent(sKey).replace(/[\-\.\+\*]/g, "\\$&") + "\\s*\\=\\s*([^;]*).*$)|^.*$"), "$1")) || null;
},
setItem: function (sKey, sValue, vEnd, sPath, sDomain, bSecure) {
if (!sKey || /^(?:expires|max\-age|path|domain|secure)$/i.test(sKey)) { return false; }
var sExpires = "";
if (vEnd) {
switch (vEnd.constructor) {
case Number:
sExpires = vEnd === Infinity ? "; expires=Fri, 31 Dec 9999 23:59:59 GMT" : "; max-age=" + vEnd;
break;
case String:
sExpires = "; expires=" + vEnd;
break;
case Date:
sExpires = "; expires=" + vEnd.toUTCString();
break;
}
}
document.cookie = encodeURIComponent(sKey) + "=" + encodeURIComponent(sValue) + sExpires + (sDomain ? "; domain=" + sDomain : "") + (sPath ? "; path=" + sPath : "") + (bSecure ? "; secure" : "");
return true;
},
removeItem: function (sKey, sPath, sDomain) {
if (!this.hasItem(sKey)) { return false; }
document.cookie = encodeURIComponent(sKey) + "=; expires=Thu, 01 Jan 1970 00:00:00 GMT" + (sDomain ? "; domain=" + sDomain : "") + (sPath ? "; path=" + sPath : "");
return true;
},
hasItem: function (sKey) {
if (!sKey) { return false; }
return (new RegExp("(?:^|;\\s*)" + encodeURIComponent(sKey).replace(/[\-\.\+\*]/g, "\\$&") + "\\s*\\=")).test(document.cookie);
},
keys: function () {
var aKeys = document.cookie.replace(/((?:^|\s*;)[^\=]+)(?=;|$)|^\s*|\s*(?:\=[^;]*)?(?:\1|$)/g, "").split(/\s*(?:\=[^;]*)?;\s*/);
for (var nLen = aKeys.length, nIdx = 0; nIdx < nLen; nIdx++) { aKeys[nIdx] = decodeURIComponent(aKeys[nIdx]); }
return aKeys;
}
};
It is also possible to use the new button attribute called formtarget
that was introduced with HTML5.
<form>
<input type="submit" formtarget="_blank"/>
</form>
I just ran into this issue and I'm using react 15.0.1 15.0.2 and I'm using ES6 syntax and didn't quite get what I needed from the other answers since v.15 dropped weeks ago and some of the this.refs
properties were deprecated and removed.
In general, what I needed was:
I'm using:
I used autoFocus={true}
on the first <input />
on the page so that when the component mounts, it will get focus.
This took longer and was more convoluted. I'm keeping out code that isn't relevant to the solution for brevity.
I need a global state to know if I should set the focus and to disable it when it was set, so I don't keep re-setting focus when the components re-render (I'll be using componentDidUpdate()
to check for setting focus.)
This could be designed as you see fit for you application.
{
form: {
resetFocus: false,
}
}
The component will need to have the resetfocus
property set and a callBack to clear the property if it ends up setting focus on itself.
Also note, I organized my Action Creators into separate files mostly due to my project is fairly large and I wanted to break them up into more manageable chunks.
import { connect } from 'react-redux';
import MyField from '../presentation/MyField';
import ActionCreator from '../actions/action-creators';
function mapStateToProps(state) {
return {
resetFocus: state.form.resetFocus
}
}
function mapDispatchToProps(dispatch) {
return {
clearResetFocus() {
dispatch(ActionCreator.clearResetFocus());
}
}
}
export default connect(mapStateToProps, mapDispatchToProps)(MyField);
import React, { PropTypes } form 'react';
export default class MyField extends React.Component {
// don't forget to .bind(this)
constructor(props) {
super(props);
this._handleRef = this._handleRef.bind(this);
}
// This is not called on the initial render so
// this._input will be set before this get called
componentDidUpdate() {
if(!this.props.resetFocus) {
return false;
}
if(this.shouldfocus()) {
this._input.focus();
this.props.clearResetFocus();
}
}
// When the component mounts, it will save a
// reference to itself as _input, which we'll
// be able to call in subsequent componentDidUpdate()
// calls if we need to set focus.
_handleRef(c) {
this._input = c;
}
// Whatever logic you need to determine if this
// component should get focus
shouldFocus() {
// ...
}
// pass the _handleRef callback so we can access
// a reference of this element in other component methods
render() {
return (
<input ref={this._handleRef} type="text" />
);
}
}
Myfield.propTypes = {
clearResetFocus: PropTypes.func,
resetFocus: PropTypes.bool
}
The general idea is that each form field that could have an error and be focused needs to check itself and if it needs to set focus on itself.
There's business logic that needs to happen to determine if the given field is the right field to set focus to. This isn't shown because it will depend on the individual application.
When a form is submitted, that event needs to set the global focus flag resetFocus
to true. Then as each component updates itself, it will see that it should check to see if it gets the focus and if it does, dispatch the event to reset focus so other elements don't have to keep checking.
edit
As a side note, I had my business logic in a "utilities" file and I just exported the method and called it within each shouldfocus()
method.
Cheers!
I ran into this and while I had the og:image (and others), I was missing og:url and og:type, so I added those and then it worked.
<meta property="og:url" content="<?
$url = 'https://' . $_SERVER['HTTP_HOST'].$_SERVER['PHP_SELF']."?".$_SERVER['QUERY_STRING'];;
echo htmlentities($url,ENT_QUOTES); ?>"/>
Here is a more complete answer with regard to InnoDB. It is a bit of a lengthy process, but can be worth the effort.
Keep in mind that /var/lib/mysql/ibdata1
is the busiest file in the InnoDB infrastructure. It normally houses six types of information:
Pictorial Representation of ibdata1
Many people create multiple ibdata
files hoping for better disk-space management and performance, however that belief is mistaken.
OPTIMIZE TABLE
?Unfortunately, running OPTIMIZE TABLE
against an InnoDB table stored in the shared table-space file ibdata1
does two things:
ibdata1
ibdata1
grow because the contiguous data and index pages are appended to ibdata1
You can however, segregate Table Data and Table Indexes from ibdata1
and manage them independently.
OPTIMIZE TABLE
with innodb_file_per_table
?Suppose you were to add innodb_file_per_table
to /etc/my.cnf (my.ini)
. Can you then just run OPTIMIZE TABLE
on all the InnoDB Tables?
Good News : When you run OPTIMIZE TABLE
with innodb_file_per_table
enabled, this will produce a .ibd
file for that table. For example, if you have table mydb.mytable
witha datadir of /var/lib/mysql
, it will produce the following:
/var/lib/mysql/mydb/mytable.frm
/var/lib/mysql/mydb/mytable.ibd
The .ibd
will contain the Data Pages and Index Pages for that table. Great.
Bad News : All you have done is extract the Data Pages and Index Pages of mydb.mytable
from living in ibdata
. The data dictionary entry for every table, including mydb.mytable
, still remains in the data dictionary (See the Pictorial Representation of ibdata1). YOU CANNOT JUST SIMPLY DELETE ibdata1
AT THIS POINT !!! Please note that ibdata1
has not shrunk at all.
To shrink ibdata1
once and for all you must do the following:
Dump (e.g., with mysqldump
) all databases into a .sql
text file (SQLData.sql
is used below)
Drop all databases (except for mysql
and information_schema
) CAVEAT : As a precaution, please run this script to make absolutely sure you have all user grants in place:
mkdir /var/lib/mysql_grants
cp /var/lib/mysql/mysql/* /var/lib/mysql_grants/.
chown -R mysql:mysql /var/lib/mysql_grants
Login to mysql and run SET GLOBAL innodb_fast_shutdown = 0;
(This will completely flush all remaining transactional changes from ib_logfile0
and ib_logfile1
)
Shutdown MySQL
Add the following lines to /etc/my.cnf
(or my.ini
on Windows)
[mysqld]
innodb_file_per_table
innodb_flush_method=O_DIRECT
innodb_log_file_size=1G
innodb_buffer_pool_size=4G
(Sidenote: Whatever your set for innodb_buffer_pool_size
, make sure innodb_log_file_size
is 25% of innodb_buffer_pool_size
.
Also: innodb_flush_method=O_DIRECT
is not available on Windows)
Delete ibdata*
and ib_logfile*
, Optionally, you can remove all folders in /var/lib/mysql
, except /var/lib/mysql/mysql
.
Start MySQL (This will recreate ibdata1
[10MB by default] and ib_logfile0
and ib_logfile1
at 1G each).
Import SQLData.sql
Now, ibdata1
will still grow but only contain table metadata because each InnoDB table will exist outside of ibdata1
. ibdata1
will no longer contain InnoDB data and indexes for other tables.
For example, suppose you have an InnoDB table named mydb.mytable
. If you look in /var/lib/mysql/mydb
, you will see two files representing the table:
mytable.frm
(Storage Engine Header)mytable.ibd
(Table Data and Indexes)With the innodb_file_per_table
option in /etc/my.cnf
, you can run OPTIMIZE TABLE mydb.mytable
and the file /var/lib/mysql/mydb/mytable.ibd
will actually shrink.
I have done this many times in my career as a MySQL DBA. In fact, the first time I did this, I shrank a 50GB ibdata1
file down to only 500MB!
Give it a try. If you have further questions on this, just ask. Trust me; this will work in the short term as well as over the long haul.
At Step 6, if mysql cannot restart because of the mysql
schema begin dropped, look back at Step 2. You made the physical copy of the mysql
schema. You can restore it as follows:
mkdir /var/lib/mysql/mysql
cp /var/lib/mysql_grants/* /var/lib/mysql/mysql
chown -R mysql:mysql /var/lib/mysql/mysql
Go back to Step 6 and continue
With regard to setting innodb_log_file_size to 25% of innodb_buffer_pool_size in Step 5, that's blanket rule is rather old school.
Back on July 03, 2006
, Percona had a nice article why to choose a proper innodb_log_file_size. Later, on Nov 21, 2008
, Percona followed up with another article on how to calculate the proper size based on peak workload keeping one hour's worth of changes.
I have since written posts in the DBA StackExchange about calculating the log size and where I referenced those two Percona articles.
Aug 27, 2012
: Proper tuning for 30GB InnoDB table on server with 48GB RAMJan 17, 2013
: MySQL 5.5 - Innodb - innodb_log_file_size higher than 4GB combined?Personally, I would still go with the 25% rule for an initial setup. Then, as the workload can more accurate be determined over time in production, you could resize the logs during a maintenance cycle in just minutes.
I'm sure someone can do better, but this works:
sapply(as.character(q.data$string), function(x, letter = "a"){
sum(unlist(strsplit(x, split = "")) == letter)
})
greatgreat magic not
2 1 0
or in a function:
countLetter <- function(charvec, letter){
sapply(charvec, function(x, letter){
sum(unlist(strsplit(x, split = "")) == letter)
}, letter = letter)
}
countLetter(as.character(q.data$string),"a")
An NDF file is a user defined secondary database file of Microsoft SQL Server with an extension .ndf, which store user data. Moreover, when the size of the database file growing automatically from its specified size, you can use .ndf file for extra storage and the .ndf file could be stored on a separate disk drive. Every NDF file uses the same filename as its corresponding MDF file. We cannot open an .ndf file in SQL Server Without attaching its associated .mdf file.
Perhaps you should divide your content like such using floats:
<div style="overflow: auto;">
<div style="float: left; width: 600px;">
Here is my content!
</div>
<div style="float: right; width: 300px;">
Here is my sidebar!
</div>
</div>
Notice the overflow: auto;
, this is to ensure that you have some height to your container. Floating things takes them out of the DOM, to ensure that your elements below don't overlap your wandering floats, set a container div
to have an overflow: auto
(or overflow: hidden
) to ensure that floats are accounted for when drawing your height. Check out more information on floats and how to use them here.
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<androidx.recyclerview.widget.RecyclerView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/recycler_view"/>
</FrameLayout>
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="46dp">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/textview"
android:text="TextView"
android:textSize="16dp" />
</LinearLayout>
public class CustomAdapter extends RecyclerView.Adapter<CustomAdapter.ViewHolder> {
private List<String> data;
public CustomAdapter (List<String> data){
this.data = data;
}
@Override
public CustomAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View rowItem = LayoutInflater.from(parent.getContext()).inflate(R.layout.list_item_view, parent, false);
return new ViewHolder(rowItem);
}
@Override
public void onBindViewHolder(CustomAdapter.ViewHolder holder, int position) {
holder.textView.setText(this.data.get(position));
}
@Override
public int getItemCount() {
return this.data.size();
}
public static class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
private TextView textView;
public ViewHolder(View view) {
super(view);
view.setOnClickListener(this);
this.textView = view.findViewById(R.id.textview);
}
@Override
public void onClick(View view) {
Toast.makeText(view.getContext(), "position : " + getLayoutPosition() + " text : " + this.textView.getText(), Toast.LENGTH_SHORT).show();
}
}
}
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
RecyclerView recyclerView = findViewById(R.id.recycler_view);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
recyclerView.setAdapter(new CustomAdapter(generateData()));
recyclerView.addItemDecoration(new DividerItemDecoration(this, DividerItemDecoration.VERTICAL));
}
private List<String> generateData() {
List<String> data = new ArrayList<>();
for (int i = 0; i < 100; i++) {
data.add(String.valueOf(i) + "th Element");
}
return data;
}
}
Use CollectionUtils
or ArrayUtils
from stanford-postagger-3.0.jar
import static edu.stanford.nlp.util.ArrayUtils.asSet;
or
import static edu.stanford.nlp.util.CollectionUtils.asSet;
...
String [] array = {"1", "q"};
Set<String> trackIds = asSet(array);
I know this doesn't answer your question, but one option you may want to look at is just having two vectors with the same index being "linked" information..
So in..
std::vector<std::string> vName;
std::vector<int> vNameCount;
if you want the count of names by name you just do your quick for loop over vName.size(), and when ya find it that is the index for vNameCount that you are looking for.
Sure this may not give ya all the functionality of the map, and depending may or may not be better, but it might be easier if ya don't know the keys, and shouldn't add too much processing.
Just remember when you add/delete from one you have to do it from the other or things will get crazy heh :P
I just want to mention a thing, there are many tools can do text processing, e.g. sort, cut, split, join, paste, comm, uniq, column, rev, tac, tr, nl, pr, head, tail.....
they are very handy but you have to learn their options etc.
A lazy way (not the best way) to learn text processing might be: only learn grep , sed and awk. with this three tools, you can solve almost 99% of text processing problems and don't need to memorize above different cmds and options. :)
AND, if you 've learned and used the three, you knew the difference. Actually, the difference here means which tool is good at solving what kind of problem.
a more lazy way might be learning a script language (python, perl or ruby) and do every text processing with it.
(Taken from my comment)
pip
won't handle system level dependencies. You'll have to apt-get install libfreetype6-dev
before continuing. (It even says so right in your output. Try skimming over it for such errors next time, usually build outputs are very detailed)
I was using a playbook like this to test my roles locally:
---
- hosts: localhost
roles:
- role: .
but this stopped working with Ansible v2.2.
I debugged the aforementioned solution of
---
- hosts: all
tasks:
- name: Find out playbooks path
shell: pwd
register: playbook_path_output
- debug: var=playbook_path_output.stdout
and it produced my home directory and not the "current working directory"
I settled with
---
- hosts: all
roles:
- role: '{{playbook_dir}}'
per the solution above.
Here's how I would do it. I'll leave range checking on the int month
up to you.
import java.text.DateFormatSymbols;
public String formatMonth(int month, Locale locale) {
DateFormatSymbols symbols = new DateFormatSymbols(locale);
String[] monthNames = symbols.getMonths();
return monthNames[month - 1];
}
We were able to solve this problem by adding in the Object.Assign polyfill to the files being imported and throwing the error. We would make it the highest import, that way it would be available to the other code to be called in the stack.
import "mdn-polyfills/Object.assign";
onchange
only occurs when the change to the input element is committed by the user, most of the time this is when the element loses focus.
if you want your function to fire everytime the element value changes you should use the oninput
event - this is better than the key up/down events as the value can be changed with the user's mouse ie pasted in, or auto-fill etc
Probably, the simplest solution on the ES6 age.
Adding following one liner directive makes HTML 'autofocus' attribute effective on Angular.js.
.directive('autofocus', ($timeout) => ({link: (_, e) => $timeout(() => e[0].focus())}))
Now, you can just use HTML5 autofocus syntax like:
<input type="text" autofocus>
the solution is implementing anonymous class in this manner:
import org.openqa.selenium.Point;
import org.openqa.selenium.interactions.HasInputDevices;
import org.openqa.selenium.interactions.Mouse;
import org.openqa.selenium.interactions.internal.Coordinates;
.....
final Point image = page.findImage("C:\\Pictures\\marker.png") ;
Mouse mouse = ((HasInputDevices) driver).getMouse();
Coordinates imageCoordinates = new Coordinates() {
public Point onScreen() {
throw new UnsupportedOperationException("Not supported yet.");
}
public Point inViewPort() {
Response response = execute(DriverCommand.GET_ELEMENT_LOCATION_ONCE_SCROLLED_INTO_VIEW,
ImmutableMap.of("id", getId()));
@SuppressWarnings("unchecked")
Map<String, Number> mapped = (Map<String, Number>) response.getValue();
return new Point(mapped.get("x").intValue(), mapped.get("y").intValue());
}
public Point onPage() {
return image;
}
public Object getAuxiliary() {
// extract the selenium imageElement id (imageElement.toString() and parse out the "{sdafbsdkjfh}" format id) and return it
}
};
mouse.mouseMove(imageCoordinates);
Remember a string is immutable so you will need to create a new string.
Strings are IEnumerable so you should be able to run a for loop over it
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
string alpha = "abcdefghijklmnopqrstuvwxyz";
var builder = new StringBuilder();
int count = 0;
foreach (var c in alpha)
{
builder.Append(c);
if ((++count % 5) == 0)
{
builder.Append('-');
}
}
Console.WriteLine("Before: {0}", alpha);
alpha = builder.ToString();
Console.WriteLine("After: {0}", alpha);
}
}
}
Produces this:
Before: abcdefghijklmnopqrstuvwxyz
After: abcde-fghij-klmno-pqrst-uvwxy-z
This will search every column of every table in a specific database. Create the stored procedure on the database that you want to search in.
The Ten Most Asked SQL Server Questions And Their Answers:
CREATE PROCEDURE FindMyData_String
@DataToFind NVARCHAR(4000),
@ExactMatch BIT = 0
AS
SET NOCOUNT ON
DECLARE @Temp TABLE(RowId INT IDENTITY(1,1), SchemaName sysname, TableName sysname, ColumnName SysName, DataType VARCHAR(100), DataFound BIT)
INSERT INTO @Temp(TableName,SchemaName, ColumnName, DataType)
SELECT C.Table_Name,C.TABLE_SCHEMA, C.Column_Name, C.Data_Type
FROM Information_Schema.Columns AS C
INNER Join Information_Schema.Tables AS T
ON C.Table_Name = T.Table_Name
AND C.TABLE_SCHEMA = T.TABLE_SCHEMA
WHERE Table_Type = 'Base Table'
And Data_Type In ('ntext','text','nvarchar','nchar','varchar','char')
DECLARE @i INT
DECLARE @MAX INT
DECLARE @TableName sysname
DECLARE @ColumnName sysname
DECLARE @SchemaName sysname
DECLARE @SQL NVARCHAR(4000)
DECLARE @PARAMETERS NVARCHAR(4000)
DECLARE @DataExists BIT
DECLARE @SQLTemplate NVARCHAR(4000)
SELECT @SQLTemplate = CASE WHEN @ExactMatch = 1
THEN 'If Exists(Select *
From ReplaceTableName
Where Convert(nVarChar(4000), [ReplaceColumnName])
= ''' + @DataToFind + '''
)
Set @DataExists = 1
Else
Set @DataExists = 0'
ELSE 'If Exists(Select *
From ReplaceTableName
Where Convert(nVarChar(4000), [ReplaceColumnName])
Like ''%' + @DataToFind + '%''
)
Set @DataExists = 1
Else
Set @DataExists = 0'
END,
@PARAMETERS = '@DataExists Bit OUTPUT',
@i = 1
SELECT @i = 1, @MAX = MAX(RowId)
FROM @Temp
WHILE @i <= @MAX
BEGIN
SELECT @SQL = REPLACE(REPLACE(@SQLTemplate, 'ReplaceTableName', QUOTENAME(SchemaName) + '.' + QUOTENAME(TableName)), 'ReplaceColumnName', ColumnName)
FROM @Temp
WHERE RowId = @i
PRINT @SQL
EXEC SP_EXECUTESQL @SQL, @PARAMETERS, @DataExists = @DataExists OUTPUT
IF @DataExists =1
UPDATE @Temp SET DataFound = 1 WHERE RowId = @i
SET @i = @i + 1
END
SELECT SchemaName,TableName, ColumnName
FROM @Temp
WHERE DataFound = 1
GO
To run it, just do this:
exec FindMyData_string 'google', 0
It works amazingly well!!!
It's not really an IDE per se, but I really like TextMate, and with the C++ bundle that ships with it, it can do a lot of the things you'd find in an IDE (without all the bloat!).
If you're writing a Java Applet, you can override the Applet "destroy()" method. It is...
* Called by the browser or applet viewer to inform * this applet that it is being reclaimed and that it should destroy * any resources that it has allocated. The stop() method * will always be called before destroy().
Obviously not what you want, but might be what other people are looking for.
right click on app folder->new->folder->Assets folder->set Target Source set->click on finish button
In Notepad++ to replace, hit Ctrl+H to open the Replace menu.
Then if you check the "Regular expression" button and you want in your replacement to use a part of your matching pattern, you must use "capture groups" (read more on google). For example, let's say that you want to match each of the following lines
value="4"
value="403"
value="200"
value="201"
value="116"
value="15"
using the .*"\d+"
pattern and want to keep only the number. You can then use a capture group in your matching pattern, using parentheses (
and )
, like that: .*"(\d+)"
. So now in your replacement you can simply write $1
, where $1 references to the value of the 1st capturing group and will return the number for each successful match. If you had two capture groups, for example (.*)="(\d+)"
, $1
will return the string value
and $2
will return the number.
So by using:
Find: .*"(\d+)"
Replace: $1
It will return you
4
403
200
201
116
15
Please note that there many alternate and better ways of matching the aforementioned pattern. For example the pattern value="([0-9]+)"
would be better, since it is more specific and you will be sure that it will match only these lines. It's even possible of making the replacement without the use of capture groups, but this is a slightly more advanced topic, so I'll leave it for now :)
For :
OS X : 10.11.6
Java : 8
I confirm the answer of @Morrie .
export JAVA_HOME=/Library/Internet\ Plug-Ins/JavaAppletPlugin.plugin/Contents/Home;
But if you are running containers your life will be easier
XmlReaderSettings _configsettings = new XmlReaderSettings();
_configsettings.IgnoreComments = true;
XmlReader _configreader = XmlReader.Create(ConfigFilePath, _configsettings);
XmlDocument doc_config = new XmlDocument();
doc_config.Load(_configreader);
_configreader.Close();
foreach (XmlNode RootName in doc_config.DocumentElement.ChildNodes)
{
if (RootName.LocalName == "appSettings")
{
if (RootName.HasChildNodes)
{
foreach (XmlNode _child in RootName.ChildNodes)
{
if (_child.Attributes["key"].Value == "HostName")
{
if (_child.Attributes["value"].Value == "false")
_child.Attributes["value"].Value = "true";
}
}
}
}
}
doc_config.Save(ConfigFilePath);
Another way of going to directly after logging in is create "Alias". When you login into your system just type that alias and you will be in that directory.
Example : Alias = myfolder '/var/www/Folder'
After you log in to your system type that alias (this works from any part of the system)
this command if not in bashrc will work for current session. So you can also add this alias to bashrc to use that in future
$ myfolder => takes you to that folder
0 will get printed.
As in C++ true refers to 1 and false refers to 0.
In case, you want to print false instead of 0,then you have to sets the boolalpha format flag for the str stream.
When the boolalpha format flag is set, bool values are inserted/extracted by their textual representation: either true or false, instead of integral values.
#include <iostream>
int main()
{
std::cout << std::boolalpha << false << std::endl;
}
output:
false
Is something wrong with the packages, when it generating de file /usr/bin/pip, you have to change the import:
from pip import main
to
from pip._internal import main
That solves the problem, I'm not sure why it generated, but it saids somthing in the following issue:
After pip 10 upgrade on pyenv "ImportError: cannot import name 'main'"
I can resolve this problem using the following code using Bootstrap 4:
<table class="table">
<tbody>
<tr class="d-flex">
<th class="col-3" scope="row">Indicador:</th>
<td class="col-9">this is my indicator</td>
</tr>
<tr class="d-flex">
<th class="col-3" scope="row">Definición:</th>
<td class="col-9">This is my definition</td>
</tr>
</tbody>
</table>
select template; iframe controller, ng model update
index.html
angularapp.controller('FieldCtrl', function ($scope, $sce) {
var iframeclass = '';
$scope.loadTemplate = function() {
if ($scope.template.length > 0) {
// add iframe classs
iframeclass = $scope.template.split('.')[0];
iframe.classList.add(iframeclass);
$scope.activeTemplate = $sce.trustAsResourceUrl($scope.template);
} else {
iframe.classList.remove(iframeclass);
};
};
});
// custom directive
angularapp.directive('myChange', function() {
return function(scope, element) {
element.bind('input', function() {
// the iframe function
iframe.contentWindow.update({
name: element[0].name,
value: element[0].value
});
});
};
});
iframe.html
window.update = function(data) {
$scope.$apply(function() {
$scope[data.name] = (data.value.length > 0) ? data.value: defaults[data.name];
});
};
Check this link: http://plnkr.co/edit/TGRj2o?p=preview
My project luddite
has this feature.
Example usage:
>>> import luddite
>>> luddite.get_versions_pypi("python-dateutil")
('0.1', '0.3', '0.4', '0.5', '1.0', '1.1', '1.2', '1.4', '1.4.1', '1.5', '2.0', '2.1', '2.2', '2.3', '2.4.0', '2.4.1', '2.4.2', '2.5.0', '2.5.1', '2.5.2', '2.5.3', '2.6.0', '2.6.1', '2.7.0', '2.7.1', '2.7.2', '2.7.3', '2.7.4', '2.7.5', '2.8.0')
It lists all versions of a package available, by querying the json API of https://pypi.org/
Object.values()
is part of ES2017, and the compile error you are getting is because you need to configure TS to use the ES2017 library. You are probably using ES6 or ES5 library in your current TS configuration.
Solution: use es2017
or es2017.object
in your --lib
compiler option.
For example, using tsconfig.json
:
"compilerOptions": {
"lib": ["es2017", "dom"]
}
Note that targeting ES2017 with TypeScript does not emit polyfills in the browser for ES2017 (meaning the above solves your compile error, but you can still encounter a runtime error because the browser doesn't implement ES2017 Object.values
), it's up to you to polyfill your project code yourself if you want. And since Object.values
is not yet well supported by all browsers (at the time of this writing) you definitely want a polyfill: core-js
will do the job.
The parent of the row is not the object you think, this is what I understand from the error.
Try detecting the parent of the row first, then you can be sure what to write into getElementById
part of the parent.
BTW: the .htaccess config must be done on the server hosting the API. For example you create an AngularJS app on x.com domain and create a Rest API on y.com, you should set Access-Control-Allow-Origin "*" in the .htaccess file on the root folder of y.com not x.com :)
<IfModule mod_headers.c>
Header set Access-Control-Allow-Origin "*"
</IfModule>
Also as Lukas mentioned make sure you have enabled mod_headers if you use Apache
You could use indexOf
function.
if(list.indexOf(createItem.artNr) !== -1) {
$scope.message = 'artNr already exists!';
}
More about indexOf:
The trick here is that the ToolTip control is an extender control, which means that it will extend the set of properties for other controls on the form. Behind the scenes this is achieved by generating code like in Svetlozar's answer. There are other controls working in the same manner (such as the HelpProvider
).
If you need direct access:
WScript.Arguments.Item(0)
WScript.Arguments.Item(1)
...
I also had this issue using Lumen, but fixed by setting DB_STRICT_MODE=false
in .env
file.
Another form that works with Postgres 9.1+ is combining a Common Table Expression with the USING statement for the join.
WITH prod AS (select m_product_id, upc from m_product where upc='7094')
DELETE FROM m_productprice B
USING prod C
WHERE B.m_product_id = C.m_product_id
AND B.m_pricelist_version_id = '1000020';
The simpliest way is to drop database phpmyadmin and run sql/create_tables.sql script. Just login to mysql console and:
DROP DATABASE phpmyadmin;
\. {your path to pma}/sql/reate_tables.sql
In your custom array adapter, you override the getView() method, as you presumably familiar with. Then all you have to do is use a switch statement or an if statement to return a certain custom View depending on the position argument passed to the getView method. Android is clever in that it will only give you a convertView of the appropriate type for your position/row; you do not need to check it is of the correct type. You can help Android with this by overriding the getItemViewType() and getViewTypeCount() methods appropriately.
For Chrome users, I recommend Stylebot, which will let you override any CSS on any page, also let you search and install other share custom CSS. However, for our purpose we don't need any advance theme. Open Stylebot, change to Edit CSS
. Jupyter captures some keystrokes, so you will not be able to type the code below in. Just copy and paste, or just your editor:
#notebook-container.container {
width: 90%;
}
Change the width as you like, I find 90% looks nicer than 100%. But it is totally up to your eye.
We should remove notification also.
Ex.
deinit
{
NotificationCenter.default.removeObserver(self, name:NSNotification.Name(rawValue: "notify"), object: nil)
}
You use a for..in
loop for this. Be sure to check if the object owns the properties or all inherited properties are shown as well. An example is like this:
var obj = {a: 1, b: 2};
for (var key in obj) {
if (obj.hasOwnProperty(key)) {
var val = obj[key];
console.log(val);
}
}
Or if you need recursion to walk through all the properties:
var obj = {a: 1, b: 2, c: {a: 1, b: 2}};
function walk(obj) {
for (var key in obj) {
if (obj.hasOwnProperty(key)) {
var val = obj[key];
console.log(val);
walk(val);
}
}
}
walk(obj);
below example with target="_blank"
works for Safari and Mozilla
<a href="http://www.starfall.com" `target="_blank"`>
Using target="new"
worked for Chrome
<a href="http://www.starfall.com" `target="new"`>
I know that the question is two years old, but it was the first result of what I am looking for. I found a good answers and I hope I can help other users.
I will make this brief:
use the $_SERVER["PHP_SELF"]
Variable with htmlspecialchars
():
`htmlspecialchars($_SERVER["PHP_SELF"]);`
PHP_SELF returns the filename of the currently executing script.
htmlspecialchars
() function converts special characters to HTML entities.
--> NO XSSActually the best way to sheared you app between users , google (firebase) proved new technology Firebase Dynamic Link Through several lines you can make it this is documentation https://firebase.google.com/docs/dynamic-links/ and the code is
Uri dynamicLinkUri = dynamicLink.getUri();
Task<ShortDynamicLink> shortLinkTask = FirebaseDynamicLinks.getInstance().createDynamicLink()
.setLink(Uri.parse("https://www.google.jo/"))
.setDynamicLinkDomain("rw4r7.app.goo.gl")
.buildShortDynamicLink()
.addOnCompleteListener(this, new OnCompleteListener<ShortDynamicLink>() {
@Override
public void onComplete(@NonNull Task<ShortDynamicLink> task) {
if (task.isSuccessful()) {
// Short link created
Uri shortLink = task.getResult().getShortLink();
Uri flowchartLink = task.getResult().getPreviewLink();
Intent intent = new Intent();
intent.setAction(Intent.ACTION_SEND);
intent.putExtra(Intent.EXTRA_TEXT, shortLink.toString());
intent.setType("text/plain");
startActivity(intent);
} else {
// Error
// ...
}
}
});
Passive event listeners are an emerging web standard, new feature shipped in Chrome 51 that provide a major potential boost to scroll performance. Chrome Release Notes.
It enables developers to opt-in to better scroll performance by eliminating the need for scrolling to block on touch and wheel event listeners.
Problem: All modern browsers have a threaded scrolling feature to permit scrolling to run smoothly even when expensive JavaScript is running, but this optimization is partially defeated by the need to wait for the results of any touchstart
and touchmove
handlers, which may prevent the scroll entirely by calling preventDefault()
on the event.
Solution: {passive: true}
By marking a touch or wheel listener as passive, the developer is promising the handler won't call preventDefault
to disable scrolling. This frees the browser up to respond to scrolling immediately without waiting for JavaScript, thus ensuring a reliably smooth scrolling experience for the user
.
document.addEventListener("touchstart", function(e) {
console.log(e.defaultPrevented); // will be false
e.preventDefault(); // does nothing since the listener is passive
console.log(e.defaultPrevented); // still false
}, Modernizr.passiveeventlisteners ? {passive: true} : false);
My own settings (Java 1.7, modify for 1.6):
-vm
C:/Program Files (x86)/Java/jdk1.7.0/bin
-startup
plugins/org.eclipse.equinox.launcher_1.1.0.v20100507.jar
--launcher.library
plugins/org.eclipse.equinox.launcher.win32.win32.x86_1.1.100.v20100628
-showsplash
org.eclipse.platform
--launcher.XXMaxPermSize
256m
--launcher.defaultAction
openFile
-vmargs
-server
-Dosgi.requiredJavaVersion=1.7
-Xmn100m
-Xss1m
-XgcPrio:deterministic
-XpauseTarget:20
-XX:PermSize=400M
-XX:MaxPermSize=500M
-XX:CompileThreshold=10
-XX:MaxGCPauseMillis=10
-XX:MaxHeapFreeRatio=70
-XX:+UnlockExperimentalVMOptions
-XX:+DoEscapeAnalysis
-XX:+UseG1GC
-XX:+UseFastAccessorMethods
-XX:+AggressiveOpts
-Xms512m
-Xmx512m
I was having exactly the same problem. I looked for two hours what was wrong with no luck until I realize my POST
method was private
instead of public
.
Funny now seeing that error message is kind of generic. Hope it helps!
Because if you want to trigger your data with deep of it,you have to pass 3th argument true
of your listener.By default it's false
and it meens that you function will trigger,only when your variable will change not it's field.
The Apache Geronimo project provides a Servlet 3.0 API dependency on the Maven Central repo:
<dependency>
<groupId>org.apache.geronimo.specs</groupId>
<artifactId>geronimo-servlet_3.0_spec</artifactId>
<version>1.0</version>
</dependency>
If you are using the Eloquent ORM you should consider using scopes. This would keep your logic in the model where it belongs.
So, in the model you would have:
public function scopeIdDescending($query)
{
return $query->orderBy('id','DESC');
}
And outside the model you would have:
$posts = Post::idDescending()->get();
Why not a/b/(c|d|e)
? I just tried with Saxon XML library (wrapped up nicely with some Clojure goodness), and it seems to work.
abc.xml
is the doc described by OP.
(require '[saxon :as xml])
(def abc-doc (xml/compile-xml (slurp "abc.xml")))
(xml/query "a/b/(c|d|e)" abc-doc)
=> (#<XdmNode <c>C1</c>>
#<XdmNode <d>D1</d>>
#<XdmNode <e>E1</e>>
#<XdmNode <c>C2</c>>
#<XdmNode <d>D2</d>>
#<XdmNode <e>E1</e>>)
For similar tasks, you can use sessionStorage
to store data locally until the browser tab is closed.
The sessionStorage
object stores data for only one session (the data is deleted when the browser tab is closed).(W3Schools)
<div id="Notice">
<span title="remove this until browser tab is closed"><u>dismiss</u>.</span>
</div>
<script>
$("#Notice").click(function() {
//set sessionStorage on click
sessionStorage.setItem("dismissNotice", "Hello");
$("#Notice").remove();
});
if (sessionStorage.getItem("dismissNotice"))
//When sessionStorage is set Do stuff...
$("#Notice").remove();
</script>
function foo(x) {
// Function with other context
// Modify `x` property, increasing the value
x.value++;
}
// Initialize `ref` as object
var ref = {
// The `value` is inside `ref` variable object
// The initial value is `1`
value: 1
};
// Call function with object value
foo(ref);
// Call function with object value again
foo(ref);
console.log(ref.value); // Prints "3"
_x000D_
rvar
/**
* Aux function to create by-references variables
*/
function rvar(name, value, context) {
// If `this` is a `rvar` instance
if (this instanceof rvar) {
// Inside `rvar` context...
// Internal object value
this.value = value;
// Object `name` property
Object.defineProperty(this, 'name', { value: name });
// Object `hasValue` property
Object.defineProperty(this, 'hasValue', {
get: function () {
// If the internal object value is not `undefined`
return this.value !== undefined;
}
});
// Copy value constructor for type-check
if ((value !== undefined) && (value !== null)) {
this.constructor = value.constructor;
}
// To String method
this.toString = function () {
// Convert the internal value to string
return this.value + '';
};
} else {
// Outside `rvar` context...
// Initialice `rvar` object
if (!rvar.refs) {
rvar.refs = {};
}
// Initialize context if it is not defined
if (!context) {
context = window;
}
// Store variable
rvar.refs[name] = new rvar(name, value, context);
// Define variable at context
Object.defineProperty(context, name, {
// Getter
get: function () { return rvar.refs[name]; },
// Setter
set: function (v) { rvar.refs[name].value = v; },
// Can be overrided?
configurable: true
});
// Return object reference
return context[name];
}
}
// Variable Declaration
// Declare `test_ref` variable
rvar('test_ref_1');
// Assign value `5`
test_ref_1 = 5;
// Or
test_ref_1.value = 5;
// Or declare and initialize with `5`:
rvar('test_ref_2', 5);
// ------------------------------
// Test Code
// Test Function
function Fn1 (v) { v.value = 100; }
// Declare
rvar('test_ref_number');
// First assign
test_ref_number = 5;
console.log('test_ref_number.value === 5', test_ref_number.value === 5);
// Call function with reference
Fn1(test_ref_number);
console.log('test_ref_number.value === 100', test_ref_number.value === 100);
// Increase value
test_ref_number++;
console.log('test_ref_number.value === 101', test_ref_number.value === 101);
// Update value
test_ref_number = test_ref_number - 10;
console.log('test_ref_number.value === 91', test_ref_number.value === 91);
// Declare and initialize
rvar('test_ref_str', 'a');
console.log('test_ref_str.value === "a"', test_ref_str.value === 'a');
// Update value
test_ref_str += 'bc';
console.log('test_ref_str.value === "abc"', test_ref_str.value === 'abc');
// Declare other...
rvar('test_ref_number', 5);
test_ref_number.value === 5; // true
// Call function
Fn1(test_ref_number);
test_ref_number.value === 100; // true
// Increase value
test_ref_number++;
test_ref_number.value === 101; // true
// Update value
test_ref_number = test_ref_number - 10;
test_ref_number.value === 91; // true
test_ref_str.value === "a"; // true
// Update value
test_ref_str += 'bc';
test_ref_str.value === "abc"; // true
_x000D_
I have a very simple answer which works:
set-executionpolicy unrestricted
I found this solution following the link that was given as part of error message: About Execution Policies
In my opinion, using "if(value)" to judge a value whether is an empty value is not strict, because the result of "v?true:false" is false when the value of v is 0(0 is not an empty value). You can use this function:
const isEmptyValue = (value) => {
if (value === '' || value === null || value === undefined) {
return true
} else {
return false
}
}
You can also do ORDER BY TITLE COLLATE NOCASE
.
Edit: If you need to specify ASC
or DESC
, add this after NOCASE
like
ORDER BY TITLE COLLATE NOCASE ASC
or
ORDER BY TITLE COLLATE NOCASE DESC
Remember that casing is a locale specific operation. Depending on scenario you may want to take that in to account. For example, if you are comparing names of two people you may want to consider locale but if you are comparing machine generated values such as UUID then you might not. This why I use following function in my utils library (note that type checking is not included for performance reason).
function compareStrings (string1, string2, ignoreCase, useLocale) {
if (ignoreCase) {
if (useLocale) {
string1 = string1.toLocaleLowerCase();
string2 = string2.toLocaleLowerCase();
}
else {
string1 = string1.toLowerCase();
string2 = string2.toLowerCase();
}
}
return string1 === string2;
}
A raw type is the name of a generic class or interface without any type arguments. For example, given the generic Box class:
public class Box<T> {
public void set(T t) { /* ... */ }
// ...
}
To create a parameterized type of Box, you supply an actual type argument for the formal type parameter T:
Box<Integer> intBox = new Box<>();
If the actual type argument is omitted, you create a raw type of Box:
Box rawBox = new Box();
When using the Windows Subsystem for Linux (e.g. Ubuntu/Debian on WSL) the xclip
solution won't work. Instead you need to use clip.exe
and powershell.exe
to copy into and paste from the Windows clipboard.
This solution works on "real" Linux-based systems (i.e. Ubuntu, Debian) as well as on WSL systems. Just put the following code into your .bashrc
:
if grep -q -i microsoft /proc/version; then
# on WSL
alias copy="clip.exe"
alias paste="powershell.exe Get-Clipboard"
else
# on "normal" linux
alias copy="xclip -sel clip"
alias paste="xclip -sel clip -o"
fi
How it works
The file /proc/version
contains information about the currently running OS. When the system is running in WSL mode, then this file additionally contains the string Microsoft
which is checked by grep
.
To copy:
cat file | copy
And to paste:
paste > new_file
For this html:
<div class="outer">
<div class="inner"></div>
</div>
This selector should work:
$('.outer > .inner')
You may try this CSS. I have experienced it working always.
div {
border-style: solid;
padding: 5px;
}
table {
width: 100%;
word-break: break-all;
border-style: solid;
}
_x000D_
<div style="width:200px;">
<table>
<tr>
<th>Col 1</th>
<th>Col 2</th>
<th>Col 3</th>
<th>Col 4</th>
<th>Col 5</th>
</tr>
<tr>
<td>data 1</td>
<td>data 2</td>
<td>data 3</td>
<td>data 4</td>
<td>data 5</td>
</tr>
<table>
</div>
_x000D_
This is exactly what TO_DATE()
is for: to convert timestamp to date.
Just use TO_DATE(sysdate)
instead of TO_CHAR(sysdate, 'YYYY/MM/DD-HH24-MI-SS-SSSSS')
.
UPDATE:
Per your update, your cdate
column is not real DATE
or TIMESTAMP
type, but VARCHAR2
. It is not very good idea to use string types to keep dates. It is very inconvenient and slow to search, compare and do all other kinds of math on dates.
You should convert your cdate
VARCHAR2
field into real TIMESTAMP
. Assuming there are no other users for this field except for your code, you can convert cdate
to timestamp as follows:
BEGIN TRANSACTION;
-- add new temp field tdate:
ALTER TABLE mytable ADD tdate TIMESTAMP;
-- save cdate to tdate while converting it:
UPDATE mytable SET tdate = to_date(cdate, 'YYYY-MM-DD HH24:MI:SS');
-- you may want to check contents of tdate before next step!!!
-- drop old field
ALTER TABLE mytable DROP COLUMN cdate;
-- rename tdate to cdate:
ALTER TABLE mytable RENAME COLUMN tdate TO cdate;
COMMIT;
Using MySQL connector and Entity Framework Core 2.0
My issue was that I was getting an exception like fx. Ex.Message = "The required column 'body' was not present in the results of a 'FromSql' operation.". So, in order to fetch rows via a stored procedure in this manner, you must return all columns for that entity type which the DBSet is associated with, even if you don't need to access all of it for your current request.
var result = _context.DBSetName.FromSql($"call storedProcedureName()").ToList();
OR with parameters
var result = _context.DBSetName.FromSql($"call storedProcedureName({optionalParam1})").ToList();
JPA doesn't allow the @Id annotation on a OneToOne or ManyToOne mapping. What you are trying to do is one-to-one entity association with shared primary key. The simplest case is unidirectional one-to-one with shared key:
@Entity
public class Person {
@Id
private int id;
@OneToOne
@PrimaryKeyJoinColumn
private OtherInfo otherInfo;
rest of attributes ...
}
The main problem with this is that JPA provides no support for shared primary key generation in OtherInfo entity. The classic book Java Persistence with Hibernate by Bauer and King gives the following solution to the problem using Hibernate extension:
@Entity
public class OtherInfo {
@Id @GeneratedValue(generator = "customForeignGenerator")
@org.hibernate.annotations.GenericGenerator(
name = "customForeignGenerator",
strategy = "foreign",
parameters = @Parameter(name = "property", value = "person")
)
private Long id;
@OneToOne(mappedBy="otherInfo")
@PrimaryKeyJoinColumn
public Person person;
rest of attributes ...
}
Also, see here.
Use getColorStateList
like this
setTextColor(resources.getColorStateList(R.color.button_states_color))
instead of getColor
setTextColor(resources.getColor(R.color.button_states_color))
From API 25.3.0 it was introduced the method setSelectedItemId(int id)
which lets you mark an item as selected as if it was tapped.
From docs:
Set the selected menu item ID. This behaves the same as tapping on an item.
Code example:
BottomNavigationView bottomNavigationView;
bottomNavigationView = (BottomNavigationView) findViewById(R.id.bottomNavigationView);
bottomNavigationView.setOnNavigationItemSelectedListener(myNavigationItemListener);
bottomNavigationView.setSelectedItemId(R.id.my_menu_item_id);
IMPORTANT
You MUST have already added all items to the menu (in case you do this programmatically) and set the Listener before calling setSelectedItemId(I believe you want the code in your listener to run when you call this method). If you call setSelectedItemId before adding the menu items and setting the listener nothing will happen.
Since there were no exact answers to my question, I made some investigation why my code doesn't work when there are other solutions that works, and decided to post what I found to complete the subject.
As it turns out:
"ssh uses direct TTY access to make sure that the password is indeed issued by an interactive keyboard user." sshpass manpage
which answers the question, why the pipes don't work in this case. The obvious solution was to create conditions so that ssh
"thought" that it is run in the regular terminal and since it may be accomplished by simple posix
functions, it is beyond what simple bash
offers.
You may already have Process Explorer (from Sysinternals, now part of Microsoft) installed. If not, go ahead and install it now -- it's just that cool.
In Process Explorer: locate the process in question, right-click and select the TCP/IP tab. It will even show you, for each socket, a stack trace representing the code that opened that socket.
I know this was posted about a year ago, but this is for users for future reference.
I came across similar issue. In my case (i will try to be brief, please do let me know if you would like more detail), i was trying to check if a string was empty or not (string is the subject of an email). It always returned the same error message no matter what i did. I knew i was doing it right but it still kept throwing the same error message. Then it dawned in me that, i was checking if the subject (string) of an email (instance/object), what if the email(instance) was already a null at the first place. How could i check for a subject of an email, if the email is already a null..i checked if the the email was empty, it worked fine.
while checking for the subject(string) i used IsNullorWhiteSpace(), IsNullOrEmpty() methods.
if (email == null)
{
break;
}
else
{
// your code here
}
For those, who want to do it automatically, I have wrote a little two-lines bash script which does next two things:
Renames extracted classes.jar to be like the aar but with a new extension
find . -name '*.aar' -exec sh -c 'unzip -d `dirname {}` {} classes.jar' \;
find . -name '*.aar' -exec sh -c 'mv `dirname {}`/classes.jar `echo {} | sed s/aar/jar/g`' \;
That's it!
Try this:
Calendar calendar = Calendar.getInstance();
calendar.setTime(yourdate);
int hours = calendar.get(Calendar.HOUR_OF_DAY);
int minutes = calendar.get(Calendar.MINUTE);
int seconds = calendar.get(Calendar.SECOND);
Edit:
hours, minutes, seconds
above will be the hours, minutes and seconds after converting yourdate
to System Timezone!
Download the file of website and start it with the commandline switch "/layout" (see msdn to download visual studio 2015 installer for offline installation). So C:\vs_community.exe /layout
for example. It asks for a location and the download begins.
EDIT: With the ISO version you still need internet connection to be able to install ALL the features. As pointed out by Augusto Barreto.
It's a pity to use .NET and not use collections and lambda to save your time and code lines This is an example of how this works: Transform yourDataTable to Enumerable, filter it if you want , according a "FILTER_ROWS_FIELD" column, and if you want, group your data by a "A_GROUP_BY_FIELD". Then get the count, the sum, or whatever you wish. If you want a count and a sum without grouby don't group the data
var groupedData = from b in yourDataTable.AsEnumerable().Where(r=>r.Field<int>("FILTER_ROWS_FIELD").Equals(9999))
group b by b.Field<string>("A_GROUP_BY_FIELD") into g
select new
{
tag = g.Key,
count = g.Count(),
sum = g.Sum(c => c.Field<double>("rvMoney"))
};
Use tqdm_notebook
from tqdm import tqdm_notebook as tqdm
x=[1,2,3,4,5]
for i in tqdm(range(0,len(x))):
print(x[i])
It should also be noted that you can't override the constructor in the subclass with the constructor of the superclass's name. The rule of OOPS tells that a constructor should have name as its class name. If we try to override the superclass constructor it will be seen as an unknown method without a return type.
I know I should not necromancy on a subject, but given the details of the question, I usually expand it to mean:
For this, I use code like this (the parenthesis on the first regexp are there just in order to make the code a bit more readable ... regexps can be a pain unless you are familiar with them):
s = s.replace(/^(\s*)|(\s*)$/g, '').replace(/\s+/g, ' ');
The reason this works is that the methods on String-object return a string object on which you can invoke another method (just like jQuery & some other libraries). Much more compact way to code if you want to execute multiple methods on a single object in succession.
It's necessary to install redhat-rpm-config to. I guess it solve your problem!
Another solution you can use is SQL Developer.
With it, you have the ability to import from a csv file (other delimited files are available).
Just open the table view, then:
You have the option to have SQL Developer do the inserts for you, create an sql insert script, or create the data for a SQL Loader script (have not tried this option myself).
Of course all that is moot if you can only use the command line, but if you are able to test it with SQL Developer locally, you can always deploy the generated insert scripts (for example).
Just adding another option to the 2 already very good answers.
Today i also face this type of problem during visual studio 2015 Community installation. As i have 64bit OS. I used https://www.microsoft.com/en-us/download/details.aspx?id=49093 link to update KB2999226 mannualy.
Try It. Good luck.
VB Version (using port 9100 - tested on Zebra ZM400)
Sub PrintZPL(ByVal pIP As String, ByVal psZPL As String)
Dim lAddress As Net.IPEndPoint
Dim lSocket As System.Net.Sockets.Socket = Nothing
Dim lNetStream As System.Net.Sockets.NetworkStream = Nothing
Dim lBytes As Byte()
Try
lAddress = New Net.IPEndPoint(Net.IPAddress.Parse(pIP), 9100)
lSocket = New Socket(AddressFamily.InterNetwork, SocketType.Stream, _ ProtocolType.Tcp)
lSocket.Connect(lAddress)
lNetStream = New NetworkStream(lSocket)
lBytes = System.Text.Encoding.ASCII.GetBytes(psZPL)
lNetStream.Write(lBytes, 0, lBytes.Length)
Catch ex As Exception When Not App.Debugging
Msgbox ex.message & vbnewline & ex.tostring
Finally
If Not lNetStream Is Nothing Then
lNetStream.Close()
End If
If Not lSocket Is Nothing Then
lSocket.Close()
End If
End Try
End Sub
So, yet again the lesson of not polluting the source tree of a project with artifacts that aren't directly related to that project is being ignored.
There is zero reason for a Visual Studio Code workspace file (workspaces.json) or directory (.vscode) or whatever to be placed in the source tree. It could just as easily have been placed under your user settings.
I thought we figured this out about 20+ years ago, but it seems that some lessons are doomed to be repeated.
With Swift 5, you may choose one of the three examples shown below in order to solve your problem.
String
's init(format:_:)
initializerFoundation
provides Swift String
a init(format:_:)
initializer. init(format:_:)
has the following declaration:
init(format: String, _ arguments: CVarArg...)
Returns a
String
object initialized by using a given format string as a template into which the remaining argument values are substituted.
The following Playground code shows how to create a String
formatted from Int
with at least two integer digits by using init(format:_:)
:
import Foundation
let string0 = String(format: "%02d", 0) // returns "00"
let string1 = String(format: "%02d", 1) // returns "01"
let string2 = String(format: "%02d", 10) // returns "10"
let string3 = String(format: "%02d", 100) // returns "100"
String
's init(format:arguments:)
initializerFoundation
provides Swift String
a init(format:arguments:)
initializer. init(format:arguments:)
has the following declaration:
init(format: String, arguments: [CVarArg])
Returns a
String
object initialized by using a given format string as a template into which the remaining argument values are substituted according to the user’s default locale.
The following Playground code shows how to create a String
formatted from Int
with at least two integer digits by using init(format:arguments:)
:
import Foundation
let string0 = String(format: "%02d", arguments: [0]) // returns "00"
let string1 = String(format: "%02d", arguments: [1]) // returns "01"
let string2 = String(format: "%02d", arguments: [10]) // returns "10"
let string3 = String(format: "%02d", arguments: [100]) // returns "100"
NumberFormatter
Foundation provides NumberFormatter
. Apple states about it:
Instances of
NSNumberFormatter
format the textual representation of cells that containNSNumber
objects and convert textual representations of numeric values intoNSNumber
objects. The representation encompasses integers, floats, and doubles; floats and doubles can be formatted to a specified decimal position.
The following Playground code shows how to create a NumberFormatter
that returns String?
from a Int
with at least two integer digits:
import Foundation
let formatter = NumberFormatter()
formatter.minimumIntegerDigits = 2
let optionalString0 = formatter.string(from: 0) // returns Optional("00")
let optionalString1 = formatter.string(from: 1) // returns Optional("01")
let optionalString2 = formatter.string(from: 10) // returns Optional("10")
let optionalString3 = formatter.string(from: 100) // returns Optional("100")
I used jordan314's solution, but then I added "border-light" class to select. If you have default border-light class defined in css, you can directly use it. It just defines the border as white). I changed the border to square/remove the radius, and maintained the arrow.
Here is what I did:
<select class="form-control border border-light" id="type">
<option>Select</option>
<option value="mobile">Apple</option>
</select>
if you don't have the predefined border-light, just add in your css:
<style>
.border-light{
border-color:#f8f9fa!important
}
#type {
border:0;
outline:1px solid #ddd;
background-color:white;
}
</style>
You can do something like this to code for both versions:
/**
* Sets the Action Bar for new Android versions.
*/
@TargetApi(Build.VERSION_CODES.HONEYCOMB)
private void actionBarSetup() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
ActionBar ab = getActionBar();
ab.setTitle("My Title");
ab.setSubtitle("sub-title");
}
}
Then call actionBarSetup()
in onCreate()
. The if
runs the code only on new Android versions and the @TargetApi
allows the code to compile. Therefore it makes it safe for both old and new API versions.
Alternatively, you can also use ActionBarSherlock (see edit) so you can have the ActionBar on all versions. You will have to do some changes such as making your Activities extend SherlockActivity
and calling getSupportActionBar()
, however, it is a very good global solution.
Note that when this answer was originally written, ActionBarSherlock
, which has since been deprecated, was the go-to compatibility solution.
Nowadays, Google's appcompat-v7
library provides the same functionality but is supported (and actively updated) by Google. Activities wanting to implement an ActionBar
must:
AppCompatActivity
Theme.AppCompat
derivativeTo get an ActionBar
instance using this library, the aptly-named getSupportActionBar()
method is used.
Since Java 11 the most convenient way it to use java.net.http.HttpClient
from the standard library.
Example:
HttpRequest request = HttpRequest.newBuilder(new URI(
"https://stackoverflow.com/questions/6159118/using-java-to-pull-data-from-a-webpage"))
.timeout(Duration.of(10, SECONDS))
.GET()
.build();
HttpResponse<String> response = HttpClient.newHttpClient()
.send(request, BodyHandlers.ofString());
if (response.statusCode() != 200) {
throw new RuntimeException(
"Invalid response: " + response.statusCode() + ", request: " + response);
}
System.out.println(response.body());
All you have to do is enable the multiline in the properties window, put the size you want in that same window and then in your .cs after the InitializeComponent put txtexample.Multiline = false; and so the multiline is not enabled but the size of the txt is as you put it.
InitializeComponent();
txtEmail.Multiline = false;
txtPassword.Multiline = false;
Another advantage of using the '[[' operator is that it works both with data.frame and data.table. So if the function has to be made running for both data.frame and data.table, and you want to extract a column from it as a vector then
data[["column_name"]]
is best.
I need something similiar with angular reactive form:
let myMap = new Map().set(0, {status: 'VALID'}).set(1, {status: 'INVALID'});
let mapToArray = Array.from(myMap.values());
let isValid = mapToArray.every(x => x.status === 'VALID');
At first glance one really wants to use New-PSDrive
supplying it credentials.
> New-PSDrive -Name P -PSProvider FileSystem -Root \\server\share -Credential domain\user
New-PSDrive : Cannot retrieve the dynamic parameters for the cmdlet. Dynamic parameters for NewDrive cannot be retrieved for the 'FileSystem' provider. The provider does not support the use of credentials. Please perform the operation again without specifying credentials.
The documentation states that you can provide a PSCredential
object but if you look closer the cmdlet does not support this yet. Maybe in the next version I guess.
Therefore you can either use net use
or the WScript.Network
object, calling the MapNetworkDrive
function:
$net = new-object -ComObject WScript.Network
$net.MapNetworkDrive("u:", "\\server\share", $false, "domain\user", "password")
Apparently with newer versions of PowerShell, the New-PSDrive
cmdlet works to map network shares with credentials!
New-PSDrive -Name P -PSProvider FileSystem -Root \\Server01\Public -Credential user\domain -Persist
This feature has been added to node.js in version 10.12.0, so it's as easy as passing an option {recursive: true}
as second argument to the fs.mkdir()
call.
See the example in the official docs.
No need for external modules or your own implementation.
Consider this code:
Products::whereIn('id', function($query){
$query->select('paper_type_id')
->from(with(new ProductCategory)->getTable())
->whereIn('category_id', ['223', '15'])
->where('active', 1);
})->get();
/C
Carries out the command specified by the string and then terminates.
You can get all the cmd command line switches by typing cmd /?
.
Same as the accepted answer but a simpler convenience method:
val myDrawable = ContextCompat.getDrawable(context, R.drawable.my_drawable)
myDrawable.setColorFilter(Color.GREEN, PorterDuff.Mode.SRC_IN)
setCompoundDrawablesWithIntrinsicBounds(myDrawable, null, null, null)
Note, the code here is Kotlin.
Thanks for the info, think I see the problem. This is a bug in hive-go
that only shows up when you add a host. The last lines of it are:
app.listen(3001);
console.log("... port %d in %s mode", app.address().port, app.settings.env);
When you add the host on the first line, it is crashing when it calls app.address().port
.
The problem is the potentially asynchronous nature of .listen()
. Really it should be doing that console.log
call inside a callback passed to listen. When you add the host, it tries to do a DNS lookup, which is async. So when that line tries to fetch the address, there isn't one yet because the DNS request is running, so it crashes.
Try this:
app.listen(3001, 'localhost', function() {
console.log("... port %d in %s mode", app.address().port, app.settings.env);
});
I am using React-Bootstrap. The onSelect trigger for dropdowns were not allowing me to pass data. Just the event. So remember you can just set any values as attributes and pick them up from the function using javascript. Picking up those attributes you set in that event target.
let currentTarget = event.target;
let currentId = currentTarget.getAttribute('data-id');
let currentValue = currentTarget.getAttribute('data-value');
I had a similar problem where i have to center the toolTip. React setState in componentDidUpdate did put me in infinite loop, i tried condition it worked. But i found using in ref callback gave me simpler and clean solution, if you use inline function for ref callback you will face the null problem for every component update. So use function reference in ref callback and set the state there, which will initiate the re-render
This explains it. Summary: const must be initialized at declaration time, readonly can be initialized on the constructor (and thus have a different value depending on the constructor used).
EDIT: See Gishu's gotcha above for the subtle difference
iBeacon uses Bluetooth Low Energy(LE) to keep aware of locations, and the distance/range of Bluetooth LE is 160ft (http://en.wikipedia.org/wiki/Bluetooth_low_energy).
In Xcode 7 a quick way is to use Product > Archive. It's probably not a signed copy for submission but it's good enough to give to somebody else for testing.
Use chocolatey in PowerShell
choco install ruby -y
refreshenv
gem install bundler
Use the Timer
class.
public static void Main()
{
System.Timers.Timer aTimer = new System.Timers.Timer();
aTimer.Elapsed += new ElapsedEventHandler(OnTimedEvent);
aTimer.Interval = 5000;
aTimer.Enabled = true;
Console.WriteLine("Press \'q\' to quit the sample.");
while(Console.Read() != 'q');
}
// Specify what you want to happen when the Elapsed event is raised.
private static void OnTimedEvent(object source, ElapsedEventArgs e)
{
Console.WriteLine("Hello World!");
}
The Elapsed
event will be raised every X amount of milliseconds, specified by the Interval
property on the Timer object. It will call the Event Handler
method you specify. In the example above, it is OnTimedEvent
.
Just change the port number used e.g. 8000 then call the http://localhost:8080
First of all, there're two kinds of keystores.
Individual and General
The application will use the one indicated in the startup or the default of the system.
It will be a different folder if JRE or JDK is running, or if you check the personal or the "global" one.
They are encrypted too
In short, the path will be like:
$JAVA_HOME/lib/security/cacerts
for the "general one", who has all the CA for the Authorities and is quite important.
Assuming the MyEjbProject is not another Maven Project you own or want to build with maven, you could use system dependencies to link to the existing jar file of the project like so
<project>
...
<dependencies>
<dependency>
<groupId>yourgroup</groupId>
<artifactId>myejbproject</artifactId>
<version>2.0</version>
<scope>system</scope>
<systemPath>path/to/myejbproject.jar</systemPath>
</dependency>
</dependencies>
...
</project>
That said it is usually the better (and preferred way) to install the package to the repository either by making it a maven project and building it or installing it the way you already seem to do.
If they are, however, dependent on each other, you can always create a separate parent project (has to be a "pom" project) declaring the two other projects as its "modules". (The child projects would not have to declare the third project as their parent). As a consequence you'd get a new directory for the new parent project, where you'd also quite probably put the two independent projects like this:
parent
|- pom.xml
|- MyEJBProject
| `- pom.xml
`- MyWarProject
`- pom.xml
The parent project would get a "modules" section to name all the child modules. The aggregator would then use the dependencies in the child modules to actually find out the order in which the projects are to be built)
<project>
...
<artifactId>myparentproject</artifactId>
<groupId>...</groupId>
<version>...</version>
<packaging>pom</packaging>
...
<modules>
<module>MyEJBModule</module>
<module>MyWarModule</module>
</modules>
...
</project>
That way the projects can relate to each other but (once they are installed in the local repository) still be used independently as artifacts in other projects
Finally, if your projects are not in related directories, you might try to give them as relative modules:
filesystem
|- mywarproject
| `pom.xml
|- myejbproject
| `pom.xml
`- parent
`pom.xml
now you could just do this (worked in maven 2, just tried it):
<!--parent-->
<project>
<modules>
<module>../mywarproject</module>
<module>../myejbproject</module>
</modules>
</project>
if(Object.getOwnPropertyNames(obj).length === 0){
//is empty
}
see http://bencollier.net/2011/04/javascript-is-an-object-empty/
You would use the WITH ADMIN OPTION
option in the GRANT
statement
GRANT CREATE SESSION TO <<username>> WITH ADMIN OPTION
This works fine for me
Run Command Prompt as Administrator
Run Powershell -ExecutionPolicy Unrestricted
Run npm-windows-upgrade
Run npm --version
add display: block;
a-tag is an inline element so your height and width are ignored.
#header div#snav div a{
display:block;
width:150px;
height:77px;
}
I wrote a snippet that allows you to send emails rendered with templates stored in the database. An example:
EmailTemplate.send('expense_notification_to_admin', {
# context object that email template will be rendered with
'expense': expense_request,
})
From the npm-link documentation:
In the local module directory:
$ cd ./package-dir
$ npm link
In the directory of the project to use the module:
$ cd ./project-dir
$ npm link package-name
Or in one go using relative paths:
$ cd ./project-dir
$ npm link ../package-dir
This is equivalent to using two commands above under the hood.
There are two pair of modal events, one is "show" and "shown", the other is "hide" and "hidden". As you can see from the name, hide event fires when modal is about the be close, such as clicking on the cross on the top-right corner or close button or so on. While hidden is fired after the modal is actually close. You can test these events your self. For exampel:
$( '#modal' )
.on('hide', function() {
console.log('hide');
})
.on('hidden', function(){
console.log('hidden');
})
.on('show', function() {
console.log('show');
})
.on('shown', function(){
console.log('shown' )
});
And, as for your question, I think you should listen to the 'hide' event of your modal.
Another implementation that is also working with list of objects, not just strings:
JS:
var postData = {};
postData[values] = selectedValues ;
$.ajax({
url: "/Home/SaveList",
type: "POST",
data: JSON.stringify(postData),
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function(data){
alert(data.Result);
}
});
Assuming that 'selectedValues' is Array of Objects.
In the controller the parameter is a list of corresponding ViewModels.
public JsonResult SaveList(List<ViewModel> values)
{
return Json(new {
Result = String.Format("Fist item in list: '{0}'", values[0].Name)
});
}