Blazorise Select Default Value - blazorise

Is there a way to choose the default value from a list using the in Blazorise? Right now the default value is null, but I would like it to be say "3".
<Select #bind-SelectedValue="#_someProperty">
#foreach (string number in _numbers)
{
<SelectItem Value="#number ">#number </SelectItem>
}
</Select>
#code
private static readonly string[] _numbers =
{
"1", "2", "3", "4", "5",
};

This is a simple approach to fix this (just add a variable with initial value).
You can Also use SelectedValueChanged to manually handle your custom variable.
<Select #bind-SelectedValue="#_selectedProperty" SelectedValueChanged="#OnSelectedValueChanged">
#foreach (string number in _numbers)
{
<SelectItem Value="#number ">#number </SelectItem>
}
</Select>
#code
{
private string _selectedProperty = 3;
private static readonly string[] _numbers =
{
"1", "2", "3", "4", "5",
};
void OnSelectedValueChanged( string value )
{
_selectedProperty = value; // Bind to the custom variable
Console.WriteLine( selectedValue ); // Write in Console Just for Checking
}
}

Related

Java 8 collect and change the format of the result

I have the data structre called MyPojo which has fields called time, name and timetaken (all are in Strings). I'm trying to do some grouping as follows:
List<MyPojo> myPojos = Arrays.asList(
new MyPojo("2017", "ABC", "30"),
new MyPojo("2017", "ABC", "20"),
new MyPojo("2016", "ABC", "25"),
new MyPojo("2017", "XYZ", "40")
);
Map<String, Map<String, Double>> resultMap = myPojos.stream()
.collect(Collectors.groupingBy(MyPojo::getName,
Collectors.groupingBy(MyPojo::getTime,
Collectors.averagingDouble(MyPojo::getTimeTakenAsDouble))));
Please note that I've a method called getTimeTakenAsDouble to convert thetimetaken string to double value.
This results as follows:
{ABC={2017=25.0, 2016=25.0}, XYZ={2017=40.0}}
However, my frontend developer wanted the data either in the following format:
{ABC={2017=25.0, 2016=25.0}, XYZ={2017=40.0, 2016=0.0}}
or
[
{
"time": "2017",
"name": "ABC",
"avgTimeTaken": 25.0
},
{
"time": "2017",
"name": "XYZ",
"avgTimeTaken": 40.0
},
{
"time": "2016",
"name": "ABC",
"avgTimeTaken": 25.0
},
{
"time": "2016",
"name": "XYZ",
"avgTimeTaken": 0.0
}
]
I'm thinking to perform iterations on the resultMap and prepare the 2nd format. I'm trying to perform the iteration again on the resultMap. Is there any other way to handle this?
Actually it's pretty interesting what you are trying to achieve. It's like you are trying to do some sort of logical padding. The way I've done it is to use Collectors.collectingAndThen. Once the result is there - I simply pad it with needed data.
Notice that I'm using Sets.difference from guava, but that can easily be put into a static method. Also there are additional operations performed.
So I assume your MyPojo looks like this:
static class MyPojo {
private final String time;
private final String name;
private final String timetaken;
public MyPojo(String time, String name, String timetaken) {
super();
this.name = name;
this.time = time;
this.timetaken = timetaken;
}
public String getName() {
return name;
}
public String getTime() {
return time;
}
public String getTimetaken() {
return timetaken;
}
public static double getTimeTakenAsDouble(MyPojo pojo) {
return Double.parseDouble(pojo.getTimetaken());
}
}
And input data that I've checked against is :
List<MyPojo> myPojos = Arrays.asList(
new MyPojo("2017", "ABC", "30"),
new MyPojo("2017", "ABC", "20"),
new MyPojo("2016", "ABC", "25"),
new MyPojo("2017", "XYZ", "40"),
new MyPojo("2018", "RDF", "80"));
Here is the code that does what you want:
Set<String> distinctYears = myPojos.stream().map(MyPojo::getTime).collect(Collectors.toSet());
Map<String, Map<String, Double>> resultMap = myPojos.stream()
.collect(Collectors.groupingBy(MyPojo::getName,
Collectors.collectingAndThen(
Collectors.groupingBy(MyPojo::getTime,
Collectors.averagingDouble(MyPojo::getTimeTakenAsDouble)),
map -> {
Set<String> localYears = map.keySet();
SetView<String> diff = Sets.difference(distinctYears, localYears);
Map<String, Double> toReturn = new HashMap<>(localYears.size() + diff.size());
toReturn.putAll(map);
diff.stream().forEach(e -> toReturn.put(e, 0.0));
return toReturn;
}
)));
Result of that would be:
{ABC={2016=25.0, 2018=0.0, 2017=25.0},
RDF={2016=0.0, 2018=80.0, 2017=0.0},
XYZ={2016=0.0, 2018=0.0, 2017=40.0}}

