Friday, May 14, 2021

Recent Questions - Stack Overflow

Recent Questions - Stack Overflow


My design elements are missing in the eclipse window builder

Posted: 14 May 2021 08:08 AM PDT

Missing design elements

Does anyone know how to fix this? I've tried running old version of eclipse but haven't had any luck. I've also installed the window builder version from the marketplace which also did nothing.

I want to make an Attendence Page in Flutter and on that the page should look like this as I am new to flutter I have figured it out that List Tile

Posted: 14 May 2021 08:08 AM PDT

React js role based routing - Restrict unauthorized access

Posted: 14 May 2021 08:08 AM PDT

I have a react js application with 2 routing sections /admin and /user.

Admin's default route is /admin/dashboard and user's default route is /user/dashboard.

I have the following routes for admin and I am using renderRoutes from react-router-config

{  path: '/admin',  component: AdminContainer,  routes: [    {      path: '/admin/login',      component: AdminLogin,    },    {      path: '/admin/dashboard',      component: AdminDashboard    },    {      path: '/admin/profile/create',      component: CreateProfile    },    {      path: '/admin/profile/approve',      component: ProfileApprove    },    {      path: '/admin/media/approve',      component: MediaApprove    },    notFoundRoute  ]  

},

I want to restrict non-admin users to access /admin routes and to show unauthorized page. How can I do this?

setting custom errors inside Route Groups in Codeigniter 4

Posted: 14 May 2021 08:08 AM PDT

Today, I was exploring Codeigniter 4 and I got stuck while setting custom 404 error inside route group.

$routes->group('admin', function ($routes) {      $routes->add('page', 'Welcome::index');      $routes->set404Override(function () {          echo 'Not Found admin';      });  });    $routes->group('user', function ($routes) {      $routes->add('page', 'Welcome::index');      $routes->set404Override(function () {          echo 'Not Found user';      });  });   

When I hit /admin/123 url, I should get 'Not Found admin'. Instead what I am getting is 'Not found user'. Can someone please help me what I am doing wrong or is it a bug? How can I manage to get separate 404 errors based on Route Groups.

Getting documents of CefSharp Winforms

Posted: 14 May 2021 08:07 AM PDT

How I can get the source document of a CefSharp chromium browser in winforms by C#?

Change text with jQuery then change again

Posted: 14 May 2021 08:07 AM PDT

I have an ajaxified Woocommerce 'Add to cart' button which adds the product to the cart. The text on the button changes to 'Added to cart'. After a delay of say, 3 seconds I would like to change it back to 'Add to cart'.

if( response.success ) {      $this.text("added to cart");      $( document.body ).trigger( 'wc_fragment_refresh' );      $this.delay(5000).text("Add to cart");      $('.gift-with-coupon').slideUp();  }  

I have tried this, a while the product is added to the cart via Ajax, the text doesn't got from 'Add to cart - Added to cart - Add to cart'. It just skips the middle one. Any ideas?

Thanks.

How to create a agreement form using signature in flutter?

Posted: 14 May 2021 08:07 AM PDT

I am building a flutter app where I need an agreement form with the user's signature. Currently I am using signature package but it only allows the signature to be saved as standalone image. What I want is the signature should appear at the bottom of an agreement form and the entire thing to be saved as an image like the example given in attached image)enter image description here Can you please help how to achieve this?

How can I convert functions in classs-bsed component to functional components in react

Posted: 14 May 2021 08:07 AM PDT

I'm trying to convert my class-based react component to a functional component. How should I convert functions like:

onFileUpload = async () => {            const formData = new FormData();            formData.append(              "ImageData.File",              this.state.selectedFile,              this.state.selectedFile.name          );                fetch('/api/Image', {              method: 'POST',              body: formData          }).then(resposne => resposne.json())              .then(data => {                  console.log(data);                  this.setState({ uploadResult: "File " + data.fileName + " successfully uploaded." });                  this.getList();              });        };  

Signal R .net core with SQL Server

Posted: 14 May 2021 08:08 AM PDT

