The method 'Equals' is not supported - subsonic

public List<Health_Scheme_System.Employee> GetPenEmployeeTable()
{
Health_Scheme_System.Health_Scheme_SystemDB db = new Health_Scheme_System.Health_Scheme_SystemDB();
var x = (from c in db.Employees
where c.Pensioners.Equals (1)
select c);
return x.ToList();
}
//Selecting multiple columns from an HR view table together with the scheme name of scheme.
public List<EmployeesX> GetPensioners()
{
Health_Scheme_System.Health_Scheme_SystemDB db = new Health_Scheme_System.Health_Scheme_SystemDB();
List<Health_Scheme_System.EmployeeDirectory> listEmployeeView = GetPenEmployeeView();
List<Health_Scheme_System.Employee> listEmployeeTable = GetPenEmployeeTable();
List<Health_Scheme_System.Scheme> listSchemes = GetSchemes();
List<EmployeesX> listOfEmployees = new List<EmployeesX>();
//checking for comparision of getemployeeview to getemployee table and then to getschemes
//Then display the scheme name if they are similar.
for (int i = 0; i < listEmployeeView.Count; i++)
{
EmployeesX emp = new EmployeesX();
emp.ID_NO = listEmployeeView[i].ID_NO;
emp.FIRST_NAME = listEmployeeView[i].FIRST_NAME;
emp.LAST_NAME = listEmployeeView[i].LAST_NAME;
emp.LOCATION_CODE = listEmployeeView[i].LOCATION_CODE;
for (int j = 0; j < listEmployeeTable.Count; j++)
{
if (listEmployeeTable[j].EmployeeIDCard == listEmployeeView[i].ID_NO)
{
emp.Pensioners = listEmployeeTable[j].Pensioners;
for (int k = 0; k < listSchemes.Count; k++)
{
if (listEmployeeTable[j].SchemeID == listSchemes[k].SchemeID)
{
emp.SCHEME_NAME = listSchemes[k].Name;
emp.START_DATE = listEmployeeTable[j].StartSchemeDate;
}
}
}
}
listOfEmployees.Add(emp);
}
return listOfEmployees;
}
How can I make the same method with using .equals??

Have you tried this:
var x = (from c in db.Employees
where c.Pensioners == 1
select c)
Additional info:
If you use a method on an object in a linq query subsonic needs to know how to translate that into pur SQL code. That does not work by default and must be implemented for every known method on every supported type for every dataprovider (if differs from default implementation). So there is a bunch of work to do for subsonic.
A good starting point for knowning what's supported and what not is the TSqlFormatter class. Have a look at protected override Expression VisitMethodCall(MethodCallExpression m)
https://github.com/subsonic/SubSonic-3.0/blob/master/SubSonic.Core/Linq/Structure/TSqlFormatter.cs
There is already an implementation for Equals
else if (m.Method.Name == "Equals")
{
if (m.Method.IsStatic && m.Method.DeclaringType == typeof(object))
{
sb.Append("(");
this.Visit(m.Arguments[0]);
sb.Append(" = ");
this.Visit(m.Arguments[1]);
sb.Append(")");
return m;
}
else if (!m.Method.IsStatic && m.Arguments.Count == 1 && m.Arguments[0].Type == m.Object.Type)
{
sb.Append("(");
this.Visit(m.Object);
sb.Append(" = ");
this.Visit(m.Arguments[0]);
sb.Append(")");
return m;
}
else if (m.Method.IsStatic && m.Method.DeclaringType == typeof(string))
{
//Note: Not sure if this is best solution for fixing side issue with Issue #66
sb.Append("(");
this.Visit(m.Arguments[0]);
sb.Append(" = ");
this.Visit(m.Arguments[1]);
sb.Append(")");
return m;
}
}
I suppose Prnsioners is an integer type so you basically have to add another else if and recomplie subsonic.
This should work but I haven't tested it.
else if (!m.Method.IsStatic && m.Method.DeclaringType == typeof(int))
{
sb.Append("(");
this.Visit(m.Arguments[0]);
sb.Append(" = ");
this.Visit(m.Arguments[1]);
sb.Append(")");
return m;
}
(or you can try the == approach like in the example on the top).

