Monday, June 7, 2021

Posts from Recent Questions - Stack Overflow for 06/07/2021

View this email in your browser
Updates from https://stackoverflow.com/questions

Recent Questions - Stack Overflow



In the 06/07/2021 edition:

SheetJs /XLSX - read sheet by column header

By Mitul Panchal on Jun 07, 2021 04:03 am
Hi All,  

enter image description here

I've excel sheet and want to read all values from column Header name "Asset Type" and may be put it into array with distinct values

I'm using https://www.npmjs.com/package/xlsx package. Any help would be highly appreciated

Thank you :)


Read in browser »
share on Twitter

Traverse Xml document using xslt

By vivek on Jun 07, 2021 04:03 am

I'm trying to convert json to csv

Input json

{      "data": {          "file": [{                  "id": "0001",                  "name": "harsha"              },              {                  "id": "0002",                  "name": "manohar"              }          ]      }  }  

XSLT style sheet

<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"      xmlns:xs="http://www.w3.org/2001/XMLSchema"      xmlns:map="http://www.w3.org/2005/xpath-functions/map"      xmlns:array="http://www.w3.org/2005/xpath-functions/array"      exclude-result-prefixes="#all"      version="3.0">      <xsl:param name="input" as="xs:string"></xsl:param>      <xsl:output method="text"/>        <xsl:variable name='newline'><xsl:text></xsl:text></xsl:variable>        <xsl:template  name="xsl:initial-template">            <xsl:variable name="json-xml" select="json-to-xml($input)"/>          <xsl:value-of select="concat('ID,NAME',$newline)"/>          <xsl:for-each select="$json-xml/data/file">              <xsl:value-of                  select="concat(id,name,$newline)"/>          </xsl:for-each>      </xsl:template>    </xsl:stylesheet>  

Here I'm trying to traverse data inside the file and converting into csv so I'm not able to fetch id and name..

Expected output:-

ID,NAME  0001,harsha  0002,manohar  

Any suggestions would be helpful...


Read in browser »
share on Twitter

python path, can't use Django

By Mr D on Jun 07, 2021 04:03 am

i tried to install django, the installation was succeeded but i couldn't create new project. so i uninstalled and try to install again and this message showed up(didn't see it the first time): WARNING: The script django-admin.exe is installed in 'C:\Users\ASUS\AppData\Roaming\Python\Python39\Scripts' which is not on PATH. Consider adding this directory to PATH or, if you prefer to suppress this warning, use --no-warn-script-location. so i look up online and people said used sys.path.append to fix but when i used it: sys.path.append('C:\Users\ASUS\AppData\Roaming\Python\Python39\Scripts') SyntaxError: (unicode error) 'unicodeescape' codec can't decode bytes in position 2-3: truncated \UXXXXXXXX escape. please help, i'm still new to Python and Django.


Read in browser »
share on Twitter

I want to push my form data inside a list and show it in mat-table in (using angular 12)

By Rakin on Jun 07, 2021 04:02 am

I want to push my form data inside a list and show it in the mat-table. For now, my dataSource for mat-table is in this format.

Array(1) 0: brand: "" color: "" description: "" image: "" item_name: "asd" manufacturer: "" other: "" storage: "" tax: "" type: "Goods" unit: "pc" front-end nothing is rendering only header of the table are displayed


Read in browser »
share on Twitter

R- Count the number of a text In a table [duplicate]

By Marianne M. on Jun 07, 2021 04:02 am

I have a table like this

ID   TEXT  1    HI  2    HI  3    BYE  4    BYE  5    HI  

I need to get a table that look like this

TEXT     COUNT  HI         3  BYE        2  

How can I do so?


Read in browser »
share on Twitter

Return all Azure AD User info using Python

By Artem on Jun 07, 2021 04:02 am

I'm fetching Azure AD data in a Python script. What I'm interested in is specifically name, email and jobtitle from the Users site in Azure.

However, the get request is limited to 100 rows, which I assume has something to do with pagination. Additionally, the jobtitle is empty, which has something to do with the app registration.

QUESTIONS

  • How do I return more than 100 rows? I'm struggling with the documentation, and I can't find any Python examples on this?

  • Why is jobtitle returned empty? I've set the User.Read.All permission in the app registration with no luck, as is shown in the screenshot.