We are looking to build a realtime dashboard using Signal R .net core with a MS SQL database. The database is updated from multiple locations / application, and so the requirement is that when there is a database change for a particular item, this item is automatically updated on the front end. Seems like a common request.

Having been through multiple examples from the Microsoft SignalR site, we are unable to find any documentation that supports this scenario, and any documentation that mentions SqlDependency is dated 4 / 5+ years old.

Due to the dated and lack of documentation, is this still the correct method to achieve this?

Are there any recommendations?

Make a Number field like "10,000.0000" when focusout in Oracle APEX?

Posted: 14 May 2021 08:08 AM PDT

In Oracle APEX - I tried to put below JS in Advance-> Custom Attributes property- onfocusout="this.value=Number(this.value).toFixed(4).replace(/(\d)(?=(\d{3})+(?!\d))/g, '$1,')"

and in Appearance-> Format mask -> 999G999G999G999G999G999G999G999G990D0000

but in this JS, I am getting result like- 10,000.0,000

I need result as comma separated like- 999G999G999G999G999G999G999G999G990D0000 e.g. 10,000.0000

Note: Decimal should be fixed 4 and rest values should be thousand separator. Please help me if you ever tried this.

Type-> NumberFormat{Plug In} is not working in this case, As I am getting the records from interactive report to update.

Please let me know if more information is required.

datetime returns ' in the output

Posted: 14 May 2021 08:09 AM PDT

Relatively new to coding but I'm having an interesting issue it seems.

I've managed to get an output of the previous day (for use in a .loc comparison for a dataset) and it returns the date information in '20210513' , where the expected output is 20210513.

Is there a format that would help resolve this to just an int?

Code for reference:

from datetime import datetime, timedelta        d = datetime.now() - timedelta(days=1)  date = d.strftime('%Y%m%d')  date  # This is the output that needs to be changed to int.  '20210513'  

Calculating weighted percentages/frequencies with dplyr in R

Posted: 14 May 2021 08:08 AM PDT

I have 100+ columns and 10k+ rows, where columns are variables and rows are respondents. Two of the variables are those by which I wish to make data cuts (in example below: group1 and group2). One of the columns (variables) is weights, which I calculated for each respondent.

I want to get a summary of each variable (most of them are categorical) that takes into account weights and groups by the two variables. Here's how the dataset looks:

respondent var1 var2 group1 group2 weights
1 Yes No Yellow Tall 0.323
2 No Maybe Black Short 0.576
3 Maybe NA Brown Short 0.123
4 NA Yes Red Tall 0.543
5 No Yes Purple Tall 0.862

Feels very simple, but I'm pretty lost.

Expected outcome:

variables YellowTall YellowShort BlackTall BlackShort
var1 weighted % weighted % weighted % weighted %
var2 weighted % weighted % weighted % weighted %
etc.

Powershell adding sequencial numbering in pscustomobject element

Posted: 14 May 2021 08:09 AM PDT

I've a $List = @([pscustomobject]) with this values. The idea is to add a sequencial numbering in each element.

 Topic   -----  los juegos  el arte  los animales  la música  los juegos  la vida de antes  los juegos  el arte  la música  la vida de antes  los juegos  

How can i add a sequencial numbering each element ? Like this:

$List.topic     Topic   -----  los juegos_1  el arte_2  los animales_3  la música_4  los juegos_5  la vida de antes_6  los juegos_7  el arte_8  la música_9  la vida de antes_10  los juegos_11  

Thanks for any help on this, I'm using this code

 $i = 1   Foreach ($rt in $List){$rt.Topic = $rt.Topic{0:D4} -f $i++}  

But the result is this :

los animales10:D4  la música10:D4  

What I'm doing wrong?

Getting java.sql.SQLException: Access denied for user ''@'localhost' (using password: NO)

Posted: 14 May 2021 08:08 AM PDT

I am trying to build and learn about Spring boot application but when i am starting my application getting this error : java.sql.SQLException: Access denied for user ''@'localhost' (using password: NO)

Here is my application.properties file configuration

