Writing multithreaded code to generate incremental index
I want to write a code in following scenario : we want to design an invoice generator.this invoice generator also generates an incremental invoice no .Also note that for some reasons we dont use something like sql Auto Increment here and we want to use C# (I wrote the increment logic). since several users can send requests at a time it means that we dont have to give the same invoice no to them (I used lock for it and I wrote it).
Now i have written increment logic. and i take care of multiple users requests with lock . and I wrote CRUD for mongodb database.
My problem is that my increent logic is naive. each time i find maximum and i increment by one which is not scalable. and another problem is that when we delete a record we don't want the invoice no to be repeated and since we find max if the deleted record had the max value then the invoice no would be duplicate and this is something we don't want to have.
I really don't know how to handle the problem. specially in case of deletion should i store max values in a file or should i change increment logic completely?
i appreciate any help
do you know?
how many words do you know
See also questions close to this topic
-
C# - Adding condition to func results in stack overflow exception
I have a func as part of specification class which sorts the given iqueryable
Func<IQueryable<T>, IOrderedQueryable<T>>? Sort { get; set; }
When i add more than one condition to the func like below , it results in stack overflow exception.
spec.OrderBy(sc => sc.Case.EndTime).OrderBy(sc => sc.Case.StartTime);
The OrderBy method is implemented like this
public ISpecification<T> OrderBy<TProperty>(Expression<Func<T, TProperty>> property) { _ = Sort == null ? Sort = items => items.OrderBy(property) : Sort = items => Sort(items).ThenBy(property); return this; }
Chaining or using separate lines doesn't make a difference.
This problem gets resolved if I assign a new instance of the specification and set it's func, but i don't want to be assigning to a new instance everytime. Please suggest what am i missing here and how to reuse the same instance (if possible).
-
How to projection fields for a dictionary (C#, MongdoDB)
I am trying my luck here, I have a model which is like the following
public class RowData : BaseBsonDefinition { . [BsonExtraElements] [BsonDictionaryOptions(DictionaryRepresentation.ArrayOfDocuments)] public Dictionary<string, object> Rows { get; set; } = new(StringComparer.OrdinalIgnoreCase); . }
In result, the schema in the MongoDB looks like
{ "_id": { "$binary": { "base64": "HiuI1sgyT0OZmcgGUit2dw==", "subType": "03" } }, "c1": "AAA", "c8": "Fully Vac", "c10": "", }
Those c1, c8 and c10 fields are keys from the dictionary, my question is how to dynamic project those fields?
I tried
Builders<RowData>.Projection.Exclude(p => "c1")
It seems the MongoDB driver can not handle a value directly.
Anyone could point me in the correct direction?
Thanks,
-
How do I add new DataSource to an already Databinded CheckBoxList
i'm building a web form that show Database's item(Tables, Rows, FK,...)
I have a CheckBoxList of Tables (
chkListTable
) which will show a new CheckBoxList of Rows (chkListRow
) everytime I SelectedIndexChanged fromchkListTable
. The problem is i can show the items fromchkListTable
with 1 selected item. But i don't know how to showchkListRow
if multiple item fromchkListTable
are selected.Here are my codes:
aspx
:<div> <asp:Label ID="Label2" runat="server" Text="Table: "></asp:Label> <asp:CheckBoxList ID="chkListTable" runat="server" DataTextField="name" DataValueFeild="name" AutoPostBack="true" OnSelectedIndexChanged="chkListTable_SelectedIndexChanged"> </asp:CheckBoxList> </div> <div> <asp:CheckBoxList ID="chkListRow" runat="server" DataTextField="COLUMN_NAME" DataValueField="COLUMN_NAME" RepeatDirection="Horizontal"> </asp:CheckBoxList> </div>
aspx.cs
:protected void chkListTable_SelectedIndexChanged(object sender, EventArgs e) { tableName.Clear(); foreach (ListItem item in chkListTable.Items) { if(item.Selected) { tableName.Add(item.Text.Trim()); } } for(int i = 0; i < tableName.Count; i++) { String query = "USE " + dbname + " SELECT * FROM information_schema.columns" + " WHERE table_name = '" + tableName[i] + "'" + " AND COLUMN_NAME != 'rowguid'"; chkListRow.DataSource = Program.ExecSqlDataReader(query); chkListRow.DataBind(); Program.conn.Close(); } }
Program.cs
:public static bool Connect() { if (Program.conn != null && Program.conn.State == ConnectionState.Open) Program.conn.Close(); try { Program.conn.ConnectionString = Program.constr; Program.conn.Open(); return true; } catch (Exception e) { return false; } } public static SqlDataReader ExecSqlDataReader(String query) { SqlDataReader myreader; SqlCommand sqlcmd = new SqlCommand(query, Program.conn); sqlcmd.CommandType = CommandType.Text; if (Program.conn.State == ConnectionState.Closed) Program.conn.Open(); try { myreader = sqlcmd.ExecuteReader(); return myreader; myreader.Close(); } catch (SqlException ex) { Program.conn.Close(); return null; } }
I want my display to be like this:
[x]Table1 [x]Table2 [ ]Table3 [ ]Row1(Table1) [ ]Row2(Table1) [ ]Row3(Table1) [ ]Row1(Table2) [ ]Row2(Table2)
-
Scraping .aspx page with Python yields 404
I'm a web-scraping beginner and am trying to scrape this webpage: https://profiles.doe.mass.edu/statereport/ap.aspx
I'd like to be able to put in some settings at the top (like District, 2020-2021, Computer Science A, Female) and then download the resulting data for those settings.
Here's the code I'm currently using:
import requests from bs4 import BeautifulSoup url = 'https://profiles.doe.mass.edu/statereport/ap.aspx' with requests.Session() as s: s.headers['User-Agent'] = "Mozilla/5.0 (Macintosh; Intel Mac OS X 10.15; rv:100.0) Gecko/20100101 Firefox/100.0" r = s.get('https://profiles.doe.mass.edu/statereport/ap.aspx') soup = BeautifulSoup(r.text,"lxml") data = {i['name']:i.get('value','') for i in soup.select('input[name]')} data["ctl00$ContentPlaceHolder1$ddReportType"]="DISTRICT", data["ctl00$ContentPlaceHolder1$ddYear"]="2021", data["ctl00$ContentPlaceHolder1$ddSubject"]="COMSCA", data["ctl00$ContentPlaceHolder1$ddStudentGroup"]="F", p = s.post(url,data=data)
When I print out
p.text
, I get a page with title'\t404 - Page Not Found\r\n'
and message<h2>We are unable to locate information at: <br /><br ' '/>http://profiles.doe.mass.edu:80/statereport/ap.aspxp?ASP.NET_SessionId=bxfgao54wru50zl5tkmfml00</h2>\r\n'
Here's what
data
looks like before I modify it:{'__EVENTVALIDATION': '/wEdAFXz4796FFICjJ1Xc5ZOd9SwSHUlrrW+2y3gXxnnQf/b23Vhtt4oQyaVxTPpLLu5SKjKYgCipfSrKpW6jkHllWSEpW6/zTHqyc3IGH3Y0p/oA6xdsl0Dt4O8D2I0RxEvXEWFWVOnvCipZArmSoAj/6Nog6zUh+Jhjqd1LNep6GtJczTu236xw2xaJFSzyG+xo1ygDunu7BCYVmh+LuKcW56TG5L0jGOqySgRaEMolHMgR0Wo68k/uWImXPWE+YrUtgDXkgqzsktuw0QHVZv7mSDJ31NaBb64Fs9ARJ5Argo+FxJW/LIaGGeAYoDphL88oao07IP77wrmH6t1R4d88C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+/dw+86OhPyG88qyJwqZODEXE1WB5zSOUywGb1/Xed7wq9WoRs6v8rAK5c/2iH7YLiJ4mUVDo+7WCKrzO5+Hsyah3frMKbheY1acRmSVUzRgCnTx7jvcLGR9Jbt6TredqZaWZBrDFcntdg7EHd7imK5PqjUld3iCVjdyO+yLKUkMKiFD85G3vEferg/Q/TtfVBqeTU0ohP9d+CsKOmV/dxVYWEtBcfa9KiN6j4N8pP7+3iUOhajojZ8jV98kxT0zPZlzkpqI4SwR6Ys8d2RjIi5K+oQul4pL5u+zZvX0lsLP9Jl7FeVTfBvST67T6ohz8dl9gBfmmbwnT23SyuFSUGd6ZGaKE+9kKYmuImW7w3ePs7C70yDWHpIpxP/IJ4GHb36LWto2g3Ld3goCQ4fXPu7C4iTiN6b5WUSlJJsWGF4eQkJue8=', '__VIEWSTATE': '/wEPDwUKLTM0NzY4OTQ4NmRkDwwPzTpuna+yxVhQxpRF4n2+zYKQtotwRPqzuCkRvyU=', '__VIEWSTATEGENERATOR': '2B6F8D71', 'ctl00$ContentPlaceHolder1$btnViewReport': 'View Report', 'ctl00$ContentPlaceHolder1$hfExport': 'ViewReport', 'leftNavId': '11241', 'quickSearchValue': '', 'runQuickSearch': 'Y', 'searchType': 'QUICK', 'searchtext': ''}
Following suggestions from similar questions, I've tried playing around with the parameters, editing
data
in various ways (to emulate the POST request that I see in my browser when I navigate the site myself), and specifying anASP.NET_SessionId
, but to no avail.How can I access the information from this website?
-
Error message : MongoServerError: bad auth :Authentication failed
What is the reason behind this error? this code I am using to connect to DB.
const uri =`mongodb+srv://${process.env.DB_USER}:${process.env.DB_PASSWORD}@cluster0.xft2s.mongodb.net/myFirstDatabase?retryWrites=true&w=majority`;
-
In Mongo, If a document I'm saving "Prateek" then I don't want on the next create operation even the "prateek" or "praTEEK", etc is saved
//** If I'm adding a new document with the name: "India", then I don't want that the DB allow another name with the name: "INDIA", "india", "indIA", etc. I'm new and learning, help would be great!!**
// Controller
var Dinosaur = require('../models/dinosaurs'); //addDino module.exports.addDino = (req, res) => { var name = req.body.name; var type = req.body.type; var height = req.body.height; var weight = req.body.weight; var Period = req.body.Period; req.checkBody('name', 'Name is required').notEmpty(); var errors = req.validationErrors(); if (errors) return res.status(400).send({ message: 'Name is Required' }); else { let newDino = { name: name, type: type, height: height, weight: weight, Period: Period } Dinosaur.addDino(newDino, (err, result) => { if (err) { if (err.name) return res.status(409).send({ message: name + ' Already Exist' }); else if (err.url) return res.json({ status: false, error: { url: "Url already exist" }, message: err.url }); else return res.json(err, "Server Error"); } else { return res.status(200).send({ message: "Done" }); } }); } }
// Model
var mongoose = require('mongoose'); //dinosaur schema var DinosaurSchema = mongoose.Schema({ name: { type: String, unique: true }, type: { type: String }, height: { type: Number }, weight: { type: Number }, Period: { type: String } }); var Dinosaur = mongoose.model('dinosaur', DinosaurSchema); //add module.exports.addDino = (query, callback) => { Dinosaur.create(query, callback); }
// GetAll, Already Created a new document with the name "Brachiosaurus"
// > Create, a new create with the first letter lower case "brachiosaurus", Don't want it to be pushed.
-
suggestions on fulltext search or already existing search algorithms
Can someone suggest how to solve the below seach problem easily, I mean is there any algorithm, or full text search will be suffice for this?
There is below classification of items data,
ItemCategory ItemCluster ItemSubCluster SubCluster Items Vegetable Root vegetables Root WithOutSkin potato, sweet potato, yam Vegetable Root vegetables Root WithSkin onion, garlic, shallot Vegetable Greens Leafy green Leaf lettuce, spinach, silverbeet Vegetable Greens Cruciferous Flower cabbage, cauliflower, Brussels sprouts, broccoli Vegetable Greens Edible plant stem Stem celery, asparagus
The inputs will be some thing like,
sweet potato, yam Yam, Potato garlik, onion lettuce, spinach, silverbeet lettuce, silverbeet lettuce, silverbeet, spinach
From the input, I want to get the mapping of the input items those belongs to which ItemCategory, ItemCluster, ItemSubCluster, SubCluster.
Any help will be much appreciated.
- create string r using string p and q, C++, Data Structures, Strings