If I'm not allowed to post 2 questions, let me know, and I'll split it into two.

enter image description here

My code is:

import logging  import json  import msal  import requests  import pandas    # Globals  token = None  graphApiVersion = "v1.0"  uri = "https://graph.microsoft.com/{v}/{r}"  headers = None    # Functions  def authenticate():      global token      global headers      authority = "https://login.microsoftonline.com/<tenant id>      appID = "<app id>"      appSecret = "<app secret>"      scope = ["https://graph.microsoft.com/.default"]        app = msal.ConfidentialClientApplication(          appID, authority=authority, client_credential = appSecret)      token = app.acquire_token_silent(scope, account=None)      if not token:          token = app.acquire_token_for_client(scopes=scope)      headers = {'Authorization': 'Bearer ' + token['access_token']}      return print(token)    def users(Format=True):      return query(graphApiVersion, "/users?$select=displayName,givenName,jobTitle,email,department", Format)    def query(v, r, Format=True):      dest = uri.format(v=v, r=r)      result = requests.get(dest, headers=headers).json()      if Format:          print(pandas.json_normalize(result["value"]))      else:          return result["value"]  

Read in browser »
share on Twitter

Java: How convert String with square brackets to Array or List

By margheri on Jun 07, 2021 04:01 am

I have this String "ANAD[LUB[TER[NQ,JI],WA[KK,SUI]]]", and I need to create an Array or ArrayList with these value:

1.ANADLUBTERNQ  2.ANADLUBTERJI  3.ANADLUBWAKK  4.ANADLUBWASUI  

Can anyone please help me, how can I do? Thanks


Read in browser »
share on Twitter

The duration of an emitter in solar2d

By Kent Salazar on Jun 07, 2021 04:01 am

I'm just confused about the solar2d emitter on what will happened to the emitter if the emitter emission ended? Will the emitter be removed after? Or remain on it's location? Pleas I need help. Thank you.


Read in browser »
share on Twitter

React JSX conditional rendering of column layout

By testndtv on Jun 07, 2021 03:54 am

I want to have a dynamic rendering of JSX as below;

<ColumnLayout container spacing={1}>      <ColumnLayout item xs={9}>          <b>{text}</b>      </ColumnLayout>      {showSubTextAndIcon ?          <ColumnLayout item xs={2}>              <span>{subText}</span>          </ColumnLayout>          <ColumnLayout item xs={1}>              <Icon  />          </ColumnLayout>          : null      }  </ColumnLayout>  

Thus, I want that only if "showSubTextAndIcon" is true, then render the subtext and Icon. Now the above does not work and I get a syntax error saying;

Adjacent JSX elements must be wrapped in an enclosing tag. Did you want a JSX fragment <>...</>

This works if I add a wrapping ColumnLayout. However, that messes my layout when showSubTextAndIcon is true. Please suggest.

{showSubTextAndIcon ?          <ColumnLayout container spacing={1}>              <ColumnLayout item xs={2}>                  <span>{subText}</span>              </ColumnLayout>              <ColumnLayout item xs={1}>                  <Icon  />              </ColumnLayout>          </ColumnLayout>          : null      }  

Note: ColumnLayout is derived from material ui library.


Read in browser »
share on Twitter

Async operations when instance created

By Or Assayag on Jun 07, 2021 03:54 am

I had a job interview yesterday, and I was given a coding challenge as the following:

// 3. Coding challenge.  // The goal is to make function1/function2 to work only when the constructor has finished its async operations.  // You CAN'T change the notifyUrls function. Imagine it's a 3th party library you don't have control on.    // CAN'T CHANGE THIS.  //===================  function notifyUrls(item, callback) {      asyncOperation(item).then((res) => {          callback(res);      });  }  //===================     const asyncOperation = () => { return new Promise((resolve, reject) => { setTimeout(() => { console.log('Timeout execute'); resolve(); }, 2000); }); };    const URL1 = 'http://www.somerestapi/get1';  const URL2 = 'http://www.somerestapi/get2';  const URL3 = 'http://www.somerestapi/get3';    class MyClass {        constructor() {          [URL1, URL2, URL3].forEach(item => {              notifyUrls(item, () => { });          });      }        myFunction1() {          // Only start working when constructor finished notifying.          // ...          console.log('myFunction1');      }        myFunction2() {          // Only start working when constructor finished notifying.          // ...          console.log('myFunction2');      }  }  

