Inconsistent indent QGIS - qgis

I try to set some qwidgets on fields in a Qgis Project, but i have an error of inconsistent dedent at elif field.name() == 'syst':. Made so far:
def load(self):
map_layers = iface.legendInterface().layers()
for layer in map_layers:
if layer.name() == 'MAT_CANA':
mat_canaId = layer.id()
elif layer.name() == 'Collecteur':
CollecteurId = layer.id()
elif layer.name() == 'FORME_CHAMBRE':
FormeChambreId = layer.id()
elif layer.name() == 'Genre_Chambre':
GenreChambreId = layer.id()
elif layer.name() == 'MAT_CHMB_COU':
MaterialChambreCouId = layer.id()
elif layer.name() == 'PRECISION':
PrecisionId = layer.id()
elif layer.name() == 'SYSTEM_ECOULE':
SystemEcouleId = layer.id()
for layer in map_layers:
if '"public"."chambre_eau_provisoire"' in layer.source():
layer.setEditForm('C:/Users/george.vina/Desktop/BOUDRY/Forme/formeUi/chambrePr.ui')
fields = layer.pendingFields()
for field in fields:
if field.name() == 'genre_cham':
fieldIndex = layer.fieldNameIndex('genre_cham')
layer.setEditorWidgetV2(fieldIndex,'ValueRelation')
layer.setEditorWidgetV2Config(fieldIndex,{'Layer': GenreChambreId,'Key': 'genre_chambre', 'Value': 'genre_chambre'})
elif field.name() == 'syst':
fieldIndex = layer.fieldNameIndex('syst')
layer.setEditorWidgetV2(fieldIndex,'ValueRelation')
layer.setEditorWidgetV2Config(fieldIndex,{'Layer': SystemEcouleId,'Key': 'system_ecoule', 'Value': 'system_ecoule'})
elif field.name() == 'type_chamb':
fieldIndex = layer.fieldNameIndex('type_chamb')
layer.setEditorWidgetV2(fieldIndex,'ValueRelation')
layer.setEditorWidgetV2Config(fieldIndex,{'Layer': FormeChambreId,'Key': 'forme_chambre', 'Value': 'forme_chambre'})
elif field.name() == 'mat_chamb':
fieldIndex = layer.fieldNameIndex('mat_chamb')
layer.setEditorWidgetV2(fieldIndex,'ValueRelation')
layer.setEditorWidgetV2Config(fieldIndex,{'Layer': MaterialChambreCouId,'Key': 'mat_chmb_cou', 'Value': 'mat_chmb_cou'})
elif field.name() == 'type_couve':
fieldIndex = layer.fieldNameIndex('type_couve')
layer.setEditorWidgetV2(fieldIndex,'ValueRelation')
layer.setEditorWidgetV2Config(fieldIndex,{'Layer': MaterialChambreCouId,'Key': 'mat_chmb_cou', 'Value': 'mat_chmb_cou'})

Related

how do i use getter and setter in flutter?