#changing server port at localhost  server.port=8080    #mysql database configuration  spring.datasource.url=jdbc:mysql://localhost:3306/myhiber  spring.datasource.data-username= root  spring.datasource.data-password= password  spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver    #Hibernate Configuration  spring.jpa.hibernate.ddl-auto=update  spring.jpa.show-sql=true  spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MySQL57Dialect  

================================================================================

I have tried many online solution for this but nothing worked for me some solutions which is tried : Provided Permission to root user i am able to connect mysql direct with my shell

Help me please with that.enter image description here

Move file to a directory with a given condition using Bash

Posted: 14 May 2021 08:08 AM PDT

First of all, thank you for your help. I have a problem trying to move a file to a directory. I have the next directories: Animals Boat Carsand I want to move the following files Animals.txt Boat.txt and Car.txt I want to do it so if the name of the file matches the name of the directory it moves to it, instead of doing the following code:

mv Animals.txt Animals  

Finding average of values every 160 lines using awk [closed]

Posted: 14 May 2021 08:08 AM PDT

I have 32160 lines and I need to find the average of every 160 lines in the file i.e. average of the first 160 values, then the next etc (201 averages in total). I assume this can be done in bash using awk but I am unsure about how to specify the average for 160 lines.

Spring data jpa operation between table views

Posted: 14 May 2021 08:08 AM PDT

in my spring data application i have two TABLE VIEW mapped: the first view

@Entity  @Immutable  @Table(name="VD_CONT")  @NamedQuery(name="VdContr.findAll", query="SELECT d FROM VdContr d")    public class VdContr  {            @Id      @Column(name="CONTR_ID")      private Long id;                @Column(name="CF")      private String cf;     @OneToMany(fetch=FetchType.LAZY, cascade = CascadeType.ALL, mappedBy="vdcontr")  private List<VdArr> vdArr;  }  

and the second view

@Entity  @Immutable  @Table(name="VD_ARR")  @NamedQuery(name="VdArr.findAll", query="SELECT v FROM VdArr v")  public class VdArr {                   @Id          @Column(name="ARR_ID")          private Long id;                          @Column(name="FK_CONTR_ID")          private Long fkContrId;          @ManyToOne(fetch=FetchType.LAZY)         public VdContr vdcontr;          }  

If i put a relationship "OneToMany" and "ManyToOne" (1, first view : many, second view), i receive errors. My question is: is it possibile create a relationship between two table view?

SQL Server SUM with conditions

Posted: 14 May 2021 08:08 AM PDT

Good morning Srs I am a beginner in SQL Server and I have a question: Do you know how to make a sum (SUM) of shift 3 of a company and organize it by day? The problem is that shift 3 ends the next day (starts at 10 pm and ends at 6 am the next day), so I'm trying to make an exception only for shift 3 that on the current day disregards the values ​​obtained before 6 am and disappears from 10 pm until 6 am the next day. Below is the script that I already made and the result obtained In the result obtained in Turn 3 today (the 14th is already with data produced, but this data should be from shift 3 of yesterday) If someone helps me, thank you

SELECT   STR(DAY(E3TimeStamp),2) + '/' + STR(MONTH(E3TimeStamp),1) + '/' + STR(YEAR(E3TimeStamp),4) AS Data,  Maquina AS Maquina,  Parametro AS Código,  ROUND(sum(Metrica),2) AS 'Metrica Total' ,  ROUND(SUM(CASE WHEN Turno = 1 THEN Metrica ELSE 0 END),2) As 'Metrica Turno 01',  ROUND(SUM(CASE WHEN Turno = 2 THEN Metrica ELSE 0 END),2) As 'Metrica Turno 02',  ROUND(SUM(CASE WHEN Turno = 3 THEN Metrica ELSE 0 END),2) As 'Metrica Turno 03'  FROM Tab_Dados_Escolha  GROUP BY   YEAR(E3TimeStamp), MONTH(E3TimeStamp),DAY(E3TimeStamp), Maquina, Parametro  

Result obtained from the script above: enter image description here

Result that should occur (Shift 03 was added to the previous day, as it has not yet started today): enter image description here

Kotlin io socket never reaches backend

Posted: 14 May 2021 08:08 AM PDT

