How to get value from response of axios get in react Posted: 24 Oct 2021 08:22 AM PDT I am trying to get values from a table to show in my dropdown list in react however when I console.log my dropdown value I am getting [object][object] as my return. How do I get the values from my table to show in the return. This is my code: componentDidMount = () => { this.getLocations(); }; getLocations = data => { console.log('Hello'); var Items = []; const apiUrl = 'http://localhost:44303/api/observation/'; axios.get('https://localhost:44303/api/observation/GetLocations').then(response => { response.data.map(item => { Items = item; this.setState({ locations: Items }); //this.setState({ locations: response.data }); }); console.log('DDL:' + this.state.locations); }); }; locations is a state variable how do I get my response to show value of the table |
PersonalInfo matching query does not exist Posted: 24 Oct 2021 08:22 AM PDT I wanted to add a multiple choice field to my form and after searching I finally made it work. however, when I create a new user and try to fill the personal info form, it gives me PersonalInfo matching query does not exist error. these are my codes: models.py: class Field(models.Model): id = models.AutoField(primary_key=True) slug = models.CharField(max_length=16, default='default') title = CharField(max_length=32) class PersonalInfo(models.Model): id = models.AutoField(primary_key=True) isCompleted = models.BooleanField(default=False) interested_fields = models.ManyToManyField(Field, blank=True) forms.py: class InterestedFieldsForm(forms.ModelForm): interested_fields = forms.ModelMultipleChoiceField(widget=forms.CheckboxSelectMultiple, queryset=Field.objects.all(), required=False) class Meta: model = PersonalInfo fields = ['interested_fields'] views.py: class PersonalView(View): template_name = 'reg/personal.html' def get(self, request, *args, **kwargs): context = {} context['fields'] = Field.objects.all() return render(request, self.template_name, context=context) def post(self, request, *args, **kwargs): user = request.user if request.method == 'POST': form = InterestedFieldsForm(request.POST, instance=PersonalInfo.objects.get(user=user)) if form.is_valid(): profile = form.save(commit=False) profile.user = request.user profile.save() form.save_m2m() else: form = InterestedFieldsForm() return render(request, 'reg/done.html', context={'form': form}) I know that the issue is because of this line in views: form = InterestedFieldsForm(request.POST, instance=PersonalInfo.objects.get(user=user)) when I remove the instance, the form gets saved as the users' personal info but the interested_field wont save. then again I put instance back and try to save the form and everything works just fine. what is causing this problem? |
Apply modifier to Image like in AsyncImage Posted: 24 Oct 2021 08:21 AM PDT my goal is to have a custom AsyncImage View because I need to authenticate my request. Therefore I have created a custom struct which implements this. Now my only problem is that I want to add modifiers to my loaded Image. Something like this: CustomAsyncImageView(dataKey: dataKey) { image in image .resizable() } placeholder: { Rectangle() } What I tried: struct CustomAsyncImageView<Content> : View where Content : View { var content: Content var image: Image? // I left out the Image loading public init<I, P>(dataKey: String, @ViewBuilder content: @escaping (Image) -> I, @ViewBuilder placeholder: @escaping () -> P) { // I have this init from AsyncImage, but I have no idea how to initialize my properties } var body: some View { if let image = image { image } else { // show placeholder } } } Is this type of initialization possible to implement or should I pass the viewModifier as a parameter? |
Share details view to modal in django Posted: 24 Oct 2021 08:21 AM PDT Getting stuck to share details view to modal. Found this answer but can't understand it properly. I am sharing my code below. Views.py from django.shortcuts import render from .models import Post from django.views.generic.list import ListView from django.urls import reverse_lazy class PostListView(ListView): model = Post context_object_name = 'posts' template_name = 'f_home/index.html' models.py from django.db import models from django.contrib.auth.models import User # Create your models here. class Post(models.Model): name = models.CharField(max_length=200, blank=True) email=models.CharField(max_length=200, blank=True) address=models.CharField(max_length=400, blank=True) weblink = models.URLField(max_length=200) image = models.ImageField( default='default.png', upload_to='uploads/%Y/%m/%d/') author = models.ForeignKey(User, on_delete=models.CASCADE) def __str__(self): return f'Added {self.name} Profile' Template {% for post in posts %} <div class="purple card"> <div class="image"> <img src="{{ post.image.url }}"> </div> <div class="content"> <div class="header"><a href="{{ post.weblink }}">{{ post.name }}</a></div> </div> <div class="ui bottom attached button" onclick="pop()"> <i class="globe icon"></i> <p>View Details</p> </div> </div> {% endfor %} <div class="ui modal"> <i class="close icon"></i> <div class="header"> Modal Title </div> <div class="image content"> <div class="ui medium image"> <img src="{% static 'images/cool-background.png' %}"> </div> <div class="description"> <div class="ui header">We've auto-chosen a profile image for you.</div> <p>We've grabbed the following image from the <a href="https://www.gravatar.com" target="_blank">gravatar</a> image associated with your registered e-mail address.</p> <p>Is it okay to use this photo?</p> </div> </div> </div> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js" integrity="sha512-894YE6QWD5I59HgZOGReFYm4dnWc1Qt5NtvYSaNcOP+u1T9qYdvdihz0PPSiiqn/+/3e7Jo4EaG7TubfWGUrMQ==" crossorigin="anonymous"></script> <script type="text/javascript"> function pop(){ $('.ui.modal').modal('show'); } </script> I want to show a brief listview with a details button. If the user wants to see the details it will open a pop modal with details according to model data. Can't find any logic on how do I do that. How do I pass details value to modal using post id from details button in the same template file? |
flutter - set snappings for drag showModalBottomSheet Posted: 24 Oct 2021 08:20 AM PDT I want to use a modal bottom sheet in the flutter. but I can't drag it. showModalBottomSheet( context: context, isScrollControlled: true, isDismissible: true, enableDrag: true, shape: RoundedRectangleBorder( borderRadius: BorderRadius.vertical(top: Radius.circular(20),), ), clipBehavior: Clip.antiAliasWithSaveLayer, builder: (context) { return StreamBuilder( stream: controller.stream, builder: (context, snapshot) => GestureDetector( behavior: HitTestBehavior.translucent, child: Container( height: snapshot.hasData ? snapshot.data as double : pageWidth * .9, child: PlayerCardDialog( epdId: episodes[index['Ep_ID'])), ),); }); can anyone help me please? how can I drag the bottom sheet and how can I set snapping for it in four positions ([0.3, 0.6, 0.9, 1.0]). like this : |
error: local variables referenced from an inner class must be final or effectively final Android Java Posted: 24 Oct 2021 08:20 AM PDT I want to create an API method that works to check whether the user already exists or not that can be called from all over the place. I want this method to return a boolean value, true/false. My code is like this: public boolean isUserExistBool(String type, String username, Context context) { boolean val = true; final ProgressDialog dialog = Functions.showProgressDialog(context, context.getString(R.string.please_wait), context.getString(R.string.please_wait)); dialog.show(); RestApi restApi = RetroFit.getInstanceRetrofit(); Call<SignIn> responseCall = restApi.getUserData( type, username ); responseCall.enqueue(new Callback<SignIn>() { @Override public void onResponse(Call<id.wifi.myapp.model.SignIn> call, Response<SignIn> response) { dialog.dismiss(); if (response.isSuccessful()) { String result = response.body().getResult(); String msg = response.body().getMsg(); User user = response.body().getUser(); if (result.equals("1")) { Toast.makeText(context, context.getString(R.string.error_user_exist), Toast.LENGTH_LONG).show(); val = true; } else { Toast.makeText(context, "OK you're new", Toast.LENGTH_LONG).show(); val = false; } } else { Toast.makeText(context, context.getString(R.string.error_msg) + " (" + Functions.networkError(response.code(), response.message()) + ")", Toast.LENGTH_LONG).show(); val = false; } } @Override public void onFailure(Call<id.wifi.myapp.model.SignIn> call, Throwable t) { dialog.dismiss(); Toast.makeText(context, context.getString(R.string.error_msg2), Toast.LENGTH_LONG).show(); val = false; } }); return val; } But I'm getting an error warning because of my boolean declaration (boolean val = true; ) like this error: local variables referenced from an inner class must be final or effectively final. val = true; I tried to replace even though I know it won't work boolean val = true; into final boolean val = true; , but I get another error error: cannot assign a value to final variable val. val = true; However if I try to solve this with IDE auto correct (ALT + Enter ), then val = true; becomes val[0] = true; , as well as other values. How can I return true/false on every successful/failed process in this method? |
How to call the binary from a different path and open a file Posted: 24 Oct 2021 08:20 AM PDT Context I created a simple program to auto update my Public IP address on OpenDNS. To be able to use the program I need the credentials for OpenDNS site, so I created a config.json file to be able to read the credentials from it. Inside the Go project folder, calling the binary, works fine ./main http return code: 200 defining the new IP: 123.123.123.123 If I change to another folder (let's say my /home/user for example), the binary can't open the file anymore ./Documents/ip-updater-opendns/main panic: couldn't open config file config.json: open config.json: no such file or directory goroutine 1 [running]: main.loadConfigFile() /home/LUCAS.VARELA/Documents/ip-updater-opendns/main.go:50 +0x1e6 main.main() /home/LUCAS.VARELA/Documents/ip-updater-opendns/main.go:25 +0x45 I'm opening the file the following way: func loadConfigFile() Config { const ConfigFileEnv = "config.json" var config Config file, err := os.Open(ConfigFileEnv) if err != nil { panic(fmt.Errorf("couldn't open config file %s: %w", ConfigFileEnv, err)) } err = json.NewDecoder(file).Decode(&config) if err != nil { panic(fmt.Errorf("couldn't decode config file %s as Json: %w", ConfigFileEnv, err)) } return config } Why do I want to call my binary from another folder? Because I want this program to be executed by cronjob every 5 minutes. So my question is, how to solve this problem? |
4-digit seven-segment display counter in-inline assembly Posted: 24 Oct 2021 08:20 AM PDT I am trying to convert the assembly code of a 4-digit seven-segment display counter to in-line assembly so I can try it on arduino, the assembly code that I have (In theory should work) is: (Sorry in advance for not commenting every line in the code // And it's for educational purposes) .def showCount = r17 .def firstDecimalCount = r19 .def secondDecimalCount = r21 .def tmp = r16 .def tmp_10 = r18 .def zero = r20 .def zeroDP = r22 .def display = r23 ldi zero, 0x3F ldi zeroDP, 0xBF .MACRO READ_TABLE ldi ZL, LOW(@0*2) ldi ZH, HIGH(@0*2) add ZL, @1 lpm r16, Z .ENDMACRO .MACRO READ_TABLE2 ldi ZL, LOW(@0*2) ldi ZH, HIGH(@0*2) add ZL, @1 lpm r18, Z .ENDMACRO ldi tmp_10, 0x3F ldi firstDecimalCount, -1 ldi secondDecimalCount, 0 next_num: ldi showCount, 0xFF inc firstDecimalCount READ_TABLE table, firstDecimalCount cpi firstDecimalCount, 0x0A breq clear_num_1st cpi secondDecimalCount, 0x0A breq clear_num_2nd rjmp show_loop show_loop: ldi display, 0x08 out DDRB, display out PORTB, zero call delay ldi display, 0x04 out DDRB, display out PORTB, zeroDP call delay ldi display, 0x02 out DDRB, display out PORTB, tmp_10 call delay ldi display, 0x01 out DDRB, display out PORTB, tmp call delay nop dec showCount brne show_loop rjmp next_num clear_num_1st: ldi firstDecimalCount, 0 READ_TABLE table, firstDecimalCount inc secondDecimalCount READ_TABLE2 table, secondDecimalCount rjmp show_loop clear_num_2nd: ldi secondDecimalCount, 0 rjmp show_loop delay: ldi r24, 200; call wait ret wait: nop dec r24 brne wait ret loopInf: rjmp loopInf table: .DB 0x3F, 0x06, 0x5B, 0x4F, 0x66, 0x6D, 0x7D, 0x07, 0x7F, 0x4F; And I'm really confused while trying to do an in-line assembly code, I did this (I'm pretty sure I'm wrong): void setup() { } void loop() { asm volatile( "ldi r25, 0b11111111 \n" "out DDRB, r25 \n" ".MACRO READ_TABLE \n" "ldi ZL, LOW(@0*2) \n" "ldi ZH, HIGH(@0*2) \n" "add ZL, @1 \n" "lpm r16, Z \n" ".ENDM \n" ".MACRO READ_TABLE2 \n" "ldi ZL, LOW(@0*2) \n" "ldi ZH, HIGH(@0*2) \n" "add ZL, @1 \n" "lpm r18, Z \n" ".ENDM \n" "ldi tmp_10,0x3F \n" "ldi r19,-1 \n" "ldi r21,0 \n" "next_num: \n" "ldi r17, 0xFF \n" "inc r19 \n" "READ_TABLE table, r19 \n" "cpi r19, 0x0A \n" "breq clear_num_1st \n" "cpi r21, 0x0A \n" "breq clear_num_2nd \n" "rjmp show_loop \n" "show_loop: \n" "ldi r23, 0x08 \n" "out DDRB, r23 \n" "out PORTB, 0x3F \n" "call delay \n" "ldi r23, 0x04 \n" "out DDRB, r23 \n" "out PORTB, 0xBF \n" "call delay \n" "ldi r23, 0x02 \n" "out DDRB, r23 \n" "out PORTB, tmp_10 \n" "call delay \n" "ldi r23, 0x01 \n" "out DDRB, r23 \n" "out PORTB, tmp \n" "call delay \n" "nop \n" "dec r17 \n" "brne show_loop \n" "rjmp next_num \n" "clear_num_1st: \n" "ldi r19, 0 \n" "READ_TABLE table, r19 \n" "inc r21 \n" "READ_TABLE2 table, r21 \n" "rjmp show_loop \n" "clear_num_2nd: \n" "ldi r21, 0 \n" "rjmp show_loop \n" "delay: \n" "ldi r24, 200 \n" "call wait \n" "ret \n" "wait: \n" "nop \n" "dec r24 \n" "brne wait \n" "ret \n" "loopInf: \n" " rjmp loopInf \n" "table: .DB 0x3F, 0x06, 0x5B, 0x4F, 0x66, 0x6D, 0x7D, 0x07, 0x7F, 0x4F \n" );} |
Why is express-validator isAlphanumeric returning true for a blank field? Posted: 24 Oct 2021 08:20 AM PDT Using express-validator I implemented a validation for a string field. The validation first checks for minimum length and then for ocurrence of non alphanumeric. When I submit the form without filling the field, instead of firing an error only for the minimum lenght, it is also firing for the isAlphanumeric, but it shouldn't catch non alphanumerics in a blank field, right? Why is that happening and how to adjust to get the correct output? Thanks in advance. Code of the validation middleware (field is the "primeiroNome") body('primeiroNome') .trim() .isLength({min:1}).escape().withMessage('Primeiro nome deve ser preenchido') .custom() .isAlphanumeric().withMessage('Foi identificado caractere não alfa-numérico no Primeiro nome') |
I am getting "message: XML document structures must start and end within the same entity" in Android Studio Posted: 24 Oct 2021 08:22 AM PDT I am new to Android Studio. I started building an app. This is the code of my xml file. I can't figure out the problem! This is the exact error code that I am getting."ParseError at [row,col]:[60,1] Message: XML document structures must start and end within the same entity." <?xml version="1.0" encoding="utf-8"?> <androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:background="#121212" tools:context=".MainActivity" > <ImageView android:id="@+id/imageView" android:layout_width="844dp" android:layout_height="1090dp" app:layout_constraintBottom_toBottomOf="parent" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintHorizontal_bias="0.501" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toTopOf="parent" app:layout_constraintVertical_bias="0.988" app:srcCompat="@drawable/up_notch_adobespark" /> <ImageButton android:id="@+id/imageButton4" android:layout_width="50dp" android:layout_height="54dp" app:layout_constraintBottom_toBottomOf="parent" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintHorizontal_bias="0.0" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toTopOf="parent" app:layout_constraintVertical_bias="0.005" tools:srcCompat="@drawable/more_button" /> <ImageButton android:id="@+id/imageButton7" android:layout_width="59dp" android:layout_height="66dp" app:layout_constraintBottom_toBottomOf="parent" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintHorizontal_bias="0.997" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toTopOf="parent" app:layout_constraintVertical_bias="0.004" app:srcCompat="@drawable/help_icon" /> <TextView android:id="@+id/textView" android:layout_width="165dp" android:layout_height="36dp" android:fontFamily="@font/baloo_tamma" android:text="Hi Josh." android:textSize="22dp" app:layout_constraintBottom_toBottomOf="parent" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintHorizontal_bias="0.065" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toTopOf="parent" app:layout_constraintVertical_bias="0.158" /> |
Cannot access to custom object which added to collection in custom class via method Posted: 24 Oct 2021 08:22 AM PDT I have a custom class List: Private me_col As New Collection Public Function GetAt(position As Integer) GetAt = me_col(position + 1) End Function Public Sub Add(value) me_col.Add value End Sub If I add a list directly to the collection, I can get it via index. The message box will show "List": Sub Run() Dim col As New Collection Dim child As New List col.Add child MsgBox TypeName(col(1)) End Sub But if I try add it to the List via List.Add and GetAt later, the application will throw a Run-time error '438': Object doesn't support this property or method: Sub Run() Dim col As New List Dim child As New List col.Add child MsgBox TypeName(col.GetAt(0)) End Sub This work well with primitive values, only fail on objects such as custom class. |
How to call a method from an another method with ruby? Posted: 24 Oct 2021 08:23 AM PDT I have this little password generating program, I want the method print_password to call the generate_password method, but it just doesn't work require 'digest' class Challenge KEY = [ '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F', '0', '1', '2', '3' ] def initialize(email) @email = email # && raise puts 'This object was initialized!' end def print_password puts %(Password 1: {generate_password}) # Here I want to call generate_password method end private def generate_password @hash = Digest::SHA1.hexdigest(@email) @id = @hash.scan(/\d+/).map(&:to_i).inject(:+) @prng = Random.new(@id) prepare_map apply_map end def prepare_map @map = [] id_string = @id.to_s id_size = id_string.size map_string = id_string * (KEY.size.to_f / id_size).ceil 0.upto(15) do |i| @map[i] = map_string[i].to_i end @map end end def apply_map calculated_key = KEY.shuffle(random: @prng).map.with_index do |char, i| (char.bytes[0] + @map[i]).chr end calculated_key.join end me = Challenge.new('me@gmail.com') # Initialize new object me.print_password # Here I want to print the password So here at the end, it initializes a new object and then where I use me.print_password it just prints out Password 1: {generate_password} Don't know exactly what I am doing wrong here, thanks for your help in advance. |
Which videojs-transcript repo and version should be used? Posted: 24 Oct 2021 08:22 AM PDT The "working sample" for videojs-transcript, whose link is on the author's Github page uses an old version, 0.7.1. The master branch is 3 versions ahead at 0.8.1. When I attempt to run 0.8.1, it fails: "Uncaught TypeError: my._options is undefined" in videojs-transcript.js:379:5" The only way that I could get something working was to download the files used by the sample from the author's github.io page. The author did not create an npm package. But I noticed that there are two npm packages for this component: I couldn't find a corresponding code repository for videojs-transcript-acvideojs-transcript-ac. But there is a bitbucket repo for @packt/videojs-transcript. The author's working sample is from 2017. I noticed that there are more recent stackoverflow Q&A for videojs-transcript, even a couple from this year. Which repository and version number is currently being used? |
Discord has no attribute Client Posted: 24 Oct 2021 08:21 AM PDT Previous question that I have looked over suggests that the name of the file is 'Discord.py' however this isn't the issue this time. Currently I am running: import discord client = discord.Client() Which then returns AttributeError: partially initialized module 'discord' has no attribute 'Client' (most likely due to a circular import) How can I fix this? and thank you in advance |
Microsoft.CSharp.RuntimeBinder.RuntimeBinderException: ''System.__ComObject' does not contain a definition for 'Language'' Posted: 24 Oct 2021 08:22 AM PDT Microsoft.CSharp.RuntimeBinder.RuntimeBinderException: ''System.__ComObject' does not contain a definition for 'Language'' Does anyone know why I'm always getting this error? I found this code on a youtube video to make a calculator. Pleas help. private void result_Click(object sender, RoutedEventArgs e) { result.Background = Brushes.BlueViolet; Type scriptType = Type.GetTypeFromCLSID(Guid.Parse("0E59F1D5-1FBE-11D0-8FF2-00A0D10038BC")); dynamic obj = Activator.CreateInstance(scriptType, false); obj.Language = "javascript"; string str = null; try { var res = obj.Eval(screen.Text); str = Convert.ToString(res); screen.Text = screen.Text + "=" + str; } catch (SystemException) { screen.Text = "syntax error"; } |
Show map in HTML Posted: 24 Oct 2021 08:21 AM PDT I am trying to to show a map with specific coordinates in a Google map. But, it doesnt show up. I have verified that the api key is valid but, I cannot display the map: Here is the code: <script async src="https://maps.googleapis.com/maps/api/js?key=xyz&callback=initMap&libraries=&v=weekly"></script> <script> function initMap() { var latlng = new google.maps.LatLng(53.385846,-1.471385); var options = { zoom: 15, // This number can be set to define the initial zoom level of the map center: latlng, mapTypeId: google.maps.MapTypeId.ROADMAP // This value can be set to define the map type ROADMAP/SATELLITE/HYBRID/TERRAIN }; var map = new google.maps.Map(document.getElementById('map'), options); var marker1 = new google.maps.Marker({ position: new google.maps.LatLng(53.385846,-1.471385), map: map, }); } </script> Console output: Cookie "csrftoken" will be soon rejected because it has the "SameSite" attribute set to "None" or an invalid value, without the "secure" attribute. To know more about the "SameSite" attribute, read https://developer.mozilla.org/docs/Web/HTTP/Headers/Set-Cookie/SameSite profile jQuery.Deferred exception: $(...).select2 is not a function @http://localhost:8000/teampages/profile/?id=4&type=driver:714:21 e@http://localhost:8000/static/js/jquery.min.js:2:29453 l/</t<@http://localhost:8000/static/js/jquery.min.js:2:29755 undefined jquery.min.js:2:31008 jQuery.Deferred exception: e is undefined t@http://localhost:8000/static/js/jquery.flot.js:1:535 o/<@http://localhost:8000/static/js/jquery.flot.js:1:36517 o@http://localhost:8000/static/js/jquery.flot.js:1:36684 K.plot@http://localhost:8000/static/js/jquery.flot.js:1:38354 @http://localhost:8000/teampages/profile/?id=4&type=driver:728:9 e@http://localhost:8000/static/js/jquery.min.js:2:29453 l/</t<@http://localhost:8000/static/js/jquery.min.js:2:29755 undefined jquery.min.js:2:31008 Uncaught TypeError: $(...).select2 is not a function http://localhost:8000/teampages/profile/?id=4&type=driver:714 jQuery 2 profile:714:21 http://localhost:8000/teampages/profile/?id=4&type=driver:714 jQuery 2 Uncaught TypeError: e is undefined jQuery 4 http://localhost:8000/teampages/profile/?id=4&type=driver:728 jQuery 2 e t jquery.flot.js:1:535 jQuery 4 <anonymous> http://localhost:8000/teampages/profile/?id=4&type=driver:728 jQuery 2 Source map error: Error: request failed with status 404 Resource URL: http://localhost:8000/static/js/jquery.flot.js Source Map URL: jquery.flot.js.map 2 Source map error: Error: request failed with status 404 Resource URL: http://localhost:8000/static/js/bootstrap.bundle.min.js Source Map URL: bootstrap.bundle.min.js.map Source map error: Error: request failed with status 404 Resource URL: http://localhost:8000/static/js/adminlte.min.js Source Map URL: adminlte.min.js.map |
Redirect URI mismatch error from Google OAuth Posted: 24 Oct 2021 08:21 AM PDT I have a Flask web application which is hosting in Google Cloud Run which is hosted with https://mydomain.run.app. Now I am trying to add google authentication to it. I have created the API under credentials in GCP. I have given https://mydomain.run.app/authorize in the redirect uri but when I tried to login from my app it throws me redirect mismatch error. And the error shows me http://mydomain.run.app/authorize. The mismatch is the https and http When I tried to give http in the credentials uri it throws me Invalid Redirect: This app has a publishing status of "In production". URI must use https:// as the scheme. |
TypeScript `extends` conditional type statement only works if expressed using Generics? Posted: 24 Oct 2021 08:21 AM PDT I am trying to gain a better understanding of the extends keyword in TypeScript and its potential applications. One thing I have come across are two built-in utilities, Extract and Exclude that leverage both extends and Conditional Typing. /** * Exclude from T those types that are assignable to U */ type Exclude<T, U> = T extends U ? never : T; /** * Extract from T those types that are assignable to U */ type Extract<T, U> = T extends U ? T : never; I was playing around to better understand how this "narrowing down", or to better say "subset filtering" works, and have tried creating my own implementation just to see it in action, and have come across this really odd behaviour: Link to the Playground Example: type ValueSet = string | 'lol' | 0 | {a: 1} | number[] | 643; type CustomExclude<T, U> = T extends U ? T : never; // this works: // type Result1 = 0 | 643 type Result1 = CustomExclude<ValueSet, number>; // but this doesn't? // type Result2 = never type Result2 = ValueSet extends number ? ValueSet : never; Why does that happen? I would expect both instances to return the correct subset of the type, but the conditional typing only works if express through Generics. Can someone explain me the logic behind this? |
How to load weather api data in c# and inject the class into _Layout Posted: 24 Oct 2021 08:20 AM PDT I'm trying to fetch openweatherapi data and return this data as object, so later in _Layout I can inject this class and use this object. However, in _Layout I can't access to object properties. public Weather WeatherApiResult() { Weather weather = null; Task t = Task.Factory.StartNew(async () => { string city = Weather(); string apiKey = "KEY"; string URL = "https://api.openweathermap.org/data/2.5/weather?q=" + city + "&units=metric&appid=" + apiKey; var httpClient = new HttpClient(); httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("apiKey", $"{apiKey}"); var httpResponse = await httpClient.GetAsync($"{URL}"); var response = await httpResponse.Content.ReadAsStringAsync(); weather = JsonConvert.DeserializeObject<Weather>(response); }); return weather; } _Layout: @{ var weather = settingsService.WeatherApiResult(); weather.name } Update: @{ var response = settingsService.WeatherApiResult(); var name = response.Result.name; var timezone = response.Result.timezone; <p>@name</p> <p>@timezone</p> } It looks like I can access only the first-level properties name , timezone , id , cod . How can I access the nested properties? In JavaScript I would do response.main.temp for temperature. Do I need to create a Class for each nested item? |
How to return failure or success status of connection Posted: 24 Oct 2021 08:21 AM PDT I have a script in which i want to return success and failure status I am trying to make a connection with database in oracle to fetch some record , if it fails due to any error want to return success : 0 or failure : 1 Depending upon that i will decide whether to run next piece of code or not Below is my code , How to return success 0 / Failure 1 sqlplus -s -S 2>&1 << EOF ABC/ABC@localhost:1XXX/ABC set heading off verify off feedback off echo off term off pagesize 0 linesize 10000 trimout on trimspool on timing off select * from dual; exit; EOF status=$? if [ $status -eq 0 ] then echo "success" echo "Running another piece of code" else echo "fail" exit 1 fi It is not returning status values to variable status ? And i want to hide printing password on terminal Any approach how to implement will be appreciated in bash |
Maximum box coordinate value is larger than 1.100000 [closed] Posted: 24 Oct 2021 08:22 AM PDT I'm trying to train and test a model which should recognize objects in PNG images. SETTING I'm running a Conda virtual env with Python 3.8.6 with Tensorflow 2.6.0 on a M1 Mac mini. Model: SSD MobileNet V2 FPNLite 320x320 ISSUE When I run the evaluation script I get this error Summarized data: b'maximum box coordinate value is larger than 1.100000: ' X (with X ranging from 3 to 1000) If I get to make the script run, I get awful results, like AP or AR = 0.000 or -1.000 WHAT I'VE ALREADY CHECKED: The script I'm using to generate TF records(https://github.com/nicknochnack/GenerateTFRecord/blob/main/generate_tfrecord.py) normalizes boxes' xmin/xmax and ymin/ymax. \ I also checked the sanity of TF record by opening it with a viewer found here:https://github.com/sulc/tfrecord-viewer Results can be seen here: image Boxes are perfect in position and dimensions for both "training" and "testing" TF records, but -as I see from this viewer- they are entirely covered by the label name ("suspension"). \ QUESTION Could this be the cause of the issue? And if so, how could I make these "suspension tags" smaller/proportional to the small boxes? More in general: what am I doing wrong? |
Use CFFI for using Python function inside Fortran. Warnings in cffi build. I can't get results from print in console or file, but not error in running Posted: 24 Oct 2021 08:21 AM PDT Coding I followed documentation described in "CFFI Documentation Release 1.15.0" section "9.1 Usage" but with semplification, using a 'identity' function. Step 1 - plugin.h # ifndef CFFI_DLLEXPORT # if defined(_MSC_VER) # define CFFI_DLLEXPORT extern __declspec(dllimport) # else # define CFFI_DLLEXPORT extern # endif
|
No comments:
Post a Comment