And here is what I did:

// CAN'T CHANGE THIS.  //===================  function notifyUrls(item, callback) {      asyncOperation(item).then((res) => {          callback(res);      });  }  //===================     const asyncOperation = () => { return new Promise((resolve, reject) => { setTimeout(() => { console.log('Timeout execute'); resolve(); }, 2000); }); };    const URL1 = 'http://www.somerestapi/get1';  const URL2 = 'http://www.somerestapi/get2';  const URL3 = 'http://www.somerestapi/get3';    class MyClass {        constructor() {          this.ready = Promise.all([URL1, URL2, URL3].map((url) => { this.myAsyncCall(url); }));      }        myAsyncCall(item) {          return new Promise((resolve, reject) => {              notifyUrls(item, (res) => { resolve(res); });          });      }        async myFunction1() {          if (await this.ready) {              // Only start working when constructor finished notifying.              // ...              console.log('myFunction1');          }      }        myFunction2() {          // Only start working when constructor finished notifying.          // ...          console.log('myFunction2');      }  }    (async () => {      const myClass = new MyClass();      await myClass.myFunction1();  })();  

But the output is:

myFunction1  Timeout execute  Timeout execute  Timeout execute  

What I want the output to be is:

Timeout execute  Timeout execute  Timeout execute  myFunction1  

How can I work around it? Thanks.


Read in browser »
share on Twitter

Copy .git(metadata) folder of private repo using access token

By Serenity on Jun 07, 2021 03:37 am

I am trying to copy .git folder of private repo of any user when access token is provided using python. However, I could not be able to download it. I found bash script to download the file but I wanted to retrieve only .git folders. This is what I was trying

python script

TOKEN = "tokensoicanaccessprivaterepo"  OWNER=""  REPO=""    API_URL=f"https://api.github.com/repos/{OWNER}/{REPO}?access_token={TOKEN}"  req_json = requests.get(API_URL).json()  # git_url = req_json['ssh_url']    # git clone https://${TOKEN}:x-oauth-basic@github.com/{OWNER}/{REPO}.git    os.system(f"git clone https://${TOKEN}@github.com/{OWNER}/{REPO}.git")  

the way I am doing asks for password event after providing personal access token with repo and user scope while cloning.

I have looked into various resources but I did not find the way to copy '.git' folder of private repo of any user with the github provider token.


Read in browser »
share on Twitter

Run notification script only once, even though script runs on multiple tabs

By Mikkel Fennefoss on Jun 07, 2021 03:32 am

I use the following code inside a Tampermonkey script.

function scriptMain () {      setTimeout(function(){          GM_notification ( {              title: 'Refresh Business Manager', text: 'Your about to be logged out of staging, click here to refresh your login.', image: 'https://i.stack.imgur.com/geLPT.png',              onclick: () => {                  console.log ("My notice was clicked.");                  location.reload();              }          } );      }, 5*1000);      console.log ("Script main code ran.");  }  

The code shows a notification whenever a browser tab is open for more than 5 seconds which includes a button to refresh the current browser tab. I wanna use this script to alert me every 20 minutes or so, that one of the logins in the browser is about to auto-logout.

The functionality works as expected, but if I have 5 tabs open from the site where im logged in, I will get 5 notifications when the page is about to run out. I would love to be able to tell from within the Tampermonkey script if this script is already running on another tab, to not execute or to maybe just be able to only show the notification once.

I have been looking into the Tampermonkey documentation for the following Grants:

GM_getTab(callback)  GM_saveTab(tab)  GM_getTabs(callback)  

But I dont seem to be able to work out if this functionality would be possible or not.

Can someone help me shine some light on this topic, or perhaps share a solution?


Read in browser »
share on Twitter

Heap of out of memory

By Evren on Jun 07, 2021 03:31 am

I am having problem with the memory when I try to start my react app with npm start. The error says

