The mask is needed: 90.99%, where:
9 - optional digit
0 - required
%,. - relevant characters '%' and '.'
For example:
Input / Result
1 ---> 1%
12 ---> 12%
12.1 ---> 12.1%
12.12 ---> 12.12%
I'm using redux-form
I've tried react-native-text-input-mask and react-native-masked-text already, however, there is no similar functionality in these packages (in the first one there is something similar, but '%' is correctly displayed only if it is used before the number but this char should be after)
The best way here is to provide masking next to the input itself.
It highly depends on how do you use the Field component (do you even use it?).
You can try to use the format prop on the Field.
Or you can provide your own component to render a field and provide own format functionality:
const renderPercentagedInput = (field) => {
function onChange(evt) {
const value = evt.target.value;
const numbers = value.replace(/[^0-9.,]/g, '')
field.input.onChange(numbers + '%')
}
return (
<TextInput
{...field.input}
onChangeText={onChange}
/>
);
}
Related
I Want to copy an array from a text file and make another array equal it
so
local mapData = {
grass = {
cam = "hud",
x = 171,
image = "valley/grass",
y = 168,
animated = true
}
}
This is an array that is in Data.lua
i want to copy this array and make it equal another array
local savedMapData = {}
savedMapData = io.open('Data.lua', 'r')
Thank you.
It depends on Lua Version what you can do further.
But i like questions about file operations.
Because filehandlers in Lua are Objects with methods.
The datatype is userdata.
That means it has methods that can directly be used on itself.
Like the methods for the datatype string.
Therefore its easy going to do lazy things like...
-- Example open > reading > loading > converting > defining
-- In one Line - That is possible with methods on datatype
-- Lua 5.4
local savedMapData = load('return {' .. io.open('Data.lua'):read('a'):gsub('^.*%{', ''):gsub('%}.*$', '') .. '}')()
for k, v in pairs(savedMapData) do print(k, '=>', v) end
Output should be...
cam => hud
animated => true
image => valley/grass
y => 168
x => 171
If you need it in the grass table then do...
local savedMapData = load('return {grass = {' .. io.open('Data.lua'):read('a'):gsub('^.*%{', ''):gsub('%}.*$', '') .. '}}')()
The Chain of above methods do...
io.open('Data.lua') - Creates Filehandler (userdata) in read only mode
(userdata):read('a') - Reading whole File into one (string)
(string):gsub('^.*%{', '') - Replace from begining to first { with nothing
(string):gsub('%}.*$', '') - Replace from End to first } with nothing
I want to append the % sign after the number is entered. How can I achieve this in React? I've concatenated the '%' sign but it is appearing after every number. How can I append it so that after entering the number e.g. 51 , the percent sign will appear?
Here's the code:
<InputBase
className={`milestone-percent-rate`}
autoComplete={"off"}
placeholder={"20%"}
maxLength="100"
value={this.state.percent_rate + '%'}
onChange={(e)=>{this.handleChange(e, "percent_rate")}}
/>
you can write the append logic in the handleChange method like below .
this.setState({percent_rate,e.value+'%'})
So I currently developing a website that support many languages. I have an input box where user can input the amount of currency inside. I need a function to validate if that input is legit or not.
however, because different countries use different format of number.
for example: England use '.' for decimal and ',' for thousand separator .
Where as Germany use ',' for decimal and '.' for thousand separator.
French use ',' for decimal and (space) for thousand separator...
And for Chinese/Jap , they even dont use number "1-9" to describe number
I can make a very big if-else function to do the validate base on the language they are using. something like this
number = userinput()
if "de":
return deValidator(number)
if "fr":
return frValidator(number)
if "en":
return enValidator(number)
if "zh":
return zhValidator(number)
However, is there any wiser way to do it?? what I am looking for is something like a already-built validator/library or an easier approach to solve this problem without having to writing different validator for different language
You can leverage on toLocaleString() method to help to build a validator; The toLocaleString() method returns a string with a language sensitive representation of the number.
const number = 123456.789;
// German uses comma as decimal separator and period for thousands
console.log(number.toLocaleString('de-DE'));
// → 123.456,789
// Arabic in most Arabic speaking countries uses Eastern Arabic digits
console.log(number.toLocaleString('ar-EG'));
// → ١٢٣٤٥٦٫٧٨٩
// India uses thousands/lakh/crore separators
console.log(number.toLocaleString('en-IN'));
// → 1,23,456.789
// the nu extension key requests a numbering system, e.g. Chinese decimal
console.log(number.toLocaleString('zh-Hans-CN-u-nu-hanidec'));
// → 一二三,四五六.七八九
// when requesting a language that may not be supported, such as
// Balinese, include a fallback language, in this case Indonesian
console.log(number.toLocaleString(['ban', 'id']));
// → 123.456,789
With this method, you can also format numbers with currency information:
const number = 10000000;
number.toLocaleString('it-IT', {style: 'currency', currency: 'EUR'})
// → 10.000.000,00 €
number.toLocaleString('it-IT', {style: 'currency', currency: 'USD'})
// → 10.000.000,00 US$
number.toLocaleString('en-US', {style: 'currency', currency: 'EUR'})
// → €10,000,000.00
number.toLocaleString('en-US', {style: 'currency', currency: 'USD'})
// → $10,000,000.00
For more details: toLocaleString https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Number/toLocaleString
I'm trying to make a program based around 8 boolean statements.
I build the array = [0,0,0,0,0,0,0,0];.
For each possible combination I need to make the program output a different text.
To make things simpler, I can remove any possibilities that contain less than 3 true statements.
For example: if (array === [1,1,1,0,0,0,0,0]){console.log('Targets: 4, 5, 6, 7')};
Is it possible to have it set so that if the value is false it's added to then end of "Targets: "? I'm very new to coding as a hobby and have only made 1 extensive program. I feel like {console.log("Targets: " + if(array[0]===0){console.log(" 1,")} + if(array[2]===0)...}would portay what I'm looking for but it's terrible as a code.
I'm sure that someone has had this issue before but I don't think I'm experienced enough to be searching with the correct keywords.
PS: I'd greatly appreciate it if we can stick to the very basics as I haven't had any luck with installing new elements other than discord.js.
This does what you need:
const values = [1,1,1,0,0,0,0,0];
const positions = values.map((v, i) => !v ? i : null).filter(v => v != null);
console.log('Target: ' + positions.join(', '));
In essence:
Map each value to its respective index if the value is falsy (0 is considered falsy), otherwise map it to null.
Filter out all null values.
Join all remaining indexes to a string.
To address your additional requirements:
const locations = ['Trees', 'Rocks', 'L1', 'R1', 'L2', 'R2', 'L3', 'R3'];
const values = [1,1,1,0,0,0,0,0];
const result = values.map((v, i) => !v ? locations[i] : null).filter(v => v != null);
console.log('Target: ' + result.join(', '));
I'm trying to read an input file in Scala that I know the structure of, however I only need every 9th entry. So far I have managed to read the whole thing using:
val lines = sc.textFile("hdfs://moonshot-ha-nameservice/" + args(0))
val fields = lines.map(line => line.split(","))
The issue, this leaves me with an array that is huge (we're talking 20GB of data). Not only have I seen myself forced to write some very ugly code in order to convert between RDD[Array[String]] and Array[String] but it's essentially made my code useless.
I've tried different approaches and mixes between using
.map()
.flatMap() and
.reduceByKey()
however nothing actually put my collected "cells" into the format that I need them to be.
Here's what is supposed to happen: Reading a folder of text files from our server, the code should read each "line" of text in the format:
*---------*
| NASDAQ: |
*---------*
exchange, stock_symbol, date, stock_price_open, stock_price_high, stock_price_low, stock_price_close, stock_volume, stock_price_adj_close
and only keep a hold of the stock_symbol as that is the identifier I'm counting. So far my attempts have been to turn the entire thing into an array only collect every 9th index from the first one into a collected_cells var. Issue is, based on my calculations and real life results, that code would take 335 days to run (no joke).
Here's my current code for reference:
import org.apache.spark.SparkContext
import org.apache.spark.SparkContext._
import org.apache.spark.SparkConf
object SparkNum {
def main(args: Array[String]) {
// Do some Scala voodoo
val sc = new SparkContext(new SparkConf().setAppName("Spark Numerical"))
// Set input file as per HDFS structure + input args
val lines = sc.textFile("hdfs://moonshot-ha-nameservice/" + args(0))
val fields = lines.map(line => line.split(","))
var collected_cells:Array[String] = new Array[String](0)
//println("[MESSAGE] Length of CC: " + collected_cells.length)
val divider:Long = 9
val array_length = fields.count / divider
val casted_length = array_length.toInt
val indexedFields = fields.zipWithIndex
val indexKey = indexedFields.map{case (k,v) => (v,k)}
println("[MESSAGE] Number of lines: " + array_length)
println("[MESSAGE] Casted lenght of: " + casted_length)
for( i <- 1 to casted_length ) {
println("[URGENT DEBUG] Processin line " + i + " of " + casted_length)
var index = 9 * i - 8
println("[URGENT DEBUG] Index defined to be " + index)
collected_cells :+ indexKey.lookup(index)
}
println("[MESSAGE] collected_cells size: " + collected_cells.length)
val single_cells = collected_cells.flatMap(collected_cells => collected_cells);
val counted_cells = single_cells.map(cell => (cell, 1).reduceByKey{case (x, y) => x + y})
// val result = counted_cells.reduceByKey((a,b) => (a+b))
// val inmem = counted_cells.persist()
//
// // Collect driver into file to be put into user archive
// inmem.saveAsTextFile("path to server location")
// ==> Not necessary to save the result as processing time is recorded, not output
}
}
The bottom part is currently commented out as I tried to debug it, but it acts as pseudo-code for me to know what I need done. I may want to point out that I am next to not at all familiar with Scala and hence things like the _ notation confuse the life out of me.
Thanks for your time.
There are some concepts that need clarification in the question:
When we execute this code:
val lines = sc.textFile("hdfs://moonshot-ha-nameservice/" + args(0))
val fields = lines.map(line => line.split(","))
That does not result in a huge array of the size of the data. That expression represents a transformation of the base data. It can be further transformed until we reduce the data to the information set we desire.
In this case, we want the stock_symbol field of a record encoded a csv:
exchange, stock_symbol, date, stock_price_open, stock_price_high, stock_price_low, stock_price_close, stock_volume, stock_price_adj_close
I'm also going to assume that the data file contains a banner like this:
*---------*
| NASDAQ: |
*---------*
The first thing we're going to do is to remove anything that looks like this banner. In fact, I'm going to assume that the first field is the name of a stock exchange that start with an alphanumeric character. We will do this before we do any splitting, resulting in:
val lines = sc.textFile("hdfs://moonshot-ha-nameservice/" + args(0))
val validLines = lines.filter(line => !line.isEmpty && line.head.isLetter)
val fields = validLines.map(line => line.split(","))
It helps to write the types of the variables, to have peace of mind that we have the data types that we expect. As we progress in our Scala skills that might become less important. Let's rewrite the expression above with types:
val lines: RDD[String] = sc.textFile("hdfs://moonshot-ha-nameservice/" + args(0))
val validLines: RDD[String] = lines.filter(line => !line.isEmpty && line.head.isLetter)
val fields: RDD[Array[String]] = validLines.map(line => line.split(","))
We are interested in the stock_symbol field, which positionally is the element #1 in a 0-based array:
val stockSymbols:RDD[String] = fields.map(record => record(1))
If we want to count the symbols, all that's left is to issue a count:
val totalSymbolCount = stockSymbols.count()
That's not very helpful because we have one entry for every record. Slightly more interesting questions would be:
How many different stock symbols we have?
val uniqueStockSymbols = stockSymbols.distinct.count()
How many records for each symbol do we have?
val countBySymbol = stockSymbols.map(s => (s,1)).reduceByKey(_+_)
In Spark 2.0, CSV support for Dataframes and Datasets is available out of the box
Given that our data does not have a header row with the field names (what's usual in large datasets), we will need to provide the column names:
val stockDF = sparkSession.read.csv("/tmp/quotes_clean.csv").toDF("exchange", "symbol", "date", "open", "close", "volume", "price")
We can answer our questions very easy now:
val uniqueSymbols = stockDF.select("symbol").distinct().count
val recordsPerSymbol = stockDF.groupBy($"symbol").agg(count($"symbol"))