Im trying to create tic tac toe game, but im getting some logical error when Im trying to use
provider method.
in the home page i have column containing three widget. first for player scores , second for gird layout, third for winner result.
i did some research and i found out using provider calss is the best option to send data from a widget to another.
import 'package:flutter/cupertino.dart';
import 'package:tictactoe/widgets/scores.dart';
import '../widgets/layout.dart';
// import '../widgets/scores.dart';
class GameProvider with ChangeNotifier {
bool oTrue = true;
List displayXO = ['', '', '', '', '', '', '', '', ''];
String resultDetection = 'hey';
int oScores = 0;
int xScores = 0;
int failedScores = 0;
checkWinner() {
// checking 1 row
if ((displayXO[0] == displayXO[1]) &&
(displayXO[0] == displayXO[2]) &&
displayXO[0] != '') {
resultDetection = 'player ' + displayXO[0] + 'wins';
print('$resultDetection');
}
// checking 2 row
if ((displayXO[3] == displayXO[4]) &&
(displayXO[3] == displayXO[5]) &&
(displayXO[3] != '')) {
resultDetection = 'player ' + displayXO[3] + 'wins';
}
// checking 3 row
if ((displayXO[6] == displayXO[7]) &&
(displayXO[6] == displayXO[8]) &&
(displayXO[6] != '')) {
resultDetection = 'player ' + displayXO[6] + 'wins';
}
// checking 1 column
if ((displayXO[0] == displayXO[3]) &&
(displayXO[0] == displayXO[6]) &&
(displayXO[0] != '')) {
resultDetection = 'player ' + displayXO[0] + 'wins';
}
// checking 2 column
if ((displayXO[1] == displayXO[4]) &&
(displayXO[1] == displayXO[7]) &&
(displayXO[1] != '')) {
resultDetection = 'player ' + displayXO[1] + 'wins';
}
// checking 3 column
if ((displayXO[2] == displayXO[5]) &&
(displayXO[2] == displayXO[8]) &&
(displayXO[2] != '')) {
resultDetection = 'player ' + displayXO[2] + 'wins';
}
// checking 1 axis
if ((displayXO[6] == displayXO[4]) &&
(displayXO[6] == displayXO[2]) &&
(displayXO[6] != '')) {
resultDetection = 'player ' + displayXO[6] + 'wins';
}
// checking 2 axis
if ((displayXO[0] == displayXO[4]) &&
(displayXO[0] == displayXO[8]) &&
(displayXO[0] != '')) {
resultDetection = 'player ' + displayXO[0] + 'wins';
}
notifyListeners();
}
set upgrateScores(String winner) {
if (winner == 'O') {
oScores++;
} else if (winner == 'X') {
xScores++;
}
print('$oScores, $xScores');
notifyListeners();
}
get winnerfunction => checkWinner();
// get upgrarate => upgrateScores();
get result => resultDetection;
}
and this is my great layout
Widget build(BuildContext context) {
void _tap() {}
return GridView.builder(
itemCount: 9,
gridDelegate:
SliverGridDelegateWithFixedCrossAxisCount(crossAxisCount: 3),
itemBuilder: ((context, index) {
return GestureDetector(
onTap: () {
tapped(index);
},
child: Container(
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(15),
border: Border.all(width: 5, color: Colors.red),
color: Colors.yellow,
),
child: Center(
child: Text(
displayXO[index],
style: GoogleFonts.coiny(fontSize: 64, color: Colors.red),
),
),
),
);
}));
}
void tapped(int tap) {
setState(() {
if (oTrue && displayXO[tap] == '') {
displayXO[tap] = 'O';
oTrue = false;
} else if (!oTrue && displayXO[tap] == '') {
displayXO[tap] = 'X';
oTrue = true;
}
print('object');
GameProvider provider = Provider.of<GameProvider>(context, listen: false);
provider.checkWinner();
});
}

Polars: Parallelizing creating a new dataframe while using groupby of another dataframe

I have an artifacts dataframe which I need to groupby some columns. This sub-dataframe is then passed to a function where I create a new dataframe.
for sub_df in merged_dataset.groupby(['PRODUCT','PROGRAM','TESTSUITE','MODULE', 'BASECLASS', 'SUBCLASS']):
flow_summary_df = sub_df.select(['PRODUCT','PROGRAM','TESTSUITE','MODULE', 'BASECLASS', 'SUBCLASS', 'VERSION', 'RELEASE_DATE', 'Status'])
current_test_events_dataset = add_test_events(flow_summary_df)
Here is the add_test_events code:
def add_test_events_new(flow_summary_df):
previous_test_status = None
known_versions = flow_summary_df.VERSION.to_list()
test_events = []
test_event_versions = []
test_events_data = {}
for i, version in enumerate(known_versions):
if i == 0:
test_events.append('Introduced')
test_event_versions.append(version)
if flow_summary_df.Status[i] == 'BINNING':
test_events.append('Binning Enabled')
test_event_versions.append(version)
previous_test_status = flow_summary_df.Status[i]
continue
if flow_summary_df.Status[i] == 'BYPASSED' and previous_test_status != 'BYPASSED':
test_events.append('Removed')
test_event_versions.append(version)
previous_test_status = 'BYPASSED'
elif flow_summary_df.Status[i] == 'BINNING' and previous_test_status != 'BINNING':
test_events.append('Binning Enabled')
test_event_versions.append(version)
previous_test_status = 'BINNING'
elif flow_summary_df.Status[i] == 'NON-BINNING' and previous_test_status == 'BINNING':
test_events.append('Binning Disabled')
test_event_versions.append(version)
previous_test_status = 'NON-BINNING'
elif flow_summary_df.Status[i] != 'BYPASSED' and previous_test_status == 'BYPASSED':
test_events.append('Re-Introduced')
test_event_versions.append(version)
if flow_summary_df.Status[i] == 'BINNING':
test_events.append('Binning Enabled')
for column in ['PRODUCT','PROGRAM','TESTSUITE','MODULE', 'BASECLASS', 'SUBCLASS', 'VERSION', 'RELEASE_DATE', 'TEST_EVENT']:
if column == 'TEST_EVENT':
test_events_data[column] = test_events
elif column == 'VERSION':
test_events_data[column] = test_event_versions
else:
if flow_summary_df[column][0] is None:
test_events_data[column] = [''] * len(test_events)
else:
test_events_data[column] = [flow_summary_df[column][0]] * len(test_events)
test_events_df = pl.DataFrame(test_events_data)
return test_events_df
It just feels like this is not the polars way to do things.
thx