<--- Last few GCs --->    [12380:006AE720]    71751 ms: Mark-sweep (reduce) 1215.6 (1266.1) -> 683.3 (1175.2) MB, 195.0 / 0.1 ms  (average mu = 0.962, current mu = 0.970) last resort GC in old space requested  [12380:006AE720]    72125 ms: Mark-sweep (reduce) 683.3 (1163.2) -> 682.6 (1010.2) MB, 374.0 / 0.1 ms  (average mu = 0.897, current mu = 0.000) last resort GC in old space requested      <--- JS stacktrace --->    FATAL ERROR: CALL_AND_RETRY_LAST Allocation failed - JavaScript heap out of memory  [nodemon] app crashed - waiting for file changes before starting...  

In package.json file inside the scripts I have "start": "nodemon --max-old-space-size=48000 -w app.js -w webpack.config.js app.js" but unfortunately it does not solve the problem. I also tried everything in this post Node.js heap out of memory but still having same problem.

This is the node-clinic report

enter image description here

These are the warnings&errors from node-clinic

buffer.js:429      return createFromString(string, ops.encodingVal);             ^        Error: Failed to allocate memory          at createFromString (<anonymous>)          at fromStringFast (buffer.js:429:12)          at fromString (buffer.js:458:10)          at Function.from (buffer.js:308:12)          at new Buffer (buffer.js:289:17)          at writeOut (C:\Users\User\documents\costaa\costa\fe\explorebook\node_modules\webpack\lib\Compiler.js:334:17)          at Immediate.<anonymous> (C:\Users\User\documents\costaa\costa\fe\explorebook\node_modules\memory-fs\lib\MemoryFileSystem.js:288:4)          at processImmediate (internal/timers.js:462:21) {        code: 'ERR_MEMORY_ALLOCATION_FAILED'      }  

Any help would be appreciated, thanks in advance.


Read in browser »
share on Twitter

Remove keys from a dictionary which has "nan" values

By vikas Sharma on Jun 07, 2021 03:20 am

I have source dictionary, please refer sample below. It has deep level nested sub-dictionaries and lists, and I need to remove all keys where the value is "nan".

data = {"col1":"val1","col2":"val2","col3":"val3","col4":"val3","list1":[{"l1":"v1","l2":"nan"},{"K1":"Kv1","K2":"nan"},{"M1":"Mv1","M2":"nan","sublist1":[{"SL1":"SV1","SL2":"nan"}]}],"list2":[{"l1":"v1","l2":"nan"},{"K1":"Kv1","K2":"nan"},{"M1":"Mv1","M2":"nan","sublist2":[{"SL1":"SV1","SL2":"nan"}]}]}  

I tried following code by creating a function but it is not working as expected:

def cleanNullTerms(d):     clean = {}     for k, v in d.items():        if isinstance(v, list):           for values in v:              nested = cleanNullTerms(values)              if values =='nan':                  clean[k] = nested        elif v is not 'nan':           clean[k] = v     return clean  

Read in browser »
share on Twitter

How to connect with MySQL using a unix socket?

By Amir Saleem on Jun 07, 2021 03:16 am

I want to connect to MySQL using a Unix socket connection. I am not sure how to pass the variables in the connection string. I have read somewhere that I can also use Config.FormatDSN struct to define the values, but I am not sure how.

// Creates a database connection and returns its instance  func Connection() (*sql.DB, error) {      conn, err := sql.Open("mysql", "username/password@unix(socketpath)/dbname")      return conn, err  }    

Read in browser »
share on Twitter

Why random words from array doesn't show when I click the button?

By Sophia Woon on Jun 07, 2021 03:00 am

I wanted to create a simple app that shows words/sentences randomly from a list that I've created every time the user click on the button.

Android Studio doesn't show any error but nothing happens when I click on the button.

Appreciate your help. Thank you

Here's my code. MainActivity.java

  package com.example.arraytesting4;    import androidx.appcompat.app.AppCompatActivity;    import android.os.Bundle;  import android.view.View;  import android.widget.TextView;  import java.lang.String;  import java.lang.StringBuilder;  import java.util.ArrayList;    public class MainActivity extends AppCompatActivity {      ArrayList<String> SList;      TextView Sentence;        @Override      protected void onCreate(Bundle savedInstanceState) {          super.onCreate(savedInstanceState);          setContentView(R.layout.activity_main);            Sentence = (TextView) findViewById(R.id.Sentence);        }      public void buttonClicked(View v){      printJoke();  }    public void printJoke() {      StringBuilder SentenceStringBuilder = new StringBuilder();      for (String s : SList) {          SentenceStringBuilder.append(s + "\n");      }      Sentence.setText(SentenceStringBuilder.toString());  }  }  