I have a PHP backend, that creates a websocket server with Ratchet and a Kotlin frontend. When I try to connect to my backend server with another computer, it works perfectly fine. (So I made sure, it´s not a firewall problem) On the other computer I just copied the example from the tutorial and entered:

var conn = new WebSocket('ws://<my-ip>:80');  conn.onopen = function(e) {      console.log("Connection established!");  };    conn.onmessage = function(e) {      console.log(e.data);  };  

and I log new connections on the server. Which indeed reacted to that call with a log of a new connection. However, interesting enough, the browser on the other pc never logged "Connection established!". But when I try to connect with my Android phone using my Kotlin app, it is even worse: The connection never even reaches the backend! There´s no log saying a new connection established. In addition the Socket on the phone fires neither the "Connection" nor the "Connection_Error" event. Here`s how I initialize the Socket in Kotlin. I am using 'io.socket:socket.io-client:2.0.1':

import io.socket.client.IO  import io.socket.client.Socket  import java.net.URI  import com.google.gson.GsonBuilder    class ChatActivity : AppCompatActivity() {      private lateinit var socket : Socket      override fun onCreate(savedInstanceState: Bundle?) {          super.onCreate(savedInstanceState)          setContentView(R.layout.activity_chat)          val uri = URI.create("ws://192.168.1.23:80")          val options = IO.Options.builder().build()          socket = IO.socket(uri, options)      }      fun onSend(view : View) {          val message = Message(//some values)          val gson = GsonBuilder().setLenient().setDateFormat("yyyy-MM-dd HH:mm:ss Z").create()          val jsonObject = gson.toJson(message)          socket.once("message") {             @Override             fun call(vararg args : Objects) {                 val response = args[0]             }          }          socket.connect()                 .once(Socket.EVENT_CONNECT) {                       socket.send(jsonObject)                  }                  .once(Socket.EVENT_CONNECT_ERROR) {                       socket.send(jsonObject)                  }      }    

Yes, I am totally aware, that there is absolutely no sense to sending on connection error, but I just needed some random line I could break on, to see if it even reaches there. I also added the <uses-permission android:name="android.permission.INTERNET" /> in my manifest.

On backend I work with Ratchet. Have a simple Connection-File, that doesn´t do much more than establishing connection right now:

use Ratchet\ConnectionInterface;  use Ratchet\MessageComponentInterface;    class SocketConnection implements MessageComponentInterface  {      protected \SplObjectStorage $clients;      public function __construct() {          $this->clients = new \SplObjectStorage;      }        function onOpen(ConnectionInterface $conn)      {          $this->clients->attach($conn);          error_log("New client attached");      }        function onClose(ConnectionInterface $conn)      {          $this->clients->detach($conn);      }        function onError(ConnectionInterface $conn, \Exception $e)      {          echo "An error has occurred: {$e->getMessage()}\n";            $conn->close();      }        function onMessage(ConnectionInterface $from, $msg)      {          //do some message stuff then      }  }  

Dependency is "cboden/ratchet": "0.4.3.*" And then I have my server.php like that:

<?php    use Ratchet\Server\IoServer;  use agroSMS\Websockets\SocketConnection;  use Ratchet\WebSocket\WsServer;  use Ratchet\Http\HttpServer;    require dirname(__DIR__) . '/vendor/autoload.php';    $server = IoServer::factory(      new HttpServer(          new WsServer(              new SocketConnection()          )      )  );    $server->run();  

Which I start from the command shell. Like I said, when the other laptop connects with a JS websocket, it logs the connection, when I try to connect with my Android phone, no log, nothing seems to reach the backend. Did I forget something?

Edit: To ensure clarity, the "onSend"-method is called on a button press. Didn´t include the xml-file here (since I didn´t consider it relevant), but I know, that it is being called, since the debugger stops at the breakpoint first line in the onSend-method.

Step to continue [closed]

Posted: 14 May 2021 08:08 AM PDT

how to force people to select the file and then only continue in CSharp WPF i only need user to continue only when they select a file from open dialog so that the application can read the file the people have selected.

I have tried to search all over website but nothing results found.

How can i wait for a program to end and then automatically start a second program in the Linux console?

Posted: 14 May 2021 08:08 AM PDT

How can I wait for a program to complete and then start another program automatically in another console?

EDIT: The first program can be long running and the other program should start right after the completion of the first program.

Create a class with getters based on the properties of another class

Posted: 14 May 2021 08:08 AM PDT

Say I have a class A with a hundred properties:

class A {    FOO = "foo";    BAR = "bar";    // (...) 98 more properties  }  

In typescript, how does one go about dynamically defining a class B with one getter for each property of class A?
The corresponding statically defined class B would look like this:

class B {    get FOO() {      someFunction('FOO');    }      get BAR() {      someFunction('BAR');    }      // (...) 98 more getters  }  

The relation between these classes is as follows:

  • a getter name in B is equal to property name in A
  • the body of getter in B is exactly the call of function someFunction with a single argument that is a string with the name of the getter

How do I split a PDF in google cloud storage using Python

Posted: 14 May 2021 08:08 AM PDT

I have a single PDF that I would like to create different PDFs for each of its pages. How would I be able to so without downloading anything locally? I know that Document AI has a file splitting module (which would actually identify different files.. that would be most ideal) but that is not available publicly.

I am using PyPDF2 to do this curretly

    list_of_blobs = list(bucket.list_blobs(prefix = 'tmp/'))      print(len(list_of_blobs))      list_of_blobs[1].download_to_filename('/' + list_of_blobs[1].name)            inputpdf = PdfFileReader(open('/' + list_of_blobs[1].name, "rb"))        individual_files = []      stream = io.StringIO()            for i in range(inputpdf.numPages):          output = PdfFileWriter()          output.addPage(inputpdf.getPage(i))          individual_files.append(output)          with open("document-page%s.pdf" % (i + 1), "a") as outputStream:              outputStream.write(stream.getvalue())              #print(outputStream.read())              with open(outputStream.name, 'rb') as f:                  data = f.seek(85)                  data = f.read()                  individual_files.append(data)                  bucket.blob('processed/' +  "doc%s.pdf" % (i + 1)).upload_from_string(data, content_type='application/pdf')    

In the output, I see different PyPDF2 objects such as <PyPDF2.pdf.PdfFileWriter object at 0x12a2037f0> but I have no idea how I should proceed next. I am also open to using other libraries if those work better.

Open A Webpage Upon An Incoming Phone Call

Posted: 14 May 2021 08:08 AM PDT

I have a (hopefully) simple question about RingCentral capabilities.

Namely, is is possible to open a URL in a call center rep's browser upon an incoming phone call?

For instance, if (555) 321-1234 calls, is it possible to open a web browser to the URL:

site.com/call?number=5553211234

If it is possible, what is the feature called (so I can look up tutorials)?

Crystal Reports 8.5 SetDataSource generates empty error message

Posted: 14 May 2021 08:08 AM PDT

I have a VB6 application that uses Crystal Reports 8.5 to view reports. I now have created a new report that uses an SQL Server stored procedure as a data source. When viewing this report in my application I use a ADODB.Recordset as a data source for the report. The problem is that Crystal Reports fails to show the report. It only shows an empty database error message, and an informational warning that the "Server has not yet been opened.".

I googled like my life depends on it but I only found examples of wokring situations that do exactly what I am doing. Sometimes with some minor differences but I tried them all. They keep ending with the same error messages.

This is my code to fill the recordset.

Dim Records As ADODB.Recordset  Dim Cmd As ADODB.Command  Set Cmd = New ADODB.Command  Cmd.ActiveConnection = clSQL.DBConnection   '< -- Existing connection that uses CursorLocation adUseClient  Cmd.CommandType = adCmdStoredProc  Cmd.CommandText = "SPCrystalReports"    Cmd.Parameters.Append Cmd.CreateParameter("ReportType", adVarChar, adParamInput, 256, Soort)  Cmd.Parameters.Append Cmd.CreateParameter("ReportFile", adVarChar, adParamInput, 256, RapportNaam)  Cmd.Parameters.Append Cmd.CreateParameter("Template", adVarChar, adParamInput, 256, Template)  Cmd.Parameters.Append Cmd.CreateParameter("WhereClause", adVarChar, adParamInput, 8000, CentralSQL)  Cmd.Parameters.Append Cmd.CreateParameter("WhereClause2", adVarChar, adParamInput, 8000, ExtraSQL)  Cmd.Parameters.Append Cmd.CreateParameter("Date", adDate, adParamInput, , Datum)  Cmd.Parameters.Append Cmd.CreateParameter("DateFrom", adDate, adParamInput, , DatumVan)  Cmd.Parameters.Append Cmd.CreateParameter("DateTo", adDate, adParamInput, , DatumTot)    Set Records = Cmd.Execute    Set Cmd = Nothing  

This is how I load my report:

Dim crApp As CRAXDRT.Application  Dim crRep As CRAXDRT.Report    Set crApp = New CRAXDRT.Application  Set crRep = crApp.OpenReport(ReportFile, 1)  

And then I tried the folowing code samples to get the report working.

Sample 1:

crRep.DiscardSavedData  crRep.Database.SetDataSource Records  

Sample 2:

crRep.DiscardSavedData  crRep.Database.SetDataSource Records, 3, 1  

Sample 3:

crRep.Database.Tables(1).SetLogOnInfo DBServer, DBDatabase, DBUser, DBPass  crRep.DiscardSavedData  crRep.Database.SetDataSource Records, 3, 1  

Sample 4:

crRep.DiscardSavedData  crRep.Database.Tables(1).SetDataSource Records, 3  

Sample 5:

crRep.Database.Tables(1).SetLogOnInfo DBServer, DBDatabase, DBUser, DBPass  crRep.DiscardSavedData  crRep.Database.Tables(1).SetDataSource Records, 3  

Sample 6:

crRep.DiscardSavedData  crRep.Database.Tables(1).SetPrivateData 3, Records  

Sample 7:

crRep.Database.Tables(1).SetLogOnInfo DBServer, DBDatabase, DBUser, DBPass  crRep.DiscardSavedData  crRep.Database.Tables(1).SetPrivateData 3, Records  

They all end up with this error popup followed by the information popup.

Empty error message Information popup

How to get this working?

m2m 'through' field in django models throwing this error: 'M2M field' object has no attribute '_m2m_reverse_name_cache'

Posted: 14 May 2021 08:08 AM PDT

Hey guys I am trying to add a m2m through field to have assistants to my 'Department' model to call like department.assistants.all(), but while doing so, I am getting this error AttributeError: 'ManyToManyField' object has no attribute '_m2m_reverse_name_cache'.

This is my model:

class Department(models.Model):      id                  = models.BigAutoField(primary_key=True)      user                = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)      assistants          = models.ManyToManyField(settings.AUTH_USER_MODEL, through='Assistants', related_name='dep_assistants',                               symmetrical=False)    class Assistants(models.Model):      id                  = models.BigAutoField(primary_key=True)      department          = models.ForeignKey(Department, related_name='of_department', on_delete=models.CASCADE)      assistant           = models.ForeignKey(settings.AUTH_USER_MODEL, related_name='dt_assistant',                               verbose_name="Department Assistant", on_delete=models.CASCADE)      added               = models.DateTimeField(auto_now_add=True)  

I am pretty new to this concept. Can someone tell me what I did wrong here?

Thanks

Error while writing phone-callLogs in android

Posted: 14 May 2021 08:09 AM PDT

For writing a CallLog, I have used the following code:

public void callLog(View view){      //textView.setText("Call Logging Started ... ");      ContentValues values = new ContentValues();      values.put(CallLog.Calls.NUMBER, 1234567890);      values.put(CallLog.Calls.DATE, System.currentTimeMillis());      values.put(CallLog.Calls.DURATION, 0);      values.put(CallLog.Calls.TYPE, CallLog.Calls.OUTGOING_TYPE);      values.put(CallLog.Calls.NEW, 1);      values.put(CallLog.Calls.CACHED_NAME, "");      values.put(CallLog.Calls.CACHED_NUMBER_TYPE, 0);      values.put(CallLog.Calls.CACHED_NUMBER_LABEL, "");      getContentResolver().insert(CallLog.Calls.CONTENT_URI, values);  }  

The onClick() method is declared as callLog() in the xml-file in the following way:

<Button      android:id="@+id/button"      android:layout_width="wrap_content"      android:layout_height="wrap_content"      android:layout_marginStart="132dp"      android:layout_marginTop="128dp"      android:onClick="callLog"      android:text="Add call log"      app:layout_constraintStart_toStartOf="parent"      app:layout_constraintTop_toTopOf="parent"   />  

I have added <uses-permission android:name="android.permission.WRITE_CALL_LOG"/> in the manifest.

But, still, I get the following error:

java.lang.IllegalStateException: Could not execute method for android:onClick          at androidx.appcompat.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:414)          at android.view.View.performClick(View.java:7448)          at com.google.android.material.button.MaterialButton.performClick(MaterialButton.java:1119)          at android.view.View.performClickInternal(View.java:7425)          .          .          .          at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:592)          at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:947)       Caused by: java.lang.reflect.InvocationTargetException          at java.lang.reflect.Method.invoke(Native Method)          at androidx.appcompat.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:409)          at android.view.View.performClick(View.java:7448)           at com.google.android.material.button.MaterialButton.performClick(MaterialButton.java:1119)           at android.view.View.performClickInternal(View.java:7425)           .          .          .          at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:947)        Caused by: java.lang.SecurityException: Permission Denial: writing com.android.providers.contacts.CallLogProvider uri content://call_log/calls from pid=5389, uid=10178 requires android.permission.WRITE_CALL_LOG, or grantUriPermission()          at android.os.Parcel.createExceptionOrNull(Parcel.java:2373)          at android.os.Parcel.createException(Parcel.java:2357)          at android.os.Parcel.readException(Parcel.java:2340)          .          .          .          at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:947)  

What is going wrong and how should I avoid this?

Keycloak Custom User Federation and Identity Provider Working Order

Posted: 14 May 2021 08:08 AM PDT

I have two custom authentication method on Keycloak.

One of them is custom implemented user federation. I configured it for X realm. System uses this implementation for login with username / password method. This implementation calls my federation service and it validates sent user. It works successfully and authenticates federated users.

Second one is an identity broking (openid connect). I configured a custom openid provider to Y realm. It works successfully and validates provider's users.

I configured both of them to same realm. When i try to use login with custom identity provider, authentication flow works correctly. In the end of flow, configured user federation (custom implemented user federation) triggers with username which comes from identity broking (custom identity provider) login process and it calls my federation service again.

When i try to login with identity providers, i do not want the user federation (custom implemented user federation) to work. It must work only when i try to login with username / password login.

How can i block working of user federation on this scenario?

Please share your experience. Thanks

Allowed values for RequestParam in get url

Posted: 14 May 2021 08:09 AM PDT

Is it possible to set possible values for @RequestParam(value = "id") String id)
?

The ideal is: I give some List<String> allowedValues and it automatically validate it. (This list will be loaded from database).

Is there a simple way to override the list object's method __getitem__?

Posted: 14 May 2021 08:08 AM PDT

I am trying to define a default style list object:

class ilist(list):      def __init__(self,r=list(),dft=None):          list.__init__(self,r)          self.dft=dft      def __getitem__(self,n):          if len(self)<=n:              for i in range(n-len(self)+1):                  self.append(self.dft)          for i,v in enumerate(self):              if i+1==len(self):                  return v    x=ilist()  print x[4]  print x  

It works.

>>>   None  [None, None, None, None, None]    

But I think it's terrible to query my ilist. I've tried the following method:

def __getitem__(self,n):      from operator import getitem      if len(self)<=n:          for i in range(n-len(self)+1):              self.append(self.dft)      return getitem(self,n)  

but the fact shows it totally equals self[n] and causes RuntimeError: maximum recursion depth exceeded

I also tried to borrow the parent class list method .But the form isx.__getitem__(y). I don't know how to adapt it to ilist.

So finally my terrible solution comes out. Raw and brute force..Is there any effecient or simple solution? Thanks in advance.

No comments:

Post a Comment