I got a garbled message in arduino while sending data from app (using flutter) to ESP8266

The problem which I'm facing is that sending data from my phone to the ESP8266 is garbled... (I use NodeMCU's Amica)
I am using a package in Flutter which uses the WebSocket principle.
When I start the app, it connects fine. I get messages for a WebSocket handshake just fine, so I complete the handshake just fine. But when I send data from my Flutter app, it doesn't seem to work...
The code I have in Flutter:
import 'package:flutter/foundation.dart';
import 'package:web_socket_channel/io.dart';
import 'package:flutter/material.dart';
import 'package:web_socket_channel/web_socket_channel.dart';
var ip = 'ws://192.168.1.53:5555';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
final title = 'WebSocket Demo';
return MaterialApp(
title: title,
home: MyHomePage(
title: title,
channel: IOWebSocketChannel.connect(ip),
),
);
}
}
class MyHomePage extends StatefulWidget {
final String title;
final WebSocketChannel channel;
MyHomePage({Key key, #required this.title, #required this.channel})
: super(key: key);
#override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
TextEditingController _controller = TextEditingController();
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
),
body: Padding(
padding: const EdgeInsets.all(20.0),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
Form(
child: TextFormField(
controller: _controller,
decoration: InputDecoration(labelText: 'Send a message'),
),
),
StreamBuilder(
stream: widget.channel.stream,
builder: (context, snapshot) {
return Padding(
padding: const EdgeInsets.symmetric(vertical: 24.0),
child: Text(snapshot.hasData ? '${snapshot.data}' : ''),
);
},
)
],
),
),
floatingActionButton: FloatingActionButton(
onPressed: _sendMessage,
tooltip: 'Send message',
child: Icon(Icons.send),
), // This trailing comma makes auto-formatting nicer for build methods.
);
}
void _sendMessage() {
if (_controller.text.isNotEmpty) {
widget.channel.sink.add(_controller.text);
}
}
#override
void dispose() {
widget.channel.sink.close();
super.dispose();
}
}
I got this code from "https://flutter.dev/docs/cookbook/networking/web-sockets".
This is just to test if it would work, the real coding will be later...
I changed the IP, and that's it.
In Arduino the code is this:
String Version = "===================================\r\n===================================\r\n===================================\r\n [NAMEHERE] v1.0\r\nBugs to fix:\r\n o N/A\r\n===================================\r\n===================================\r\n===================================\r\n";
bool keySent = true;
String Key;
char ThrowAway;
String StringSlice;
String HexToBinary;
int HexToNumber;
String EncodedKey = "";
int Count = 0;
#include <ESP8266WiFi.h>
#include <Hash.h>
#include <rBase64.h>
WiFiServer wifiServer(5555);
const char* ssid = "[NAME]";
const char* password = "[PASSWORD]";
void setup() {
Serial.begin(115200);
delay(1000);
Serial.println(Version);
IPAddress ip(192, 168, 1, 53);
IPAddress gateway(192, 168, 1, 1);
IPAddress subnet(255, 255, 255, 0);
WiFi.config(ip, gateway, subnet);
WiFi.begin(ssid, password);
while(WiFi.status() != WL_CONNECTED) {
delay(1000);
Serial.println("Connecting ...");
}
Serial.print("Connected to WiFi. IP: ");
Serial.println(WiFi.localIP());
wifiServer.begin();
}
void loop() {
WiFiClient client = wifiServer.available();
if(client) {
while(client.connected()) {
while(client.available() > 0) {
char c = client.read();
//Reading key if applicable
Serial.write(c);
if(c == 'k') {
c = client.read();
Serial.write(c);
if(c == 'e') {
c = client.read();
Serial.write(c);
if(c == 'y') {
c = client.read();
Serial.write(c);
if(c == ':') {
c = client.read();
Serial.write(c);
c = client.read();
while(c != '=') {
Serial.write(c);
Key = Key + c;
c = client.read();
}
while(c == '=') {
Serial.write(c);
Key = Key + c;
c = client.read();
}
Serial.print(c);
calculateKey();
keySent = false;
}
}
}
}
}
if(keySent == false) {
Serial.println("SENT:");
Serial.write("HTTP/1.1 101 Switching Protocols\r\nUpgrade: websocket\r\nConnection: Upgrade\r\nSec-WebSocket-Accept: ");
client.write("HTTP/1.1 101 Switching Protocols\r\nUpgrade: websocket\r\nConnection: Upgrade\r\nSec-WebSocket-Accept: ");
Serial.println(Key);
client.print(Key);
client.write("\r\n\r\n");
keySent = true;
}
delay(10);
}
client.stop();
Serial.println("Client disconnected");
Serial.println("###################");
Key = "";
EncodedKey = "";
Count = 0;
}
}
void calculateKey(){
Serial.println();
Serial.println();
Serial.println("Calculating new key...");
Key = Key + "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";
Serial.print("Concatenating that with certain string: ");
Serial.println(Key);
Key = sha1(Key);
Serial.print("Sha1 hash applied to key: ");
Serial.println(Key);
hexToBase64();
Serial.print("And encoded in base64: ");
Key = EncodedKey;
Serial.println(Key);
Serial.println();
}
String binaryToBase64(String x) {
if(x == "000000")
return "A";
else if(x == "000001")
return "B";
else if(x == "000010")
return "C";
else if(x == "000011")
return "D";
else if(x == "000100")
return "E";
else if(x == "000101")
return "F";
else if(x == "000110")
return "G";
else if(x == "000111")
return "H";
else if(x == "001000")
return "I";
else if(x == "001001")
return "J";
else if(x == "001010")
return "K";
else if(x == "001011")
return "L";
else if(x == "001100")
return "M";
else if(x == "001101")
return "N";
else if(x == "001110")
return "O";
else if(x == "001111")
return "P";
else if(x == "010000")
return "Q";
else if(x == "010001")
return "R";
else if(x == "010010")
return "S";
else if(x == "010011")
return "T";
else if(x == "010100")
return "U";
else if(x == "010101")
return "V";
else if(x == "010110")
return "W";
else if(x == "010111")
return "X";
else if(x == "011000")
return "Y";
else if(x == "011001")
return "Z";
else if(x == "011010")
return "a";
else if(x == "011011")
return "b";
else if(x == "011100")
return "c";
else if(x == "011101")
return "d";
else if(x == "011110")
return "e";
else if(x == "011111")
return "f";
else if(x == "100000")
return "g";
else if(x == "100001")
return "h";
else if(x == "100010")
return "i";
else if(x == "100011")
return "j";
else if(x == "100100")
return "k";
else if(x == "100101")
return "l";
else if(x == "100110")
return "m";
else if(x == "100111")
return "n";
else if(x == "101000")
return "o";
else if(x == "101001")
return "p";
else if(x == "101010")
return "q";
else if(x == "101011")
return "r";
else if(x == "101100")
return "s";
else if(x == "101101")
return "t";
else if(x == "101110")
return "u";
else if(x == "101111")
return "v";
else if(x == "110000")
return "w";
else if(x == "110001")
return "x";
else if(x == "110010")
return "y";
else if(x == "110011")
return "z";
else if(x == "110100")
return "0";
else if(x == "110101")
return "1";
else if(x == "110110")
return "2";
else if(x == "110111")
return "3";
else if(x == "111000")
return "4";
else if(x == "111001")
return "5";
else if(x == "111010")
return "6";
else if(x == "111011")
return "7";
else if(x == "111100")
return "8";
else if(x == "111101")
return "9";
else if(x == "111110")
return "+";
else if(x == "111111")
return "/";
}
void hexToBase64() {
WiFiClient client = wifiServer.available();
for(;;) {
StringSlice = Key.substring(Count,Count+1);
Serial.print(StringSlice);
if(StringSlice == "0")
HexToBinary = "0000";
else if(StringSlice == "1")
HexToBinary = "0001";
else if(StringSlice == "2")
HexToBinary = "0010";
else if(StringSlice == "3")
HexToBinary = "0011";
else if(StringSlice == "4")
HexToBinary = "0100";
else if(StringSlice == "5")
HexToBinary = "0101";
else if(StringSlice == "6")
HexToBinary = "0110";
else if(StringSlice == "7")
HexToBinary = "0111";
else if(StringSlice == "8")
HexToBinary = "1000";
else if(StringSlice == "9")
HexToBinary = "1001";
else if(StringSlice == "a")
HexToBinary = "1010";
else if(StringSlice == "b")
HexToBinary = "1011";
else if(StringSlice == "c")
HexToBinary = "1100";
else if(StringSlice == "d")
HexToBinary = "1101";
else if(StringSlice == "e")
HexToBinary = "1110";
else if(StringSlice == "f")
HexToBinary = "1111";
else
break;
Serial.print(" = ");
Serial.println(HexToBinary);
Count++;
StringSlice = Key.substring(Count,Count+1);
if(StringSlice == "0" || StringSlice == "1" || StringSlice == "2" || StringSlice == "3")
HexToBinary = HexToBinary + "00";
else if(StringSlice == "4" || StringSlice == "5" || StringSlice == "6" || StringSlice == "7")
HexToBinary = HexToBinary + "01";
else if(StringSlice == "8" || StringSlice == "9" || StringSlice == "a" || StringSlice == "b")
HexToBinary = HexToBinary + "10";
else if(StringSlice == "c" || StringSlice == "d" || StringSlice == "e" || StringSlice == "f")
HexToBinary = HexToBinary + "11";
else {
HexToBinary = HexToBinary + "00";
EncodedKey = EncodedKey + binaryToBase64(HexToBinary);
EncodedKey = EncodedKey + "=";
break;
}
EncodedKey = EncodedKey + binaryToBase64(HexToBinary);
StringSlice = Key.substring(Count,Count+1);
HexToBinary = "";
if(StringSlice == "0" || StringSlice == "4" || StringSlice == "8" || StringSlice == "c")
HexToBinary = "00";
else if(StringSlice == "1" || StringSlice == "5" || StringSlice == "9" || StringSlice == "d")
HexToBinary = "01";
else if(StringSlice == "2" || StringSlice == "6" || StringSlice == "a" || StringSlice == "e")
HexToBinary = "10";
else if(StringSlice == "3" || StringSlice == "7" || StringSlice == "b" || StringSlice == "f")
HexToBinary = "11";
Count++;
StringSlice = Key.substring(Count,Count+1);
Serial.print(StringSlice);
if(StringSlice == "0")
HexToBinary = HexToBinary + "0000";
else if(StringSlice == "1")
HexToBinary = HexToBinary + "0001";
else if(StringSlice == "2")
HexToBinary = HexToBinary + "0010";
else if(StringSlice == "3")
HexToBinary = HexToBinary + "0011";
else if(StringSlice == "4")
HexToBinary = HexToBinary + "0100";
else if(StringSlice == "5")
HexToBinary = HexToBinary + "0101";
else if(StringSlice == "6")
HexToBinary = HexToBinary + "0110";
else if(StringSlice == "7")
HexToBinary = HexToBinary + "0111";
else if(StringSlice == "8")
HexToBinary = HexToBinary + "1000";
else if(StringSlice == "9")
HexToBinary = HexToBinary + "1001";
else if(StringSlice == "a")
HexToBinary = HexToBinary + "1010";
else if(StringSlice == "b")
HexToBinary = HexToBinary + "1011";
else if(StringSlice == "c")
HexToBinary = HexToBinary + "1100";
else if(StringSlice == "d")
HexToBinary = HexToBinary + "1101";
else if(StringSlice == "e")
HexToBinary = HexToBinary + "1110";
else if(StringSlice == "f")
HexToBinary = HexToBinary + "1111";
else {
HexToBinary = HexToBinary + "0000";
EncodedKey = EncodedKey + binaryToBase64(HexToBinary);
EncodedKey = EncodedKey + "==";
break;
}
Count++;
EncodedKey = EncodedKey + binaryToBase64(HexToBinary);
}
Serial.println("#############################################");
Serial.println(EncodedKey);
}
I'll be cleaning this code up later... The bulk of what matters is upwards...
I changed the names of some stuff, for the privacy of the people whom I do this for.
My log resembles something like this:
Flutter sends WebSocket key.
Key sent back by ESP...
Message from App:
⸮⸮uD⸮ZD⸮⸮⸮⸮□⸮⸮□⸮
I tried to send something like "Hello World" or "test"
Those weird characters are multiple messages by the way...
Just to verify, the key is right.
If I were to send a wrong key back, it would disconnect.
Does anyone have any idea why this happens?
I think it is something with the timings of which messages get sent or received.
If there is anything I need to add, please tell me.