In SList.java

  package com.example.arraytesting4;  import java.util.*;    import java.util.ArrayList;    public class SList extends MainActivity {      public void Sentence(){            ArrayList<String> SList = new ArrayList<String>();            SList.add("Apple");          SList.add("Banana");          SList.add("Ciku");          SList.add("Danny ate the others.");          }  }  

Read in browser »
share on Twitter

Why am I getting discord.py AttributeError: 'str' object has no attribute 'trigger_typing'

By daedsky on Jun 07, 2021 02:11 am

I can't figure out why the hell I am getting this error. Everything in the code looks good to me. Maybe it is due to the converters not working but my other commands are working properly.

   async def ship(self, ctx: commands.Context, user1: discord.Member = None, user2: discord.Member = None):          if user1 is None or user2 is None:              await ctx.send(embed=discord.Embed(                  description=f"please mention two persons or provide two image urls! try: `{self.GetPrefix(ctx)}ship @person1 @person2` or `{self.GetPrefix(ctx)}ship [img url1] [img url2]`",                  color=self.randomcolor()))          else:              await ctx.trigger_typing()                r1 = requests.get(user1.avatar_url)              with open("images/ship_avatar1.png", "wb") as f1:                  f1.write(r1.content)                r2 = requests.get(user2.avatar_url)              with open("images/ship_avatar2.png", "wb") as f2:                  f2.write(r2.content)                await self.ship("images/ship_avatar1.png", "images/ship_avatar2.png", "images/ship.png")                embed = discord.Embed()              embed.set_image(url="attachment://ship.png")                file = discord.File("images/ship.png", "ship.png")                await ctx.send(embed=embed, file=file)    The error I am getting is:    Ignoring exception in on_command_error  Traceback (most recent call last):    File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/ext/commands/core.py", line 85, in wrapped      ret = await coro(*args, **kwargs)    File "/home/runner/Mob/cogs/fun.py", line 397, in ship      await self.ship("images/ship_avatar1.png", "images/ship_avatar2.png", "images/ship.png")    File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/ext/commands/core.py", line 372, in __call__      return await self.callback(self.cog, *args, **kwargs)    File "/home/runner/Mob/cogs/fun.py", line 387, in ship      await ctx.trigger_typing()  AttributeError: 'str' object has no attribute 'trigger_typing'    

Read in browser »
share on Twitter

How to get a specific length of string in my array?

By shadow_blade on Jun 07, 2021 01:29 am

I am generating an integer from 5-10.

once I generate an integer ranging from 5-10, the loop should choose a string on my array that has a character length based on the random integer that is generated.

example:

random integer generated: 10

the system should display a string that has a length of 10 character so either it will display the testNames1 or testNames2 because it has 10 character length

I tried doing this on my code, but it doesn't work.