Does Nest.ConnectionSettings.SetJsonSerializerSettingsModifier even work?

Here is my question. Due to project needs, we have to keep our dates within elasticsearch index in the same format. What we've tried is the next way -
var connectionPool = new SniffingConnectionPool(nodeList);
var connectionSettings = new ConnectionSettings(connectionPool)
.SetJsonSerializerSettingsModifier(
m => m.DateFormatString = "yyyy-MM-ddTHH:mm:ss.fffffffK")
// other configuration goes here
But it didn't work out. Searching through ES index, I saw dates with dropped trailing zeros ( like 2015-05-05T18:55:27Z insted of expected 2015-05-05T18:55:27.0000000Z). Neither did next option help:
var connectionPool = new SniffingConnectionPool(nodeList);
var connectionSettings = new ConnectionSettings(connectionPool)
.SetJsonSerializerSettingsModifier(m =>
{
m.Converters.Add(new IsoDateTimeConverter { DateTimeFormat = "yyyy'-'MM'-'dd'T'HH':'mm':'ss.fffffffK"});
})
// other configuration goes here
With digging into ElasticClient at run-time, I've found that eventually there is a contract resolver which seems like overrides all those settings:
public class ElasticContractResolver : DefaultContractResolver
{
protected override JsonContract CreateContract(Type objectType)
{
JsonContract contract = base.CreateContract(objectType);
...
if (objectType == typeof(DateTime) || objectType == typeof(DateTime?))
contract.Converter = new IsoDateTimeConverter();
...
if (this.ConnectionSettings.ContractConverters.HasAny())
{
foreach (var c in this.ConnectionSettings.ContractConverters)
{
var converter = c(objectType);
if (converter == null)
continue;
contract.Converter = converter;
break;
}
}
return contract;
}
}
So if I have it right, without specifying a converter explicitly(via Connection Settings.AddContractJsonConverters()), my json settings will be gone since IsoDateTimeConverter is instantiated with the default settings rather than ones I've passed through SetJsonSerializerSettingsModifier.
Has anyone run into this issue? Or I'm just missing something? Thanks in advance!
This is how I handled custom date format for my needs:
public class Document
{
[ElasticProperty(DateFormat = "yyyy-MM-dd", Type = FieldType.Date)]
public string CreatedDate { get; set; }
}
client.Index(new Document {CreatedDate = DateTime.Now.ToString("yyyy-MM-dd")});
My document in ES
{
"_index": "indexname",
"_type": "document",
"_id": "AU04kd4jnBKFIw7rP3gX",
"_score": 1,
"_source": {
"createdDate": "2015-05-09"
}
}
Hope it will help you.

How can I make my PokerHand class randomly deal a thousand hands?

