how to use Tuple in MVC 5 - asp.net-mvc-5

I'm trying to use tuples so I can use 2 models in the same View and I did this in my controller:
public ActionResult Index( int id = 0 )
{
int lastVoyageID = entities.log_voyage.Max(item => item.Num_Voy);
var first = entities.log_voyage.Where(v => v.Num_Voy == lastVoyageID);
log_voyage voyage1 = entities.log_voyage.Find(lastVoyageID);
var second = entities.log_ligne_voyage.Where(x => x.NUM_Voy == lastVoyageID).ToList();
var t = new Tuple<log_voyage, log_ligne_voyage>(first, second);
return View(t);
}
but I got this:
I don't know what to do? How do I use tuples?
this is the error :
Can not convert system.Linq.IQueryable into WebApplication.Models.log_voyage

var first = entities.log_voyage.Where(v => v.Num_Voy == lastVoyageID) returns collection but Tuple expects for a single object so it should be;
var first = entities.log_voyage.Where(v => v.Num_Voy == lastVoyageID).FirstOrDefault()
And this expression returns collection and Tuple seeks for just one object again
var second = entities.log_ligne_voyage.Where(x => x.NUM_Voy == lastVoyageID).ToList()
You might want to change the Tuple signature as Tuple<log_voyage, List<log_ligne_voyage>>
Finally,
public ActionResult Index( int id = 0 )
{
int lastVoyageID = entities.log_voyage.Max(item => item.Num_Voy);
var first = entities.log_voyage.Where(v => v.Num_Voy == lastVoyageID).FirstOrDefault();
log_voyage voyage1 = entities.log_voyage.Find(lastVoyageID);
var second = entities.log_ligne_voyage.Where(x => x.NUM_Voy == lastVoyageID).ToList();
var t = new Tuple<log_voyage, List<log_ligne_voyage>>(first, second);
return View(t);
}

Related

Dynamic map creation in terraform

I have a map passed as variable
dummy = {
1 = {
instances = {
"ip1" = {
a = "earth"
b = "hi"
c = 1
}
"ip2" = {
a = "world"
b = "hello"
c = 2
}
"ip3" = {
a = "planet"
b = "hey"
c = 3
}
}
}
}
Now I want construct a map as follows
value = {
"ip1" = {
b = "hi"
c = 1
}
"ip2" = {
b = "hello"
c = 2
}
"ip3" = {
b = "hey"
c = 3
}
}
I tried using for loops but nothing seems to work out
The following is what I have tried since
_meta = {
for instance in var.dummy.1.instances:
(instance.key) = {
b = instance.value.b
c = instance.value.c
}
}
But it says I cant access the key with for iteration variable
_meta = {
for key, instance in var.dummy.1.instances:
key => {
b = instance.b
c = instance.c
}
}
A for expression is a bit different from a for_each. You don't get key or value variables in a for expression and you can explicitly pull whole entries from the map as I've shown above using key, value in map as the expression form.
You also need to use a fat arrow => operator between the key and value of the generated map entries.

Kotlin .add overriding all items of list in MutableList