Related

MT5/MQL5 How to make 6 trades with different currency

I have manage to open up 6 charts for 6 different currency pairs. Instead of open up position on 6 different pairs, it made 6 trades of the same pair. How do I fix it?
string symbol[];
for(int i=0; i > maxNoOfTrades; i--)
{
symbol[i]=PositionGetString(POSITION_SYMBOL);
if(symbol[i]==EURUSD)
return true;
if(symbol[i]==GBPUSD)
return true;
if(symbol[i]==USDJPY)
return true;
if(symbol[i]==USDCHF)
return true;
if(symbol[i]==USDCAD)
return true;
if(symbol[i]==AUDUSD)
return true;
}
return false;
If you want to open a marked Order directly, it is called Position in MQL5.
So you have to open a Position.
Opening a Order will not be marked, only e.g. a Stop / StopLimit Order.
Opening a Position e.g. by following Code:
void OpenBuyPosition(){
for (int attempt = 0; attempt < TRADE_RETRY_COUNT; attempt++){
// Vorbereitung / Zuordnung der Variablen
double lots = Entry_Amount;
ulong ticket = posTicket;
MqlTradeRequest request;
MqlTradeResult result;
ZeroMemory(request);
ZeroMemory(result);
request.action = TRADE_ACTION_DEAL;
request.symbol = _Symbol;
request.volume = lots;
request.type = ORDER_TYPE_BUY;
request.price = Ask();
//request.type_filling = ORDER_FILLING_FOK;
request.type_filling = orderFillingType;
request.deviation = 10;
//request.sl = stopLoss;
request.sl = 0;
//request.tp = takeProfit;
request.tp = 0;
request.magic = Magic_Number;
request.position = ticket;
request.comment = IntegerToString(Magic_Number);
bool isOrderCheck = CheckOrder(request);
bool isOrderSend = false;
if (isOrderCheck){
ResetLastError();
isOrderSend = OrderSend(request, result);
}
if (isOrderCheck && isOrderSend && result.retcode == TRADE_RETCODE_DONE){
return;
}
Sleep(TRADE_RETRY_WAIT);
Print("Order Send retry no: " + IntegerToString(attempt + 2));
}
}
You can switch the variable for your needed Symbol with you own code.
Also the Type from Buy to Sell ;-)

How to create sourcemaps for concatenated files

