Flutter Dropdown Menu <Model> is not a subtype of type 'String' Posted: 27 May 2021 08:08 AM PDT I'm self taught (i.e. not good) and trying to build a flutter page whereby I select a category from a dropdown (_careCat) e.g. "Option 1", then populate a second dropdown with the options for "Option 1" from sqlite. This part works fine. However, the data I retrieve for the second dropdown has 5 columns of data & by selecting a value on the dropdown I want to be able to set variables related to that data (dropdown has dropdownText but I want to reference fullText). I either seem to be able to get the dropdown menu value to update to the selection but not be able to reference the other data or I'm able to reference the alternative data but not update the selection, the below is the current stage I'm at and I get the error: "type 'CareAdviceOptions' is not a subtype of type 'String'" I hope that makes sense. Any pointers would be appreciated, thank you. care_advice_model.dart class CareAdviceOptions { int id; String category; String shortCode; String dropdownText; String fullText; CareAdviceOptions({ this.id, this.category, this.shortCode, this.dropdownText, this.fullText }); Map<String, dynamic> toMap() => { 'id': id, 'category': category, 'shortCode': shortCode, 'dropdownText': dropdownText, 'fullText': fullText, }; factory CareAdviceOptions.fromJson(Map<String, dynamic> parsedJson) { return CareAdviceOptions( id: parsedJson['id'], category: parsedJson['category'], shortCode: parsedJson['shortCode'], dropdownText: parsedJson['dropdownText'], fullText: parsedJson['fullText'], ); } } db_provider.dart await db.execute('CREATE TABLE CareAdviceLookup(' 'id INTEGER PRIMARY KEY,' 'category TEXT,' 'shortCode TEXT,' 'dropdownText TEXT,' 'fullText TEXT' ')'); Future<List<CareAdviceOptions>> getCareAdviceMenu(String category) async { final db = await database; var response = await db.rawQuery("SELECT * from CareAdviceLookup WHERE category = (?) Order by shortCode asc", [category]); List<CareAdviceOptions> list = await response.map((c) => CareAdviceOptions.fromJson(c)).toList(); return list; } care_advice_page.dart CareAdviceOptions _care; Container careOptions() { return Container( child: FutureBuilder<List<CareAdviceOptions>>( future:DBProvider.db.getCareAdviceMenu(_careCat), builder: (BuildContext context, AsyncSnapshot <List<CareAdviceOptions>>snapshot) { return snapshot.hasData ? Container( child: DropdownButton<CareAdviceOptions>( value: _care, hint: Text(_care ?? 'Make a selection'), items: snapshot.data.map((CareAdviceOptions item) { return new DropdownMenuItem<CareAdviceOptions>( value: item, child: Text('${item.dropdownText}'),);}).toList(), onChanged: (CareAdviceOptions value) { _care = value; var _index = snapshot.data.indexOf(value); _careInstruction = snapshot.data[_index].fullText; _careInsSetAs = snapshot.data[_index].dropdownText; setState(() { _isOptionSelected = true; }); }, ), ) : Container( child: Center( child: Container(), ), ); }, ), ); } |
ToString("C") does not display currency symbol on output Posted: 27 May 2021 08:07 AM PDT Problem Statement I am trying to output a value with a currency symbol. But I am not able to make Approach 1 work (refer to code below). My Code using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Globalization; //Additional import to make it work namespace firstProject { class Program { static void Main(string[] args) { Program p = new Program(); p.Go(); Console.ReadKey(); } public void Go() { Console.Write("Please enter a number: "); String x = Console.ReadLine(); int myInt = int.Parse(x); //Approach 1 - Gives a ? symbol on output screen. Console.WriteLine("The number is {0}", myInt.ToString("C")); // Approach 2 - Works as expected. Shows the currency symbol. Console.WriteLine("The number is {0}", myInt.ToString("C", CultureInfo.CreateSpecificCulture("en-US"))); } } } Output I am getting Answer that I am looking for specifically from this question The MSDN documentation also shows how to print the currency using Approach 1, but I am trying to find the reason why Approach 1 does not work for me. I mean, is it absolutely necessary to import the System.Threading.Tasks library? |
Kubernetes show Cron Job Successfully but when not getting desired result Posted: 27 May 2021 08:07 AM PDT when I run the cronjob into Kubernetes, that time cron gives me to success the corn but not getting the desired result apiVersion: batch/v1beta1 kind: CronJob metadata: name: {{ $.Values.appName }} namespace: {{ $.Values.appName }} spec: schedule: "* * * * *" concurrencyPolicy: Forbid jobTemplate: spec: template: spec: containers: - name: test image: image command: ["/bin/bash"] args: [ "test.sh" ] restartPolicy: OnFailure also, I am sharing test.sh #!/bin/sh rm -rf /tmp/*.* echo "remove done" cronjob running successfully but when I checked the container the file is not getting deleted into /tmp directory |
Is javascript asynchronous? Posted: 27 May 2021 08:07 AM PDT I am confused about javascript. Is javascript asynchronous or synchronous? I got asked a question about javascript that is javascript asynchronous. I search about it but I didn't get a proper answer. |
Using CTE in dbContext.Entity.FromSqlRaw() Posted: 27 May 2021 08:07 AM PDT I've run into some problems trying to use a cte query in a FromSqlRaw method call. The query runs fine on SSMS though, and it goes as: WITH cte_query AS () SELECT * FROM cte_query At first, i was getting the following error: FromSqlRaw or FromSqlInterpolated was called with non-composable SQL and with a query composing over it. Consider calling AsEnumerable after the FromSqlRaw or FromSqlInterpolated method to perform the composition on the client side. I've tried to put a cte into a subquery, but as i've found out - one cannot put a cte into a subquery. Any advices on the matter? |
my code doesn't work, I can't print hello world [closed] Posted: 27 May 2021 08:07 AM PDT I need to create Hello world in different languages, post it here. I need help to produce all of those. |
Parse json string where numbers have commas instead of dots Posted: 27 May 2021 08:07 AM PDT I have a string that I would like to deserialize into a json object. Unfortunately I do not have control over the content of the string. Is there a simple way to do this? let result = "{\"var1\": 15,000, \"var2\": 22,000, \"var3\": 333,000, \"var4\": 77,000}" I have tried: JSON.parse(result); |
Somebody please help me with unity incompatibility in Visual Studio Posted: 27 May 2021 08:07 AM PDT So I'm having this problem where I can't actually do anything {Autofill, MonoBehaviour not showing, everything is incompatible}. You can see more in the screenshot. Please help me :D Incompatibility with unity |
javascript function call runs twice when called Posted: 27 May 2021 08:07 AM PDT function addByX(x) { function addby2(num) { console.log(num + x); } return addby2; } const addByTwo = addByX(2); function once(func) { return func } const onceFunc = once(addByTwo); console.log(onceFunc(4)); // => should log 6 This is practice problem related to javascript closures, In the function Once i am passing addByTwo callback function as an argument and returning the same, when i call Once(4) it gives the following result 6 undefined The first value 6 is fine, but I am not sure why i am getting undefined, it means the function is running twice, although i have called it just once. |
Free the memory after it is allocated with calloc() to create an array of strings Posted: 27 May 2021 08:07 AM PDT After allocating memory with calloc() to create an array of strings, I want to try to free it and make sure that both strings and string pointers are permanently deleted. The code is as follows #include <stdlib.h> #include <stdio.h> int main(int argc, char **argv) { char **arr; arr = calloc(3, sizeof(char *)); arr[0] = calloc(30, sizeof(char)); arr[1] = calloc(30, sizeof(char)); arr[2] = calloc(30, sizeof(char)); arr[0] = "jhgfdjhgfdjhgfds"; arr[1] = "oru95u9iojituy"; arr[2] = "hggpooki0opkopreiyh"; free(arr[2]); free(arr[1]); free(arr[0]); //free(arr[0]); free(arr[1]); free(arr[2]); free(arr); } As you can see in the end I tried to free up the memory allocated for strings. In the commented line I tried to free the memory in the opposite direction, believing that I had to follow the order in which the strings appeared in the array. Despite this, I always get the following error: free(): invalid pointer I can't understand the problem. I know that each calloc () / malloc () must have its respective free () . It seems to be no memory address in arr [i], even though I called a calloc to it. How can I go about freeing up the memory completely? |
What does "Error: reached end pf file while parsing }" mean? Posted: 27 May 2021 08:07 AM PDT New here, hoping I'm posting correctly. Please pardon any indention errors based on copy and paste. This is the error I receive: ShoppingCartPrinter.java:29: error: reached end of file while parsing } ^ but I don't see where I'm missing any curly braces. Not sure what else that could mean. Thanks! import java.util.Scanner; public class ShoppingCartPrinter { public static void main(String args[]) { String name; int price; int qty; Scanner scnr=new Scanner(System.in); ItemToPurchase ip1=new ItemToPurchase(); System.out.println("Item 1 \n"); System.out.println("Enter the item name: "); name=scnr.nextLine(); System.out.println("Enter the item price: "); price=scnr.nextInt(); System.out.println("Enter the item quantity: "); qty=scnr.nextInt(); ip1.setName(name); ip1.setPrice(price); ip1.setQuantity(qty); scnr.nextLine(); ItemToPurchase ip2=new ItemToPurchase(); System.out.println("Item 2 \n"); System.out.println("Enter the item name: "); name=scnr.nextLine(); System.out.println("Enter the item price: "); price=scnr.nextInt(); System.out.println("Enter the item quantity: "); qty=scnr.nextInt(); ip2.setName(name); ip2.setPrice(price); ip2.setQuantity(qty); System.out.println("\nTOTAL COST "); System.out.println(ip1.getName()+" "+ip1.getQuantity()+" @ $"+ip1.getPrice()+" = $"+(ip1.getQuantity()*ip1.getPrice())); System.out.println(ip2.getName()+" "+ip2.getQuantity()+" @ $"+ip2.getPrice()+" = $"+(ip2.getQuantity()*ip2.getPrice())); System.out.println("\nTotal: $"+((ip1.getQuantity()*ip1.getPrice())+(ip2.getQuantity()*ip2.getPrice()))); } } |
Is there a example character in python Posted: 27 May 2021 08:07 AM PDT To be more specific, it's for an "if" condition I have a list of string that look like this " 0" or " A" Is there a charactere that can replace the last charactere of every string Like: if string == " &": do something And the condition would be true if & == A or & == 1 |
How to modify an array of object and push in JavaScript? Posted: 27 May 2021 08:07 AM PDT I have any array of objects like this let myObj=[{a:'CR',showMe: true},{a:'PY'}]; Now I'm trying to find the object which has a as CR and showMe as true and want to change the a value. let findObj = myObj.filter(i=> i.a == 'CR' && i.showMe); findObj.map(ele => ele['a'] = "PS"); When I'm trying to console myObj,value of a in myObj is changed along with findObj. I don't want myObj to be changed. What is causing the issue, could someone help? |
Display other value than Id in dataTable asp .net core Posted: 27 May 2021 08:07 AM PDT I have 2 tables (customers and appointments) with a foreign key of customerId in appointments. I want to display the customerFirstName and customerLastName of the customer, but I can only pass customerId as data in my loadDataTable ajax function. I cannot do this because customerId is the only foreign key entity in my Appointment model. What can I do to be able to pass the customerFirstName and customerLastName data in my ajax function? My appointment table var dataTable; $(document).ready(function () { loadDataTable(); }); function loadDataTable() { dataTable = $('#DT_load').DataTable({ "ajax": { "url": "/Appointment/getall/", "type": "GET", "datatype": "json" }, "columns": [ { "data": "customerId", "width": "auto" }, |
Python function that accepts either an integer or a list of integer Posted: 27 May 2021 08:07 AM PDT I need a function, that takes two arguments a (an integer) and b (either an integer or a list of integer), to return True if a == b or a in b . This can be easily done by putting a simple or between the two conditions, but I wanted to know if it was possible to do it in a single condition. I thought of doing: a in list(b) but it is not working because integers are not iterable, a in [b] but it is not working if b is already a list. |
Cannot login to Debian 10 buster Posted: 27 May 2021 08:08 AM PDT I updated the linux and after a restart, when I press enter after writing my password, the console shows up. I can see that I got logged in but the only thing in the screen is a console and the login screen in background: I can use terminal as usual but cannot see my desktop. |
Compare the elements of two arrays with regex Posted: 27 May 2021 08:07 AM PDT This is my piece of code, I want to display the difference of every element of array1 to array2, When I am doing this way it is not giving the expected output. Can anyone please tell how can I take the difference up to two decimal place, considering I have comma too in the data? Expected output arr3= ["$20.00", "$150.60", "-$0.50", "$168.20", "Can't Compare", "$0", "$0", "-$1000.00","-$300.00", "Can't compare", "Can't compare"] arr1 = ["$33.90", "$161.90", "$53.30", "$186.20", "Match up to $350 ", "Match to $700 ", "$3,000.00", "$6,000.00", "$6,650.00", "$13,300.00", "None"] arr2 = ["$13.90", "$11.30", "$53.80", "$18.00", "$350 ", "Match to $700 ", "$3,000.00", "$7,000.00", "$6,950.00", "Match up to $350 ", "Not available"] arr3 = []; function difference() { for (let i = 0; i < arr1.length; i++) { const regex = /\d+/; let firstnum = parseInt(arr1[i].match(regex)); let secondnum = parseInt(arr2[i].match(regex)); let diff = firstnum - secondnum; if (isNaN(diff)) { diff = `Can't Compare`; } else if (diff < 0) { diff = Math.abs(diff) diff= `-$${diff}` } else { diff = `$${diff}` } arr3.push(diff) } alert(arr3) } difference(); |
i can't figure how to turn an html page to an xhtml(jsf) , when i run the page i get no tag was defined for name: input Posted: 27 May 2021 08:07 AM PDT im trying to implement jsf for a login page , when i run it it give me this :[/login.xhtml @33,49 <h:input> Tag Library supports namespace: http://java.sun.com/jsf/html, but no tag was defined for name: input] avec la cause javax.faces.view.facelets.TagException: /login.xhtml @33,49 <h:input> Tag Library supports namespace: http://java.sun.com/jsf/html, but no tag was defined for name: input login.xhtml = <html xmlns="http://www.w3.org/1999/xhtml" xmlns:ui="http://java.sun.com/jsf/facelets" xmlns:f="http://java.sun.com/jsf/core" xmlns:h="http://java.sun.com/jsf/html"> <h:head> <meta charset="utf-8" /> <title>Web Application | todo</title> <meta name="description" content="app, web app, responsive, admin dashboard, admin, flat, flat ui, ui kit, off screen nav" /> <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1" /> <link rel="stylesheet" href="Web Application _ todo_files/app.v2.css" type="text/css"/> <link rel="stylesheet" href="Web Application _ todo_files/font.css" type="text/css"/> <!--[if lt IE 9]> <script src="js/ie/respond.min.js" cache="false"></script> <script src="js/ie/html5.js" cache="false"></script> <script src="js/ie/fix.js" cache="false"></script> <![endif]--> </h:head> <body> <section id="content" class="m-t-lg wrapper-md animated fadeInUp"> <a class="nav-brand" href="index.html">WELCOME</a> <div class="row m-n"> <div class="col-md-4 col-md-offset-4 m-t-lg"> <section class="panel"> <header class="panel-heading text-center"> Sign in </header> <h:form action="index.html" class="panel-body"> <div class="form-group"> <label class="control-label">username</label> <h:inputText type="email" placeholder="username" class="form-control"/> </div> <div class="form-group"> <label class="control-label">Password</label> <h:inputSecret type="password" id="inputPassword" placeholder="Password" class="form-control"/> </div> <div class="checkbox"> <label> <h:input type="checkbox"/> Keep me logged in </label> </div> <a href="#" class="pull-right m-t-xs"><small>Forgot password?</small></a> <h:commandButton value="Sign in" class="btn btn-info"/> <div class="line line-dashed"></div> <div class="line line-dashed"></div> <p class="text-muted text-center"><small>Do not have an account?</small></p> <a href="signup.html" class="btn btn-white btn-block">Create an account</a> </h:form> </section> </div> </div> </section> </body> </html> |
Error R10 (Boot timeout) heroku in nodejs (Discord Bot) "SOLVED" Posted: 27 May 2021 08:07 AM PDT EDIT: This solved the problem for me i'm creating a bot for my discord channel, and want to up him to heroku, but everytime i got this error. i got this error with this code : const Discord = require("discord.js"); const Enmap = require("enmap"); const fs = require("fs"); const client = new Discord.Client(); const config = require("./config.json"); client.config = config; fs.readdir("./events/", (err, files) => { if (err) return console.error(err); files.forEach(file => { const event = require(`./events/${file}`); let eventName = file.split(".")[0]; client.on(eventName, event.bind(null, client)); }); }); client.commands = new Enmap(); fs.readdir("./commands/", (err, files) => { if (err) return console.error(err); files.forEach(file => { if (!file.endsWith(".js")) return; let props = require(`./commands/${file}`); let commandName = file.split(".")[0]; console.log(`carregando ${commandName}`); client.commands.set(commandName, props); }); }); client.login(config.token); |
Flask - How do I use the value of an HTML button in a Python function? Posted: 27 May 2021 08:08 AM PDT I am new to programming and have only used a little bit of Python in the past. I am using Flask to build a website to host a scientific experiment. I am doing this on pythonanywhere.com. For the last part of the experiment, participants are shown 30 individual images and they have to say if they remember seeing the image in an earlier part of the experiment. To do this I have created a javascript function that randomly shows one of 30 images every time changeImage() is run. Below it are two buttons saying "yes" and "no". Pressing the button should change the shown image and send "yes" or "no" to the flask_app.py, along with the variable "x" from javascript. This is so the Python function can save the number of the image and what answer the participant gives. Javascript var array2 = new Array(); var index = 0 var x = 0 for (var i = 1; i < 31; i++) { array2.push(i); } function changeImage() { if (array2.length) { var index = Math.floor(Math.random() * array2.length); x = array2[index]; var image = "/static/images/image" + x + ".jpg" document.getElementById('ad').src = image; array2.splice(index, 1); } } HTML <body onload="changeImage()"> <div class="w3-row-padding w3-padding-16 w3-center"> <img id="ad" class="img-fluid" src="/static/images/image99.jpg" /> <form action="{{ url_for('recog1') }}" id="answer" method="POST"> <div class="w3-center"> <input type="submit" id="answerY" value="Yes" name="Yes" style="width:47%;" class="w3-bar-item w3-button w3-padding-medium w3-blue" onclick= "changeImage();"> <input type="submit" id="answerN" value="No" name="No" style="width:47%;" class="w3-bar-item w3-button w3-padding-medium w3-blue" onclick= "changeImage();"> </div> </form> </body> The problem is that I can't get my Python function to take the value of the buttons themselves. I do succesfully save data in an earlier part of the site where users have to enter their age and gender in a form, but I just can't get it to work when there are no fields to enter the data. The value from the button itself should be saved. Python function @app.route("/recog1", methods=["POST", "GET"]) def recog1(): if request.method == "GET": return render_template("recog1.html") Yes = request.form['Yes'] No = request.form['No'] entry_time = datetime.fromtimestamp(time.time()).strftime('%Y-%m-%d %H:%M:%S') #save to file with open(BASE_DIR + '/userinfo/userinfo.csv', 'a+') as myfile: myfile.write( str(entry_time) + ', ' + str(Yes) + ', ' + str(No) + ', ' + '\n') myfile.close() return redirect(url_for("thankyou")) Now, there is a lot wrong with what is done with the data here and it would immediately go to the thankyou page, instead of waiting for thirty button clicks. I'll change those things later but first the problem is that I can't even get the button values to my python here. I always get "Bad Request: The browser (or proxy) sent a request that this server could not understand". I have looked at stackoverflow questions similar to this but they have never been useful to me or more likely, I didn't know how exactly to apply them to my case. Any amount of help would be greatly appreciated and thank you for taking the time to read! |
Binding dynamic and dependent selects in Svelte Posted: 27 May 2021 08:07 AM PDT I have a select component of which the options are dependent on the value of second select component. I would like the selected value of the first select to be the first of the dynamically provided options. Here is a REPL that illustrates the issue. The options are updated, but the selected value is not updated in the parent App component. Additionally, when you first select the second or third option from the right dropdown, and then change the left one, it is not the first option that is selected in the right one. This REPL has it working, but without the selects being child components. There was a Svelte bug related to this, but this was solved in Svelte 3.23, see here Any solution or workaround would be greatly appreciated. |
Firebase Functions Accepting Payments and Firestore structure Posted: 27 May 2021 08:08 AM PDT I'm trying to use a payment api with Firebase Functions (PayPal but am open to Stripe, Venmo, really any) to allow users to tip each other for help, quality, posts, content, etc. How would I go about this with cloud functions and what do I need to know to write them/required steps and structuring the databases? I write front ends in Flutter and databases are cloud firestore. I'd prefer to send payments direct and take a small cut if this makes a difference. I will use Javascript. |
Simplest way to create Unix-like continuous pipeline in Powershell Posted: 27 May 2021 08:07 AM PDT I have two programs: emiter.exe - runs an infinite loop, and prints on stdout a message all the time. receiver.exe - also runs an infinite loop, waits for messages on stdin and processes them. On Unix-line systems I can run something like that and everything works well: $ emiter | receiver It of course doesn't work on PowerShell. PS first try to buffer the entire emiter 's output, and if it completes, passes it to the receiver . In our case the output will never be passed because of the infinite loop in both programs. What is the simplest workaround to emulate the Unix-like behaviour? |
Tokenizing sentences a special way Posted: 27 May 2021 08:07 AM PDT from os import listdir from os.path import isfile, join from datasets import load_dataset from transformers import BertTokenizer test_files = [join('./test/', f) for f in listdir('./test') if isfile(join('./test', f))] dataset = load_dataset('json', data_files={"test": test_files}, cache_dir="./.cache_dir") After running the code, here output of dataset["test"]["abstract"] : [['eleven politicians from 7 parties made comments in letter to a newspaper .', "said dpp alison saunders had ` damaged public confidence ' in justice .", 'ms saunders ruled lord janner unfit to stand trial over child abuse claims .', 'the cps has pursued at least 19 suspected paedophiles with dementia .'], ['an increasing number of surveys claim to reveal what makes us happiest .', 'but are these generic lists really of any use to us ?', 'janet street-porter makes her own list - of things making her unhappy !'], ["author of ` into the wild ' spoke to five rape victims in missoula , montana .", "` missoula : rape and the justice system in a college town ' was released april 21 .", "three of five victims profiled in the book sat down with abc 's nightline wednesday night .", 'kelsey belnap , allison huguet and hillary mclaughlin said they had been raped by university of montana football players .', "huguet and mclaughlin 's attacker , beau donaldson , pleaded guilty to rape in 2012 and was sentenced to 10 years .", 'belnap claimed four players gang-raped her in 2010 , but prosecutors never charged them citing lack of probable cause .', 'mr krakauer wrote book after realizing close friend was a rape victim .'], ['tesco announced a record annual loss of £ 6.38 billion yesterday .', 'drop in sales , one-off costs and pensions blamed for financial loss .', 'supermarket giant now under pressure to close 200 stores nationwide .', 'here , retail industry veterans , plus mail writers , identify what went wrong .'], ..., ['snp leader said alex salmond did not field questions over his family .', "said she was not ` moaning ' but also attacked criticism of women 's looks .", 'she made the remarks in latest programme profiling the main party leaders .', 'ms sturgeon also revealed her tv habits and recent image makeover .', 'she said she relaxed by eating steak and chips on a saturday night .']] I would like that each sentence to have this structure of tokenizing. How can I do such thing using huggingface? In fact, I think I have to flatten each list of the above list to get a list of strings and then tokenize each string. |
Problems with any graph output in SAS Posted: 27 May 2021 08:07 AM PDT Whatever function I use to generate a graph in SAS, even a simple proc gchart data=data; vbar hello / type=percent; run; I get this error ERROR: The PNG driver can not find any fonts. No output will be created. ERROR: The PNG driver can not find any fonts. No output will be created. ERROR: Physical file does not exist, C:\Windows\Fonts\sasmono.ttf.. WARNING: No output destinations active. Do you have any idea about the error? Thanks |
How to parse apt no from the address field in SQL [closed] Posted: 27 May 2021 08:07 AM PDT Data '250 Cambridge ST 305' '30 ACKERS AVE 2' I NEED TO EXTRACT LAST NUMBER IN THE DATA AS APTNO? enter image description here My data in the below picture. I m almost there to get my results but i want the number and also when there is APt i want number with APT as well |
Data validation error in Django Serializer Posted: 27 May 2021 08:07 AM PDT I am trying to add multiple ManytoMany relationship in a model but when I am trying to add the data it shows OrderedDict() in the validated data in serializer Models.py class Client(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, primary_key=True) client_name = models.CharField(max_length=500, default=0) client_shipping_address = models.CharField(max_length=500, default=0,blank=True, null=True) class Group(models.Model): emp = models.ForeignKey(Employee, on_delete=models.CASCADE) #try user name = models.CharField(max_length=500, default=0) groupmodels = models.ManyToManyField(GroupModels) sender_clients = models.ManyToManyField(Client) receiver_clients = models.ManyToManyField(ReceiverClient) warehouses = models.ManyToManyField(Warehouse) Views.py class GroupsCreateAPIView(CreateAPIView): permission_classes = (permissions.IsAuthenticated,) def post(self, request, *args, **kwargs): d = request.data.copy() print(d) serializer = GroupsSerializer(data=d) if serializer.is_valid(): serializer.save() print("Serializer data", serializer.data) return Response(serializer.data, status=status.HTTP_201_CREATED) else: print('error') return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) Serilalizer.py class GroupSenderClientSerializer(serializers.ModelSerializer): class Meta: model = Client fields = "__all__" read_only_fields = ('user',) class GroupsSerializer(serializers.ModelSerializer): groupmodels = GroupModelsSerializer(many=True) sender_clients = GroupSenderClientSerializer(many=True) receiver_clients = ReceiverClientSerializer(many=True) warehouses = WarehouseSerializer(many=True) class Meta: model = Group fields = "__all__" def create(self, validated_data): print("v data", validated_data) items_objects = validated_data.pop('groupmodels', None) sc_objects = validated_data.pop('sender_clients', None) rc_objects = validated_data.pop('receiver_clients', None) ware_objects = validated_data.pop('warehouses', None) prdcts = [] sc = [] rc = [] ware = [] for item in items_objects: i = GroupModels.objects.create(**item) prdcts.append(i) instance = Group.objects.create(**validated_data) print("sc objects", sc_objects) if len(sc_objects)>0: for i in sc_objects: print("id", i['id']) inst = Client.objects.get(pk=i['id']) sc.append(inst) if len(rc_objects)>0: for i in rc_objects: inst = ReceiverClient.objects.get(pk=i['id']) rc.append(inst) if len(ware_objects)>0: for i in ware_objects: inst = Warehouse.objects.get(pk=i['id']) ware.append(inst) instance.groupmodels.set(prdcts) instance.sender_clients.set(sc) instance.receiver_clients.set(rc) instance.warehouses.set(ware) return instance The initial data in the serializer is like the following initial_data = {'name': '546', 'emp': 14, 'sender_clients': [{'id': 3}, {'id': 4}], 'receiver_clients': [], 'warehouses': [], 'groupmodels': []} validated_data = {'groupmodels': [], 'sender_clients': [OrderedDict(), OrderedDict()], 'receiver_clients': [], 'warehouses': [], 'name': '546', 'emp': <Employee: Employee object (14)>} Please help me figure out why the sender_clients is converted to blank dicts and how do I change it? |
Prevent generation of explicit `private` modifier in VS Code for C#? Posted: 27 May 2021 08:08 AM PDT How can I prevent the private access modifier from being explicitly added in VS Code for C# when generating members? This is needed to comply with my company's coding standards. E.g. I have the error: The name 'foo' does not exist in the current context [Assembly-CSharp]csharp(CS0103) I focus the caret at the foo(); with the help of the cursor. Press Ctrl+. and select the Generate method 'MyClass.foo' Here is the method which gets generated: private void foo() { throw new NotImplementedException(); } As you can see I am getting the private modifier being added. I do the method generation quite often and in my project, the accepted style is to avoid adding the default modifiers. So, I have to go and manually remove the private . Here is what I want to be generated instead of the one I showed above: void foo() { throw new NotImplementedException(); } I tried searching for the private , accessibility settings in VS Code but found nothing. Given that VS Code is quite configurable, I am expecting to be able to set up this config as well. If you know how to do that, could you share it with me, please? |
HttpClient: "HttpRequestException: An error occurred while sending the request" Posted: 27 May 2021 08:07 AM PDT I'm trying to get a image using HttpClient and I'm getting this error: HttpRequestException: An error occurred while sending the request Using WebClient with DownloadData method, works fine. var cookieContainer = new CookieContainer(); using (var handler = new HttpClientHandler() { CookieContainer = cookieContainer }) using (var client = new HttpClient(handler)) { client.DefaultRequestHeaders.Add("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/61.0.3163.100 Safari/537.36"); client.DefaultRequestHeaders.Add("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8"); client.DefaultRequestHeaders.Add("Accept-Encoding", "gzip, deflate"); client.DefaultRequestHeaders.Add("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/61.0.3163.100 Safari/537.36"); client.DefaultRequestHeaders.Add("Accept-Language", "pt-BR,pt;q=0.8,en-US;q=0.6,en;q=0.4"); client.DefaultRequestHeaders.Add("Upgrade-Insecure-Requests", "1"); client.GetAsync("cookieGenerateUrl").Wait(); client.DefaultRequestHeaders.Remove("Accept"); client.DefaultRequestHeaders.Add("Accept", "image/webp,image/apng,image/*,*/*;q=0.8"); var imagem = client.GetByteArrayAsync(imageUrl).Result; } What is the equivalent to WebClient.DownloadData on HttpClient class? |
How to generate a random UUID which is reproducible (with a seed) in Python Posted: 27 May 2021 08:07 AM PDT The uuid4() function of Python's module uuid generates a random UUID, and seems to generate a different one every time: In [1]: import uuid In [2]: uuid.uuid4() Out[2]: UUID('f6c9ad6c-eea0-4049-a7c5-56253bc3e9c0') In [3]: uuid.uuid4() Out[3]: UUID('2fc1b6f9-9052-4564-9be0-777e790af58f') I would like to be able to generate the same random UUID every time I run a script - that is, I'd like to seed the random generator in uuid4() . Is there a way to do this? (Or achieve this by some other means)? What I've tried so far I've to generate a UUID using the uuid.UUID() method with a random 128-bit integer (from a seeded instance of random.Random() ) as input: import uuid import random rd = random.Random() rd.seed(0) uuid.UUID(rd.getrandbits(128)) However, UUID() seems not to accept this as input: Traceback (most recent call last): File "uuid_gen_seed.py", line 6, in <module> uuid.UUID(rd.getrandbits(128)) File "/usr/lib/python2.7/uuid.py", line 133, in __init__ hex = hex.replace('urn:', '').replace('uuid:', '') AttributeError: 'long' object has no attribute 'replace' Any other suggestions? |
No comments:
Post a Comment