I have an object which contains a Mutable List
object TrackingEventsList {
var EventDate: String = ""
var EventDescription: String = ""
}
object Waybill {
var WaybillNumber: String = ""
var OriginHub: String = ""
var TrackingEvents: MutableList<TrackingEventsList> = ArrayList()
}
When I try to add Waybill.TrackingEvents all previous instances are overwritten to and duplicate the last TrackingEvent added.
private fun fillTracking(events: NodeList) {
var list = TrackingEventsList
for (x: Int in 0 until events.length) {
var tName = (events.item(x) as Element).tagName
var event = (events.item(x).firstChild as Text).wholeText
if (tName == "EventDate") {
list.EventDate = event
}
if (tName == "EventDescription") {
list.EventDescription = event
}
}
Waybill.TrackingEvents.plus(list)
}
The result after calling fillTracking 3 times:
Waybill.TrackingEvents[0].EventDescription = "Event3"
Waybill.TrackingEvents[1].EventDescription = "Event3"
Waybill.TrackingEvents[2].EventDescription = "Event3"
object in Kotlin is a singleton, which means you can't initialize it, and it only has one instance globally. So when you change the items of a single instance, you will override the previous data.
You should change both of them (or at least TrackingEventsList) to class instead. If Waybill's variables are instance-sensitive, it needs to be a class too. But in the code you added, I couldn't find anything that would say you use it as a singleton, so I left it as one.
class TrackingEventsList (
var eventDate: String = "",
var eventDescription: String = "")
/**
* Also want to point out that this is still a singleton. If the data inside is instance-specific, you need to change it
* to a class.
*/
object Waybill {
var waybillNumber: String = ""
var originHum: String = ""
var trackingEvents: MutableList<TrackingEventsList> = ArrayList()
}
private fun fillTracking(events: NodeList) {
val item = TrackingEventsList()
for (x: Int in 0 until events.length) {
var tName = (events.item(x) as Element).tagName
var event = (events.item(x).firstChild as Text).wholeText
if (tName == "EventDate") {
item.eventDate = event
}
if (tName == "EventDescription") {
item.eventDescription = event
}
}
Waybill.trackingEvents.add(item)
}
And you should look into the naming conventions for Kotlin; fields never start with an upper-case letter, unless it's a static constant (in which case it's all-upper)
Since TrackingEventsList is an object, it means it's a singleton (or only has a single instance.) When you go through your loop, you're always updating the same instance of your TrackingEventsList object.
Change TrackingEventsList to be this:
data class TrackingEventsList(var eventDate: String, var eventDescription: String)
Create a new instance each time you go through your loop, and then add it to your list at the end:
private fun fillTracking(events: NodeList) {
var eventDate: String = ""
var eventDescription: String = ""
for (x: Int in 0 until events.length) {
val tName = (events.item(x) as Element).tagName
val event = (events.item(x).firstChild as Text).wholeText
if (tName == "EventDate") {
eventDate = event
}
if (tName == "EventDescription") {
eventDescription = event
}
}
Waybill.TrackingEvents.plus(TrackingEventsList(eventDate, eventDescription))
}

Expression Lambda Func to string in c#

I want to get the string representation of a lambda Func<> Expression to get the Property Path. I have this example
Expression<Func<Employee, object>> _xxx = e => e.EmployeeInfo.Addresses["Address"];
and i am expecting a string
"EmployeeInfo.Addresses["Address"]"
when i do _xxx.ToString(); i'll just do some string parsing and i can get the result above.
My problem is when i do
var _addrName = "Address";
Expression<Func<Employee, object>> _xxx = e => e.EmployeeInfo.Addresses[_addrName];
i got a very long string
"EmployeeInfo.Addresses.get_Item(value(UnitTestProj.UnitTest.AnyTest+<>c__DisplayClass0)._addr)"
which is very hard to manipulate to come up with
"EmployeeInfo.Addresses["Address"]"
Is there any way to achieve my purpose?
TIA
This should get you pretty far - it's very hacky but I don't think there's a way around it:
Expression<Func<Employee, object>> _xxx = e => e.EmployeeInfo.Addresses[address];
WriteLine(ExprToString(_xxx)); //e.EmployeeInfo.Addresses[address]
_xxx = x => x.EmployeeInfo.Addresses["XYZ"];
WriteLine(ExprToString(_xxx)); //x.EmployeeInfo.Addresses["XYZ"]
_xxx = y => y.EmployeeInfo.Addresses[null];
WriteLine(ExprToString(_xxx)); //y.EmployeeInfo.Addresses[null]
_xxx = z => z.EmployeeInfo.Name;
WriteLine(ExprToString(_xxx)); //z.EmployeeInfo.Name
_xxx = z => z.EmployeeInfo.GetSalary();
WriteLine(ExprToString(_xxx)); //z.EmployeeInfo.GetSalary()
_xxx = z => z.EmployeeInfo.Addresses.Select(a => a.Street);
WriteLine(ExprToString(_xxx)); //z.EmployeeInfo.Addresses.Select(a.Street)
_xxx = z => z.EmployeeInfo.Array[3];
WriteLine(ExprToString(_xxx)); //z.EmployeeInfo.Array[3]
The implementation:
static string ExprToString(Expression expr)
{
switch (expr.NodeType)
{
case ExpressionType.Lambda:
//x => (Something), return only (Something), the Body
return ExprToString(((LambdaExpression) expr).Body);
case ExpressionType.Convert:
case ExpressionType.ConvertChecked:
//type casts are not important
return ExprToString(((UnaryExpression) expr).Operand);
case ExpressionType.Call:
//method call can be an Indexer (get_Item),
var callExpr = (MethodCallExpression) expr;
if (callExpr.Method.Name == "get_Item")
{
//indexer call
return ExprToString(callExpr.Object) + "[" + string.Join(",", callExpr.Arguments.Select(ExprToString)) + "]";
}
else
{
//method call
var arguments = callExpr.Arguments.Select(ExprToString).ToArray();
string target;
if (callExpr.Method.IsDefined(typeof (ExtensionAttribute), false))
{
//extension method
target = string.Join(".", arguments[0], callExpr.Method.Name);
arguments = arguments.Skip(1).ToArray();
}
else if (callExpr.Object == null)
{
//static method
target = callExpr.Method.Name;
}
else
{
//instance method
target = string.Join(".", ExprToString(callExpr.Object), callExpr.Method.Name);
}
return target + "(" + string.Join(",", arguments) + ")";
}
case ExpressionType.MemberAccess:
//property or field access
var memberExpr = (MemberExpression) expr;
if (memberExpr.Expression.Type.Name.Contains("<>")) //closure type, don't show it.
{
return memberExpr.Member.Name;
}
else
{
return string.Join(".", ExprToString(memberExpr.Expression), memberExpr.Member.Name);
}
}
//by default, show the standard implementation
return expr.ToString();
}

