This answer is similar to others with requests
and BeautifulSoup
, but using list comprehension.
Because find_all()
is the most popular method in the Beautiful Soup search API, you can use soup("a")
as a shortcut of soup.findAll("a")
and using list comprehension:
import requests
from bs4 import BeautifulSoup
URL = "http://www.yourwebsite.com"
page = requests.get(URL)
soup = BeautifulSoup(page.content, features='lxml')
# Find links
all_links = [link.get("href") for link in soup("a")]
# Only external links
ext_links = [link.get("href") for link in soup("a") if "http" in link.get("href")]
https://www.crummy.com/software/BeautifulSoup/bs4/doc/#calling-a-tag-is-like-calling-find-all
echo '<a href="' . $folder_path . '">Link text</a>';
Please note that you must use the path relative to your domain and, if the folder path is outside the public htdocs directory, it will not work.
EDIT: maybe i misreaded the question; you have a file on your pc and want to insert the path on the html page, and then send it to the server?
printAccountSummary: function()
{return "Welcome!" + "\n" + "Your balance is currently $1000 and your interest rate is 1%."}
};
console.log(savingsAccount.printAccountSummary()); // method
Prints:
Welcome!
Your balance is currently $1000 and your interest rate is 1%.
I might be missing something, but afaik, you get undefined
only
Update: Ok, I missed a lot, trying to complete:
You get undefined
...
... when you try to access properties of an object that don't exist:
var a = {}
a.foo // undefined
... when you have declared a variable but not initialized it:
var a;
// a is undefined
... when you access a parameter for which no value was passed:
function foo (a, b) {
// something
}
foo(42); // b inside foo is undefined
... when a function does not return a value:
function foo() {};
var a = foo(); // a is undefined
It might be that some built-in functions return null
on some error, but if so, then it is documented. null
is a concrete value in JavaScript, undefined
is not.
Normally you don't need to distinguish between those. Depending on the possible values of a variable, it is sufficient to use if(variable)
to test whether a value is set or not (both, null
and undefined
evaluate to false
).
Also different browsers seem to be returning these differently.
Please give a concrete example.
std::string str(buffer, buffer + length);
Or, if the string already exists:
str.assign(buffer, buffer + length);
Edit: I'm still not completely sure I understand the question. But if it's something like what JoshG is suggesting, that you want up to length
characters, or until a null terminator, whichever comes first, then you can use this:
std::string str(buffer, std::find(buffer, buffer + length, '\0'));
Using jQuery only (no UI library/plugin). Even jQuery can be easily eliminated
//Color row background in HSL space (easier to manipulate fading)
$('tr').eq(1).css('backgroundColor','hsl(0,100%,50%');
var d = 1000;
for(var i=50; i<=100; i=i+0.1){ //i represents the lightness
d += 10;
(function(ii,dd){
setTimeout(function(){
$('tr').eq(1).css('backgroundColor','hsl(0,100%,'+ii+'%)');
}, dd);
})(i,d);
}
Demo : http://jsfiddle.net/5NB3s/2/
You possibly do not have create permissions to the folder. So WinSCP fails to create a temporary file for the transfer.
You have two options:
Grant write permissions to the folder to the user or group you log in with (myuser
), or change the ownership of the folder to the user, or
Disable a transfer to temporary file.
In Preferences, go to Transfer > Endurance page and in Enable transfer resume/transfer to temporary file name for select Disable:
Sorry if this is old but I just found a solution.
Try setting the font-size
to 0. Thus the white-spaces in between the images will be 0 in width, and the images won't be affected.
Don't know if this works in all browsers, but I tried it with Chromium and some <li>
elements with display: inline-block;
.
The simple answer is that there is no such function.
The closest thing you have is:
var millisecondsToWait = 500;
setTimeout(function() {
// Whatever you want to do after the wait
}, millisecondsToWait);
Note that you especially don't want to busy-wait (e.g. in a spin loop), since your browser is almost certainly executing your JavaScript in a single-threaded environment.
Here are a couple of other SO questions that deal with threads in JavaScript:
And this question may also be helpful:
While, most other answers here are valid. Sometimes, it's best to just make a short simple function near where you will use it.
// indexOf wrapper for the list of objects
function indexOfbyKey(obj_list, key, value) {
for (index in obj_list) {
if (obj_list[index][key] === value) return index;
}
return -1;
}
// Find the string in the list (default -1)
var test1 = indexOfbyKey(object_list, 'name', 'Stevie');
var test2 = indexOfbyKey(object_list, 'last_name', 'some other name');
It depends on what is important to you. It might save lines of code and be very clever to use a one-liner, or to put a generic solution somewhere that covers various edge cases. But sometimes it's better to just say: "here I did it like this" rather than leave future developers to have extra reverse engineering work. Especially if you consider yourself "a newbie" like in your question.
After facing a similar issue, below is what I did :
To the CORS filter, I added corsFilter.getAllowedOrigins().add("http://localhost:4200");
.
Basically, you should add the URL which you want to allow Cross-Origin Resource Sharing. Ans you can also use "*"
instead of any specific URL to allow any URL.
public class RestApplication
extends Application
{
private Set<Object> singletons = new HashSet<Object>();
public MessageApplication()
{
singletons.add(new CalculatorService()); //CalculatorService is your specific service you want to add/use.
CorsFilter corsFilter = new CorsFilter();
// To allow all origins for CORS add following, otherwise add only specific urls.
// corsFilter.getAllowedOrigins().add("*");
System.out.println("To only allow restrcited urls ");
corsFilter.getAllowedOrigins().add("http://localhost:4200");
singletons = new LinkedHashSet<Object>();
singletons.add(corsFilter);
}
@Override
public Set<Object> getSingletons()
{
return singletons;
}
}
<web-app id="WebApp_ID" version="2.4"
xmlns="http://java.sun.com/xml/ns/j2ee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee
http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
<display-name>Restful Web Application</display-name>
<!-- Auto scan rest service -->
<context-param>
<param-name>resteasy.scan</param-name>
<param-value>true</param-value>
</context-param>
<context-param>
<param-name>resteasy.servlet.mapping.prefix</param-name>
<param-value>/rest</param-value>
</context-param>
<listener>
<listener-class>
org.jboss.resteasy.plugins.server.servlet.ResteasyBootstrap
</listener-class>
</listener>
<servlet>
<servlet-name>resteasy-servlet</servlet-name>
<servlet-class>
org.jboss.resteasy.plugins.server.servlet.HttpServletDispatcher
</servlet-class>
<init-param>
<param-name>javax.ws.rs.Application</param-name>
<param-value>com.app.RestApplication</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>resteasy-servlet</servlet-name>
<url-pattern>/rest/*</url-pattern>
</servlet-mapping>
</web-app>
The most important code which I was missing when I was getting this issue was, I was not adding my class extending javax.ws.rs.Application i.e RestApplication to the init-param of <servlet-name>resteasy-servlet</servlet-name>
<init-param>
<param-name>javax.ws.rs.Application</param-name>
<param-value>com.app.RestApplication</param-value>
</init-param>
And therefore my Filter was not able to execute and thus the application was not allowing CORS from the URL specified.
I face similar issue while importing TensorFlow
. If you are using Tensorflow which uses Pandas library, I suggest restarting your kernel of Anaconda
. This works for me.
I think that Spring Data ignores the FetchMode. I always use the @NamedEntityGraph
and @EntityGraph
annotations when working with Spring Data
@Entity
@NamedEntityGraph(name = "GroupInfo.detail",
attributeNodes = @NamedAttributeNode("members"))
public class GroupInfo {
// default fetch mode is lazy.
@ManyToMany
List<GroupMember> members = new ArrayList<GroupMember>();
…
}
@Repository
public interface GroupRepository extends CrudRepository<GroupInfo, String> {
@EntityGraph(value = "GroupInfo.detail", type = EntityGraphType.LOAD)
GroupInfo getByGroupName(String name);
}
Check the documentation here
Install PAR::Packer from CPAN (it is free) and use pp utility.
To continue using the iframe YouTube, you should only have to change ?autoplay=1
to ?autoplay=0
.
Another way to accomplish this would be by using the YouTube JavaScript Player API. (https://developers.google.com/youtube/js_api_reference)
Edit: the YouTube JavaScript Player API is no longer supported.
<div id="howToVideo"></div>
<script type="application/javascript">
var ga = document.createElement('script');
ga.type = 'text/javascript';
ga.async = false;
ga.src = 'http://www.youtube.com/player_api';
var s = document.getElementsByTagName('script')[0];
s.parentNode.insertBefore(ga, s);
var done = false;
var player;
function onYouTubePlayerAPIReady() {
player = new YT.Player('howToVideo', {
height: '390',
width: '640',
videoId: 'qUJYqhKZrwA',
playerVars: {
controls: 0,
disablekb: 1
},
events: {
'onReady': onPlayerReady,
'onStateChange': onPlayerStateChange
}
});
}
function onPlayerReady(evt) {
console.log('onPlayerReady', evt);
}
function onPlayerStateChange(evt) {
console.log('onPlayerStateChange', evt);
if (evt.data == YT.PlayerState.PLAYING && !done) {
setTimeout(stopVideo, 6000);
done = true;
}
}
function stopVideo() {
console.log('stopVideo');
player.stopVideo();
}
</script>
Here is a jsfiddle for the example: http://jsfiddle.net/fgkrj/
Note that player controls are disabled in the "playerVars" part of the player. The one sacrifice you make is that users are still able to pause the video by clicking on it. I would suggest writing a simple javascript function that subscribes to a stop event and calls player.playVideo()
.
Include the following function at the start of your code, whenever you want to busy wait. This is distinct from sleep, because the process will be utilizing 100% cpu while this function is running.
void sleep(unsigned int mseconds)
{
clock_t goal = mseconds + clock();
while (goal > clock())
;
}
Note that the name sleep
for this function is misleading, since the CPU will not be sleeping at all.
This may be cleaner (you dont need all the into
statements):
var query =
from order in dc.Orders
from vendor
in dc.Vendors
.Where(v => v.Id == order.VendorId)
.DefaultIfEmpty()
from status
in dc.Status
.Where(s => s.Id == order.StatusId)
.DefaultIfEmpty()
select new { Order = order, Vendor = vendor, Status = status }
//Vendor and Status properties will be null if the left join is null
Here is another left join example
var results =
from expense in expenseDataContext.ExpenseDtos
where expense.Id == expenseId //some expense id that was passed in
from category
// left join on categories table if exists
in expenseDataContext.CategoryDtos
.Where(c => c.Id == expense.CategoryId)
.DefaultIfEmpty()
// left join on expense type table if exists
from expenseType
in expenseDataContext.ExpenseTypeDtos
.Where(e => e.Id == expense.ExpenseTypeId)
.DefaultIfEmpty()
// left join on currency table if exists
from currency
in expenseDataContext.CurrencyDtos
.Where(c => c.CurrencyID == expense.FKCurrencyID)
.DefaultIfEmpty()
select new
{
Expense = expense,
// category will be null if join doesn't exist
Category = category,
// expensetype will be null if join doesn't exist
ExpenseType = expenseType,
// currency will be null if join doesn't exist
Currency = currency
}
Just do:
git push origin <your_branch_name> --force
or if you have a specific repo:
git push https://git.... --force
This will delete your previous commit(s) and push your current one.
It may not be proper, but if anyone stumbles upon this page, thought they might want a simple solution...
Also note that -f
is short for --force
, so
git push origin <your_branch_name> -f
will also work.
For IE 6, you'll want to equal colspan to the number of columns in your table. If you have 5 columns, then you'll want: colspan="5"
.
The reason is that IE handles colspans differently, it uses the HTML 3.2 specification:
IE implements the HTML 3.2 definition, it sets
colspan=0
ascolspan=1
.
The bug is well documented.
Firstly, you should use randrange(0,1000)
or randint(0,999)
, not randint(0,1000)
. The upper limit of randint
is inclusive.
For efficiently, randint
is simply a wrapper of randrange
which calls random
, so you should just use random
. Also, use xrange
as the argument to sample
, not range
.
You could use
[a for a in sample(xrange(1000),1000) for _ in range(10000/1000)]
to generate 10,000 numbers in the range using sample
10 times.
(Of course this won't beat NumPy.)
$ python2.7 -m timeit -s 'from random import randrange' '[randrange(1000) for _ in xrange(10000)]'
10 loops, best of 3: 26.1 msec per loop
$ python2.7 -m timeit -s 'from random import sample' '[a%1000 for a in sample(xrange(10000),10000)]'
100 loops, best of 3: 18.4 msec per loop
$ python2.7 -m timeit -s 'from random import random' '[int(1000*random()) for _ in xrange(10000)]'
100 loops, best of 3: 9.24 msec per loop
$ python2.7 -m timeit -s 'from random import sample' '[a for a in sample(xrange(1000),1000) for _ in range(10000/1000)]'
100 loops, best of 3: 3.79 msec per loop
$ python2.7 -m timeit -s 'from random import shuffle
> def samplefull(x):
> a = range(x)
> shuffle(a)
> return a' '[a for a in samplefull(1000) for _ in xrange(10000/1000)]'
100 loops, best of 3: 3.16 msec per loop
$ python2.7 -m timeit -s 'from numpy.random import randint' 'randint(1000, size=10000)'
1000 loops, best of 3: 363 usec per loop
But since you don't care about the distribution of numbers, why not just use:
range(1000)*(10000/1000)
?
used https://www.npmjs.com/package/uniqid in npm
npm i uniqid
It will always create unique id's based on the current time, process and machine name.
Features:-
Just using this code: If you want backpressed disable, you dont use super.OnBackPressed();
@Override
public void onBackPressed() {
}
In my case the following was necessary:
sudo chgrp vboxsf /media/sf_sharedFolder
take look at this sample code from my project
public static IList<Letter> GetDepartmentLettersLinq(int departmentId)
{
IEnumerable<Letter> allDepartmentLetters =
from allLetter in LetterService.GetAllLetters()
join allUser in UserService.GetAllUsers() on allLetter.EmployeeID equals allUser.ID into usersGroup
from user in usersGroup.DefaultIfEmpty()// here is the tricky part
join allDepartment in DepartmentService.GetAllDepartments() on user.DepartmentID equals allDepartment.ID
where allDepartment.ID == departmentId
select allLetter;
return allDepartmentLetters.ToArray();
}
in this code I joined 3 tables and I spited join condition from where clause
note: the Services classes are just warped(encapsulate) the database operations
While this is possible, you should not use the Flask dev server in production. The Flask dev server is not designed to be particularly secure, stable, or efficient. See the docs on deploying for correct solutions.
Add a parameter to your app.run()
. By default it runs on localhost
, change it to app.run(host= '0.0.0.0')
to run on all your machine's IP addresses. 0.0.0.0
is a special value, you'll need to navigate to the actual IP address.
Documented on the Flask site under "Externally Visible Server" on the Quickstart page:
Externally Visible Server
If you run the server you will notice that the server is only available from your own computer, not from any other in the network. This is the default because in debugging mode a user of the application can execute arbitrary Python code on your computer. If you have debug disabled or trust the users on your network, you can make the server publicly available.
Just change the call of the
run()
method to look like this:
app.run(host='0.0.0.0')
This tells your operating system to listen on a public IP.
Actually, you can process the find
command output in a copy command in two ways:
If the find
command's output doesn't contain any space, i.e if the filename doesn't contain a space in it, then you can use:
Syntax:
find <Path> <Conditions> | xargs cp -t <copy file path>
Example:
find -mtime -1 -type f | xargs cp -t inner/
But our production data files might contain spaces, so most of time this command is effective:
Syntax:
find <path> <condition> -exec cp '{}' <copy path> \;
Example
find -mtime -1 -type f -exec cp '{}' inner/ \;
In the second example, the last part, the semi-colon is also considered as part of the find
command, and should be escaped before pressing Enter. Otherwise you will get an error something like:
find: missing argument to `-exec'
If you want to make it easier on yourself, there are CentOS RPMs for new Python versions floating around the net. E.g. see:
If you're using ASP.NET MVC and Web API chances are you have the Newtonsoft.Json NuGet package installed.This library has a class called JObject which allows you to pass through multiple parameters:
Api Controller:
public class ProductController : ApiController
{
[HttpPost]
public void Post(Newtonsoft.Json.Linq.JObject data)
{
System.Diagnostics.Debugger.Break();
Product product = data["product"].ToObject<Product>();
Product product2 = data["product2"].ToObject<Product>();
int someRandomNumber = data["randomNumber"].ToObject<int>();
string productName = product.ProductName;
string product2Name = product2.ProductName;
}
}
public class Product
{
public int ProductID { get; set; }
public string ProductName { get; set; }
}
View:
<script src="~/Scripts/angular.js"></script>
<script type="text/javascript">
var myApp = angular.module("app", []);
myApp.controller('controller', function ($scope, $http) {
$scope.AddProducts = function () {
var product = {
ProductID: 0,
ProductName: "Orange",
}
var product2 = {
ProductID: 1,
ProductName: "Mango",
}
var data = {
product: product,
product2: product2,
randomNumber:12345
};
$http.post("/api/Product", data).
success(function (data, status, headers, config) {
}).
error(function (data, status, headers, config) {
alert("An error occurred during the AJAX request");
});
}
});
</script>
<div ng-app="app" ng-controller="controller">
<input type="button" ng-click="AddProducts()" value="Get Full Name" />
</div>
jQuery hover function gives mouseover and mouseout functionality.
$(".item-image").hover(function () {
// mouseover event codes...
}, function () {
// mouseout event codes...
});
Do configure --help
and see what other options are available.
It is very common to provide different options to override different locations. By standard, --prefix
overrides all of them, so you need to override config location after specifying the prefix. This course of actions usually works for every automake-based project.
The worse case scenario is when you need to modify the configure script, or even worse, generated makefiles and config.h headers. But yeah, for Xfce you can try something like this:
./configure --prefix=/home/me/somefolder/mybuild/output/target --sysconfdir=/etc
I believe that should do it.
Using the python-varname
package, you can easily retrieve the name of the variables
https://github.com/pwwang/python-varname
As of v0.6.0
, in your case, you can do:
from varname.helpers import Wrapper
foo = Wrapper(dict())
# foo.name == 'foo'
# foo.value == {}
foo.value['bar'] = 2
For list comprehension part, you can do:
n_jobs = Wrapper(<original_value>)
users = Wrapper(<original_value>)
queues = Wrapper(<original_value>)
priorities = Wrapper(<original_value>)
list_of_dicts = [n_jobs, users, queues, priorities]
columns = [d.name for d in list_of_dicts]
# ['n_jobs', 'users', 'queues', 'priorities']
# REMEMBER that you have to access the <original_value> by d.value
You can also try to retrieve the variable name DIRECTLY:
from varname import nameof
foo = dict()
fooname = nameof(foo)
# fooname == 'foo'
Note that this is working in this case as you expected:
n_jobs = <original_value>
d = n_jobs
nameof(d) # will return d, instead of n_jobs
# nameof only works directly with the variable
I am the author of this package. Please let me know if you have any questions or you can submit issues on Github.
hash = { :a => ["a", "b", "c"], :b => ["b", "c"] }
hash.values #=> [["a","b","c"],["b","c"]]
Found this answer here and wanted to reference it as it appear much cleaner than the accepted answer:
function blobToDataURL(blob, callback) {
var fileReader = new FileReader();
fileReader.onload = function(e) {callback(e.target.result);}
fileReader.readAsDataURL(blob);
}
simple way is to move your files to be read under the same folder of your python file, then you just need to use the name of the file, without calling another path.
This code works:
$(".ui-button-text").live(
'hover',
function (ev) {
if (ev.type == 'mouseover') {
$(this).addClass("ui-state-hover");
}
if (ev.type == 'mouseout') {
$(this).removeClass("ui-state-hover");
}
});
Stack memory is specifically the range of memory that is accessible via the Stack register of the CPU. The Stack was used as a way to implement the "Jump-Subroutine"-"Return" code pattern in assembly language, and also as a means to implement hardware-level interrupt handling. For instance, during an interrupt, the Stack was used to store various CPU registers, including Status (which indicates the results of an operation) and Program Counter (where was the CPU in the program when the interrupt occurred).
Stack memory is very much the consequence of usual CPU design. The speed of its allocation/deallocation is fast because it is strictly a last-in/first-out design. It is a simple matter of a move operation and a decrement/increment operation on the Stack register.
Heap memory was simply the memory that was left over after the program was loaded and the Stack memory was allocated. It may (or may not) include global variable space (it's a matter of convention).
Modern pre-emptive multitasking OS's with virtual memory and memory-mapped devices make the actual situation more complicated, but that's Stack vs Heap in a nutshell.
Try this:
$("a").each(function() {
if ($('[href$="?"]', this).length()) {
alert("Contains questionmark");
}
});
You can not count nulls (at least not in Oracle). Instead try this
SELECT count(1) FROM TABLE WHERE COL_NAME IS NULL
This is a refined and better performing variant:
String.prototype.hashCode = function() {
var hash = 0, i = 0, len = this.length;
while ( i < len ) {
hash = ((hash << 5) - hash + this.charCodeAt(i++)) << 0;
}
return hash;
};
This matches Java's implementation of the standard object.hashCode()
Here is also one that returns only positive hashcodes:
String.prototype.hashcode = function() {
return (this.hashCode() + 2147483647) + 1;
};
And here is a matching one for Java that only returns positive hashcodes:
public static long hashcode(Object obj) {
return ((long) obj.hashCode()) + Integer.MAX_VALUE + 1l;
}
Enjoy!
Without prototype:
function hashCode(str) {
var hash = 0, i = 0, len = str.length;
while ( i < len ) {
hash = ((hash << 5) - hash + str.charCodeAt(i++)) << 0;
}
return hash;
}
// Function for basic field validation (present and neither empty nor only white space
function IsNullOrEmptyString($str){
return (!isset($str) || trim($str) === '');
}
Do this:
$checksum = "my value";
header("Location: recordupdated.php?checksum=$checksum");
seeing it in digital circuit domain
so it completely depends on your use whether you need to create a register and tick it according to sensitivity list or you want to create a port/pin assignment
In the context of ASP.Net a Web API is a Controller whose base class is ApiController and does not use Views. A Web Service is a class derived from WebService and has automatic WSDL generation. By default it is a SOAP api, but you can also use JSON by adding a ScriptServiceAttribute.
From command prompt Run as Administrator. Example below is to print a list of Services running on your PC run the command below:
net start > c:\netstart.txt
You should see a copy of the text file you just exported with a listing all the PC services running at the root of your C:\
drive.
BufferedReader br = null;
try {
String fpath = Environment.getExternalStorageDirectory() + <your file name>;
try {
br = new BufferedReader(new FileReader(fpath));
} catch (FileNotFoundException e1) {
e1.printStackTrace();
}
String line = "";
while ((line = br.readLine()) != null) {
//Do something here
}
1.Very Simple Code to iterate datatable and get columns in list.
2.code ==>>>
foreach (DataColumn dataColumn in dataTable.Columns)
{
var list = dataTable.Rows.OfType<DataRow>()
.Select(dataRow => dataRow.Field<string>
(dataColumn.ToString())).ToList();
}
Their feature sets are not at all the same. Sqlite is an embedded database which has no network capabilities (unless you add them). So you can't use it on a network.
If you need
You need to use mysql or some other server-based RDBMS.
Note that MySQL is not the only choice and there are plenty of others which might be better for new applications (for example pgSQL).
Sqlite is a very, very nice piece of software, but it has never made claims to do any of these things that RDBMS servers do. It's a small library which runs SQL on local files (using locking to ensure that multiple processes don't screw the file up). It's really well tested and I like it a lot.
Also, if you aren't able to choose this correctly by yourself, you probably need to hire someone on your team who can.
The answer is given but think that for some situation this will be also interesting way to get string from NSInteger
NSInteger value = 12;
NSString * string = [NSString stringWithFormat:@"%0.0f", (float)value];
Or you can just use this library to get all errors, even from deep and dynamic forms.
npm i @naologic/forms
If you want to use the static function on your own forms
import {NaoFormStatic} from '@naologic/forms';
...
const errorsFlat = NaoFormStatic.getAllErrorsFlat(fg);
console.log(errorsFlat);
If you want to use NaoFromGroup
you can import and use it
import {NaoFormGroup, NaoFormControl, NaoValidators} from '@naologic/forms';
...
this.naoFormGroup = new NaoFormGroup({
firstName: new NaoFormControl('John'),
lastName: new NaoFormControl('Doe'),
ssn: new NaoFormControl('000 00 0000', NaoValidators.isSSN()),
});
const getFormErrors = this.naoFormGroup.getAllErrors();
console.log(getFormErrors);
// --> {first: {ok: false, isSSN: false, actualValue: "000 00 0000"}}
Read the full documentation
Here is an option using dplyr
. The %<>%
operator from magrittr
update the lhs object with the resulting value.
library(magrittr)
library(dplyr)
cols <- c("A", "C", "D", "H")
data %<>%
mutate_each_(funs(factor(.)),cols)
str(data)
#'data.frame': 4 obs. of 10 variables:
# $ A: Factor w/ 4 levels "23","24","26",..: 1 2 3 4
# $ B: int 15 13 39 16
# $ C: Factor w/ 4 levels "3","5","18","37": 2 1 3 4
# $ D: Factor w/ 4 levels "2","6","28","38": 3 1 4 2
# $ E: int 14 4 22 20
# $ F: int 7 19 36 27
# $ G: int 35 40 21 10
# $ H: Factor w/ 4 levels "11","29","32",..: 1 4 3 2
# $ I: int 17 1 9 25
# $ J: int 12 30 8 33
Or if we are using data.table
, either use a for
loop with set
setDT(data)
for(j in cols){
set(data, i=NULL, j=j, value=factor(data[[j]]))
}
Or we can specify the 'cols' in .SDcols
and assign (:=
) the rhs to 'cols'
setDT(data)[, (cols):= lapply(.SD, factor), .SDcols=cols]
Most answers here either require a clean working directory and multiple interactive steps (bad for scripting), or don't work for all cases, e.g. past merges which already bring some of the outstanding changes into your target branch, or cherry-picks doing the same.
To truly see what would change in the master
branch if you merged develop
into it, right now:
git merge-tree $(git merge-base master develop) master develop
As it's a plumbing command, it does not guess what you mean, you have to be explicit. It also doesn't colorize the output or use your pager, so the full command would be:
git merge-tree $(git merge-base master develop) master develop | colordiff | less -R
— https://git.seveas.net/previewing-a-merge-result.html
(thanks to David Normington for the link)
P.S.:
If you would get merge conflicts, they will show up with the usual conflict markers in the output, e.g.:
$ git merge-tree $(git merge-base a b ) a b
added in both
our 100644 78981922613b2afb6025042ff6bd878ac1994e85 a
their 100644 61780798228d17af2d34fce4cfbdf35556832472 a
@@ -1 +1,5 @@
+<<<<<<< .our
a
+=======
+b
+>>>>>>> .their
User @dreftymac makes a good point: this makes it unsuitable for scripting, because you can't easily catch that from the status code. The conflict markers can be quite different depending on circumstance (deleted vs modified, etc), which makes it hard to grep, too. Beware.
The problem is somewhere else in your code, because this works:
string line("test\ttest2\ttest3");
vector<string> strs;
boost::split(strs,line,boost::is_any_of("\t"));
cout << "* size of the vector: " << strs.size() << endl;
for (size_t i = 0; i < strs.size(); i++)
cout << strs[i] << endl;
and testing your approach, which uses a vector iterator also works:
string line("test\ttest2\ttest3");
vector<string> strs;
boost::split(strs,line,boost::is_any_of("\t"));
cout << "* size of the vector: " << strs.size() << endl;
for (vector<string>::iterator it = strs.begin(); it != strs.end(); ++it)
{
cout << *it << endl;
}
Again, your problem is somewhere else. Maybe what you think is a \t
character on the string, isn't. I would fill the code with debugs, starting by monitoring the insertions on the vector to make sure everything is being inserted the way its supposed to be.
Output:
* size of the vector: 3
test
test2
test3
The problem is that you are attempting to define the elements in lists to multiple lists (not multiple ints as is defined). You should be defining lists like this.
int[,] list = new int[4,4] {
{1,2,3,4},
{5,6,7,8},
{1,3,2,1},
{5,4,3,2}};
You could also do
int[] list1 = new int[4] { 1, 2, 3, 4};
int[] list2 = new int[4] { 5, 6, 7, 8};
int[] list3 = new int[4] { 1, 3, 2, 1 };
int[] list4 = new int[4] { 5, 4, 3, 2 };
int[,] lists = new int[4,4] {
{list1[0],list1[1],list1[2],list1[3]},
{list2[0],list2[1],list2[2],list2[3]},
etc...};
How about:
class MyClass(object):
def __init__(self, filename):
self.filename = filename
self.stats = parse_file(filename)
def parse_file(filename):
#do some parsing
return results_from_parse
By the way, if you have variables named stat1
, stat2
, etc., the situation is begging for a tuple:
stats = (...)
.
So let parse_file
return a tuple, and store the tuple in
self.stats
.
Then, for example, you can access what used to be called stat3
with self.stats[2]
.
I use iText RUPS(Reading and Updating PDF Syntax) in Linux. Since it's written in Java, it works on Windows, too. You can browse all the objects in PDF file in a tree structure. It can also decode Flate encoded streams on-the-fly to make inspecting easier.
Here is a screenshot:
You should use other variable:
$m=0;
for($n=1; $n<=8; $n++):
$n = $n + $m;
$m++;
echo '<p>'. $n .'</p>';
endfor;
As pointed out, your hashcode implementation has too many collisions, and fixing it should result in decent performance. Moreover, caching hashCodes and implementing equals efficiently will help.
If you need to optimize even further:
By your description, there are only (52 * 51 / 2) * (52 * 51 * 50 / 6) = 29304600 different keys (of which 26000000, i.e. about 90%, will be present). Therefore, you can design a hash function without any collisions, and use a simple array rather than a hashmap to hold your data, reducing memory consumption and increasing lookup speed:
T[] array = new T[Key.maxHashCode];
void put(Key k, T value) {
array[k.hashCode()] = value;
T get(Key k) {
return array[k.hashCode()];
}
(Generally, it is impossible to design an efficient, collision-free hash function that clusters well, which is why a HashMap will tolerate collisions, which incurs some overhead)
Assuming a
and b
are sorted, you might use the following hash function:
public int hashCode() {
assert a[0] < a[1];
int ahash = a[1] * a[1] / 2
+ a[0];
assert b[0] < b[1] && b[1] < b[2];
int bhash = b[2] * b[2] * b[2] / 6
+ b[1] * b[1] / 2
+ b[0];
return bhash * 52 * 52 / 2 + ahash;
}
static final int maxHashCode = 52 * 52 / 2 * 52 * 52 * 52 / 6;
I think this is collision-free. Proving this is left as an exercise for the mathematically inclined reader.
if exist C:\VTS\NUL echo "Folder already exists"
if not exist C:\VTS\NUL echo "Folder does not exist"
See also https://support.microsoft.com/en-us/kb/65994
(Update March 7, 2018; Microsoft article is down, archive on https://web.archive.org/web/20150609092521/https://support.microsoft.com/en-us/kb/65994 )
ModelState.IsValid
tells you if any model errors have been added to ModelState
.
The default model binder will add some errors for basic type conversion issues (for example, passing a non-number for something which is an "int"). You can populate ModelState more fully based on whatever validation system you're using.
The sample DataAnnotations
model binder will fill model state with validation errors taken from the DataAnnotations
attributes on your model.
To navigate to the parent component regardless of the number of parameters in the current route or the parent route: Angular 6 update 1/21/19
let routerLink = this._aRoute.parent.snapshot.pathFromRoot
.map((s) => s.url)
.reduce((a, e) => {
//Do NOT add last path!
if (a.length + e.length !== this._aRoute.parent.snapshot.pathFromRoot.length) {
return a.concat(e);
}
return a;
})
.map((s) => s.path);
this._router.navigate(routerLink);
This has the added bonus of being an absolute route you can use with the singleton Router.
(Angular 4+ for sure, probably Angular 2 too.)
I agree with several of the points I've read in this post and I've incorporated them into my solution to solve the exact same issue as the original posting.
That said, the comments I appreciated are:
"unless you are using .NET 1.0 or 1.1, use List<T>
instead of ArrayList
. "
"Also, add the item(s) to be deleted to a new list. Then go through and delete those items." .. in my case I just created a new List and the populated it with the valid data values.
e.g.
private List<string> managedLocationIDList = new List<string>();
string managedLocationIDs = ";1321;1235;;" // user input, should be semicolon seperated list of values
managedLocationIDList.AddRange(managedLocationIDs.Split(new char[] { ';' }));
List<string> checkLocationIDs = new List<string>();
// Remove any duplicate ID's and cleanup the string holding the list if ID's
Functions helper = new Functions();
checkLocationIDs = helper.ParseList(managedLocationIDList);
...
public List<string> ParseList(List<string> checkList)
{
List<string> verifiedList = new List<string>();
foreach (string listItem in checkList)
if (!verifiedList.Contains(listItem.Trim()) && listItem != string.Empty)
verifiedList.Add(listItem.Trim());
verifiedList.Sort();
return verifiedList;
}
According to HTML living standard specification, the load
event is
Fired at the Window when the document has finished loading; fired at an element containing a resource (e.g. img, embed) when its resource has finished loading
I.e. load
event is not fired on document
object.
Credit: Why does document.addEventListener(‘load’, handler) not work?
I'm a fan of gitk
's graphical UI to visualize git repos. You can view the last item stashed with:
gitk stash
You can also use view any of your stashed changes (as listed by git stash list
). For example:
gitk stash@{2}
In the below screenshot, you can see the stash as a commit in the upper-left, when and where it came from in commit history, the list of files modified on the bottom right, and the line-by-line diff in the lower-left. All while the stash is still tucked away.
i know i am late but this is what i got after 1 hour of search
<?php
$file = 'file.pdf';
if (! file) {
die('file not found'); //Or do something
} else {
if(isset($_GET['file'])){
// Set headers
header("Cache-Control: public");
header("Content-Description: File Transfer");
header("Content-Disposition: attachment; filename=$file");
header("Content-Type: application/zip");
header("Content-Transfer-Encoding: binary");
// Read the file from disk
readfile($file); }
}
?>
and for downloadable link i did this
<a href="index.php?file=file.pdf">Download PDF</a>
I have used the exact steps from here and it worked flawlessly : https://docs.microsoft.com/en-us/visualstudio/install/install-vs-inconsistent-quality-network
In 3 simple steps:
Step 1 : Download the respective Visual Studio 2017 version from the download page (https://www.visualstudio.com/downloads/)
Step 2: Open your command prompt as Administarator, point to where your Visual studio download exe is and execute the following command (this command is specifically for Web & Desktop development) :
vs_community.exe --layout c:\vs2017layout --add Microsoft.VisualStudio.Workload.ManagedDesktop --add Microsoft.VisualStudio.Workload.NetWeb --add Component.GitHub.VisualStudio --includeOptional --lang en-US
Step 3 : Traverse to the path c:\vs2017layout in your command prompt and then run the following command (this command is specifically for Web & Desktop development)
vs_community.exe --add Microsoft.VisualStudio.Workload.ManagedDesktop --add Microsoft.VisualStudio.Workload.NetWeb --add Component.GitHub.VisualStudio --includeOptional
Create a file, a.py:
print(__name__) # It will print out __main__
__name__
is always equal to __main__
whenever that file is run directly showing that this is the main file.
Create another file, b.py, in the same directory:
import a # Prints a
Run it. It will print a, i.e., the name of the file which is imported.
So, to show two different behavior of the same file, this is a commonly used trick:
# Code to be run when imported into another python file
if __name__ == '__main__':
# Code to be run only when run directly
Open res -> values -> styles.xml
and to your <style>
add this line replacing with your image path <item name="android:windowBackground">@drawable/background</item>
. Example:
<resources>
<!-- Base application theme. -->
<style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">
<!-- Customize your theme here. -->
<item name="colorPrimary">@color/colorPrimary</item>
<item name="colorPrimaryDark">@color/colorPrimaryDark</item>
<item name="colorAccent">@color/colorAccent</item>
<item name="android:windowBackground">@drawable/background</item>
</style>
</resources>
There is a <item name ="android:colorBackground">@color/black</item>
also, that will affect not only your main window background but all the component in your app. Read about customize theme here.
If you want version specific styles:
If a new version of Android adds theme attributes that you want to use, you can add them to your theme while still being compatible with old versions. All you need is another styles.xml file saved in a values directory that includes the resource version qualifier. For example:
res/values/styles.xml # themes for all versions res/values-v21/styles.xml # themes for API level 21+ only
Because the styles in the values/styles.xml file are available for all versions, your themes in values-v21/styles.xml can inherit them. As such, you can avoid duplicating styles by beginning with a "base" theme and then extending it in your version-specific styles.
If one has to call pd.Series.between(l,r)
repeatedly (for different bounds l
and r
), a lot of work is repeated unnecessarily. In this case, it's beneficial to sort the frame/series once and then use pd.Series.searchsorted()
. I measured a speedup of up to 25x, see below.
def between_indices(x, lower, upper, inclusive=True):
"""
Returns smallest and largest index i for which holds
lower <= x[i] <= upper, under the assumption that x is sorted.
"""
i = x.searchsorted(lower, side="left" if inclusive else "right")
j = x.searchsorted(upper, side="right" if inclusive else "left")
return i, j
# Sort x once before repeated calls of between()
x = x.sort_values().reset_index(drop=True)
# x = x.sort_values(ignore_index=True) # for pandas>=1.0
ret1 = between_indices(x, lower=0.1, upper=0.9)
ret2 = between_indices(x, lower=0.2, upper=0.8)
ret3 = ...
Benchmark
Measure repeated evaluations (n_reps=100
) of pd.Series.between()
as well as the method based on pd.Series.searchsorted()
, for different arguments lower
and upper
. On my MacBook Pro 2015 with Python v3.8.0 and Pandas v1.0.3, the below code results in the following outpu
# pd.Series.searchsorted()
# 5.87 ms ± 321 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
# pd.Series.between(lower, upper)
# 155 ms ± 6.08 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)
# Logical expressions: (x>=lower) & (x<=upper)
# 153 ms ± 3.52 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)
import numpy as np
import pandas as pd
def between_indices(x, lower, upper, inclusive=True):
# Assumption: x is sorted.
i = x.searchsorted(lower, side="left" if inclusive else "right")
j = x.searchsorted(upper, side="right" if inclusive else "left")
return i, j
def between_fast(x, lower, upper, inclusive=True):
"""
Equivalent to pd.Series.between() under the assumption that x is sorted.
"""
i, j = between_indices(x, lower, upper, inclusive)
if True:
return x.iloc[i:j]
else:
# Mask creation is slow.
mask = np.zeros_like(x, dtype=bool)
mask[i:j] = True
mask = pd.Series(mask, index=x.index)
return x[mask]
def between(x, lower, upper, inclusive=True):
mask = x.between(lower, upper, inclusive=inclusive)
return x[mask]
def between_expr(x, lower, upper, inclusive=True):
if inclusive:
mask = (x>=lower) & (x<=upper)
else:
mask = (x>lower) & (x<upper)
return x[mask]
def benchmark(func, x, lowers, uppers):
for l,u in zip(lowers, uppers):
func(x,lower=l,upper=u)
n_samples = 1000
n_reps = 100
x = pd.Series(np.random.randn(n_samples))
# Sort the Series.
# For pandas>=1.0:
# x = x.sort_values(ignore_index=True)
x = x.sort_values().reset_index(drop=True)
# Assert equivalence of different methods.
assert(between_fast(x, 0, 1, True ).equals(between(x, 0, 1, True)))
assert(between_expr(x, 0, 1, True ).equals(between(x, 0, 1, True)))
assert(between_fast(x, 0, 1, False).equals(between(x, 0, 1, False)))
assert(between_expr(x, 0, 1, False).equals(between(x, 0, 1, False)))
# Benchmark repeated evaluations of between().
uppers = np.linspace(0, 3, n_reps)
lowers = -uppers
%timeit benchmark(between_fast, x, lowers, uppers)
%timeit benchmark(between, x, lowers, uppers)
%timeit benchmark(between_expr, x, lowers, uppers)
cvc-elt.1: Cannot find the declaration of element 'Root'. [7]
Your schemaLocation
attribute on the root element should be xsi:schemaLocation
, and you need to fix it to use the right namespace.
You should probably change the targetNamespace
of the schema and the xmlns
of the document to http://myNameSpace.com
(since namespaces are supposed to be valid URIs, which Test.Namespace
isn't, though urn:Test.Namespace
would be ok). Once you do that it should find the schema. The point is that all three of the schema's target namespace, the document's namespace, and the namespace for which you're giving the schema location must be the same.
(though it still won't validate as your <element2>
contains an <element3>
in the document where the schema expects item
)
You can add ng-change
directive to input fields. Have a look at the docs example.
As a workaround to force the evaluation of the SELECT clause before the WHERE clause, you could put the former in a sub-query while the latter remains in the main query:
SELECT * FROM (
SELECT (InvoiceTotal - PaymentTotal - CreditTotal) AS BalanceDue
FROM Invoices) AS temp
WHERE BalanceDue > 0
If you're using getApplicationContext()
as Context
in Activity for the dialog like this
Dialog dialog = new Dialog(getApplicationContext());
then use YourActivityName.this
Dialog dialog = new Dialog(YourActivityName.this);
BFree's answer worked for me. I needed to post the stream right to the browser. Which I'd imagine is a common alternative. I added the following to BFree's Main() code to do this:
//StreamReader reader = new StreamReader(stream);
//Console.WriteLine(reader.ReadToEnd());
string fileName = "fileName.csv";
HttpContext.Current.Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
HttpContext.Current.Response.AddHeader("content-disposition", string.Format("attachment;filename={0}", fileName));
stream.Position = 0;
stream.WriteTo(HttpContext.Current.Response.OutputStream);
OrbitControls and TrackballControls seems to be good for this purpose.
controls = new THREE.TrackballControls( camera );
controls.rotateSpeed = 1.0;
controls.zoomSpeed = 1.2;
controls.panSpeed = 0.8;
controls.noZoom = false;
controls.noPan = false;
controls.staticMoving = true;
controls.dynamicDampingFactor = 0.3;
update in render
controls.update();
To pass arguments to the jar:
java -jar myjar.jar one two
You can access them in the main() method of "Main-Class" (mentioned in the manifest.mf
file of a JAR).
String one = args[0];
String two = args[1];
controller_name
holds the name of the controller used to serve the current view.
Automatic Package Restore will fail for any of the following reasons:
The following article outlines in more detail how to go about points 1-3: https://docs.nuget.org/consume/package-restore/migrating-to-automatic-package-restore
@(Model.IsEnabled) Use this condition for dynamically check and uncheck and set readonly if check box is already checked.
<input id="abc" name="abc" type="checkbox" @(Model.IsEnabled ? "checked=checked onclick=this.checked=!this.checked;" : string.Empty) >
Launch4j is a cross-platform tool for wrapping Java applications distributed as jars in lightweight Windows native executables. The executable can be configured to search for a certain JRE version or use a bundled one, and it's possible to set runtime options, like the initial/max heap size. The wrapper also provides better user experience through an application icon, a native pre-JRE splash screen, a custom process name, and a Java download page in case the appropriate JRE cannot be found.
– Launch4j's website
right click on SQL Server browser and properties, then Connection tab and chose open session with system account and not this account. then apply and chose automatic and finally run the server.
I upgraded my IntelliJ Version from 2018.1 to 2018.3.6. It works !
// for numbers
a = [1,3,2,4,5,6,7,8, 1,1,4,5,6]
$.unique(a)
[7, 6, 1, 8, 3, 2, 5, 4]
// for string
a = ["a", "a", "b"]
$.unique(a)
["b", "a"]
And for dom elements there is no example is needed here I guess because you already know that!
Here is the jsfiddle link of live example: http://jsfiddle.net/3BtMc/4/
add this code to your project
public static class Extension {
public static string TextAfter(this string value ,string search) {
return value.Substring(value.IndexOf(search) + search.Length);
}
}
then use
"code : string text ".TextAfter(":")
I've seen this error a few times too, and I've always been able to solve it by correctly identifying the project's module settings. In IntelliJ, right-click on the top level project -> "Open Module Settings". This should open up a window with the entire project structure and content identified as "Source Folders", "Test Source Folders", etc. Make sure these are correctly set. For the "Source Folders", ensure that the folder is your src/ or src/java (or whatever your source language is), as the case may be
Remove semicolon and you can see that link: http://www.ntu.edu.sg/home/ehchua/programming/howto/Tomcat_HowTo.html
There are a few reasons for the main thread (or any other thread) to join other threads
A thread may have created or holding (locking) some resources. The join-calling thread may be able to clear the resources on its behalf
join() is a natural blocking call for the join-calling thread to continue after the called thread has terminated.
If a python program does not join other threads, the python interpreter will still join non-daemon threads on its behalf.
In my case, this error was caused by an identical server instance already running background.
The weird thing is when I started my server without notice there's one running already, the console didn't show anything like 'something is using port xxx'. I could even upload something to the server. So, it took me quite long to locate this problem.
What's more, after closing all the applications I can imagine, I still could not find the process which is using this port in my Mac's activity monitor. I have to use lsof
to trace. The culprit was not surprising - it's a node process. However, with the PID shown in the terminal, I found the port number in the monitor is different from the one used by my server.
All in all, kill all the node processes may solve this problem directly.
From the link: http://www.aptibook.com/discuss-technical?uid=tech-hive4&question=What-kind-of-datawarehouse-application-is-suitable-for-Hive?
Hive is not a full database. The design constraints and limitations of Hadoop and HDFS impose limits on what Hive can do.
Hive is most suited for data warehouse applications, where
1) Relatively static data is analyzed,
2) Fast response times are not required, and
3) When the data is not changing rapidly.
Hive doesn’t provide crucial features required for OLTP, Online Transaction Processing. It’s closer to being an OLAP tool, Online Analytic Processing. So, Hive is best suited for data warehouse applications, where a large data set is maintained and mined for insights, reports, etc.
As others have indicated, something of the form
x ? y : z
is an expression, not a (complete) statement. It is an rvalue which needs to get used someplace - like on the right side of an assignment, or a parameter to a function etc.
Perhaps you could look at this: http://download.oracle.com/javase/tutorial/java/nutsandbolts/expressions.html
For horizontal alignment (No CSS)
Just insert an align attribute inside the table tag
<table align="center"></table
According to John Day's answer
You should have a Data/Packages folder in your Sublime Text 2 install directory. All you need to do is download the plugin and put the plugin folder in the Packages folder.
In case if you are searching for Data/Packages folder you can find it here
Windows: %APPDATA%\Sublime Text 2
OS X: ~/Library/Application Support/Sublime Text 2
Linux: ~/.Sublime Text 2
Portable Installation: Sublime Text 2/Data
Using Arel:
topics=Topic.arel_table
Topic.where(topics[:forum_id].not_in(@forum_ids))
or, if preferred:
topics=Topic.arel_table
Topic.where(topics[:forum_id].in(@forum_ids).not)
and since rails 4 on:
topics=Topic.arel_table
Topic.where.not(topics[:forum_id].in(@forum_ids))
Please notice that eventually you do not want the forum_ids to be the ids list, but rather a subquery, if so then you should do something like this before getting the topics:
@forum_ids = Forum.where(/*whatever conditions are desirable*/).select(:id)
in this way you get everything in a single query: something like:
select * from topic
where forum_id in (select id
from forum
where /*whatever conditions are desirable*/)
Also notice that eventually you do not want to do this, but rather a join - what might be more efficient.
Unless you write your own Homescreen launcher or use an existing one from Goolge Play, there's "no way" to resize icons.
Well, "no way" does not mean its impossible:
In Python 3, they made the /
operator do a floating-point division, and added the //
operator to do integer division (i.e., quotient without remainder); whereas in Python 2, the /
operator was simply integer division, unless one of the operands was already a floating point number.
In Python 2.X:
>>> 10/3
3
>>> # To get a floating point number from integer division:
>>> 10.0/3
3.3333333333333335
>>> float(10)/3
3.3333333333333335
In Python 3:
>>> 10/3
3.3333333333333335
>>> 10//3
3
For further reference, see PEP238.
as an extension of SmileyChris' answer, you can add a datetime field to the model for last_updated, and set some sort of limit for the max age you'll let it get to before checking for a change
You can use trim function from php to trim both sides (left and right)
trim($yourinputdata," ");
Or
trim($yourinputdata);
You can also use
ltrim() - Removes whitespace or other predefined characters from the left side of a string
rtrim() - Removes whitespace or other predefined characters from the right side of a string
System: PHP 4,5,7
Docs: http://php.net/manual/en/function.trim.php
Centering is one of the biggest issues in CSS. However, some tricks exist:
To center your table horizontally, you can set left and right margin to auto:
<style>
#test {
width:100%;
height:100%;
}
table {
margin: 0 auto; /* or margin: 0 auto 0 auto */
}
</style>
To center it vertically, the only way is to use javascript:
var tableMarginTop = Math.round( (testHeight - tableHeight) / 2 );
$('table').css('margin-top', tableMarginTop) # with jQuery
$$('table')[0].setStyle('margin-top', tableMarginTop) # with Mootools
No vertical-align:middle
is possible as a table is a block and not an inline element.
Here is a website that sums up CSS centering solutions: http://howtocenterincss.com/
Try this thing, i dont think anyone suggested this in the Topic, this will resolve like 70% of your issue, for some other pages, you have to scrap, i have the full solution but not for public,
ADD below to your iframe
sandbox="allow-same-origin allow-scripts allow-popups allow-forms"
Have you tried the SVG text element?
.append("text").text(function(d, i) { return d[whichevernode];})
rect element doesn't permit text element inside of it. It only allows descriptive elements (<desc>, <metadata>, <title>
) and animation elements (<animate>, <animatecolor>, <animatemotion>, <animatetransform>, <mpath>, <set>
)
Append the text element as a sibling and work on positioning.
UPDATE
Using g grouping, how about something like this? fiddle
You can certainly move the logic to a CSS class you can append to, remove from the group (this.parentNode)
Beyond Compare 3, my favorite, has a merge functionality in the Pro edition. The good thing with its merge is that it let you see all 4 views: base, left, right, and merged result. It's somewhat less visual than P4V but way more than WinDiff. It integrates with many source control and works on Windows/Linux. It has many features like advanced rules, editions, manual alignment...
The Perforce Visual Client (P4V) is a free tool that provides one of the most explicit interface for merging (see some screenshots). Works on all major platforms. My main disappointement with that tool is its kind of "read-only" interface. You cannot edit manually the files and you cannot manually align.
PS: P4Merge is included in P4V. Perforce tries to make it a bit hard to get their tool without their client.
SourceGear Diff/Merge may be my second free tool choice. Check that merge screens-shot and you'll see it's has the 3 views at least.
Meld is a newer free tool that I'd prefer to SourceGear Diff/Merge: Now it's also working on most platforms (Windows/Linux/Mac) with the distinct advantage of natively supporting some source control like Git. So you can have some history diff on all files much simpler. The merge view (see screenshot) has only 3 panes, just like SourceGear Diff/Merge. This makes merging somewhat harder in complex cases.
PS: If one tool one day supports 5 views merging, this would really be awesome, because if you cherry-pick commits in Git you really have not one base but two. Two base, two changes, and one resulting merge.
Use the Chr or ChrW function, Chr(charNumber)
.
Upgrade your SQL Server to SP3
You can install it from: http://www.microsoft.com/en-us/download/details.aspx?id=27594
Just put a line break into your text.
You don't add lines as a method. Multiline just supports the use of line breaks.
You need to install C compiler, C/C++ extension, configure launch.json and tasks.json to be able to debug C code.
This article would guide you how to do it: https://medium.com/@jerrygoyal/run-debug-intellisense-c-c-in-vscode-within-5-minutes-3ed956e059d6
Sorry for comment in an old post but if you want to use an else if statement this will help you
{% if title == source %}
Do This
{% elif title == value %}
Do This
{% else %}
Do This
{% endif %}
For more info see Django Documentation
This should give you a list of all the tables in your database
SELECT Distinct TABLE_NAME FROM information_schema.TABLES
So you can use it similar to your database check.
If NOT EXISTS(SELECT Distinct TABLE_NAME FROM information_schema.TABLES Where TABLE_NAME = 'Your_Table')
BEGIN
--CREATE TABLE Your_Table
END
GO
When you have some binary data that you want to ship across a network, you generally don't do it by just streaming the bits and bytes over the wire in a raw format. Why? because some media are made for streaming text. You never know -- some protocols may interpret your binary data as control characters (like a modem), or your binary data could be screwed up because the underlying protocol might think that you've entered a special character combination (like how FTP translates line endings).
So to get around this, people encode the binary data into characters. Base64 is one of these types of encodings.
Why 64?
Because you can generally rely on the same 64 characters being present in many character sets, and you can be reasonably confident that your data's going to end up on the other side of the wire uncorrupted.
A practical explanation: By default, <p> </p>
will add line breaks before and after the enclosed text (so it creates a paragraph). <span>
does not do this, that is why it is called inline.
in console (cmd), go to app root path and execute:
type .env.example > .env
There's no need to use jQuery to change the title. Try:
document.title = "blarg";
See this question for more details.
To dynamically change on button click:
$(selectorForMyButton).click(function(){
document.title = "blarg";
});
To dynamically change in loop, try:
var counter = 0;
var titleTimerId = setInterval(function(){
document.title = document.title + '>';
counter++;
if(counter == 5){
clearInterval(titleTimerId);
}
}, 100);
To string the two together so that it dynamically changes on button click, in a loop:
var counter = 0;
$(selectorForMyButton).click(function(){
titleTimerId = setInterval(function(){
document.title = document.title + '>';
counter++;
if(counter == 5){
clearInterval(titleTimerId);
}
}, 100);
});
In addition to the Python 2 approach here are the equivalents for Python 3:
# Create a range that does not contain 50
for i in [x for x in range(100) if x != 50]:
print(i)
# Create 2 ranges [0,49] and [51, 100]
from itertools import chain
concatenated = chain(range(50), range(51, 100))
for i in concatenated:
print(i)
# Create a iterator and skip 50
xr = iter(range(100))
for i in xr:
print(i)
if i == 49:
next(xr)
# Simply continue in the loop if the number is 50
for i in range(100):
if i == 50:
continue
print(i)
Ranges are lists in Python 2 and iterators in Python 3.
For AAPT2 error: check logs for details or error: failed linking file resources. errors:
Check your .xml files that contains android:background="" and remove this empty attribute can solve your problem.
try this code to create Scale animation without using xml
ScaleAnimation animation = new ScaleAnimation(fromXscale, toXscale, fromYscale, toYscale, Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f);
You need to change textview parameters, not parameters of attributed string
textView.linkTextAttributes = [
NSAttributedString.Key.foregroundColor: UIColor.red,
NSAttributedString.Key.underlineColor: UIColor.red,
NSAttributedString.Key.underlineStyle: NSUnderlineStyle.single.rawValue
]
INSERT INTO exampleTbl VALUES('he doesn''t work for me')
If you're adding a record through ASP.NET, you can use the SqlParameter object to pass in values so you don't have to worry about the apostrophe's that users enter in.
Please note on iPad Safari, NoviceCoding's solution won't work if you have -webkit-overflow-scrolling: touch;
somewhere in your CSS.
The solution is either removing all the occurrences of -webkit-overflow-scrolling: touch;
or putting -webkit-overflow-scrolling: auto;
with
NoviceCoding's solution.
You can't select a range without having first selected the sheet it is in. Try to select the sheet first and see if you still get the problem:
sourceSheetSum.Select
sourceSheetSum.Range("C3").Select
I personally prefer to see switch statements over too many nested if-elses because they can be much easier to read. Switches are also better in readability terms for showing a state.
See also the comment in this post regarding pacman ifs.
In build.gradle
add
wrapper { gradleVersion = '6.0' }
After importing pandas, as an alternative to using the context manager, set such options for displaying entire dataframes:
pd.set_option('display.max_columns', None) # or 1000
pd.set_option('display.max_rows', None) # or 1000
pd.set_option('display.max_colwidth', -1) # or 199
For full list of useful options, see:
pd.describe_option('display')
Len(word)
Although that's not what your question title asks =)
Microsoft recently modified the reflection API rendering most of these answers obsolete. The following should work on modern platforms (including Xamarin.Forms and UWP):
obj.GetType().GetTypeInfo().GetDeclaredMethod("MethodName").Invoke(obj, yourArgsHere);
Or as an extension method:
public static object InvokeMethod<T>(this T obj, string methodName, params object[] args)
{
var type = typeof(T);
var method = type.GetTypeInfo().GetDeclaredMethod(methodName);
return method.Invoke(obj, args);
}
Note:
If the desired method is in a superclass of obj
the T
generic must be explicitly set to the type of the superclass.
If the method is asynchronous you can use await (Task) obj.InvokeMethod(…)
.
You need to check the folder permissions on your server and check that the account that you are using to run your application has access to that folder.
raw_input is your helper here. From documentation -
If the prompt argument is present, it is written to standard output without a trailing newline. The function then reads a line from input, converts it to a string (stripping a trailing newline), and returns that. When EOF is read, EOFError is raised.
So your code will basically look like this.
num_array = list()
num = raw_input("Enter how many elements you want:")
print 'Enter numbers in array: '
for i in range(int(num)):
n = raw_input("num :")
num_array.append(int(n))
print 'ARRAY: ',num_array
P.S: I have typed all this free hand. Syntax might be wrong but the methodology is correct. Also one thing to note is that, raw_input
does not do any type checking, so you need to be careful...
This worked for me.
var number = 8008
number = number + "";
numberreverse = number.split("").reverse().join('');
console.log ("The number if reversed is: " +numberreverse);
if (number == numberreverse)
console.log("Yes, this is a palindrome");
else
console.log("Nope! It isnt a palindrome");
For spring boot framework version 2.0.4.RELEASE+
. Add this line to application.properties
server.servlet.context-path=/api
Iterate over the Array. First initialize the maximum value to the first element of the array and then for each element optimize it if the element under consideration is greater.
to allow periods and any other character just add them like so:
change: '#[^a-zA-Z ]#
'
to:'#[^a-zA-Z .()!]#
'
public void Each<T>(IEnumerable<T> items, Action<T> action)
{
foreach (var item in items)
action(item);
}
... and call it thusly:
Each(myList, i => Console.WriteLine(i));
You need to set a height on the DIV. Otherwise it will keep expanding indefinitely.
I solve this by SQL command:
ALTER USER 'mysqlUsername'@'localhost' IDENTIFIED WITH mysql_native_password BY 'mysqlUsernamePassword';
which is referenced by https://dev.mysql.com/doc/refman/8.0/en/alter-user.html
if you are creating new user
CREATE USER 'jeffrey'@'localhost' IDENTIFIED WITH mysql_native_password BY 'password';
which is referenced by https://dev.mysql.com/doc/refman/8.0/en/create-user.html
this works for me
You just missed an extra pair of brackets for the "OR" symbol. The following should do the trick:
([0-9]+)\s+((\bseconds\b)|(\bminutes\b))
Without those you were either matching a number followed by seconds OR just the word minutes
Go to your desired perspective. Go to 'Window->show view' menu.
If you see logcat there, click it and you are done.
Else, click on 'other' (at the bottom), chose 'Android'->logcat.
Hope that helps :-)
This sometime works, sometime no.
I have installed 1 Eclipse - works.
Installed second - doesn't work.
And I cann't figure why!
After some time may be found a solution.
Need delete all setting for proxy (included credentials). And re-insert for new.
After this for me getting work.
This can give you the correct Answer
#include <stdio.h>
int main()
{
float total=100, number=50;
float percentage;
percentage=(number/total)*100;
printf("%0.2f",percentage);
return 0;
}
If you'd like to link to the root directory you can use
/
, or /index.html
If you'd like to link to a file in the same directory, simply put the file name
<a href="/employees.html">Employees Click Here</a>
To move back a folder, you can use
../
To link to the index page in the employees directory from the root directory, you'd do this
<a href="../employees/index.html">Employees Directory Index Page</a>
Use: http://jsfiddle.net/xH79d/
var n = $("input[name^='card']").length;
var array = $("input[name^='card']");
for(i=0; i < n; i++) {
// use .eq() within a jQuery object to navigate it by Index
card_value = array.eq(i).attr('name'); // I'm assuming you wanted -name-
// otherwise it'd be .eq(i).val(); (if you wanted the text value)
alert(card_value);
}
?
There is absolutely no reason to download a 3rd party library to achieve this simple problem, like the above solutions suggest.
The one line version to group a list
of objects by a certain key
in es6:
const groupByKey = (list, key) => list.reduce((hash, obj) => ({...hash, [obj[key]]:( hash[obj[key]] || [] ).concat(obj)}), {})
The longer version that filters out the objects without the key
:
function groupByKey(array, key) {
return array
.reduce((hash, obj) => {
if(obj[key] === undefined) return hash;
return Object.assign(hash, { [obj[key]]:( hash[obj[key]] || [] ).concat(obj)})
}, {})
}
var cars = [{'make':'audi','model':'r8','year':'2012'},{'make':'audi','model':'rs5','year':'2013'},{'make':'ford','model':'mustang','year':'2012'},{'make':'ford','model':'fusion','year':'2015'},{'make':'kia','model':'optima','year':'2012'}];
console.log(groupByKey(cars, 'make'))
_x000D_
NOTE: It appear the original question asks how to group cars by make, but omit the make in each group. So the short answer, without 3rd party libraries, would look like this:
const groupByKey = (list, key, {omitKey=false}) => list.reduce((hash, {[key]:value, ...rest}) => ({...hash, [value]:( hash[value] || [] ).concat(omitKey ? {...rest} : {[key]:value, ...rest})} ), {})
var cars = [{'make':'audi','model':'r8','year':'2012'},{'make':'audi','model':'rs5','year':'2013'},{'make':'ford','model':'mustang','year':'2012'},{'make':'ford','model':'fusion','year':'2015'},{'make':'kia','model':'optima','year':'2012'}];
console.log(groupByKey(cars, 'make', {omitKey:true}))
_x000D_
c# version of @qfactor77's answer. This is the best way without LINQ .
string[] wildcards= {"*.mp4", "*.jpg"};
ReadOnlyCollection<string> filePathCollection = FileSystem.GetFiles(dirPath, Microsoft.VisualBasic.FileIO.SearchOption.SearchAllSubDirectories, wildcards);
string[] filePath=new string[filePathCollection.Count];
filePathCollection.CopyTo(filePath,0);
now return filePath
string array. In the beginning you need
using Microsoft.VisualBasic.FileIO;
using System.Collections.ObjectModel;
also you need to add reference to Microsoft.VisualBasic
Did you try using the Select(filterExpression, sortOrder)
method on DataTable? See here for an example. Note this method will not sort the data table in place, if that is what you are looking for, but it will return a sorted array of rows without using a data view.
//form/descendant::input[@type='submit']
You can use tee
to write to the file without the need for flushing.
/homedir/MyScript 2>&1 | tee some_log.log > /dev/null
function refreshPage()
{
jQuery.mobile.changePage(window.location.href, {
allowSamePageTransition: true,
transition: 'none',
reloadPage: true
});
}
Taken from here http://scottwb.com/blog/2012/06/29/reload-the-same-page-without-blinking-on-jquery-mobile/ also tested on jQuery Mobile 1.2.0
Swift 4
In viewDidLoad() just call below code:
CODE SAMPLE
//txtVComplaint is a textView
txtVComplaint.tintColor = UIColor.white
txtVComplaint.tintColorDidChange()
var field = $("#field")_x000D_
field.keyup(function(ev){_x000D_
if(field[0].value.length < 10) {_x000D_
field[0].setCustomValidity("characters less than 10")_x000D_
_x000D_
}else if (field[0].value.length === 10) {_x000D_
field[0].setCustomValidity("characters equal to 10")_x000D_
_x000D_
}else if (field[0].value.length > 10 && field[0].value.length < 20) {_x000D_
field[0].setCustomValidity("characters greater than 10 and less than 20")_x000D_
_x000D_
}else if(field[0].validity.typeMismatch) {_x000D_
field[0].setCustomValidity("wrong email message")_x000D_
_x000D_
}else {_x000D_
field[0].setCustomValidity("") // no more errors_x000D_
_x000D_
}_x000D_
field[0].reportValidity()_x000D_
_x000D_
});
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
<input type="email" id="field">
_x000D_
assuming you have npm installed and bower installed globally
bower init
(this will generate the bower.json file in your directory)to set the path where bootstrap will be installed:
manually create a .bowerrc
file next to the bower.json file and add the following to it:
{ "directory" : "public/components" }
bower install bootstrap --save
Note: to install other components:
bower search {component-name-here}
Don't moveTo()
after each lineTo()
In other words, remove every moveTo()
except the first one.
Seriously, if I just copy-paste OP's code and remove the unnecessary moveTo()
calls, it works.
Nothing else needs to be done.
EDIT: I know the OP already posted his "final working solution", but he didn't state why it works. The actual reason was quite surprising to me, so I felt the need to add an answer.
You can use wildcard to do this as following
ArrayList<String> strList = (ArrayList<String>)(ArrayList<?>)(list);
function validateDays() {
if (document.getElementById("option1").checked == true) {
alert("You have selected Option 1");
}
else if (document.getElementById("option2").checked == true) {
alert("You have selected Option 2");
}
else if (document.getElementById("option3").checked == true) {
alert("You have selected Option 3");
}
else {
// DO NOTHING
}
}
It doesn't - the C# compiler does :)
So this code:
string x = "hello";
string y = "there";
string z = "chaps";
string all = x + y + z;
actually gets compiled as:
string x = "hello";
string y = "there";
string z = "chaps";
string all = string.Concat(x, y, z);
(Gah - intervening edit removed other bits accidentally.)
The benefit of the C# compiler noticing that there are multiple string concatenations here is that you don't end up creating an intermediate string of x + y
which then needs to be copied again as part of the concatenation of (x + y)
and z
. Instead, we get it all done in one go.
EDIT: Note that the compiler can't do anything if you concatenate in a loop. For example, this code:
string x = "";
foreach (string y in strings)
{
x += y;
}
just ends up as equivalent to:
string x = "";
foreach (string y in strings)
{
x = string.Concat(x, y);
}
... so this does generate a lot of garbage, and it's why you should use a StringBuilder
for such cases. I have an article going into more details about the two which will hopefully answer further questions.
I have a solution that works well for me. It consists of a local jenkins running in docker and a git web hook to trigger the pipeline in the local jenkins on every commit. You no longer need to push to your github or bitbucket repository to test the pipeline.
This has only been tested in a linux environment.
It is fairly simple to make this work although this instruction is a tad long. Most steps are there.
Create a file called Dockerfile in place of your choosing. I'm placing it in /opt/docker/jenkins/Dockerfile
fill it with this:
FROM jenkins/jenkins:lts
USER root
RUN apt-get -y update && apt-get -y upgrade
# Your needed installations goes here
USER jenkins
Build the local_jenkins image
This you will need to do only once or after you have added something to the Dockerfile.
$ docker build -t local_jenkins /opt/docker/jenkins/
Start and restart local_jenkins
From time to time you want to start and restart jenkins easily. E.g. after a reboot of your machine. For this I made an alias that I put in .bash_aliases
in my home folder.
$ echo "alias localjenkinsrestart='docker stop jenkins;docker rm jenkins;docker run --name jenkins -i -d -p 8787:8080 -p 50000:50000 -v /opt/docker/jenkins/jenkins_home:/var/jenkins_home:rw local_jenkins'" >> ~/.bash_aliases
$ source .bash_aliases # To make it work
Make sure the /opt/docker/jenkins/jenkins_home
folder exists and that you have user read and write rights to it.
To start or restart your jenkins just type:
$ localjenkinsrestart
Everything you do in your local jenkins will be stored in the folder /opt/docker/jenkins/jenkins_home and preserved between restarts.
Create a ssh access key in your docker jenkins
This is a very important part for this to work. First we start the docker container and create a bash shell to it:
$ localjenkinsrestart
$ docker exec -it jenkins /bin/bash
You have now entered into the docker container, this you can see by something like jenkins@e7b23bad10aa:/$
in your terminal. The hash after the @ will for sure differ.
Create the key
jenkins@e7b23bad10aa:/$ ssh-keygen
Press enter on all questions until you get the prompt back
Copy the key to your computer. From within the docker container your computer is 172.17.0.1 should you wonder.
jenkins@e7b23bad10aa:/$ ssh-copy-id [email protected]
user = your username and 172.17.0.1 is the ip address to your computer from within the docker container.
You will have to type your password at this point.
Now lets try to complete the loop by ssh-ing to your computer from within the docker container.
jenkins@e7b23bad10aa:/$ ssh [email protected]
This time you should not need to enter you password. If you do, something went wrong and you have to try again.
You will now be in your computers home folder. Try ls
and have a look.
Do not stop here since we have a chain of ssh shells that we need to get out of.
$ exit
jenkins@e7b23bad10aa:/$ exit
Right! Now we are back and ready to continue.
Install your Jenkins
You will find your local Jenkins in your browser at http://localhost:8787.
First time you point your browser to your local Jenkins your will be greated with a Installation Wizard. Defaults are fine, do make sure you install the pipeline plugin during the setup though.
Setup your jenkins
It is very important that you activate matrix based security on http://localhost:8787/configureSecurity and give yourself all rights by adding yourself to the matrix and tick all the boxes. (There is a tick-all-boxes icon on the far right)
Jenkins’ own user database
as the Security RealmMatrix-based security
in the Authorization sectionUser/group to add:
and click on the [ Add ]
buttonPrevent Cross Site Request Forgery exploits
is unchecked. (Since this Jenkins is only reachable from your computer this isn't such a big deal)[ Save ]
and log out of Jenkins and in again just to make sure it works.
If it doesn't you have to start over from the beginning and emptying the /opt/docker/jenkins/jenkins_home
folder before restartingAdd the git user
We need to allow our git hook to login to our local Jenkins with minimal rights. Just to see and build jobs is sufficient. Therefore we create a user called git
with password login
.
Direct your browser to http://localhost:8787/securityRealm/addUser and add git
as username and login
as password.
Click on [ Create User ]
.
Add the rights to the git user
Go to the http://localhost:8787/configureSecurity page in your browser. Add the git user to the matrix:
git
in the field User/group to add:
and click on [ Add ]
Now it is time to check the boxes for minimal rights to the git user. Only these are needed:
Make sure that the Prevent Cross Site Request Forgery exploits
checkbox is unchecked and click on [ Save ]
We assume we have the username user
and our git enabled project with the Jenkinsfile
in it is called project
and is located at /home/user/projects/project
In your http://localhost:8787 Jenkins add a new pipeline project. I named it hookpipeline for reference.
New Item
in the Jenkins menuhookpipeline
[ OK ]
Poll SCM
in the Build Triggers section. Leave the Schedule empty.Pipeline script from SCM
Repository URL
field enter [email protected]:projects/project/.git
Script Path
field enter Jenkinsfile
Go to the /home/user/projects/project/.git/hooks
folder and create a file called post-commit
that contains this:
#!/bin/sh
BRANCHNAME=$(git rev-parse --abbrev-ref HEAD)
MASTERBRANCH='master'
curl -XPOST -u git:login http://localhost:8787/job/hookpipeline/build
echo "Build triggered successfully on branch: $BRANCHNAME"
Make this file executable:
$ chmod +x /home/user/projects/project/.git/hooks/post-commit
Test the post-commit hook:
$ /home/user/projects/project/.git/hooks/post-commit
Check in Jenkins if your hookpipeline project was triggered.
Finally make some arbitrary change to your project, add the changes and do a commit. This will now trigger the pipeline in your local Jenkins.
Happy Days!
int id = getResources().getIdentifier("gameover", "drawable", getPackageName());
ImageView imageView = new ImageView(this);
LinearLayout.LayoutParams vp =
new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT,
LayoutParams.WRAP_CONTENT);
imageView.setLayoutParams(vp);
imageView.setImageResource(id);
someLinearLayout.addView(imageView);
I just want to add my 2 cents. I had the same goal (to change the background color from the .java class). But none of the above methods worked for me.
Issue was, that I set the background color inside the layout .xml file with android:background="@color/colorGray"
:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="@color/colorGray">
So I just deleted particular line:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
Now I (you) can set the color from the code with:
getWindow().getDecorView().setBackgroundColor(Color.GRAY);
There are some syntax errors on your HTML
.
First, the URL of the image needs to point to an address on the public Internet. The users viewing your page won't have your hard drive, so pointing to a file on your local hard drive cannot work. Replace C:\Pics
with the actual URL of the image, not a path on development machine filesystem. If you want to be absolutely sure, use a different computer and paste the img tag src attribute value to the address bar of the browser. If it works there, then you're good. Do not that the path can be relative and still valid, but then it needs to be relative to the public URL of the web page it's embedded in.
Second, the <title>
tag. You need to add this tag if you need a title on the browser, and you can't format it.
The third error, if about the <th>
tag, you have to add this header inside a <tr>
tag, because <th>
needs a row (create by <tr>
).
Another thing is, you don't need all colspan you did.
I tried to do a valid html as you need. Take a look:
<!DOCTYPE html>
<html>
<head>
<title>CAR APPLICATION</title>
</head>
<body>
<center>
<h1>CAR APPLICATION</h1>
</center>
<table border="5" bordercolor="red" align="center">
<tr>
<th colspan="3">SONAKSHI RAINA 10B ROLL No:-32</th>
</tr>
<tr>
<th>Name</th>
<th>Origin</th>
<th>Photo</th>
</tr>
<tr>
<td>Bugatti Veyron Super Sport</td>
<td>Molsheim, Alsace, France</td>
<!-- considering it is on the same folder that .html file -->
<td><img src="H.gif" alt="" border=3 height=100 width=100></img></td>
</tr>
<tr>
<td>SSC Ultimate Aero TT TopSpeed</td>
<td>United States</td>
<td border=3 height=100 width=100>Photo1</td>
</tr>
<tr>
<td>Koenigsegg CCX</td>
<td>Ängelholm, Sweden</td>
<td border=4 height=100 width=300>Photo1</td>
</tr>
<tr>
<td>Saleen S7</td>
<td>Irvine, California, United States</td>
<td border=3 height=100 width=100>Photo1</td>
</tr>
<tr>
<td> McLaren F1</td>
<td>Surrey, England</td>
<td border=3 height=100 width=100>Photo1</td>
</tr>
<tr>
<td>Ferrari Enzo</td>
<td>Maranello, Italy</td>
<td border=3 height=100 width=100>Photo1</td>
</tr>
<tr>
<td> Pagani Zonda F Clubsport</td>
<td>Modena, Italy</td>
<td border=3 height=100 width=100>Photo1</td>
</tr>
</table>
</body>
<html>
$ mvn --version
and look for Maven home: in the output
, mine is: Maven home: /usr/share/maven
I tried all the solutions mentioned above, then did not work. I have 3 tables one below the other. The last one over flowed. I fixed it using:
/* Grid Definition */
table {
word-break: break-word;
}
For IE11 in edge mode, you need to set this to word-break:break-all
Sorry, I wasn't sure which SQL platform you're talking about:
In MySQL:
$query = ("SELECT * FROM $db WHERE conditions AND LENGTH(col_name) = 3");
in MSSQL
$query = ("SELECT * FROM $db WHERE conditions AND LEN(col_name) = 3");
The LENGTH() (MySQL) or LEN() (MSSQL) function will return the length of a string in a column that you can use as a condition in your WHERE clause.
Edit
I know this is really old but thought I'd expand my answer because, as Paulo Bueno rightly pointed out, you're most likely wanting the number of characters as opposed to the number of bytes. Thanks Paulo.
So, for MySQL there's the CHAR_LENGTH()
. The following example highlights the difference between LENGTH()
an CHAR_LENGTH()
:
CREATE TABLE words (
word VARCHAR(100)
) ENGINE INNODB DEFAULT CHARSET utf8mb4 COLLATE utf8mb4_unicode_ci;
INSERT INTO words(word) VALUES('??'), ('happy'), ('hayir');
SELECT word, LENGTH(word) as num_bytes, CHAR_LENGTH(word) AS num_characters FROM words;
+--------+-----------+----------------+
| word | num_bytes | num_characters |
+--------+-----------+----------------+
| ?? | 6 | 2 |
| happy | 5 | 5 |
| hayir | 6 | 5 |
+--------+-----------+----------------+
Be careful if you're dealing with multi-byte characters.
In My case it was something else. I had installed a package and then uninstall it and reinstall an earlier version. That left a residual configuration/runtime/asssemblyBinding/dependencyIdentity
redirecting in my app.config. I had to correct it.
I figured it out by looking at the Output
window and selecting "Tests
" in the drop down. The error message was there.
This was a pain... I hope it helps someone else.
The return
statement stops a loop only if it's inside the function (i.e. it terminates both the loop and the function). Otherwise, you will get this error:
Uncaught SyntaxError: Illegal return statement(…)
To terminate a loop you should use break
.
I had this issue and it was due to the .Net framework version. I had upgraded the build to framework 4.0 but this seemed to affect some comms dlls the application was using. I rolled back to framework 3.5 and it worked fine.
Unfortunately the above solutions did not work in my case - maybe because a put the button inside a form-tag. This code ...
<input class="button" type="submit" value=" ">
<img src="../assets/logo.png" alt="test" />
</input>
... always leads to error (with or without the closing slash of the img tag):
error Parsing error: x-invalid-end-tag vue/no-parsing-error
? 1 problem (1 error, 0 warnings)
A kind of workaround that did work was to define the image as background-image by means of css.
The html snippet describes the button only. The value attribute contains a single blank in order to suppress some browsers presenting unwanted default text.
<input class="button" type="submit" value=" " />
the CSS defines the button's background image:
.button {
display: block;
width: 6em;
height: 6em;
color: white;
background-color: #639f59;
padding: 0.4em 1.2em;
box-shadow: inset 0 -0.6em 1em -0.35em rgba(5, 122, 11, 0.30),
inset 0 0.6em 2em -0.3em rgba(255, 255, 255, 0.30),
inset 0 0 0em 0.05em rgba(255, 255, 255, 0.30);
cursor: pointer;
background: url("../assets/logo.png") ;
background-repeat: no-repeat;
background-size: 6em;
background-position: center;
border: 0;
border-radius: 3em;
}
If you do not want to define a separate class for nested json , Defining nested json object as JsonNode should work ,for example :
{"id":2,"socket":"0c317829-69bf-43d6-b598-7c0c550635bb","type":"getDashboard","data":{"workstationUuid":"ddec1caa-a97f-4922-833f-632da07ffc11"},"reply":true}
@JsonProperty("data")
private JsonNode data;
The new method for dynamic elements is MutationsObserver .. The following example uses underscore.js to use ( _.each ) function.
MutationObserver = window.MutationObserver || window.WebKitMutationObserver || window.MozMutationObserver;
var observerjQueryPlugins = new MutationObserver(function (repeaterWrapper) {
_.each(repeaterWrapper, function (repeaterItem, index) {
var jq_nodes = $(repeaterItem.addedNodes);
jq_nodes.each(function () {
// Date Picker
$(this).parents('.current-repeateritem-container').find('.element-datepicker').datepicker({
dateFormat: "dd MM, yy",
showAnim: "slideDown",
changeMonth: true,
numberOfMonths: 1
});
});
});
});
observerjQueryPlugins.observe(document, {
childList: true,
subtree: true,
attributes: false,
characterData: false
});
Best way is to make function for this
FUNCTION:
$.fn.escape = function (callback) {
return this.each(function () {
$(document).on("keydown", this, function (e) {
var keycode = ((typeof e.keyCode !='undefined' && e.keyCode) ? e.keyCode : e.which);
if (keycode === 27) {
callback.call(this, e);
};
});
});
};
EXAMPLE:
$("#my-div").escape(function () {
alert('Escape!');
})
You can split and join the string, but why not use substrings? Then you only end up with one split instead of splitting the string into 5 parts and re-joining it. The end result is the same, but the substring is probably a bit faster.
string lcStart = "Some Very Large String Here";
int lnSpace = lcStart.IndexOf(' ');
if (lnSpace > -1)
{
string lcFirst = lcStart.Substring(0, lnSpace);
string lcRest = lcStart.Substring(lnSpace + 1);
}
I have written the function to find distance between two coordinates. It will return distance in meter.
function findDistance() {
var R = 6371e3; // R is earth’s radius
var lat1 = 23.18489670753479; // starting point lat
var lat2 = 32.726601; // ending point lat
var lon1 = 72.62524545192719; // starting point lon
var lon2 = 74.857025; // ending point lon
var lat1radians = toRadians(lat1);
var lat2radians = toRadians(lat2);
var latRadians = toRadians(lat2-lat1);
var lonRadians = toRadians(lon2-lon1);
var a = Math.sin(latRadians/2) * Math.sin(latRadians/2) +
Math.cos(lat1radians) * Math.cos(lat2radians) *
Math.sin(lonRadians/2) * Math.sin(lonRadians/2);
var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));
var d = R * c;
console.log(d)
}
function toRadians(val){
var PI = 3.1415926535;
return val / 180.0 * PI;
}
Update May 2020, installed Anaconda 3 Individual Edition from https://www.anaconda.com/products/individual, chose 32-bit installer for Python 3.7, and installed with Default options.
Here is the directory where Anaconda was installed (C:\ProgramData\Anaconda3). Note ProgramData is a hidden folder not visible via Windows File Explorer.
And launching Anaconda command prompt from Start Menu>>Anaconda3 gives below command shell
"where anaconda" command gives below output C:\ProgramData\Anaconda3\Scripts\anaconda.exe and versions for anaconda, conda, python
Updated original question which was asked 3 years ago, and is relevant today as well in May 2020 as I had similar question/doubt when installing Anaconda recently.
Regarding tables names, case, etc, the prevalent convention is:
UPPER CASE
lower_case_with_underscores
UPDATE my_table SET name = 5;
This is not written in stone, but the bit about identifiers in lower case is highly recommended, IMO. Postgresql treats identifiers case insensitively when not quoted (it actually folds them to lowercase internally), and case sensitively when quoted; many people are not aware of this idiosyncrasy. Using always lowercase you are safe. Anyway, it's acceptable to use camelCase
or PascalCase
(or UPPER_CASE
), as long as you are consistent: either quote identifiers always or never (and this includes the schema creation!).
I am not aware of many more conventions or style guides. Surrogate keys are normally made from a sequence (usually with the serial
macro), it would be convenient to stick to that naming for those sequences if you create them by hand (tablename_colname_seq
).
See also some discussion here, here and (for general SQL) here, all with several related links.
Note: Postgresql 10 introduced identity
columns as an SQL-compliant replacement for serial.
You could also use wp_list_categories();
wp_list_categories( array('taxonomy' => 'product_cat', 'title_li' => '') );
If, like me, you have diligently followed all the above solutions and the error is still there, try closing and reopening Visual Studio.
Obvious, I know, but perhaps I'm not the only one who's become fuzzy-brained after staring at a computer screen all day.
If you dont want to use any module for age calculation
var age = Math.floor((new Date() - new Date(date_of_birth)) / 1000 / 60 / 60 / 24 / 365.25)
You need to have
#include <string>
in the header file too.The forward declaration on it's own doesn't do enough.
Also strongly consider header guards for your header files to avoid possible future problems as your project grows. So at the top do something like:
#ifndef THE_FILE_NAME_H
#define THE_FILE_NAME_H
/* header goes in here */
#endif
This will prevent the header file from being #included multiple times, if you don't have such a guard then you can have issues with multiple declarations.
You can use
holder.text.setTextColor(Color.rgb(200,0,0));
You can also specify what color you want with Transparency.
holder.text.setTextColor(Color.argb(0,200,0,0));
a for Alpha (Transparent) value r-red g-green b-blue
curl
sends POST requests with the default content type of application/x-www-form-urlencoded
. If you want to send a JSON request, you will have to specify the correct content type header:
$ curl -vX POST http://server/api/v1/places.json -d @testplace.json \
--header "Content-Type: application/json"
But that will only work if the server accepts json input. The .json
at the end of the url may only indicate that the output is json, it doesn't necessarily mean that it also will handle json input. The API documentation should give you a hint on whether it does or not.
The reason you get a 401
and not some other error is probably because the server can't extract the auth_token
from your request.
I fixed this issue use the method on http://matthill.eu/android/google-play-error-rpcs5aec0/
Using plain javascript
var isEmpty = document.getElementById('cartContent').innerHTML === "";
And if you are using jquery it can be done like
var isEmpty = $("#cartContent").html() === "";
Try following int git bash
1.git add -u :/
2.git commit -m "your commit message"
git push -u origin master
Note:if you have not initialized your repo.
First of all
git init
and follow above mentioned steps in order. This worked for me
There isn't currently a built-in PowerShell method for doing the SFTP part. You'll have to use something like psftp.exe or a PowerShell module like Posh-SSH.
Here is an example using Posh-SSH:
# Set the credentials
$Password = ConvertTo-SecureString 'Password1' -AsPlainText -Force
$Credential = New-Object System.Management.Automation.PSCredential ('root', $Password)
# Set local file path, SFTP path, and the backup location path which I assume is an SMB path
$FilePath = "C:\FileDump\test.txt"
$SftpPath = '/Outbox'
$SmbPath = '\\filer01\Backup'
# Set the IP of the SFTP server
$SftpIp = '10.209.26.105'
# Load the Posh-SSH module
Import-Module C:\Temp\Posh-SSH
# Establish the SFTP connection
$ThisSession = New-SFTPSession -ComputerName $SftpIp -Credential $Credential
# Upload the file to the SFTP path
Set-SFTPFile -SessionId ($ThisSession).SessionId -LocalFile $FilePath -RemotePath $SftpPath
#Disconnect all SFTP Sessions
Get-SFTPSession | % { Remove-SFTPSession -SessionId ($_.SessionId) }
# Copy the file to the SMB location
Copy-Item -Path $FilePath -Destination $SmbPath
Some additional notes:
That should give you a decent starting point.
Very Simple with no extra code, just input, conversion and output.
using System;
namespace _01.Decimal_to_Binary
{
class DecimalToBinary
{
static void Main(string[] args)
{
Console.Write("Decimal: ");
int decimalNumber = int.Parse(Console.ReadLine());
int remainder;
string result = string.Empty;
while (decimalNumber > 0)
{
remainder = decimalNumber % 2;
decimalNumber /= 2;
result = remainder.ToString() + result;
}
Console.WriteLine("Binary: {0}",result);
}
}
}
<a href="#" onClick="window.open('http://www.yahoo.com', '_blank')">test</a>
Easy as that.
Or without JS
<a href="http://yahoo.com" target="_blank">test</a>
diff -y --suppress-common-lines file1 file2
It works!
decimal moneyvalue = 1921.39m;
string html = String.Format("Order Total: {0:C}", moneyvalue);
Console.WriteLine(html);
Output
Order Total: $1,921.39
Since you mentioned that you're working on a NFS system, do you have access to those semaphores and shared memory? I think you misunderstood what they are, they are an API code that enables processes to communicate with each other, semaphores are a solution for preventing race conditions and for threads to communicate with each other, in simple answer, they do not leave any residue on any filesystem.
Unless you are using an socket or a pipe? Do you have the necessary permissions to remove them, why are they on an NFS system?
Hope this helps, Best regards, Tom.
Here is a solution which needed ctypes module only. Support pyinstaller wrapped program.
#!python
# coding: utf-8
import sys
import ctypes
def run_as_admin(argv=None, debug=False):
shell32 = ctypes.windll.shell32
if argv is None and shell32.IsUserAnAdmin():
return True
if argv is None:
argv = sys.argv
if hasattr(sys, '_MEIPASS'):
# Support pyinstaller wrapped program.
arguments = map(unicode, argv[1:])
else:
arguments = map(unicode, argv)
argument_line = u' '.join(arguments)
executable = unicode(sys.executable)
if debug:
print 'Command line: ', executable, argument_line
ret = shell32.ShellExecuteW(None, u"runas", executable, argument_line, None, 1)
if int(ret) <= 32:
return False
return None
if __name__ == '__main__':
ret = run_as_admin()
if ret is True:
print 'I have admin privilege.'
raw_input('Press ENTER to exit.')
elif ret is None:
print 'I am elevating to admin privilege.'
raw_input('Press ENTER to exit.')
else:
print 'Error(ret=%d): cannot elevate privilege.' % (ret, )
If you work in IntelliJ, there are four independent ways to refresh maven repositories. Each of them refreshes another local repository on your computer or refreshes them differently.
1. mvn -U clean install
2. Ctrl+Shift+A - Reimport
3. Round arrows in the Maven window
4. Ctrl+Alt+S , go to Build, Execution, Deployment | Build Tools | Maven | Repositories -choose rep - update
What is interesting, it is often said, that the last refresh is equal to the round arrows in the Maven window. But, according to my experience, they are absolutely different! The proof: Our large project fails the last refresh, but exists and runs happily without it. And double round arrows run OK on it.
Each of these four can help you with your problems or/and find problems of its own. For example, for running our real-life project only the first is necessary, but for testing in IntelliJ we also need 2 and 3. Surely, somebody needs 4, too. (Why else IntelliJ has it?)
Qiqi Abaziz's answer is ok, but I still struggled for a long time getting it to work with the compatibility pack and to apply the style to the correct elements. Also, the transparency-hack is unneccessary. So here is a complete example working for v8 and up:
values\styles.xml
<?xml version="1.0" encoding="utf-8"?>
<resources>
<style name="MyActivityTheme" parent="@style/Theme.AppCompat">
<item name="actionBarStyle">@style/NoLogoActionBar</item> <!-- pre-v11-compatibility -->
<item name="android:actionBarStyle">@style/NoLogoActionBar</item>
</style>
<style name="NoLogoActionBar" parent="@style/Widget.AppCompat.ActionBar">
<item name="displayOptions">showHome</item> <!-- pre-v11-compatibility -->
<item name="android:displayOptions">showHome</item>
</style>
</resources>
AndroidManifest.xml (shell)
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android">
<uses-sdk android:minSdkVersion="8" android:targetSdkVersion="19"/>
<application android:theme="@android:style/Theme.Light.NoTitleBar">
<activity android:theme="@style/PentActivityTheme"/>
</application>
</manifest>
In older Java versions, instead of "::" or lambd, you can use:
public interface Action {
void execute();
}
public class ActionImpl implements Action {
@Override
public void execute() {
System.out.println("execute with ActionImpl");
}
}
public static void main(String[] args) {
Action action = new Action() {
@Override
public void execute() {
System.out.println("execute with anonymous class");
}
};
action.execute();
//or
Action actionImpl = new ActionImpl();
actionImpl.execute();
}
Or passing to the method:
public static void doSomething(Action action) {
action.execute();
}
this.setState({abc: {xyz: 'new value'}});
will NOT work, as state.abc
will be entirely overwritten, not merged.
This works for me:
this.setState((previousState) => {
previousState.abc.xyz = 'blurg';
return previousState;
});
Unless I'm reading the docs wrong, Facebook recommends the above format. https://facebook.github.io/react/docs/component-api.html
Additionally, I guess the most direct way without mutating state is to directly copy by using the ES6 spread/rest operator:
const newState = { ...this.state.abc }; // deconstruct state.abc into a new object-- effectively making a copy
newState.xyz = 'blurg';
this.setState(newState);
If you need to import more than just one or two photos then take a look at this article that I wrote. It describes an easy way to perform a bulk import of photos and works for iOS 4.x.
It depends on your mark-up, but it can certainly be made to work, I used the following:
$(document).ready(
function() {
$('td p').slideUp();
$('td h2').click(
function(){
$(this).siblings('p').slideToggle();
}
);
}
);
<table>
<thead>
<tr>
<th>Actor</th>
<th>Which Doctor</th>
<th>Significant companion</th>
</tr>
</thead>
<tbody>
<tr>
<td><h2>William Hartnell</h2></td>
<td><h2>First</h2><p>Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas.</p></td>
<td><h2>Susan Foreman</h2><p>Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Vestibulum tortor quam, feugiat vitae, ultricies eget, tempor sit amet, ante. Donec eu libero sit amet quam egestas semper. Aenean ultricies mi vitae est. Mauris placerat eleifend leo.</p></td>
</tr>
<tr>
<td><h2>Patrick Troughton</h2></td>
<td><h2>Second</h2><p>Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas.</p></td>
<td><h2>Jamie MacCrimmon</h2><p>Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Vestibulum tortor quam, feugiat vitae, ultricies eget, tempor sit amet, ante. Donec eu libero sit amet quam egestas semper. Aenean ultricies mi vitae est. Mauris placerat eleifend leo.</p></td>
</tr>
<tr>
<td><h2>Jon Pertwee</h2></td>
<td><h2>Third</h2><p>Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas.</p></td>
<td><h2>Jo Grant</h2><p>Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Vestibulum tortor quam, feugiat vitae, ultricies eget, tempor sit amet, ante. Donec eu libero sit amet quam egestas semper. Aenean ultricies mi vitae est. Mauris placerat eleifend leo.</p></td>
</tr>
</tbody>
</table>
The way I approached it is to collapse specific elements within the cells of the row, so that, in my case, the row would slideUp()
as the paragraphs were hidden, and still leave an element, h2
to click on in order to re-show the content. If the row collapsed entirely there'd be no easily obvious way to bring it back.
As @Peter Ajtai noted, in the comments, the above approach focuses on only one cell (though deliberately). To expand all the child p
elements this would work:
$(document).ready(
function() {
$('td p').slideUp();
$('td h2').click(
function(){
$(this).closest('tr').find('p').slideToggle();
}
);
}
);
At the very core, the file extension you use makes no difference as to how perl
interprets those files.
However, putting modules in .pm
files following a certain directory structure that follows the package name provides a convenience. So, if you have a module Example::Plot::FourD
and you put it in a directory Example/Plot/FourD.pm
in a path in your @INC
, then use
and require
will do the right thing when given the package name as in use Example::Plot::FourD
.
The file must return true as the last statement to indicate successful execution of any initialization code, so it's customary to end such a file with
1;
unless you're sure it'll return true otherwise. But it's better just to put the1;
, in case you add more statements.If
EXPR
is a bareword, therequire
assumes a ".pm" extension and replaces "::" with "/" in the filename for you, to make it easy to load standard modules. This form of loading of modules does not risk altering your namespace.
All use
does is to figure out the filename from the package name provided, require
it in a BEGIN
block and invoke import
on the package. There is nothing preventing you from not using use
but taking those steps manually.
For example, below I put the Example::Plot::FourD
package in a file called t.pl
, loaded it in a script in file s.pl
.
C:\Temp> cat t.pl
package Example::Plot::FourD;
use strict; use warnings;
sub new { bless {} => shift }
sub something { print "something\n" }
"Example::Plot::FourD"
C:\Temp> cat s.pl
#!/usr/bin/perl
use strict; use warnings;
BEGIN {
require 't.pl';
}
my $p = Example::Plot::FourD->new;
$p->something;
C:\Temp> s
something
This example shows that module files do not have to end in 1
, any true value will do.
Problem:
Try running below(without solution) from Internet Explorer and see the result.
console.log("abcde".includes("cd"));
_x000D_
Solution:
Now run below solution and check the result
if (!String.prototype.includes) {//To check browser supports or not_x000D_
String.prototype.includes = function (str) {//If not supported, then define the method_x000D_
return this.indexOf(str) !== -1;_x000D_
}_x000D_
}_x000D_
console.log("abcde".includes("cd"));
_x000D_
Following works out for me.
#!/usr/bin/env python
a = [{ 'main_color': 'red', 'second_color':'blue'},
{ 'main_color': 'yellow', 'second_color':'green'},
{ 'main_color': 'yellow', 'second_color':'blue'}]
found_event = next(
filter(
lambda x: x['main_color'] == 'red',
a
),
#return this dict when not found
dict(
name='red',
value='{}'
)
)
if found_event:
print(found_event)
$python /tmp/x
{'main_color': 'red', 'second_color': 'blue'}
Yes, see the following from String Resources: Formatting and Styling
If you need to format your strings using
String.format(String, Object...)
, then you can do so by putting your format arguments in the string resource. For example, with the following resource:<string name="welcome_messages">Hello, %1$s! You have %2$d new messages.</string>
In this example, the format string has two arguments:
%1$s
is a string and%2$d
is a decimal number. You can format the string with arguments from your application like this:Resources res = getResources(); String text = String.format(res.getString(R.string.welcome_messages), username, mailCount);
Note that getString
has an overload that uses the string as a format string:
String text = res.getString(R.string.welcome_messages, username, mailCount);
If you need to handle plurals, use this:
<plurals name="welcome_messages">
<item quantity="one">Hello, %1$s! You have a new message.</item>
<item quantity="other">Hello, %1$s! You have %2$d new messages.</item>
</plurals>
The first mailCount
param is used to decide which format to use (single or plural), the other params are your substitutions:
Resources res = getResources();
String text = res.getQuantityString(R.plurals.welcome_messages, mailCount, username, mailCount);
See String Resources: Plurals for more details.
You can use dtype=np.int64
instead of dtype=int
Packaging of pom
is used in projects that aggregate other projects, and in projects whose only useful output is an attached artifact from some plugin. In your case, I'd guess that your top-level pom includes <modules>...</modules>
to aggregate other directories, and the actual output is the result of one of the other (probably sub-) directories. It will, if coded sensibly for this purpose, have a packaging of war
.
I created dummy sample for Google Maps v2 Android with Kotlin and AndroidX
You can find complete project here: github-link
MainActivity.kt
class MainActivity : AppCompatActivity() {
val position = LatLng(-33.920455, 18.466941)
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
with(mapView) {
// Initialise the MapView
onCreate(null)
// Set the map ready callback to receive the GoogleMap object
getMapAsync{
MapsInitializer.initialize(applicationContext)
setMapLocation(it)
}
}
}
private fun setMapLocation(map : GoogleMap) {
with(map) {
moveCamera(CameraUpdateFactory.newLatLngZoom(position, 13f))
addMarker(MarkerOptions().position(position))
mapType = GoogleMap.MAP_TYPE_NORMAL
setOnMapClickListener {
Toast.makeText(this@MainActivity, "Clicked on map", Toast.LENGTH_SHORT).show()
}
}
}
override fun onResume() {
super.onResume()
mapView.onResume()
}
override fun onPause() {
super.onPause()
mapView.onPause()
}
override fun onDestroy() {
super.onDestroy()
mapView.onDestroy()
}
override fun onLowMemory() {
super.onLowMemory()
mapView.onLowMemory()
}
}
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools" package="com.murgupluoglu.googlemap">
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme"
tools:ignore="GoogleAppIndexingWarning">
<meta-data
android:name="com.google.android.geo.API_KEY"
android:value="API_KEY_HERE" />
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN"/>
<category android:name="android.intent.category.LAUNCHER"/>
</intent-filter>
</activity>
</application>
</manifest>
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<com.google.android.gms.maps.MapView
android:layout_width="0dp"
android:layout_height="0dp"
android:id="@+id/mapView"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"/>
</androidx.constraintlayout.widget.ConstraintLayout>
Can't you use
id = id.substring(0, id.length()-4);
And what Eric said, ofcourse.