Here's a solution in R
subset_sum = function(numbers,target,partial=0){
if(any(is.na(partial))) return()
s = sum(partial)
if(s == target) print(sprintf("sum(%s)=%s",paste(partial[-1],collapse="+"),target))
if(s > target) return()
for( i in seq_along(numbers)){
n = numbers[i]
remaining = numbers[(i+1):length(numbers)]
subset_sum(remaining,target,c(partial,n))
}
}
If you happen to be a Vim user, you could try bash's vim mode. Run this or put it in your ~/.bashrc
file:
set -o vi
By default you're in insert mode; hit escape and you can move around just like you can in normal-mode Vim, so movement by word is w
or b
, and the usual movement keys also work.
Use DateTime.TryParseExact()
if you want to match against a specific date format
string format = "ddd dd MMM h:mm tt yyyy";
DateTime dateTime;
if (DateTime.TryParseExact(dateString, format, CultureInfo.InvariantCulture,
DateTimeStyles.None, out dateTime))
{
Console.WriteLine(dateTime);
}
else
{
Console.WriteLine("Not a date");
}
You can Hide/Show Div using Js function. sample below
<script>
function showDivAttid(){
if(Your Condition)
{
document.getElementById("attid").style.display = 'inline';
}
else
{
document.getElementById("attid").style.display = 'none';
}
}
</script>
HTML - Show/Hide this text
For your question as asked
Columns(3).Insert
Range("c1:c4") = Application.Transpose(Array("Loc", "uk", "us", "nj"))
If you had a way of automatically looking up the data (ie matching uk against employer id) then you could do that in VBA
setSize
will resize the component to the specified size.
setPreferredSize
sets the preferred size. The component may not actually be this size depending on the size of the container it's in, or if the user re-sized the component manually.
Of course!
Use FirstOrDefault()
to select the first object which matches the condition:
Answer answer = Answers.FirstOrDefault(a => a.Correct);
Otherwise use Where()
to select a subset of your list:
var answers = Answers.Where(a => a.Correct);
Use
num = num.toFixed(2);
Where 2 is the number of decimal places
Edit:
Here's the function to format number as you want
function formatNumber(number)
{
number = number.toFixed(2) + '';
x = number.split('.');
x1 = x[0];
x2 = x.length > 1 ? '.' + x[1] : '';
var rgx = /(\d+)(\d{3})/;
while (rgx.test(x1)) {
x1 = x1.replace(rgx, '$1' + ',' + '$2');
}
return x1 + x2;
}
Sorce: www.mredkj.com
It is true that a typical IPv4 header is 20 bytes, and the UDP header is 8 bytes. However it is possible to include IP options which can increase the size of the IP header to as much as 60 bytes. In addition, sometimes it is necessary for intermediate nodes to encapsulate datagrams inside of another protocol such as IPsec (used for VPNs and the like) in order to route the packet to its destination. So if you do not know the MTU on your particular network path, it is best to leave a reasonable margin for other header information that you may not have anticipated. A 512-byte UDP payload is generally considered to do that, although even that does not leave quite enough space for a maximum size IP header.
Please change only the name of the function; no other change is required
<script>
function totalbandwidthresult() {
alert("fdf");
var fps = Number(document.calculator.fps.value);
var bitrate = Number(document.calculator.bitrate.value);
var numberofcameras = Number(document.calculator.numberofcameras.value);
var encoding = document.calculator.encoding.value;
if (encoding = "mjpeg") {
storage = bitrate * fps;
} else {
storage = bitrate;
}
totalbandwidth = (numberofcameras * storage) / 1000;
alert(totalbandwidth);
document.calculator.totalbandwidthresult.value = totalbandwidth;
}
</script>
<form name="calculator" class="formtable">
<div class="formrow">
<label for="rcname">RC Name</label>
<input type="text" name="rcname">
</div>
<div class="formrow">
<label for="fps">FPS</label>
<input type="text" name="fps">
</div>
<div class="formrow">
<label for="bitrate">Bitrate</label>
<input type="text" name="bitrate">
</div>
<div class="formrow">
<label for="numberofcameras">Number of Cameras</label>
<input type="text" name="numberofcameras">
</div>
<div class="formrow">
<label for="encoding">Encoding</label>
<select name="encoding" id="encodingoptions">
<option value="h264">H.264</option>
<option value="mjpeg">MJPEG</option>
<option value="mpeg4">MPEG4</option>
</select>
</div>Total Storage:
<input type="text" name="totalstorage">Total Bandwidth:
<input type="text" name="totalbandwidth">
<input type="button" value="totalbandwidthresult" onclick="totalbandwidthresult();">
</form>
The correct solution is to add the timezone info e.g., to get the current time as an aware datetime object in Python 3:
from datetime import datetime, timezone
now = datetime.now(timezone.utc)
On older Python versions, you could define the utc
tzinfo object yourself (example from datetime docs):
from datetime import tzinfo, timedelta, datetime
ZERO = timedelta(0)
class UTC(tzinfo):
def utcoffset(self, dt):
return ZERO
def tzname(self, dt):
return "UTC"
def dst(self, dt):
return ZERO
utc = UTC()
then:
now = datetime.now(utc)
I simply use the -subj
parameter adding the machines ip address. So solved with one command only.
sudo openssl req -x509 -nodes -days 3650 -newkey rsa:2048 -sha256 -subj '/CN=my-domain.com/subjectAltName=DNS.1=192.168.0.222/' -keyout my-domain.key -out my-domain.crt
You can add others attributes like C, ST, L, O, OU, emailAddress to generate certs without being prompted.
While a lot of the above answers give ways to embed an image using a file or with Python code, there is a way to embed an image in the jupyter notebook itself using only markdown and base64!
To view an image in the browser, you can visit the link data:image/png;base64,**image data here**
for a base64-encoded PNG image, or data:image/jpg;base64,**image data here**
for a base64-encoded JPG image. An example link can be found at the end of this answer.
To embed this into a markdown page, simply use a similar construct as the file answers, but with a base64 link instead: ![**description**](data:image/**type**;base64,**base64 data**)
. Now your image is 100% embedded into your Jupyter Notebook file!
Example link: data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAoAAAAKCAYAAACNMs+9AAAABHNCSVQICAgIfAhkiAAAAD9JREFUGJW1jzEOADAIAqHx/1+mE4ltNXEpI3eJQknCIGsiHSLJB+aO/06PxOo/x2wBgKR2jCeEy0rOO6MDdzYQJRcVkl1NggAAAABJRU5ErkJggg==
Example markdown:
![smile](data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAoAAAAKCAYAAACNMs+9AAAABHNCSVQICAgIfAhkiAAAAD9JREFUGJW1jzEOADAIAqHx/1+mE4ltNXEpI3eJQknCIGsiHSLJB+aO/06PxOo/x2wBgKR2jCeEy0rOO6MDdzYQJRcVkl1NggAAAABJRU5ErkJggg==)
I just noticed that this question is quite old. Nevertheless, I consider the following aspects to be worth adding:
Use MongoDB if you don't know yet how you're going to query your data.
MongoDB is suited for Hackathons, startups or every time you don't know how you'll query the data you inserted. MongoDB does not make any assumptions on your underlying schema. While MongoDB is schemaless and non-relational, this does not mean that there is no schema at all. It simply means that your schema needs to be defined in your app (e.g. using Mongoose). Besides that, MongoDB is great for prototyping or trying things out. Its performance is not that great and can't be compared to Redis.
Use Redis in order to speed up your existing application.
Redis can be easily integrated as a LRU cache. It is very uncommon to use Redis as a standalone database system (some people prefer referring to it as a "key-value"-store). Websites like Craigslist use Redis next to their primary database. Antirez (developer of Redis) demonstrated using Lamernews that it is indeed possible to use Redis as a stand alone database system.
Redis does not make any assumptions based on your data.
Redis provides a bunch of useful data structures (e.g. Sets, Hashes, Lists), but you have to explicitly define how you want to store you data. To put it in a nutshell, Redis and MongoDB can be used in order to achieve similar things. Redis is simply faster, but not suited for prototyping. That's one use case where you would typically prefer MongoDB. Besides that, Redis is really flexible. The underlying data structures it provides are the building blocks of high-performance DB systems.
Caching
Caching using MongoDB simply doesn't make a lot of sense. It would be too slow.
If you have enough time to think about your DB design.
You can't simply throw in your documents into Redis. You have to think of the way you in which you want to store and organize your data. One example are hashes in Redis. They are quite different from "traditional", nested objects, which means you'll have to rethink the way you store nested documents. One solution would be to store a reference inside the hash to another hash (something like key: [id of second hash]). Another idea would be to store it as JSON, which seems counter-intuitive to most people with a *SQL-background.
If you need really high performance.
Beating the performance Redis provides is nearly impossible. Imagine you database being as fast as your cache. That's what it feels like using Redis as a real database.
If you don't care that much about scaling.
Scaling Redis is not as hard as it used to be. For instance, you could use a kind of proxy server in order to distribute the data among multiple Redis instances. Master-slave replication is not that complicated, but distributing you keys among multiple Redis-instances needs to be done on the application site (e.g. using a hash-function, Modulo etc.). Scaling MongoDB by comparison is much simpler.
Prototyping, Startups, Hackathons
MongoDB is perfectly suited for rapid prototyping. Nevertheless, performance isn't that good. Also keep in mind that you'll most likely have to define some sort of schema in your application.
When you need to change your schema quickly.
Because there is no schema! Altering tables in traditional, relational DBMS is painfully expensive and slow. MongoDB solves this problem by not making a lot of assumptions on your underlying data. Nevertheless, it tries to optimize as far as possible without requiring you to define a schema.
TL;DR - Use Redis if performance is important and you are willing to spend time optimizing and organizing your data. - Use MongoDB if you need to build a prototype without worrying too much about your DB.
Further reading:
To achieve this use following html:
<a href="www.mysite.com" onclick="make(event)">Item</a>
<script>
function make(e) {
// ... your function code
// e.preventDefault(); // use this to NOT go to href site
}
</script>
Here is working example.
you can use
getElementsByClassName
suppose you have some elements and applied a class name 'test', so, you can get elements like as following
var tests = document.getElementsByClassName('test');
its returns an instance NodeList
, or its superset: HTMLCollection
(FF).
In general, when you need a character that is "special" in regexes, just prefix it with a \
. So a literal [
would be \[
.
Check you index.html
file. If you use external resources, that not available when you run application then you can get this error.
In my case I forgot to delete link on debugger script (weinre).
<script src="http://192.168.0.102:8080/target/target-script-min.js#anonymous"></script>
So application worked on emulator because http://192.168.0.102:8080/
was on my localhost and available for emulator.
But when I setup application on mobile phone I had same error, because 192.168.0.102 was not available from mobile network.
You can find a good explanation of why it was replaced by reading A name for the null pointer: nullptr, to quote the paper:
This problem falls into the following categories:
Improve support for library building, by providing a way for users to write less ambiguous code, so that over time library writers will not need to worry about overloading on integral and pointer types.
Improve support for generic programming, by making it easier to express both integer 0 and nullptr unambiguously.
Make C++ easier to teach and learn.
The functionality to name returned aggregate columns has been reintroduced in the master branch and is targeted for pandas 0.25. The new syntax is .agg(new_col_name=('col_name', 'agg_func')
. Detailed example from the PR linked above:
In [2]: df = pd.DataFrame({'kind': ['cat', 'dog', 'cat', 'dog'],
...: 'height': [9.1, 6.0, 9.5, 34.0],
...: 'weight': [7.9, 7.5, 9.9, 198.0]})
...:
In [3]: df
Out[3]:
kind height weight
0 cat 9.1 7.9
1 dog 6.0 7.5
2 cat 9.5 9.9
3 dog 34.0 198.0
In [4]: df.groupby('kind').agg(min_height=('height', 'min'),
max_weight=('weight', 'max'))
Out[4]:
min_height max_weight
kind
cat 9.1 9.9
dog 6.0 198.0
It will also be possible to use multiple lambda expressions with this syntax and the two-step rename syntax I suggested earlier (below) as per this PR. Again, copying from the example in the PR:
In [2]: df = pd.DataFrame({"A": ['a', 'a'], 'B': [1, 2], 'C': [3, 4]})
In [3]: df.groupby("A").agg({'B': [lambda x: 0, lambda x: 1]})
Out[3]:
B
<lambda> <lambda 1>
A
a 0 1
and then .rename()
, or in one go:
In [4]: df.groupby("A").agg(b=('B', lambda x: 0), c=('B', lambda x: 1))
Out[4]:
b c
A
a 0 0
The currently accepted answer by unutbu describes are great way of doing this in pandas versions <= 0.20. However, as of pandas 0.20, using this method raises a warning indicating that the syntax will not be available in future versions of pandas.
Series:
FutureWarning: using a dict on a Series for aggregation is deprecated and will be removed in a future version
DataFrames:
FutureWarning: using a dict with renaming is deprecated and will be removed in a future version
According to the pandas 0.20 changelog, the recommended way of renaming columns while aggregating is as follows.
# Create a sample data frame
df = pd.DataFrame({'A': [1, 1, 1, 2, 2],
'B': range(5),
'C': range(5)})
# ==== SINGLE COLUMN (SERIES) ====
# Syntax soon to be deprecated
df.groupby('A').B.agg({'foo': 'count'})
# Recommended replacement syntax
df.groupby('A').B.agg(['count']).rename(columns={'count': 'foo'})
# ==== MULTI COLUMN ====
# Syntax soon to be deprecated
df.groupby('A').agg({'B': {'foo': 'sum'}, 'C': {'bar': 'min'}})
# Recommended replacement syntax
df.groupby('A').agg({'B': 'sum', 'C': 'min'}).rename(columns={'B': 'foo', 'C': 'bar'})
# As the recommended syntax is more verbose, parentheses can
# be used to introduce line breaks and increase readability
(df.groupby('A')
.agg({'B': 'sum', 'C': 'min'})
.rename(columns={'B': 'foo', 'C': 'bar'})
)
Please see the 0.20 changelog for additional details.
With the old style dictionary syntax, it was possible to pass multiple lambda
functions to .agg
, since these would be renamed with the key in the passed dictionary:
>>> df.groupby('A').agg({'B': {'min': lambda x: x.min(), 'max': lambda x: x.max()}})
B
max min
A
1 2 0
2 4 3
Multiple functions can also be passed to a single column as a list:
>>> df.groupby('A').agg({'B': [np.min, np.max]})
B
amin amax
A
1 0 2
2 3 4
However, this does not work with lambda functions, since they are anonymous and all return <lambda>
, which causes a name collision:
>>> df.groupby('A').agg({'B': [lambda x: x.min(), lambda x: x.max]})
SpecificationError: Function names must be unique, found multiple named <lambda>
To avoid the SpecificationError
, named functions can be defined a priori instead of using lambda
. Suitable function names also avoid calling .rename
on the data frame afterwards. These functions can be passed with the same list syntax as above:
>>> def my_min(x):
>>> return x.min()
>>> def my_max(x):
>>> return x.max()
>>> df.groupby('A').agg({'B': [my_min, my_max]})
B
my_min my_max
A
1 0 2
2 3 4
// suppose that we have a test.txt at E:\
string filePath = @"E:\test.txt";
if (!File.Exists(filePath))
{
return;
}
// combine the arguments together
// it doesn't matter if there is a space after ','
string argument = "/select, \"" + filePath +"\"";
System.Diagnostics.Process.Start("explorer.exe", argument);
You can use XMLHttpRequest, fetch API, ...
If you want to use XMLHttpRequest you can do the following
var xhr = new XMLHttpRequest();
xhr.open("POST", url, true);
xhr.setRequestHeader('Content-Type', 'application/json');
xhr.send(JSON.stringify({
name: "Deska",
email: "[email protected]",
phone: "342234553"
}));
xhr.onload = function() {
var data = JSON.parse(this.responseText);
console.log(data);
};
Or if you want to use fetch API
fetch(url, {
method:"POST",
body: JSON.stringify({
name: "Deska",
email: "[email protected]",
phone: "342234553"
})
})
.then(result => {
// do something with the result
console.log("Completed with result:", result);
});
This is one of the most easily found question on the topic, so I wanted to give a modern answer to the it (both for my reference and to help others out). By using first_value
and over
you can make short work of the above query:
Select distinct DocumentID
, first_value(status) over (partition by DocumentID order by DateCreated Desc) as Status
, first_value(DateCreated) over (partition by DocumentID order by DateCreated Desc) as DateCreated
From DocumentStatusLogs
This should work in Sql Server 2008 and up. First_value
can be thought of as a way to accomplish Select Top 1
when using an over
clause. Over
allows grouping in the select list so instead of writing nested subqueries (like many of the existing answers do), this does it in a more readable fashion. Hope this helps.
Also, you can use the "sql" parameter as a format specifier:
context.Database.SqlQuery<MyEntityType>("mySpName @param1 = {0}", param1)
You can use facebook javascript sdk. First add FB Js SDK to your code (please refer to https://developers.facebook.com/docs/javascript)
window.fbAsyncInit = function(){
FB.init({
appId: 'xxxxx', status: true, cookie: true, xfbml: true });
};
(function(d, debug){var js, id = 'facebook-jssdk', ref = d.getElementsByTagName('script')[0];
if(d.getElementById(id)) {return;}
js = d.createElement('script'); js.id = id;
js.async = true;js.src = "//connect.facebook.net/en_US/all" + (debug ? "/debug" : "") + ".js";
ref.parentNode.insertBefore(js, ref);}(document, /*debug*/ false));
function postToFeed(title, desc, url, image){
var obj = {method: 'feed',link: url, picture: 'http://www.url.com/images/'+image,name: title,description: desc};
function callback(response){}
FB.ui(obj, callback);
}
So when you want to share something
<a href="someurl.com/some-article" data-image="article-1.jpg" data-title="Article Title" data-desc="Some description for this article" class="btnShare">Share</a>
And finally JS to handle click:
$('.btnShare').click(function(){
elem = $(this);
postToFeed(elem.data('title'), elem.data('desc'), elem.prop('href'), elem.data('image'));
return false;
});
As the documentation says, a Vector
and an ArrayList
are almost equivalent. The difference is that access to a Vector
is synchronized, whereas access to an ArrayList
is not. What this means is that only one thread can call methods on a Vector
at a time, and there's a slight overhead in acquiring the lock; if you use an ArrayList
, this isn't the case. Generally, you'll want to use an ArrayList
; in the single-threaded case it's a better choice, and in the multi-threaded case, you get better control over locking. Want to allow concurrent reads? Fine. Want to perform one synchronization for a batch of ten writes? Also fine. It does require a little more care on your end, but it's likely what you want. Also note that if you have an ArrayList, you can use the Collections.synchronizedList
function to create a synchronized list, thus getting you the equivalent of a Vector
.
Have you tried using the stream_context_set_option()
method ?
$context = stream_context_create();
$result = stream_context_set_option($context, 'ssl', 'local_cert', '/etc/ssl/certs/cacert.pem');
$fp = fsockopen($host, $port, $errno, $errstr, 20, $context);
In addition, try file_get_contents()
for the pem file, to make sure you have permissions to access it, and make sure the host name matches the certificate.
I'm always using this syntax at the very top of the php script.
ini_set('error_reporting', E_ALL);
ini_set('display_errors', 'On'); //On or Off
You can do it:
var str = "Doctor Who,Fantasy,Steven Moffat,David Tennant";
var title = str.Split(',').First();
Also you can do it this way:
var index = str.IndexOf(",");
var title = index < 0 ? str : str.Substring(0, index);
You need execute permission on your static files directory. Also they need to be chown'ed by your nginx user and group.
On saveAndFlush
, changes will be flushed to DB immediately in this command. With save
, this is not necessarily true, and might stay just in memory, until flush
or commit
commands are issued.
But be aware, that even if you flush the changes in transaction and do not commit them, the changes still won't be visible to the outside transactions until the commit in this transaction.
In your case, you probably use some sort of transactions mechanism, which issues commit
command for you if everything works out fine.
Dim sHostName As String
' Get Host Name / Get Computer Name
sHostName = Environ$("computername")
I used the RowHeight
property of a range (which means cells as well). If it's zero then it's hidden.
So just loop through all rows as you would normally but in the if
condition check for that property as in If myRange.RowHeight > 0 then DoStuff
where DoStuff
is something you want to do with the visible cells.
open node.js command prompt
run this command
node -v
This was my solution (using .net core 3.1, in an api controller):
string baseUrl = $"{Request.Scheme}://{Request.Headers.Where(h => h.Key == "Host").First().Value}";
I solved this in a somewhat different way. Here's what happened.
First, I popped on the wrong branch and got conflicts. The stash remained intact but the index was in conflict resolution, blocking many commands.
A simple git reset HEAD
aborted the conflict resolution and left the uncommitted (and UNWANTED) changes.
Several git co <filename>
reverted the index to the initial state. Finally, I switched branch with git co <branch-name>
and run a new git stash pop
, which resolved without conflicts.
For Oracle versions which does not support the WM_CONCAT, the following can be used
select "User", RTRIM(
XMLAGG (XMLELEMENT(e, department||',') ORDER BY department).EXTRACT('//text()') , ','
) AS departments
from yourtable
group by "User"
This one is much more powerful and flexible - you can specify both delimiters and sort order within each group as in listagg.
You first have to tell Gnuplot to use a style that uses points, e.g. with points
or with linespoints
. Try for example:
plot sin(x) with points
Output:
Now try:
plot sin(x) with points pointtype 5
Output:
You may also want to look at the output from the test
command which shows you the capabilities of the current terminal. Here are the capabilities for my pngairo terminal:
<?php
$xml = $argv[1];
$dom = new DOMDocument();
// Initial block (must before load xml string)
$dom->preserveWhiteSpace = false;
$dom->formatOutput = true;
// End initial block
$dom->loadXML($xml);
$out = $dom->saveXML();
print_R($out);
You can use something like this: Arrays#copyOfRange
I was having similar problems loading 3D models from S3 into a javascript 3D viewer (3D HOP), but strangely enough only with certain file types (.nxs).
What fixed it for me was changing AllowedHeader
from the default Authorization
to *
in the CORS config:
<?xml version="1.0" encoding="UTF-8"?>
<CORSConfiguration xmlns="http://s3.amazonaws.com/doc/2006-03-01/">
<CORSRule>
<AllowedOrigin>*</AllowedOrigin>
<AllowedMethod>GET</AllowedMethod>
<MaxAgeSeconds>3000</MaxAgeSeconds>
<AllowedHeader>*</AllowedHeader>
</CORSRule>
</CORSConfiguration>
var https = require('https');
https.globalAgent.options.secureProtocol = 'SSLv3_method';
I consider state to be for view only information and data that should persist beyond the view state is better stored as props. URL params are useful when you want to be able to link to a page or share the URL deep in to the app but otherwise clutter the address bar.
Take a look at Redux-Persist (if you're using redux) https://github.com/rt2zz/redux-persist
You should use something like this:
<div style="text-align:center">
<input type="submit" />
</div>
Or you could use something like this. By giving the element a width and specifying auto
for the left and right margins the element will center itself in its parent.
<input type="submit" style="width: 300px; margin: 0 auto;" />
If you want to flat nested dictionary and want all unique keys list then here is the solution:
def flat_dict_return_unique_key(data, unique_keys=set()):
if isinstance(data, dict):
[unique_keys.add(i) for i in data.keys()]
for each_v in data.values():
if isinstance(each_v, dict):
flat_dict_return_unique_key(each_v, unique_keys)
return list(set(unique_keys))
Use border-collapse and border-spacing to get spaces between the table cells. I would not recommend using floating cells as suggested by QQping.
Found a solution:
SWIFT_OBJC_BRIDGING_HEADER
) must be set at the Target level, and NOT the Project level. Be sure to delete the setting value at the Project level.(to me, it seems like an Xcode bug, since I don't know why it fixes it).
I forced to use a proxy and also forced to add proxy setting on gradle.properties as these:
systemProp.http.proxyHost=127.0.0.1
systemProp.http.proxyPort=1080
systemProp.https.proxyHost=127.0.0.1
systemProp.https.proxyPort=1080
And also forced to close and open studio64.exe
as administrator .
Now its all seems greate
Event log says
8:21:39 AM Platform and Plugin Updates: The following components are ready to update: Android Support Repository, Google Repository, Intel x86 Emulator Accelerator (HAXM installer), Android SDK Platform-Tools 24, Google APIs Intel x86 Atom System Image, Android SDK Tools 25.1.7
8:21:40 AM Gradle sync started
8:22:03 AM Gradle sync completed
8:22:04 AM Executing tasks: [:app:generateDebugSources, :app:generateDebugAndroidTestSources, :app:prepareDebugUnitTestDependencies, :app:mockableAndroidJar]
8:22:25 AM Gradle build finished in 21s 607ms
I'm using android studio 2.1.2 downloaded as exe setup file. it has its Gradle ( I also forced to use custom install to address the Gradle )
The integer passed to the constructor represents its initial capacity, i.e., the number of elements it can hold before it needs to resize its internal array (and has nothing to do with the initial number of elements in the list).
To initialize an list with 60 zeros you do:
List<Integer> list = new ArrayList<Integer>(Collections.nCopies(60, 0));
If you want to create a list with 60 different objects, you could use the Stream API with a Supplier
as follows:
List<Person> persons = Stream.generate(Person::new)
.limit(60)
.collect(Collectors.toList());
You will need to have root access to do this. If you aren't already the administrative user, login as the administrator. Then use 'sudo' to change the permissions:
sudo chmod go-w /usr/local/bin
Obviously, that will mean you can no longer install material in /usr/local/bin except via 'sudo', but you probably shouldn't be doing that anyway.
if(stop == true)
or
if(stop)
= is for assignment.
== is for checking condition.
if(stop = true)
It will assign true to stop and evaluates if(true). So it will always execute the code inside if because stop will always being assigned with true.
Solution in python, based on @Joe Skeen
def check_line_segment_circle_intersection(line, point, radious):
""" Checks whether a point intersects with a line defined by two points.
A `point` is list with two values: [2, 3]
A `line` is list with two points: [point1, point2]
"""
line_distance = distance(line[0], line[1])
distance_start_to_point = distance(line[0], point)
distance_end_to_point = distance(line[1], point)
if (distance_start_to_point <= radious or distance_end_to_point <= radious):
return True
# angle between line and point with law of cosines
numerator = (math.pow(distance_start_to_point, 2)
+ math.pow(line_distance, 2)
- math.pow(distance_end_to_point, 2))
denominator = 2 * distance_start_to_point * line_distance
ratio = numerator / denominator
ratio = ratio if ratio <= 1 else 1 # To account for float errors
ratio = ratio if ratio >= -1 else -1 # To account for float errors
angle = math.acos(ratio)
# distance from the point to the line with sin projection
distance_line_to_point = math.sin(angle) * distance_start_to_point
if distance_line_to_point <= radious:
point_projection_in_line = math.cos(angle) * distance_start_to_point
# Intersection occurs whent the point projection in the line is less
# than the line distance and positive
return point_projection_in_line <= line_distance and point_projection_in_line >= 0
return False
def distance(point1, point2):
return math.sqrt(
math.pow(point1[1] - point2[1], 2) +
math.pow(point1[0] - point2[0], 2)
)
the repr
function will return a string which is the exact definition of your dict (except for the order of the element, dicts are unordered in python). unfortunately, i can't tell a way to automatically get a string which represent the variable name.
>>> dict = {'one': 1, 'two': 2}
>>> repr(dict)
"{'two': 2, 'one': 1}"
writing to a file is pretty standard stuff, like any other file write:
f = open( 'file.py', 'w' )
f.write( 'dict = ' + repr(dict) + '\n' )
f.close()
You can reproduce the error by running:
Directory.CreateDirectory(@"C:\Temp\a\b\c\");
Process.Start(@"C:\Temp\a\b\c\");
Thread.Sleep(1000);
Directory.Delete(@"C:\Temp\a\b\c");
Directory.Delete(@"C:\Temp\a\b");
Directory.Delete(@"C:\Temp\a");
When trying to delete directory 'b', it throws the IOException "The directory is not empty". That's stupid since we just deleted the directory 'c'.
From my understanding, the explanation is that directory 'c' is stamped as deleted. But the delete is not yet commited in the system. The system has reply the job is done, while in fact, it is still processing. The system probably wait the file explorer has focus on the parent directory to commit the delete.
If you look on the source code of the Delete function (http://referencesource.microsoft.com/#mscorlib/system/io/directory.cs) you will see it uses the native Win32Native.RemoveDirectory function. This do-not-wait behavior is noted here :
The RemoveDirectory function marks a directory for deletion on close. Therefore, the directory is not removed until the last handle to the directory is closed.
(http://msdn.microsoft.com/en-us/library/windows/desktop/aa365488(v=vs.85).aspx)
Sleep and retry is the solution. Cf the ryascl's solution.
You Should uninstall the existed python,then download new version.
I use codeignator and I got the error:
Object of class stdClass could not be converted to string.
for this post I get my result
I use in my model section
$query = $this->db->get('user', 10);
return $query->result();
and from this post I use
$query = $this->db->get('user', 10);
return $query->row();
and I solved my problem
This issue has been discussed in https://github.com/twbs/bootstrap/issues/10203 By now, there is no plan to change Grid because compatibility reasons.
You can get Bootstrap from this fork, branch hs
: https://github.com/antespi/bootstrap/tree/hs
This branch give you an extra breakpoint at 480px, so yo have to:
Design mobile first is the key to understand Bootstrap 3. This is the major change from BootStrap 2.x. As a rule template you can follow this (in LESS):
.template {
/* rules for mobile vertical (< 480) */
@media (min-width: @screen-hs-min) {
/* rules for mobile horizontal (480 > 768) */
}
@media (min-width: @screen-sm-min) {
/* rules for tablet (768 > 992) */
}
@media (min-width: @screen-md-min) {
/* rules for desktop (992 > 1200) */
}
@media (min-width: @screen-lg-min) {
/* rules for large (> 1200) */
}
}
You can use 2 methods from the String
class.
String.contains()
which checks if the string contains a specified sequence of char valuesString.indexOf()
which returns the index within the string of the first occurence of the specified character or substring or returns -1 if the character is not found (there are 4 variations of this method)Method 1:
String myString = "foobar";
if (myString.contains("x") {
// Do something.
}
Method 2:
String myString = "foobar";
if (myString.indexOf("x") >= 0 {
// Do something.
}
Links by: Zach Scrivena
I think this is the culprit:
cmd = new SqlCommand(query, con);
DataTable dt = Select(query);
cmd.ExecuteNonQuery();
ddtype.DataSource = dt;
I don't know what that code is supposed to do, but it looks like you want to create an SqlDataReader
for that, as explained here and all over the web if you search for "SqlCommand DropDownList DataSource":
cmd = new SqlCommand(query, con);
ddtype.DataSource = cmd.ExecuteReader();
Or you can create a DataTable
as explained here:
cmd = new SqlCommand(query, con);
SqlDataAdapter listQueryAdapter = new SqlDataAdapter(cmd);
DataTable listTable = new DataTable();
listQueryAdapter.Fill(listTable);
ddtype.DataSource = listTable;
To get the bottom 1000 you will want to order it by a column in descending order, and still take the top 1000.
SELECT TOP 1000 *
FROM [SomeTable]
ORDER BY MySortColumn DESC
If you care for it to be in the same order as before you can use a common table expression for that:
;WITH CTE AS (
SELECT TOP 1000 *
FROM [SomeTable]
ORDER BY MySortColumn DESC
)
SELECT *
FROM CTE
ORDER BY MySortColumn
If you don't want any button at all (e.g. you are developing a GUI for blind people where tap cannot be positional and you rely on single/double/long taps):
text.setItemOptions(EditorInfo.IME_ACTION_NONE)
Or in Kotlin:
text.imeOptions = EditorInfo.IME_ACTION_NONE
.m2/repository
mvn clean verify
) from the terminal at the current project location(where your project's pom.xml file exist) instead of running maven from eclipse.I set the opacity to 0. This made it disappear but still function when you click on it.
I was able to get creation time on posix by running the system's stat command and parsing the output.
commands.getoutput('stat FILENAME').split('\"')[7]
Running stat outside of python from Terminal (OS X) returned:
805306374 3382786932 -rwx------ 1 km staff 0 1098083 "Aug 29 12:02:05 2013" "Aug 29 12:02:05 2013" "Aug 29 12:02:20 2013" "Aug 27 12:35:28 2013" 61440 2150 0 testfile.txt
... where the fourth datetime is the file creation (rather than ctime change time as other comments noted).
I think the performance will be quite similar. The overhead that is involved when using a List vs an Array is, IMHO when you add items to the list, and when the list has to increase the size of the array that it's using internally, when the capacity of the array is reached.
Suppose you have a List with a Capacity of 10, then the List will increase it's capacity once you want to add the 11th element. You can decrease the performance impact by initializing the Capacity of the list to the number of items it will hold.
But, in order to figure out if iterating over a List is as fast as iterating over an array, why don't you benchmark it ?
int numberOfElements = 6000000;
List<int> theList = new List<int> (numberOfElements);
int[] theArray = new int[numberOfElements];
for( int i = 0; i < numberOfElements; i++ )
{
theList.Add (i);
theArray[i] = i;
}
Stopwatch chrono = new Stopwatch ();
chrono.Start ();
int j;
for( int i = 0; i < numberOfElements; i++ )
{
j = theList[i];
}
chrono.Stop ();
Console.WriteLine (String.Format("iterating the List took {0} msec", chrono.ElapsedMilliseconds));
chrono.Reset();
chrono.Start();
for( int i = 0; i < numberOfElements; i++ )
{
j = theArray[i];
}
chrono.Stop ();
Console.WriteLine (String.Format("iterating the array took {0} msec", chrono.ElapsedMilliseconds));
Console.ReadLine();
On my system; iterating over the array took 33msec; iterating over the list took 66msec.
To be honest, I didn't expect that the variation would be that much. So, I've put my iteration in a loop: now, I execute both iteration 1000 times. The results are:
iterating the List took 67146 msec iterating the array took 40821 msec
Now, the variation is not that large anymore, but still ...
Therefore, I've started up .NET Reflector, and the getter of the indexer of the List class, looks like this:
public T get_Item(int index)
{
if (index >= this._size)
{
ThrowHelper.ThrowArgumentOutOfRangeException();
}
return this._items[index];
}
As you can see, when you use the indexer of the List, the List performs a check whether you're not going out of the bounds of the internal array. This additional check comes with a cost.
By convention, .h files are included by other files, and never compiled directly by themselves. .cpp files are - again, by convention - the roots of the compilation process; they include .h files directly or indirectly, but generally not .cpp files.
"ViewModel" implies MVVM. If you're doing MVVM you shouldn't be passing views into your view models. Typically you do something like this in your XAML:
<Button Content="Edit"
Command="{Binding EditCommand}"
CommandParameter="{Binding ViewModelItem}" >
And then this in your view model:
private ViewModelItemType _ViewModelItem;
public ViewModelItemType ViewModelItem
{
get
{
return this._ViewModelItem;
}
set
{
this._ViewModelItem = value;
RaisePropertyChanged(() => this.ViewModelItem);
}
}
public ICommand EditCommand { get { return new RelayCommand<ViewModelItemType>(OnEdit); } }
private void OnEdit(ViewModelItemType itemToEdit)
{
... do something here...
}
Obviously this is just to illustrate the point, if you only had one property to edit called ViewModelItem then you wouldn't need to pass it in as a command parameter.
JQuery uses CSS selectors to select elements, so you just need to use more than one rule by separating them with commas, as so:
a=$('[myc="blue"], [myid="1"], [myid="3"]');
Edit:
Sorry, you wanted blue and 1 or 3. How about:
a=$('[myc="blue"][myid="1"], [myid="3"]');
Putting the two attribute selectors together gives you AND, using a comma gives you OR.
I think you are looking for this
git reset --soft HEAD~1
It undoes the most recent commit whilst keeping the changes made in that commit to staging.
Simple:
var removedText = self.val().replace(/[^0-9]+/, '');
^ - means NOT
The simplest solution simply is:
<a href="#" onclick="event.preventDefault(); myfunc({a:1, b:'hi'});" />click</a>
It's actually a good way of doing cache busting for documents with a fallback for no JS enabled browsers (no cache busting if no JS)
<a onclick="
if(event.preventDefault) event.preventDefault(); else event.returnValue = false;
window.location = 'http://www.domain.com/docs/thingy.pdf?cachebuster=' +
Math.round(new Date().getTime() / 1000);"
href="http://www.domain.com/docs/thingy.pdf">
If JavaScript is enabled, it opens the PDF with a cache busting query string, if not it just opens the PDF.
Try in your console
conda install pandas
and see what's the message given.
If the path in Ubuntu is "/home/ec2-user/Name of Directory", then do this:
1) Java's build.properties file:
build_path='/home/ec2-user/Name\\ of\\ Directory'
Where ~/
is equal to /home/ec2-user
2) Jenkinsfile:
build_path=buildprops['build_path']
echo "Build path= ${build_path}"
sh "cd ${build_path}"
For anyone going through this error and you've tried updating versions and making sure effects core is present etc and still scratching your head. Check the documentation for animate() and other syntax.
All I did was write "Linear" instead of "linear" and got the [this.easing] is not a function
$("#main").animate({ scrollLeft: '187px'}, 'slow', 'Linear'); //bad
$("#main").animate({ scrollLeft: '187px'}, 'slow', 'linear'); //good
.Cells(.Rows.Count,"A").End(xlUp).row
I think the first dot in the parenthesis should not be there, I mean, you should write it in this way:
.Cells(Rows.Count,"A").End(xlUp).row
Before the Cells, you can write your worksheet name, for example:
Worksheets("sheet1").Cells(Rows.Count, 2).End(xlUp).row
The worksheet name is not necessary when you operate on the same worksheet.
I ran into this same issue and none of what I was seeing here was working. If you are listing your Component in the app-routing.module issue you may have run into the same problem I was having.
app.module.ts
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { HttpModule } from '@angular/http';
import { AppComponent } from './app.component';
import { NavbarComponent } from './navbar/navbar.component';
import { TopbarComponent } from './topbar/topbar.component';
import { FooterbarComponent } from './footerbar/footerbar.component';
import { MRDBGlobalConstants } from './shared/mrdb.global.constants';
import {AppRoutingModule} from './app.routing';
import {HomeModule} from './Home/home.module';
// import HomeComponent here
@NgModule({
declarations: [
AppComponent,
FooterbarComponent,
TopbarComponent,
NavbarComponent,
// add HomeComponent here
],
imports: [
BrowserModule,
HttpModule,
AppRoutingModule,
HomeModule // remove this
],
providers: [MRDBGlobalConstants],
bootstrap: [AppComponent]
})
export class AppModule { }
home/index.ts
export * from './';
app-routing.module.ts
import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import { HomeComponent } from './components';
const routes: Routes = [
{ path: 'app/home', component: HomeComponent },
{ path: '', redirectTo: 'app/home', pathMatch: 'full' },
{ path: '**', redirectTo: 'app/home' }
];
@NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule]
})
export class AppRoutingModule { }
home/home.module.ts
import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
// import { HomeComponent } from './home.component'; This would cause app to break
import { HomeComponent } from './';
@NgModule({
imports: [
CommonModule
],
exports: [HomeComponent],
declarations: [HomeComponent]
})
export class HomeModule { }
I won't claim to understand exactly why this is the case, but when using indexing to export components (and I would assume the same for services, etc.), when referencing the same component in separate modules you need to import them from the same file, in this case the index, in order to avoid this issue.
you shoud use <a href="javascript:void(0)" ></a>
instead of <a href="#" ></a>
Some generic help:
gdb start GDB, with no debugging les
gdb program begin debugging program
gdb program core debug coredump core produced by program
gdb --help describe command line options
First of all, find the directory where the corefile is generated.
Then use ls -ltr
command in the directory to find the latest generated corefile.
To load the corefile use
gdb binary path of corefile
This will load the corefile.
Then you can get the information using the bt
command.
For a detailed backtrace use bt full
.
To print the variables, use print variable-name
or p variable-name
To get any help on GDB, use the help
option or use apropos search-topic
Use frame frame-number
to go to the desired frame number.
Use up n
and down n
commands to select frame n frames up and select frame n frames down respectively.
To stop GDB, use quit
or q
.
If you are talking about browser javascript, you can not write data directly to local file for security reason. HTML 5 new API can only allow you to read files.
But if you want to write data, and enable user to download as a file to local. the following code works:
function download(strData, strFileName, strMimeType) {
var D = document,
A = arguments,
a = D.createElement("a"),
d = A[0],
n = A[1],
t = A[2] || "text/plain";
//build download link:
a.href = "data:" + strMimeType + "charset=utf-8," + escape(strData);
if (window.MSBlobBuilder) { // IE10
var bb = new MSBlobBuilder();
bb.append(strData);
return navigator.msSaveBlob(bb, strFileName);
} /* end if(window.MSBlobBuilder) */
if ('download' in a) { //FF20, CH19
a.setAttribute("download", n);
a.innerHTML = "downloading...";
D.body.appendChild(a);
setTimeout(function() {
var e = D.createEvent("MouseEvents");
e.initMouseEvent("click", true, false, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null);
a.dispatchEvent(e);
D.body.removeChild(a);
}, 66);
return true;
}; /* end if('download' in a) */
//do iframe dataURL download: (older W3)
var f = D.createElement("iframe");
D.body.appendChild(f);
f.src = "data:" + (A[2] ? A[2] : "application/octet-stream") + (window.btoa ? ";base64" : "") + "," + (window.btoa ? window.btoa : escape)(strData);
setTimeout(function() {
D.body.removeChild(f);
}, 333);
return true;
}
to use it:
download('the content of the file', 'filename.txt', 'text/plain');
@media print {
.footer,
#non-printable {
display: none !important;
}
#printable {
display: block;
}
}
It is possible to have hierarchical branch names (branch names with slash). For example in my repository I have such branch(es). One caveat is that you can't have both branch 'foo' and branch 'foo/bar' in repository.
Your problem is not with creating branch with slash in name.
$ git branch foo/bar error: unable to resolve reference refs/heads/labs/feature: Not a directory fatal: Failed to lock ref for update: Not a directory
The above error message talks about 'labs/feature' branch, not 'foo/bar' (unless it is a mistake in copy'n'paste, i.e you edited parts of session). What is the result of git branch
or git rev-parse --symbolic-full-name HEAD
?
Use date() function to get the desired date
<?php
// set default timezone
date_default_timezone_set('UTC');
//define date and time
$strtotime = 1307595105;
// output
echo date('d M Y H:i:s',$strtotime);
// more formats
echo date('c',$strtotime); // ISO 8601 format
echo date('r',$strtotime); // RFC 2822 format
?>
Recommended online tool for strtotime to date conversion:
It's pretty strange for FB not to be loaded in your javascript if you have the script tag there correctly. Check that you don't have any javascript blockers, ad blockers, tracking blockers etc installed in your browser that are neutralizing your FB Connect code.
yourtextView.setMovementMethod(new ScrollingMovementMethod());
you can scroll it now.
VARCHAR with probably 15-20 length would be sufficient and would be the best option for the database. Since you would probably require various hyphens and plus signs along with your phone numbers.
To remove a specific container
docker rm CONTAINER_ID CONTAINER_ID
For single image
docker rm 70c0e19168cf
For multiple images
docker rm 70c0e19168cf c2ce80b62174
Remove exited containers
docker ps -a -f status=exited
Remove all the containers
docker ps -q -a | xargs docker rm
docker rmi IMAGE_ID
Remove specific images
for single image
docker rmi ubuntu
for multiple images
docker rmi ubuntu alpine
Remove dangling images
Dangling images are layers that have no relationship to any tagged images as the Docker images are constituted of multiple images.
docker rmi -f $(docker images -f dangling=true -q)
Remove all Docker images
docker rmi -f $(docker images -a -q)
To list volumes, run docker volume ls
Remove a specific volume
docker volume rm VOLUME_NAME
Remove dangling volumes
docker volume rm $(docker volume ls -f dangling=true -q)
Remove a container and its volumes
docker rm -v CONTAINER_NAME
You can use the extension method AsEnumerable in Assembly System.Core and System.Linq namespace :
List<Book> list = new List<Book>();
return list.AsEnumerable();
This will, as said on this MSDN link change the type of the List in compile-time. This will give you the benefits also to only enumerate your collection we needed (see MSDN example for this).
The simple answer to your question is that there is no Annotation-Inheritance in Java. However, there is a way to use the Spring annotations in a way that I think will help solve your problem.
@RequestMapping is supported at both the type level and at the method level.
When you put @RequestMapping
at the type level, most of the attributes are 'inherited' for each method in that class. This is mentioned in the Spring reference documentation. Look at the api docs for details on how each attribute is handled when adding @RequestMapping
to a type. I've summarized this for each attribute below:
name
: Value at Type level is concatenated with value at method level using '#' as a separator.value
: Value at Type level is inherited by method.path
: Value at Type level is inherited by method.method
: Value at Type level is inherited by method.params
: Value at Type level is inherited by method.headers
: Value at Type level is inherited by method.consumes
: Value at Type level is overridden by method.produces
: Value at Type level is overridden by method.Here is a brief example Controller that showcases how you could use this:
package com.example;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
@RestController
@RequestMapping(path = "/",
consumes = MediaType.APPLICATION_JSON_VALUE,
produces = MediaType.APPLICATION_JSON_VALUE,
method = {RequestMethod.GET, RequestMethod.POST})
public class JsonProducingEndpoint {
private FooService fooService;
@RequestMapping(path = "/foo", method = RequestMethod.POST)
public String postAFoo(@RequestBody ThisIsAFoo theFoo) {
fooService.saveTheFoo(theFoo);
return "http://myservice.com/foo/1";
}
@RequestMapping(path = "/foo/{id}", method = RequestMethod.GET)
public ThisIsAFoo getAFoo(@PathVariable String id) {
ThisIsAFoo foo = fooService.getAFoo(id);
return foo;
}
@RequestMapping(path = "/foo/{id}", produces = MediaType.APPLICATION_XML_VALUE, method = RequestMethod.GET)
public ThisIsAFooXML getAFooXml(@PathVariable String id) {
ThisIsAFooXML foo = fooService.getAFoo(id);
return foo;
}
}
If you don't mind importing then fileinput does exactly what you need (this is you can read the line number of the current line)
I would say technically it might not be an HTTP failure, since the resource was (presumably) validly specified, the user was authenticated, and there was no operational failure (however even the spec does include some reserved codes like 402 Payment Required which aren't strictly speaking HTTP-related either, though it might be advisable to have that at the protocol level so that any device can recognize the condition).
If that's actually the case, I would add a status field to the response with application errors, like
<status><code>4</code><message>Date range is invalid</message></status>
You just use an ImageButton and make the background whatever you want and set the icon as the src.
<ImageButton
android:id="@+id/ImageButton01"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/album_icon"
android:background="@drawable/round_button" />
To prevent users from resizing, set the FormBoderStyle to Fixed3D or FixedDialog from properties window or from code
frmYour.BorderStyle = System.WinForms.FormBorderStyle.Fixed3D
And set the WindowState property to Maximized, set the MaximizeBox and MinimizeBox properties to false.
To prevent the user from moving around, override WndProc
Protected Overrides Sub WndProc(ByRef m As Message)
Const WM_NCLBUTTONDOWN As Integer = 161
Const WM_SYSCOMMAND As Integer = 274
Const HTCAPTION As Integer = 2
Const SC_MOVE As Integer = 61456
If (m.Msg = WM_SYSCOMMAND) And (m.WParam.ToInt32() = SC_MOVE) Then
Return
End If
If (m.Msg = WM_NCLBUTTONDOWN) And (m.WParam.ToInt32() = HTCAPTION) Then
Return
End If
MyBase.WndProc(m)
End Sub
Transform the data structure to a map if you frequently use this search
mapPersons: Map<number, Person>;
// prepare the map - call once or when person array change
populateMap() : void {
this.mapPersons = new Map();
for (let o of this.personService.getPersons()) this.mapPersons.set(o.id, o);
}
getPerson(id: number) : Person {
return this.mapPersons.get(id);
}
You can validate point a and b compactly by doing something like the following:
#!/bin/sh
MYVAL=$(echo ${1} | awk '/^[0-9]+$/')
MYVAL=${MYVAL:?"Usage - testparms <number>"}
echo ${MYVAL}
Which gives us ...
$ ./testparams.sh
Usage - testparms <number>
$ ./testparams.sh 1234
1234
$ ./testparams.sh abcd
Usage - testparms <number>
This method should work fine in sh.
$(document).ready(function() {
$('#div2').hide(0);
$('#preview').on('click', function() {
$('#div1').hide(300, function() { // first hide div1
// then show div2
$('#div2').show(300);
});
});
});
You missed #
before div2
A different approach, i.e: You could just do it 'the Angular way' and use ngModel
and skip document.getElementById('loginInput').value = '123';
altogether. Instead:
<input type="text" [(ngModel)]="username"/>
<input type="text" [(ngModel)]="password"/>
and in your component you give these values:
username: 'whatever'
password: 'whatever'
this will preset the username and password upon navigating to page.
This code will print a pyramid of dollars.
public static void main(String[] args) {
for(int i=0;i<5;i++) {
for(int j=0;j<5-i;j++) {
System.out.print(" ");
}
for(int k=0;k<=i;k++) {
System.out.print("$ ");
}
System.out.println();
}
}
OUPUT :
$
$ $
$ $ $
$ $ $ $
$ $ $ $ $
jsoup supports java 1.5
https://github.com/tburch/jsoup/commit/d8ea84f46e009a7f144ee414a9fa73ea187019a3
looks like that stack was a bug, and has been fixed
For those who rooted the Android device with Magisk, you can install adb_root from https://github.com/evdenis/adb_root. Then adb root
can run smoothly.
You can get around the "impedance mismatch" caused by the lack of precision in the DateTimeField/date
object comparison -- that can occur if using range -- by using a datetime.timedelta to add a day to last date in the range. This works like:
start = date(2012, 12, 11)
end = date(2012, 12, 18)
new_end = end + datetime.timedelta(days=1)
ExampleModel.objects.filter(some_datetime_field__range=[start, new_end])
As discussed previously, without doing something like this, records are ignored on the last day.
Edited to avoid the use of datetime.combine
-- seems more logical to stick with date instances when comparing against a DateTimeField
, instead of messing about with throwaway (and confusing) datetime
objects. See further explanation in comments below.
foo.bars.one.counter=1
foo.bars.one.active=false
foo.bars[two].id=IdOfBarWithKeyTwo
public class Foo {
private Map<String, Bar> bars = new HashMap<>();
public Map<String, Bar> getBars() { .... }
}
https://github.com/spring-projects/spring-boot/wiki/Spring-Boot-Configuration-Binding
I think this is a good way of solving this problem and it's extremely simple:
$(function() {
var pastValue, pastSelectionStart, pastSelectionEnd;
$("input").on("keydown", function() {
pastValue = this.value;
pastSelectionStart = this.selectionStart;
pastSelectionEnd = this.selectionEnd;
}).on("input propertychange", function() {
var regex = /^[0-9]+\.?[0-9]*$/;
if (this.value.length > 0 && !regex.test(this.value)) {
this.value = pastValue;
this.selectionStart = pastSelectionStart;
this.selectionEnd = pastSelectionEnd;
}
});
});
Example: JSFiddle
Scenarios covered
Most similar recommendations here fail at least one of these or require a lot of code to cover all these scenarios.
home
, end
, and the arrow
keys.delete
and backspace
to be used at any index.keyup
event is not used.Scenarios failed
0.5
and deleting only the zero will not work. This can be fixed by changing the regex to /^[0-9]*\.?[0-9]*$/
and then adding a blur event to prepend a 0
when the textbox starts with a decimal point (if desired). See this advanced scenario for a better idea of how to fix this.Plugin
I created this simple jquery plugin to make this easier:
$("input").limitRegex(/^[0-9]+\.?[0-9]*$/);
you did not use S anywhere in your algorithm (besides modifying it). the idea of dijkstra is once a vertex is on S, it will not be modified ever again. in this case, once B is inside S, you will not reach it again via C.
this fact ensures the complexity of O(E+VlogV) [otherwise, you will repeat edges more then once, and vertices more then once]
in other words, the algorithm you posted, might not be in O(E+VlogV), as promised by dijkstra's algorithm.
The most voted answer is for solving this specific problem posted by OP, where the content (text) was being wrapped inside an inline-block
element. Some cases may be about centering a normal element vertically inside a container, which also applied in my case, so for that all you need is:
align-self: center;
if you use cast, that is, (int)SomeDouble
you will truncate the fractional part. That is, if SomeDouble
were 4.9999 the result would be 4, not 5. Converting to int doesn't round the number. If you want rounding use Math.Round
In order to prevent 'Access Denied
' error:
Start
-> search 'Services
' -> right click -> Run as admistrator
Similar to the response from @rogeriopvl I added a slight modification to convert to hour minute seconds using the same library for long running jobs.
import time
start_time = time.time()
main()
seconds = time.time() - start_time
print('Time Taken:', time.strftime("%H:%M:%S",time.gmtime(seconds)))
Sample Output
Time Taken: 00:00:08
Dim
and Private
work the same, though the common convention is to use Private
at the module level, and Dim
at the Sub/Function level. Public
and Global
are nearly identical in their function, however Global
can only be used in standard modules, whereas Public
can be used in all contexts (modules, classes, controls, forms etc.) Global
comes from older versions of VB and was likely kept for backwards compatibility, but has been wholly superseded by Public
.
Try this one for Updating:
[HttpPost]
public ActionResult Edit(Models.MathClass mathClassModel)
{
//get current entry from db (db is context)
var item = db.Entry<Models.MathClass>(mathClassModel);
//change item state to modified
item.State = System.Data.Entity.EntityState.Modified;
//load existing items for ManyToMany collection
item.Collection(i => i.Students).Load();
//clear Student items
mathClassModel.Students.Clear();
//add Toner items
foreach (var studentId in mathClassModel.SelectedStudents)
{
var student = db.Student.Find(int.Parse(studentId));
mathClassModel.Students.Add(student);
}
if (ModelState.IsValid)
{
db.SaveChanges();
return RedirectToAction("Index");
}
return View(mathClassModel);
}
In the case of most major browsers, having an input outside of and not connected to any forms whatsoever tricks the browser into thinking there was no submission. In this case, you would have to use pure JS validation for your login and encryption of your passwords would be necessary as well.
Before:
<form action="..."><input type="password"/></form>
After:
<input type="password"/>
Reference:https://docs.microsoft.com/en-us/sql/t-sql/functions/newid-transact-sql?view=sql-server-2017
-- Creating a table using NEWID for uniqueidentifier data type.
CREATE TABLE cust
(
CustomerID uniqueidentifier NOT NULL
DEFAULT newid(),
Company varchar(30) NOT NULL,
ContactName varchar(60) NOT NULL,
Address varchar(30) NOT NULL,
City varchar(30) NOT NULL,
StateProvince varchar(10) NULL,
PostalCode varchar(10) NOT NULL,
CountryRegion varchar(20) NOT NULL,
Telephone varchar(15) NOT NULL,
Fax varchar(15) NULL
);
GO
-- Inserting 5 rows into cust table.
INSERT cust
(CustomerID, Company, ContactName, Address, City, StateProvince,
PostalCode, CountryRegion, Telephone, Fax)
VALUES
(NEWID(), 'Wartian Herkku', 'Pirkko Koskitalo', 'Torikatu 38', 'Oulu', NULL,
'90110', 'Finland', '981-443655', '981-443655')
,(NEWID(), 'Wellington Importadora', 'Paula Parente', 'Rua do Mercado, 12', 'Resende', 'SP',
'08737-363', 'Brasil', '(14) 555-8122', '')
,(NEWID(), 'Cactus Comidas para Ilevar', 'Patricio Simpson', 'Cerrito 333', 'Buenos Aires', NULL,
'1010', 'Argentina', '(1) 135-5555', '(1) 135-4892')
,(NEWID(), 'Ernst Handel', 'Roland Mendel', 'Kirchgasse 6', 'Graz', NULL,
'8010', 'Austria', '7675-3425', '7675-3426')
,(NEWID(), 'Maison Dewey', 'Catherine Dewey', 'Rue Joseph-Bens 532', 'Bruxelles', NULL,
'B-1180', 'Belgium', '(02) 201 24 67', '(02) 201 24 68');
GO
@babel/plugin-proposal-export-default-from
via:yarn add -D @babel/plugin-proposal-export-default-from
.babelrc.json
or any of the Configuration File Typesmodule.exports = {
//...
plugins: [
'@babel/plugin-proposal-export-default-from'
]
//...
}
export
directly from a file-path
:export Foo from './components/Foo'
export Bar from './components/Bar'
Good Luck...
Here's a variation of @RichieHindle's excellent answer which implements a decorator that can be selectively applied to functions as desired. Works with Python 2.7.14 and 3.6.4.
from __future__ import print_function
import functools
import traceback
import sys
INDENT = 4*' '
def stacktrace(func):
@functools.wraps(func)
def wrapped(*args, **kwds):
# Get all but last line returned by traceback.format_stack()
# which is the line below.
callstack = '\n'.join([INDENT+line.strip() for line in traceback.format_stack()][:-1])
print('{}() called:'.format(func.__name__))
print(callstack)
return func(*args, **kwds)
return wrapped
@stacktrace
def test_func():
return 42
print(test_func())
Output from sample:
test_func() called:
File "stacktrace_decorator.py", line 28, in <module>
print(test_func())
42
I've found the best way to program the font sizes of a website are to define a base font size for the body
and then use em's (or rem's) for every other font-size
I declare after that. That's personal preference I suppose, but it's served me well and also made it very easy to incorporate a more responsive design.
As far as using rem units go, I think it's good to find a balance between being progressive in your code, but to also offer support for older browsers. Check out this link about browser support for rem units, that should help out a good amount on your decision.
This method will use the LocationManager service.
Source Link
//Check GPS Status true/false
public static boolean checkGPSStatus(Context context){
LocationManager manager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE );
boolean statusOfGPS = manager.isProviderEnabled(LocationManager.GPS_PROVIDER);
return statusOfGPS;
};
Pandas magic at work. All logic is out.
The error message "ValueError: If using all scalar values, you must pass an index"
Says you must pass an index.
This does not necessarily mean passing an index makes pandas do what you want it to do
When you pass an index, pandas will treat your dictionary keys as column names and the values as what the column should contain for each of the values in the index.
a = 2
b = 3
df2 = pd.DataFrame({'A':a,'B':b}, index=[1])
A B
1 2 3
Passing a larger index:
df2 = pd.DataFrame({'A':a,'B':b}, index=[1, 2, 3, 4])
A B
1 2 3
2 2 3
3 2 3
4 2 3
An index is usually automatically generated by a dataframe when none is given. However, pandas does not know how many rows of 2
and 3
you want. You can however be more explicit about it
df2 = pd.DataFrame({'A':[a]*4,'B':[b]*4})
df2
A B
0 2 3
1 2 3
2 2 3
3 2 3
The default index is 0 based though.
I would recommend always passing a dictionary of lists to the dataframe constructor when creating dataframes. It's easier to read for other developers. Pandas has a lot of caveats, don't make other developers have to experts in all of them in order to read your code.
Improved solution that basically work with any binary operator (at least numbers, strings doesn't work well with eval, TAKE CARE OF POSSIBLE SCRIPT INJECTION IF USING A NON DEFINED OPERATOR WITH USER INPUTS):
Handlebars.registerHelper("ifCond",function(v1,operator,v2,options) {
switch (operator)
{
case "==":
return (v1==v2)?options.fn(this):options.inverse(this);
case "!=":
return (v1!=v2)?options.fn(this):options.inverse(this);
case "===":
return (v1===v2)?options.fn(this):options.inverse(this);
case "!==":
return (v1!==v2)?options.fn(this):options.inverse(this);
case "&&":
return (v1&&v2)?options.fn(this):options.inverse(this);
case "||":
return (v1||v2)?options.fn(this):options.inverse(this);
case "<":
return (v1<v2)?options.fn(this):options.inverse(this);
case "<=":
return (v1<=v2)?options.fn(this):options.inverse(this);
case ">":
return (v1>v2)?options.fn(this):options.inverse(this);
case ">=":
return (v1>=v2)?options.fn(this):options.inverse(this);
default:
return eval(""+v1+operator+v2)?options.fn(this):options.inverse(this);
}
});
Since you have two densitys I imagine you may be wanting to set your own colours with scale_fill_manual
.
If so you can do:
df <- data.frame(x=1:10,group=c(rep("a",5),rep("b",5)))
legend_title <- "OMG My Title"
ggplot(df, aes(x=x, fill=group)) + geom_density(alpha=.3) +
scale_fill_manual(legend_title,values=c("orange","red"))
Java code:
public class MapActivity extends FragmentActivity implements LocationListener {
GoogleMap googleMap;
LatLng myPosition;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_map);
// Getting reference to the SupportMapFragment of activity_main.xml
SupportMapFragment fm = (SupportMapFragment)
getSupportFragmentManager().findFragmentById(R.id.map);
// Getting GoogleMap object from the fragment
googleMap = fm.getMap();
// Enabling MyLocation Layer of Google Map
googleMap.setMyLocationEnabled(true);
// Getting LocationManager object from System Service LOCATION_SERVICE
LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
// Creating a criteria object to retrieve provider
Criteria criteria = new Criteria();
// Getting the name of the best provider
String provider = locationManager.getBestProvider(criteria, true);
// Getting Current Location
Location location = locationManager.getLastKnownLocation(provider);
if (location != null) {
// Getting latitude of the current location
double latitude = location.getLatitude();
// Getting longitude of the current location
double longitude = location.getLongitude();
// Creating a LatLng object for the current location
LatLng latLng = new LatLng(latitude, longitude);
myPosition = new LatLng(latitude, longitude);
googleMap.addMarker(new MarkerOptions().position(myPosition).title("Start"));
}
}
}
activity_map.xml:
<?xml version="1.0" encoding="utf-8"?>
<fragment xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:map="http://schemas.android.com/apk/res-auto"
android:id="@+id/map"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
class="com.google.android.gms.maps.SupportMapFragment"/>
You will get your current location in a blue circle.
This is an old post, but thanks to this post I have found this:
\! echo 'some text';
Tested with MySQL 8 and working correctly. Cool right? :)
Edit: the api call has been removed by google. so it is no longer functioning.
Agree with Pareshkumar's answer. Now there is a python wrapper googlefinance for the url call.
Install googlefinance
$pip install googlefinance
It is easy to get current stock price:
>>> from googlefinance import getQuotes
>>> import json
>>> print json.dumps(getQuotes('AAPL'), indent=2)
[
{
"Index": "NASDAQ",
"LastTradeWithCurrency": "129.09",
"LastTradeDateTime": "2015-03-02T16:04:29Z",
"LastTradePrice": "129.09",
"Yield": "1.46",
"LastTradeTime": "4:04PM EST",
"LastTradeDateTimeLong": "Mar 2, 4:04PM EST",
"Dividend": "0.47",
"StockSymbol": "AAPL",
"ID": "22144"
}
]
Google finance is a source that provides real-time stock data. There are also other APIs from yahoo, such as yahoo-finance, but they are delayed by 15min for NYSE and NASDAQ stocks.
The simplest solution is probably:
In [10]: ''.join(set('aaabcabccd'))
Out[10]: 'acbd'
Note that this doesn't guarantee the order in which the letters appear in the output, even though the example might suggest otherwise.
You refer to the output as a "list". If a list is what you really want, replace ''.join
with list
:
In [1]: list(set('aaabcabccd'))
Out[1]: ['a', 'c', 'b', 'd']
As far as performance goes, worrying about it at this stage sounds like premature optimization.
You need to use objcopy to separate the debug information:
objcopy --only-keep-debug "${tostripfile}" "${debugdir}/${debugfile}"
strip --strip-debug --strip-unneeded "${tostripfile}"
objcopy --add-gnu-debuglink="${debugdir}/${debugfile}" "${tostripfile}"
I use the bash script below to separate the debug information into files with a .debug extension in a .debug directory. This way I can tar the libraries and executables in one tar file and the .debug directories in another. If I want to add the debug info later on I simply extract the debug tar file and voila I have symbolic debug information.
This is the bash script:
#!/bin/bash
scriptdir=`dirname ${0}`
scriptdir=`(cd ${scriptdir}; pwd)`
scriptname=`basename ${0}`
set -e
function errorexit()
{
errorcode=${1}
shift
echo $@
exit ${errorcode}
}
function usage()
{
echo "USAGE ${scriptname} <tostrip>"
}
tostripdir=`dirname "$1"`
tostripfile=`basename "$1"`
if [ -z ${tostripfile} ] ; then
usage
errorexit 0 "tostrip must be specified"
fi
cd "${tostripdir}"
debugdir=.debug
debugfile="${tostripfile}.debug"
if [ ! -d "${debugdir}" ] ; then
echo "creating dir ${tostripdir}/${debugdir}"
mkdir -p "${debugdir}"
fi
echo "stripping ${tostripfile}, putting debug info into ${debugfile}"
objcopy --only-keep-debug "${tostripfile}" "${debugdir}/${debugfile}"
strip --strip-debug --strip-unneeded "${tostripfile}"
objcopy --add-gnu-debuglink="${debugdir}/${debugfile}" "${tostripfile}"
chmod -x "${debugdir}/${debugfile}"
Apparently Facebook no longer (as of 2014) allows you to customise the sharing screen, no matter if you are just opening sharer.php URL or using Android intents in more specialised ways. See for example these answers:
Anyway, using plain Intents, you can still share a URL, but not any default text with it, as billynomates commented. (Also, if you have no URL to share, just launching Facebook app with empty "Write Post" (i.e. status update) dialog is equally easy; use the code below but leave out EXTRA_TEXT
.)
Here's the best solution I've found that does not involve using any Facebook SDKs.
This code opens the official Facebook app directly if it's installed, and otherwise falls back to opening sharer.php in a browser. (Most of the other solutions in this question bring up a huge "Complete action using…" dialog which isn't optimal at all!)
String urlToShare = "https://stackoverflow.com/questions/7545254";
Intent intent = new Intent(Intent.ACTION_SEND);
intent.setType("text/plain");
// intent.putExtra(Intent.EXTRA_SUBJECT, "Foo bar"); // NB: has no effect!
intent.putExtra(Intent.EXTRA_TEXT, urlToShare);
// See if official Facebook app is found
boolean facebookAppFound = false;
List<ResolveInfo> matches = getPackageManager().queryIntentActivities(intent, 0);
for (ResolveInfo info : matches) {
if (info.activityInfo.packageName.toLowerCase().startsWith("com.facebook.katana")) {
intent.setPackage(info.activityInfo.packageName);
facebookAppFound = true;
break;
}
}
// As fallback, launch sharer.php in a browser
if (!facebookAppFound) {
String sharerUrl = "https://www.facebook.com/sharer/sharer.php?u=" + urlToShare;
intent = new Intent(Intent.ACTION_VIEW, Uri.parse(sharerUrl));
}
startActivity(intent);
(Regarding the com.facebook.katana
package name, see MatheusJardimB's comment.)
The result looks like this on my Nexus 7 (Android 4.4) with Facebook app installed:
It may seem as being too cautious, but I frequently zip a copy of whatever I've been working on before I make source control changes. In a Gitlab project I'm working on, I recently deleted a remote branch by mistake that I wanted to keep after merging a merge request. It turns out all I had to do to get it back with the commit history was push again. The merge request was still tracked by Gitlab, so it still shows the blue 'merged' label to the right of the branch. I still zipped my local folder in case something bad happened.
I found the solution, I just forgot to Cast the result:
var stream ="[encoded jwt]";
var handler = new JwtSecurityTokenHandler();
var jsonToken = handler.ReadToken(stream);
var tokenS = handler.ReadToken(stream) as JwtSecurityToken;
I can get Claims using:
var jti = tokenS.Claims.First(claim => claim.Type == "jti").Value;
To start:
Pros:
Cons:
I think the lightsail as the name suggest is light weight and meant for initial development. For production sites and apps with high volume it simply becomes unavailable and hangs....It is just a sandbox to play with things. Further lack of support reduces its reliability. There should be an option to migrate to EC2, when u fully develop your apps or sites..So that with same minimum configuration you can migrate to scalable EC2..
Similarly to @brucexin I needed to get OS-level thread identifier (which != thread.get_ident()
) and use something like below not to depend on particular numbers and being amd64-only:
---- 8< ---- (xos.pyx)
"""module xos complements standard module os"""
cdef extern from "<sys/syscall.h>":
long syscall(long number, ...)
const int SYS_gettid
# gettid returns current OS thread identifier.
def gettid():
return syscall(SYS_gettid)
and
---- 8< ---- (test.py)
import pyximport; pyximport.install()
import xos
...
print 'my tid: %d' % xos.gettid()
this depends on Cython though.
As addon to ITmeze post, I've used this function to convert the output of C# port for Mozilla Universal Charset Detector
private Encoding GetEncodingFromString(string codePageName)
{
try
{
return Encoding.GetEncoding(codePageName);
}
catch
{
return Encoding.ASCII;
}
}
Header files can contain any valid C code, since they are injected into the compilation unit by the pre-processor prior to compilation.
If a header file contains a function, and is included by multiple .c
files, each .c
file will get a copy of that function and create a symbol for it. The linker will complain about the duplicate symbols.
It is technically possible to create static
functions in a header file for inclusion in multiple .c
files. Though this is generally not done because it breaks from the convention that code is found in .c
files and declarations are found in .h
files.
See the discussions in C/C++: Static function in header file, what does it mean? for more explanation.
dep and clg alphabets validation is not working
var selectedRow = null;
function validateform() {
var table = document.getElementById("mytable");
var rowCount = table.rows.length;
console.log(rowCount);
var x = document.forms["myform"]["usrname"].value;
if (x == "") {
alert("name must be filled out");
return false;
}
var y = document.forms["myform"]["usremail"].value;
if (y == "") {
alert("email must be filled out");
return false;
}
var mail = /[^@]+@[a-zA-Z]+\.[a-zA-Z]{2,6}/
if (mail.test(y)) {
//alert("email must be a valid format");
//return false ;
} else {
alert("not a mail id")
return false;
}
var z = document.forms["myform"]["usrage"].value;
if (z == "") {
alert("age must be filled out");
return false;
}
if (isNaN(z) || z < 1 || z > 100) {
alert("The age must be a number between 1 and 100");
return false;
}
var a = document.forms["myform"]["usrdpt"].value;
if (a == "") {
alert("Dept must be filled out");
return false;
}
var dept = "`@#$%^&*()+=-[]\\\';,./{}|\":<>?~_";
if (dept.match(a)) {
alert("special charachers found");
return false;
}
var b = document.forms["myform"]["usrclg"].value;
if (b == "") {
alert("College must be filled out");
return false;
}
console.log(table);
var row = table.insertRow(rowCount);
row.setAttribute('id', rowCount);
var cell0 = row.insertCell(0);
var cell1 = row.insertCell(1);
var cell2 = row.insertCell(2);
var cell3 = row.insertCell(3);
var cell4 = row.insertCell(4);
var cell5 = row.insertCell(5);
var cell6 = row.insertCell(6);
var cell7 = row.insertCell(7);
cell0.innerHTML = rowCount;
cell1.innerHTML = x;
cell2.innerHTML = y;
cell3.innerHTML = z;
cell4.innerHTML = a;
cell5.innerHTML = b;
cell6.innerHTML = '<Button type="button" onclick=onEdit("' + x + '","' + y + '","' + z + '","' + a + '","' + b + '","' + rowCount + '")>Edit</BUTTON>';
cell7.innerHTML = '<Button type="button" onclick=deletefunction(' + rowCount + ')>Delete</BUTTON>';
}
function emptyfunction() {
document.getElementById("usrname").value = "";
document.getElementById("usremail").value = "";
document.getElementById("usrage").value = "";
document.getElementById("usrdpt").value = "";
document.getElementById("usrclg").value = "";
}
function onEdit(x, y, z, a, b, rowCount) {
selectedRow = rowCount;
console.log(selectedRow);
document.forms["myform"]["usrname"].value = x;
document.forms["myform"]["usremail"].value = y;
document.forms["myform"]["usrage"].value = z;
document.forms["myform"]["usrdpt"].value = a;
document.forms["myform"]["usrclg"].value = b;
document.getElementById('Add').style.display = 'none';
document.getElementById('update').style.display = 'block';
}
function deletefunction(rowCount) {
document.getElementById("mytable").deleteRow(rowCount);
}
function onUpdatefunction() {
var row = document.getElementById(selectedRow);
console.log(row);
var x = document.forms["myform"]["usrname"].value;
if (x == "") {
alert("name must be filled out");
document.myForm.x.focus();
return false;
}
var y = document.forms["myform"]["usremail"].value;
if (y == "") {
alert("email must be filled out");
document.myForm.y.focus();
return false;
}
var mail = /[^@]+@[a-zA-Z]+\.[a-zA-Z]{2,6}/
if (mail.test(y)) {
//alert("email must be a valid format");
//return false ;
} else {
alert("not a mail id");
return false;
}
var z = document.forms["myform"]["usrage"].value;
if (z == "") {
alert("age must be filled out");
document.myForm.z.focus();
return false;
}
if (isNaN(z) || z < 1 || z > 100) {
alert("The age must be a number between 1 and 100");
return false;
}
var a = document.forms["myform"]["usrdpt"].value;
if (a == "") {
alert("Dept must be filled out");
return false;
}
var letters = /^[A-Za-z]+$/;
if (a.test(letters)) {
//Your logice will be here.
} else {
alert("Please enter only alphabets");
return false;
}
var b = document.forms["myform"]["usrclg"].value;
if (b == "") {
alert("College must be filled out");
return false;
}
var letters = /^[A-Za-z]+$/;
if (b.test(letters)) {
//Your logice will be here.
} else {
alert("Please enter only alphabets");
return false;
}
row.cells[1].innerHTML = x;
row.cells[2].innerHTML = y;
row.cells[3].innerHTML = z;
row.cells[4].innerHTML = a;
row.cells[5].innerHTML = b;
}
_x000D_
<html>
<head>
</head>
<body>
<form name="myform">
<h1>
<center> Admission form </center>
</h1>
<center>
<tr>
<td>Name :</td>
<td><input type="text" name="usrname" PlaceHolder="Enter Your First Name" required></td>
</tr>
<tr>
<td> Email ID :</td>
<td><input type="text" name="usremail" PlaceHolder="Enter Your email address" pattern="[^@]+@[a-zA-Z]+\.[a-zA-Z]{2,6}" required></td>
</tr>
<tr>
<td>Age :</td>
<td><input type="number" name="usrage" PlaceHolder="Enter Your Age" required></td>
</tr>
<tr>
<td>Dept :</td>
<td><input type="text" name="usrdpt" PlaceHolder="Enter Dept"></td>
</tr>
<tr>
<td>College :</td>
<td><input type="text" name="usrclg" PlaceHolder="Enter college"></td>
</tr>
</center>
<center>
<br>
<br>
<tr>
<td>
<Button type="button" onclick="validateform()" id="Add">Add</button>
</td>
<td>
<Button type="button" onclick="onUpdatefunction()" style="display:none;" id="update">update</button>
</td>
<td><button type="reset">Reset</button></td>
</tr>
</center>
<br><br>
<center>
<table id="mytable" border="1">
<tr>
<th>SNO</th>
<th>Name</th>
<th>Email ID</th>
<th>Age</th>
<th>Dept</th>
<th>College</th>
</tr>
</center>
</table>
</form>
</body>
</html>
_x000D_
Open eclipse.ini
in the installation directory, and observe the line with text:
plugins/org.eclipse.equinox.launcher.win32.win32.x86_64_1.0.200.v20090519 then it is 64 bit.
If it would be plugins/org.eclipse.equinox.launcher.win32.win32.x86_32_1.0.200.v20090519 then it is 32 bit.
PyQt4 can be forced to use a new API in which QString is automatically converted to and from a Python object:
import sip
sip.setapi('QString', 2)
With this API, QtCore.QString
class is no longer available and self.ui.comboBox.currentText()
will return a Python string or unicode object.
See Selecting Incompatible APIs from the doc.
_, err := os.Stat(file)
if err == nil {
log.Printf("file %s exists", file)
} else if os.IsNotExist(err) {
log.Printf("file %s not exists", file)
} else {
log.Printf("file %s stat error: %v", file, err)
}
Finally, this is what I did:
private File getFileFromURL() {
URL url = this.getClass().getClassLoader().getResource("/sql");
File file = null;
try {
file = new File(url.toURI());
} catch (URISyntaxException e) {
file = new File(url.getPath());
} finally {
return file;
}
}
...
File folder = getFileFromURL();
File[] listOfFiles = folder.listFiles();
So, for those who would like to know the summary of that discussion. The final top scores for counting a 50 million-lengthed generator expression using:
len(list(gen))
, len([_ for _ in gen])
, sum(1 for _ in gen),
ilen(gen)
(from more_itertool), reduce(lambda c, i: c + 1, gen, 0)
, sorted by performance of execution (including memory consumption), will make you surprised:
```
gen = (i for i in data*1000); t0 = monotonic(); len(list(gen))
('list, sec', 1.9684218849870376)
gen = (i for i in data*1000); t0 = monotonic(); len([i for i in gen])
('list_compr, sec', 2.5885991149989422)
gen = (i for i in data*1000); t0 = monotonic(); sum(1 for i in gen); t1 = monotonic()
('sum, sec', 3.441088170016883)
d = deque(enumerate(iterable, 1), maxlen=1)
test_ilen.py:10: 0.875 KiB
gen = (i for i in data*1000); t0 = monotonic(); ilen(gen)
('ilen, sec', 9.812256851990242)
gen = (i for i in data*1000); t0 = monotonic(); reduce(lambda counter, i: counter + 1, gen, 0)
('reduce, sec', 13.436614598002052) ```
So, len(list(gen))
is the most frequent and less memory consumable
This is how I do this with JQuery...
using the jquery-watermark plugin (http://code.google.com/p/jquery-watermark/)
$('#inputId').watermark('Please select a name');
works like a charm!!
There is some good documentation at that google code site.
Hope this helps!
As far as I know you can use all mentioned technologies separately or together. It's up to you. I think you look at the problem from the wrong angle. Material Design is just the way particular elements of the page are designed, behave and put together. Material Design provides great UI/UX, but it relies on the graphic layout (HTML/CSS) rather than JS (events, interactions).
On the other hand, AngularJS and Bootstrap are front-end frameworks that can speed up your development by saving you from writing tons of code. For example, you can build web app utilizing AngularJS, but without Material Design. Or You can build simple HTML5 web page with Material Design without AngularJS or Bootstrap. Finally you can build web app that uses AngularJS with Bootstrap and with Material Design. This is the best scenario. All technologies support each other.
You can check awesome material design components for AngularJS:
https://material.angularjs.org
Most layout managers work best with a component's preferredSize, and most GUI's are best off allowing the components they contain to set their own preferredSizes based on their content or properties. To use these layout managers to their best advantage, do call pack()
on your top level containers such as your JFrames before making them visible as this will tell these managers to do their actions -- to layout their components.
Often when I've needed to play a more direct role in setting the size of one of my components, I'll override getPreferredSize and have it return a Dimension that is larger than the super.preferredSize (or if not then it returns the super's value).
For example, here's a small drag-a-rectangle app that I created for another question on this site:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class MoveRect extends JPanel {
private static final int RECT_W = 90;
private static final int RECT_H = 70;
private static final int PREF_W = 600;
private static final int PREF_H = 300;
private static final Color DRAW_RECT_COLOR = Color.black;
private static final Color DRAG_RECT_COLOR = new Color(180, 200, 255);
private Rectangle rect = new Rectangle(25, 25, RECT_W, RECT_H);
private boolean dragging = false;
private int deltaX = 0;
private int deltaY = 0;
public MoveRect() {
MyMouseAdapter myMouseAdapter = new MyMouseAdapter();
addMouseListener(myMouseAdapter);
addMouseMotionListener(myMouseAdapter);
}
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
if (rect != null) {
Color c = dragging ? DRAG_RECT_COLOR : DRAW_RECT_COLOR;
g.setColor(c);
Graphics2D g2 = (Graphics2D) g;
g2.draw(rect);
}
}
@Override
public Dimension getPreferredSize() {
return new Dimension(PREF_W, PREF_H);
}
private class MyMouseAdapter extends MouseAdapter {
@Override
public void mousePressed(MouseEvent e) {
Point mousePoint = e.getPoint();
if (rect.contains(mousePoint)) {
dragging = true;
deltaX = rect.x - mousePoint.x;
deltaY = rect.y - mousePoint.y;
}
}
@Override
public void mouseReleased(MouseEvent e) {
dragging = false;
repaint();
}
@Override
public void mouseDragged(MouseEvent e) {
Point p2 = e.getPoint();
if (dragging) {
int x = p2.x + deltaX;
int y = p2.y + deltaY;
rect = new Rectangle(x, y, RECT_W, RECT_H);
MoveRect.this.repaint();
}
}
}
private static void createAndShowGui() {
MoveRect mainPanel = new MoveRect();
JFrame frame = new JFrame("MoveRect");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(mainPanel);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGui();
}
});
}
}
Note that my main class is a JPanel, and that I override JPanel's getPreferredSize:
public class MoveRect extends JPanel {
//.... deleted constants
private static final int PREF_W = 600;
private static final int PREF_H = 300;
//.... deleted fields and constants
//... deleted methods and constructors
@Override
public Dimension getPreferredSize() {
return new Dimension(PREF_W, PREF_H);
}
Also note that when I display my GUI, I place it into a JFrame, call pack();
on the JFrame, set its position, and then call setVisible(true);
on my JFrame:
private static void createAndShowGui() {
MoveRect mainPanel = new MoveRect();
JFrame frame = new JFrame("MoveRect");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(mainPanel);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGui();
}
});
}
}
Multiply by 2, round, then divide by 2
if you want nearest quarter, multiply by 4, divide by 4, etc
Just a quick change to wp-config.php
define('FS_METHOD','direct');
That’s it, enjoy your wordpress updates without ftp!
Alternate Method:
There are hosts out there that will prevent this method from working to ease your WordPress updating. Fortunately, there is another way to keep this pest from prompting you for your FTP user name and password.
Again, after the MYSQL login declarations in your wp-config.php file, add the following:
define("FTP_HOST", "localhost");
define("FTP_USER", "yourftpusername");
define("FTP_PASS", "yourftppassword");
List<String> list = new List<String> { "6", "1", "2", "4", "6", "5", "1" };
var q = from s in list
group s by s into g
where g.Count() > 1
select g.First();
foreach (var item in q)
{
Console.WriteLine(item);
}
Thanks to @Yiling. That was a hint.
<bean id="propertyConfigurer"
class="org.springframework.web.context.support.ServletContextPropertyPlaceholderConfigurer">
<property name="systemPropertiesModeName" value="SYSTEM_PROPERTIES_MODE_OVERRIDE" />
<property name="searchSystemEnvironment" value="true" />
<property name="locations">
<list>
<value>file:#{systemEnvironment['FILE_PATH']}/first.properties</value>
<value>file:#{systemEnvironment['FILE_PATH']}/second.properties</value>
<value>file:#{systemEnvironment['FILE_PATH']}/third.properties</value>
</list>
</property>
</bean>
After this, you should have one environment variable named 'FILE_PATH'. Make sure you restart your terminal/IDE after creating that environment variable.
In a strict definition of a boolean element, there are only two values. In a perfect world, that would be true. In the real world, the element may be missing or unknown. Typically, this involves user input. In a screen based system, it could be forced by an edit. In a batch world using either a database or XML input, the element could easily be missing.
So, in the non-perfect world we live in, the Boolean object is great in that it can represent the missing or unknown state as null. After all, computers just model the real world an should account for all possible states and handle them with throwing exceptions (mostly since there are use cases where throwing the exception would be the correct response).
In my case, the Boolean object was the perfect answer since the input XML sometimes had the element missing and I could still get a value, assign it to a Boolean and then check for a null before trying to use a true or false test with it.
Just my 2 cents.
The answer by Nick Mitchinson is for Bootstrap version 2.
If you are using Bootstrap version 3, then forms have changed a bit. For bootstrap 3, use the following instead:
<div class="form-horizontal">
<div class="form-group">
<div class="col-md-6">
<textarea class="form-control" rows="3" placeholder="What's up?" required></textarea>
</div>
</div>
</div>
Where, col-md-6 will target medium sized devices. You can add col-xs-6 etc to target smaller devices.
Since [^a-z0-9]
character class contains all that is not alnum, it contains white characters too!
text.replace(/[^a-z0-9]+/gi, " ");
Spring Data JPA 1.11 now supports the exists
projection in repository query derivation.
See documentation here.
In your case the following will work:
public interface MyEntityRepository extends CrudRepository<MyEntity, String> {
boolean existsByFoo(String foo);
}
I navigate to:
/usr/lib/android-sdk/licenses
and I typed in terminal:
echo -e "\n8933bad161af4178b1185d1a37fbf41ea5269c55" > $ANDROID_SDK/licenses/android-sdk-license"
With root permission. And it works for me now.
Try like this:
if message.value[0] == "/" or message.value[0] == "\\":
do_stuff
Due to difficulties to clearly distinguish between URI and URL, as far as I remember W3C does not make a difference any longer between URI and URL (http://www.w3.org/Addressing/).
This solution avoids the issue in IE where the last character is removed when a character in the middle of the text is added. It also works fine with other browsers.
$("textarea[maxlength]").keydown( function(e) {
var key = e.which; // backspace = 8, delete = 46, arrows = 37,38,39,40
if ( ( key >= 37 && key <= 40 ) || key == 8 || key == 46 ) return;
return $(this).val().length < $(this).attr( "maxlength" );
});
My form validation then deals with any issues where the user may have pasted (only seems to be a problem in IE) text exceeding the maximum length of the textarea.
This would give you all valid numeric values in lines
. You can change the loop to validate, strip out invalid characters, etc - whichever you want.
var lines = [];
$('#my_textarea_selector').val().split("\n").each(function ()
{
if (parseInt($(this) != 'NaN')
lines[] = parseInt($(this));
}
Preferred string type in C++ is string
, defined in namespace std
, in header <string>
and you can initialize it like this for example:
#include <string>
int main()
{
std::string str1("Some text");
std::string str2 = "Some text";
}
CGRect buttonFrame = CGRectMake( 10, 80, 100, 30 );
UIButton *button = [[UIButton alloc] initWithFrame: buttonFrame];
[button setTitle: @"My Button" forState: UIControlStateNormal];
[button addTarget:self action:@selector(btnSelected:) forControlEvents:UIControlEventTouchUpInside];
[button setTitleColor: [UIColor redColor] forState: UIControlStateNormal];
[view addSubview:button];
You can use:
if (parentGuest.nextSibling) {
parentGuest.parentNode.insertBefore(childGuest, parentGuest.nextSibling);
}
else {
parentGuest.parentNode.appendChild(childGuest);
}
But as Pavel pointed out, the referenceElement can be null/undefined, and if so, insertBefore behaves just like appendChild. So the following is equivalent to the above:
parentGuest.parentNode.insertBefore(childGuest, parentGuest.nextSibling);
New XCode 7 will only require 'UIFileSharingEnabled' key in Info.plist. 'CFBundleDisplayName' is not required any more.
One more hint: do not only modify the Info.plist of the 'tests' target. The main app and the 'tests' have different Info.plist.
Training set: Is used for finding Nearest neighbors. Validation set: Is for finding different k which is applying to train set. Test set: Is used for finding the maximum accuracy and unseen data in future.
My implementation)
const items = Array.from(document.querySelectorAll('.item'));_x000D_
items.forEach(item =>{_x000D_
item.style.color = checkEllipsis(item) ? 'red': 'black'_x000D_
})_x000D_
_x000D_
function checkEllipsis(el){_x000D_
const styles = getComputedStyle(el);_x000D_
const widthEl = parseFloat(styles.width);_x000D_
const ctx = document.createElement('canvas').getContext('2d');_x000D_
ctx.font = `${styles.fontSize} ${styles.fontFamily}`;_x000D_
const text = ctx.measureText(el.innerText);_x000D_
return text.width > widthEl;_x000D_
}
_x000D_
.item{_x000D_
width: 60px;_x000D_
overflow: hidden;_x000D_
text-overflow: ellipsis;_x000D_
}
_x000D_
<div class="item">Short</div>_x000D_
<div class="item">Loooooooooooong</div>
_x000D_
You'll have to style your printout with @media print {}
in the CSS but the simple code is:
export default class Component extends Component {
print(){
window.print();
}
render() {
...
<span className="print"
onClick={this.print}>
PRINT
</span>
}
}
Hope that's helpful!
One solution (though not very pretty) is to use Apache common List/Set mutation
import org.apache.commons.collections.list.SetUniqueList;
final List<Long> vertexes=SetUniqueList.setUniqueList(new LinkedList<>());
it is a list without duplicates
I have a solution from a while ago that I kept improving. Also searches within XML columns if told to do so, or searches integer values if providing a integer only string.
/* Reto Egeter, fullparam.wordpress.com */
DECLARE @SearchStrTableName nvarchar(255), @SearchStrColumnName nvarchar(255), @SearchStrColumnValue nvarchar(255), @SearchStrInXML bit, @FullRowResult bit, @FullRowResultRows int
SET @SearchStrColumnValue = '%searchthis%' /* use LIKE syntax */
SET @FullRowResult = 1
SET @FullRowResultRows = 3
SET @SearchStrTableName = NULL /* NULL for all tables, uses LIKE syntax */
SET @SearchStrColumnName = NULL /* NULL for all columns, uses LIKE syntax */
SET @SearchStrInXML = 0 /* Searching XML data may be slow */
IF OBJECT_ID('tempdb..#Results') IS NOT NULL DROP TABLE #Results
CREATE TABLE #Results (TableName nvarchar(128), ColumnName nvarchar(128), ColumnValue nvarchar(max),ColumnType nvarchar(20))
SET NOCOUNT ON
DECLARE @TableName nvarchar(256) = '',@ColumnName nvarchar(128),@ColumnType nvarchar(20), @QuotedSearchStrColumnValue nvarchar(110), @QuotedSearchStrColumnName nvarchar(110)
SET @QuotedSearchStrColumnValue = QUOTENAME(@SearchStrColumnValue,'''')
DECLARE @ColumnNameTable TABLE (COLUMN_NAME nvarchar(128),DATA_TYPE nvarchar(20))
WHILE @TableName IS NOT NULL
BEGIN
SET @TableName =
(
SELECT MIN(QUOTENAME(TABLE_SCHEMA) + '.' + QUOTENAME(TABLE_NAME))
FROM INFORMATION_SCHEMA.TABLES
WHERE TABLE_TYPE = 'BASE TABLE'
AND TABLE_NAME LIKE COALESCE(@SearchStrTableName,TABLE_NAME)
AND QUOTENAME(TABLE_SCHEMA) + '.' + QUOTENAME(TABLE_NAME) > @TableName
AND OBJECTPROPERTY(OBJECT_ID(QUOTENAME(TABLE_SCHEMA) + '.' + QUOTENAME(TABLE_NAME)), 'IsMSShipped') = 0
)
IF @TableName IS NOT NULL
BEGIN
DECLARE @sql VARCHAR(MAX)
SET @sql = 'SELECT QUOTENAME(COLUMN_NAME),DATA_TYPE
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_SCHEMA = PARSENAME(''' + @TableName + ''', 2)
AND TABLE_NAME = PARSENAME(''' + @TableName + ''', 1)
AND DATA_TYPE IN (' + CASE WHEN ISNUMERIC(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(@SearchStrColumnValue,'%',''),'_',''),'[',''),']',''),'-','')) = 1 THEN '''tinyint'',''int'',''smallint'',''bigint'',''numeric'',''decimal'',''smallmoney'',''money'',' ELSE '' END + '''char'',''varchar'',''nchar'',''nvarchar'',''timestamp'',''uniqueidentifier''' + CASE @SearchStrInXML WHEN 1 THEN ',''xml''' ELSE '' END + ')
AND COLUMN_NAME LIKE COALESCE(' + CASE WHEN @SearchStrColumnName IS NULL THEN 'NULL' ELSE '''' + @SearchStrColumnName + '''' END + ',COLUMN_NAME)'
INSERT INTO @ColumnNameTable
EXEC (@sql)
WHILE EXISTS (SELECT TOP 1 COLUMN_NAME FROM @ColumnNameTable)
BEGIN
PRINT @ColumnName
SELECT TOP 1 @ColumnName = COLUMN_NAME,@ColumnType = DATA_TYPE FROM @ColumnNameTable
SET @sql = 'SELECT ''' + @TableName + ''',''' + @ColumnName + ''',' + CASE @ColumnType WHEN 'xml' THEN 'LEFT(CAST(' + @ColumnName + ' AS nvarchar(MAX)), 4096),'''
WHEN 'timestamp' THEN 'master.dbo.fn_varbintohexstr('+ @ColumnName + '),'''
ELSE 'LEFT(' + @ColumnName + ', 4096),''' END + @ColumnType + '''
FROM ' + @TableName + ' (NOLOCK) ' +
' WHERE ' + CASE @ColumnType WHEN 'xml' THEN 'CAST(' + @ColumnName + ' AS nvarchar(MAX))'
WHEN 'timestamp' THEN 'master.dbo.fn_varbintohexstr('+ @ColumnName + ')'
ELSE @ColumnName END + ' LIKE ' + @QuotedSearchStrColumnValue
INSERT INTO #Results
EXEC(@sql)
IF @@ROWCOUNT > 0 IF @FullRowResult = 1
BEGIN
SET @sql = 'SELECT TOP ' + CAST(@FullRowResultRows AS VARCHAR(3)) + ' ''' + @TableName + ''' AS [TableFound],''' + @ColumnName + ''' AS [ColumnFound],''FullRow>'' AS [FullRow>],*' +
' FROM ' + @TableName + ' (NOLOCK) ' +
' WHERE ' + CASE @ColumnType WHEN 'xml' THEN 'CAST(' + @ColumnName + ' AS nvarchar(MAX))'
WHEN 'timestamp' THEN 'master.dbo.fn_varbintohexstr('+ @ColumnName + ')'
ELSE @ColumnName END + ' LIKE ' + @QuotedSearchStrColumnValue
EXEC(@sql)
END
DELETE FROM @ColumnNameTable WHERE COLUMN_NAME = @ColumnName
END
END
END
SET NOCOUNT OFF
SELECT TableName, ColumnName, ColumnValue, ColumnType, COUNT(*) AS Count FROM #Results
GROUP BY TableName, ColumnName, ColumnValue, ColumnType
Source: http://fullparam.wordpress.com/2012/09/07/fck-it-i-am-going-to-search-all-tables-all-collumns/
An easier and more standard way to simulate a mouse click would be directly using the event constructor to create an event and dispatch it.
Though the
MouseEvent.initMouseEvent()
method is kept for backward compatibility, creating of a MouseEvent object should be done using theMouseEvent()
constructor.
var evt = new MouseEvent("click", {
view: window,
bubbles: true,
cancelable: true,
clientX: 20,
/* whatever properties you want to give it */
});
targetElement.dispatchEvent(evt);
Demo: http://jsfiddle.net/DerekL/932wyok6/
This works on all modern browsers. For old browsers including IE, MouseEvent.initMouseEvent
will have to be used unfortunately though it's deprecated.
var evt = document.createEvent("MouseEvents");
evt.initMouseEvent("click", canBubble, cancelable, view,
detail, screenX, screenY, clientX, clientY,
ctrlKey, altKey, shiftKey, metaKey,
button, relatedTarget);
targetElement.dispatchEvent(evt);
Well, for me this is the expected result; adding six months to Jan. 1st July.
mysql> SELECT DATE_ADD( '2011-01-01', INTERVAL 6 month );
+--------------------------------------------+
| DATE_ADD( '2011-01-01', INTERVAL 6 month ) |
+--------------------------------------------+
| 2011-07-01 |
+--------------------------------------------+
Or, to get a pseudo-random int in the range 0 to 19, for example, you could use the higher bits like this:
j = ((rand() >> 15) % 20;
I just ran into this and it was due to a mod_authnz_ldap misconfiguration in my .htaccess file. Absolutely nothing was being logged, but I kept getting a 500 error.
If you run into this particular issue, you can change the log level of mod_authnz_ldap like so:
LogLevel warn authnz_ldap_module:debug
That will use a log level of debug for mod_authnz_ldap but warn for everything else (https://httpd.apache.org/docs/2.4/en/mod/core.html#loglevel).
Nothing elegant but this could be another satisfactory answer.
merge(x = DF1, y = DF2, by = "Client", all.x=TRUE)[,c("Client","LO","CON")]
This will be useful especially when you don't need the keys that were used to join the tables in your results.
It looks like sklearn requires the data shape of (row number, column number).
If your data shape is (row number, ) like (999, )
, it does not work.
By using numpy.reshape()
, you should change the shape of the array to (999, 1)
, e.g. using
data=data.reshape((999,1))
In my case, it worked with that.
The JQuery code is fine. You must execute in the ready handler not in the window load event.
<script type="text/javascript">
$(function(){
var aspForm = $("form#aspnetForm");
var firstInput = $(":input:not(input[type=button],input[type=submit],button):visible:first", aspForm);
firstInput.focus();
});
</script>
Update
I tried with the example of Karim79(thanks for the example) and it works fine: http://jsfiddle.net/2sMfU/
An alternative setting is to have the default virtual host at the end of the config file rather than the beginning. This way, all alternative virtual hosts will be checked before being matched by the default virtual host.
Example:
NameVirtualHost *:80
Listen 80
...
<VirtualHost *:80>
ServerName host1
DocumentRoot /someDir
</VirtualHost>
<VirtualHost *:80>
ServerName host2
DocumentRoot /someOtherDir
</VirtualHost>
<VirtualHost *:80>
DocumentRoot /defaultDir
</VirtualHost>
If you only need the default style, make sure you have the following width/height, otherwise the numStars could get messed up:
android:layout_width="wrap_content"
android:layout_height="wrap_content"
If you want search for sensitive data in order to remove it from your git history (which is the reason why I landed here), there are tools for that. Github as a dedicated help page for that issue.
Here is the gist of the article:
The BFG Repo-Cleaner is a faster, simpler alternative to git filter-branch for removing unwanted data. For example, to remove your file with sensitive data and leave your latest commit untouched), run:
bfg --delete-files YOUR-FILE-WITH-SENSITIVE-DATA
To replace all text listed in passwords.txt wherever it can be found in your repository's history, run:
bfg --replace-text passwords.txt
See the BFG Repo-Cleaner's documentation for full usage and download instructions.
jupyter kernelspec remove
now exists, see #7934.
So you can just.
# List all kernels and grap the name of the kernel you want to remove
jupyter kernelspec list
# Remove it
jupyter kernelspec remove <kernel_name>
That's it.
You need to float all the buttons to left and make sure its width to fit within outer container.
CSS:
.btn{
float:left;
}
HTML:
<button type="submit" class="btn" onClick="return false;" >Save</button>
<button type="submit" class="btn" onClick="return false;">Publish</button>
<button class="btn">Back</button>
For me the easiest solution was this:
map.fitBounds(bounds);
function set_zoom() {
if(map.getZoom()) {map.setZoom(map.getZoom() - 1);}
else {setTimeout(set_zoom, 5);}
}
setTimeout(set_zoom, 5);
The answer with for
is correct, but if you really want to use functional style avoiding for
statement - you can use the following instead of your expression:
Array.from(Array(1000000), () => Math.random());
The Array.from() method creates a new Array instance from an array-like or iterable object. The second argument of this method is a map function to call on every element of the array.
Following the same idea you can rewrite it using ES2015 Spread operator:
[...Array(1000000)].map(() => Math.random())
In both examples you can get an index of the iteration if you need, for example:
[...Array(1000000)].map((_, i) => i + Math.random())
@Scripts.Render("~/favicon.ico"); Please try above code at the bottom of your Layout file in MVC
You might look at how pygame handles this to steal some ideas.
for Arabic language
var table = $('#my_table')
.DataTable({
"columns":{//......}
"language":
{
"sProcessing": "???? ???????...",
"sLengthMenu": "???? _MENU_ ??????",
"sZeroRecords": "?? ???? ??? ??? ?????",
"sInfo": "????? _START_ ??? _END_ ?? ??? _TOTAL_ ????",
"sInfoEmpty": "???? 0 ??? 0 ?? ??? 0 ???",
"sInfoFiltered": "(?????? ?? ????? _MAX_ ?????)",
"sInfoPostFix": "",
"sSearch": "????:",
"sUrl": "",
"oPaginate": {
"sFirst": "?????",
"sPrevious": "??????",
"sNext": "??????",
"sLast": "??????"
}
}
});
Ref: https://datatables.net/plug-ins/i18n/Arabic
Author: Ossama Khayat
It's possible, as addressed in Issue #7396:
When you do want to insert a
<br />
break tag using Markdown, you end a line with two or more spaces, then type return or Enter.
If it is something that you reference but never mutate, then use const
:
declare const bootbox;
I wrote rabbitmq-dump-queue which allows dumping messages from a RabbitMQ queue to local files and requeuing the messages in their original order.
Example usage (to dump the first 50 messages of queue incoming_1
):
rabbitmq-dump-queue -url="amqp://user:[email protected]:5672/" -queue=incoming_1 -max-messages=50 -output-dir=/tmp
I would use ruby-build
with rbenv
. The following lines install Ruby 3.0.0 and set it as your default Ruby version:
$ brew update
$ brew install ruby-build
$ brew install rbenv
$ rbenv install 3.0.0
$ rbenv global 3.0.0
First of all, you do not have to develop any form yourself : phpMyAdmin, depending on its configuration (i.e. config.inc.php
) will display an identification form, asking for a login and password.
To get that form, you should not use :
$cfg['Servers'][$i]['auth_type'] = 'config';
But you should use :
$cfg['Servers'][$i]['auth_type'] = 'cookie';
(At least, that's what I have on a server which prompts for login/password, using a form)
For more informations, you can take a look at the documentation :
'config'
authentication ($auth_type = 'config'
) is the plain old way: username and password are stored in config.inc.php.'cookie'
authentication mode ($auth_type = 'cookie'
) as introduced in 2.2.3 allows you to log in as any valid MySQL user with the help of cookies.
Username and password are stored in cookies during the session and password is deleted when it ends.
Go to project directory then follow below steps.
step 1: rename file .env.example `to .env
mv .env.example .env (for linux)
step 2: php artisan key:generate
You should put this line in your application context:
<context:component-scan base-package="com.cinebot.service" />
Read more about Automatically detecting classes and registering bean definitions in documentation.
Laravel 5.2+ solution.
Model::getQuery()->delete();
Just grab underlying builder with table name and do whatever. Couldn't be any tidier than that.
Laravel 5.6 solution
\App\Model::query()->delete();
Try (untested):
$.getJSON("data.php", function(data){
$.each(data.justIn, function() {
$.each(this, function(k, v) {
alert(k + ' ' + v);
});
});
$.each(data.recent, function() {
$.each(this, function(k, v) {
alert(k + ' ' + v);
});
});
$.each(data.old, function() {
$.each(this, function(k, v) {
alert(k + ' ' + v);
});
});
});
I figured, three separate loops since you'll probably want to treat each dataset differently (justIn, recent, old). If not, you can do:
$.getJSON("data.php", function(data){
$.each(data, function(k, v) {
alert(k + ' ' + v);
$.each(v, function(k1, v1) {
alert(k1 + ' ' + v1);
});
});
});
Sorry to jump on this question late in the game but I have an answer for irregular (non-rectangular) shapes. I solved it using SVGs to generate masks of where I want to have the event attached.
The idea is to attach events to inlined SVGs, super cheap and even user friendly because there are plenty of programs for generating SVGs. The SVG can have a layer of the image as a background.
http://jcrogel.com/code/2015/03/18/mapping-images-using-javascript-events/
If you're looking to paginate results, use the integrated paginator, it works great!
$games = Game::paginate(30);
// $games->results = the 30 you asked for
// $games->links() = the links to next, previous, etc pages
My similar issue was caused by having special characters (e.g. periods) in the selector.
The fix was to escape the special characters:
$("#dots\\.er\\.bad").val("mmmk");
I'd agree it is interesting to propose a particular style of working. However, unless I have the chance to set the style, I usually follow what's been done for consistency.
Taking a look at the Linux Kernel Commits, the project that started git if you like, http://git.kernel.org/?p=linux/kernel/git/torvalds/linux-2.6.git;a=commit;h=bca476139d2ded86be146dae09b06e22548b67f3, they don't follow the 50/72 rule. The first line is 54 characters.
I would say consistency matters. Set up proper means of identifying users who've made commits (user.name, user.email - especially on internal networks. User@OFFICE-1-PC-10293982811111 isn't a useful contact address). Depending on the project, make the appropriate detail available in the commit. It's hard to say what that should be; it might be tasks completed in a development process, then details of what's changed.
I don't believe users should use git one way because certain interfaces to git treat the commits in certain ways.
I should also note there are other ways to find commits. For a start, git diff
will tell you what's changed. You can also do things like git log --pretty=format:'%T %cN %ce'
to format the options of git log
.
Java Heap Memory is part of memory allocated to JVM by Operating System.
Objects reside in an area called the heap. The heap is created when the JVM starts up and may increase or decrease in size while the application runs. When the heap becomes full, garbage is collected.
You can find more details about Eden Space, Survivor Space, Tenured Space and Permanent Generation in below SE question:
Young , Tenured and Perm generation
PermGen has been replaced with Metaspace since Java 8 release.
Regarding your queries:
Codecache: The Java Virtual Machine (JVM) generates native code and stores it in a memory area called the codecache. The JVM generates native code for a variety of reasons, including for the dynamically generated interpreter loop, Java Native Interface (JNI) stubs, and for Java methods that are compiled into native code by the just-in-time (JIT) compiler. The JIT is by far the biggest user of the codecache.
If you would need to escape special characters like '_' (underscore), as it was in my case, and you are not willing/not able to define an ESCAPE clause, you may wish to enclose the special character with square brackets '[' and ']'.
This explains the meaning of the "weird" string '[[]' - it just embraces the '[' character with square brackets, effectively escaping it.
My use case was to specify the name of a stored procedure with underscores in it as a filter criteria for the Profiler. So I've put string '%name[_]of[_]a[_]stored[_]procedure%' in a TextData LIKE field and it gave me trace results I wanted to achieve.
Here is a good example from the documentation: LIKE (Transact-SQL) - Using Wildcard Characters As Literals
In Excel VBA, this function will give you the content of any cell in any worksheet.
Function getCellContent(Byref ws As Worksheet, ByVal rowindex As Integer, ByVal colindex As Integer) as String
getCellContent = CStr(ws.Cells(rowindex, colindex))
End Function
So if you want to check the value of cells, just put the function in a loop, give it the reference to the worksheet you want and the row index and column index of the cell. Row index and column index both start from 1, meaning that cell A1 will be ws.Cells(1,1) and so on.
This should strip away the date part:
select convert(datetime,convert(float, getdate()) - convert(int,getdate())), getdate()
and return a datetime with a default date of 1900-01-01.
For any Solaris users (am using 5.10, may apply to newer versions too, as well as other unix systems):
dos2unix doesn't default to overwriting the file, it will just print the updated version to stdout, so you will have to specify the source and target, i.e. the same name twice:
find . -type f -exec dos2unix {} {} \;
This is for Swift 3 running Xcode 8.2.1 ( 8C1002 )
The best solution that I've found is to set a fixed width in your Storyboard or IB on the label. Set your constraints with constrain to margins. In your viewDidLoad add the following lines of code:
override func viewDidLoad() {
super.viewDidLoad()
label.numberOfLines = 1
label.adjustsFontSizeToFitWidth = true
label.minimumScaleFactor = 0.5
}
This worked like a charm and it doesn't overflow to a new line and shrinks the text to fit the width of the label without any weird issues and works in Swift 3.