Convert Int to String in Swift

I'm trying to work out how to cast an Int into a String in Swift.
I figure out a workaround, using NSNumber but I'd love to figure out how to do it all in Swift.
let x : Int = 45
let xNSNumber = x as NSNumber
let xString : String = xNSNumber.stringValue
Converting Int to String:
let x : Int = 42
var myString = String(x)
And the other way around - converting String to Int:
let myString : String = "42"
let x: Int? = myString.toInt()
if (x != nil) {
// Successfully converted String to Int
}
Or if you're using Swift 2 or 3:
let x: Int? = Int(myString)
Check the Below Answer:
let x : Int = 45
var stringValue = "\(x)"
print(stringValue)
Here are 4 methods:
var x = 34
var s = String(x)
var ss = "\(x)"
var sss = toString(x)
var ssss = x.description
I can imagine that some people will have an issue with ss. But if you were looking to build a string containing other content then why not.
In Swift 3.0:
var value: Int = 10
var string = String(describing: value)
Swift 4:
let x:Int = 45
let str:String = String(describing: x)
Developer.Apple.com > String > init(describing:)
The String(describing:) initializer is the preferred way to convert an instance of any type to a string.
Custom String Convertible
Just for completeness, you can also use:
let x = 10.description
or any other value that supports a description.
Swift 4:
Trying to show the value in label without Optional() word.
here x is a Int value using.
let str:String = String(x ?? 0)
To save yourself time and hassle in the future you can make an Int extension. Typically I create a shared code file where I put extensions, enums, and other fun stuff. Here is what the extension code looks like:
extension Int
{
func toString() -> String
{
var myString = String(self)
return myString
}
}
Then later when you want to convert an int to a string you can just do something like:
var myNumber = 0
var myNumberAsString = myNumber.toString()
in swift 3.0 this is how we can convert Int to String and String to Int
//convert Integer to String in Swift 3.0
let theIntegerValue :Int = 123 // this can be var also
let theStringValue :String = String(theIntegerValue)
//convert String to Integere in Swift 3.0
let stringValue : String = "123"
let integerValue : Int = Int(stringValue)!
for whatever reason the accepted answer did not work for me. I went with this approach:
var myInt:Int = 10
var myString:String = toString(myInt)
Multiple ways to do this :
var str1:String="\(23)"
var str2:String=String(format:"%d",234)
let intAsString = 45.description // "45"
let stringAsInt = Int("45") // 45
Swift 2:
var num1 = 4
var numString = "56"
var sum2 = String(num1) + numString
var sum3 = Int(numString)
Swift String performance
A little bit about performance
UI Testing Bundle on iPhone 7(real device) with iOS 14
let i = 0
lt result1 = String(i) //0.56s 5890kB
lt result2 = "\(i)" //0.624s 5900kB
lt result3 = i.description //0.758s 5890kB
import XCTest
class ConvertIntToStringTests: XCTestCase {
let count = 1_000_000
func measureFunction(_ block: () -> Void) {
let metrics: [XCTMetric] = [
XCTClockMetric(),
XCTMemoryMetric()
]
let measureOptions = XCTMeasureOptions.default
measureOptions.iterationCount = 5
measure(metrics: metrics, options: measureOptions) {
block()
}
}
func testIntToStringConstructor() {
var result = ""
measureFunction {
for i in 0...count {
result += String(i)
}
}
}
func testIntToStringInterpolation() {
var result = ""
measureFunction {
for i in 0...count {
result += "\(i)"
}
}
}
func testIntToStringDescription() {
var result = ""
measureFunction {
for i in 0...count {
result += i.description
}
}
}
}
iam using this simple approach
String to Int:
var a = Int()
var string1 = String("1")
a = string1.toInt()
and from Int to String:
var a = Int()
a = 1
var string1 = String()
string1= "\(a)"
Convert Unicode Int to String
For those who want to convert an Int to a Unicode string, you can do the following:
let myInteger: Int = 97
// convert Int to a valid UnicodeScalar
guard let myUnicodeScalar = UnicodeScalar(myInteger) else {
return ""
}
// convert UnicodeScalar to String
let myString = String(myUnicodeScalar)
// results
print(myString) // a
Or alternatively:
let myInteger: Int = 97
if let myUnicodeScalar = UnicodeScalar(myInteger) {
let myString = String(myUnicodeScalar)
}
I prefer using String Interpolation
let x = 45
let string = "\(x)"
Each object has some string representation. This makes things simpler. For example if you need to create some String with multiple values. You can also do any math in it or use some conditions
let text = "\(count) \(count > 1 ? "items" : "item") in the cart. Sum: $\(sum + shippingPrice)"
exampleLabel.text = String(yourInt)
To convert String into Int
var numberA = Int("10")
Print(numberA) // It will print 10
To covert Int into String
var numberA = 10
1st way)
print("numberA is \(numberA)") // It will print 10
2nd way)
var strSomeNumber = String(numberA)
or
var strSomeNumber = "\(numberA)"
let a =123456888
var str = String(a)
OR
var str = a as! String
In swift 3.0, you may change integer to string as given below
let a:String = String(stringInterpolationSegment: 15)
Another way is
let number: Int = 15
let _numberInStringFormate: String = String(number)
//or any integer number in place of 15
If you like swift extension, you can add following code
extension Int
{
var string:String {
get {
return String(self)
}
}
}
then, you can get string by the method you just added
var x = 1234
var s = x.string
let Str = "12"
let num: Int = 0
num = Int (str)

Compare two big variables in javascript

I have 2 big variables, and I need to compare like:
var a = 15000000000000000000000001 // integer
var b = "15000000000000000000000000" // string
In all my test comparisons get wrong results.
eg:
Convert var b into a integer
var a = 15000000000000000000000001
var b = 15000000000000000000000000
a > b // return false and is wrong
Convert var a into a string
var a = "1500000000000000000000001"
var b = "15000000000000000000000000"
a > b // return true and is wrong
My solution:
function compareCheck(a,b){
if (a.length > b.length) {
return true;
}
else if (a.length == b.length) {
if (a.localeCompare(b) > 0) {
return true
}
else return false;
}
else return false;
}
var a = "15000000000000000000000001"
var b = "15000000000000000000000000"
compareCheck(a,b) // return true and is correct
var a = "1500000000000000000000001"
var b = "15000000000000000000000000"
compareCheck(a,b) // return false and is correct
My question is whether the solution found is the correct one, or will have problems in the future?
Here the standard practice I believe is to subtract one number from another and compare it with an epsilon value.

Resources