Top answers on this page use too simple examples like object with one property (e.g. {name: value}). I think that still simple but real life example can help someone.
So this is the JSON returned by Google Translate API:
{
"data":
{
"translations":
[
{
"translatedText": "Arbeit"
}
]
}
}
I want to retrieve the value of "translatedText" attribute e.g. "Arbeit" using Google's Gson.
Two possible approaches:
Retrieve just one needed attribute
String json = callToTranslateApi("work", "de");
JsonObject jsonObject = new JsonParser().parse(json).getAsJsonObject();
return jsonObject.get("data").getAsJsonObject()
.get("translations").getAsJsonArray()
.get(0).getAsJsonObject()
.get("translatedText").getAsString();
Create Java object from JSON
class ApiResponse {
Data data;
class Data {
Translation[] translations;
class Translation {
String translatedText;
}
}
}
...
Gson g = new Gson();
String json =callToTranslateApi("work", "de");
ApiResponse response = g.fromJson(json, ApiResponse.class);
return response.data.translations[0].translatedText;
Try this:
declare @var char(3)
set @var='[%]'
select Address from Accomodation where Address like '%'+@var+'%'
You must use [] cancels the effect of wildcard, so you read % as a normal character, idem about character _
This can also be achieved using the Scalar-Valued Function
in MSSQL 2008
Declare your function as following,
CREATE FUNCTION [dbo].[FunctionName]
(@MaskId INT)
RETURNS Varchar(500)
AS
BEGIN
DECLARE @SchoolName varchar(500)
SELECT @SchoolName =ISNULL(@SchoolName ,'')+ MD.maskdetail +', '
FROM maskdetails MD WITH (NOLOCK)
AND MD.MaskId=@MaskId
RETURN @SchoolName
END
And then your final query will be like
SELECT m.maskid,m.maskname,m.schoolid,s.schoolname,
(SELECT [dbo].[FunctionName](m.maskid)) 'maskdetail'
FROM tblmask m JOIN school s on s.id = m.schoolid
ORDER BY m.maskname ;
Note: You may have to change the function, as I don't know the complete table structure.
You can use the rootViewController
also when your controller is not a UINavigationController
:
UIViewController *vc = self.window.rootViewController;
Once you know the root view controller, then it depends on how you have built your UI, but you can possibly find out a way to navigate through the controllers hierarchy.
If you give some more details about the way you defined your app, then I might give some more hint.
EDIT:
If you want the topmost view (not view controller), you could check
[[[[UIApplication sharedApplication] keyWindow] subviews] lastObject];
although this view might be invisible or even covered by some of its subviews...
again, it depends on your UI, but this might help...
throw $e->getMessage();
You try to throw a string
As a sidenote: Exceptions are usually to define exceptional states of the application and not for error messages after validation. Its not an exception, when a user gives you invalid data
Best thing I found is: https://github.com/mattt/TTTAttributedLabel
It's a UILabel subclass so you can just drop it in, and then to change the line height:
myLabel.lineHeightMultiple = 0.85;
myLabel.leading = 2;
Here is another method to add days on date using dateutil's relativedelta.
from datetime import datetime
from dateutil.relativedelta import relativedelta
print 'Today: ',datetime.now().strftime('%d/%m/%Y %H:%M:%S')
date_after_month = datetime.now()+ relativedelta(day=1)
print 'After a Days:', date_after_month.strftime('%d/%m/%Y %H:%M:%S')
Output:
Today: 25/06/2015 20:41:44
After a Days: 01/06/2015 20:41:44
You are looking for the chr
function.
You seem to be mixing decimal representations of integers and hex representations of integers, so it's not entirely clear what you need. Based on the description you gave, I think one of these snippets shows what you want.
>>> chr(0x65) == '\x65'
True
>>> hex(65)
'0x41'
>>> chr(65) == '\x41'
True
Note that this is quite different from a string containing an integer as hex. If that is what you want, use the hex
builtin.
Use this:
((AssemblyFileVersionAttribute)Attribute.GetCustomAttribute(
Assembly.GetExecutingAssembly(),
typeof(AssemblyFileVersionAttribute), false)
).Version;
Or this:
new Version(System.Windows.Forms.Application.ProductVersion);
The following will work for KornShell(ksh) where the process substitution is not available,
# create a combined(stdin and stdout) collector
exec 3 <> combined.log
# stream stderr instead of stdout to tee, while draining all stdout to the collector
./aaa.sh 2>&1 1>&3 | tee -a stderr.log 1>&3
# cleanup collector
exec 3>&-
The real trick here, is the sequence of the 2>&1 1>&3
which in our case redirects the stderr
to stdout
and redirects the stdout
to descriptor 3
. At this point the stderr
and stdout
are not combined yet.
In effect, the stderr
(as stdin
) is passed to tee
where it logs to stderr.log
and also redirects to descriptor 3.
And descriptor 3
is logging it to combined.log
all the time. So the combined.log
contains both stdout
and stderr
.
If you prefer a one-liner:
matched_lines = [line for line in my_string.split('\n') if "substring" in line]
I have been using MongoDB .NET driver for a little over a month now. If I were to do it using .NET driver, I would use Update method on the collection object. First, I will construct a query that will get me all the documents I am interested in and do an Update on the fields I want to change. Update in Mongo only affects the first document and to update all documents resulting from the query one needs to use 'Multi' update flag. Sample code follows...
var collection = db.GetCollection("Foo");
var query = Query.GTE("No", 1); // need to construct in such a way that it will give all 20K //docs.
var update = Update.Set("timestamp", datetime.UtcNow);
collection.Update(query, update, UpdateFlags.Multi);
1.Clear browser cache in browser developer tools 2.Under Network tab – select Disable cache option 3.Restarted browser 4.Force reload Js file command+shift+R in mac Make sure the fresh war is deployed properly on the Server side
Using Java 8, you can simply use ncopies
of Collections
class:
Object[] arrays = Collections.nCopies(size, object).stream().toArray();
In your case it will be:
Integer[] arrays = Collections.nCopies(10, Integer.valueOf(1)).stream().toArray(Integer[]::new);
.
Here is a detailed answer of a similar case of yours.
EADDRINUSE
means that the port number which listen()
tries to bind the server to is already in use.
So, in your case, there must be running a server on port 80 already.
If you have another webserver running on this port you have to put node.js behind that server and proxy it through it.
You should check for the listening
event like this, to see if the server is really listening:
var http=require('http');
var server=http.createServer(function(req,res){
res.end('test');
});
server.on('listening',function(){
console.log('ok, server is running');
});
server.listen(80);
As stated in the JQuery documentation
The focusout event is sent to an element when it, or any element inside of it, loses focus. This is distinct from the blur event in that it supports detecting the loss of focus on descendant elements (in other words, it supports event bubbling).
Please stop all services MySQL with following command /etc/init.d/mysqld stop After it use this
mysqld_safe --skip-grant-tables
its may work properly
Is there any better way than just looping through and manually comparing the two fields for each object and then breaking when found? That just seems so messy, looking for a better way.
If your concern is maintainability you could do what Fabian Steeg suggest ( that's what I would do ) although it probably isn't the "most efficient" ( because you have to sort the array first and then perform the binary search ) but certainly the cleanest and better option.
If you're really concerned with efficiency, you can create a custom List implementation that uses the field in your object as the hash and use a HashMap as storage. But probably this would be too much.
Then you have to change the place where you fill the data from ArrayList to YourCustomList.
Like:
List list = new ArrayList();
fillFromSoap( list );
To:
List list = new MyCustomSpecialList();
fillFromSoap( list );
The implementation would be something like the following:
class MyCustomSpecialList extends AbstractList {
private Map<Integer, YourObject> internalMap;
public boolean add( YourObject o ) {
internalMap.put( o.getThatFieldYouKnow(), o );
}
public boolean contains( YourObject o ) {
return internalMap.containsKey( o.getThatFieldYouKnow() );
}
}
Pretty much like a HashSet, the problem here is the HashSet relies on the good implementation of the hashCode method, which probably you don't have. Instead you use as the hash "that field you know" which is the one that makes one object equals to the other.
Of course implementing a List from the scratch lot more tricky than my snippet above, that's why I say the Fabian Steeg suggestion would be better and easier to implement ( although something like this would be more efficient )
Tell us what you did at the end.
A fragment must always be embedded in an activity and the fragment's lifecycle is directly affected by the host activity's lifecycle. For example, when the activity is paused, so are all fragments in it, and when the activity is destroyed, so are all fragments
You'd use REGEXP_REPLACE
in order to remove all non-digit characters from a string:
select regexp_replace(column_name, '[^0-9]', '')
from mytable;
or
select regexp_replace(column_name, '[^[:digit:]]', '')
from mytable;
Of course you can write a function extract_number
. It seems a bit like overkill though, to write a funtion that consists of only one function call itself.
create function extract_number(in_number varchar2) return varchar2 is
begin
return regexp_replace(in_number, '[^[:digit:]]', '');
end;
Having trouble wrapping my head around this.
Have a rewrite rule with four conditions.
The first three conditions A, B, C are to be AND which is then OR with D
RewriteCond A true
RewriteCond B false
RewriteCond C [OR] true
RewriteCond D true
RewriteRule ...
But that seems to be an expression of A and B and (C or D) = false (don't rewrite)
How can I get to the desired expression? (A and B and C) or D = true (rewrite)
Preferably without using the additional steps of setting environment variables.
HELP!!!
The following SQL Code will help you to calculate the median in MySQL using user defined variables.
create table employees(salary int);_x000D_
_x000D_
insert into employees values(8);_x000D_
insert into employees values(23);_x000D_
insert into employees values(45);_x000D_
insert into employees values(123);_x000D_
insert into employees values(93);_x000D_
insert into employees values(2342);_x000D_
insert into employees values(2238);_x000D_
_x000D_
select * from employees;_x000D_
_x000D_
Select salary from employees order by salary;_x000D_
_x000D_
set @rowid=0;_x000D_
set @cnt=(select count(*) from employees);_x000D_
set @middle_no=ceil(@cnt/2);_x000D_
set @odd_even=null;_x000D_
_x000D_
select AVG(salary) from _x000D_
(select salary,@rowid:=@rowid+1 as rid, (CASE WHEN(mod(@cnt,2)=0) THEN @odd_even:=1 ELSE @odd_even:=0 END) as odd_even_status from employees order by salary) as tbl where tbl.rid=@middle_no or tbl.rid=(@middle_no+@odd_even);
_x000D_
If you are looking for detailed explanation, please refer this blog.
You can find the Team ID via this link: https://developer.apple.com/membercenter/index.action#accountSummary
Here we go,
DataSet ds = new DataSet();
SqlCommand cmd = new SqlCommand();
cmd.Connection = con; //database connection
cmd.CommandText = "WRITE_STORED_PROC_NAME"; // Stored procedure name
cmd.CommandType = CommandType.StoredProcedure; // set it to stored proc
//add parameter if necessary
cmd.Parameters.Add("@userId", SqlDbType.Int).Value = courseid;
SqlDataAdapter adap = new SqlDataAdapter(cmd);
adap.Fill(ds, "Course");
return ds;
Update on data.table methods for joining datasets. See below examples for each type of join. There are two methods, one from [.data.table
when passing second data.table as the first argument to subset, another way is to use merge
function which dispatches to fast data.table method.
df1 = data.frame(CustomerId = c(1:6), Product = c(rep("Toaster", 3), rep("Radio", 3)))
df2 = data.frame(CustomerId = c(2L, 4L, 7L), State = c(rep("Alabama", 2), rep("Ohio", 1))) # one value changed to show full outer join
library(data.table)
dt1 = as.data.table(df1)
dt2 = as.data.table(df2)
setkey(dt1, CustomerId)
setkey(dt2, CustomerId)
# right outer join keyed data.tables
dt1[dt2]
setkey(dt1, NULL)
setkey(dt2, NULL)
# right outer join unkeyed data.tables - use `on` argument
dt1[dt2, on = "CustomerId"]
# left outer join - swap dt1 with dt2
dt2[dt1, on = "CustomerId"]
# inner join - use `nomatch` argument
dt1[dt2, nomatch=NULL, on = "CustomerId"]
# anti join - use `!` operator
dt1[!dt2, on = "CustomerId"]
# inner join - using merge method
merge(dt1, dt2, by = "CustomerId")
# full outer join
merge(dt1, dt2, by = "CustomerId", all = TRUE)
# see ?merge.data.table arguments for other cases
Below benchmark tests base R, sqldf, dplyr and data.table.
Benchmark tests unkeyed/unindexed datasets.
Benchmark is performed on 50M-1 rows datasets, there are 50M-2 common values on join column so each scenario (inner, left, right, full) can be tested and join is still not trivial to perform. It is type of join which well stress join algorithms. Timings are as of sqldf:0.4.11
, dplyr:0.7.8
, data.table:1.12.0
.
# inner
Unit: seconds
expr min lq mean median uq max neval
base 111.66266 111.66266 111.66266 111.66266 111.66266 111.66266 1
sqldf 624.88388 624.88388 624.88388 624.88388 624.88388 624.88388 1
dplyr 51.91233 51.91233 51.91233 51.91233 51.91233 51.91233 1
DT 10.40552 10.40552 10.40552 10.40552 10.40552 10.40552 1
# left
Unit: seconds
expr min lq mean median uq max
base 142.782030 142.782030 142.782030 142.782030 142.782030 142.782030
sqldf 613.917109 613.917109 613.917109 613.917109 613.917109 613.917109
dplyr 49.711912 49.711912 49.711912 49.711912 49.711912 49.711912
DT 9.674348 9.674348 9.674348 9.674348 9.674348 9.674348
# right
Unit: seconds
expr min lq mean median uq max
base 122.366301 122.366301 122.366301 122.366301 122.366301 122.366301
sqldf 611.119157 611.119157 611.119157 611.119157 611.119157 611.119157
dplyr 50.384841 50.384841 50.384841 50.384841 50.384841 50.384841
DT 9.899145 9.899145 9.899145 9.899145 9.899145 9.899145
# full
Unit: seconds
expr min lq mean median uq max neval
base 141.79464 141.79464 141.79464 141.79464 141.79464 141.79464 1
dplyr 94.66436 94.66436 94.66436 94.66436 94.66436 94.66436 1
DT 21.62573 21.62573 21.62573 21.62573 21.62573 21.62573 1
Be aware there are other types of joins you can perform using data.table
:
- update on join - if you want to lookup values from another table to your main table
- aggregate on join - if you want to aggregate on key you are joining you do not have to materialize all join results
- overlapping join - if you want to merge by ranges
- rolling join - if you want merge to be able to match to values from preceeding/following rows by rolling them forward or backward
- non-equi join - if your join condition is non-equal
Code to reproduce:
library(microbenchmark)
library(sqldf)
library(dplyr)
library(data.table)
sapply(c("sqldf","dplyr","data.table"), packageVersion, simplify=FALSE)
n = 5e7
set.seed(108)
df1 = data.frame(x=sample(n,n-1L), y1=rnorm(n-1L))
df2 = data.frame(x=sample(n,n-1L), y2=rnorm(n-1L))
dt1 = as.data.table(df1)
dt2 = as.data.table(df2)
mb = list()
# inner join
microbenchmark(times = 1L,
base = merge(df1, df2, by = "x"),
sqldf = sqldf("SELECT * FROM df1 INNER JOIN df2 ON df1.x = df2.x"),
dplyr = inner_join(df1, df2, by = "x"),
DT = dt1[dt2, nomatch=NULL, on = "x"]) -> mb$inner
# left outer join
microbenchmark(times = 1L,
base = merge(df1, df2, by = "x", all.x = TRUE),
sqldf = sqldf("SELECT * FROM df1 LEFT OUTER JOIN df2 ON df1.x = df2.x"),
dplyr = left_join(df1, df2, by = c("x"="x")),
DT = dt2[dt1, on = "x"]) -> mb$left
# right outer join
microbenchmark(times = 1L,
base = merge(df1, df2, by = "x", all.y = TRUE),
sqldf = sqldf("SELECT * FROM df2 LEFT OUTER JOIN df1 ON df2.x = df1.x"),
dplyr = right_join(df1, df2, by = "x"),
DT = dt1[dt2, on = "x"]) -> mb$right
# full outer join
microbenchmark(times = 1L,
base = merge(df1, df2, by = "x", all = TRUE),
dplyr = full_join(df1, df2, by = "x"),
DT = merge(dt1, dt2, by = "x", all = TRUE)) -> mb$full
lapply(mb, print) -> nul
Multiple drop downs with checkbox's and jQuery.
<div id="list3" class="dropdown-check-list" tabindex="100">
<span class="anchor">Which development(s) are you interested in?</span>
<ul class="items">
<li><input id="answers_2529_the-lawns" name="answers[2529][answers][]" type="checkbox" value="The Lawns"/><label for="answers_2529_the-lawns">The Lawns</label></li>
<li><input id="answers_2529_the-residence" name="answers[2529][answers][]" type="checkbox" value="The Residence"/><label for="answers_2529_the-residence">The Residence</label></li>
</ul>
</div>
<style>
.dropdown-check-list{
display: inline-block;
width: 100%;
}
.dropdown-check-list:focus{
outline:0;
}
.dropdown-check-list .anchor {
width: 98%;
position: relative;
cursor: pointer;
display: inline-block;
padding-top:5px;
padding-left:5px;
padding-bottom:5px;
border:1px #ccc solid;
}
.dropdown-check-list .anchor:after {
position: absolute;
content: "";
border-left: 2px solid black;
border-top: 2px solid black;
padding: 5px;
right: 10px;
top: 20%;
-moz-transform: rotate(-135deg);
-ms-transform: rotate(-135deg);
-o-transform: rotate(-135deg);
-webkit-transform: rotate(-135deg);
transform: rotate(-135deg);
}
.dropdown-check-list .anchor:active:after {
right: 8px;
top: 21%;
}
.dropdown-check-list ul.items {
padding: 2px;
display: none;
margin: 0;
border: 1px solid #ccc;
border-top: none;
}
.dropdown-check-list ul.items li {
list-style: none;
}
.dropdown-check-list.visible .anchor {
color: #0094ff;
}
.dropdown-check-list.visible .items {
display: block;
}
</style>
<script>
jQuery(function ($) {
var checkList = $('.dropdown-check-list');
checkList.on('click', 'span.anchor', function(event){
var element = $(this).parent();
if ( element.hasClass('visible') )
{
element.removeClass('visible');
}
else
{
element.addClass('visible');
}
});
});
</script>
StringBuilder sb = new StringBuilder();
for(int i=0;i<100;i++){
sb.insert(0, Integer.toString(i));
}
Warning: It defeats the purpose of StringBuilder
, but it does what you asked.
Better technique (although still not ideal):
StringBuilder
.StringBuilder
when you're done.This will turn an O(n²) solution into O(n).
that will do it all without css
<TABLE BORDER=1 RULES=ALL FRAME=VOID>
code from: HTML CODE TUTORIAL
I don't recall of a "indexOf" on arrays other than coding it for yourself... though you could probably use one of the many java.util.Arrays#binarySearch(...)
methods (see the Arrays javadoc) if your array contains primitive types
The <ul>
element has browser inherent padding & margin by default. In your case, Use
#footer ul {
margin: 0; /* To remove default bottom margin */
padding: 0; /* To remove default left padding */
}
or a CSS browser reset ( https://cssreset.com/ ) to deal with this.
int[] anArray = { 1, 5, 2, 7 };
// Finding max
int m = anArray.Max();
// Positioning max
int p = Array.IndexOf(anArray, m);
syntax is:
sheet.addMergedRegion(new CellRangeAddress(start-col,end-col,start-cell,end-cell));
Example:
sheet.addMergedRegion(new CellRangeAddress(4, 4, 0, 5));
Here the cell 0 to cell 5 will be merged of the 4th row.
Minimal POSIX C exit status example
To understand $?
, you must first understand the concept of process exit status which is defined by POSIX. In Linux:
when a process calls the exit
system call, the kernel stores the value passed to the system call (an int
) even after the process dies.
The exit system call is called by the exit()
ANSI C function, and indirectly when you do return
from main
.
the process that called the exiting child process (Bash), often with fork
+ exec
, can retrieve the exit status of the child with the wait
system call
Consider the Bash code:
$ false
$ echo $?
1
The C "equivalent" is:
false.c
#include <stdlib.h> /* exit */
int main(void) {
exit(1);
}
bash.c
#include <unistd.h> /* execl */
#include <stdlib.h> /* fork */
#include <sys/wait.h> /* wait, WEXITSTATUS */
#include <stdio.h> /* printf */
int main(void) {
if (fork() == 0) {
/* Call false. */
execl("./false", "./false", (char *)NULL);
}
int status;
/* Wait for a child to finish. */
wait(&status);
/* Status encodes multiple fields,
* we need WEXITSTATUS to get the exit status:
* http://stackoverflow.com/questions/3659616/returning-exit-code-from-child
**/
printf("$? = %d\n", WEXITSTATUS(status));
}
Compile and run:
g++ -ggdb3 -O0 -std=c++11 -Wall -Wextra -pedantic -o bash bash.c
g++ -ggdb3 -O0 -std=c++11 -Wall -Wextra -pedantic -o false false.c
./bash
Output:
$? = 1
In Bash, when you hit enter, a fork + exec + wait happens like above, and bash then sets $?
to the exit status of the forked process.
Note: for built-in commands like echo
, a process need not be spawned, and Bash just sets $?
to 0 to simulate an external process.
Standards and documentation
POSIX 7 2.5.2 "Special Parameters" http://pubs.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#tag_18_05_02 :
? Expands to the decimal exit status of the most recent pipeline (see Pipelines).
man bash
"Special Parameters":
The shell treats several parameters specially. These parameters may only be referenced; assignment to them is not allowed. [...]
? Expands to the exit status of the most recently executed foreground pipeline.
ANSI C and POSIX then recommend that:
0
means the program was successful
other values: the program failed somehow.
The exact value could indicate the type of failure.
ANSI C does not define the meaning of any vaues, and POSIX specifies values larger than 125: What is the meaning of "POSIX"?
Bash uses exit status for if
In Bash, we often use the exit status $?
implicitly to control if
statements as in:
if true; then
:
fi
where true
is a program that just returns 0.
The above is equivalent to:
true
result=$?
if [ $result = 0 ]; then
:
fi
And in:
if [ 1 = 1 ]; then
:
fi
[
is just an program with a weird name (and Bash built-in that behaves like it), and 1 = 1 ]
its arguments, see also: Difference between single and double square brackets in Bash
.e:hover{
background-color:#FF0000;
}
java.util.Date date= new Date();
Calendar cal = Calendar.getInstance();
cal.setTime(date);
int month = cal.get(Calendar.MONTH);
I too have this problem: EclipseNeon + Tomcat8 doesn't show all the variables when in debug mode. I've tried above suggestions without success. Then I have debugged the same web project with NetBeans8 + GlassFish4 and all the variables are listed with values. Then I have debugged the same web project with NetBeans8 + Tomcat8 and not all the variables are listed. Then I've installed GlassFish4 for EclipseNeon and, debugging the same web project, all the variables are listed with values. So, the problem is in Tomcat8. A note: run Eclipse as administrator to install GlassFish4; with NetBeans is easier to install other servers.
window.location
always refers to the location of the current window. Changing it will affect only the current window.
One thing that can be done is forcing a click on the link after setting its target
attribute to _blank
:
Check this: http://www.techfoobar.com/2012/jquery-programmatically-clicking-a-link-and-forcing-the-default-action
Disclaimer: Its my blog.
If you want PHP to treat $_GET['select2']
as an array of options just add square brackets to the name of the select element like this: <select name="select2[]" multiple …
Then you can acces the array in your PHP script
<?php
header("Content-Type: text/plain");
foreach ($_GET['select2'] as $selectedOption)
echo $selectedOption."\n";
$_GET
may be substituted by $_POST
depending on the <form method="…"
value.
Fairly straightforward:
git remote rm origin
As for the filter-branch
question - just add --prune-empty
to your filter branch command and it'll remove any revision that doesn't actually contain any changes in your resulting repo:
git filter-branch --prune-empty --subdirectory-filter path/to/subtree HEAD
In the code below, Class A
implements the interface IShow
and implements its method ShowData
. Class B
inherits Class A
. In order to use ShowData
method in Class B
, we have to use keyword new
in the ShowData
method in order to hide the base class Class A
method and use override
keyword in order to extend the method.
interface IShow
{
protected void ShowData();
}
class A : IShow
{
protected void ShowData()
{
Console.WriteLine("This is Class A");
}
}
class B : A
{
protected new void ShowData()
{
Console.WriteLine("This is Class B");
}
}
You can always add your own AssemblyInfo.cs, which comes in handy for InternalsVisibleToAttribute
, CLSCompliantAttribute
and others that are not automatically generated.
<project name> > Add > New Folder
. Add > New Item...
.If you want to move your attributes back to AssemblyInfo.cs instead of having them auto-generated, you can suppress them in MSBuild as natemcmaster pointed out in his answer.
Specifically, I got this issue when attempting to retrieve the default (no-args) InitialContext
within an embedded Tomcat7 instance, in SpringBoot.
The solution for me, was to tell Tomcat to enableNaming
.
i.e.
@Bean
public TomcatEmbeddedServletContainerFactory tomcatFactory() {
return new TomcatEmbeddedServletContainerFactory() {
@Override
protected TomcatEmbeddedServletContainer getTomcatEmbeddedServletContainer(
Tomcat tomcat) {
tomcat.enableNaming();
return super.getTomcatEmbeddedServletContainer(tomcat);
}
};
}
You can get around this by using a traits class:
It requires you set up a specialsed traits class for each actuall class you use.
template<typename SubClass>
class SubClass_traits
{};
template<typename Subclass>
class A {
public:
void action(typename SubClass_traits<Subclass>::mytype var)
{
(static_cast<Subclass*>(this))->do_action(var);
}
};
// Definitions for B
class B; // Forward declare
template<> // Define traits for B. So other classes can use it.
class SubClass_traits<B>
{
public:
typedef int mytype;
};
// Define B
class B : public A<B>
{
// Define mytype in terms of the traits type.
typedef SubClass_traits<B>::mytype mytype;
public:
B() {}
void do_action(mytype var) {
// Do stuff
}
};
int main(int argc, char** argv)
{
B myInstance;
return 0;
}
Without an index, maintaining an autoincrement column becomes too expensive, that's why MySQL
requires an autoincrement column to be a leftmost part of an index.
You should remove the autoincrement property before dropping the key:
ALTER TABLE user_customer_permission MODIFY id INT NOT NULL;
ALTER TABLE user_customer_permission DROP PRIMARY KEY;
Note that you have a composite PRIMARY KEY
which covers all three columns and id
is not guaranteed to be unique.
If it happens to be unique, you can make it to be a PRIMARY KEY
and AUTO_INCREMENT
again:
ALTER TABLE user_customer_permission MODIFY id INT NOT NULL PRIMARY KEY AUTO_INCREMENT;
Use $ne
(for "not equal")
db.collection.find({ "fieldToCheck": { $exists: true, $ne: null } })
You could also use Alamofire\AlmofireImage for that task: https://github.com/Alamofire/AlamofireImage
The code should look something like that (Based on the first example on link above):
import AlamofireImage
Alamofire.request("http://i.imgur.com/w5rkSIj.jpg").responseImage { response in
if let catPicture = response.result.value {
print("image downloaded: \(image)")
}
}
While it is neat yet safe, you should consider if that worth the Pod overhead. If you are going to use more images and would like to add also filter and transiations I would consider using AlamofireImage
select case
when exists (SELECT 1 FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = 'Tags' AND COLUMN_NAME = 'ModifiedByUser')
then 0
else 1
end
First in your terminal:
rails g migration change_date_format_in_my_table
Then in your migration file:
For Rails >= 3.2:
class ChangeDateFormatInMyTable < ActiveRecord::Migration
def up
change_column :my_table, :my_column, :datetime
end
def down
change_column :my_table, :my_column, :date
end
end
Even though CMD is written down in the Dockerfile, it really is runtime information. Just like EXPOSE, but contrary to e.g. RUN and ADD. By this, I mean that you can override it later, in an extending Dockerfile, or simple in your run command, which is what you are experiencing. At all times, there can be only one CMD.
If you want to run multiple services, I indeed would use supervisor. You can make a supervisor configuration file for each service, ADD these in a directory, and run the supervisor with supervisord -c /etc/supervisor
to point to a supervisor configuration file which loads all your services and looks like
[supervisord]
nodaemon=true
[include]
files = /etc/supervisor/conf.d/*.conf
If you would like more details, I wrote a blog on this subject here: http://blog.trifork.com/2014/03/11/using-supervisor-with-docker-to-manage-processes-supporting-image-inheritance/
I agree with the compacity of the switch solution but IMO you're hijacking the switch here.
The purpose of the switch is to have different handling depending on the value.
If you had to explain your algo in pseudo-code, you'd use an if because, semantically, that's what it is: if whatever_error do this...
So unless you intend someday to change your code to have specific code for each error, I would use if.
Using python 64 bit solves lot of problems.
if it is coming from server as object you can do
this.service.subscribe(data:any) keep any type on data it will solve the issue
my_hash.each { |k, v| my_hash[k] = v.upcase }
or, if you'd prefer to do it non-destructively, and return a new hash instead of modifying my_hash
:
a_new_hash = my_hash.inject({}) { |h, (k, v)| h[k] = v.upcase; h }
This last version has the added benefit that you could transform the keys too.
The best you could do is have accessor/mutators for the variable.
Something like getTAG()
That way all implementing classes would have to implement them.
Abstract classes are used to define abstract behaviour not data.
Your question is good, it is not only about methods. Functions and objects in modules are commonly prefixed with one underscore as well, and can be prefixed by two.
But __double_underscore names are not name-mangled in modules, for example. What happens is that names beginning with one (or more) underscores are not imported if you import all from a module (from module import *), nor are the names shown in help(module).
What it correct way of installing SmartGit on Ubuntu? Thus I can have normal icon
In smartgit/bin folder, there's a shell script waiting for you: add-menuitem.sh. It does just that.
[In no particular order.] However, if you have any other requirements, let us know. BTW: I am not just posting results of a Google query here, I have used all of these (and SDL -- wrote my first few games in SDL :) and I'd say without a set of requirements, it's very difficult to choose among the ones listed.
I have used below line of code and it works, Try this
DataTable dt = dataSource.Tables[0];
You need to just press CTRL + F5. It will work after that.
So I am not sure I can really think of why you would actually need a "site collection unique" id, so maybe you can comment and let us know what is actually trying to be accomplished here...
Either way, all items have a UniqueID property that is a GUID if you really need it: http://msdn.microsoft.com/en-us/library/microsoft.sharepoint.splistitem.uniqueid.aspx
Check if Tensorflow was installed successfully using:
pip3 show tensorflow
If you get something like
Name: tensorflow
Version: 1.2.1
Summary: TensorFlow helps the tensors flow
Home-page: http://tensorflow.org/
Author: Google Inc.
Author-email: [email protected]
License: Apache 2.0
Location: /usr/local/lib/python3.5/dist-packages
Requires: bleach, markdown, html5lib, backports.weakref, werkzeug, numpy, protobuf, wheel, six
You may try adding the path of your tensorflow location by:
export PYTHONPATH=/your/tensorflow/path:$PYTHONPATH.
Here is a work-around:
js
directory in the same directory as your index.htmljs
directory
https://github.com/FezVrasta/popper.js#installatione.g.: https://unpkg.com/popper.js/dist/umd/popper.min.js
Change your the src of your script include to look like this:
src="js/popper.min.js"
Note that you've removed Popper from npm
version control, so you'll have to manually download updates.
Use references all the time and pointers only when you have to refer to NULL
which reference cannot refer.
See this FAQ : http://www.parashift.com/c++-faq-lite/references.html#faq-8.6
Use WinSCP for file transfer over SSH, putty is only for SSH commands.
Thank you all for your reply. I have got my script working with the module/ script written by Preston Landers way back in 2010. After two days of browsing the internet I could find the script as it was was deeply hidden in pywin32 mailing list. With this script it is easier to check if the user is admin and if not then ask for UAC/ admin right. It does provide output in separate windows to find out what the code is doing. Example on how to use the code also included in the script. For the benefit of all who all are looking for UAC on windows have a look at this code. I hope it helps someone looking for same solution. It can be used something like this from your main script:-
import admin
if not admin.isUserAdmin():
admin.runAsAdmin()
The actual code is:-
#!/usr/bin/env python
# -*- coding: utf-8; mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*-
# vim: fileencoding=utf-8 tabstop=4 expandtab shiftwidth=4
# (C) COPYRIGHT © Preston Landers 2010
# Released under the same license as Python 2.6.5
import sys, os, traceback, types
def isUserAdmin():
if os.name == 'nt':
import ctypes
# WARNING: requires Windows XP SP2 or higher!
try:
return ctypes.windll.shell32.IsUserAnAdmin()
except:
traceback.print_exc()
print "Admin check failed, assuming not an admin."
return False
elif os.name == 'posix':
# Check for root on Posix
return os.getuid() == 0
else:
raise RuntimeError, "Unsupported operating system for this module: %s" % (os.name,)
def runAsAdmin(cmdLine=None, wait=True):
if os.name != 'nt':
raise RuntimeError, "This function is only implemented on Windows."
import win32api, win32con, win32event, win32process
from win32com.shell.shell import ShellExecuteEx
from win32com.shell import shellcon
python_exe = sys.executable
if cmdLine is None:
cmdLine = [python_exe] + sys.argv
elif type(cmdLine) not in (types.TupleType,types.ListType):
raise ValueError, "cmdLine is not a sequence."
cmd = '"%s"' % (cmdLine[0],)
# XXX TODO: isn't there a function or something we can call to massage command line params?
params = " ".join(['"%s"' % (x,) for x in cmdLine[1:]])
cmdDir = ''
showCmd = win32con.SW_SHOWNORMAL
#showCmd = win32con.SW_HIDE
lpVerb = 'runas' # causes UAC elevation prompt.
# print "Running", cmd, params
# ShellExecute() doesn't seem to allow us to fetch the PID or handle
# of the process, so we can't get anything useful from it. Therefore
# the more complex ShellExecuteEx() must be used.
# procHandle = win32api.ShellExecute(0, lpVerb, cmd, params, cmdDir, showCmd)
procInfo = ShellExecuteEx(nShow=showCmd,
fMask=shellcon.SEE_MASK_NOCLOSEPROCESS,
lpVerb=lpVerb,
lpFile=cmd,
lpParameters=params)
if wait:
procHandle = procInfo['hProcess']
obj = win32event.WaitForSingleObject(procHandle, win32event.INFINITE)
rc = win32process.GetExitCodeProcess(procHandle)
#print "Process handle %s returned code %s" % (procHandle, rc)
else:
rc = None
return rc
def test():
rc = 0
if not isUserAdmin():
print "You're not an admin.", os.getpid(), "params: ", sys.argv
#rc = runAsAdmin(["c:\\Windows\\notepad.exe"])
rc = runAsAdmin()
else:
print "You are an admin!", os.getpid(), "params: ", sys.argv
rc = 0
x = raw_input('Press Enter to exit.')
return rc
if __name__ == "__main__":
sys.exit(test())
It may be a little late, but you could use the helper function time() to get the current timestamp. I tried this function and it did the job, no need for classes :).
You can find this in the official documentation at https://laravel.com/docs/5.0/templates
Regards.
Like others mentioned, your app runs in a sandboxed environment and you can use the documents directory to store images or other assets your app may use, eg. downloading offline-d files as user prefers - File System Basics - Apple Documentation - Which directory to use, for storing application specific files
Updated to swift 5, you can use one of these functions, as per requirement -
func getDocumentsDirectory() -> URL {
let paths = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)
return paths[0]
}
func getCacheDirectory() -> URL {
let paths = FileManager.default.urls(for: .cachesDirectory, in: .userDomainMask)
return paths[0]
}
func getApplicationSupportDirectory() -> URL {
let paths = FileManager.default.urls(for: .applicationSupportDirectory, in: .userDomainMask)
return paths[0]
}
Usage:
let urlPath = "https://jumpcloud.com/wp-content/uploads/2017/06/SSH-Keys.png" //Or string path to some URL of valid image, for eg.
if let url = URL(string: urlPath){
let destination = getDocumentsDirectory().appendingPathComponent(url.lastPathComponent)
do {
let data = try Data(contentsOf: url) //Synchronous call, just as an example
try data.write(to: destination)
} catch _ {
//Do something to handle the error
}
}
Another way to do it is a TEXT column. And then convert the boolean value between Boolean and String before/after saving/reading the value from the database.
Ex. You have "boolValue = true;
"
To String:
//convert to the string "TRUE"
string StringValue = boolValue.ToString;
And back to boolean:
//convert the string back to boolean
bool Boolvalue = Convert.ToBoolean(StringValue);
Unlike SOAP, REST isn't a standardized protocol so it's a bit difficult to have a "REST Client". However, since most RESTful services use HTTP as their underlying protocol, you should be able to use any HTTP library. In addition to cURL, PHP has these via PEAR:
which replaced
A sample of how they do HTTP Basic Auth
// This will set credentials for basic auth
$request = new HTTP_Request2('http://user:[email protected]/secret/');
The also support Digest Auth
// This will set credentials for Digest auth
$request->setAuth('user', 'password', HTTP_Request2::AUTH_DIGEST);
Create PDF from External URL
Here's an adaptation of the previous answers which utilizes html-pdf
, but also combines it with requestify
so it works with an external URL:
Install your dependencies
npm i -S html-pdf requestify
Then, create the script:
//MakePDF.js
var pdf = require('html-pdf');
var requestify = require('requestify');
var externalURL= 'http://www.google.com';
requestify.get(externalURL).then(function (response) {
// Get the raw HTML response body
var html = response.body;
var config = {format: 'A4'}; // or format: 'letter' - see https://github.com/marcbachmann/node-html-pdf#options
// Create the PDF
pdf.create(html, config).toFile('pathtooutput/generated.pdf', function (err, res) {
if (err) return console.log(err);
console.log(res); // { filename: '/pathtooutput/generated.pdf' }
});
});
Then you just run from the command line:
node MakePDF.js
Watch your beautify pixel perfect PDF be created for you (for free!)
I had the same problem with my Galaxy S3.
My problem was that the idVendor
value 04E8
was not the right one.
To find the right one connect your smartphone to the computer and run lsusb
in the terminal. It will list your smartphone like this:
Bus 002 Device 010: ID 18d1:d002 Google Inc.
So the right idVendor
value is 18d1
. And the line in the /etc/udev/rules.d/51-android.rules
has to be:
SUBSYSTEM=="usb", ATTR{idVendor}=="18d1", MODE="0666", GROUP="plugdev"
Then I run sudo udevadm control --reload-rules
and everything worked!
I used this approach in a recent project and I was pretty happy with the result:
.select-wrapper {
position: relative;
&::after {
position: absolute;
top: 0;
right: 0;
width: 100px;
height: 100%;
content: "";
background: linear-gradient(to right, transparent, white);
pointer-events: none;
}
}
Basically, wrap the select in a div and insert a pseudo element to overlay the end of the text to create the appearance that the text fades out.
Here is how I handle mine. I create a file called template.php in my views folder. This file contains all of my my main site layout. Then from this template file I call my additional views. Here is an example:
<!doctype html>
<html lang="en">
<head>
<meta charset=utf-8">
<title><?php echo $title; ?></title>
<link href="<?php echo base_url() ;?>assets/css/bootstrap.min.css" rel="stylesheet" type="text/css" />
<link href="<?php echo base_url() ;?>assets/css/main.css" rel="stylesheet" type="text/css" />
<noscript>
Javascript is not enabled! Please turn on Javascript to use this site.
</noscript>
<script type="text/javascript">
//<![CDATA[
base_url = '<?php echo base_url();?>';
//]]>
</script>
</head>
<body>
<div id="wrapper">
<div id="container">
<div id="top">
<?php $this->load->view('top');?>
</div>
<div id="main">
<?php $this->load->view($main);?>
</div>
<div id="footer">
<?php $this->load->view('bottom');?>
</div>
</div><!-- end container -->
</div><!-- end wrapper -->
<script type="text/javascript" src="<?php echo base_url();?>assets/js/jquery-1.8.2.min.js" ></script>
<script type="text/javascript" src="<?php echo base_url();?>assets/js/bootstrap.min.js"></script>
</body>
</html>
From my controller, I will pass the name of the view to $data['main']. So I will do something like this then:
class Main extends CI_Controller {
public function index()
{
$data['main'] = 'main_view';
$data['title'] = 'Site Title';
$this->load->vars($data);
$this->load->view('template', $data);
}
}
I just tried with Git 2.30.0 (released 2020-12-28).
This is NOT a full answer but a few useful tidbits nonetheless. (Feel free to cannibalize for your own answer.)
There's a documentation link when installing Git for Windows
This link takes you here: https://github.com/git-for-windows/git/wiki/Symbolic-Links
And this is quite a longish discussion.
Also symbolic links keep popping up in the release notes. As of 2.30.0 this here is still listed as a "Known issue":
On Windows 10 before 1703, or when Developer Mode is turned off, special permissions are required when cloning repositories with symbolic links, therefore support for symbolic links is disabled by default. Use
git clone -c core.symlinks=true <URL>
to enable it, see details here.
I think everyone missed the "suddenly" part of this question. Most likely, your .jshintrc has a syntax error, so it's not including the 'browser' line. Run it through a json validator to see where the error is.
With the command:
sudo apt-get remove --purge mysql\*
you can delete anything related to packages named mysql. Those commands are only valid on debian / debian-based linux distributions (Ubuntu for example).
You can list all installed mysql packages with the command:
sudo dpkg -l | grep -i mysql
For more cleanup of the package cache, you can use the command:
sudo apt-get clean
Also, remember to use the command:
sudo updatedb
Otherwise the "locate" command will display old data.
To install mysql again, use the following command:
sudo apt-get install libmysqlclient-dev mysql-client
This will install the mysql client, libmysql and its headers files.
To install the mysql server, use the command:
sudo apt-get install mysql-server
i think the problem is we are trying to connect to a local server that is not running.
we need to first run the MySQL
server then connect to it.
just Go to task manager > services
find MYSQL80
and then start the service.
From what I know, printing can be done in many ways
Here's what I follow:
Printing string with variables
a = 1
b = "ball"
print("I have", a, b)
Versus printing string with functions
a = 1
b = "ball"
print("I have" + str(a) + str(b))
In this case, str() is a function that takes a variable and spits out what its assigned to as a string
They both yield the same print, but in two different ways. I hope that was helpful
cut -c1
This is POSIX, and unlike case
actually extracts the first char if you need it for later:
myvar=abc
first_char="$(printf '%s' "$myvar" | cut -c1)"
if [ "$first_char" = a ]; then
echo 'starts with a'
else
echo 'does not start with a'
fi
awk substr
is another POSIX but less efficient alternative:
printf '%s' "$myvar" | awk '{print substr ($0, 0, 1)}'
printf '%s'
is to avoid problems with escape characters: https://stackoverflow.com/a/40423558/895245 e.g.:
myvar='\n'
printf '%s' "$myvar" | cut -c1
outputs \
as expected.
${::}
does not seem to be POSIX.
See also: How to extract the first two characters of a string in shell scripting?
None of the answers here worked for me. This was what worked.
Test_y = np.nan_to_num(Test_y)
It replaces the infinity values with high finite values and the nan values with numbers
I don't think you want the data from your Request, I think you want the data from your Response. The two are different. Also you should build your response correctly in your controller.
Looking at the class in edit #2, I would make it look like this:
class XmlController extends Controller
{
public function index()
{
$content = Request::all();
return Response::json($content);
}
}
Once you've gotten that far you should check the content of your response in your test case (use print_r if necessary), you should see the data inside.
More information on Laravel responses here:
This may come a bit too late, but I have written something for this very purpose. My library will mock out the basic crud repository methods for you as well as interpret most of the functionalities of your query methods. You will have to inject functionalities for your own native queries, but the rest are done for you.
Take a look:
https://github.com/mmnaseri/spring-data-mock
UPDATE
This is now in Maven central and in pretty good shape.
PSFTP -b path/file_name.sftp user@IP_server -hostkey 1e:52:b1... -pw password
the file content is:
lcd "path_file for send"
cd path_destination
mput file_name_to_send
quit
to have the hostkey run:
psftp user@IP_SERVER
you must check is user loggined ?
Auth::check() ? Auth::user()->id : null
I think you have to do mydb.commit()
all the insert into.
Something like this
import csv
import MySQLdb
mydb = MySQLdb.connect(host='localhost',
user='root',
passwd='',
db='mydb')
cursor = mydb.cursor()
csv_data = csv.reader(file('students.csv'))
for row in csv_data:
cursor.execute('INSERT INTO testcsv(names, \
classes, mark )' \
'VALUES("%s", "%s", "%s")',
row)
#close the connection to the database.
mydb.commit()
cursor.close()
print "Done"
you can use
state.name for state in states track by state.code
Where states in the JSON array, state is the variable name for each object in the array.
Hope this helps
This simple helped me you don't have to include anything at the end because if you include something, some of your packages will be upgraded but some will be downgraded. You can get this from this url: https://anaconda.org/anaconda/py-xgboost
conda install -c anaconda py-xgboost
The only difference between slice and substring method is of arguments
Both take two arguments e.g. start/from and end/to.
You cannot pass a negative value as first argument for substring method but for slice method to traverse it from end.
Slice method argument details:
REF: http://www.thesstech.com/javascript/string_slice_method
Arguments
start_index Index from where slice should begin. If value is provided in negative it means start from last. e.g. -1 for last character. end_index Index after end of slice. If not provided slice will be taken from start_index to end of string. In case of negative value index will be measured from end of string.
Substring method argument details:
REF: http://www.thesstech.com/javascript/string_substring_method
Arguments
from It should be a non negative integer to specify index from where sub-string should start. to An optional non negative integer to provide index before which sub-string should be finished.
try this
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<body>
<a href="#name">click me</a>
<br><br><br><br><br><br><br><br><br><br><br>
<br><br><br><br><br><br><br><br><br><br><br>
<br><br><br><br><br><br><br><br><br><br><br>
<div name="name" id="name">here</div>
</body>
</html>
I stuck with the same issue. I have found easiest solution which I like to share.
1) Create new branch with your changes.
git checkout -b mybranch
2) (Optional) Push new branch code on remote server.
git push origin mybranch
3) Checkout back to master branch.
git checkout master
4) Reset master branch code with remote server and remove local commit.
git reset --hard origin/master
The error code 10060 means it cannot connect to the remote peer. It might be because of the network problem or mostly your setting issues, such as proxy setting.
You could try to connect the same host with other tools(such as ncat) and/or with another PC within your same local network to find out where the problem is occuring.
For proxy issue, there are some material here:
Why can't I get Python's urlopen() method to work on Windows?
Hope it helps!
Use a memory stream
using(MemoryStream ms = new MemoryStream())
{
image.Save(ms, ...);
return ms.ToArray();
}
Just remove the inner quotes - they confuse Firefox. You can just use "video/ogg; codecs=theora,vorbis".
Also, that markup works in my Minefiled 3.7a5pre, so if your ogv file doesn't play, it may be a bogus file. How did you create it? You might want to register a bug with Firefox.
I had this issue, the only problem was my Procfile was like this
web : node index.js
and I changed to
web:node index.js
the only problem was spaces
install
npm install --save @ngx-pwa/local-storage
first of all you need to Install "angular-2-local-storage"
import { LocalStorageService } from 'angular-2-local-storage';
Save into LocalStorage:
localStorage.setItem('key', value);
Get From Local Storage:
localStorage.getItem('key');
You can replace database value in date_default_timezone_set function, date_default_timezone_set(SOME_PHP_VARIABLE); but just needs to take care of exact values relevant to the timezones.
Take a look at this: Complete Example
Server:
let exp = require('express');
let app = exp();
//UPDATE: this is seems to be deprecated
//let io = require('socket.io').listen(app.listen(9009));
//New Syntax:
const io = require('socket.io')(app.listen(9009));
app.all('/', function (request, response, next) {
response.header("Access-Control-Allow-Origin", "*");
response.header("Access-Control-Allow-Headers", "X-Requested-With");
next();
});
Client:
<!--LOAD THIS SCRIPT FROM SOMEWHERE-->
<script src="http://127.0.0.1:9009/socket.io/socket.io.js"></script>
<script>
var socket = io("127.0.0.1:9009/", {
"force new connection": true,
"reconnectionAttempts": "Infinity",
"timeout": 10001,
"transports": ["websocket"]
}
);
</script>
I remember this from the combination of stackoverflow answers many days ago; but I could not find the main links to mention them
For me the following command did the trick
sudo apt install php-mbstring
You can truncate the date part:
select * from table1 where trunc(field1) = to_date('2012-01-01', 'YYYY-MM-DD')
The trouble with this approach is that any index on field1
wouldn't be used due to the function call.
Alternatively (and more index friendly)
select * from table1
where field1 >= to_timestamp('2012-01-01', 'YYYY-MM-DD')
and field1 < to_timestamp('2012-01-02', 'YYYY-MM-DD')
By getting the getLastKnownLocation
you do not actually initiate a fix yourself.
Be aware that this could start the provider, but if the user has ever gotten a location before, I don't think it will. The docs aren't really too clear on this.
According to the docs getLastKnownLocation:
Returns a Location indicating the data from the last known location fix obtained from the given provider. This can be done without starting the provider.
Here is a quick snippet:
import android.content.Context;
import android.location.Location;
import android.location.LocationManager;
import java.util.List;
public class UtilLocation {
public static Location getLastKnownLoaction(boolean enabledProvidersOnly, Context context){
LocationManager manager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
Location utilLocation = null;
List<String> providers = manager.getProviders(enabledProvidersOnly);
for(String provider : providers){
utilLocation = manager.getLastKnownLocation(provider);
if(utilLocation != null) return utilLocation;
}
return null;
}
}
You also have to add new permission to AndroidManifest.xml
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
I think the answer for your question is here
To have Chrome send Access-Control-Allow-Origin in the header, just alias your localhost in your /etc/hosts file to some other domain, like:
127.0.0.1 localhost yourdomain.com
A more object oriented way would be to provide a range to the #[] method. For instance:
Say you want the first 3 items from an array.
numbers = [1,2,3,4,5,6]
numbers[0..2] # => [1,2,3]
Say you want the first x items from an array.
numbers[0..x-1]
The great thing about this method is if you ask for more items than the array has, it simply returns the entire array.
numbers[0..100] # => [1,2,3,4,5,6]
You can also use number formatter JS available at
https://code.google.com/p/javascript-number-formatter/
http://jsfiddle.net/chauhangs/hUE3h/
format("##,###.", 98700)
format("#,###.", 8211)
Use:
((Long) userService.getAttendanceList(currentUser)).intValue();
instead.
The .intValue()
method is defined in class Number
, which Long
extends.
You can assign a const
object to a non-const
object just fine. Because you're copying and thus creating a new object, const
ness is not violated.
int main() {
const int a = 3;
int b = a;
}
It's different if you want to obtain a pointer or reference to the original, const
object:
int main() {
const int a = 3;
int& b = a; // or int* b = &a;
}
// error: invalid initialization of reference of type 'int&' from
// expression of type 'const int'
You can use const_cast
to hack around the type safety if you really must, but recall that you're doing exactly that: getting rid of the type safety. It's still undefined to modify a
through b
in the below example:
int main() {
const int a = 3;
int& b = const_cast<int&>(a);
b = 3;
}
Although it compiles without errors, anything can happen including opening a black hole or transferring all your hard-earned savings into my bank account.
If you have arrived at what you think is a requirement to do this, I'd urgently revisit your design because something is very wrong with it.
On Linux, if you call this inside the git repository folder:
git config http.sslVerify false
this will add sslVerify = false
in the [http]
section of the config
file in the .git
folder, which can also be the solution, if you want to add this manually with nano .git/config
:
...
[http]
sslVerify = false
Some Theory
$
is the name of a function like any other name you give to a function. Anyone can create a function in JavaScript and name it $
as shown below:
$ = function() {
alert('I am in the $ function');
}
JQuery is a very famous JavaScript library and they have decided to put their entire framework inside a function named jQuery
. To make it easier for people to use the framework and reduce typing the whole word jQuery
every single time they want to call the function, they have also created an alias for it. That alias is $
. Therefore $
is the name of a function. Within the jQuery source code, you can see this yourself:
window.jQuery = window.$ = jQuery;
Answer To Your Question
So what is $(function() { });?
Now that you know that $
is the name of the function, if you are using the jQuery library, then you are calling the function named $
and passing the argument function() {}
into it. The jQuery library will call the function at the appropriate time. When is the appropriate time? According to jQuery documentation, the appropriate time is once all the DOM elements of the page are ready to be used.
The other way to accomplish this is like this:
$(document).ready(function() { });
As you can see this is more verbose so people prefer $(function() { })
So the reason why some functions cannot be called, as you have noticed, is because those functions do not exist yet. In other words the DOM has not loaded yet. But if you put them inside the function you pass to $
as an argument, the DOM is loaded by then. And thus the function has been created and ready to be used.
Another way to interpret $(function() { })
is like this:
Hey $ or jQuery, can you please call this function I am passing as an argument once the DOM has loaded?
I think these are the main differences
Readability can make the code improved or substituted 6 months after it was created with litte effort, on the other hand, if performance is critical you may want to use a low level language to target the specific hardware you will have in production, so to get faster execution.
IMO today computers are fast enough to let a programmer gain fast execution with OOP.
Press
CTRL+L
Shortcut to clear log
, even if you have ticked Preserve log
option.
Hope this helps.
widget['bg'] = '#000000'
or
widget['background'] = '#000000'
would also work as hex-valued colors are also accepted.
In your comment on @Kenneth's answer you're saying that ReadAsStringAsync()
is returning empty string.
That's because you (or something - like model binder) already read the content, so position of internal stream in Request.Content is on the end.
What you can do is this:
public static string GetRequestBody()
{
var bodyStream = new StreamReader(HttpContext.Current.Request.InputStream);
bodyStream.BaseStream.Seek(0, SeekOrigin.Begin);
var bodyText = bodyStream.ReadToEnd();
return bodyText;
}
Personally I had the same issue and when I tried again today after a while I found in the new version (2.5.0) that going in the json I could see an explanation of the error that was in here.
Also another thing that helped to fix it to me was removing the hosting information connected to the website that is hold inside "..vs\config\applicationhost.config" at the root of the solution folder
I removed the element that was configuring the website.
<site name="**" id="9">
<application path="/" applicationPool=""></application>
<bindings></bindings>
</site>
Look at
For Each c as DataColumn in dt.Columns
'... = c.ColumnName
Next
or:
dt.GetDataTableSchema(...)
UPDATE user_account student, (
SELECT teacher.education_facility_id as teacherid
FROM user_account teacher
WHERE teacher.user_account_id = student.teacher_id AND teacher.user_type = 'ROLE_TEACHER'
) teach SET student.student_education_facility_id= teach.teacherid WHERE student.user_type = 'ROLE_STUDENT';
I was trying do the same of making a particular file my default page, instead of directory structure. So in IIS server I had to go to Default Document, add the page that I want to make as default and at the same time, go to the Web.config file and update the defaultDocument header with "enabled=true". This worked for me. Hopefully it helps.
Database is like container of data with schema, and schemas is layout of the tables there data types, relations and stuff
Try to replace the \n
with %0A
just like you have spaces replaced with %20
.
it is because you already defined the 'abuse_id' as auto increment, then there is no need to insert its value. it will be inserted automatically. the error comes because you are inserting 1 many times that is duplication of data. the primary key should be unique. should not be repeated.
the thing you have to do is to change your insertion query as below
INSERT INTO `abuses` ( `user_id` , `abuser_username` , `comment` , `reg_date` , `auction_id` )
VALUES ( 100020, 'artictundra', 'I placed a bid for it more than an hour ago. It is still active. I thought I was supposed to get an email after 15 minutes.', 1338052850, 108625 ) ;
A better solution is to use the array_filter
function:
$display_related_tags =
array_filter($display_related_tags, function($e) use($found_tag){
return $e != $found_tag['name'];
});
As the php documentation reads:
As foreach relies on the internal array pointer in PHP 5, changing it within the loop may lead to unexpected behavior.
In PHP 7, foreach does not use the internal array pointer.
Space char is hexadecimal 0x20, decimal 32 and octal \040.
>>> SPACE = 0x20
>>> a = chr(SPACE)
>>> type(a)
<class 'str'>
>>> print(f"'{a}'")
' '
Use .parentElement
and you can't go wrong as long as you aren't using document fragments.
If you use document fragments, then you need .parentNode
:
let div = document.createDocumentFragment().appendChild(document.createElement('div'));
div.parentElement // null
div.parentNode // document fragment
Also:
let div = document.getElementById('t').content.firstChild_x000D_
div.parentElement // null_x000D_
div.parentNode // document fragment
_x000D_
<template id="t"><div></div></template>
_x000D_
Apparently the <html>
's .parentNode
links to the Document. This should be considered a decision phail as documents aren't nodes since nodes are defined to be containable by documents and documents can't be contained by documents.
If your web server supports Serlvet 3.0 spec, like tomcat 7.0+, you can use below in web.xml
as:
<session-config>
<cookie-config>
<http-only>true</http-only>
<secure>true</secure>
</cookie-config>
</session-config>
As mentioned in docs:
HttpOnly: Specifies whether any session tracking cookies created by this web application will be marked as HttpOnly
Secure: Specifies whether any session tracking cookies created by this web application will be marked as secure even if the request that initiated the corresponding session is using plain HTTP instead of HTTPS
Please refer to how to set httponly and session cookie for java web application
I too faced the same problem, But accidentally i written the without writting the ,the previous one should go inside this tags. thus the 'Configuration System Failed to Initialize' error was arising. Hope it will help
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
alert(this.responseText);
}
};
xhttp.open("GET", "ajax_info.txt", true);
xhttp.send();
As Seth stated thread safe means that a method or class instance can be used by multiple threads at the same time without any problems occuring.
Consider the following method:
private int myInt = 0;
public int AddOne()
{
int tmp = myInt;
tmp = tmp + 1;
myInt = tmp;
return tmp;
}
Now thread A
and thread B
both would like to execute AddOne()
. but A
starts first and reads the value of myInt (0)
into tmp
. Now for some reason the scheduler decides to halt thread A
and defer execution to thread B
. Thread B
now also reads the value of myInt
(still 0
) into it's own variable tmp
. Thread B
finishes the entire method, so in the end myInt = 1
. And 1
is returned. Now it's Thread A
's turn again. Thread A
continues. And adds 1
to tmp
(tmp
was 0
for thread A
). And then saves this value in myInt
. myInt
is again 1
.
So in this case the method AddOne()
was called two times, but because the method was not implemented in a thread safe way the value of myInt
is not 2
, as expected, but 1
because the second thread read the variable myInt
before the first thread finished updating it.
Creating thread safe methods is very hard in non trivial cases. And there are quite a few techniques. In Java you can mark a method as synchronized, this means that only one thread can execute that method at a given time. The other threads wait in line. This makes a method thread safe, but if there is a lot of work to be done in a method, then this wastes a lot of time. Another technique is to 'mark only a small part of a method as synchronized' by creating a lock or semaphore, and locking this small part (usually called the critical section). There are even some methods that are implemented as lockless thread safe, which means that they are built in such a way that multiple threads can race through them at the same time without ever causing problems, this can be the case when a method only executes one atomic call. Atomic calls are calls that can't be interrupted and can only be done by one thread at a time.
You can also add column to a specific position using before column or after column like:
rails generate migration add_dob_to_customer dob:date
The migration file will generate the following code except after: :email. you need to add after: :email or before: :email
class AddDobToCustomer < ActiveRecord::Migration[5.2]
def change
add_column :customers, :dob, :date, after: :email
end
end
It's basically 2 step process:
First, you need to stringify like this:
var JSON_VAR = JSON.stringify(OBJECT_NAME, null, 2);
After that, you need to convert the string
to Object
:
var obj = JSON.parse(JSON_VAR);
$(document).ready(function(){
$('#some-id').trigger('click');
});
did the trick.
Another option would be file_get_contents()
:
// $xml_str = your xml
// $url = target url
$post_data = array('xml' => $xml_str);
$stream_options = array(
'http' => array(
'method' => 'POST',
'header' => 'Content-type: application/x-www-form-urlencoded' . "\r\n",
'content' => http_build_query($post_data)));
$context = stream_context_create($stream_options);
$response = file_get_contents($url, null, $context);
Here's another example I wrote a while ago:
<?php
// Get class for Instagram
// More examples here: https://github.com/cosenary/Instagram-PHP-API
require_once 'instagram.class.php';
// Initialize class with client_id
// Register at http://instagram.com/developer/ and replace client_id with your own
$instagram = new Instagram('CLIENT_ID_HERE');
// Set keyword for #hashtag
$tag = 'KEYWORD HERE';
// Get latest photos according to #hashtag keyword
$media = $instagram->getTagMedia($tag);
// Set number of photos to show
$limit = 5;
// Set height and width for photos
$size = '100';
// Show results
// Using for loop will cause error if there are less photos than the limit
foreach(array_slice($media->data, 0, $limit) as $data)
{
// Show photo
echo '<p><img src="'.$data->images->thumbnail->url.'" height="'.$size.'" width="'.$size.'" alt="SOME TEXT HERE"></p>';
}
?>
You can use this function to get the absolute value:
+(NSNumber *)absoluteValue:(NSNumber *)input {
return [NSNumber numberWithDouble:fabs([input doubleValue])];
}
The width attribute of <td>
is deprecated in HTML 5.
Use CSS. e.g.
<td style="width:100px">
in detail, like this:
<table >
<tr>
<th>Month</th>
<th>Savings</th>
</tr>
<tr>
<td style="width:70%">January</td>
<td style="width:30%">$100</td>
</tr>
<tr>
<td>February</td>
<td>$80</td>
</tr>
</table>
For an HTTP-based server there is a Python script to find the server version at: http://svn.apache.org/repos/asf/subversion/trunk/tools/client-side/server-version.py
You can get the client version with
`svn --version`
Go through this and remove corresponding cache files in selected db then after you can drop your database
First find Your MySQL Data Directory Containing Your selected DB
Linux
Search for the term "datadir": /datadir
If it exists, it will highlight a line that reads: datadir = [path]
You can also manually look for that line. It typically would be found under a section heading of [mysqld] but it does not necessarily have to be found there.
If that line does not exist, then MySQL will default to: /var/lib/mysql.
Windows 1. Open up MySQL's configuration file into Notepad: my.ini
The my.ini will be located in the MySQL program folder, which would be wherever it got installed. If you did not install MySQL, then use the Windows "search" feature to look for my.ini. You could also manually search for it by browsing to [drive]:\Program Files\MySQL\MySQL Server 5.5.
Do a search in Notepad to find the term "datadir".
If it exists, it will highlight a line that reads: datadir = [path]
You can also manually look for that line. It typically would be found under a section heading of [mysqld] but it does not necessarily have to be found there.
If that line does not exist, then you'll probably find it under [drive]:\ProgramData\MySQL\MySQL Server 5.5\data.
NOTE: The "ProgramData" folder may be hidden. You may have to type the explicit path into Windows Explore
This might work for you:
OIFS=$IFS; IFS=$'\n'; array=($(ls -ls)); IFS=$OIFS; echo "${array[1]}"
in my case, i have a cdn,and i am going to place all my processed static files (js,imgs,fonts...) into my cdn,suppose the url is http://my.cdn.com/
so if there is a js file which is the orginal refer url in html is './js/my.js' it should became http://my.cdn.com/js/my.js in production environment
in that case,what i need to do is just set publicpath equals http://my.cdn.com/ and webpack will automatic add that prefix
It means it's an array of wide characters (wchar_t
) instead of narrow characters (char
).
It's a just a string of a different kind of character, not necessarily a Unicode string.
this, work for me :
with open('file.json', 'a') as outfile:
outfile.write(json.dumps(data))
outfile.write(",")
outfile.close()
I dont have access to a Solaris machine, but grep "\-X"
works for me on linux.
You might want to look here and here.
A Little code example from the first link:
<?php
// include the SOAP classes
require_once('nusoap.php');
// define parameter array (ISBN number)
$param = array('isbn'=>'0385503954');
// define path to server application
$serverpath ='http://services.xmethods.net:80/soap/servlet/rpcrouter';
//define method namespace
$namespace="urn:xmethods-BNPriceCheck";
// create client object
$client = new soapclient($serverpath);
// make the call
$price = $client->call('getPrice',$param,$namespace);
// if a fault occurred, output error info
if (isset($fault)) {
print "Error: ". $fault;
}
else if ($price == -1) {
print "The book is not in the database.";
} else {
// otherwise output the result
print "The price of book number ". $param[isbn] ." is $". $price;
}
// kill object
unset($client);
?>
React.JS People, remember allowFullScreen
and frameBorder="0"
Without camel-case, react strips these tags out!
Other ways if we are being exhaustive.
anewarray
, multianewarray
, newarray
or new
. These can be added using libraries such as ASM or BCEL. A version of bcel is shipped with Oracle's Java. Again this doesn't call a constructor, but you can call a constructor as a seperate call.I think you want to print the name of the person or both the name and email :
const renObjData = this.props.data.map(function(data, idx) {
return <p key={idx}>{data.name}</p>;
});
or :
const renObjData = this.props.data.map(function(data, idx) {
return ([
<p key={idx}>{data.name}</p>,
<p key={idx}>{data.email}</p>,
]);
});
For the bootstrap 4 beta were some big changes between the alpha and beta versions of bootstrap (and also bootstrap 3), esp. in regards to form validation.
First, to place the icons correctly you'll need to add styling which equates to what was in bootstrap 3 and no longer in bootstrap 4 beta...here's what I'm using
.fa.valid-feedback,
.fa.invalid-feedback {
position: absolute;
right: 25px;
margin-top: -50px;
z-index: 2;
display: block;
pointer-events: none;
}
.fa.valid-feedback {
margin-top: -28px;
}
The classes have also changed as the beta uses the 'state' of the control rather than classes which your posted code doesn't reflect, so your above code may not work. Anyway, you'll need to add 'was-validated' class to the form either in the success or highlight/unhighlight callbacks
$(element).closest('form').addClass('was-validated');
I would also recommend using the new element and classes for form control help text
errorElement: 'small',
errorClass: 'form-text invalid-feedback',
Just use it as you would a non-concurrent collection. The Concurrent[Collection] classes wrap the regular collections so that you don't have to think about synchronizing access.
Edit: ConcurrentLinkedList isn't actually just a wrapper, but rather a better concurrent implementation. Either way, you don't have to worry about synchronization.
Easiest modern method: Alt
+Enter
on
private static final long serialVersionUID = ;
IntelliJ will underline the space after the =
. put your cursor on it and hit alt
+Enter
(Option
+Enter
on Mac). You'll get a popover that says "Randomly Change serialVersionUID Initializer". Just hit enter, and it'll populate that space with a random long.
For anyone wondering about the difference between -1.#IND00
and -1.#IND
(which the question specifically asked, and none of the answers address):
-1.#IND00
This specifically means a non-zero number divided by zero, e.g. 3.14 / 0
(source)
-1.#IND
(a synonym for NaN
)
This means one of four things (see wiki from source):
1) sqrt
or log
of a negative number
2) operations where both variables are 0 or infinity, e.g. 0 / 0
3) operations where at least one variable is already NaN
, e.g. NaN * 5
4) out of range trig, e.g. arcsin(2)
You'll have to pass the new ordinal position to insert
using len
in this case:
In [62]:
a=[1,2,3,4]
a.insert(len(a),5)
a
Out[62]:
[1, 2, 3, 4, 5]
This will move all files to parent directory like expected but will not move hidden files. How to do that?
You could turn on dotglob
:
shopt -s dotglob # This would cause mv below to match hidden files
mv /path/subfolder/* /path/
In order to turn off dotglob
, you'd need to say:
shopt -u dotglob
Is there a specific reason you want to use FileNameExtensionFilter
? I know this works..
private File[] getNewTextFiles() {
return dir.listFiles(new FilenameFilter() {
@Override
public boolean accept(File dir, String name) {
return name.toLowerCase().endsWith(".txt");
}
});
}
Don't think it is supported yet. Take a look at this JIRA issue "Add delete topic support".
To delete manually:
log.dir
attribute in kafka config file ) as well the zookeeper dataFor any given topic what you can do is
/tmp/kafka-logs/MyTopic-0
where /tmp/kafka-logs
is specified by the log.dir
attributeThis is NOT
a good and recommended approach but it should work.
In the Kafka broker config file the log.retention.hours.per.topic
attribute is used to define The number of hours to keep a log file before deleting it for some specific topic
Also, is there a way the messages gets deleted as soon as the consumer reads it?
From the Kafka Documentation :
The Kafka cluster retains all published messages—whether or not they have been consumed—for a configurable period of time. For example if the log retention is set to two days, then for the two days after a message is published it is available for consumption, after which it will be discarded to free up space. Kafka's performance is effectively constant with respect to data size so retaining lots of data is not a problem.
In fact the only metadata retained on a per-consumer basis is the position of the consumer in in the log, called the "offset". This offset is controlled by the consumer: normally a consumer will advance its offset linearly as it reads messages, but in fact the position is controlled by the consumer and it can consume messages in any order it likes. For example a consumer can reset to an older offset to reprocess.
For finding the start offset to read in Kafka 0.8 Simple Consumer example they say
Kafka includes two constants to help,
kafka.api.OffsetRequest.EarliestTime()
finds the beginning of the data in the logs and starts streaming from there,kafka.api.OffsetRequest.LatestTime()
will only stream new messages.
You can also find the example code there for managing the offset at your consumer end.
public static long getLastOffset(SimpleConsumer consumer, String topic, int partition,
long whichTime, String clientName) {
TopicAndPartition topicAndPartition = new TopicAndPartition(topic, partition);
Map<TopicAndPartition, PartitionOffsetRequestInfo> requestInfo = new HashMap<TopicAndPartition, PartitionOffsetRequestInfo>();
requestInfo.put(topicAndPartition, new PartitionOffsetRequestInfo(whichTime, 1));
kafka.javaapi.OffsetRequest request = new kafka.javaapi.OffsetRequest(requestInfo, kafka.api.OffsetRequest.CurrentVersion(),clientName);
OffsetResponse response = consumer.getOffsetsBefore(request);
if (response.hasError()) {
System.out.println("Error fetching data Offset Data the Broker. Reason: " + response.errorCode(topic, partition) );
return 0;
}
long[] offsets = response.offsets(topic, partition);
return offsets[0];
}
A little late to the game here, but another option is:
public class NerdDinners : DbContext
{
public NerdDinners(string connString)
{
this.Database.Connection.ConnectionString = connString;
}
public DbSet<Dinner> Dinners { get; set; }
}
Here is an attempt to get << and >> stream operators on enum automatically with an one line macro command only...
Definitions:
#include <string>
#include <iostream>
#include <stdexcept>
#include <algorithm>
#include <iterator>
#include <sstream>
#include <vector>
#define MAKE_STRING(str, ...) #str, MAKE_STRING1_(__VA_ARGS__)
#define MAKE_STRING1_(str, ...) #str, MAKE_STRING2_(__VA_ARGS__)
#define MAKE_STRING2_(str, ...) #str, MAKE_STRING3_(__VA_ARGS__)
#define MAKE_STRING3_(str, ...) #str, MAKE_STRING4_(__VA_ARGS__)
#define MAKE_STRING4_(str, ...) #str, MAKE_STRING5_(__VA_ARGS__)
#define MAKE_STRING5_(str, ...) #str, MAKE_STRING6_(__VA_ARGS__)
#define MAKE_STRING6_(str, ...) #str, MAKE_STRING7_(__VA_ARGS__)
#define MAKE_STRING7_(str, ...) #str, MAKE_STRING8_(__VA_ARGS__)
#define MAKE_STRING8_(str, ...) #str, MAKE_STRING9_(__VA_ARGS__)
#define MAKE_STRING9_(str, ...) #str, MAKE_STRING10_(__VA_ARGS__)
#define MAKE_STRING10_(str) #str
#define MAKE_ENUM(name, ...) MAKE_ENUM_(, name, __VA_ARGS__)
#define MAKE_CLASS_ENUM(name, ...) MAKE_ENUM_(friend, name, __VA_ARGS__)
#define MAKE_ENUM_(attribute, name, ...) name { __VA_ARGS__ }; \
attribute std::istream& operator>>(std::istream& is, name& e) { \
const char* name##Str[] = { MAKE_STRING(__VA_ARGS__) }; \
std::string str; \
std::istream& r = is >> str; \
const size_t len = sizeof(name##Str)/sizeof(name##Str[0]); \
const std::vector<std::string> enumStr(name##Str, name##Str + len); \
const std::vector<std::string>::const_iterator it = std::find(enumStr.begin(), enumStr.end(), str); \
if (it != enumStr.end())\
e = name(it - enumStr.begin()); \
else \
throw std::runtime_error("Value \"" + str + "\" is not part of enum "#name); \
return r; \
}; \
attribute std::ostream& operator<<(std::ostream& os, const name& e) { \
const char* name##Str[] = { MAKE_STRING(__VA_ARGS__) }; \
return (os << name##Str[e]); \
}
Usage:
// Declare global enum
enum MAKE_ENUM(Test3, Item13, Item23, Item33, Itdsdgem43);
class Essai {
public:
// Declare enum inside class
enum MAKE_CLASS_ENUM(Test, Item1, Item2, Item3, Itdsdgem4);
};
int main() {
std::cout << Essai::Item1 << std::endl;
Essai::Test ddd = Essai::Item1;
std::cout << ddd << std::endl;
std::istringstream strm("Item2");
strm >> ddd;
std::cout << (int) ddd << std::endl;
std::cout << ddd << std::endl;
}
Not sure about the limitations of this scheme though... comments are welcome!
For this case word boundary (\b) can also be used instead of start anchor (^) and end anchor ($):
\b\d{1,45}\b
\b
is a position between \w and \W (non-word char), or at the beginning or end of a string.
tessdata_dir_config = r'--tessdata-dir "/usr/local/Cellar/tesseract/4.1.1/share/tessdata"'
pytesseract.image_to_string(imgCrop,lang='eng',config=tessdata_dir_config)
I realize this is an old question, but I came across it when doing something similar.
Using SASS, you have a very elegant way to convert RGBA to hex ARGB: ie-hex-str
. I've used it here in a mixin.
@mixin ie8-rgba ($r, $g, $b, $a){
$rgba: rgba($r, $g, $b, $a);
$ie8-rgba: ie-hex-str($rgba);
.lt-ie9 &{
background-color: transparent;
filter:progid:DXImageTransform.Microsoft.gradient(GradientType=0,startColorstr='#{$ie8-rgba}', endColorstr='#{$ie8-rgba}');
}
}
.transparent{
@include ie8-rgba(88,153,131,.8);
background-color: rgba(88,153,131,.8);
}
outputs:
.transparent {_x000D_
background-color: rgba(88, 153, 131, 0.8);_x000D_
}_x000D_
.lt-ie9 .transparent {_x000D_
background-color: transparent;_x000D_
filter: progid:DXImageTransform.Microsoft.gradient(GradientType=0,startColorstr='#CC589983', endColorstr='#CC589983');_x000D_
zoom: 1;_x000D_
}
_x000D_
An object can only have one prototype. Inheriting from two classes can be done by creating a parent object as a combination of two parent prototypes.
The syntax for subclassing makes it possible to do that in the declaration, since the right-hand side of the extends
clause can be any expression. Thus, you can write a function that combines prototypes according to whatever criteria you like, and call that function in the class declaration.
There are two ideas here being confused:
Those are two very different concepts people here are confusing.
Because each browser often had default, out-of-the-box element and layout styles that looked slightly different, people came up with the idea of the "reset" or "reboot" style sheet to align all the browsers BEFORE applying custom CSS. Bootstrap now does this, for example. But that had nothing to do with people wanting to return to the browser's default look and feel.
The problem was not the building of these custom "reset" style sheets, it is figuring out what the default CSS was for each browser and each element BEFORE any styles were applied. Most found out you cant rebuild an existing clean cascade until you "clear out" all styles already applied. But how to get back to the default browser styling?
For some this meant going beyond returning the elements to the browsers UA style sheet that comes with the browser. Many wanted to reset back to "initial" property values which has NOTHING to do with the browser's default style, but really the properties defaults. This is dangerous as in the case of "display" pushes block level elements back to "inline" and breaks table layouts and other things.
So I do NOT agree with users here using "initial" to reset anything or custom reset classes that change every property back to some arbitrary base value set.
A better solution to me has always been to attempt to try and return all core element styling back to the browser's UA style sheet values, which is what all our end-users are using anyway. If you are creating a new website, you don't have to do this. You start with the browser's default styles and add to them. Its only after you've added third-party CSS products, or found yourself with complicated CSS cascades you want to figure out how to return to the browser default style sheet values.
For this reason, I'm for creating your own "reset" sheet to reset all the elements to one common style first that's shared by all old and new browsers as a first step. You then have a solid framework that's much easier to revert to without going back to the browser defaults. You are simply building on a reset common core set of element style values. Once build your own "reset" sheet, one that ADDS not ALTERS the browsers UA styles, you have a site that's very easy to modify.
The only problem remaining then is when you have a site that does NOT have such a reset sheet, or have that complex third party CSS and need to try and return to the browser UA styles. How do you do that?
I realize Internet Explorer has forced us too manually reset every property to get back to any sort of reset. But pushing those property values all back to "initial" destroys the browser UA style sheet values completely! BAD IDEA! A better way is to simply use "all:revert" for non-IE browsers on every element using a wildcard, and "inherit" only for a handful of inherited root-level properties found in the "html" and "body" elements that affect all inheriting children in the page. (see below). I'm NOT for these huge resets of properties using "initial" or going back to some imaginary standard we assume all browsers or IE will use. For starters "initial" has poor support in IE and doesn't reset values to element defaults, only property defaults. But its also pointless if you are going to create a reset sheet to align all elements to a common style. In that case its pointless to clear out styles and start over.
So here is my simple solution that in most cases does enough to reset what text-based values sift down into IE from the root and use "all:revert" for all non-IE browsers to force non-inherited values back to the browser's UA style sheet completely, giving you a true restart. This does not interfere with higher level classes and styles layered over your element styles, which should always be the goal anyway. Its why I'm NOT for these custom reset classes which is tedious and unnecessary and doesn't return the element to its browser UA style anyway. Notice the slightly more selective selectors below which would write over, for example, Bootstrap's "reboot" style values, returning them to the browser default styles. These would not reset element styles on elements for IE, of course, but for non-IE browsers and most inheritable text styling it would return elements in most agents to the UA style sheets that come with browsers:
:root, html {
display: block;
font-family: inherit;
font-size: inherit;
font-weight: inherit;
line-height: inherit;
-webkit-text-size-adjust: inherit;
-webkit-tap-highlight-color: inherit;
all: revert;
}
html body {
display: block;
font-family: inherit;
font-size: inherit;
font-weight: inherit;
line-height: inherit;
margin: inherit;
padding: inherit;
color: inherit;
text-align: inherit;
background-color: inherit;
background: inherit;
all: revert;
}
html body * {
/* IE elements under body would not be affected by this, but if needed you could add custom elements with property resets as needed to this sheet. */
all: revert;
}
In my case, I was able to find the problem by temporarily catching the exception, descending into causes as needed (based on how deep the IllegalAnnotationException was), and calling getErrors() on it.
try {
// in my case, this was what gave me an exception
endpoint.publish("/MyWebServicePort");
// I got a WebServiceException caused by another exception, which was caused by the IllegalAnnotationsException
} catch (WebServiceException e) {
// Incidentally, I need to call getCause().getCause() on it, and cast to IllegalAnnotationsException before calling getErrors()
System.err.println(((com.sun.xml.internal.bind.v2.runtime.IllegalAnnotationsException)e.getCause().getCause()).getErrors());
}
I think you'll want to look at the <intent-filter>
element of your Mainfest file. Specifically, take a look at the documentation for the <data>
sub-element.
Basically, what you'll need to do is define your own scheme. Something along the lines of:
<intent-filter>
<data android:scheme="anton" />
<action android:name="android.intent.action.VIEW" />
<category android:name="android.intent.category.DEFAULT" />
<category android:name="android.intent.category.BROWSABLE" /> <--Not positive if this one is needed
...
</intent-filter>
Then you should be able to launch your app with links that begin with the anton:
URI scheme.
public JsonResult GetAjaxValue()
{
return Json("string value", JsonRequetBehaviour.Allowget);
}
The web.config transforms that are part of Visual Studio 2010 use XSLT in order to "transform" the current web.config file into its .Debug or .Release version.
In your .Debug/.Release files, you need to add the following parameter in your connection string fields:
xdt:Transform="SetAttributes" xdt:Locator="Match(name)"
This will cause each connection string line to find the matching name and update the attributes accordingly.
Note: You won't have to worry about updating your providerName parameter in the transform files, since they don't change.
Here's an example from one of my apps. Here's the web.config file section:
<connectionStrings>
<add name="EAF" connectionString="[Test Connection String]" />
</connectionString>
And here's the web.config.release section doing the proper transform:
<connectionStrings>
<add name="EAF" connectionString="[Prod Connection String]"
xdt:Transform="SetAttributes"
xdt:Locator="Match(name)" />
</connectionStrings>
One added note: Transforms only occur when you publish the site, not when you simply run it with F5 or CTRL+F5. If you need to run an update against a given config locally, you will have to manually change your Web.config file for this.
For more details you can see the MSDN documentation
https://msdn.microsoft.com/en-us/library/dd465326(VS.100).aspx
Another FP aproach:
def repeat_string(string_to_repeat, repetitions):
return ''.join([ string_to_repeat for n in range(repetitions)])
Taken from the javadoc spec
@see <a href="URL#value">label</a>
:
Adds a link as defined by URL#value
. The URL#value
is a relative or absolute URL. The Javadoc tool distinguishes this from other cases by looking for a less-than symbol (<
) as the first character.
For example : @see <a href="http://www.google.com">Google</a>
Firs you need to import CSV file into Data Table
Then you can insert bulk rows using SQLBulkCopy
using System;
using System.Data;
using System.Data.SqlClient;
namespace SqlBulkInsertExample
{
class Program
{
static void Main(string[] args)
{
DataTable prodSalesData = new DataTable("ProductSalesData");
// Create Column 1: SaleDate
DataColumn dateColumn = new DataColumn();
dateColumn.DataType = Type.GetType("System.DateTime");
dateColumn.ColumnName = "SaleDate";
// Create Column 2: ProductName
DataColumn productNameColumn = new DataColumn();
productNameColumn.ColumnName = "ProductName";
// Create Column 3: TotalSales
DataColumn totalSalesColumn = new DataColumn();
totalSalesColumn.DataType = Type.GetType("System.Int32");
totalSalesColumn.ColumnName = "TotalSales";
// Add the columns to the ProductSalesData DataTable
prodSalesData.Columns.Add(dateColumn);
prodSalesData.Columns.Add(productNameColumn);
prodSalesData.Columns.Add(totalSalesColumn);
// Let's populate the datatable with our stats.
// You can add as many rows as you want here!
// Create a new row
DataRow dailyProductSalesRow = prodSalesData.NewRow();
dailyProductSalesRow["SaleDate"] = DateTime.Now.Date;
dailyProductSalesRow["ProductName"] = "Nike";
dailyProductSalesRow["TotalSales"] = 10;
// Add the row to the ProductSalesData DataTable
prodSalesData.Rows.Add(dailyProductSalesRow);
// Copy the DataTable to SQL Server using SqlBulkCopy
using (SqlConnection dbConnection = new SqlConnection("Data Source=ProductHost;Initial Catalog=dbProduct;Integrated Security=SSPI;Connection Timeout=60;Min Pool Size=2;Max Pool Size=20;"))
{
dbConnection.Open();
using (SqlBulkCopy s = new SqlBulkCopy(dbConnection))
{
s.DestinationTableName = prodSalesData.TableName;
foreach (var column in prodSalesData.Columns)
s.ColumnMappings.Add(column.ToString(), column.ToString());
s.WriteToServer(prodSalesData);
}
}
}
}
}
class receipt_model extends CI_Model {
public function index(){
$this->db->select('*');
$this->db->from('donor_details');
$this->db->order_by('donor_id','desc');
$query=$this->db->get();
$row=$query->row();
return $row;
}
}
My way to detect loading event is not to detect scrolling, but to listen whether the last view was attached. If the last view was attached, I regard it as timing to load more content.
class MyListener implements RecyclerView.OnChildAttachStateChangeListener {
RecyclerView mRecyclerView;
MyListener(RecyclerView view) {
mRecyclerView = view;
}
@Override
public void onChildViewAttachedToWindow(View view) {
RecyclerView.Adapter adapter = mRecyclerView.getAdapter();
RecyclerView.LayoutManager mgr = mRecyclerView.getLayoutManager();
int adapterPosition = mgr.getPosition(view);
if (adapterPosition == adapter.getItemCount() - 1) {
// last view was attached
loadMoreContent();
}
@Override
public void onChildViewDetachedFromWindow(View view) {}
}
This should be OK
$value = explode(".", $value);
$extension = strtolower(array_pop($value)); //Line 32
// the file name is before the last "."
$fileName = array_shift($value); //Line 34
It will work on Linux kernel 2.6.28 (confirmed on 4.9.x). It won't work on FreeBSD and other Unix flavors.
Your /usr/local/bin/groovy
is a shell script wrapping the Java runtime running Groovy.
See the Interpreter Scripts section of EXECVE(2) and EXECVE(2).
When nothing else works when it should work, restart ng serve. It's sad to find this kind of bugs.
A simple function that blits an image front
onto an image back
and returns the result. It works with both 3 and 4-channel images and deals with the alpha channel. Overlaps are handled as well.
The output image has the same size as back, but always 4 channels.
The output alpha channel is given by (u+v)/(1+uv) where u,v are the alpha channels of the front and back image and -1 <= u,v <= 1. Where there is no overlap with front, the alpha value from back is taken.
import cv2
def merge_image(back, front, x,y):
# convert to rgba
if back.shape[2] == 3:
back = cv2.cvtColor(back, cv2.COLOR_BGR2BGRA)
if front.shape[2] == 3:
front = cv2.cvtColor(front, cv2.COLOR_BGR2BGRA)
# crop the overlay from both images
bh,bw = back.shape[:2]
fh,fw = front.shape[:2]
x1, x2 = max(x, 0), min(x+fw, bw)
y1, y2 = max(y, 0), min(y+fh, bh)
front_cropped = front[y1-y:y2-y, x1-x:x2-x]
back_cropped = back[y1:y2, x1:x2]
alpha_front = front_cropped[:,:,3:4] / 255
alpha_back = back_cropped[:,:,3:4] / 255
# replace an area in result with overlay
result = back.copy()
print(f'af: {alpha_front.shape}\nab: {alpha_back.shape}\nfront_cropped: {front_cropped.shape}\nback_cropped: {back_cropped.shape}')
result[y1:y2, x1:x2, :3] = alpha_front * front_cropped[:,:,:3] + alpha_back * back_cropped[:,:,:3]
result[y1:y2, x1:x2, 3:4] = (alpha_front + alpha_back) / (1 + alpha_front*alpha_back) * 255
return result
The first part:
.Cells(.Rows.Count,"A")
Sends you to the bottom row of column A, which you knew already.
The End function starts at a cell and then, depending on the direction you tell it, goes that direction until it reaches the edge of a group of cells that have text. Meaning, if you have text in cells C4:E4 and you type:
Sheet1.Cells(4,"C").End(xlToRight).Select
The program will select E4, the rightmost cell with text in it.
In your case, the code is spitting out the row of the very last cell with text in it in column A. Does that help?
Yes. It will work: FileInfo.CopyTo Method
Use this method to allow or prevent overwriting of an existing file. Use the CopyTo method to prevent overwriting of an existing file by default.
All other responses are correct, but since you asked for FileInfo
, here's a sample:
FileInfo fi = new FileInfo(@"c:\yourfile.ext");
fi.CopyTo(@"d:\anotherfile.ext", true); // existing file will be overwritten
I also tried this a while ago (Launch iPhone Application with Identifier), but there definitely is no DOCUMENTED way to do this. :)
It was not asked precisely to remove accent (only special characters), but I needed to.
The solutions givens here works but they don’t remove accent: é, è, etc.
So, before doing epascarello’s solution, you can also do:
var newString = "développeur & intégrateur";_x000D_
_x000D_
newString = replaceAccents(newString);_x000D_
newString = newString.replace(/[^A-Z0-9]+/ig, "_");_x000D_
alert(newString);_x000D_
_x000D_
/**_x000D_
* Replaces all accented chars with regular ones_x000D_
*/_x000D_
function replaceAccents(str) {_x000D_
// Verifies if the String has accents and replace them_x000D_
if (str.search(/[\xC0-\xFF]/g) > -1) {_x000D_
str = str_x000D_
.replace(/[\xC0-\xC5]/g, "A")_x000D_
.replace(/[\xC6]/g, "AE")_x000D_
.replace(/[\xC7]/g, "C")_x000D_
.replace(/[\xC8-\xCB]/g, "E")_x000D_
.replace(/[\xCC-\xCF]/g, "I")_x000D_
.replace(/[\xD0]/g, "D")_x000D_
.replace(/[\xD1]/g, "N")_x000D_
.replace(/[\xD2-\xD6\xD8]/g, "O")_x000D_
.replace(/[\xD9-\xDC]/g, "U")_x000D_
.replace(/[\xDD]/g, "Y")_x000D_
.replace(/[\xDE]/g, "P")_x000D_
.replace(/[\xE0-\xE5]/g, "a")_x000D_
.replace(/[\xE6]/g, "ae")_x000D_
.replace(/[\xE7]/g, "c")_x000D_
.replace(/[\xE8-\xEB]/g, "e")_x000D_
.replace(/[\xEC-\xEF]/g, "i")_x000D_
.replace(/[\xF1]/g, "n")_x000D_
.replace(/[\xF2-\xF6\xF8]/g, "o")_x000D_
.replace(/[\xF9-\xFC]/g, "u")_x000D_
.replace(/[\xFE]/g, "p")_x000D_
.replace(/[\xFD\xFF]/g, "y");_x000D_
}_x000D_
_x000D_
return str;_x000D_
}
_x000D_
Why? One almost never needs to update the statistics. Rebuilding an index is even more rarely needed.
OPTIMIZE TABLE tbl;
will rebuild the indexes and do ANALYZE
; it takes time.
ANALYZE TABLE tbl;
is fast for InnoDB to rebuild the stats. With 5.6.6 it is even less needed.
Example using Collections and ArrayList:
Develop an intern static class like the example "CompareStrings".
Call the intern static class in the main method.
Easy to understand and works fine!
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
public class MainClass {
public static void main(String[] args) {
ArrayList<String> myArray = new ArrayList<String>();
myArray.add("zzz");
myArray.add("xxx");
myArray.add("Aaa");
myArray.add("bb");
myArray.add("BB");
Collections.sort(myArray, new MainClass.CompareStrings());
for(String s : myArray) {
System.out.println(s);
}
}
public static class CompareStrings implements Comparator<String> {
@Override
public int compare(String s1, String s2) {
return s1.compareToIgnoreCase(s2);
}
}
}
My Hosting server block requesting URL And code site getting the same error
Unable to read data from the transport connection: An existing connection was forcibly closed by the remote host. ---> System.Net.Sockets.SocketException: An existing connection was forcibly closed by the remote host
After a lot of time spent and apply the following step to resolve this issue
Added line before the call web URL
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12 | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls;
still issue not resolve then I upgrade .net version to 4.7.2 but I think it's optional
Last change I have checked my hosting server security level which causes to TLS handshaking for this used "https://www.ssllabs.com/ssltest/index.html" site
and also check to request URL security level then I find the difference is requested URL have to enable a weak level Cipher Suites you can see in the below image
Now here are my hosting server supporting Cipher Suites
here is called if you have control over requesting URL host server then you can sync this both server Cipher Suites. but in my case, it's not possible so I have applied the following script in Windows PowerShell on my hosting server for enabling required weak level Cipher Suites.
Enable-TlsCipherSuite -Name "TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA384"
Enable-TlsCipherSuite -Name "TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256"
Enable-TlsCipherSuite -Name "TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA"
Enable-TlsCipherSuite -Name "TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA"
Enable-TlsCipherSuite -Name "TLS_DHE_RSA_WITH_AES_256_CBC_SHA"
Enable-TlsCipherSuite -Name "TLS_DHE_RSA_WITH_AES_128_CBC_SHA"
Enable-TlsCipherSuite -Name "TLS_RSA_WITH_AES_256_GCM_SHA384"
Enable-TlsCipherSuite -Name "TLS_RSA_WITH_AES_128_GCM_SHA256"
Enable-TlsCipherSuite -Name "TLS_RSA_WITH_AES_256_CBC_SHA256"
Enable-TlsCipherSuite -Name "TLS_RSA_WITH_AES_128_CBC_SHA256"
Enable-TlsCipherSuite -Name "TLS_RSA_WITH_AES_256_CBC_SHA"
Enable-TlsCipherSuite -Name "TLS_RSA_WITH_AES_256_CBC_SHA"
after applying the above script my hosting server Cipher Suites level look like
Then my issue resolved.
Note: server security level downgrade is not a recommended option.
I suggest playing with the :before attribute and seeing what you can achieve with it. It will mean your code really is limited to nice new browsers, and excludes the (annoyingly large) section of the market still using rubbish old browsers,
Something like the following, which forces a fixed with on the items. Yes, I know it's less elegant to have to choose the width yourself, but using CSS for your layout is like undercover police work: however good your motives, it always gets messy.
li:before {
content: counter(item) ") ";
counter-increment: item;
display: marker;
width: 2em;
}
But you're going to have to experiment to find the exact solution.
That entire block is misplaced.
class Example(object):
def main(self):
print "Hello World!"
if __name__ == '__main__':
Example().main()
But you really shouldn't be using a class just to run your main code.
ID is suitable for the elements which appears only once Like Logo sidebar container
And Class is suitable for the elements which has same UI but they can be appear more than once. Like
.feed in the #feeds Container
I have recently discovered that minidlna doesn't update the database if the media file is a hardlink. If you want these files to show up in the database, a full rescan is necessary.
ex: If you have a file /home/movies/foo.mkv and a hardlink in /home/minidlna/video/foo.mkv, where '/home/minidlna' is your minidlna share, you will have to do a rescan till that file appears in the db (and subsequently your dlna client).
I'm still trying to find a way around this. If anyone has any input, it's most welcome.
It's worth checking task manager for any stray wscript.exe tasks that are stuck. It could be one of those that's blocking access to the file.
You don't have to load the whole product. Magentos collections are very powerful and smart.
$collection = Mage::getModel('catalog/product')->getCollection();
$collection->addAttributeToFilter('entity_id', $product->getId());
$collection->addAttributeToSelect('manufacturer');
$product = $collection->getFirstItem();
$manufacturer = $product->getAttributeText('manufacturer');
At the moment you call getFirstItem() the query will be executed and the result product is very minimal:
[status] => 1
[entity_id] => 38901
[type_id] => configurable
[attribute_set_id] => 9
[manufacturer] => 492
[manufacturer_value] => JETTE
[is_salable] => 1
[stock_item (Varien_Object)] => Array
(
[is_in_stock] => 1
)
The major difference between Spring MVC and Struts is: Spring MVC is loosely coupled framework whereas Struts is tightly coupled. For enterprise Application you need to build your application as loosely coupled as it would make your application more reusable and robust as well as distributed.
A popular method to tackle the problem of reducing JavaScript references from HTML files is by using a concatenation tool like Sprockets, which preprocesses and concatenates JavaScript source files together.
Apart from reducing the number of references from the HTML files, this will also reduce the number of hits to the server.
You may then want to run the resulting concatenation through a minification tool like jsmin to have it minified.
An other solution (if possible) would be to use TomEE instead of Tomcat, which has a working maven plugin:
<plugin>
<groupId>org.apache.tomee.maven</groupId>
<artifactId>tomee-maven-plugin</artifactId>
<version>7.1.1</version>
</plugin>
Version 7.1.1 wraps a Tomcat 8.5.41
You may want to use:
SELECT Name, 'Unpaid' AS Status FROM table;
The SELECT
clause syntax, as defined in MSDN: SELECT Clause (Transact-SQL), is as follows:
SELECT [ ALL | DISTINCT ]
[ TOP ( expression ) [ PERCENT ] [ WITH TIES ] ]
<select_list>
Where the expression
can be a constant, function, any combination of column names, constants, and functions connected by an operator or operators, or a subquery.
In case anyone else is running in to the same problem, the only solution I could find that satisfied me was to have the canvas cover everything and then to raise the Z-index of all clickable elements. You can't draw on them, but at least they are clickable...
for /f "tokens=* delims= " %%f in (myfile) do
This reads a file line-by-line, removing leading spaces (thanks, jeb).
set line=%%f
sets then the line
variable to the line just read and
call :procesToken
calls a subroutine that does something with the line
:processToken
is the start of the subroutine mentioned above.
for /f "tokens=1* delims=/" %%a in ("%line%") do
will then split the line at /
, but stopping tokenization after the first token.
echo Got one token: %%a
will output that first token and
set line=%%b
will set the line
variable to the rest of the line.
if not "%line%" == "" goto :processToken
And if line
isn't yet empty (i.e. all tokens processed), it returns to the start, continuing with the rest of the line.
I had the same problem on my mac, but in my case, the problem was that I did not run the database (sudo mongod) before; the problem was solved when I first ran the mondo sudod on the console and, once it was done, on another console, the connection to the server ...
Try it:
String command = "killall <your_proccess>";
Process p = Runtime.getRuntime().exec(command);
p.destroy();
if the process is still alive, add:
p.destroyForcibly();
The answer given by Francois results in listing all the cities from a country. But if the requirement is to list all the regions (cities + states + other regions etc) in a country or the establishments in the country, you can filter results accordingly by changing types.
List only cities in the country
var options = {
types: ['(cities)'],
componentRestrictions: {country: "us"}
};
List all cities, states and regions in the country
var options = {
types: ['(regions)'],
componentRestrictions: {country: "us"}
};
List all establishments — such as restaurants, stores, and offices in the country
var options = {
types: ['establishment'],
componentRestrictions: {country: "us"}
};
More information and options available at
https://developers.google.com/maps/documentation/javascript/places-autocomplete
Hope this might be useful to someone
You are getting this error because you are calling $apply
inside an existing digestion cycle.
The big question is: why are you calling $apply
? You shouldn't ever need to call $apply
unless you are interfacing from a non-Angular event. The existence of $apply
usually means I am doing something wrong (unless, again, the $apply happens from a non-Angular event).
If $apply
really is appropriate here, consider using a "safe apply" approach:
Your css will only work in IE browser. And the css suggessted by hayk.mart will olny work in webkit browsers. And by using different css hacks you can't style your browsers scroll bars with a same result.
So, it is better to use a jQuery/Javascript plugin to achieve a cross browser solution with a same result.
Solution:
By Using jScrollPane a jQuery plugin, you can achieve a cross browser solution