I want to concatenate a bunch of different files of a single type into one large file. For example, many javascript files into one large file, many css files down to one etc. I want to create a sourcemap of the files pre concatenation, but I do not know where to start. I am working in Node, but I am also open to solutions in other environments.
I know there are tools that can do this, but they seem to be on a language by language basis (uglifyjs, cssmin or whatever its called these days), but I want a tool that is not language specific.
Also, I would like to define how the files are bound. For example, in javascript I want to give each file its own closure with an IIFE. Such as:
(function () {
// File
}());
I can also think of other wrappers I would like to implement for different files.
Here are my options as I see it right now. However, I don't know which is best or how to start any of them.
Find a module that does this (I'm working in a Node.js environment)
Create an algorithm with Mozilla's source-map module. For that I also see a couple options.
Only map each line to the new line location
Map every single character to the new location
Map every word to its new location (this options seems way out of scope)
Don't even worry about source maps
What do you guys think about these options. I've already tried options 2.1 and 2.2, but the solution seemed way too complicated for a concatenation algorithm and it did not perform perfectly in the Google Chrome browser tools.
I implemented code without any dependencies like this:
export interface SourceMap {
version: number; // always 3
file?: string;
sourceRoot?: string;
sources: string[];
sourcesContent?: string[];
names?: string[];
mappings: string | Buffer;
}
const emptySourceMap: SourceMap = { version: 3, sources: [], mappings: new Buffer(0) }
var charToInteger = new Buffer(256);
var integerToChar = new Buffer(64);
charToInteger.fill(255);
'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/='.split('').forEach((char, i) => {
charToInteger[char.charCodeAt(0)] = i;
integerToChar[i] = char.charCodeAt(0);
});
class DynamicBuffer {
buffer: Buffer;
size: number;
constructor() {
this.buffer = new Buffer(512);
this.size = 0;
}
ensureCapacity(capacity: number) {
if (this.buffer.length >= capacity)
return;
let oldBuffer = this.buffer;
this.buffer = new Buffer(Math.max(oldBuffer.length * 2, capacity));
oldBuffer.copy(this.buffer);
}
addByte(b: number) {
this.ensureCapacity(this.size + 1);
this.buffer[this.size++] = b;
}
addVLQ(num: number) {
var clamped: number;
if (num < 0) {
num = (-num << 1) | 1;
} else {
num <<= 1;
}
do {
clamped = num & 31;
num >>= 5;
if (num > 0) {
clamped |= 32;
}
this.addByte(integerToChar[clamped]);
} while (num > 0);
}
addString(s: string) {
let l = Buffer.byteLength(s);
this.ensureCapacity(this.size + l);
this.buffer.write(s, this.size);
this.size += l;
}
addBuffer(b: Buffer) {
this.ensureCapacity(this.size + b.length);
b.copy(this.buffer, this.size);
this.size += b.length;
}
toBuffer(): Buffer {
return this.buffer.slice(0, this.size);
}
}
function countNL(b: Buffer): number {
let res = 0;
for (let i = 0; i < b.length; i++) {
if (b[i] === 10) res++;
}
return res;
}
export class SourceMapBuilder {
outputBuffer: DynamicBuffer;
sources: string[];
mappings: DynamicBuffer;
lastSourceIndex = 0;
lastSourceLine = 0;
lastSourceCol = 0;
constructor() {
this.outputBuffer = new DynamicBuffer();
this.mappings = new DynamicBuffer();
this.sources = [];
}
addLine(text: string) {
this.outputBuffer.addString(text);
this.outputBuffer.addByte(10);
this.mappings.addByte(59); // ;
}
addSource(content: Buffer, sourceMap?: SourceMap) {
if (sourceMap == null) sourceMap = emptySourceMap;
this.outputBuffer.addBuffer(content);
let sourceLines = countNL(content);
if (content.length > 0 && content[content.length - 1] !== 10) {
sourceLines++;
this.outputBuffer.addByte(10);
}
let sourceRemap = [];
sourceMap.sources.forEach((v) => {
let pos = this.sources.indexOf(v);
if (pos < 0) {
pos = this.sources.length;
this.sources.push(v);
}
sourceRemap.push(pos);
});
let lastOutputCol = 0;
let inputMappings = (typeof sourceMap.mappings === "string") ? new Buffer(<string>sourceMap.mappings) : <Buffer>sourceMap.mappings;
let outputLine = 0;
let ip = 0;
let inOutputCol = 0;
let inSourceIndex = 0;
let inSourceLine = 0;
let inSourceCol = 0;
let shift = 0;
let value = 0;
let valpos = 0;
const commit = () => {
if (valpos === 0) return;
this.mappings.addVLQ(inOutputCol - lastOutputCol);
lastOutputCol = inOutputCol;
if (valpos === 1) {
valpos = 0;
return;
}
let outSourceIndex = sourceRemap[inSourceIndex];
this.mappings.addVLQ(outSourceIndex - this.lastSourceIndex);
this.lastSourceIndex = outSourceIndex;
this.mappings.addVLQ(inSourceLine - this.lastSourceLine);
this.lastSourceLine = inSourceLine;
this.mappings.addVLQ(inSourceCol - this.lastSourceCol);
this.lastSourceCol = inSourceCol;
valpos = 0;
}
while (ip < inputMappings.length) {
let b = inputMappings[ip++];
if (b === 59) { // ;
commit();
this.mappings.addByte(59);
inOutputCol = 0;
lastOutputCol = 0;
outputLine++;
} else if (b === 44) { // ,
commit();
this.mappings.addByte(44);
} else {
b = charToInteger[b];
if (b === 255) throw new Error("Invalid sourceMap");
value += (b & 31) << shift;
if (b & 32) {
shift += 5;
} else {
let shouldNegate = value & 1;
value >>= 1;
if (shouldNegate) value = -value;
switch (valpos) {
case 0: inOutputCol += value; break;
case 1: inSourceIndex += value; break;
case 2: inSourceLine += value; break;
case 3: inSourceCol += value; break;
}
valpos++;
value = shift = 0;
}
}
}
commit();
while (outputLine < sourceLines) {
this.mappings.addByte(59);
outputLine++;
}
}
toContent(): Buffer {
return this.outputBuffer.toBuffer();
}
toSourceMap(sourceRoot?: string): Buffer {
return new Buffer(JSON.stringify({ version: 3, sourceRoot, sources: this.sources, mappings: this.mappings.toBuffer().toString() }));
}
}
I, at first, implemented "index map" from that spec, only to find out that it is not supported by any browser.
Another project that could be useful to look at is magic string.

Optimising A* pathfinding, runs very slow. Possible bugs(?) visual c++

Hi I'm having a few problems with my A* pathfinding algorithm. The algorithm does successfully execute, however in a debug environment it executes in about 10 seconds, in release it will still take 2-3 seconds. This speed is way too slow. I suspect this is either due to a bug in the code, or the fact it isn't well optimised.
The map that pathfinding is being used on is a 30*30 grid, with each square being 10 unites away from one another.
I have noticed when running the algorithm, that when the open and closed list are searched to see if a node already exists, the node already stored in one of the lists always has a lower cost, so there is no updating of nodes. Not sure if this is normal or not. Also, I am not sure if quicksort is a good sort to be using in this situation.
Here is the code:
The coords struture used as a node:
struct coords
{
int x;
int z;
coords* parent;
int cost;
int score;
};
The sort compare function:
bool decompare(coords* o1, coords* o2)
{
return (o1->score < o2->score);
}
The main pathfind loop:
while (!goalFound) //While goal has not been found
{
current = openList.front(); //Retrieve current state from the open list
openList.pop_front();
for (int count = 1; count < 5; count++)
{
if (!goalFound)
{
coords* possibleState = new (coords); //Allocate new possible state
found = false;
if (count == 1)
{
possibleState->x = current->x;
possibleState->z = current->z + 10; //North
}
else if (count == 2)
{
possibleState->x = current->x + 10; //East
possibleState->z = current->z;
}
else if (count == 3)
{
possibleState->x = current->x; //South
possibleState->z = current->z - 10;
}
else if (count == 4)
{
possibleState->x = current->x - 10; //West
possibleState->z = current->z;
}
if (possibleState->x >-1 && possibleState->x <291 && possibleState->z >-1 && possibleState->z < 291) //If possible state is in game boundary
{
possibleState->cost = current->cost + 10; //Add 10 to current state to get cost of new possible state
int a = (possibleState->x / 10) + (30 * (possibleState->z / 10)); //get index of map
if (map[a] != wallTest) //Test possible state is not inside a wall
{
p = openList.begin();
while (p != openList.end() && !found) //Search open list to see if possible state already exists
{
if (possibleState->x == (*p)->x && possibleState->z == (*p)->z) //Already exists
{
found = true;
if (!possibleState->cost >= (*p)->cost) //Test possible state has lower cost
{
(*p)->parent = current; //Update existing with attributes of possible state
a = abs((*p)->x - goalState->x);
b = abs((*p)->z - goalState->z);
(*p)->cost = possibleState->cost;
(*p)->score = (possibleState->cost) + ((a)+(b));
}
}
else
{
found = false; //Set not found
}
p++;
}
q = closedList.begin();
while (q != closedList.end())
{
if (possibleState->x == (*q)->x && possibleState->z == (*q)->z)
{
found = true;
int a = (*q)->cost;
if (possibleState->cost < a) //Test if on closed list
{
(*q)->parent = current;
a = abs((*q)->x - goalState->x);
b = abs((*q)->z - goalState->z);
(*q)->cost = possibleState->cost;
(*q)->score = (possibleState->cost) + ((a)+(b)); //If cost lower push onto open list
coords* newcoord;
newcoord->x = (*q)->x;
newcoord->z = (*q)->z;
newcoord->score = (*q)->score;
newcoord->cost = (*q)->cost;
openList.push_back(newcoord);
closedList.erase(q);
}
}
q++;
}
if (!found) //If not found on either list
{
possibleState->parent = current; //Push onto open list
a = abs((possibleState)->x / 10 - goalState->x / 10);
b = abs((possibleState)->z / 10 - goalState->z / 10);
(possibleState)->score = (possibleState->cost) + ((a)+(b));
openList.push_back(possibleState);
}
sort(openList.begin(), openList.end(), decompare); // Sort the open list by score
}
if (possibleState->x == goalState->x && possibleState->z == goalState->z) //if goal found
{
openList.push_back(possibleState);
node = possibleState;
goalFound = true;
while (node != 0)
{
wayPoints.push_back(*node);
node = node->parent;
wayCount = wayPoints.size() - 1;
}
}
}
}
}
closedList.push_back(current);
}
player->setWayPoints(wayPoints);
wayPoints.clear();
player->setMoved(2);
player->setPath(1);
openList.clear();
closedList.clear();
goalFound = false;
player->setNewPath(1);
return true;
}
else {
return false;
}
}
Are there any bugs that need to be sorted in this code that anyone can see? Or is it just important optimizations that need making? Thanks

