The X and Y matrix of Independent Variable and Dependent Variable respectively to DataFrame from int64 Type so that it gets converted from 1D array to 2D array.. i.e X=pd.DataFrame(X) and Y=pd.dataFrame(Y) where pd is of pandas class in python. and thus feature scaling in-turn doesn't lead to any error!
There are several problems here:
The newdata
argument of predict()
needs a predictor variable. You should thus pass it values for Coupon
, instead of Total
, which is the response variable in your model.
The predictor variable needs to be passed in as a named column in a data frame, so that
predict()
knows what the numbers its been handed represent. (The need for this becomes clear when you consider more complicated models, having more than one predictor variable).
For this to work, your original call should pass df
in through the data
argument, rather than using it directly in your formula. (This way, the name of the column in newdata
will be able to match the name on the RHS of the formula).
With those changes incorporated, this will work:
model <- lm(Total ~ Coupon, data=df)
new <- data.frame(Coupon = df$Coupon)
predict(model, newdata = new, interval="confidence")
Thanks Hong, that was exactly the problem I was running into. The error you get suggests that the number of rows is wrong, but the problem is actually that the model has been trained using a command that ends up with the wrong names for parameters.
This is really a critical detail that is entirely non-obvious for lm and so on. Some of the tutorial make reference to doing lines like lm(olive$Area@olive$Palmitic)
- ending up with variable names of olive$Area NOT Area, so creating an entry using anewdata<-data.frame(Palmitic=2)
can't then be used. If you use lm(Area@Palmitic,data=olive)
then the variable names are right and prediction works.
The real problem is that the error message does not indicate the problem at all:
Warning message: 'anewdata' had 1 rows but variable(s) found to have X rows
I have a very simple answer which works:
set-executionpolicy unrestricted
I found this solution following the link that was given as part of error message: About Execution Policies
Ignore this answer. Not that it doesn't work. But there are better methods available. Moreover, Android emphatically discourage direct communication between fragments. See official doc. Thanks user @Wahib Ul Haq for the tip.
Well, you can create a private variable and setter in Fragment B, and set the value from Fragment A itself,
FragmentB.java
private String inputString;
....
....
public void setInputString(String string){
inputString = string;
}
FragmentA.java
//go to fragment B
FragmentB frag = new FragmentB();
frag.setInputString(YOUR_STRING);
//create your fragment transaction object, set animation etc
fragTrans.replace(ITS_ARGUMENTS)
Or you can use Activity as you suggested in question..
It annoys me for days. And finally I make use of the CSS property selector to solve it.
[data-reactroot]
{height: 100% !important; }
Brandon, short and sweet. Also flexible.
set dSource=C:\Main directory\sub directory
set dTarget=D:\Documents
set fType=*.doc
for /f "delims=" %%f in ('dir /a-d /b /s "%dSource%\%fType%"') do (
copy /V "%%f" "%dTarget%\" 2>nul
)
Hope this helps.
I would add some checks after the copy (using '||') but i'm not sure how "copy /v" reacts when it encounters an error.
you may want to try this:
copy /V "%%f" "%dTarget%\" 2>nul|| echo En error occured copying "%%F".&& exit /b 1
As the copy line. let me know if you get something out of it (in no position to test a copy failure atm..)
I like the Apache Commons IO library. Take a look at its version of ByteArrayOutputStream, which has a toString(String enc)
method as well as toByteArray()
. Using existing and trusted components like the Commons project lets your code be smaller and easier to extend and repurpose.
Solution
The date format that you requested is called ODBC format (code 120).
To actually calculate the values that you requested, include the following in your SQL.
Copy, paste...
DECLARE
@FirstDayOfLastMonth DATETIME = CONVERT(DATE, DATEADD(d, -( DAY(DATEADD(m, -1, GETDATE() - 2)) ), DATEADD(m, -1, GETDATE() - 1)))
, @LastDayOfLastMonth DATETIME = CONVERT(DATE, DATEADD(d, -( DAY(GETDATE()) ), GETDATE()))
...and use in your code:
- @FirstDayOfLastMonth
- @LastDayOfLastMonth
Be aware that it has to be pasted earlier than any statements that reference the parameters, but from that point on you can reference @FirstDayOfLastMonth and @LastDayOfLastMonth in your code.
Example
Let's see some code in action:
DECLARE
@FirstDayOfLastMonth DATETIME = CONVERT(DATE, DATEADD(d, -( DAY(DATEADD(m, -1, GETDATE() - 2)) ), DATEADD(m, -1, GETDATE() - 1)))
, @LastDayOfLastMonth DATETIME = CONVERT(DATE, DATEADD(d, -( DAY(GETDATE()) ), GETDATE()))
SELECT
'First day of last month' AS Title, CONVERT(VARCHAR, @FirstDayOfLastMonth , 120) AS [ODBC]
UNION
SELECT
'Last day of last month' AS Title, CONVERT(VARCHAR, @LastDayOfLastMonth , 120) AS [ODBC]
Run the above code to produce the following output:
Note: Bear in mind that today's date for me is 12th September, 2016.
More (for completeness' sake)
Common date parameters
Are you left wanting more?
To set up a more comprehensive range of handy date related parameters, include the following in your SQL:
DECLARE
@FirstDayOfCurrentWeek DATETIME = CONVERT(DATE, DATEADD(WEEK, DATEDIFF(WEEK, 0, GETDATE()), 0))
, @LastDayOfCurrentWeek DATETIME = CONVERT(DATE, DATEADD(WEEK, DATEDIFF(WEEK, 0, GETDATE()), 6))
, @FirstDayOfLastWeek DATETIME = CONVERT(DATE, DATEADD(WEEK, DATEDIFF(WEEK, 7, GETDATE()), 0))
, @LastDayOfLastWeek DATETIME = CONVERT(DATE, DATEADD(WEEK, DATEDIFF(WEEK, 7, GETDATE()), 6))
, @FirstDayOfNextWeek DATETIME = CONVERT(DATE, DATEADD(WEEK, DATEDIFF(WEEK, 0, GETDATE()), 7))
, @LastDayOfNextWeek DATETIME = CONVERT(DATE, DATEADD(WEEK, DATEDIFF(WEEK, 0, GETDATE()), 13))
, @FirstDayOfCurrentMonth DATETIME = CONVERT(DATE, DATEADD(d, -( DAY(GETDATE() - 1) ), GETDATE()))
, @LastDayOfCurrentMonth DATETIME = CONVERT(DATE, DATEADD(d, -( DAY(DATEADD(m, 1, GETDATE())) ), DATEADD(m, 1, GETDATE())))
, @FirstDayOfLastMonth DATETIME = CONVERT(DATE, DATEADD(d, -( DAY(DATEADD(m, -1, GETDATE() - 2)) ), DATEADD(m, -1, GETDATE() - 1)))
, @LastDayOfLastMonth DATETIME = CONVERT(DATE, DATEADD(d, -( DAY(GETDATE()) ), GETDATE()))
, @FirstDayOfNextMonth DATETIME = CONVERT(DATE, DATEADD(d, -( DAY(DATEADD(m, 1, GETDATE() - 1)) ), DATEADD(m, 1, GETDATE())))
, @LastDayOfNextMonth DATETIME = CONVERT(DATE, DATEADD(d, -( DAY(DATEADD(m, 2, GETDATE())) ), DATEADD(m, 2, GETDATE())))
, @FirstDayOfCurrentYear DATETIME = CONVERT(DATE, DATEADD(YEAR, DATEDIFF(YEAR, 0, GETDATE()), 0))
, @LastDayOfCurrentYear DATETIME = CONVERT(DATE, DATEADD(ms, -2, DATEADD(YEAR, 0, DATEADD(YEAR, DATEDIFF(YEAR, 0, GETDATE()) + 1, 0))))
, @FirstDayOfLastYear DATETIME = CONVERT(DATE, DATEADD(YEAR, DATEDIFF(YEAR, 0, GETDATE()) - 1, 0))
, @LastDayOfLastYear DATETIME = CONVERT(DATE, DATEADD(ms, -2, DATEADD(YEAR, 0, DATEADD(YEAR, DATEDIFF(YEAR, 0, GETDATE()), 0))))
, @FirstDayOfNextYear DATETIME = CONVERT(DATE, DATEADD(YEAR, DATEDIFF(YEAR, 0, GETDATE()) + 1, 0))
, @LastDayOfNextYear DATETIME = CONVERT(DATE, DATEADD(ms, -2, DATEADD(YEAR, 0, DATEADD(YEAR, DATEDIFF(YEAR, 0, GETDATE()) + 2, 0))))
It would make most sense to include it earlier on, preferably at the top of your procedure or SQL query.
Once declared, the parameters can be referenced anywhere in your code, as many times as you need them.
Example
Let's see some code in action:
DECLARE
@FirstDayOfCurrentWeek DATETIME = CONVERT(DATE, DATEADD(WEEK, DATEDIFF(WEEK, 0, GETDATE()), 0))
, @LastDayOfCurrentWeek DATETIME = CONVERT(DATE, DATEADD(WEEK, DATEDIFF(WEEK, 0, GETDATE()), 6))
, @FirstDayOfLastWeek DATETIME = CONVERT(DATE, DATEADD(WEEK, DATEDIFF(WEEK, 7, GETDATE()), 0))
, @LastDayOfLastWeek DATETIME = CONVERT(DATE, DATEADD(WEEK, DATEDIFF(WEEK, 7, GETDATE()), 6))
, @FirstDayOfNextWeek DATETIME = CONVERT(DATE, DATEADD(WEEK, DATEDIFF(WEEK, 0, GETDATE()), 7))
, @LastDayOfNextWeek DATETIME = CONVERT(DATE, DATEADD(WEEK, DATEDIFF(WEEK, 0, GETDATE()), 13))
, @FirstDayOfCurrentMonth DATETIME = CONVERT(DATE, DATEADD(d, -( DAY(GETDATE() - 1) ), GETDATE()))
, @LastDayOfCurrentMonth DATETIME = CONVERT(DATE, DATEADD(d, -( DAY(DATEADD(m, 1, GETDATE())) ), DATEADD(m, 1, GETDATE())))
, @FirstDayOfLastMonth DATETIME = CONVERT(DATE, DATEADD(d, -( DAY(DATEADD(m, -1, GETDATE() - 2)) ), DATEADD(m, -1, GETDATE() - 1)))
, @LastDayOfLastMonth DATETIME = CONVERT(DATE, DATEADD(d, -( DAY(GETDATE()) ), GETDATE()))
, @FirstDayOfNextMonth DATETIME = CONVERT(DATE, DATEADD(d, -( DAY(DATEADD(m, 1, GETDATE() - 1)) ), DATEADD(m, 1, GETDATE())))
, @LastDayOfNextMonth DATETIME = CONVERT(DATE, DATEADD(d, -( DAY(DATEADD(m, 2, GETDATE())) ), DATEADD(m, 2, GETDATE())))
, @FirstDayOfCurrentYear DATETIME = CONVERT(DATE, DATEADD(YEAR, DATEDIFF(YEAR, 0, GETDATE()), 0))
, @LastDayOfCurrentYear DATETIME = CONVERT(DATE, DATEADD(ms, -2, DATEADD(YEAR, 0, DATEADD(YEAR, DATEDIFF(YEAR, 0, GETDATE()) + 1, 0))))
, @FirstDayOfLastYear DATETIME = CONVERT(DATE, DATEADD(YEAR, DATEDIFF(YEAR, 0, GETDATE()) - 1, 0))
, @LastDayOfLastYear DATETIME = CONVERT(DATE, DATEADD(ms, -2, DATEADD(YEAR, 0, DATEADD(YEAR, DATEDIFF(YEAR, 0, GETDATE()), 0))))
, @FirstDayOfNextYear DATETIME = CONVERT(DATE, DATEADD(YEAR, DATEDIFF(YEAR, 0, GETDATE()) + 1, 0))
, @LastDayOfNextYear DATETIME = CONVERT(DATE, DATEADD(ms, -2, DATEADD(YEAR, 0, DATEADD(YEAR, DATEDIFF(YEAR, 0, GETDATE()) + 2, 0))))
SELECT
'a) FirstDayOfCurrentWeek.' AS [Title] ,
@FirstDayOfCurrentWeek AS [DATE (Server default)] ,
CONVERT(VARCHAR, @FirstDayOfCurrentWeek, 127) AS [ISO8601] ,
CONVERT(VARCHAR, @FirstDayOfCurrentWeek, 103) + ' ' + CONVERT(CHAR(5), @FirstDayOfCurrentWeek, 108) AS [British&French] ,
CONVERT(VARCHAR, @FirstDayOfCurrentWeek, 104) + ' ' + CONVERT(CHAR(5), @FirstDayOfCurrentWeek, 108) AS [German] ,
CONVERT(VARCHAR, @FirstDayOfCurrentWeek, 105) + ' ' + CONVERT(CHAR(5), @FirstDayOfCurrentWeek, 108) AS [Italian] ,
CONVERT(VARCHAR, @FirstDayOfCurrentWeek, 111) + ' ' + CONVERT(CHAR(5), @FirstDayOfCurrentWeek, 108) AS [Japan] ,
CONVERT(VARCHAR, @FirstDayOfCurrentWeek, 100) AS [U.S.] ,
CONVERT(VARCHAR, @FirstDayOfCurrentWeek, 120) AS [ODBC]
UNION
SELECT
'b) LastDayOfCurrentWeek.' AS [Title] ,
@LastDayOfCurrentWeek AS [DATE (Server default)] ,
CONVERT(VARCHAR, @LastDayOfCurrentWeek, 127) AS [ISO8601] ,
CONVERT(VARCHAR, @LastDayOfCurrentWeek, 103) + ' ' + CONVERT(CHAR(5), @FirstDayOfCurrentWeek, 108) AS [British&French] ,
CONVERT(VARCHAR, @LastDayOfCurrentWeek, 104) + ' ' + CONVERT(CHAR(5), @FirstDayOfCurrentWeek, 108) AS [German] ,
CONVERT(VARCHAR, @LastDayOfCurrentWeek, 105) + ' ' + CONVERT(CHAR(5), @FirstDayOfCurrentWeek, 108) AS [Italian] ,
CONVERT(VARCHAR, @LastDayOfCurrentWeek, 111) + ' ' + CONVERT(CHAR(5), @FirstDayOfCurrentWeek, 108) AS [Japan] ,
CONVERT(VARCHAR, @LastDayOfCurrentWeek, 100) AS [U.S.] ,
CONVERT(VARCHAR, @LastDayOfCurrentWeek, 120) AS [ODBC]
UNION
SELECT
'c) FirstDayOfLastWeek.' AS [Title] ,
@FirstDayOfLastWeek AS [DATE (Server default)] ,
CONVERT(VARCHAR, @FirstDayOfLastWeek, 127) AS [ISO8601] ,
CONVERT(VARCHAR, @FirstDayOfLastWeek, 103) + ' ' + CONVERT(CHAR(5), @FirstDayOfCurrentWeek, 108) AS [British&French] ,
CONVERT(VARCHAR, @FirstDayOfLastWeek, 104) + ' ' + CONVERT(CHAR(5), @FirstDayOfCurrentWeek, 108) AS [German] ,
CONVERT(VARCHAR, @FirstDayOfLastWeek, 105) + ' ' + CONVERT(CHAR(5), @FirstDayOfCurrentWeek, 108) AS [Italian] ,
CONVERT(VARCHAR, @FirstDayOfLastWeek, 111) + ' ' + CONVERT(CHAR(5), @FirstDayOfCurrentWeek, 108) AS [Japan] ,
CONVERT(VARCHAR, @FirstDayOfLastWeek, 100) AS [U.S.] ,
CONVERT(VARCHAR, @FirstDayOfLastWeek, 120) AS [ODBC]
UNION
SELECT
'd) LastDayOfLastWeek.' AS [Title] ,
@LastDayOfLastWeek AS [DATE (Server default)] ,
CONVERT(VARCHAR, @LastDayOfLastWeek, 127) AS [ISO8601] ,
CONVERT(VARCHAR, @LastDayOfLastWeek, 103) + ' ' + CONVERT(CHAR(5), @FirstDayOfCurrentWeek, 108) AS [British&French] ,
CONVERT(VARCHAR, @LastDayOfLastWeek, 104) + ' ' + CONVERT(CHAR(5), @FirstDayOfCurrentWeek, 108) AS [German] ,
CONVERT(VARCHAR, @LastDayOfLastWeek, 105) + ' ' + CONVERT(CHAR(5), @FirstDayOfCurrentWeek, 108) AS [Italian] ,
CONVERT(VARCHAR, @LastDayOfLastWeek, 111) + ' ' + CONVERT(CHAR(5), @FirstDayOfCurrentWeek, 108) AS [Japan] ,
CONVERT(VARCHAR, @LastDayOfLastWeek, 100) AS [U.S.] ,
CONVERT(VARCHAR, @LastDayOfLastWeek, 120) AS [ODBC]
UNION
SELECT
'e) FirstDayOfNextWeek.' AS [Title] ,
@FirstDayOfNextWeek AS [DATE (Server default)] ,
CONVERT(VARCHAR, @FirstDayOfNextWeek, 127) AS [ISO8601] ,
CONVERT(VARCHAR, @FirstDayOfNextWeek, 103) + ' ' + CONVERT(CHAR(5), @FirstDayOfCurrentWeek, 108) AS [British&French] ,
CONVERT(VARCHAR, @FirstDayOfNextWeek, 104) + ' ' + CONVERT(CHAR(5), @FirstDayOfCurrentWeek, 108) AS [German] ,
CONVERT(VARCHAR, @FirstDayOfNextWeek, 105) + ' ' + CONVERT(CHAR(5), @FirstDayOfCurrentWeek, 108) AS [Italian] ,
CONVERT(VARCHAR, @FirstDayOfNextWeek, 111) + ' ' + CONVERT(CHAR(5), @FirstDayOfCurrentWeek, 108) AS [Japan] ,
CONVERT(VARCHAR, @FirstDayOfNextWeek, 100) AS [U.S.] ,
CONVERT(VARCHAR, @FirstDayOfNextWeek, 120) AS [ODBC]
UNION
SELECT
'f) LastDayOfNextWeek.' AS [Title] ,
@LastDayOfNextWeek AS [DATE (Server default)] ,
CONVERT(VARCHAR, @LastDayOfNextWeek, 127) AS [ISO8601] ,
CONVERT(VARCHAR, @LastDayOfNextWeek, 103) + ' ' + CONVERT(CHAR(5), @FirstDayOfCurrentWeek, 108) AS [British&French] ,
CONVERT(VARCHAR, @LastDayOfNextWeek, 104) + ' ' + CONVERT(CHAR(5), @FirstDayOfCurrentWeek, 108) AS [German] ,
CONVERT(VARCHAR, @LastDayOfNextWeek, 105) + ' ' + CONVERT(CHAR(5), @FirstDayOfCurrentWeek, 108) AS [Italian] ,
CONVERT(VARCHAR, @LastDayOfNextWeek, 111) + ' ' + CONVERT(CHAR(5), @FirstDayOfCurrentWeek, 108) AS [Japan] ,
CONVERT(VARCHAR, @LastDayOfNextWeek, 100) AS [U.S.] ,
CONVERT(VARCHAR, @LastDayOfNextWeek, 120) AS [ODBC]
UNION
SELECT
'g) FirstDayOfCurrentMonth.' AS [Title] ,
@FirstDayOfCurrentMonth AS [DATE (Server default)] ,
CONVERT(VARCHAR, @FirstDayOfCurrentMonth, 127) AS [ISO8601] ,
CONVERT(VARCHAR, @FirstDayOfCurrentMonth, 103) + ' ' + CONVERT(CHAR(5), @FirstDayOfCurrentWeek, 108) AS [British&French] ,
CONVERT(VARCHAR, @FirstDayOfCurrentMonth, 104) + ' ' + CONVERT(CHAR(5), @FirstDayOfCurrentWeek, 108) AS [German] ,
CONVERT(VARCHAR, @FirstDayOfCurrentMonth, 105) + ' ' + CONVERT(CHAR(5), @FirstDayOfCurrentWeek, 108) AS [Italian] ,
CONVERT(VARCHAR, @FirstDayOfCurrentMonth, 111) + ' ' + CONVERT(CHAR(5), @FirstDayOfCurrentWeek, 108) AS [Japan] ,
CONVERT(VARCHAR, @FirstDayOfCurrentMonth, 100) AS [U.S.] ,
CONVERT(VARCHAR, @FirstDayOfCurrentMonth, 120) AS [ODBC]
UNION
SELECT
'h) LastDayOfCurrentMonth.' AS [Title] ,
@LastDayOfCurrentMonth AS [DATE (Server default)] ,
CONVERT(VARCHAR, @LastDayOfCurrentMonth, 127) AS [ISO8601] ,
CONVERT(VARCHAR, @LastDayOfCurrentMonth, 103) + ' ' + CONVERT(CHAR(5), @FirstDayOfCurrentWeek, 108) AS [British&French] ,
CONVERT(VARCHAR, @LastDayOfCurrentMonth, 104) + ' ' + CONVERT(CHAR(5), @FirstDayOfCurrentWeek, 108) AS [German] ,
CONVERT(VARCHAR, @LastDayOfCurrentMonth, 105) + ' ' + CONVERT(CHAR(5), @FirstDayOfCurrentWeek, 108) AS [Italian] ,
CONVERT(VARCHAR, @LastDayOfCurrentMonth, 111) + ' ' + CONVERT(CHAR(5), @FirstDayOfCurrentWeek, 108) AS [Japan] ,
CONVERT(VARCHAR, @LastDayOfCurrentMonth, 100) AS [U.S.] ,
CONVERT(VARCHAR, @LastDayOfCurrentMonth, 120) AS [ODBC]
UNION
SELECT
'i) FirstDayOfLastMonth.' AS [Title] ,
@FirstDayOfLastMonth AS [DATE (Server default)] ,
CONVERT(VARCHAR, @FirstDayOfLastMonth, 127) AS [ISO8601] ,
CONVERT(VARCHAR, @FirstDayOfLastMonth, 103) + ' ' + CONVERT(CHAR(5), @FirstDayOfCurrentWeek, 108) AS [British&French] ,
CONVERT(VARCHAR, @FirstDayOfLastMonth, 104) + ' ' + CONVERT(CHAR(5), @FirstDayOfCurrentWeek, 108) AS [German] ,
CONVERT(VARCHAR, @FirstDayOfLastMonth, 105) + ' ' + CONVERT(CHAR(5), @FirstDayOfCurrentWeek, 108) AS [Italian] ,
CONVERT(VARCHAR, @FirstDayOfLastMonth, 111) + ' ' + CONVERT(CHAR(5), @FirstDayOfCurrentWeek, 108) AS [Japan] ,
CONVERT(VARCHAR, @FirstDayOfLastMonth, 100) AS [U.S.] ,
CONVERT(VARCHAR, @FirstDayOfLastMonth, 120) AS [ODBC]
UNION
SELECT
'j) LastDayOfLastMonth.' AS [Title] ,
@LastDayOfLastMonth AS [DATE (Server default)] ,
CONVERT(VARCHAR, @LastDayOfLastMonth, 127) AS [ISO8601] ,
CONVERT(VARCHAR, @LastDayOfLastMonth, 103) + ' ' + CONVERT(CHAR(5), @FirstDayOfCurrentWeek, 108) AS [British&French] ,
CONVERT(VARCHAR, @LastDayOfLastMonth, 104) + ' ' + CONVERT(CHAR(5), @FirstDayOfCurrentWeek, 108) AS [German] ,
CONVERT(VARCHAR, @LastDayOfLastMonth, 105) + ' ' + CONVERT(CHAR(5), @FirstDayOfCurrentWeek, 108) AS [Italian] ,
CONVERT(VARCHAR, @LastDayOfLastMonth, 111) + ' ' + CONVERT(CHAR(5), @FirstDayOfCurrentWeek, 108) AS [Japan] ,
CONVERT(VARCHAR, @LastDayOfLastMonth, 100) AS [U.S.] ,
CONVERT(VARCHAR, @LastDayOfLastMonth, 120) AS [ODBC]
UNION
SELECT
'k) FirstDayOfNextMonth.' AS [Title] ,
@FirstDayOfNextMonth AS [DATE (Server default)] ,
CONVERT(VARCHAR, @FirstDayOfNextMonth, 127) AS [ISO8601] ,
CONVERT(VARCHAR, @FirstDayOfNextMonth, 103) + ' ' + CONVERT(CHAR(5), @FirstDayOfCurrentWeek, 108) AS [British&French] ,
CONVERT(VARCHAR, @FirstDayOfNextMonth, 104) + ' ' + CONVERT(CHAR(5), @FirstDayOfCurrentWeek, 108) AS [German] ,
CONVERT(VARCHAR, @FirstDayOfNextMonth, 105) + ' ' + CONVERT(CHAR(5), @FirstDayOfCurrentWeek, 108) AS [Italian] ,
CONVERT(VARCHAR, @FirstDayOfNextMonth, 111) + ' ' + CONVERT(CHAR(5), @FirstDayOfCurrentWeek, 108) AS [Japan] ,
CONVERT(VARCHAR, @FirstDayOfNextMonth, 100) AS [U.S.] ,
CONVERT(VARCHAR, @FirstDayOfNextMonth, 120) AS [ODBC]
UNION
SELECT
'l) LastDayOfNextMonth.' AS [Title] ,
@LastDayOfNextMonth AS [DATE (Server default)] ,
CONVERT(VARCHAR, @LastDayOfNextMonth, 127) AS [ISO8601] ,
CONVERT(VARCHAR, @LastDayOfNextMonth, 103) + ' ' + CONVERT(CHAR(5), @FirstDayOfCurrentWeek, 108) AS [British&French] ,
CONVERT(VARCHAR, @LastDayOfNextMonth, 104) + ' ' + CONVERT(CHAR(5), @FirstDayOfCurrentWeek, 108) AS [German] ,
CONVERT(VARCHAR, @LastDayOfNextMonth, 105) + ' ' + CONVERT(CHAR(5), @FirstDayOfCurrentWeek, 108) AS [Italian] ,
CONVERT(VARCHAR, @LastDayOfNextMonth, 111) + ' ' + CONVERT(CHAR(5), @FirstDayOfCurrentWeek, 108) AS [Japan] ,
CONVERT(VARCHAR, @LastDayOfNextMonth, 100) AS [U.S.] ,
CONVERT(VARCHAR, @LastDayOfNextMonth, 120) AS [ODBC]
UNION
SELECT
'm) FirstDayOfCurrentYear.' AS [Title] ,
@FirstDayOfCurrentYear AS [DATE (Server default)] ,
CONVERT(VARCHAR, @FirstDayOfCurrentYear, 127) AS [ISO8601] ,
CONVERT(VARCHAR, @FirstDayOfCurrentYear, 103) + ' ' + CONVERT(CHAR(5), @FirstDayOfCurrentWeek, 108) AS [British&French] ,
CONVERT(VARCHAR, @FirstDayOfCurrentYear, 104) + ' ' + CONVERT(CHAR(5), @FirstDayOfCurrentWeek, 108) AS [German] ,
CONVERT(VARCHAR, @FirstDayOfCurrentYear, 105) + ' ' + CONVERT(CHAR(5), @FirstDayOfCurrentWeek, 108) AS [Italian] ,
CONVERT(VARCHAR, @FirstDayOfCurrentYear, 111) + ' ' + CONVERT(CHAR(5), @FirstDayOfCurrentWeek, 108) AS [Japan] ,
CONVERT(VARCHAR, @FirstDayOfCurrentYear, 100) AS [U.S.] ,
CONVERT(VARCHAR, @FirstDayOfCurrentYear, 120) AS [ODBC]
UNION
SELECT
'n) LastDayOfCurrentYear.' AS [Title] ,
@LastDayOfCurrentYear AS [DATE (Server default)] ,
CONVERT(VARCHAR, @LastDayOfCurrentYear, 127) AS [ISO8601] ,
CONVERT(VARCHAR, @LastDayOfCurrentYear, 103) + ' ' + CONVERT(CHAR(5), @FirstDayOfCurrentWeek, 108) AS [British&French] ,
CONVERT(VARCHAR, @LastDayOfCurrentYear, 104) + ' ' + CONVERT(CHAR(5), @FirstDayOfCurrentWeek, 108) AS [German] ,
CONVERT(VARCHAR, @LastDayOfCurrentYear, 105) + ' ' + CONVERT(CHAR(5), @FirstDayOfCurrentWeek, 108) AS [Italian] ,
CONVERT(VARCHAR, @LastDayOfCurrentYear, 111) + ' ' + CONVERT(CHAR(5), @FirstDayOfCurrentWeek, 108) AS [Japan] ,
CONVERT(VARCHAR, @LastDayOfCurrentYear, 100) AS [U.S.] ,
CONVERT(VARCHAR, @LastDayOfCurrentYear, 120) AS [ODBC]
UNION
SELECT
'o) FirstDayOfLastYear.' AS [Title] ,
@FirstDayOfLastYear AS [DATE (Server default)] ,
CONVERT(VARCHAR, @FirstDayOfLastYear, 127) AS [ISO8601] ,
CONVERT(VARCHAR, @FirstDayOfLastYear, 103) + ' ' + CONVERT(CHAR(5), @FirstDayOfCurrentWeek, 108) AS [British&French] ,
CONVERT(VARCHAR, @FirstDayOfLastYear, 104) + ' ' + CONVERT(CHAR(5), @FirstDayOfCurrentWeek, 108) AS [German] ,
CONVERT(VARCHAR, @FirstDayOfLastYear, 105) + ' ' + CONVERT(CHAR(5), @FirstDayOfCurrentWeek, 108) AS [Italian] ,
CONVERT(VARCHAR, @FirstDayOfLastYear, 111) + ' ' + CONVERT(CHAR(5), @FirstDayOfCurrentWeek, 108) AS [Japan] ,
CONVERT(VARCHAR, @FirstDayOfLastYear, 100) AS [U.S.] ,
CONVERT(VARCHAR, @FirstDayOfLastYear, 120) AS [ODBC]
UNION
SELECT
'p) LastDayOfLastYear.' AS [Title] ,
@LastDayOfLastYear AS [DATE (Server default)] ,
CONVERT(VARCHAR, @LastDayOfLastYear, 127) AS [ISO8601] ,
CONVERT(VARCHAR, @LastDayOfLastYear, 103) + ' ' + CONVERT(CHAR(5), @FirstDayOfCurrentWeek, 108) AS [British&French] ,
CONVERT(VARCHAR, @LastDayOfLastYear, 104) + ' ' + CONVERT(CHAR(5), @FirstDayOfCurrentWeek, 108) AS [German] ,
CONVERT(VARCHAR, @LastDayOfLastYear, 105) + ' ' + CONVERT(CHAR(5), @FirstDayOfCurrentWeek, 108) AS [Italian] ,
CONVERT(VARCHAR, @LastDayOfLastYear, 111) + ' ' + CONVERT(CHAR(5), @FirstDayOfCurrentWeek, 108) AS [Japan] ,
CONVERT(VARCHAR, @LastDayOfLastYear, 100) AS [U.S.] ,
CONVERT(VARCHAR, @LastDayOfLastYear, 120) AS [ODBC]
UNION
SELECT
'q) FirstDayOfNextYear.' AS [Title] ,
@FirstDayOfNextYear AS [DATE (Server default)] ,
CONVERT(VARCHAR, @FirstDayOfNextYear, 127) AS [ISO8601] ,
CONVERT(VARCHAR, @FirstDayOfNextYear, 103) + ' ' + CONVERT(CHAR(5), @FirstDayOfCurrentWeek, 108) AS [British&French] ,
CONVERT(VARCHAR, @FirstDayOfNextYear, 104) + ' ' + CONVERT(CHAR(5), @FirstDayOfCurrentWeek, 108) AS [German] ,
CONVERT(VARCHAR, @FirstDayOfNextYear, 105) + ' ' + CONVERT(CHAR(5), @FirstDayOfCurrentWeek, 108) AS [Italian] ,
CONVERT(VARCHAR, @FirstDayOfNextYear, 111) + ' ' + CONVERT(CHAR(5), @FirstDayOfCurrentWeek, 108) AS [Japan] ,
CONVERT(VARCHAR, @FirstDayOfNextYear, 100) AS [U.S.] ,
CONVERT(VARCHAR, @FirstDayOfNextYear, 120) AS [ODBC]
UNION
SELECT
'r) LastDayOfNextYear.' AS [Title] ,
@LastDayOfNextYear AS [DATE (Server default)] ,
CONVERT(VARCHAR, @LastDayOfNextYear, 127) AS [ISO8601] ,
CONVERT(VARCHAR, @LastDayOfNextYear, 103) + ' ' + CONVERT(CHAR(5), @FirstDayOfCurrentWeek, 108) AS [British&French] ,
CONVERT(VARCHAR, @LastDayOfNextYear, 104) + ' ' + CONVERT(CHAR(5), @FirstDayOfCurrentWeek, 108) AS [German] ,
CONVERT(VARCHAR, @LastDayOfNextYear, 105) + ' ' + CONVERT(CHAR(5), @FirstDayOfCurrentWeek, 108) AS [Italian] ,
CONVERT(VARCHAR, @LastDayOfNextYear, 111) + ' ' + CONVERT(CHAR(5), @FirstDayOfCurrentWeek, 108) AS [Japan] ,
CONVERT(VARCHAR, @LastDayOfNextYear, 100) AS [U.S.] ,
CONVERT(VARCHAR, @LastDayOfNextYear, 120) AS [ODBC];
Run the above code to produce the following output:
If your country is missing, then it is because I don't know the code for it. It would be most helpful and appreciated if you could please edit this answer and add a new column for your country.
Thanks in advance.
Note: Bear in mind that today's date for me is 12th September, 2016.
References
For further reading on the ISO8601 international date standard, follow this link:
For further reading on the ODBC international date standard, follow this link:
To view the list of date formats I worked from, follow this link:
For further reading on the DATETIME data type, follow this link:
The documentation for the parameter spark.files.overwrite
says this: "Whether to overwrite files added through SparkContext.addFile()
when the target file exists and its contents do not match those of the source." So it has no effect on saveAsTextFiles method.
You could do this before saving the file:
val hadoopConf = new org.apache.hadoop.conf.Configuration()
val hdfs = org.apache.hadoop.fs.FileSystem.get(new java.net.URI("hdfs://localhost:9000"), hadoopConf)
try { hdfs.delete(new org.apache.hadoop.fs.Path(filepath), true) } catch { case _ : Throwable => { } }
Aas explained here: http://apache-spark-user-list.1001560.n3.nabble.com/How-can-I-make-Spark-1-0-saveAsTextFile-to-overwrite-existing-file-td6696.html
On our site we have pages where the content is static, and pages where it is loaded in with AJAX. On one page (a search page), there were cases when the AJAX results would more than fill the page, and cases where it would return no results. In order for the background image to fill the page in all cases we had to apply the following CSS:
html {
margin: 0px;
height: 100%;
width: 100%;
}
body {
margin: 0px;
min-height: 100%;
width: 100%;
}
height
for the html
and min-height
for the body
.
I got it working using:
$('#id-of-table').on('draw.dt', function() {
// do action here
});
1.- Upcasting.
Doing an upcasting, you define a tag of some type, that points to an object of a subtype (Type and subtype may be called class and subclass, if you feel more comfortable...).
Animal animalCat = new Cat();
What means that such tag, animalCat, will have the functionality (the methods) of type Animal only, because we've declared it as type Animal, not as type Cat.
We are allowed to do that in a "natural/implicit/automatic" way, at compile-time or at a run-time, mainly because Cat inherits some of its functionality from Animal; for example, move(). (At least, cat is an animal, isn't it?)
2.- Downcasting.
But, what would happen if we need to get the functionality of Cat, from our type Animal tag?.
As we have created the animalCat tag pointing to a Cat object, we need a way to call the Cat object methods, from our animalCat tag in a some smart pretty way.
Such procedure is what we call Downcasting, and we can do it only at the run-time.
Time for some code:
public class Animal {
public String move() {
return "Going to somewhere";
}
}
public class Cat extends Animal{
public String makeNoise() {
return "Meow!";
}
}
public class Test {
public static void main(String[] args) {
//1.- Upcasting
// __Type_____tag________object
Animal animalCat = new Cat();
//Some animal movement
System.out.println(animalCat.move());
//prints "Going to somewhere"
//2.- Downcasting
//Now you wanna make some Animal noise.
//First of all: type Animal hasn't any makeNoise() functionality.
//But Cat can do it!. I wanna be an Animal Cat now!!
//___________________Downcast__tag_____ Cat's method
String animalNoise = ( (Cat) animalCat ).makeNoise();
System.out.println(animalNoise);
//Prints "Meow!", as cats usually done.
//3.- An Animal may be a Cat, but a Dog or a Rhinoceros too.
//All of them have their own noises and own functionalities.
//Uncomment below and read the error in the console:
// __Type_____tag________object
//Cat catAnimal = new Animal();
}
}
Not really a reliable method, better of using JodaTime
Calendar thatDay = Calendar.getInstance();
thatDay.set(Calendar.DAY_OF_MONTH,25);
thatDay.set(Calendar.MONTH,7); // 0-11 so 1 less
thatDay.set(Calendar.YEAR, 1985);
Calendar today = Calendar.getInstance();
long diff = today.getTimeInMillis() - thatDay.getTimeInMillis(); //result in millis
Here's an approximation...
long days = diff / (24 * 60 * 60 * 1000);
To Parse the date from a string, you could use
String strThatDay = "1985/08/25";
SimpleDateFormat formatter = new SimpleDateFormat("yyyy/MM/dd");
Date d = null;
try {
d = formatter.parse(strThatDay);//catch exception
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Calendar thatDay = Calendar.getInstance();
thatDay.setTime(d); //rest is the same....
Although, since you're sure of the date format...
You Could also do Integer.parseInt()
on it's Substrings to obtain their numeric values.
You may see if you are not loading jQuery twice somehow. Especially after your plugin JavaScript file loaded.
I has the same error and found that one of my external PHP files was loading jQuery again.
Here is what is going on.
First, the only global variables Python really has are module-scoped variables. You cannot make a variable that is truly global; all you can do is make a variable in a particular scope. (If you make a variable inside the Python interpreter, and then import other modules, your variable is in the outermost scope and thus global within your Python session.)
All you have to do to make a module-global variable is just assign to a name.
Imagine a file called foo.py, containing this single line:
X = 1
Now imagine you import it.
import foo
print(foo.X) # prints 1
However, let's suppose you want to use one of your module-scope variables as a global inside a function, as in your example. Python's default is to assume that function variables are local. You simply add a global
declaration in your function, before you try to use the global.
def initDB(name):
global __DBNAME__ # add this line!
if __DBNAME__ is None: # see notes below; explicit test for None
__DBNAME__ = name
else:
raise RuntimeError("Database name has already been set.")
By the way, for this example, the simple if not __DBNAME__
test is adequate, because any string value other than an empty string will evaluate true, so any actual database name will evaluate true. But for variables that might contain a number value that might be 0, you can't just say if not variablename
; in that case, you should explicitly test for None
using the is
operator. I modified the example to add an explicit None
test. The explicit test for None
is never wrong, so I default to using it.
Finally, as others have noted on this page, two leading underscores signals to Python that you want the variable to be "private" to the module. If you ever do an import * from mymodule
, Python will not import names with two leading underscores into your name space. But if you just do a simple import mymodule
and then say dir(mymodule)
you will see the "private" variables in the list, and if you explicitly refer to mymodule.__DBNAME__
Python won't care, it will just let you refer to it. The double leading underscores are a major clue to users of your module that you don't want them rebinding that name to some value of their own.
It is considered best practice in Python not to do import *
, but to minimize the coupling and maximize explicitness by either using mymodule.something
or by explicitly doing an import like from mymodule import something
.
EDIT: If, for some reason, you need to do something like this in a very old version of Python that doesn't have the global
keyword, there is an easy workaround. Instead of setting a module global variable directly, use a mutable type at the module global level, and store your values inside it.
In your functions, the global variable name will be read-only; you won't be able to rebind the actual global variable name. (If you assign to that variable name inside your function it will only affect the local variable name inside the function.) But you can use that local variable name to access the actual global object, and store data inside it.
You can use a list
but your code will be ugly:
__DBNAME__ = [None] # use length-1 list as a mutable
# later, in code:
if __DBNAME__[0] is None:
__DBNAME__[0] = name
A dict
is better. But the most convenient is a class instance, and you can just use a trivial class:
class Box:
pass
__m = Box() # m will contain all module-level values
__m.dbname = None # database name global in module
# later, in code:
if __m.dbname is None:
__m.dbname = name
(You don't really need to capitalize the database name variable.)
I like the syntactic sugar of just using __m.dbname
rather than __m["DBNAME"]
; it seems the most convenient solution in my opinion. But the dict
solution works fine also.
With a dict
you can use any hashable value as a key, but when you are happy with names that are valid identifiers, you can use a trivial class like Box
in the above.
I just wanted to test how Union
works with the default comparer on overlapping collections of reference type objects.
My object is:
class MyInt
{
public int val;
public override string ToString()
{
return val.ToString();
}
}
My test code is:
MyInt[] myInts1 = new MyInt[10];
MyInt[] myInts2 = new MyInt[10];
int overlapFrom = 4;
Console.WriteLine("overlapFrom: {0}", overlapFrom);
Action<IEnumerable<MyInt>, string> printMyInts = (myInts, myIntsName) => Console.WriteLine("{2} ({0}): {1}", myInts.Count(), string.Join(" ", myInts), myIntsName);
for (int i = 0; i < myInts1.Length; i++)
myInts1[i] = new MyInt { val = i };
printMyInts(myInts1, nameof(myInts1));
int j = 0;
for (; j + overlapFrom < myInts1.Length; j++)
myInts2[j] = myInts1[j + overlapFrom];
for (; j < myInts2.Length; j++)
myInts2[j] = new MyInt { val = j + overlapFrom };
printMyInts(myInts2, nameof(myInts2));
IEnumerable<MyInt> myUnion = myInts1.Union(myInts2);
printMyInts(myUnion, nameof(myUnion));
for (int i = 0; i < myInts2.Length; i++)
myInts2[i].val += 10;
printMyInts(myInts2, nameof(myInts2));
printMyInts(myUnion, nameof(myUnion));
for (int i = 0; i < myInts1.Length; i++)
myInts1[i].val = i;
printMyInts(myInts1, nameof(myInts1));
printMyInts(myUnion, nameof(myUnion));
The output is:
overlapFrom: 4
myInts1 (10): 0 1 2 3 4 5 6 7 8 9
myInts2 (10): 4 5 6 7 8 9 10 11 12 13
myUnion (14): 0 1 2 3 4 5 6 7 8 9 10 11 12 13
myInts2 (10): 14 15 16 17 18 19 20 21 22 23
myUnion (14): 0 1 2 3 14 15 16 17 18 19 20 21 22 23
myInts1 (10): 0 1 2 3 4 5 6 7 8 9
myUnion (14): 0 1 2 3 4 5 6 7 8 9 20 21 22 23
So, everything works fine.
What's the difference between Perl's backticks (`
), system
, and exec
?
exec -> exec "command"; ,
system -> system("command"); and
backticks -> print `command`;
exec
exec
executes a command and never resumes the Perl script. It's to a script like a return
statement is to a function.
If the command is not found, exec
returns false. It never returns true, because if the command is found, it never returns at all. There is also no point in returning STDOUT
, STDERR
or exit status of the command. You can find documentation about it in perlfunc, because it is a function.
E.g.:
#!/usr/bin/perl
print "Need to start exec command";
my $data2 = exec('ls');
print "Now END exec command";
print "Hello $data2\n\n";
In above code, there are three print
statements, but due to exec
leaving the script, only the first print statement is executed. Also, the exec
command output is not being assigned to any variable.
Here, only you're only getting the output of the first print
statement and of executing the ls
command on standard out.
system
system
executes a command and your Perl script is resumed after the command has finished. The return value is the exit status of the command. You can find documentation about it in perlfunc.
E.g.:
#!/usr/bin/perl
print "Need to start system command";
my $data2 = system('ls');
print "Now END system command";
print "Hello $data2\n\n";
In above code, there are three print
statements. As the script is resumed after the system
command, all three print statements are executed.
Also, the result of running system
is assigned to data2
, but the assigned value is 0
(the exit code from ls
).
Here, you're getting the output of the first print
statement, then that of the ls
command, followed by the outputs of the final two print
statements on standard out.
`
)Like system
, enclosing a command in backticks executes that command and your Perl script is resumed after the command has finished. In contrast to system
, the return value is STDOUT
of the command. qx//
is equivalent to backticks. You can find documentation about it in perlop, because unlike system and exec
, it is an operator.
E.g.:
#!/usr/bin/perl
print "Need to start backticks command";
my $data2 = `ls`;
print "Now END system command";
print "Hello $data2\n\n";
In above code, there are three print
statements and all three are being executed. The output of ls
is not going to standard out directly, but assigned to the variable data2
and then printed by the final print statement.
You could do something like this for your case - (syntax may be a bit off). Also look at this link
subQuery = (from crtu in CompanyRolesToUsers where crtu.RoleId==2 || crtu.RoleId==3 select crtu.UserId).ToArrayList();
finalQuery = from u in Users where u.LastName.Contains('fra') && subQuery.Contains(u.Id) select u;
Way too complicated guys. Just include it in your gradle dependencies:
dependencies {
...
compile 'com.mcxiaoke.volley:library:1.0.17'
}
There newer ways to connect Node.js and C++. Please, loot at Nan.
EDIT
The fastest and easiest way is nbind. If you want to write asynchronous add-on you can combine Asyncworker
class from nan.
I can't think a simpler/easier way! ;-)
Using Anchor tags (Links) :
<a href="#delete-modal" class="btn btn-danger" id="delete">Delete</a>
To enable the Anchor tag:
$('#delete').removeClass('disabled');
$('#delete').attr("data-toggle", "modal");
To disable the Anchor tag:
$('#delete').addClass('disabled');
$('#delete').removeAttr('data-toggle');
For iOS 7 & 8:
Objective-C:
NSNumber *value = [NSNumber numberWithInt:UIInterfaceOrientationLandscapeLeft];
[[UIDevice currentDevice] setValue:value forKey:@"orientation"];
Swift 3+:
let value = UIInterfaceOrientation.landscapeLeft.rawValue
UIDevice.current.setValue(value, forKey: "orientation")
I call it in - viewDidAppear:
.
I suspect you want to check that it's after 11pm or before 7am:
select *
from MyTable
where CAST(Created as time) >= '23:00:00'
or CAST(Created as time) < '07:00:00'
To do it the ASP.NET way:
<asp:TextBox ID="txtBox1" TextMode="Password" runat="server" />
Armin's answer + a strict check for object types and non-angular keys such as $resolve
app.filter('orderObjectBy', function(){
return function(input, attribute) {
if (!angular.isObject(input)) return input;
var array = [];
for(var objectKey in input) {
if (typeof(input[objectKey]) === "object" && objectKey.charAt(0) !== "$")
array.push(input[objectKey]);
}
array.sort(function(a, b){
a = parseInt(a[attribute]);
b = parseInt(b[attribute]);
return a - b;
});
return array;
}
})
in your device you want to run app on Go to settings About device >> Build number triple clicks or more and back to settings you will found "Developer options" appear go to and click on "USB debugging" Done
Modern JS Solution using Set (and average case O(n))
const nums = new Set();_x000D_
while(nums.size !== 8) {_x000D_
nums.add(Math.floor(Math.random() * 100) + 1);_x000D_
}_x000D_
_x000D_
console.log([...nums]);
_x000D_
On a semi-related note, if you want to start a process that has more privileges than your current process (say, launching an admin app, which requires Administrator rights, from the main app running as a normal user), you can't do so using CreateProcess() on Vista since it won't trigger the UAC dialog (assuming it is enabled). The UAC dialog is triggered when using ShellExecute(), though.
As of C++11, the memory-safe way to do this (still using a similar construction) is with std::unique_ptr
:
std::unique_ptr<int[]> array(new int[n]);
This creates a smart pointer to a memory block large enough for n
integers that automatically deletes itself when it goes out of scope. This automatic clean-up is important because it avoids the scenario where your code quits early and never reaches your delete [] array;
statement.
Another (probably preferred) option would be to use std::vector
if you need an array capable of dynamic resizing. This is good when you need an unknown amount of space, but it has some disadvantages (non-constant time to add/delete an element). You could create an array and add elements to it with something like:
std::vector<int> array;
array.push_back(1); // adds 1 to end of array
array.push_back(2); // adds 2 to end of array
// array now contains elements [1, 2]
You could also use a dummy form arround it like:
<mat-card-footer>
<form (submit)="search(ref, id, forename, surname, postcode)" action="#">
<button mat-raised-button type="submit" class="successButton" id="invSearch" title="Click to perform search." >Search</button>
</form>
</mat-card-footer>
the search function has to return false
to make sure that the action doesn't get executed.
Just make sure the form is focused (should be when you have the input in the form) when you press enter.
If you need to handle error messages using jQuery.AJAX you will need to modify the xhr
function so the responseType
is not being modified when an error happens.
So you will have to modify the responseType
to "blob" only if it is a successful call:
$.ajax({
...
xhr: function() {
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
if (xhr.readyState == 2) {
if (xhr.status == 200) {
xhr.responseType = "blob";
} else {
xhr.responseType = "text";
}
}
};
return xhr;
},
...
error: function(xhr, textStatus, errorThrown) {
// Here you are able now to access to the property "responseText"
// as you have the type set to "text" instead of "blob".
console.error(xhr.responseText);
},
success: function(data) {
console.log(data); // Here is "blob" type
}
});
If you debug and place a breakpoint at the point right after setting the xhr.responseType
to "blob" you can note that if you try to get the value for responseText
you will get the following message:
The value is only accessible if the object's 'responseType' is '' or 'text' (was 'blob').
You could just use an even simpler typedef
:
typedef char *string;
Then, your malloc would look like a usual malloc:
string s = malloc(maxStringLength);
ByteArrayInputStream
extends InputStream
:
InputStream myInputStream = new ByteArrayInputStream(myBytes);
I don't know which version of Python you are using but I tried this in Python 3 and made a few changes and it looks like it works. The raw_input function seems to be the issue here. I changed all the raw_input functions to "input()" and I also made minor changes to the printing to be compatible with Python 3. AJ Uppal is correct when he says that you shouldn't name a variable and a function with the same name. See here for reference:
TypeError: 'int' object is not callable
My code for Python 3 is as follows:
# https://stackoverflow.com/questions/27097039/why-am-i-getting-a-traceback-most-recent-call-last-error
raw_input = 0
M = 1.6
# Miles to Kilometers
# Celsius Celsius = (var1 - 32) * 5/9
# Gallons to liters Gallons = 3.6
# Pounds to kilograms Pounds = 0.45
# Inches to centimete Inches = 2.54
def intro():
print("Welcome! This program will convert measures for you.")
main()
def main():
print("Select operation.")
print("1.Miles to Kilometers")
print("2.Fahrenheit to Celsius")
print("3.Gallons to liters")
print("4.Pounds to kilograms")
print("5.Inches to centimeters")
choice = input("Enter your choice by number: ")
if choice == '1':
convertMK()
elif choice == '2':
converCF()
elif choice == '3':
convertGL()
elif choice == '4':
convertPK()
elif choice == '5':
convertPK()
else:
print("Error")
def convertMK():
input_M = float(input(("Miles: ")))
M_conv = (M) * input_M
print("Kilometers: {M_conv}\n")
restart = str(input("Do you wish to make another conversion? [y]Yes or [n]no: "))
if restart == 'y':
main()
elif restart == 'n':
end()
else:
print("I didn't quite understand that answer. Terminating.")
main()
def converCF():
input_F = float(input(("Fahrenheit: ")))
F_conv = (input_F - 32) * 5/9
print("Celcius: {F_conv}\n")
restart = str(input("Do you wish to make another conversion? [y]Yes or [n]no: "))
if restart == 'y':
main()
elif restart == 'n':
end()
else:
print("I didn't quite understand that answer. Terminating.")
main()
def convertGL():
input_G = float(input(("Gallons: ")))
G_conv = input_G * 3.6
print("Centimeters: {G_conv}\n")
restart = str(input("Do you wish to make another conversion? [y]Yes or [n]no: "))
if restart == 'y':
main()
elif restart == 'n':
end()
else:
print ("I didn't quite understand that answer. Terminating.")
main()
def convertPK():
input_P = float(input(("Pounds: ")))
P_conv = input_P * 0.45
print("Centimeters: {P_conv}\n")
restart = str(input("Do you wish to make another conversion? [y]Yes or [n]no: "))
if restart == 'y':
main()
elif restart == 'n':
end()
else:
print ("I didn't quite understand that answer. Terminating.")
main()
def convertIC():
input_cm = float(input(("Inches: ")))
inches_conv = input_cm * 2.54
print("Centimeters: {inches_conv}\n")
restart = str(input("Do you wish to make another conversion? [y]Yes or [n]no: "))
if restart == 'y':
main()
elif restart == 'n':
end()
else:
print ("I didn't quite understand that answer. Terminating.")
main()
def end():
print("This program will close.")
exit()
intro()
I noticed a small bug in your code as well. This function should ideally convert pounds to kilograms but it looks like when it prints, it is printing "Centimeters" instead of kilograms.
def convertPK():
input_P = float(input(("Pounds: ")))
P_conv = input_P * 0.45
# Printing error in the line below
print("Centimeters: {P_conv}\n")
restart = str(input("Do you wish to make another conversion? [y]Yes or [n]no: "))
if restart == 'y':
main()
elif restart == 'n':
end()
else:
print ("I didn't quite understand that answer. Terminating.")
main()
I hope this helps.
It's a great question, but be warned that you're treading in dangerous waters here. When you're deleting code you will have to make sure you're compiling and testing often.
One great tool come to mind:
NDepend - this tool is just amazing. It takes a little while to grok, and after the first 10 minutes I think most developers just say "Screw it!" and delete the app. Once you get a good feel for NDepend, it gives you amazing insight to how your apps are coupled. Check it out: http://www.ndepend.com/. Most importantly, this tool will allow you to view methods which do not have any direct callers. It will also show you the inverse, a complete call tree for any method in the assembly (or even between assemblies).
Whatever tool you choose, it's not a task to take lightly. Especially if you're dealing with public methods on library type assemblies, as you may never know when an app is referencing them.
For users of GitHub, this worked for me:
git reset --hard <full_hash_of_commit_to_reset_to>
git push --force
This will "correct" the branch history on your local machine and the GitHub server, but anyone who has sync'ed this branch with the server since the bad commit will have the history on their local machine. If they have permission to push to the branch directly then these commits will show right back up when they sync.
All everyone else needs to do is the git reset
command from above to "correct" the branch on their local machine. Of course they would need to be wary of any local commits made to this branch after the target hash. Cherry pick/backup and reapply those as necessary, but if you are in a protected branch then the number of people who can commit directly to it is likely limited.
tray this:
getSupportActionBar().setHomeAsUpIndicator(R.drawable.ic_close);
inside onCreate()
;
Started working after adding property:
mail.smtp.starttls.enable=true
Using:
mail.smtp.host=smtp.office365.com
mail.smtp.port=587
mail.transport.protocol=smtp
mail.smtp.auth=true
mail.smtp.starttls.enable=true
[email protected]
mail.smtp.password=xxx
[email protected]
As Leo points out, the code you added to your question would not suggest a strong reference cycle (a.k.a., retain cycle). One operation-related issue that could cause a strong reference cycle would be if the operation is not getting released. While your code snippet suggests that you have not defined your operation to be concurrent, but if you have, it wouldn't be released if you never posted isFinished
, or if you had circular dependencies, or something like that. And if the operation isn't released, the view controller wouldn't be released either. I would suggest adding a breakpoint or NSLog
in your operation's dealloc
method and confirm that's getting called.
You said:
I understand the notion of retain cycles, but I am not quite sure what happens in blocks, so that confuses me a little bit
The retain cycle (strong reference cycle) issues that occur with blocks are just like the retain cycle issues you're familiar with. A block will maintain strong references to any objects that appear within the block, and it will not release those strong references until the block itself is released. Thus, if block references self
, or even just references an instance variable of self
, that will maintain strong reference to self, that is not resolved until the block is released (or in this case, until the NSOperation
subclass is released.
For more information, see the Avoid Strong Reference Cycles when Capturing self section of the Programming with Objective-C: Working with Blocks document.
If your view controller is still not getting released, you simply have to identify where the unresolved strong reference resides (assuming you confirmed the NSOperation
is getting deallocated). A common example is the use of a repeating NSTimer
. Or some custom delegate
or other object that is erroneously maintaining a strong
reference. You can often use Instruments to track down where objects are getting their strong references, e.g.:
Or in Xcode 5:
You've got what rebase
does backwards. git rebase master
does what you're asking for — takes the changes on the current branch (since its divergence from master) and replays them on top of master
, then sets the head of the current branch to be the head of that new history. It doesn't replay the changes from master
on top of the current branch.
To do structural modification on the source of the stream, as Pshemo mentioned in his answer, one solution is to create a new instance of a Collection
like ArrayList
with the items inside your primary list; iterate over the new list, and do the operations on the primary list.
new ArrayList<>(users).stream().forEach(u -> users.remove(u));
The new
keyword is for creating new object instances. And yes, javascript is a dynamic programming language, which supports the object oriented programming paradigm. The convention about the object naming is, always use capital letter for objects that are supposed to be instantiated by the new keyword.
obj = new Element();
I suggest you to go through switch (manual).
switch ($your_variable)
{
case 1:
case 2:
echo "the value is either 1 or 2.";
break;
}
Explanation
Like for the value you want to execute a single statement for, you can put it without a break as as until or unless break is found. It will go on executing the code and if a break found, it will come out of the switch case.
In regards to your code, see @Coulton. You'll need to use JavaScript.
Checkout either FitText (it does work in IE, they just ballsed their site somehow) or BigText.
FitText will allow you to scale some text in relation to the container it is in, while BigText is more about resizing different sections of text to be the same width within the container.
BigText will set your string to exactly the width of the container, whereas FitText is less pixel perfect. It starts by setting the font-size at 1/10th of the container element's width. It doesn't work very well with all fonts by default, but it has a setting which allows you to decrease or increase the 'power' of the re-size. It also allows you to set a min and max font-size. It will take a bit of fiddling to get working the first time, but does work great.
http://marabeas.io <- playing with it currently here. As far as I understand, BigText wouldn't work in my context at all.
For those of you using Angularjs, here's an Angular version of FitText I've made.
Here's a LESS mixin you can use to make @humanityANDpeace's solution a little more pretty:
@mqIterations: 19;
.fontResize(@i) when (@i > 0) {
@media all and (min-width: 100px * @i) { body { font-size:0.2em * @i; } }
.fontResize((@i - 1));
}
.fontResize(@mqIterations);
And an SCSS version thanks to @NIXin!
$mqIterations: 19;
@mixin fontResize($iterations) {
$i: 1;
@while $i <= $iterations {
@media all and (min-width: 100px * $i) { body { font-size:0.2em * $i; } }
$i: $i + 1;
}
}
@include fontResize($mqIterations);
@html.label and @html.textbox are use when you want bind it to your model in a easy way...which cannot be achieve by input etc. in one line
For the modern answer I am ignoring the requirement to use SimpleDateFormat
. While using this class for parsing was a good idea in 2010 when this question was asked, it is now long outdated. The replacement, DateTimeFormatter
, came out in 2014. The idea in the following is pretty much the same as in the accepted answer.
private static DateTimeFormatter[] parseFormatters = Stream.of("M/yy", "M/y", "M/d/y", "M-d-y")
.map(DateTimeFormatter::ofPattern)
.toArray(DateTimeFormatter[]::new);
public static YearMonth parseYearMonth(String input) {
for (DateTimeFormatter formatter : parseFormatters) {
try {
return YearMonth.parse(input, formatter);
} catch (DateTimeParseException dtpe) {
// ignore, try next format
}
}
throw new IllegalArgumentException("Could not parse " + input);
}
This parses each of the input strings from the question into a year-month of 2009-09
. It’s important to try the two-digit year first since "M/y"
could also parse 9/09
, but into 0009-09
instead.
A limitation of the above code is it ignores the day-of-month from the strings that have one, like 9/1/2009
. Maybe it’s OK as long as most formats have only month and year. To pick it up, we’d have to try LocalDate.parse()
rather then YearMonth.parse()
for the formats that include d
in the pattern string. Surely it can be done.
you can verify a Google authentication access token by using this endpoint:
https://www.googleapis.com/oauth2/v3/tokeninfo?access_token=<access_token>
This is Google V3 OAuth AccessToken validating endpoint, you can refer from google document below: (In OAUTH 2.0 ENDPOINTS
Tab)
https://developers.google.com/identity/protocols/OAuth2UserAgent#validate-access-token
The merge method returns the merged collection, it doesn't mutate the original collection, thus you need to do the following
$original = new Collection(['foo']);
$latest = new Collection(['bar']);
$merged = $original->merge($latest); // Contains foo and bar.
Applying the example to your code
$related = new Collection();
foreach ($question->tags as $tag)
{
$related = $related->merge($tag->questions);
}
This worked for me:
<div class="container><p>My text</p></div>
.container{
position: absolute;
left: 0;
right: 0;
margin-left: auto;
margin-right: auto;
}
Tried the Swift 3 option above, but it didnt work. I think you need the following if you are to run against iOS 10+ on Swift 3:
Swift 3 (iOS 10+):
let phoneNumber = mymobileNO.titleLabel.text
UIApplication.shared.open(URL(string: phoneNumber)!, options: [:], completionHandler: nil)
You need to parse each octet back to number, and use that value to get a character, something like this:
function bin2String(array) {
var result = "";
for (var i = 0; i < array.length; i++) {
result += String.fromCharCode(parseInt(array[i], 2));
}
return result;
}
bin2String(["01100110", "01101111", "01101111"]); // "foo"
// Using your string2Bin function to test:
bin2String(string2Bin("hello world")) === "hello world";
Edit: Yes, your current string2Bin
can be written more shortly:
function string2Bin(str) {
var result = [];
for (var i = 0; i < str.length; i++) {
result.push(str.charCodeAt(i).toString(2));
}
return result;
}
But by looking at the documentation you linked, I think that the setBytesParameter
method expects that the blob array contains the decimal numbers, not a bit string, so you could write something like this:
function string2Bin(str) {
var result = [];
for (var i = 0; i < str.length; i++) {
result.push(str.charCodeAt(i));
}
return result;
}
function bin2String(array) {
return String.fromCharCode.apply(String, array);
}
string2Bin('foo'); // [102, 111, 111]
bin2String(string2Bin('foo')) === 'foo'; // true
Just download and install "Samsung Kies" from this link. and everything would work as required.
Before installing, uninstall the drivers you have installed for your device.
Update:
Two possible solutions:
I think you're looking for dispatch_after()
. It requires your block to accept no parameters, but you can just let the block capture those variables from your local scope instead.
int parameter1 = 12;
float parameter2 = 144.1;
// Delay execution of my block for 10 seconds.
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 10 * NSEC_PER_SEC), dispatch_get_main_queue(), ^{
NSLog(@"parameter1: %d parameter2: %f", parameter1, parameter2);
});
More: https://developer.apple.com/documentation/dispatch/1452876-dispatch_after
I would like to add some additional aspect of this discussion. In windows OS I have observed that when a jar file containing schema is stored in a directory whose path contains a space character, for instance like in the following example
"c:\Program Files\myApp\spring-beans-4.0.2.RELEASE.jar"
then specifying schema location URL in the following way is not sufficient when you are developing some standalone application that should work also offline
<beans
xsi:schemaLocation="
http://www.springframework.org/schema/beans org/springframework/beans/factory/xml/spring-beans-2.0.xsd"
/>
I have learned that result of such schema location URL resolution is a file which has a path like the following
"c:\Program%20Files\myApp\spring-beans-4.0.2.RELEASE.jar"
When I started my application from some other directory which didn't contain space character on its path then schema location resolution worked fine. Maybe somebody faced similar problems? Nevertheless I discoverd that classpath protocol works fine in my case
<beans
xsi:schemaLocation="
http://www.springframework.org/schema/beans classpath:org/springframework/beans/factory/xml/spring-beans-2.0.xsd"
/>
Here's what I've been doing to cope with the situation.
I use global imports on a new test class.
import static org.junit.Assert.*;
import static org.mockito.Mockito.*;
import static org.mockito.Matchers.*;
When you are finished writing your test and need to commit, you just CTRL+SHIFT+O to organize the packages. For example, you may just be left with:
import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import static org.mockito.Matchers.anyString;
This allows you to code away without getting 'stuck' trying to find the correct package to import.
If problem persists after trying any of the above solutions, Restart your server once. It worked for me :)
use this code create xml file in drawable folder name:button
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item
android:state_pressed="true"
android:drawable="@drawable/buutton_pressed" />
<item
android:drawable="@drawable/button_image" />
</selector>
and in button xml file
android:background="@drawable/button"
Here is a ready to run source code for random number generator using c taken from this site: http://www.random-number.com/random-number-c/ . The implementation here is more general (a function that gets 3 parameters: min,max and number of random numbers to generate)
#include <time.h>
#include <stdlib.h>
#include <stdio.h>
// the random function
void RandomNumberGenerator(const int nMin, const int nMax, const int nNumOfNumsToGenerate)
{
int nRandonNumber = 0;
for (int i = 0; i < nNumOfNumsToGenerate; i++)
{
nRandonNumber = rand()%(nMax-nMin) + nMin;
printf("%d ", nRandonNumber);
}
printf("\n");
}
void main()
{
srand(time(NULL));
RandomNumberGenerator(1,70,5);
}
Easiest method is
<TD>
<xsl:value-of select="concat(//author/first-name,' ',//author/last-name)"/>
</TD>
when the XML Structure is
<title>The Confidence Man</title>
<author>
<first-name>Herman</first-name>
<last-name>Melville</last-name>
</author>
<price>11.99</price>
Work with:
ALTER TABLE `table` CHANGE `cust_fax` `cust_fax` VARCHAR(60) NULL DEFAULT NULL;
I believe that variable names aren't stored in pyc/pyd/pyo files, so you can not retrieve the exact code lines if you don't have source files.
You're looking for http_build_query()
.
To achieve this we can use this formatter:
DecimalFormat df = new DecimalFormat("#.00");
String resultado = df.format(valor)
or:
DecimalFormat df = new DecimalFormat("0.00"); :
Use this method to get always two decimals:
private static String getTwoDecimals(double value){
DecimalFormat df = new DecimalFormat("0.00");
return df.format(value);
}
Defining this values:
91.32
5.22
11.5
1.2
2.6
Using the method we can get this results:
91.32
5.22
11.50
1.20
2.60
Here's what I've used in past projects:
var myDate = new Date();
var tzo = (myDate.getTimezoneOffset()/60)*(-1);
//get server date value here, the parseInvariant is from MS Ajax, you would need to do something similar on your own
myDate = new Date.parseInvariant('<%=DataCurrentDate%>', 'yyyyMMdd hh:mm:ss');
myDate.setHours(myDate.getHours() + tzo);
//here you would have to get a handle to your span / div to set. again, I'm using MS Ajax's $get
var dateSpn = $get('dataDate');
dateSpn.innerHTML = myDate.localeFormat('F');
Plenty of good solutions exist for finding all the prime factors of not too large numbers. I just wanted to point out, that once you have them, no computation is required to get all the factors.
if N = p_1^{a}*p_{2}^{b}*p_{3}^{c}.....
Then the number of factors is clearly (a+1)(b+1)(c+1)....
since every factor can occur zero up to a times.
e.g. 12 = 2^2*3^1
so it has 3*2 = 6
factors. 1,2,3,4,6,12
======
I originally thought that you just wanted the number of distinct factors. But the same logic applies. You just iterate over the set of numbers corresponding to the possible combinations of exponents.
so int he example above:
00
01
10
11
20
21
gives you the 6
factors.
foreach (new SplFileObject(__FILE__) as $line) {
echo $line;
}
It boils down to:
Class<? extends Serializable> c1 = null;
Class<java.util.Date> d1 = null;
c1 = d1; // compiles
d1 = c1; // wont compile - would require cast to Date
You can see the Class reference c1 could contain a Long instance (since the underlying object at a given time could have been List<Long>
), but obviously cannot be cast to a Date since there is no guarantee that the "unknown" class was Date. It is not typsesafe, so the compiler disallows it.
However, if we introduce some other object, say List (in your example this object is Matcher), then the following becomes true:
List<Class<? extends Serializable>> l1 = null;
List<Class<java.util.Date>> l2 = null;
l1 = l2; // wont compile
l2 = l1; // wont compile
...However, if the type of the List becomes ? extends T instead of T....
List<? extends Class<? extends Serializable>> l1 = null;
List<? extends Class<java.util.Date>> l2 = null;
l1 = l2; // compiles
l2 = l1; // won't compile
I think by changing Matcher<T> to Matcher<? extends T>
, you are basically introducing the scenario similar to assigning l1 = l2;
It's still very confusing having nested wildcards, but hopefully that makes sense as to why it helps to understand generics by looking at how you can assign generic references to each other. It's also further confusing since the compiler is inferring the type of T when you make the function call (you are not explicitly telling it was T is).
You have misunderstood the Python list
object. It is similar to a C pointer-array
. It does not actually "copy" the object which you append to it. Instead, it just store a "pointer" to that object.
Try the following code:
>>> d={}
>>> dlist=[]
>>> for i in xrange(0,3):
d['data']=i
dlist.append(d)
print(d)
{'data': 0}
{'data': 1}
{'data': 2}
>>> print(dlist)
[{'data': 2}, {'data': 2}, {'data': 2}]
So why is print(dlist)
not the same as print(d)
?
The following code shows you the reason:
>>> for i in dlist:
print "the list item point to object:", id(i)
the list item point to object: 47472232
the list item point to object: 47472232
the list item point to object: 47472232
So you can see all the items in the dlist
is actually pointing to the same dict
object.
The real answer to this question will be to append the "copy" of the target item, by using d.copy()
.
>>> dlist=[]
>>> for i in xrange(0,3):
d['data']=i
dlist.append(d.copy())
print(d)
{'data': 0}
{'data': 1}
{'data': 2}
>>> print dlist
[{'data': 0}, {'data': 1}, {'data': 2}]
Try the id()
trick, you can see the list items actually point to completely different objects.
>>> for i in dlist:
print "the list item points to object:", id(i)
the list item points to object: 33861576
the list item points to object: 47472520
the list item points to object: 47458120
In [5]:
import pandas as pd
test = {
383: 3.000000,
663: 1.000000,
726: 1.000000,
737: 9.000000,
833: 8.166667
}
s = pd.Series(test)
s = s[s != 1]
s
Out[0]:
383 3.000000
737 9.000000
833 8.166667
dtype: float64
Use the library EventBus to pass event that could contain your variable back and forth. It's a good solution because it keeps your activities and fragments loosely coupled
You do not need a Javascript code for that...
I think you mean the placeholder attribute. Here is the code:
<input type="text" placeholder="Your descriptive text goes here...">
The default text will be grey-ish and when clicked, it will dissapear!
How about this? I frequently use the CSS Flexible Box Layout to center something.
<div style="display: flex; justify-content: center;">_x000D_
<img src="http://icons.iconarchive.com/icons/rokey/popo-emotions/128/big-smile-icon.png" style="width: 40px; height: 40px;" />_x000D_
</div>
_x000D_
If you only want the position, vp.getCurrentItem()
will give it to you, no need to apply the onPageChangeListener() for that purpose alone.
Not sure why you aren't able to set it. In the source, PUBLIC_URL
takes precedence over homepage
const envPublicUrl = process.env.PUBLIC_URL;
...
const getPublicUrl = appPackageJson =>
envPublicUrl || require(appPackageJson).homepage;
You can try setting breakpoints in their code to see what logic is overriding your environment variable.
Guid guidId = Guid.Parse("xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx");
string guidValue = guidId.ToString("D"); //return with hyphens
I had a requirement to provide a report showing details by month where the date field was formatted as date & time, I simply changed the formatting of the date column to "General" and then used the following formula in a new column,
=CONCATENATE(YEAR(C2),MONTH(C2))
With question 3, this article states that RESTful Services are appropiate in this scenarios:
While SOAP is the way to go when:
^[^_]*_
will match all text up to the first underscore. Replace that with the empty string.
For example, in C#:
resultString = Regex.Replace(subjectString,
@"^ # Match start of string
[^_]* # Match 0 or more characters except underscore
_ # Match the underscore", "", RegexOptions.IgnorePatternWhitespace);
For learning regexes, take a look at http://www.regular-expressions.info
Run your code under a JRockit JVM, then use JRCMD <PID> print_class_summary
This will output all loaded classes, one on each line.
Edit: The original link I answered with is now invalid.The newer URL would be https://developers.google.com/web/tools/chrome-devtools/javascript/add-breakpoints#exceptions as of 2016-11-11.
I realize this question has an answer, but it's no longer accurate. Use the link above ^
(link replaced by edited above) - you can now set it to break on all exceptions or just unhandled ones. (Note that you need to be in the Sources tab to see the button.)
Chrome's also added some other really useful breakpoint capabilities now, such as breaking on DOM changes or network events.
Normally I wouldn't re-answer a question, but I had the same question myself, and I found this now-wrong answer, so I figured I'd put this information in here for people who came along later in searching. :)
For more complex tasks there is expect
( http://en.wikipedia.org/wiki/Expect ).
It basically simulates a user, you can code a script how to react to specific program outputs and related stuff.
This also works in cases like ssh
that prohibits piping passwords to it.
Answer for Elasticsearch inside Docker:
Just stop the docker container. It seems to stop gracefully because it logs:
[INFO ][o.e.n.Node ] [elastic] stopping ...
I think @Evert has the right answer:
plt.scatter(dates,values)
plt.plot(dates, values)
plt.show()
Which is pretty much the same as
plt.plot(dates, values, '-o')
plt.show()
or whatever linestyle you prefer.
In case someone wants a PostgreSQL solution:
select id, name
from customer
order by random()
limit 5;
I have Windows 8.1 and my JDK under "Program Files" as well. What worked for me was replacing the name of the folder by the 8-digit internal MS-DOS name.
-vm
C:/PROGRA~1/Java/jdk1.8.0_40/bin/javaw.exe
I realized what was going on after running this in cmd.exe
CD \
DIR P* /X
It returned...
<DIR> PROGRA~1 Program Files
<DIR> PROGRA~2 Program Files (x86)
So we can find out how to use a path containing spaces
There is a command
svn revert -R .
OR
you can use the --depth=infinity, which is actually same as above:
svn revert --depth=infinity
svn revert
is inherently dangerous, since its entire purpose is to throw away data—namely, your uncommitted changes. Once you've reverted, Subversion provides no way to get back those uncommitted changes
In order to get a notification from the database I wrote a command line script using websocket to check for the latest updated timestamp every second. This ran as an infinite loop on the server. If there is a change all connected clients will can be sent a notification.
Something like this should do the trick
function array_max_key($array) {
$max_key = -1;
$max_val = -1;
foreach ($array as $key => $value) {
if ($value > $max_val) {
$max_key = $key;
$max_val = $value;
}
}
return $max_key;
}
Try to include length > 0 as well.
column1 is not NULL AND column1 <> '' AND length(column1) > 0
Here's something that I just wrote along those lines::
#include <random>
#include <chrono>
#include <thread>
using namespace std;
//==============================================================
// RANDOM BACKOFF TIME
//==============================================================
class backoff_time_t {
public:
random_device rd;
mt19937 mt;
uniform_real_distribution<double> dist;
backoff_time_t() : rd{}, mt{rd()}, dist{0.5, 1.5} {}
double rand() {
return dist(mt);
}
};
thread_local backoff_time_t backoff_time;
int main(int argc, char** argv) {
double x1 = backoff_time.rand();
double x2 = backoff_time.rand();
double x3 = backoff_time.rand();
double x4 = backoff_time.rand();
return 0;
}
~
decimal d = 5.5
;
int i = decimal.ToInt32(d);// you will get i = 5
ref: link text
If I have to change the contents of my options menu I perform it during the onMenuOpened(). This allows me to check the running state at the very moment that the user is accessing the menu.
public boolean onMenuOpened(int featureid, Menu menu)
{
menu.clear();
if (!editable)
{
MenuItem itemAdd = menu.add(0, REASSIGN, Menu.NONE, context.getString(R.string.reassign));
MenuItem itemMod = menu.add(1, EDIT, Menu.NONE, context.getString(R.string.modify));
MenuItem itemDel = menu.add(2, DELETE, Menu.NONE, context.getString(R.string.delete));
itemAdd.setShortcut('0', 'a');
itemMod.setShortcut('1', 'm');
itemDel.setShortcut('2', 'd');
}
else
{
MenuItem itemSave = menu.add(3, SAVE, Menu.NONE, context.getString(R.string.savechanges));
itemSave.setShortcut('0', 'S');
}
return true;
}
Moving an application from one database to another isn't very common, but sooner or later you may find yourself working on another project using a different RDBMS. If you're at home with PDO then there will at least be one thing less to learn at that point.
Apart from that I find the PDO API a little more intuitive, and it feels more truly object oriented. mysqli feels like it is just a procedural API that has been objectified, if you know what I mean. In short, I find PDO easier to work with, but that is of course subjective.
Yes - just do it this way:
WITH DependencedIncidents AS
(
....
),
lalala AS
(
....
)
You don't need to repeat the WITH
keyword
Annotation-driven indicates to Spring that it should scan for annotated beans, and to not just rely on XML bean configuration. Component-scan indicates where to look for those beans.
Here's some doc: http://static.springsource.org/spring/docs/current/spring-framework-reference/html/mvc.html#mvc-config-enable
I figured out how to do this with InjectionTokens (see example below), and if your project was built using the Angular CLI
you can use the environment files found in /environments
for static application wide settings
like an API endpoint, but depending on your project's requirements you will most likely end up using both since environment files are just object literals, while an injectable configuration using InjectionToken
's can use the environment variables and since it's a class can have logic applied to configure it based on other factors in the application, such as initial http request data, subdomain, etc.
Injection Tokens Example
/app/app-config.module.ts
import { NgModule, InjectionToken } from '@angular/core';
import { environment } from '../environments/environment';
export let APP_CONFIG = new InjectionToken<AppConfig>('app.config');
export class AppConfig {
apiEndpoint: string;
}
export const APP_DI_CONFIG: AppConfig = {
apiEndpoint: environment.apiEndpoint
};
@NgModule({
providers: [{
provide: APP_CONFIG,
useValue: APP_DI_CONFIG
}]
})
export class AppConfigModule { }
/app/app.module.ts
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { AppConfigModule } from './app-config.module';
@NgModule({
declarations: [
// ...
],
imports: [
// ...
AppConfigModule
],
bootstrap: [AppComponent]
})
export class AppModule { }
Now you can just DI it into any component, service, etc:
/app/core/auth.service.ts
import { Injectable, Inject } from '@angular/core';
import { Http, Response } from '@angular/http';
import { Router } from '@angular/router';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/catch';
import 'rxjs/add/observable/throw';
import { APP_CONFIG, AppConfig } from '../app-config.module';
import { AuthHttp } from 'angular2-jwt';
@Injectable()
export class AuthService {
constructor(
private http: Http,
private router: Router,
private authHttp: AuthHttp,
@Inject(APP_CONFIG) private config: AppConfig
) { }
/**
* Logs a user into the application.
* @param payload
*/
public login(payload: { username: string, password: string }) {
return this.http
.post(`${this.config.apiEndpoint}/login`, payload)
.map((response: Response) => {
const token = response.json().token;
sessionStorage.setItem('token', token); // TODO: can this be done else where? interceptor
return this.handleResponse(response); // TODO: unset token shouldn't return the token to login
})
.catch(this.handleError);
}
// ...
}
You can then also type check the config using the exported AppConfig.
Incase you are dynamically getting your data e.g When you need data based on the user logged in by their id use consider the following code example for a No Active Record:
$this->db->query('SELECT * FROM my_users_table WHERE id = ?', $this->session->userdata('id'));
return $query->row_array();
This will return a specific row based on your the set session data of user.
Another way to find all View:
SELECT DISTINCT table_name FROM information_schema.TABLES WHERE table_type = 'VIEW'
In response to question edits here is how it works for Anonymous classes
final X parameter = ...; // the final is important
Thread t = new Thread(new Runnable() {
p = parameter;
public void run() {
...
};
t.start();
You have a class that extends Thread (or implements Runnable) and a constructor with the parameters you'd like to pass. Then, when you create the new thread, you have to pass in the arguments, and then start the thread, something like this:
Thread t = new MyThread(args...);
t.start();
Runnable is a much better solution than Thread BTW. So I'd prefer:
public class MyRunnable implements Runnable {
private X parameter;
public MyRunnable(X parameter) {
this.parameter = parameter;
}
public void run() {
}
}
Thread t = new Thread(new MyRunnable(parameter));
t.start();
This answer is basically the same as this similar question: How to pass parameters to a Thread object
The difference is quite simple:
OLTP (Online Transaction Processing)
OLTP is a class of information systems that facilitate and manage transaction-oriented applications. OLTP has also been used to refer to processing in which the system responds immediately to user requests. Online transaction processing applications are high throughput and insert or update-intensive in database management. Some examples of OLTP systems include order entry, retail sales, and financial transaction systems.
OLAP (Online Analytical Processing)
OLAP is part of the broader category of business intelligence, which also encompasses relational database, report writing and data mining. Typical applications of OLAP include business reporting for sales, marketing, management reporting, business process management (BPM), budgeting and forecasting, financial reporting and similar areas.
See more details OLTP and OLAP
The default string representation for a dictionary seems to be just right:
>>> a={3: 'foo', 17: 'bar' }
>>> a
{17: 'bar', 3: 'foo'}
>>> print a
{17: 'bar', 3: 'foo'}
>>> print "a=", a
a= {17: 'bar', 3: 'foo'}
Not sure if you can get at the "variable name", since variables in Python are just labels for values. See this question.
This error is usually encountered when inserting a record in a table where one of the columns is a VARCHAR or CHAR data type and the length of the value being inserted is longer than the length of the column.
I am not satisfied how Microsoft decided to inform with this "dry" response message, without any point of where to look for the answer.
The following might be helpful for RecyclerView with Single Choice.
Three steps to do that, 1) Declare a global integer variable,
private int mSelectedItem = -1;
2) in onBindViewHolder
mRadio.setChecked(position == mSelectedItem);
3) in onClickListener
mSelectedItem = getAdapterPosition();
notifyItemRangeChanged(0, mSingleCheckList.size());
mAdapter.onItemHolderClick(SingleCheckViewHolder.this);
The best way I found was to check the difference between the given date and today:
NSCalendar* calendar = [NSCalendar currentCalendar];
NSDate* now = [NSDate date];
int differenceInDays =
[calendar ordinalityOfUnit:NSCalendarUnitDay inUnit:NSCalendarUnitEra forDate:date] -
[calendar ordinalityOfUnit:NSCalendarUnitDay inUnit:NSCalendarUnitEra forDate:now];
According to Listing 13 of Calendrical Calculations in Apple's Date and Time Programming Guide [NSCalendar ordinalityOfUnit:NSDayCalendarUnit inUnit: NSEraCalendarUnit forDate:myDate] gives you the number of midnights since the start of the era. This way it's easy to check whether the date is yesterday, today, or tomorrow.
switch (differenceInDays) {
case -1:
dayString = @"Yesterday";
break;
case 0:
dayString = @"Today";
break;
case 1:
dayString = @"Tomorrow";
break;
default: {
NSDateFormatter* dayFormatter = [[NSDateFormatter alloc] init];
[dayFormatter setLocale:usLocale];
[dayFormatter setDateFormat:@"dd MMM"];
dayString = [dayFormatter stringFromDate: date];
break;
}
}
The NULLIF function will convert any column value with only whitespace into a NULL value. Works for T-SQL and SQL Server 2008 & up.
SELECT [column_name]
FROM [table_name]
WHERE NULLIF([column_name], '') IS NULL
If you want to add your custom headers to ALL requests, you can change the defaults on $httpProvider to always add this header…
app.config(['$httpProvider', function ($httpProvider) {
$httpProvider.defaults.headers.common = {
'Authorization': 'Basic d2VudHdvcnRobWFuOkNoYW5nZV9tZQ==',
'Accept': 'application/json;odata=verbose'
};
}]);
In my nginx install I found I had to go to:
/opt/nginx/cache
and
sudo rm -rf *
in that directory. If you know the path to your nginx install and can find the cache directory the same may work for you. Be very careful with the rm -rf
command, if you are in the wrong directory you could delete your entire hard drive.
I had same problem and the solution was very simple. Solution : foreign keys declared in table should not set to be not null.
reference : If you specify a SET NULL action, make sure that you have not declared the columns in the child table as NOT NULL. (ref )
You could just have <hr style="border-top: dotted 1px;" />
. That should work.
I am working on an angular js app, andhavecome across a similar issue. What i did was display the image from the db, then created a button to remove or keep the current image. If the user decided to keep the current image, i changed the ng-submit attribute to another function whihc doesnt require image validation, and updated the record in the db without touching the original image path name. The remove image function also changed the ng-submit attribute value back to a function that submits the form and includes image validation and upload. Also a bit of javascript to slide the into view to upload a new image.
Try this . . .
Code snippet:
NSDateComponents *components = [[NSCalendar currentCalendar] components:NSCalendarUnitDay | NSCalendarUnitMonth | NSCalendarUnitYear fromDate:[NSDate date]];
int year = [components year];
int month = [components month];
int day = [components day];
It gives current year, month, date
The use of the deprecated new Buffer()
constructor (i.E. as used by Yarn) can cause deprecation warnings. Therefore one should NOT use the deprecated/unsafe Buffer constructor.
According to the deprecation warning new Buffer()
should be replaced with one of:
Buffer.alloc()
Buffer.allocUnsafe()
or Buffer.from()
Another option in order to avoid this issue would be using the safe-buffer package instead.
You can also try (when using yarn..):
yarn global add yarn
as mentioned here: Link
Another suggestion from the comments (thx to gkiely): self-update
Note: self-update is not available. See policies for enforcing versions within a project
In order to update your version of Yarn, run
curl --compressed -o- -L https://yarnpkg.com/install.sh | bash
You can also install Git Credential Manager for Windows to save Git passwords in Windows credentials manager instead of _netrc
. This is a more secure way to store passwords.
You can also add a UIGestureRecognizer. It does not require you to add an additional element in your view hierarchy, but still provides you will all the nicely written code for handling touch events with a fairly simple interface:
UISwipeGestureRecognizer *swipeRight = [[UISwipeGestureRecognizer alloc]
initWithTarget:self action:@selector(handleSwipe:)];
swipeRight.direction = UISwipeGestureRecognizerDirectionRight;
[imgView_ addGestureRecognizer:swipeRight];
[swipeRight release];
UISwipeGestureRecognizer *swipeLeft = [[UISwipeGestureRecognizer alloc]
initWithTarget:self action:@selector(handleSwipe:)];
swipeLeft.direction = UISwipeGestureRecognizerDirectionLeft;
[imgView_ addGestureRecognizer:swipeLeft];
[swipeLeft release];
.line {_x000D_
width: 53px;_x000D_
height: 0;_x000D_
border: 1px solid #C4C4C4;_x000D_
margin: 3px;_x000D_
display:inline-block;_x000D_
}
_x000D_
<html>_x000D_
<body>_x000D_
<div class="line"></div>_x000D_
<div style="display:inline-block;">OR</div>_x000D_
<div class="line"></div>_x000D_
</body>_x000D_
</html>
_x000D_
Modifying the location of window might cause some issue especially when you have a persistent connection like websocket. So I always resort to good old iframe solution.
HTML
<input type="button" onclick="downloadButtonClicked()" value="Download"/>
...
...
...
<iframe style="display:none;" name="hiddenIframe" id="hiddenIframe"></iframe>
Javascript
function downloadButtonClicked() {
// Simulate a link click
var url = 'your_download_url_here';
var elem = document.createElement('a');
elem.href = url;
elem.target = 'hiddenIframe';
elem.click();
}
The following bash code will pass $file to command where $file will represent every file in /dir
for file in /dir/*
do
cmd [option] "$file" >> results.out
done
Example
el@defiant ~/foo $ touch foo.txt bar.txt baz.txt
el@defiant ~/foo $ for i in *.txt; do echo "hello $i"; done
hello bar.txt
hello baz.txt
hello foo.txt
instead of newdata you are using newdate in your predict code, verify once. and just use Coupon$estimate <- predict(model, Coupon)
It will work.
This is for Android, testing for IPv4
and IPv6
Note: the commonly used InetAddressUtils
is deprecated. Use new InetAddress
classes
public static Boolean isIPv4Address(String address) {
if (address.isEmpty()) {
return false;
}
try {
Object res = InetAddress.getByName(address);
return res instanceof Inet4Address || res instanceof Inet6Address;
} catch (final UnknownHostException exception) {
return false;
}
}
Why are you using array
and bothering with the first question of number of wanted numbers ?
Prefer an ArrayList
associated with a corresponding comparator:
List numbers = new Arraylist();
//add read numbers (int (with autoboxing if jdk>=5) or Integer directly) into it
//Initialize the associated comparator reversing order. (since Integer implements Comparable)
Comparator comparator = Collections.reverseOrder();
//Sort the list
Collections.sort(numbers,comparator);
I know this is an old question.
Here's another option - attending to different platform requirements - Source
<link rel='shortcut icon' type='image/vnd.microsoft.icon' href='/favicon.ico'> <!-- IE -->
<link rel='apple-touch-icon' type='image/png' href='/icon.57.png'> <!-- iPhone -->
<link rel='apple-touch-icon' type='image/png' sizes='72x72' href='/icon.72.png'> <!-- iPad -->
<link rel='apple-touch-icon' type='image/png' sizes='114x114' href='/icon.114.png'> <!-- iPhone4 -->
<link rel='icon' type='image/png' href='/icon.114.png'> <!-- Opera Speed Dial, at least 144×114 px -->
This is the broadest approach I have found so far.
Ultimately the decision depends on your own needs. Ask yourself, who is your target audience?
UPDATE May 27, 2018: As expected, time goes by and things change. But there's good news too. I found a tool called Real Favicon Generator that generates all the required lines for the icon to work on all modern browsers and platforms. It doesn't handle backwards compatibility though.
If you don't want to change the value of the original variable after passing it into a function, the function should be constructed with a "pass by value" parameter.
Then the function will have ONLY the value but not the address of the passed in variable. Without the variable's address, the code inside the function cannot change the variable value as seen from the outside of the function.
But if you want to give the function the ability to change the value of the variable as seen from the outside, you need to use pass by reference. As both the value and the address (reference) are passed in and available inside the function.
The real problem: How to get the difference of two sets?
The fastest way I've found is to convert the sets to dictionaries first, then diff 'em. Here's a generic approach:
static IEnumerable<T> DictionaryDiff<K, T>(Dictionary<K, T> d1, Dictionary<K, T> d2)
{
return from x in d1 where !d2.ContainsKey(x.Key) select x.Value;
}
Then you can do something like this:
static public IEnumerable<PropertyInfo> PropertyDiff(Type t1, Type t2)
{
var d1 = t1.GetProperties().ToDictionary(x => x.Name);
var d2 = t2.GetProperties().ToDictionary(x => x.Name);
return DictionaryDiff(d1, d2);
}
An example:
log4j.rootLogger=ERROR, logfile
log4j.appender.logfile=org.apache.log4j.DailyRollingFileAppender
log4j.appender.logfile.datePattern='-'dd'.log'
log4j.appender.logfile.File=log/radius-prod.log
log4j.appender.logfile.layout=org.apache.log4j.PatternLayout
log4j.appender.logfile.layout.ConversionPattern=%-6r %d{ISO8601} %-5p %40.40c %x - %m\n
log4j.logger.foo.bar.Baz=DEBUG, myappender
log4j.additivity.foo.bar.Baz=false
log4j.appender.myappender=org.apache.log4j.DailyRollingFileAppender
log4j.appender.myappender.datePattern='-'dd'.log'
log4j.appender.myappender.File=log/access-ext-dmz-prod.log
log4j.appender.myappender.layout=org.apache.log4j.PatternLayout
log4j.appender.myappender.layout.ConversionPattern=%-6r %d{ISO8601} %-5p %40.40c %x - %m\n
Setting Activity
’s title from a Fragment
messes up responsibility levels. Fragment
is contained within an Activity
, so this is the Activity
, which should set its own title according to the type of the Fragment
for example.
Suppose you have an interface:
interface TopLevelFragment
{
String getTitle();
}
The Fragment
s which can influence the Activity
’s title then implement this interface. While in the hosting activity you write:
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
FragmentManager fm = getFragmentManager();
fm.beginTransaction().add(0, new LoginFragment(), "login").commit();
}
@Override
public void onAttachFragment(Fragment fragment)
{
super.onAttachFragment(fragment);
if (fragment instanceof TopLevelFragment)
setTitle(((TopLevelFragment) fragment).getTitle());
}
In this manner Activity
is always in control what title to use, even if several TopLevelFragment
s are combined, which is quite possible on a tablet.
Tip : To make Auto size work , the call to sheet.autoSizeColumn(columnNumber)
should be made after populating the data into the excel.
Calling the method before populating the data, will have no effect.
In CakePHP 3 $this->here
will be deprecated. The actual way is using this method:
Router::url($this->request->getRequestTarget())
Try to update npm,It works for me
[sudo] npm install -g npm
What we have in our table:-
Primary Key
Event type (e.g. "UPDATED", "APPROVED")
Description ("Frisbar was added to blong")
User Id
User Id of second authoriser
Amount
Date/time
Generic Id
Table Name
The generic id points at a row in the table that was updated and the table name is the name of that table as a string. Not a good DB design, but very usable. All our tables have a single surrogate key column so this works well.
orderby Pipe in Angular JS will support but Angular (higher versions) will not support . Please find he details discussed to increase performance speed its obsolete.
https://angular.io/guide/pipes#appendix-no-filterpipe-or-orderbypipe
Use a single formatted text column[1] for storing the tags and use a capable full text search engine to index this. Else you will run into scaling problems when trying to implement boolean queries.
If you need details about the tags you have, you can either keep track of it in a incrementally maintained table or run a batch job to extract the information.
[1] Some RDBMS even provide a native array type which might be even better suited for storage by not needing a parsing step, but might cause problems with the full text search.
The null character is '\0'
, not '/0'
.
while (*(forward++) != '\0')
Note that your pod specs will remain, and are located at ~/.cocoapods/ . This directory may also need to be removed if you want a completely fresh install.
They can be removed using pod spec remove SPEC_NAME
then pod setup
It may help to do pod spec remove master
then pod setup
If you want to disable ctrl+f5 , ctrl+R , f5 ,backspace then you can use this simple code. This code is working in Mozila as well as Chrome . Add this code inside your body tag:
<body onkeydown="return (event.keyCode == 154)">
document.getElementsByTagName("html")[0].classList.add('theme-dark');
document.getElementsByTagName("html")[0].classList.remove('theme-dark')
document.getElementsByTagName("html")[0].classList.toggle('theme-dark')
Try the strict equality comparison:
if(1 === true)
document.write("oh!!! that's true"); //**this is not displayed**
The ==
operator does conversion from one type to another, the ===
operator doesn't.
Instead of playing with tags, I took different approach. Made delegate for my subclass of UITableViewCell(OptionButtonsCell) and added an indexPath var. From my button in storyboard I connected @IBAction to the OptionButtonsCell and there I send delegate method with the right indexPath to anyone interested. In cell for index path I set current indexPath and it works :)
Let the code speak for itself:
Swift 3 Xcode 8
OptionButtonsTableViewCell.swift
import UIKit
protocol OptionButtonsDelegate{
func closeFriendsTapped(at index:IndexPath)
}
class OptionButtonsTableViewCell: UITableViewCell {
var delegate:OptionButtonsDelegate!
@IBOutlet weak var closeFriendsBtn: UIButton!
var indexPath:IndexPath!
@IBAction func closeFriendsAction(_ sender: UIButton) {
self.delegate?.closeFriendsTapped(at: indexPath)
}
}
MyTableViewController.swift
class MyTableViewController: UIViewController, UITableViewDelegate, UITableViewDataSource, OptionButtonsDelegate {...
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "optionCell") as! OptionButtonsTableViewCell
cell.delegate = self
cell.indexPath = indexPath
return cell
}
func closeFriendsTapped(at index: IndexPath) {
print("button tapped at index:\(index)")
}
Suppose you have following lines of code
MyUrl = "www.google.com" #Your url goes here
urllib.urlretrieve(MyUrl)
If you are receiving following error message
AttributeError: module 'urllib' has no attribute 'urlretrieve'
Then you should try following code to fix the issue:
import urllib.request
MyUrl = "www.google.com" #Your url goes here
urllib.request.urlretrieve(MyUrl)
Use convert
from http://www.imagemagick.org. (Readily supplied as a package in most Linux distributions.)
As dfsq said i just had to use removeClass("hide")
instead of toggle()
You've probably miss-typed something above that bit of code or created your own class called IPAddress. If you're using the .net one, that function should be available.
Have you tried using System.Net.IPAddress just in case?
System.Net.IPAddress ipaddress = System.Net.IPAddress.Parse("127.0.0.1"); //127.0.0.1 as an example
The docs on Microsoft's site have a complete example which works fine on my machine.
I know there are several answers to this post already, but I haven't seen one wherein there are multiple properties and they are within an array. And this solution by the way is for ES6.
For illustration, let's say we have an array named person with objects inside:
let Person = [{id:1, Name: "John"}, {id:2, Name: "Susan"}, {id:3, Name: "Jet"}]
So, you can add a property with corresponding value. Let's say we want to add a Language with a default value of EN.
Person.map((obj)=>({...obj,['Language']:"EN"}))
The Person array now would become like this:
Person = [{id:1, Name: "John", Language:"EN"},
{id:2, Name: "Susan", Language:"EN"}, {id:3, Name: "Jet", Language:"EN"}]
Frank Heikens answer will only update database ownership. Often, you also want to update ownership of contained objects (including tables). Starting with Postgres 8.2, REASSIGN OWNED is available to simplify this task.
IMPORTANT EDIT!
Never use REASSIGN OWNED
when the original role is postgres
, this could damage your entire DB instance. The command will update all objects with a new owner, including system resources (postgres0, postgres1, etc.)
First, connect to admin database and update DB ownership:
psql
postgres=# REASSIGN OWNED BY old_name TO new_name;
This is a global equivalent of ALTER DATABASE
command provided in Frank's answer, but instead of updating a particular DB, it change ownership of all DBs owned by 'old_name'.
The next step is to update tables ownership for each database:
psql old_name_db
old_name_db=# REASSIGN OWNED BY old_name TO new_name;
This must be performed on each DB owned by 'old_name'. The command will update ownership of all tables in the DB.
The current (as of version 0.20) method for changing column names after a groupby operation is to chain the rename
method. See this deprecation note in the documentation for more detail.
This is the first result in google and although the top answer works it does not really answer the question. There is a better answer here and a long discussion on github about the full functionality of passing dictionaries to the agg
method.
These answers unfortunately do not exist in the documentation but the general format for grouping, aggregating and then renaming columns uses a dictionary of dictionaries. The keys to the outer dictionary are column names that are to be aggregated. The inner dictionaries have keys that the new column names with values as the aggregating function.
Before we get there, let's create a four column DataFrame.
df = pd.DataFrame({'A' : list('wwwwxxxx'),
'B':list('yyzzyyzz'),
'C':np.random.rand(8),
'D':np.random.rand(8)})
A B C D
0 w y 0.643784 0.828486
1 w y 0.308682 0.994078
2 w z 0.518000 0.725663
3 w z 0.486656 0.259547
4 x y 0.089913 0.238452
5 x y 0.688177 0.753107
6 x z 0.955035 0.462677
7 x z 0.892066 0.368850
Let's say we want to group by columns A, B
and aggregate column C
with mean
and median
and aggregate column D
with max
. The following code would do this.
df.groupby(['A', 'B']).agg({'C':['mean', 'median'], 'D':'max'})
D C
max mean median
A B
w y 0.994078 0.476233 0.476233
z 0.725663 0.502328 0.502328
x y 0.753107 0.389045 0.389045
z 0.462677 0.923551 0.923551
This returns a DataFrame with a hierarchical index. The original question asked about renaming the columns in the same step. This is possible using a dictionary of dictionaries:
df.groupby(['A', 'B']).agg({'C':{'C_mean': 'mean', 'C_median': 'median'},
'D':{'D_max': 'max'}})
D C
D_max C_mean C_median
A B
w y 0.994078 0.476233 0.476233
z 0.725663 0.502328 0.502328
x y 0.753107 0.389045 0.389045
z 0.462677 0.923551 0.923551
This renames the columns all in one go but still leaves the hierarchical index which the top level can be dropped with df.columns = df.columns.droplevel(0)
.
Here is a simpler method (hack) that gives you back the setdefaultencoding()
function that was deleted from sys
:
import sys
# sys.setdefaultencoding() does not exist, here!
reload(sys) # Reload does the trick!
sys.setdefaultencoding('UTF8')
(Note for Python 3.4+: reload()
is in the importlib
library.)
This is not a safe thing to do, though: this is obviously a hack, since sys.setdefaultencoding()
is purposely removed from sys
when Python starts. Reenabling it and changing the default encoding can break code that relies on ASCII being the default (this code can be third-party, which would generally make fixing it impossible or dangerous).
Dart lang:
import 'dart:math' show cos, sqrt, asin;
double calculateDistance(LatLng l1, LatLng l2) {
const p = 0.017453292519943295;
final a = 0.5 -
cos((l2.latitude - l1.latitude) * p) / 2 +
cos(l1.latitude * p) *
cos(l2.latitude * p) *
(1 - cos((l2.longitude - l1.longitude) * p)) /
2;
return 12742 * asin(sqrt(a));
}
Actually you don't even need the block:
Dir.chdir 'C:/Users/name/Music'
music = Dir['C:/Users/name/Music/*.{mp3, MP3}']
puts 'what would you like to call the playlist?'
playlist_name = gets.chomp + '.m3u'
File.open(playlist_name, 'w').puts(music)
There is something wrong with your code.
position : absolute
makes the element on top irrespective of other elements in the same page. But the position not relative to the scroll
This can be solved with position : fixed
This property will make the element position fixed and still relative to the scroll.
Or
You can check it out Here
This should work (untested, based on JavaDoc):
DecimalFormat formatter = (DecimalFormat) NumberFormat.getInstance(Locale.US);
DecimalFormatSymbols symbols = formatter.getDecimalFormatSymbols();
symbols.setGroupingSeparator(' ');
formatter.setDecimalFormatSymbols(symbols);
System.out.println(formatter.format(bd.longValue()));
According to the JavaDoc, the cast in the first line should be save for most locales.
Try this for multiple CSS styles:
$(this).css({
"background-color": 'red',
"color" : "white"
});
Can this code be simplified in one if test instead two?
nil
and ''
are different values. If you need to test that s
is neither, IMO you should just compare against both, because it makes your intent the most clear.
That and a few alternatives, with their generated bytecode:
if not foo or foo == '' then end
GETGLOBAL 0 -1 ; foo
TEST 0 0 0
JMP 3 ; to 7
GETGLOBAL 0 -1 ; foo
EQ 0 0 -2 ; - ""
JMP 0 ; to 7
if foo == nil or foo == '' then end
GETGLOBAL 0 -1 ; foo
EQ 1 0 -2 ; - nil
JMP 3 ; to 7
GETGLOBAL 0 -1 ; foo
EQ 0 0 -3 ; - ""
JMP 0 ; to 7
if (foo or '') == '' then end
GETGLOBAL 0 -1 ; foo
TEST 0 0 1
JMP 1 ; to 5
LOADK 0 -2 ; ""
EQ 0 0 -2 ; - ""
JMP 0 ; to 7
The second is fastest in Lua 5.1 and 5.2 (on my machine anyway), but difference is tiny. I'd go with the first for clarity's sake.
When checking for a function, one must always use typeof
.
Here's the difference:
var f = Object.create(Function);
console.log(f instanceof Function); //=> true
console.log(typeof f === 'function'); //=> false
f(); // throws TypeError: f is not a function
This is why one must never use instanceof
to check for a function.
I think that "\r\n" should work fine
Earlier responders have answered the question but have not provided the information the title led me to expect. I had a method that returned a one character string but I wanted a character which I could convert to hexadecimal. The following code demonstrates what I thought I would find in the hope it is helpful to others.
string s = "\ta£\x0394\x221A"; // tab; lower case a; pound sign; Greek delta;
// square root
Debug.Print(s);
char c = s[0];
int i = (int)c;
string x = i.ToString("X");
c = s[1];
i = (int)c;
x = i.ToString("X");
Debug.Print(c.ToString() + " " + i.ToString() + " " + x);
c = s[2];
i = (int)c;
x = i.ToString("X");
Debug.Print(c.ToString() + " " + i.ToString() + " " + x);
c = s[3];
i = (int)c;
x = i.ToString("X");
Debug.Print(c.ToString() + " " + i.ToString() + " " + x);
c = s[4];
i = (int)c;
x = i.ToString("X");
Debug.Print(c.ToString() + " " + i.ToString() + " " + x);
The above code outputs the following to the immediate window:
a£?v
a 97 61
£ 163 A3
? 916 394
v 8730 221A
add $row = mysql_fetch_object($result);
after your mysql_query();
your html <img src="<?php echo $row->dvdimage; ?>" width="175" height="200" />
For Eclipse: menu bar-> window -> show view then find "debug" option if not in list then select other ...
new window will open and then search using keyword "debug" -> select debug from list
it will added near console tab. use debug tab to terminate and remove previous executions. ( right clicking on executing process will show you many option including terminate)
This will give you the second row of each group (zero indexed, nth(0) is the same as first()):
df.groupby('id').nth(1)
Documentation: http://pandas.pydata.org/pandas-docs/stable/groupby.html#taking-the-nth-row-of-each-group
Use Css Selector for this, or learn more about Css Selector just go here
https://www.w3schools.com/cssref/css_selectors.asp
#main_text > .title {
/* Style goes here */
}
#main_text .title {
/* Style goes here */
}
Now, there are plenty of example of me answering questions with essays on why following validation rules are important. I've also said that sometimes you just have to be a rebel and break the rules, and document the reasons.
You can see in this example that framesets do work in HTML5 still. I had to download the code and add an HTML5 doctype at the top, however. But the frameset element was still recognized, and the desired result was achieved.
Therefore, knowing that using framesets is completely absurd, and knowing that you have to use this as dictated by your professor/teacher, you could just deal with the single validation error in the W3C validator and use both the HTML5 video element as well as the deprecated frameset element.
<!DOCTYPE html>
<html>
<head>
</head>
<!-- frameset is deprecated in html5, but it still works. -->
<frameset framespacing="0" rows="150,*" frameborder="0" noresize>
<frame name="top" src="http://www.npscripts.com/framer/demo-top.html" target="top">
<frame name="main" src="http://www.google.com" target="main">
</frameset>
</html>
Keep in mind that if it's a project for school, it's most likely not going to be something that will be around in a year or two once the browser vendors remove frameset support for HTML5 completely. Just know that you are right and just do what your teacher/professor asks just to get the grade :)
UPDATE:
The toplevel parent doc uses XHTML and the frame uses HTML5. The validator did not complain about the frameset being illegal, and it didn't complain about the video element.
index.php:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Frameset//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-frameset.dtd">
<html>
<head>
</head>
<frameset framespacing="0" rows="150,*" frameborder="0" noresize>
<frame name="top" src="http://www.npscripts.com/framer/demo-top.html" target="top">
<frame name="main" src="video.html" target="main">
</frameset>
</html>
video.html:
<!doctype html>
<html>
<head>
</head>
<body>
<div id="player-container">
<div class="arrow"></div>
<div class="player">
<video id="vid1" width="480" height="267"
poster="http://cdn.kaltura.org/apis/html5lib/kplayer-examples/media/bbb480.jpg"
durationHint="33" controls>
<source src="http://cdn.kaltura.org/apis/html5lib/kplayer-examples/media/bbb_trailer_iphone.m4v" />
<source src="http://cdn.kaltura.org/apis/html5lib/kplayer-examples/media/bbb400p.ogv" />
</video>
</div>
</body>
</html>
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.
Check under project properties -> deployment assembly if jar file are under deployed path- WEB-INF/lib if not use add button and add jar under WEB-INF/lib
sometime eclipse (in my case Juno Service Release 2 ) was not doing it for me so i did manually. this worked for me.
In this case background-color:rgba(0,0,0,0.5);
is the best way.
For example: background-color:rgba(0,0,0,opacity option);
For MultiIndex you can extract its subindex using
df['si_name'] = R.index.get_level_values('si_name')
where si_name
is the name of the subindex.
Although you cannot use different sized slides in one PowerPoint file, for the actual presentation you can link several different files together to create a presentation that has different slide sizes.
The process to do so is as follows:
Reference to Office Support Page where this solution was first posted. https://support.office.com/en-us/article/can-i-use-portrait-and-landscape-slide-orientation-in-the-same-presentation-d8c21781-1fb6-4406-bcd6-25cfac37b5d6?ocmsassetID=HA010099556&CorrelationId=1ac4e97f-bfe6-47b1-bab6-5783e78d126d&ui=en-US&rs=en-US&ad=US
If your input file is in.txt, you can use freopen to set stdin file as in.txt
freopen("in.txt","r",stdin);
if you want to do the same with your output:
freopen("out.txt","w",stdout);
this will work for std::cin (if using c++), printf, etc...
This will also help you in debugging your code in clion, vscode
private static boolean isValidFolderPath(String path) {
File file = new File(path);
if (!file.exists()) {
return file.mkdirs();
}
return true;
}
@IBOutlet weak var button: UIButton!
...
I think for radius just enough this parameter:
button.layer.cornerRadius = 5
sed -n 's/.*/&,/;H;$x;$s/,\n/,/g;$s/\n\(.*\)/\1/;$s/\(.*\),/\1/;$p'
Here's my solution, which just iterates over the string until n
matches have been found:
String.prototype.nthIndexOf = function(searchElement, n, fromElement) {
n = n || 0;
fromElement = fromElement || 0;
while (n > 0) {
fromElement = this.indexOf(searchElement, fromElement);
if (fromElement < 0) {
return -1;
}
--n;
++fromElement;
}
return fromElement - 1;
};
var string = "XYZ 123 ABC 456 ABC 789 ABC";
console.log(string.nthIndexOf('ABC', 2));
>> 16
Assuming that you only want to read a single line, then use LINE_MAX
, which is defined in <limits.h>
:
#include <stdio.h>
#include <limits.h>
...
char line[LINE_MAX];
...
if (fgets(line, LINE_MAX, stdin) != NULL) {
...
}
...
If you take a look at the official docs, you'll see right below append
, extend
. That's what your looking for.
There's also itertools.chain
if you are more interested in efficient iteration than ending up with a fully populated data structure.
The new recommended way to do this is to use the setNames
function. See
?setNames
. Since this creates a new copy of the data.frame
, be sure to assign the result to the original data.frame
, if that is your intention.
data_frame <- setNames(data_frame, c("premium","change","newprice"))
Newer versions of R will give you warning if you use colnames
in some of the ways suggested by earlier answers.
If this were a data.table
instead, you could use the data.table
function setnames
, which can modify specific column names or a single column name by reference:
setnames(data_table, "old-name", "new-name")
I got similar error after deleting a subproject, removed
"*compile project(path: ':MySubProject', configuration: 'android-endpoints')*"
in build.gradle
(dependencies) under Gradle Scripts
you're comparing the result against a string ('false') not the built-in negative constant (false)
just use
if(ValidateForm() == false) {
or better yet
if(!ValidateForm()) {
also why are you calling validateForm twice?
Use the Ant war task
You can remove "JavaAppletPlugin.plugin" found in Spotlight or Finder, then re-install downloaded Java 8.
This will simply solve your problem.
int days = DateTime.DaysInMonth(DateTime.Now.Year, DateTime.Now.Month);
if you want to find days in this year and present month then this is best
If any doubt in this code, please ask your questions(Here for gmail Port number is 587)
// code to Send Mail
// Add following Lines in your web.config file
// <system.net>
// <mailSettings>
// <smtp>
// <network host="smtp.gmail.com" port="587" userName="[email protected]" password="yyy" defaultCredentials="false"/>
// </smtp>
// </mailSettings>
// </system.net>
// Add below lines in your config file inside appsetting tag <appsetting></appsetting>
// <add key="emailFromAddress" value="[email protected]"/>
// <add key="emailToAddress" value="[email protected]"/>
// <add key="EmailSsl" value="true"/>
// Namespace Used
using System.Net.Mail;
public static bool SendingMail(string subject, string content)
{
// getting the values from config file through c#
string fromEmail = ConfigurationSettings.AppSettings["emailFromAddress"];
string mailid = ConfigurationSettings.AppSettings["emailToAddress"];
bool useSSL;
if (ConfigurationSettings.AppSettings["EmailSsl"] == "true")
{
useSSL = true;
}
else
{
useSSL = false;
}
SmtpClient emailClient;
MailMessage message;
message = new MailMessage();
message.From = new MailAddress(fromEmail);
message.ReplyTo = new MailAddress(fromEmail);
if (SetMailAddressCollection(message.To, mailid))
{
message.Subject = subject;
message.Body = content;
message.IsBodyHtml = true;
emailClient = new SmtpClient();
emailClient.EnableSsl = useSSL;
emailClient.Send(message);
}
return true;
}
// if you are sending mail in group
private static bool SetMailAddressCollection(MailAddressCollection toAddresses, string mailId)
{
bool successfulAddressCreation = true;
toAddresses.Add(new MailAddress(mailId));
return successfulAddressCreation;
}
Here is a pretty simple socket program. This is about as simple as sockets get.
for the client program(CPU 1)
import socket
s = socket.socket()
host = '111.111.0.11' # needs to be in quote
port = 1247
s.connect((host, port))
print s.recv(1024)
inpt = raw_input('type anything and click enter... ')
s.send(inpt)
print "the message has been sent"
You have to replace the 111.111.0.11 in line 4 with the IP number found in the second computers network settings.
For the server program(CPU 2)
import socket
s = socket.socket()
host = socket.gethostname()
port = 1247
s.bind((host,port))
s.listen(5)
while True:
c, addr = s.accept()
print("Connection accepted from " + repr(addr[1]))
c.send("Server approved connection\n")
print repr(addr[1]) + ": " + c.recv(1026)
c.close()
Run the server program and then the client one.
If you have installed postgres via the Windows installer you can start it in Services like so:
Figured it out for myself in the end. It is simple, I was just missing the ** operator to unpack the dictionary
So my example becomes:
d = dict(p1=1, p2=2)
def f2(p1,p2):
print p1, p2
f2(**d)
From the PHP Manual:
Warning This extension was deprecated in PHP 5.5.0, and it was removed in PHP 7.0.0. Instead, the MySQLi or PDO_MySQL extension should be used. See also MySQL: choosing an API guide. Alternatives to this function include:
mysqli_connect()
PDO::__construct()
use MySQLi
or PDO
<?php
$con = mysqli_connect('localhost', 'username', 'password', 'database');
I know question is specific to MVC4. But since we are way past MVC4 and if anyone looking for ASP.NET Core, you can use:
<partial name="_My_Partial" model="Model.MyInfo" />
A year or so has passed since the question was asked, but I wasn't satisfied with the answers. I fiddled for a while, and here is a code that:
Live demo here: http://jsbin.com/bagaro/1/edit?html,output.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Scrollabe table</title>
<!-- Substantially simplified and improved version of the table on
http://www.cssbakery.com/2010/12/css-scrolling-tables-with-fixed.html -->
<script>
if ('ontouchstart' in window || (window.DocumentTouch && document instanceof DocumentTouch)) {
document.documentElement.className += ' touchScreen';
}
</script>
<style>
/* BASICS: */
* {
padding: 0;
margin: 0;
box-sizing: border-box; /* in case block elements are used inside table cells */
}
html {
font-size: 62.5%; /* standardizes older IEs */
}
body {
font: normal 1.3em Verdana; /* = 13px */
}
table {
border-collapse: collapse;
table-layout: fixed;
empty-cells: show;
}
td {
border: 1px solid black;
padding: 4px;
}
/* SCROLL TABLE ESSENTIALS (+ SOME ADDITIONAL CSS): */
div#scrollTableContainer {
width: 617px;
margin: 40px; /* just for presentation purposes */
border: 1px solid black;
}
.touchScreen div#scrollTableContainer {
width: 600px; /* touch devices do not form scrollbars (= 17 px wide) */
}
#tHeadContainer {
background: #CC3600;
color: white;
font-weight: bold;
}
#tBodyContainer {
height: 240px;
overflow-y: scroll;
}
.touchScreen #tBodyContainer {
-webkit-overflow-scrolling: touch; /* smooths scrolling on touch screens */
}
/* FINER LAYOUT MATTERS: */
tr:first-child td {
border-top: 0;
}
#tBody tr.lastRow td {
border-bottom: 0;
}
td:first-child {
min-width: 108px; /* Firefox needs min- and max-widths */
max-width: 108px;
border-left: 0;
}
td:first-child + td {
min-width: 125px;
max-width: 125px;
}
td:first-child + td + td {
min-width: 90px;
max-width: 90px;
}
td:first-child + td + td + td {
min-width: 95px;
max-width: 95px;
}
td:first-child + td + td + td + td {
width: 180px; /* here, Firefox messes up with only min- and max-widths */
border-right: 0;
}
/* AND SOME CSS TO INFORM TOUCH SCREEN USERS: */
p#touchDeviceText {
display: none;
}
.touchScreen p#touchDeviceText {
display: block;
}
</style>
</head>
<body>
<p id="touchDeviceText">This table is scrollable</p>
<div id="scrollTableContainer">
<div id="tHeadContainer">
<table id="tHead">
<tr>
<td>Name</td>
<td>Operator</td>
<td>Began operation</td>
<td>Tonnage</td>
<td>Status</td>
</tr>
</table>
</div><!-- tHeadContainer -->
<div id="tBodyContainer">
<table id="tBody">
<tr>
<td>Seabourne Sun</td>
<td>Seabourn Cruise Line</td>
<td>1988</td>
<td>?</td>
<td>Ended service in 2002, currently operating as Prinsendam</td>
</tr>
<tr>
<td>Adventures of the Seas</td>
<td>Royal Caribbean International</td>
<td>2001</td>
<td>138,000</td>
<td>Operating</td>
</tr>
<tr>
<td>Oceanic Independence</td>
<td>American Hawaiian Cruises / American Global Line</td>
<td>1974</td>
<td>23,719</td>
<td>Named formerly (1951-1974) and subsequently renamed (1982-2006) the Independence, renamed the Oceanic (2006), sold for scrap in 2008 but remains in mothballs</td>
</tr>
<tr>
<td>Cunard Ambassador</td>
<td>Cunard Line</td>
<td>1972</td>
<td>14,160</td>
<td>Burnt 1974, rebuilt into a livestock carrier, renamed Linda Clausen, later Procyon, Raslan. Scrapped 1984 after a second fire.</td>
</tr>
<tr>
<td>Aegean Beauty</td>
<td>Voyages to Antiquity</td>
<td>1973</td>
<td>11,563</td>
<td>Formerly Aegean Dolphin and Aegean I. Operating</td>
</tr>
<tr>
<td>Serenade of the Seas</td>
<td>Royal Caribbean International</td>
<td>2003</td>
<td>90,090</td>
<td>Operating</td>
</tr>
<tr>
<td>Queen Elizabeth 2</td>
<td>Cunard Line</td>
<td>1969</td>
<td>70,327</td>
<td>Left fleet in November 2008</td>
</tr>
<tr>
<td>National Geographic Endeavour</td>
<td>Lindblad Expeditions</td>
<td>1996</td>
<td></td>
<td>Operating, also known as Endeavour</td>
</tr>
<tr class="lastRow">
<td>Liberty of the Seas</td>
<td>Royal Caribbean International</td>
<td>2007</td>
<td>154,407</td>
<td>Operating</td>
</tr>
</table>
</div><!-- tBodyContainer -->
</div><!-- scrollTableContainer -->
</body>
</html>
I like user64141's answer but found that it could be more generalized. Here's my take:
public abstract class ExpectedThrowableAsserter implements Runnable {
private final Class<? extends Throwable> throwableClass;
private final String expectedExceptionMessage;
protected ExpectedThrowableAsserter(Class<? extends Throwable> throwableClass, String expectedExceptionMessage) {
this.throwableClass = throwableClass;
this.expectedExceptionMessage = expectedExceptionMessage;
}
public final void run() {
try {
expectException();
} catch (Throwable e) {
assertTrue(String.format("Caught unexpected %s", e.getClass().getSimpleName()), throwableClass.isInstance(e));
assertEquals(String.format("%s caught, but unexpected message", throwableClass.getSimpleName()), expectedExceptionMessage, e.getMessage());
return;
}
fail(String.format("Expected %s, but no exception was thrown.", throwableClass.getSimpleName()));
}
protected abstract void expectException();
}
Note that leaving the "fail" statement within the try block causes the related assertion exception to be caught; using return within the catch statement prevents this.
display:flex
method seems to be today the most solid and easiest to set in action.
Wrote Mar 17 '15 at 17:06:
for later(nowdays ) browser , display:flex
and pseudo-elements
makes it easy to draw without extra markup.
border-style
, box-shadow
and even background
helps too for the makeup if you need it fancy or ugly.
h1 {margin-top:50px;
display:flex;
background:linear-gradient(to left,gray,lightgray,white,yellow,turquoise);;
}
h1:before, h1:after {
color:white;
content:'';
flex:1;
border-bottom:groove 2px;
margin:auto 0.25em;
box-shadow: 0 -1px ;/* ou 0 1px si border-style:ridge */
}
_x000D_
<h1>side lines via flex</h1>
_x000D_
ressource (added 09/2020):
https://css-tricks.com/snippets/css/a-guide-to-flexbox/ (see flex
/flex-grow
used here)
https://css-tricks.com/the-peculiar-magic-of-flexbox-and-auto-margins/ (margin:auto 0.25em;
used here )
Let's combine everything we learned here into one simple function (imageDimensions()
). It uses promises.
// helper to get dimensions of an image
const imageDimensions = file =>
new Promise((resolve, reject) => {
const img = new Image()
// the following handler will fire after the successful loading of the image
img.onload = () => {
const { naturalWidth: width, naturalHeight: height } = img
resolve({ width, height })
}
// and this handler will fire if there was an error with the image (like if it's not really an image or a corrupted one)
img.onerror = () => {
reject('There was some problem with the image.')
}
img.src = URL.createObjectURL(file)
})
// here's how to use the helper
const getInfo = async ({ target: { files } }) => {
const [file] = files
try {
const dimensions = await imageDimensions(file)
console.info(dimensions)
} catch(error) {
console.error(error)
}
}
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/babel-standalone/7.0.0-beta.3/babel.min.js"></script>
Select an image:
<input
type="file"
onchange="getInfo(event)"
/>
<br />
<small>It works offline.</small>
_x000D_
Datetime formatting is performed by the org.joda.time.format.DateTimeFormatter class
. Three classes provide factory methods to create formatters, and this is one. The others are ISODateTimeFormat
and DateTimeFormatterBuilder
.
DateTimeFormatter format = DateTimeFormat.forPattern("yyyy-MMM-dd");
LocalDate lDate = new LocalDate().parse("2005-nov-12",format);
final org.joda.time.LocalDate class
is an immutable datetime class representing a date without a time zone. LocalDate
is thread-safe and immutable, provided that the Chronology is as well. All standard Chronology classes supplied are thread-safe and immutable.
You can this query:
pip install image
I had pillow installed, and still, I got the error that you mentioned. But after I executed the above command, the error vanished. And My program worked perfectly.
I edited a little in the accepted answer. There is a problem when leftInset
and rightInset
increase, a part of text will be disappeared, b/c the width of label will be narrowed but the height does not increase as figure:
To resolve this problem you need to re-calculate height of text as follow:
@IBDesignable class PaddingLabel: UILabel {
@IBInspectable var topInset: CGFloat = 20.0
@IBInspectable var bottomInset: CGFloat = 20.0
@IBInspectable var leftInset: CGFloat = 20.0
@IBInspectable var rightInset: CGFloat = 20.0
override func drawTextInRect(rect: CGRect) {
let insets = UIEdgeInsets(top: topInset, left: leftInset, bottom: bottomInset, right: rightInset)
super.drawTextInRect(UIEdgeInsetsInsetRect(rect, insets))
}
override func intrinsicContentSize() -> CGSize {
var intrinsicSuperViewContentSize = super.intrinsicContentSize()
let textWidth = frame.size.width - (self.leftInset + self.rightInset)
let newSize = self.text!.boundingRectWithSize(CGSizeMake(textWidth, CGFloat.max), options: NSStringDrawingOptions.UsesLineFragmentOrigin, attributes: [NSFontAttributeName: self.font], context: nil)
intrinsicSuperViewContentSize.height = ceil(newSize.size.height) + self.topInset + self.bottomInset
return intrinsicSuperViewContentSize
}
}
and result:
I hope to help some people in the same situation as me.
I just dealt with this same issue. Make sure your query lists the full source name, using no shortcuts. Visual Studio can recognize the shortcuts, but your reporting services application may not be able to recognize which tables your data should be coming from. Hope that helps.
Why not use the PDFMergerUtility of pdfbox?
PDFMergerUtility ut = new PDFMergerUtility();
ut.addSource(...);
ut.addSource(...);
ut.addSource(...);
ut.setDestinationFileName(...);
ut.mergeDocuments();
That very well may be a false positive. Like the warning message says, it is common for a capture to start in the middle of a tcp session. In those cases it does not have that information. If you are really missing acks then it is time to start looking upstream from your host for where they are disappearing. It is possible that tshark can not keep up with the data and so it is dropping some metrics. At the end of your capture it will tell you if the "kernel dropped packet" and how many. By default tshark disables dns lookup, tcpdump does not. If you use tcpdump you need to pass in the "-n" switch. If you are having a disk IO issue then you can do something like write to memory /dev/shm. BUT be careful because if your captures get very large then you can cause your machine to start swapping.
My bet is that you have some very long running tcp sessions and when you start your capture you are simply missing some parts of the tcp session due to that. Having said that, here are some of the things that I have seen cause duplicate/missing acks.
In order to resolve this on an operating system level in an Ubuntu installation check the following:
$ locale charmap
If you get
locale: Cannot set LC_CTYPE to default locale: No such file or directory
instead of
UTF-8
then set LC_CTYPE
and LC_ALL
like this:
$ export LC_ALL="en_US.UTF-8"
$ export LC_CTYPE="en_US.UTF-8"
I wrote a DateTextField component.
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Cursor;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.Font;
import java.awt.Frame;
import java.awt.GridLayout;
import java.awt.Point;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JSpinner;
import javax.swing.JTextField;
import javax.swing.SpinnerNumberModel;
import javax.swing.SwingConstants;
import javax.swing.SwingUtilities;
import javax.swing.border.LineBorder;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
public class DateTextField extends JTextField {
private static String DEFAULT_DATE_FORMAT = "MM/dd/yyyy";
private static final int DIALOG_WIDTH = 200;
private static final int DIALOG_HEIGHT = 200;
private SimpleDateFormat dateFormat;
private DatePanel datePanel = null;
private JDialog dateDialog = null;
public DateTextField() {
this(new Date());
}
public DateTextField(String dateFormatPattern, Date date) {
this(date);
DEFAULT_DATE_FORMAT = dateFormatPattern;
}
public DateTextField(Date date) {
setDate(date);
setEditable(false);
setCursor(new Cursor(Cursor.HAND_CURSOR));
addListeners();
}
private void addListeners() {
addMouseListener(new MouseAdapter() {
public void mouseClicked(MouseEvent paramMouseEvent) {
if (datePanel == null) {
datePanel = new DatePanel();
}
Point point = getLocationOnScreen();
point.y = point.y + 30;
showDateDialog(datePanel, point);
}
});
}
private void showDateDialog(DatePanel dateChooser, Point position) {
Frame owner = (Frame) SwingUtilities
.getWindowAncestor(DateTextField.this);
if (dateDialog == null || dateDialog.getOwner() != owner) {
dateDialog = createDateDialog(owner, dateChooser);
}
dateDialog.setLocation(getAppropriateLocation(owner, position));
dateDialog.setVisible(true);
}
private JDialog createDateDialog(Frame owner, JPanel contentPanel) {
JDialog dialog = new JDialog(owner, "Date Selected", true);
dialog.setUndecorated(true);
dialog.getContentPane().add(contentPanel, BorderLayout.CENTER);
dialog.pack();
dialog.setSize(DIALOG_WIDTH, DIALOG_HEIGHT);
return dialog;
}
private Point getAppropriateLocation(Frame owner, Point position) {
Point result = new Point(position);
Point p = owner.getLocation();
int offsetX = (position.x + DIALOG_WIDTH) - (p.x + owner.getWidth());
int offsetY = (position.y + DIALOG_HEIGHT) - (p.y + owner.getHeight());
if (offsetX > 0) {
result.x -= offsetX;
}
if (offsetY > 0) {
result.y -= offsetY;
}
return result;
}
private SimpleDateFormat getDefaultDateFormat() {
if (dateFormat == null) {
dateFormat = new SimpleDateFormat(DEFAULT_DATE_FORMAT);
}
return dateFormat;
}
public void setText(Date date) {
setDate(date);
}
public void setDate(Date date) {
super.setText(getDefaultDateFormat().format(date));
}
public Date getDate() {
try {
return getDefaultDateFormat().parse(getText());
} catch (ParseException e) {
return new Date();
}
}
private class DatePanel extends JPanel implements ChangeListener {
int startYear = 1980;
int lastYear = 2050;
Color backGroundColor = Color.gray;
Color palletTableColor = Color.white;
Color todayBackColor = Color.orange;
Color weekFontColor = Color.blue;
Color dateFontColor = Color.black;
Color weekendFontColor = Color.red;
Color controlLineColor = Color.pink;
Color controlTextColor = Color.white;
JSpinner yearSpin;
JSpinner monthSpin;
JButton[][] daysButton = new JButton[6][7];
DatePanel() {
setLayout(new BorderLayout());
setBorder(new LineBorder(backGroundColor, 2));
setBackground(backGroundColor);
JPanel topYearAndMonth = createYearAndMonthPanal();
add(topYearAndMonth, BorderLayout.NORTH);
JPanel centerWeekAndDay = createWeekAndDayPanal();
add(centerWeekAndDay, BorderLayout.CENTER);
reflushWeekAndDay();
}
private JPanel createYearAndMonthPanal() {
Calendar cal = getCalendar();
int currentYear = cal.get(Calendar.YEAR);
int currentMonth = cal.get(Calendar.MONTH) + 1;
JPanel panel = new JPanel();
panel.setLayout(new FlowLayout());
panel.setBackground(controlLineColor);
yearSpin = new JSpinner(new SpinnerNumberModel(currentYear,
startYear, lastYear, 1));
yearSpin.setPreferredSize(new Dimension(56, 20));
yearSpin.setName("Year");
yearSpin.setEditor(new JSpinner.NumberEditor(yearSpin, "####"));
yearSpin.addChangeListener(this);
panel.add(yearSpin);
JLabel yearLabel = new JLabel("Year");
yearLabel.setForeground(controlTextColor);
panel.add(yearLabel);
monthSpin = new JSpinner(new SpinnerNumberModel(currentMonth, 1,
12, 1));
monthSpin.setPreferredSize(new Dimension(35, 20));
monthSpin.setName("Month");
monthSpin.addChangeListener(this);
panel.add(monthSpin);
JLabel monthLabel = new JLabel("Month");
monthLabel.setForeground(controlTextColor);
panel.add(monthLabel);
return panel;
}
private JPanel createWeekAndDayPanal() {
String colname[] = { "S", "M", "T", "W", "T", "F", "S" };
JPanel panel = new JPanel();
panel.setFont(new Font("Arial", Font.PLAIN, 10));
panel.setLayout(new GridLayout(7, 7));
panel.setBackground(Color.white);
for (int i = 0; i < 7; i++) {
JLabel cell = new JLabel(colname[i]);
cell.setHorizontalAlignment(JLabel.RIGHT);
if (i == 0 || i == 6) {
cell.setForeground(weekendFontColor);
} else {
cell.setForeground(weekFontColor);
}
panel.add(cell);
}
int actionCommandId = 0;
for (int i = 0; i < 6; i++)
for (int j = 0; j < 7; j++) {
JButton numBtn = new JButton();
numBtn.setBorder(null);
numBtn.setHorizontalAlignment(SwingConstants.RIGHT);
numBtn.setActionCommand(String
.valueOf(actionCommandId));
numBtn.setBackground(palletTableColor);
numBtn.setForeground(dateFontColor);
numBtn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
JButton source = (JButton) event.getSource();
if (source.getText().length() == 0) {
return;
}
dayColorUpdate(true);
source.setForeground(todayBackColor);
int newDay = Integer.parseInt(source.getText());
Calendar cal = getCalendar();
cal.set(Calendar.DAY_OF_MONTH, newDay);
setDate(cal.getTime());
dateDialog.setVisible(false);
}
});
if (j == 0 || j == 6)
numBtn.setForeground(weekendFontColor);
else
numBtn.setForeground(dateFontColor);
daysButton[i][j] = numBtn;
panel.add(numBtn);
actionCommandId++;
}
return panel;
}
private Calendar getCalendar() {
Calendar calendar = Calendar.getInstance();
calendar.setTime(getDate());
return calendar;
}
private int getSelectedYear() {
return ((Integer) yearSpin.getValue()).intValue();
}
private int getSelectedMonth() {
return ((Integer) monthSpin.getValue()).intValue();
}
private void dayColorUpdate(boolean isOldDay) {
Calendar cal = getCalendar();
int day = cal.get(Calendar.DAY_OF_MONTH);
cal.set(Calendar.DAY_OF_MONTH, 1);
int actionCommandId = day - 2 + cal.get(Calendar.DAY_OF_WEEK);
int i = actionCommandId / 7;
int j = actionCommandId % 7;
if (isOldDay) {
daysButton[i][j].setForeground(dateFontColor);
} else {
daysButton[i][j].setForeground(todayBackColor);
}
}
private void reflushWeekAndDay() {
Calendar cal = getCalendar();
cal.set(Calendar.DAY_OF_MONTH, 1);
int maxDayNo = cal.getActualMaximum(Calendar.DAY_OF_MONTH);
int dayNo = 2 - cal.get(Calendar.DAY_OF_WEEK);
for (int i = 0; i < 6; i++) {
for (int j = 0; j < 7; j++) {
String s = "";
if (dayNo >= 1 && dayNo <= maxDayNo) {
s = String.valueOf(dayNo);
}
daysButton[i][j].setText(s);
dayNo++;
}
}
dayColorUpdate(false);
}
public void stateChanged(ChangeEvent e) {
dayColorUpdate(true);
JSpinner source = (JSpinner) e.getSource();
Calendar cal = getCalendar();
if (source.getName().equals("Year")) {
cal.set(Calendar.YEAR, getSelectedYear());
} else {
cal.set(Calendar.MONTH, getSelectedMonth() - 1);
}
setDate(cal.getTime());
reflushWeekAndDay();
}
}
}
SELECT name,COUNT(*) as count
FROM tablename
GROUP BY name
ORDER BY count DESC;
Run the following from the command prompt:
set Path="C:\Program Files\Java\jdk1.7.0_09\bin"
or
set PATH="C:\Program Files\Java\jdk1.7.0_09\bin"
I have tried this and it works well.
Submodule repositories stay in a detached HEAD state pointing to a specific commit. Changing that commit simply involves checking out a different tag or commit then adding the change to the parent repository.
$ cd submodule
$ git checkout v2.0
Previous HEAD position was 5c1277e... bumped version to 2.0.5
HEAD is now at f0a0036... version 2.0
git-status
on the parent repository will now report a dirty tree:
# On branch dev [...]
#
# modified: submodule (new commits)
Add the submodule directory and commit to store the new pointer.
You should set a TimeZone in your DateFormat, otherwise it will use the default one (depending on the settings of the computer).
It is not strictly possible in default db due to the many public executes that each user gains automatically through public.
This error is gradle permission related . Just paste below line in your terminal and run...
chmod a+rx android/gradlew