How do I have = trips.maximum(:maximum_speed_mph).round(0).to_s default to zero if there is no value?
I was able to do it with this = number_with_precision(trips.average(:average_speed_mpg), :precision=>0) || 0
The same does not work for = trips.maximum(:maximum_speed_mph).round(0).to_s
(trips.maximum(:maximum_speed_mph) || 0).round(0).to_s
since nil.to_i == 0 you can do:
max = trips.maximum(:maximum_speed_mph).to_i
and then convert it to string max.to_s
This is interesting if you want to assign a value automatically to your next record. e.g.
self.maximum_speed_mph = Trip.maximum_speed_mph.to_i + 1
Related
sorry for asking this question but I couldn't understand it
-- but i don't understand this code
ballDX = math.random(2) == 1 and 100 or -100
--here ballDY will give value between -50 to 50
ballDY = math.random(-50, 50)
I don't understand the structure what is (2) and why it's == 1
Thank you a lot
math.random(x) will randomly return an integer between 1 and x.
So math.random(2) will randomly return 1 or 2.
If it returns 1 (== 1), ballDX will be set to 100.
If it returns 2 (~= 1), ballDX will be set to -100.
A simple way to make a 50-50 chance.
That is a very common way of assigning variables in Lua based on conditionals. It’s the same you’d do, for example, in Python with “foo = a if x else b”:
The first function, math.random(2), returns either 1 or 2. So, if it returns 1 the part math.random(2) == 1 is true and so you assign 100 to the variable ballDX. Otherwise, assign -100 to it.
In lua
result = condition and first or second
basically means the same as
if condition and first ~= nil and first ~= false then
result = first
else
result = second
end
So in your case
if math.random(2) == 1 then
ballDX = 100
else
ballDX = -100
end
in other words, there is a 50/50 chance for ballDX to become 100 or -100
For a better understanding, a look at lua documentation helps a lot :
https://www.lua.org/pil/3.3.html
You can read:
The operator or returns its first argument if it is not false; otherwise, it returns its second argument:
So if the random number is 1 it will return the first argument (100) of the "or" otherwise it will return the second argument (-100).
I'm having issues with the below error:
esx_glovebox_sv.lua:138: attempt to compare number with nil.
Line 138 is third in RAW data below
RegisterServerEvent("esx_glovebox:getItem")
AddEventHandler(
"esx_glovebox:getItem",
function(plate, type, item, count, max, owned)
local _source = source
local xPlayer = ESX.GetPlayerFromId(_source)
if type == "item_standard" then
local targetItem = xPlayer.getInventoryItem(item)
if targetItem.limit == -1 or ((targetItem.count + count) <= targetItem.limit) then
TriggerEvent(
"esx_glovebox:getSharedDataStore",
plate,
function(store)
local coffres = (store.get("coffres") or {})
for i = 1, #coffres, 1 do
if coffres[i].name == item then
if (coffres[i].count >= count and count > 0) then
xPlayer.addInventoryItem(item, count)
if (coffres[i].count - count) == 0 then
table.remove(coffres, i)
else
coffres[i].count = coffres[i].count - count
end
break
else
TriggerClientEvent(
"pNotify:SendNotification",
_source,
{
text = _U("invalid_quantity"),
type = "error",
queue = "glovebox",
timeout = 3000,
layout = "bottomCenter"
}
)
end
If I understand your post correctly "line 138" points to the third line in your posted code snippet, which would be:
if targetItem.limit == -1 or ((targetItem.count + count) <= targetItem.limit) then
The error means, that one of the values you are working with is nil and therefore can't be compared to a number. In your case this can only be targetItem.limit.
If each targetItem should have a limit and count value, the issue is somewhere else in your code.
Instead of throwing an error you can simply check for the existance of the value by adding additional checks:
if type == "item_standard" then
local targetItem = xPlayer.getInventoryItem(item)
-- Make sure that targetItem and targetItem.limit aren't nil.
if targetItem and targetItem.limit then
if targetItem.limit == -1 or ((targetItem.count + count) <= targetItem.limit) then
Short explanation: In Lua both nil and the boolean value false represent a false value inside of a logical expression. Any other value will be treated as true. In this case you'll skip the nested if-statement if either targetItem or targetItem.limit are nil.
Via an enterpreise service consumer I connect to a webservice, which returns me some data, and also url's.
However, I tried all methods of the mentioned class above and NO METHOD seems to convert the unicode-characters inside my url into the proper readable characters.... ( in this case '=' and ';' ) ...
The only method, which runs properly is "is_valid_url", which returns false, when I pass url's like this:
http://not_publish-workflow-dev.hq.not_publish.com/lc/content/forms/af/not_publish/request-datson-internal/v01/request-datson-internal.html?taskId\u003d105862\u0026wcmmode\u003ddisabled
What am I missing?
It seems that this format is for json values. Usually = and & don't need to be written with the \u prefix. To decode all \u characters, you may use this code:
DATA(json_value) = `http://not_publish-workflow-dev.hq.not_publish.com/lc`
&& `/content/forms/af/not_publish/request-datson-internal/v01`
&& `/request-datson-internal.html?taskId\u003d105862\u0026wcmmode\u003ddisabled`.
FIND ALL OCCURRENCES OF REGEX '\\u....' IN json_value RESULTS DATA(matches).
SORT matches BY offset DESCENDING.
LOOP AT matches ASSIGNING FIELD-SYMBOL(<match>).
DATA hex2 TYPE x LENGTH 2.
hex2 = to_upper( substring( val = json_value+<match>-offset(<match>-length) off = 2 ) ).
DATA(uchar) = cl_abap_conv_in_ce=>uccp( hex2 ).
REPLACE SECTION OFFSET <match>-offset LENGTH <match>-length OF json_value WITH uchar.
ENDLOOP.
ASSERT json_value = `http://not_publish-workflow-dev.hq.not_publish.com/lc`
&& `/content/forms/af/not_publish/request-datson-internal/v01`
&& `/request-datson-internal.html?taskId=105862&wcmmode=disabled`.
I hate to answer my own questions, but anyway, I found an own solution, via manually replacing those unicodes. It is similar to Sandra's idea, but able to convert ANY unicode.
I share it here, just in case, any person might also need it.
DATA: lt_res_tab TYPE match_result_tab.
DATA(valid_url) = url.
FIND ALL OCCURRENCES OF REGEX '\\u.{4}' IN valid_url RESULTS lt_res_tab.
WHILE lines( lt_res_tab ) > 0.
DATA(match) = substring( val = valid_url off = lt_res_tab[ 1 ]-offset len = lt_res_tab[ 1 ]-length ).
DATA(hex_unicode) = to_upper( match+2 ).
DATA(char) = cl_abap_conv_in_ce=>uccp( uccp = hex_unicode ).
valid_url = replace( val = valid_url off = lt_res_tab[ 1 ]-offset len = lt_res_tab[ 1 ]-length with = char ).
FIND ALL OCCURRENCES OF REGEX '\\u.{4}' IN valid_url RESULTS lt_res_tab.
ENDWHILE.
WRITE / url.
WRITE / valid_url.
I have NoDataBase calculator app. It takes digit parameters from view, made calculations in controller with some methods and return answer. The issue is to show correct answer in view. I need to show exact float or integer.
I made some convertation, but it seems to looks ugly.
I wondering, how to implement DRY converter.
Links:
interest_calculator/index.html.erb
interest_calculator_controller.rb
number_to_number spec tests
persent_from_number spec tests
Rounding of float to 10 characters
# If accepted parameter is integer, then it shows in view as 5, when it
# is float, it shows as 5.1
#first_0 = params[:a_0].to_f % 1 != 0 ? params[:a_0].to_f : params[:a_0].to_i
#second_0 = params[:b_0].to_f % 1 != 0 ? params[:b_0].to_f : params[:b_0].to_i
#first_1 = params[:a_1].to_f % 1 != 0 ? params[:a_1].to_f : params[:a_1].to_i
#second_1 = params[:b_1].to_f % 1 != 0 ? params[:b_1].to_f : params[:b_1].to_i
integer_decimal_converter(#first_0, #second_0, #first_1, #second_1)
If you don't need global variables you can do something like this:
result = [:a_0, :b_0, :a_1, :b_1].map do |key|
value = params[key].to_f
value % 1 == 0 ? value.to_i : value
end
integer_decimal_converter(*result)
I am new to programming and trying to find a simpler way to do this:
if state[0] != 0 && state[1] != 0 && state[2] != 0 && state[3] != 0 && state[4] != 0 && state[5] != 0 && state[6] != 0 && state[7] != 0 && state[8] != 0 {
gameOverLabel.text = "It's a tie."
gameOverLabel.hidden = false
active = false
}
I tried the code below but it reacted like a OR rather than a AND.
if state[0&1&2&3&4&5&6&7&8] != 0 {
gameOverLabel.text = "It's a tie."
gameOverLabel.hidden = false
active = false
}
Thanks for any help!
Assuming that your intention is to check if all array elements
are different from zero, the easiest approach would be
if !state.contains(0) { ... }
Your code
if state[0&1&2&3&4&5&6&7&8] != 0 { ... }
does not work
as intended because here the bitwise AND 0&1&2&3&4&5&6&7&8
is computed first (with result zero), so that is equivalent to
if state[0] != 0 { ... }
let state = [0,1,2,0,4,5,6,7]
if state.filter{$0 != 0}.count > 0 {
gameOverLabel.text = "It's a tie."
gameOverLabel.hidden = false
active = false
}
Try this one
The general case with an Array of indices
The short version
let indices = [4,2,9,6,5,3,8,0]
if !indices.contains({ state[$0] == 0 }) {
// ...
}
A second version which only shows the possibilities of Swift:
if !indices.lazy.map{ state[$0] }.contains(0) {
// ...
}
The lazy is used since otherwise map would apply the closure to all indices whereas lazy applies it on average only to half the elements (contains determines the number of executions of the closure).
Note: There is probably no performance improvement for a small amount of indices. The first version is certainly (ever so slightly) faster.
A specific range of indices
Just use the approach above with
let indices = 5...9
Or directly operate on the sub sequence of Array which is ArraySlice.
Side note: Even though it seems that ArraySlice (return type of Array[Range<Int>]) is a value type, internally it is a reference type (like Array) which only copies itself on mutation. In addition ArraySlice is only a view into the array (as long none of them is mutated). So it could be even faster than the first approach.
if !state[24...42].contains(0) {
// ...
}