C# - Trying to create a threaded process using a function that has as Action as a parameter

This is a project I'm doing for my own amusement.
I started out wanting to experiment with combination and permutations. In a console application I have the following code
public static void Save(string newWord)
{
using (var db = new MyDataContext())
{
var w = new Word {word = newWord};
db.Words.InsertOnSubmit(w);
db.SubmitChanges();
}
}
static void Main(string[] args)
{
var letters = new[] { 'A', 'B', 'C', '1', '2', '3'};
for (var i = 2; i < 10; i++)
{
letters.GetPermutations(a => Save(string.Join(string.Empty, a.ToArray())), i, true);
}
}
In an extension class, I have the code to generate the combinations. I found the code for the combinations here (http://blog.noldorin.com/2010/05/combinatorics-in-csharp/) for those wanting to review that.
public static void GetCombinations<T>(this IList<T> list, Action<IList<T>> action, int? resultSize = null, bool withRepetition = false)
{
if (list == null)
throw new ArgumentNullException("list");
if (action == null)
throw new ArgumentNullException("action");
if (resultSize.HasValue && resultSize.Value <= 0)
throw new ArgumentException(errorMessageValueLessThanZero, "resultSize");
var result = new T[resultSize.HasValue ? resultSize.Value : list.Count];
var indices = new int[result.Length];
for (int i = 0; i < indices.Length; i++)
indices[i] = withRepetition ? -1 : indices.Length - i - 2;
int curIndex = 0;
while (curIndex != -1)
{
indices[curIndex]++;
if (indices[curIndex] == (curIndex == 0 ? list.Count : indices[curIndex - 1] + (withRepetition ? 1 : 0)))
{
indices[curIndex] = withRepetition ? -1 : indices.Length - curIndex - 2;
curIndex--;
}
else
{
result[curIndex] = list[indices[curIndex]];
if (curIndex < indices.Length - 1)
curIndex++;
else
action(result);
}
}
}
Then I thought it would be cool to calculate the combinations for all charaters in a list, each in its own thread. So in my for/next loop, I tried
Thread t = new Thread(letters.GetPermutations(a => Save(string.Join(string.Empty, a.ToArray())), i, true));
But apparently, the Action that is being passed in, the call to the 'Save' function, is not liked in the Thread. If someone could give me a nudge in the right direction, I'd appreciate it.
Thanks,
Andy
The Thread constructor is looking for a delegate but you're appearing to pass a value instead. Try wrapping it in an ThreadStart delegate.
ThreadStart del = () => letters.GetPermutations(a => Save(string.Join(string.Empty, a.ToArray())), i, true);
Thread t = new Thread(del);
t.Start();

Getting a random UserProfile In SharePoint 2010

I am trying to retrieve a random number of users from the UserProfileManager.
But I am encountering errors when deploying to the live servers. I can't seem to see what is causing the error. My code is below:
for (int i = 0; i < NumberOfUserLimit; i++)
{
UserProfile up = profileManager.GetUserProfile(random.Next(1, NumberOfUserLimit));
if (up["FirstName"] != null && up["FirstName"].Value != null && !String.IsNullOrEmpty(up["FirstName"].Value.ToString()))
{
DataRow drUserProfile;
drUserProfile = dtUserProfile.NewRow();
drUserProfile["DisplayName"] = up.DisplayName;
drUserProfile["FirstName"] = up["FirstName"].Value;
drUserProfile["LastName"] = up["LastName"].Value;
drUserProfile["Department"] = up["Department"].Value;
drUserProfile["Location"] = up["SPS-Location"].Value;
drUserProfile["HireDate"] = up["SPS-HireDate"].Value;
drUserProfile["ContactNumber"] = up["Office"].Value;
if (up["PictureURL"] != null && up["PictureURL"].Value != null && !String.IsNullOrEmpty(up["PictureURL"].Value.ToString()))
{
string cleanAccountName = up["AccountName"].Value.ToString().Replace(#"\", "_");
string pictureUrl = String.Format("https://my.someintranet.com/User Photos/Profile Pictures/{0}_MThumb.jpg", cleanAccountName);
drUserProfile["Image"] = pictureUrl;
}
else
{
drUserProfile["Image"] = "~/_layouts/images/O14_person_placeHolder_96.png";
}
drUserProfile["MySiteUrl"] = up.PublicUrl;
dtUserProfile.Rows.Add(drUserProfile);
}
}
My code works when I apply a simple foreach to my code above instead of the "for loop":
foreach (UserProfile up in profileManager)
Which proves I can return userprofiles.
Any help is appreciated.
profileManager.GetUserProfile(long recordId)
expects a recordId from userprofile table. It is not an index, so you cannot use "random".
If you want to check RecordId, you can take a look at SQL tables of ProfileDB. Table "UserProfile_Full" has MasterRecordId column. Your parameter in GetUserProfile has to match of the user profile's MasterRecordId.
you can use the following code to get your random profiles:
IEnumerator profiles = profileManager.GetEnumerator();
int index = new Random().Next(1, 100);
while (index >= 0 && profiles.MoveNext())
index--;
UserProfile currentProfile = (UserProfile)profiles.Current
Code that handles Random better
public class TestClass
{
private random = new Random();
private long totalNumberOfProfiles; //ProfileManager.Count not always returns count correctly
public TestClass()
{
//this does not have to be in constructor but point is to have it cached (reasonably)
IEnumerator profiles = profileManager.GetEnumerator();
long counter = 0;
while (profiles.MoveNext())
counter++;
this.totalNumberOfProfiles = counter;
}
public fillInDataSet()
{
//something is here...
IEnumerator profiles = profileManager.GetEnumerator();
int index = random.Next(1, totalNumberOfProfiles);
while (index >= 0 && profiles.MoveNext())
index--;
UserProfile currentProfile = (UserProfile)profiles.Current
//something is here...
}
}

Resources