public class PokerHand
{
// ArrayList for cards
private ArrayList<Card> cards;
/**
* Constructor for class Pokerhand
*/
public PokerHand()
{
cards = new ArrayList<Card>(); // arrayList of cards
}
/**
* Add cards to list
*/
public void addCard(Card card1, Card card2, Card card3)
{
cards.add(card1);
cards.add(card2);
cards.add(card3);
}
}
This is my Card Class
public class Card()
{
private int value;
private int suit;
private static String[] suits = { "hearts", "spades", "diamonds", "clubs" };
private static String[] values = { "Ace", "2", "3", "4", "5", "6", "7",
"8", "9", "10", "Jack", "Queen", "King" };
public static String valueAsString( int value ) {
return values[value];
}
Card(int suit, int rank)
{
this.value=value;
this.suit=suit;
}
public String toString()
{
return values[value] + " of " + suits[suit];
}
public int getValue() {
return value;
}
public int getSuit() {
return suit;
}
}
How can I deal a 1000 three card hands? I am stuck on how a variety of things, including what additional methods I need. How can I construct a deal method and how can I make the deal method dish out a thousand random hands while shuffling every time a hand is dealt?
All of these are implementations are based on code from my card library.
Shuffle
public Card[] shuffle(Card[] deck) {
Random gen = new Random();
boolean[] added = new boolean[deck.length];
int positionToAdd = gen.nextInt(deck.length);
Card[] newDeck = new Card[deck.length];
for (int i = 0; i < deck.length; i++) {
while (newDeck[i] == null) {
if (!added[positionToAdd]) {
newDeck[i] = deck[positionToAdd];
positionToAdd = gen.nextInt(deck.length);
added[i] = true;
} else {
positionToAdd = gen.nextInt(deck.length);
}
}
}
return newDeck;
}
Implementation
ArrayList<Card> dealFrom = new ArrayList<Card>();
PokerHand[] hands = new PokerHand[1000];
/*Populate the "dealFrom" yourself here*/
dealFrom = Array.asList(shuffle(dealFrom.toArray()));
for (int i = 0; i < 3000; i += 3) {
//Write your deal method here
hands[i] = new PokerHand(dealFrom[i], dealFrom[i + 1], dealFrom[i + 2]);
}
Hope this helps.

JSON.net Linq and NullValueHandling

Developing a new MVC4 app, I have followed this example on the JSON.net website to fill my viewmodel with a new JSON JObject:
FinalViewModel finalVM= new FinalViewModel();
IList<ResultModel> results = GetResultList();
FinalVM.QueryResults = results;
JObject myJSON = new JObject(
new JProperty("grid",
new JArray(
from g in results
group g by g.ResultYear into y
orderby y.Key
select new JObject {
new JProperty("Year", y.Key),
new JProperty("min_1", y.Min(g=> g.Result_val1)),
new JProperty("min_2", y.Min(g=> g.Result_val2)),
new JProperty("items",
new JArray(
from g in results
where g.ResultYear==y.Key
orderby g.id
select new JObject(
new JProperty("l", g.Result_val1),
new JProperty("j",g.Result_val2),
new JProperty("id", g.id)
)
)
)}
)));
FinalVM.DataJson = myJSON;
return PartialView("_JSONView", FinalVM);
Everything works fine and i get this type of json sent to my view:
{
"grid": [
{
"Year": 1998,
"min_val1": "12",
"min_val2": null,
"items": [
{
"l": 12,
"j": null,
"id": 60
},
{
"l": 25,
"j": null,
"id": 61
}
]
}
]
}
I would like to get rid of the null values when they exist. I read a lot about the NullValueHandling option but do not see how to use it into my Json.Net linq code.
Instead of creating JObjects as part of your LINQ transformation, use anonymous objects. (This will also make your code a heck of a lot more readable!) Afterward, you can load the result object into a JObject using a JsonSerializer instance that has NullValueHandling set to Ignore. This will get rid of the nulls. Here's a demo:
class Program
{
static void Main(string[] args)
{
IList<ResultModel> results = new List<ResultModel>
{
new ResultModel
{
id = 60,
ResultYear = 1998,
Result_val1 = 12,
Result_val2 = null
},
new ResultModel
{
id = 61,
ResultYear = 1998,
Result_val1 = 25,
Result_val2 = null
}
};
var groupedResult = new
{
grid = from g in results
group g by g.ResultYear into y
orderby y.Key
select new
{
Year = y.Key,
min_1 = y.Min(g => g.Result_val1),
min_2 = y.Min(g => g.Result_val2),
items = from g in results
where g.ResultYear == y.Key
orderby g.id
select new
{
l = g.Result_val1,
j = g.Result_val2,
id = g.id
}
}
};
JsonSerializer serializer = new JsonSerializer();
serializer.NullValueHandling = NullValueHandling.Ignore;
JObject myJSON = JObject.FromObject(groupedResult, serializer);
Console.WriteLine(myJSON.ToString(Formatting.Indented));
}
class ResultModel
{
public int id { get; set; }
public int ResultYear { get; set; }
public int? Result_val1 { get; set; }
public int? Result_val2 { get; set; }
}
}
Output:
{
"grid": [
{
"Year": 1998,
"min_1": 12,
"items": [
{
"l": 12,
"id": 60
},
{
"l": 25,
"id": 61
}
]
}
]
}
One other note: if you are not planning to manipulate the JSON, you can actually skip the JObject altogether and serialize your grouped result directly to string instead:
JsonSerializerSettings settings = new JsonSerializerSettings();
settings.NullValueHandling = NullValueHandling.Ignore;
settings.Formatting = Formatting.Indented;
string myJSON = JsonConvert.SerializeObject(groupedResult, settings);