EF other way to Sum() new Column

i got stuck on this query that calculate the new column.
i cannot explain briefly just see the snippet code below.
from user in context.Table
select new
{
Total = user.Total,
Paid = user.Paid,
Balance = //should be Total - Paid to assign result
}
i have tried this query
var result = from a in context.EnrollmentRequests
where a.SchoolYear == SchoolYear
select new
{
a.StudentID,
Name = a.Student.FirstName + " " + a.Student.MiddleName + " " + a.Student.LastName,
Tuition = context.Miscs.Where(m => m.YearLevel == a.YearLevel && m.SchoolYear == SchoolYear && m.Term == a.Term && m.CourseID == a.CourseID)
.Select(ms => new { Amount = ms.Amount })
.Union(context.StudentCharges
.Where(s => s.YearLevel == a.YearLevel && s.SchoolYear == SchoolYear && s.Term == a.Term && s.CourseID == a.CourseID && s.StudentID == a.StudentID)
.Select(ss => new { Amount = ss.Amount }))
.Union(context.StudentSubjectTakes
.Where(st => st.StudentID == a.StudentID && st.SchoolYear == a.SchoolYear && st.Term == a.Term && st.YearLevel == a.YearLevel && st.EducationalLevel == a.Student.StudentAdvanceEducations.FirstOrDefault().EducationLevel)
.Select(st => new
{
Amount = context.SubjectOfferedFees
.Where(f => f.SubjectsOfferedID == st.SubjectsOfferedID).Sum(w => (decimal?)w.Cost ?? 0)
}))
.Select(f => f.Amount).Sum(),
PaymentMade = context.Payments.Where(p => p.SchoolYear == SchoolYear && p.Term == a.Term && p.StudentID == a.StudentID && p.PaymentDes == "Tuition Fee").Sum(sm => (decimal?)sm.Amount),
Balance = Tuition - PaymentMade //Does not exist on current context
};
but doesn't work it says that does not exist on current context.
how could this possible.
thanks. this will be helpful to anyone.
Balance = user.Total - user.Paid

