In my Kotlin code:
const val TS_DATE_PATTERN = "yyyy-MM-dd'T'HH:mm:ss.SSS"
val ts = responseJsonObject.get("TS").getAsString()
val tsDate = SimpleDateFormat(TS_DATE_PATTERN).parse(ts)
val tsDateAsString = SimpleDateFormat(TS_DATE_PATTERN).format(tsDate)
logger.info("ts = " + ts + " -> tsDate = " + tsDate + " -> tsDateAsString = " + tsDateAsString)
And here the (formatted for readability) result:
ts = 2019-01-14T22:56:30.429582
tsDate = Mon Jan 14 23:03:39 EET 2019
tsDateAsString = 2019-01-14T23:03:39.582
As you can see the ts and tsDateAsString have different times, although they came from the same starting point.
E.g. ts = 22:56:30 but in tsDateAsString = 23:03:39
Why?
As a suggestion: whenever you can, use java.time-utilities.
SimpleDateFormat has a special handling for the milliseconds. Everything that is parsed by the S is treated as milliseconds. As long as you deal with 3-digit-milliseconds, everything is fine (you may even just use a single S (i.e. .S) for the milliseconds to parse them), but if you use 6-digit-milliseconds as input then you also get a 6-digit-millisecond(!)-value.
The 6-digit-milliseconds then are actually 3-digit seconds + the 3-digit milliseconds. That is where the deviation is coming from.
How to solve that? Well either shorten the input time string and lose some precision or use the preferred DateTimeFormatter instead with a pattern matching your input, i.e. yyyy-MM-dd'T'HH:mm:ss.SSSSSS:
val TS_DATE_PATTERN = "yyyy-MM-dd'T'HH:mm:ss.SSSSSS"
val formatter = DateTimeFormatter.ofPattern(TS_DATE_PATTERN)
val tsDate = formatter.parse(ts) // now the value as you would expect it...
Transforming that to a TimeStamp will work as follows:
Timestamp.valueOf(LocalDateTime.from(tsDate))
Related
I'm new to LUA but figured out that gsub is a global substitution function and tonumber is a converter function. What I don't understand is how the two functions are used together to produce an encoded string.
I've already tried reading parts of PIL (Programming in Lua) and the reference manual but still, am a bit confused.
local L0_0, L1_1
function L0_0(A0_2)
return (A0_2:gsub("..", function(A0_3)
return string.char((tonumber(A0_3, 16) + 256 - 13 + 255999744) % 256)
end))
end
encodes = L0_0
L0_0 = gg
L0_0 = L0_0.toast
L1_1 = "__loading__\226\128\166"
L0_0(L1_1)
L0_0 = encodes
L1_1 = --"The Encoded String"
L0_0 = L0_0(L1_1)
L1_1 = load
L1_1 = L1_1(L0_0)
pcall(L1_1)
I removed the encoded string where I put the comment because of how long it was. If needed I can upload the encoded string as well.
gsub is being used to get 2 digit sections of A0_2. This means the string A0_3 is a 2 digit hexadecimal number but it is not in a number format so we cannot preform math on the value. A0_3 being a hex number can be inferred based on how tonubmer is used.
tonumber from Lua 5.1 Reference Manual:
Tries to convert its argument to a number. If the argument is already a number or a string convertible to a number, then tonumber returns this number; otherwise, it returns nil.
An optional argument specifies the base to interpret the numeral. The base may be any integer between 2 and 36, inclusive. In bases above 10, the letter 'A' (in either upper or lower case) represents 10, 'B' represents 11, and so forth, with 'Z' representing 35. In base 10 (the default), the number can have a decimal part, as well as an optional exponent part (see ยง2.1). In other bases, only unsigned integers are accepted.
So tonumber(A0_3, 16) means we are expecting for A0_3 to be a base 16 number (hexadecimal).
Once we have the number value of A0_3 we do some math and finally convert it to a character.
function L0_0(A0_2)
return (A0_2:gsub("..", function(A0_3)
return string.char((tonumber(A0_3, 16) + 256 - 13 + 255999744) % 256)
end))
end
This block of code takes a string of hex digits and converts them into chars. tonumber is being used to allow for the manipulation of the values.
Here is an example of how this works with Hello World:
local str = "Hello World"
local hex_str = ''
for i = 1, #str do
hex_string = hex_string .. string.format("%x", str:byte(i,i))
end
function L0_0(A0_2)
return (A0_2:gsub("..", function(A0_3)
return string.char((tonumber(A0_3, 16) + 256 - 13 + 255999744) % 256)
end))
end
local encoded = L0_0(hex_str)
print(encoded)
Output
;X__bJbe_W
And taking it back to the orginal string:
function decode(A0_2)
return (A0_2:gsub("..", function(A0_3)
return string.char((tonumber(A0_3, 16) + 13) % 256)
end))
end
hex_string = ''
for i = 1, #encoded do
hex_string = hex_string .. string.format("%x", encoded:byte(i,i))
end
print(decode(hex_string))
Using HtmlProvider to access a web-based table sometimes returns a fraction as a string (correct) and, at other times, returns a DateTime (incorrect).
What am I missing?
module Test =
open FSharp.Data
let [<Literal>] url = "https://www.example.com/fractions"
type profile = HtmlProvider<url>
let profile = profile.Load(url)
let [<Literal>] resultFile = #"C:\temp\data\Profile.csv"
let CsvResult =
do
use writer = new StreamWriter(resultFile, false)
writer.WriteLine "\"Date\";\"Fraction\""
for row in profile.Tables.Table1.Rows do
"\"" + row.``Date``.ToString() + "\"" + ";" |> writer.Write
"\"" + row.``Fraction``.ToString() + "\"" + ";" |> writer.WriteLine
writer.Close
let csvResult = CsvResult
Without seeing sample data I can't be 100% certain, but I'm guessing that it's parsing fractions as dates if the numbers involved would be valid dates in the culture you're using: e.g., 1/4 would be a valid date in any culture that uses / as a separator, and would be treated either as April 1st or as January 4th, depending on which parsing culture your system defaults to.
Other type providers in FSharp.Data (such as the CSV type provideryou could ) allow you to configure how each column will be parsed, but that's not an option the HTML type provider gives you. (Which is a bit of a missing feature, of course). But since the HTML type provider does allow you to specify the culture info for datetime and number parsing, one way you might be able to work around this is specify a culture that does not use / as a separator (but still uses . as a decimal point, since otherwise if the HTML you're parsing has numbers written like 1,000 for one thousand, that could be interpreted as 1). One such culture is the en-IN culture ("English (India)"), where the date separator is - and the decimal point is ..
So try passing Culture=System.Globalization.CultureInfo.GetCultureInfo("en-IN") in your HtmlProvider options, and see if that helps it stop treating fractions as dates.
The following combination of functions worked:
// http://www.fssnip.net/29/title/Regular-expression-active-pattern
module Solution =
open System
open System.Text.RegularExpressions
open FSharp.Data
let (|Regex|_|) pattern input =
let m = Regex.Match(input, pattern)
if m.Success then Some(List.tail [ for g in m.Groups -> g.Value ])
else None
let ptrnFraction = #"^([0-9]?[0-9]?)(\/)([0-9]?[0-9]?)$"
let ptrnDateTime = #"(\d{2})\/(\d{2})\/(\d{4}) (\d{2}):(\d{2}):(\d{2})"
let ToFraction input =
match input with
| Regex ptrnFraction [ numerator; operator; denominator ] ->
(numerator + operator + denominator).ToString()
| Regex ptrnDateTime [ day; month; year; hours; minutes; seconds ] ->
(day + "/" + month).ToString()
| _ -> "Not valid!"
let dtInput = #"05/09/2017 00:00:00"
let frcInput = #"13/20"
let outDate = ToFraction dtInput
printfn "Out Date: %s" outDate
let outFraction = ToFraction frcInput
printfn "Out Fraction: %s" outFraction
//Output:> Out Date: 05/09 Out Fraction: 13/20
Thus, I was able to replace:
"\"" + row.``Fraction``.ToString() + "\"" + ";" |> writer.WriteLine
with:
"\"" + ToFraction(row.``Fraction``.ToString()) + "\"" + ";" |> writer.Write
Thanks to #rmunn for the clarity of his explanations and the benefit of his expertise.
How to get 6 decimal precision using vb.net as in this example (7090982.885183 (6 decimal places precision)) i.e i want to read the .885183 in my previous sample as 6 decimal only.
The javascript for the above looks like :
//declare variables and assign calculated values
var HashA = OrdNo * Amt;
var HashB = MerchID * Amt;
var HashC = MerchID * OrdNo;
var TotalHash = String((HashA + HashB + HashC) / (parseInt(MerchID) + parseInt(RCode)));
//assign only 6 decimal places value
if (TotalHash.indexOf(".") != -1)
TotalHash = TotalHash.substr(0,TotalHash.indexOf(".")+7);
else
TotalHash = TotalHash + ".000000";
document.form1.HashCount.value = TotalHash;
}
I need to read this no 7090982.8851830000011 as this format 7090982.885183
What about using % operater like
you have an variable a and variable decimalresult you should code it like this
decimalresult=a % 1000000
In this example it should be
decimalresult= 7090982.885183 % 1000000
decimalresult = 885183
If you have a Decimal and you want to get the value after the decimal dot, you can do
result = input - Math.Floor(input)
What i want is to retrieve quantity in database from piece and covert it to dozen. Then input as dozen and convert back to pieces and save to database again.
when I input data eg. 10.3, it should convert to 123 piece for me ((10 * 12) + 3). My code work well without my "If clause" but only when data was "single" type. It made error when I input integer number, so I added "If.." statement to check it first which is now the output was correct for Integer but incorrect when I input single number.
I have this code..
Function DzToPcs(val)
'If CLng(val) = val then <-- not work
'if Fix(val) <> val then <-- work but the output was not correct when input single type number.
if Int(vInt) = vInt then <-- work but the output was not correct when input single type number.
DztoPcs = val * 12
else
strInt = Cstr(val)
a = Split(strInt,".")
dz = a(0)
pcs = a(1)
getdz = Cint(dz)
getpcs = Cint(pcs)
DztoPcs = (getdz * 12) + getpcs
end if
I'm not sure what's wrong with your if statements (my VBScript is a little rusty), but you could try this alternative:
Function DzToPcs(val)
strInt = Cstr(val)
a = Split(strInt,".")
dz = a(0)
if UBound(a) > 0 then
pcs = a(1)
getdz = Cint(dz)
getpcs = Cint(pcs)
DztoPcs = (getdz * 12) + getpcs
else
DztoPcs = dz * 12
end if
end function
I've got date and time in separate fields, in yyyyMMdd and HHmmss formats respectively. To parse them I think to construct a yyyy-MM-ddTHH:mm:ss string and feed this to joda-time constructor. So I am looking to get 1-st 4 digits, then 2 digits starting from the index 5, etc. How to achieve this? List.fromString(String) (which I found here) seems to be broken.
The substring method certainly can get you there but String in Scala 2.8 also supports all other methods on sequences. The ScalaDoc for class StringOps gives a complete list.
In particular, the splitAt method comes in handly. Here's a REPL interaction which shows how.
scala> val ymd = "yyyyMMdd"
ymd: java.lang.String = yyyyMMdd
scala> val (y, md) = ymd splitAt 4
y: String = yyyy
md: String = MMdd
scala> val (m, d) = md splitAt 2
m: String = MM
d: String = dd
scala> y+"-"+m+"-"+d
res3: java.lang.String = yyyy-MM-dd
Just use the substring() method on the string. Note that Scala strings behave like Java strings (with some extra methods), so anything that's in java.lang.String can also be used on Scala strings.
val s = "20100903"
val t = s.substring(0, 4) // t will contain "2010"
(Note that the arguments are not length and starting index, but starting index (inclusive) and ending index (exclusive)).
But if this is about parsing dates, why don't you just use java.text.SimpleDateFormat, like you would in Java?
val s = "20100903"
val fmt = new SimpleDateFormat("yyyyMMdd")
val date = fmt.parse(s) // will give you a java.util.Date object
If you're using Joda Time, you should be able to use
val date = DateTimeFormat.forPattern("yyyyMMdd, HHmmss")
.parseDateTime(field1 + ", " + field2)
For the more general problem of parsing Strings like this, it can be helpful to use a Regex (although I wouldn't recommend it in this case):
scala> val Date = "(\\d\\d\\d\\d)(\\d\\d)(\\d\\d)".r
Date: scala.util.matching.Regex = (\d\d\d\d)(\d\d)(\d\d)
scala> "20100903" match {
| case Date(year, month, day) => year + "-" + month + "-" + day
| }
res1: java.lang.String = 2010-09-03
val field1="20100903"
val field2="100925"
val year = field1.substring(1,5)
val month = field1.substring(5,7)
val day = ...
...
val toYodaTime = year + "-" + month+"-"+day+ ...