<?php    function getName(){        $names = array(          'Juans',          'Luisss',          'Pedroaa',          'testNames1',          'testNames2',          'testName3',          'test', //This should not be return because im only generating a number random of 5-10 and this character has only 4 character length          'tse', //This should not be return because im only generating a number random of 5-10 and this character has only 3 character length          // and so on      );        $randomString = "";        for ($i = 0; $i <count($names); $i++) {          $value = rand(5,10);          $length_string = strlen($names[$i]);            if ($value == $length_string) {              return "name:".$names[$i].$value;          }        }      }    echo getName();  ?>  

Can anyone help me on how to do this?


Read in browser »
share on Twitter

How to monitor accuracy in tensorflow

By syed2096 on Jun 07, 2021 12:19 am

I would like to monitor accuracy for my tensorflow model, however, when compiling my model using metrics=['accuracy'] or metrics=[tf.keras.metrics.Accuracy()] and then train my model the following Warning pops up.

WARNING:tensorflow: Early stopping conditioned on metric accuracy which is not available. Available metrics are: loss, val_loss

model.compile(optimizer='adam', loss='mean_squared_error', metrics=["tried both options i mentioned"])  callbacks = [EarlyStopping(monitor='accuracy', patience=1000)]  model.fit(x_train, y_train, epochs=5000, batch_size=100, validation_split=0.2, callbacks=callbacks)  

Read in browser »
share on Twitter

Unity3D editor: Rendering nested elements in sidebar

By Max on Jun 07, 2021 12:09 am

In Unity, one of my MonoBehaviours has a field pointing to another object (a ScriptableObject). If I double-click that field, I can see the fields of that object. How do I render those fields into the top-level MonoBehaviour's property drawer?

In picture form

What I have

enter image description here

(double-click the element)

enter image description here

What I want

enter image description here

I have my own [CustomEditor] component, but I can't quite get it to work right; stuff like this:

SerializedProperty activityStack = serializedObject.FindProperty("activityStack");  EditorGUILayout.PropertyField(activityStack.GetArrayElementAtIndex(0));  

just renders the "Element 0 (Idle Activity)" bit and not the actual contents of the reference.


Read in browser »
share on Twitter

Conditional WHERE clauses with TVP parameter

By Martunis99 on Jun 06, 2021 06:47 pm

I am building and recipe website and I am trying to create a stored procedure with a table-valued parameter but am running into some issues.

So the TVP is filled based on the checkboxlists that the user selects when he is trying to search for a recipe. I then would like to show recipes based on those selections, and for that reason I used a TVP in my stored procedure.

However I would like for the query to display all records (for each section) when the user does not select any options in one of the checkboxlists. When I try to do this the query immediately returns no results.

TVP Setup and Logic

Category Difficulty Duration
Meat Easy 0-15 min
Empty Average 30-45 min
Fish Hard Empty

I want the procedure to filter each recipe by all the options selected in Category, Difficulty and Duration. I.e. in this case, I want the stored procedure to return all recipes that have Category = "Meat" or "Fish"; that have Difficulty = "Easy" or "Average" or "Hard" and have Duration = "0-15min" or "30-45min".

In case nothing is selected for Category, for instance, the stored procedure should return recipes from all categories, and only filter based on the columns that have values.

Working code so far

ALTER PROCEDURE uspPesquisarReceita (@TVP dbo.Filters READONLY)  AS  BEGIN      SELECT R.RecipeName, C.Category, DF.Dificulty, D.Duration, R.Rating, R.Publication, R.Photo, R.Views, R.IDRecipe          FROM dbo.Recipes R          LEFT JOIN dbo.Categories C ON R.IDCategory = C.IDCategory          LEFT JOIN dbo.Dificulty DF ON R.IDDificulty = DF.IDDificulty          LEFT JOIN dbo.Duration D ON R.IDDuration = D.IDDuration          WHERE R.IDStatus = 1          AND (C.Category IN (SELECT Category FROM @TVP)          AND DF.Dificulty IN (SELECT Dificulty FROM @TVP)          AND D.Duration IN (SELECT Duration FROM @TVP))  END  

This code is working, only when I select options in all three of the checkboxlists (called Category, Dificulty and Duration).

Code I have tried #1

ALTER PROCEDURE uspPesquisarReceita (@TVP dbo.Filters READONLY)      AS      BEGIN          SELECT R.RecipeName, C.Category, DF.Dificulty, D.Duration, R.Rating, R.Publication, R.Photo, R.Views, R.IDRecipe              FROM dbo.Recipes R              LEFT JOIN dbo.Categories C ON R.IDCategory = C.IDCategory              LEFT JOIN dbo.Dificulty DF ON R.IDDificulty = DF.IDDificulty              LEFT JOIN dbo.Duration D ON R.IDDuration = D.IDDuration              WHERE R.IDStatus = 1              AND (C.Category IN (CASE WHEN NOT EXISTS (SELECT Category FROM @TVP)                                   THEN                                    (SELECT R.RecipeName, C.Category, DF.Dificulty, D.Duration,                                    R.Rating, R.Publication, R.Photo, R.Views, R.IDRecipe                                    FROM dbo.Recipes R                                    LEFT JOIN dbo.Categories C ON R.IDCategory = C.IDCategory                                    LEFT JOIN dbo.Dificulty DF ON R.IDDificulty = DF.IDDificulty                                    LEFT JOIN dbo.Duration D ON R.IDDuration = D.IDDuration                                    WHERE R.IDStatus = 1)                                   ELSE (SELECT Category FROM @TVP)              AND DF.Dificulty IN (SELECT Dificulty FROM @TVP)                                    *same as above*              AND D.Duration IN (SELECT Duration FROM @TVP))                                    *same as above*      END  

Code I have tried #2 (only with example for Category)

ALTER PROCEDURE uspPesquisarReceita (@TVP dbo.Filters READONLY)          AS          BEGIN              IF NOT EXISTS (SELECT Category FROM @TVP)                  SELECT R.RecipeName, C.Category, DF.Dificulty, D.Duration, R.Rating,                  R.Publication, R.Photo, R.Views, R.IDRecipe                  FROM dbo.Recipes R                  LEFT JOIN dbo.Categories C ON R.IDCategory = C.IDCategory                  LEFT JOIN dbo.Dificulty DF ON R.IDDificulty = DF.IDDificulty                  LEFT JOIN dbo.Duration D ON R.IDDuration = D.IDDuration                  WHERE R.IDStatus = 1                  AND DF.Dificulty IN (SELECT Dificulty FROM @TVP)                  AND D.Duration IN (SELECT Duration FROM @TVP))              ELSE                  SELECT R.RecipeName, C.Category, DF.Dificulty, D.Duration, R.Rating,                  R.Publication, R.Photo, R.Views, R.IDRecipe                  FROM dbo.Recipes R                  LEFT JOIN dbo.Categories C ON R.IDCategory = C.IDCategory                  LEFT JOIN dbo.Dificulty DF ON R.IDDificulty = DF.IDDificulty                  LEFT JOIN dbo.Duration D ON R.IDDuration = D.IDDuration                  WHERE R.IDStatus = 1                  AND (C.Category IN (SELECT Category FROM @TVP)                  AND DF.Dificulty IN (SELECT Dificulty FROM @TVP)                  AND D.Duration IN (SELECT Duration FROM @TVP))      END  

None of these two attempts have yielded any results. Can you help me out? What am I missing?

Thank you!


Read in browser »
share on Twitter

No serializer found for class org.springframework.security...WebSecurityConfigurerAdapter$AuthenticationManagerDelegator

By Jayanta Baishya on Jun 06, 2021 10:52 am

I was trying to configure spring security implementing JWT. On exposing the authenticationManagerBean in the configuration file, I got the error.

org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'welcomeController': Unsatisfied dependency expressed through field 'authenticationManager'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'authenticationManagerBean' defined in class path resource [com/janus/garden/security/SecurityConfiguration.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.security.authentication.AuthenticationManager]: Factory method 'authenticationManagerBean' threw exception; nested exception is com.fasterxml.jackson.databind.exc.InvalidDefinitionException: No serializer found for class org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter$AuthenticationManagerDelegator and no properties discovered to create BeanSerializer (to avoid exception, disable SerializationFeature.FAIL_ON_EMPTY_BEANS)      at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:643)    Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'authenticationManagerBean' defined in class path resource [com/janus/garden/security/SecurityConfiguration.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.security.authentication.AuthenticationManager]: Factory method 'authenticationManagerBean' threw exception; nested exception is com.fasterxml.jackson.databind.exc.InvalidDefinitionException: No serializer found for class org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter$AuthenticationManagerDelegator and no properties discovered to create BeanSerializer (to avoid exception, disable SerializationFeature.FAIL_ON_EMPTY_BEANS)      at org.springframework.beans.factory.support.ConstructorResolver.instantiate(ConstructorResolver.java:656)      Caused by: org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.security.authentication.AuthenticationManager]: Factory method 'authenticationManagerBean' threw exception; nested exception is com.fasterxml.jackson.databind.exc.InvalidDefinitionException: No serializer found for class org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter$AuthenticationManagerDelegator and no properties discovered to create BeanSerializer (to avoid exception, disable SerializationFeature.FAIL_ON_EMPTY_BEANS)      at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:185)      at org.springframework.beans.factory.support.ConstructorResolver.instantiate(ConstructorResolver.java:651)      ... 37 common frames omitted  Caused by: com.fasterxml.jackson.databind.exc.InvalidDefinitionException: No serializer found for class org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter$AuthenticationManagerDelegator and no properties discovered to create BeanSerializer (to avoid exception, disable SerializationFeature.FAIL_ON_EMPTY_BEANS)      at com.fasterxml.jackson.databind.exc.InvalidDefinitionException.from(InvalidDefinitionException.java:77)  