Is it a lazy loading query or Eager Loading ? , Slow Query, Performance needed please

First, I would like to know if this query is Lazy loading or Eager loading. I Read a lot on both, and not sure if I understand the difference between each other.
2- I Get this query, This query take a lot of time to execute. Anybody have some suggest when you see this query. I'll do all modification needed to speed up this query.
Note: I just want your opinion about this query and method.
Thanks a lot.
public SearchLocationViewModel GetSearchLocationViewModel( string CivicNumber = null ,
string Street = null,
string City = null,
List<int?> ListCountryID = null,
List<int?> ListStateID = null,
int IsActive =1,
string SortField ="FileNumber",
string SortDirection = "asc" ,
List<int?> GrpDescID1 = null,
List<int?> GrpDescID2 = null,
List<int?> GrpDescID3 = null,
List<int?> GrpDescID4 = null,
int LocationTypeID = -1,
List<int?> ListUsageID = null)
{
if (GrpDescID1 == null)
{
GrpDescID1 = new List<int?>();
}
if (GrpDescID2 == null)
{
GrpDescID2 = new List<int?>();
}
if (GrpDescID3 == null)
{
GrpDescID3 = new List<int?>();
}
if (GrpDescID4 == null)
{
GrpDescID4 = new List<int?>();
}
if (ListCountryID == null)
{
ListCountryID = new List<int?>();
}
if (ListStateID == null)
{
ListStateID = new List<int?>();
}
if (ListUsageID == null)
{
ListUsageID = new List<int?>();
}
GrpDescID1.Remove(GrpDescID1.SingleOrDefault(p => p < 0));
GrpDescID2.Remove(GrpDescID2.SingleOrDefault(p => p < 0));
GrpDescID3.Remove(GrpDescID3.SingleOrDefault(p => p < 0));
GrpDescID4.Remove(GrpDescID4.SingleOrDefault(p => p < 0));
ListCountryID.Remove(ListCountryID.SingleOrDefault(p => p < 0));
ListStateID.Remove(ListStateID.SingleOrDefault(p => p < 0));
ListUsageID.Remove(ListUsageID.SingleOrDefault(p => p < 0));
int lang = BaseStaticClass.CurrentLangID();
int UserID = Convert.ToInt32(Session["UserID"]);
SearchLocationViewModel ViewModel = InitSearchViewModel();
IGrpRepository repGrp = new GrpRepository(_db);
ICountryRepository repCountry = new CountryRepository(_db);
IProvinceRepository repProvince = new ProvinceRepository(_db);
ViewModel.Perm = repPermission;
ViewModel. CivicNumber = CivicNumber ;
ViewModel. Street = Street;
ViewModel. City = City;
ViewModel. IsActive =IsActive;
ViewModel. SortField =SortField;
ViewModel. SortDirection = SortDirection ;
ViewModel.ListCountry = repCountry.GetCountryForSearchByUser(true,UserID);
ViewModel.ListProvince = repProvince.GetProvinceSearchByUserID(true, UserID);
ViewModel.ListGrpDescID1 =GrpDescID1;
ViewModel.ListGrpDescID2 = GrpDescID2;
ViewModel.ListGrpDescID3 = GrpDescID3;
ViewModel.ListGrpDescID4 = GrpDescID4;
ViewModel.ListCountryID = ListCountryID;
ViewModel.ListStateID = ListStateID;
ViewModel.LocationTypeID = LocationTypeID;
ViewModel.ListUsageID = ListUsageID;
var LocationType = new SelectList(repGeneric.GetTextByCurrentLang<LocationType, LocationTypeText>(), "ID", "Txt").ToList();
bc.AddDropdownSearchValueNoNew(ref LocationType);
var ListUsage = new SelectList(repGeneric.GetTextByCurrentLang<Usage, UsageText>(), "ID", "Txt").ToList();
ViewModel.ListUsage = ListUsage;
ViewModel.ListLocationType = LocationType;
var ListGrp1 = new SelectList(repGrp.GetAllGrpDescTextForUserByLevel(UserID, 1).AsEnumerable(), "GrpDescID", "GrpDescTxt").ToList();
var ListGrp2 = new SelectList(repGrp.GetAllGrpDescTextForUserByLevel(UserID, 2).AsEnumerable(), "GrpDescID", "GrpDescTxt").ToList();
var ListGrp3 = new SelectList(repGrp.GetAllGrpDescTextForUserByLevel(UserID, 3).AsEnumerable(), "GrpDescID", "GrpDescTxt").ToList();
var ListGrp4 = new SelectList(repGrp.GetAllGrpDescTextForUserByLevel(UserID, 4).AsEnumerable(), "GrpDescID", "GrpDescTxt").ToList();
var t1 = ListGrp1.Select(s => (int?)Convert.ToInt32(s.Value));
var t2 = ListGrp2.Select(s => (int?)Convert.ToInt32(s.Value));
var t3 = ListGrp3.Select(s => (int?)Convert.ToInt32(s.Value));
var t4 = ListGrp4.Select(s => (int?)Convert.ToInt32(s.Value));
ViewModel.ListGrp1 = ListGrp1;
ViewModel.ListGrp2 = ListGrp2;
ViewModel.ListGrp3 = ListGrp3;
ViewModel.ListGrp4 = ListGrp4;
ViewModel.ListGrpTogether = new List<SelectListItem>();
if(ViewModel.GrpName1 != "")
ViewModel.ListGrpTogether.Add(new SelectListItem() { Text = ViewModel.GrpName1 ,Value = "1"});
if (ViewModel.GrpName2 != "")
ViewModel.ListGrpTogether.Add(new SelectListItem() { Text = ViewModel.GrpName2, Value = "2" });
if (ViewModel.GrpName3 != "")
ViewModel.ListGrpTogether.Add(new SelectListItem() { Text = ViewModel.GrpName3, Value = "3" });
if (ViewModel.GrpName4 != "")
ViewModel.ListGrpTogether.Add(new SelectListItem() { Text = ViewModel.GrpName4, Value = "4" });
ViewModel.ListGrpTogether.Insert(0, new SelectListItem() { Text = ViewRes.GeneralString.Choose, Value = "-1", Selected = true });
int iUserID = Convert.ToInt32(Session["UserID"]);
//this is use for Permission
//Get all the user permission about group and province
IEnumerable<int?> usrGrpDesc = _db.UserGroupDescs.Where(p => p.UserID == iUserID).Select(s => s.GrpDescID);
IEnumerable<int?> usrProvince = _db.UserProvinces.Where(p => p.UserID == iUserID).Select(s => s.PrvID);
var ListLocation = from s in _db.Locations.Where(p =>
p.IsDelete == false &&
(IsActive < 0 || IsActive == (p.IsActive == true ? 1 : 0)) &&
(LocationTypeID < 0 || LocationTypeID == p.LocationTypeID) &&
(City == null || p.Address.City.CityName.Contains(City)) &&
(ListUsageID.Count() == 0 || p.Premises.Select(gs => gs.UsageID).Intersect(ListUsageID).Any()) &&
(ListCountryID.Count() == 0 || ListCountryID.Any(pl => pl == p.Address.City.Province.Country.CtryID)) &&
(ListStateID.Count() == 0 || ListStateID.Any(pl => pl == p.Address.City.Province.PrvID)) &&
(Street == null || p.Address.Street.Contains(Street)) &&
(CivicNumber == null || p.Address.CivicNumber.Contains(CivicNumber)) &&
((GrpDescID1.Count() == 0 )|| p.GroupLocations.Select(gs => gs.GrpDescID).Intersect(GrpDescID1).Any()) &&
((GrpDescID2.Count() == 0)|| p.GroupLocations.Select(gs => gs.GrpDescID).Intersect(GrpDescID2).Any()) &&
((GrpDescID3.Count() == 0) || p.GroupLocations.Select(gs => gs.GrpDescID).Intersect(GrpDescID3).Any()) &&
((GrpDescID4.Count() == 0 ) || p.GroupLocations.Select(gs => gs.GrpDescID).Intersect(GrpDescID4).Any()) &&
(p.GroupLocations.Select(gs => gs.GrpDescID).Intersect(usrGrpDesc).Any()) &&
((p.Address.City == null || usrProvince.Any(ps => ps.Value == p.Address.City.PrvID)))
)
select new LocationViewModel()
{
LocationID = s.LocationID,
LocationTypeID = s.LocationTypeID,
Long = s.Address.Longitude,
Lat = s.Address.Latitude,
FileNumber = s.LocationFile,
State = s.Address.City.Province.PrvName,
City = s.Address.City.CityName,
Address = s.Address.CivicNumber + " " + s.Address.Street,
Status = s.LocationType.LocationTypeTexts.Where(h => h.Txt != "" && h.LangID == lang || h.LangID == 1).OrderByDescending(g => g.LangID).FirstOrDefault().Txt,
ListGroupe1 = s.GroupLocations.Where(g=>g.GrpDesc.Grp.GrpLevel == 1).Select(grpLoc => grpLoc.GrpDesc.GrpDescTexts.Where(h => h.GrpDescTxt != "" && (h.LangID == lang || h.LangID == 1)).OrderByDescending(g => g.LangID).FirstOrDefault()).Select(txt => txt.GrpDescTxt),
ListGroupe2 = s.GroupLocations.Where(g => g.GrpDesc.Grp.GrpLevel == 2).Select(grpLoc => grpLoc.GrpDesc.GrpDescTexts.Where(h => h.GrpDescTxt != "" && (h.LangID == lang || h.LangID == 1)).OrderByDescending(g => g.LangID).FirstOrDefault()).Select(txt => txt.GrpDescTxt),
ListGroupe3 = s.GroupLocations.Where(g=>g.GrpDesc.Grp.GrpLevel == 3).Select(grpLoc => grpLoc.GrpDesc.GrpDescTexts.Where(h => h.GrpDescTxt != "" && (h.LangID == lang || h.LangID == 1)).OrderByDescending(g => g.LangID).FirstOrDefault()).Select(txt => txt.GrpDescTxt),
ListGroupe4 = s.GroupLocations.Where(g=>g.GrpDesc.Grp.GrpLevel == 4).Select(grpLoc => grpLoc.GrpDesc.GrpDescTexts.Where(h => h.GrpDescTxt != "" && (h.LangID == lang || h.LangID == 1)).OrderByDescending(g => g.LangID).FirstOrDefault()).Select(txt => txt.GrpDescTxt),
DefaultImgPath = s.LocationPictures.Where(p=>p.IsDefault == true && p.IsActive == true).FirstOrDefault().FilePath,
HasPremises = s.Premises.Any(p => p.IsActive == true && p.IsDelete == false)
};
ViewModel.ListLocation = ListLocation.ToList();
return ViewModel;
}
Lazy loading is deferring initialization of an object until the point at which it is needed. If you returned your ListLocation back to its caller, as you've written above, with no .ToList() (or other), then you'd be consuming this lazily.
Eager loading is having the results of your query gathered at the time that the query is defined. In this case it'd be retrieving the results of your LINQ query all at once (at the time that the query is constrcuted). Usually a .ToList() or .Single() or other will do this for you.
I suspect you're consuming the results your LINQ query (var ListLocation) later in your code. Your code above is using a lazy-loaded approach.
You're showing that you're calling .ToList(), so you're indeed using eager-loading; even though it's on a different statement/line of code.
Performance: I'm not 100% on this being your perf problem, but I'd refactor your LINQ into something like this, using an extension method .WhereIf(). It's a heck of a lot easier to read and write.
var ListLocation = from s in _db.Locations
.Where(p => p.IsDelete == false)
.WhereIf(IsActive >= 0, p=> IsActive == (p.IsActive == true ? 1 : 0))
.WhereIf(LocationTypeID >= 0, p=> LocationTypeID == p.LocationTypeID
.WhereIf(City!=null, p=> p.Address.City.CityName.Contains(City)) //etc
If you're using this, and it works, then you're probably lazy loading, since you don't have any calls to .Include().