ArgumentException when deserializing using JSON.Net

I have an object as follows,
public class Foo
{
public Dictionary<string, List<double?>> Bar { get; set; }
}
I serialize using, string myJson = JsonConvert.Serialize(myFoo) and get sensible Json. However when I run JsonConvert.Deserialize<Foo>(myJson) I get an ArgumentException Parameter name: value.
Why is this?
I am using Json.Net on a Windows Phone 7.1 project.
Edit: Here is an example object and the Json it produces,
Foo myFoo = new Foo()
{
Bar = new Dictionary<string,List<double?>>() {
{"Flim", new List<double?>() { 0, 0.2, null, 0.9 }},
{"Flam", new List<double?>() { 0.0,0.1, null, null}},
}
};
The contents of myJson after serialization (double quote escapes removed)
{"Bar":{"Flim":[0.0,0.2,null,0.9],"Flam":[0.0,0.1,null,null]}}
It worked fine for me using Json.Net 4.5.11 on .NET 4.5 in standard Windows. Here is the program I used (below). Can you try running this exact code in your environment and see if it works? If so, then your ArgumentException must be coming from somewhere else. If not, then that seems to point to a difference between Windows and Windows Phone environments.
class Program
{
static void Main(string[] args)
{
Foo myFoo = new Foo()
{
Bar = new Dictionary<string, List<double?>>()
{
{ "Flim", new List<double?>() { 0, 0.2, null, 0.9 } },
{ "Flam", new List<double?>() { 0.0, 0.1, null, null } },
}
};
string json = JsonConvert.SerializeObject(myFoo);
Console.WriteLine(json);
Foo foo2 = JsonConvert.DeserializeObject<Foo>(json);
foreach (KeyValuePair<string, List<double?>> kvp in foo2.Bar)
{
Console.Write(kvp.Key);
Console.Write(":");
string sep = " {";
foreach (double? d in kvp.Value)
{
Console.Write(sep);
Console.Write(d.HasValue ? d.Value.ToString() : "null");
sep = ", ";
}
Console.WriteLine("}");
}
}
public class Foo
{
public Dictionary<string, List<double?>> Bar { get; set; }
}
}
Output:
{"Bar":{"Flim":[0.0,0.2,null,0.9],"Flam":[0.0,0.1,null,null]}}
Flim: {0, 0.2, null, 0.9}
Flam: {0, 0.1, null, null}

Resources