POM file

<?xml version="1.0" encoding="UTF-8"?>  <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"           xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">      <modelVersion>4.0.0</modelVersion>      <parent>          <groupId>org.springframework.boot</groupId>          <artifactId>spring-boot-starter-parent</artifactId>          <version>2.2.2.RELEASE</version>  <!--        <version>2.5.0</version>-->          <relativePath/> <!-- lookup parent from repository -->      </parent>      <groupId>com.janus</groupId>      <artifactId>garden</artifactId>      <version>0.0.1-SNAPSHOT</version>      <name>garden</name>      <description>TeaGarden Service</description>      <properties>          <java.version>1.8</java.version>      </properties>      <dependencies>          <dependency>              <groupId>org.springframework.boot</groupId>              <artifactId>spring-boot-starter-actuator</artifactId>          </dependency>          <dependency>              <groupId>org.springframework.boot</groupId>              <artifactId>spring-boot-starter-data-jpa</artifactId>          </dependency>          <dependency>              <groupId>org.springframework.boot</groupId>              <artifactId>spring-boot-starter-validation</artifactId>          </dependency>          <dependency>              <groupId>org.springframework.boot</groupId>              <artifactId>spring-boot-starter-jdbc</artifactId>          </dependency>          <dependency>              <groupId>org.springframework.boot</groupId>              <artifactId>spring-boot-starter-security</artifactId>          </dependency>          <dependency>              <groupId>org.springframework.boot</groupId>              <artifactId>spring-boot-starter-web</artifactId>          </dependency>          <dependency>              <groupId>org.springframework.boot</groupId>              <artifactId>spring-boot-starter-thymeleaf</artifactId>          </dependency>          <dependency>              <groupId>org.springframework.boot</groupId>              <artifactId>spring-boot-starter-aop</artifactId>          </dependency>            <dependency>              <groupId>io.jsonwebtoken</groupId>              <artifactId>jjwt</artifactId>              <version>0.9.1</version>          </dependency>          <dependency>              <groupId>org.springframework.boot</groupId>              <artifactId>spring-boot-devtools</artifactId>              <scope>runtime</scope>              <optional>true</optional>          </dependency>          <dependency>              <groupId>mysql</groupId>              <artifactId>mysql-connector-java</artifactId>              <version>5.1.6</version>              <scope>runtime</scope>          </dependency>          <dependency>              <groupId>org.projectlombok</groupId>              <artifactId>lombok</artifactId>              <optional>true</optional>          </dependency>          <dependency>              <groupId>org.springframework.boot</groupId>              <artifactId>spring-boot-starter-test</artifactId>              <scope>test</scope>          </dependency>          <!--        <dependency>-->          <!--            <groupId>org.mockito</groupId>-->          <!--            <artifactId>mockito-core</artifactId>-->          <!--            <scope>test</scope>-->          <!--        </dependency>-->          <dependency>              <groupId>javax.xml.bind</groupId>              <artifactId>jaxb-api</artifactId>              <version>2.3.0</version>          </dependency>          <dependency>              <groupId>org.springframework.security</groupId>              <artifactId>spring-security-test</artifactId>              <scope>test</scope>          </dependency>          <dependency>              <groupId>junit</groupId>              <artifactId>junit</artifactId>              <scope>test</scope>          </dependency>      </dependencies>        <build>          <plugins>              <plugin>                  <groupId>org.springframework.boot</groupId>                  <artifactId>spring-boot-maven-plugin</artifactId>                  <configuration>                      <excludes>                          <exclude>                              <groupId>org.projectlombok</groupId>                              <artifactId>lombok</artifactId>                          </exclude>                      </excludes>                  </configuration>              </plugin>          </plugins>      </build>    </project>  

Read in browser »
share on Twitter




Recent Articles:

How to resize Bcache PV?
For every line in a file, determine if string is present within another file
why isn't the re.group function giving me the expected output
Implement log4net in a windows service using dependency injection
Node.js vs .Net Core
Twitter
Facebook
Website
Copyright © 2021 reader, All rights reserved.
You are receiving this email because you opted in via our website.

Our mailing address is:
reader
88 CELICA STREET
Davao 8000
Philippines

Add us to your address book


Want to change how you receive these emails?
You can update your preferences or unsubscribe from this list.

Email Marketing Powered by Mailchimp

No comments:

Post a Comment