Wednesday, March 24, 2021

Recent Questions - Stack Overflow

Recent Questions - Stack Overflow


remove key value pair from an array in mule 4

Posted: 24 Mar 2021 08:06 AM PDT

I'm facing issue to apply logic to remove one key from the array. Below i have added my payload that i am getting after processing now from here i want to remove the object key. Kindly suggest me the logic to remove the contact key dynamically.

 [{      "TB1": [{              "object": "TB1",              "Name": 200          },          {              "object": "TB1",              "Name": 220          }      ]    },    {      "TB2": [{          "object": "TB2",          "Field1": 100      }]    },    {      "TB3": [{          "object": "TB3",          "Field2": 1300      }]    }]  

expected:

 [{      "TB1": [{              "Name": 200          },          {              "Name": 220          }      ]  },  {      "TB2": [{          "Field1": 100      }]  },  {      "TB3": [{          "Field2": 1300      }]  }]  

Kubernetes no compatible version found (dotnet)

Posted: 24 Mar 2021 08:06 AM PDT

It was not possible to find any compatible framework version

My Error in Logs Explorer when I deploy my App in Google Cloud>Workloads
The framework 'Microsoft.NETCore.App', version '3.1.0' was not found.

The following frameworks were found: 5.0.4 at [/usr/share/dotnet/shared/Microsoft.NETCore.App]

You can resolve the problem by installing the specified framework and/or SDK.

The specified framework can be found at:

https://aka.ms/dotnet-core-applaunch?framework=Microsoft.NETCore.App&framework_version=3.1.0&arch=x64&rid=debian.10-x64

My Dockerfile:

FROM mcr.microsoft.com/dotnet/sdk    COPY . /app    WORKDIR /app    RUN dotnet publish -c Release -o out    COPY /out .    ENTRYPOINT ["dotnet", "Test.dll"]  

Packed chain with gravity top

Posted: 24 Mar 2021 08:06 AM PDT

I have two view that are fit at the top and bottom of the screen and I have a Recycler view that will sit between them but there is one view that much be packed with recyclview vertically. Something like this

enter image description here

I have to use constraint layout to achieve this. I have tried to achieve this with using packed-chain but that puts the view in center of screen not align to the the top view.

.set Tkinter not working when called from a class

Posted: 24 Mar 2021 08:05 AM PDT

I am trying to set the text of a label to a question in a tkinter GUI. This works when I call the method separately but doesn't display anything when called from another class.

When called from main the default text "Question and Correct/False" is not set.

  def quiz():      root = Tk()      window = Quiz(root, "Main", '300x250', "---", None)    class Quiz(Window):        score = 0        def __init__(self, root, title, geometry, message, questions):          super().__init__(root, title, geometry, message)            self.question_number = -1            if questions == None:              self.questions = {}              self.create_questions(10)          else:              self.questions = questions                        self.response_text = StringVar()          self.response_label = Label(self.root, textvariable=self.response_text).pack()          self.response_text.set("Correct/False")                      self.question_text = StringVar()          self.question_label = Label(self.root, textvariable=self.question_text).pack()          self.question_text.set("Question")            self.answer_entry = Entry(self.root)          self.answer_entry.pack()            self.button = Button(self.root, text="Enter", command=self.next_question).pack()            self.root.mainloop()          def next_question(self):            current_question = list(self.questions.keys())[self.question_number]          current_answer = list(self.questions.values())[self.question_number-1]            self.question_number += 1            self.question_text.set(current_question)            if self.verify_answer(current_answer, self.answer_entry.get()):              self.response_text.set("Correct")          else:              self.response_text.set("Incorrect")            self.root.mainloop()  

Problem with creating array of binary trees in C

Posted: 24 Mar 2021 08:05 AM PDT

So as the title says i'm having problems with creating an array of binary trees. My goal is to create unknown amount of structs and fill them up with values. I managed to create and fill up one tree but now i'm stuck with creating an array. Here is my current code:

#include <stdlib.h>  #include <stdio.h>    struct tree{      int data;      struct tree* left;      struct tree* right;  };        typedef struct tree node;    void insert(node ** tree, int value){      node *vkladac = NULL;      if(!(*tree))      {          vkladac = (node *)malloc(sizeof(node));          vkladac->left = vkladac->right = NULL;          vkladac->data = value;          *tree = vkladac;          return;      }        if(value < (*tree)->data)      {          insert(&(*tree)->left, value);      }      else if(value > (*tree)->data)      {          insert(&(*tree)->right, value);      }    }    int main(){      size_t pocet_tree = 0;      int pocet_cisiel = 0;      int a = 0;      int b = 0;        scanf("%zu %d", &pocet_tree, &pocet_cisiel);        if(pocet_tree < 1 || pocet_tree > 50 || pocet_cisiel < 1 || pocet_cisiel > 20){          printf("Error: Boli zadane zle hodnoty!\n");          exit(EXIT_FAILURE);      }        struct tree trees[pocet_tree];        int pole[pocet_tree][pocet_cisiel];        for(a = 0; a < pocet_tree; a++){          for(b = 0; b < pocet_cisiel; b++){              scanf("%d", &pole[a][b]);          }      }        a = 0;      b = 0;        node *root;      root = NULL;          for(a = 0; a < pocet_tree; a++){          insert(&root, pole[a][b]);      }        return 0;  }  

Any help would be appreciated.

Concatenate ui.labels in Earth Engine

Posted: 24 Mar 2021 08:05 AM PDT

Is there an easy way to concatenate ui.Labels in Earth Engine? I have two ui.Labels, one of which is a link..

var link = ui.Label('Hawbaker et al. 2020', {},'https://www.sciencedirect.com/science/article/pii/S0034425720301711');  var label = ui.Label('Description of the application goes here (hyperlink text goes here)')  

See the whole code here.. https://code.earthengine.google.com/9e57e03bba46ffacf91e9099f374a31d

I would like to place the link into the other label. I imagine this shouldn't be too hard, but I cannot find an immediate solution.

Thanks

i am currently learning node.js and been given an activity related to web scrapping .here is my issue

Posted: 24 Mar 2021 08:05 AM PDT

i am using request npm package and request take two parameters request(url,callback);

here i somehow want to pass extra argument to my callback function how do i do it. this is the code i am trying to write

 function extractIssues(url,filepath){            request(url,issueCb);  }    function issueCb(err,response,html)  {    if(err){        console.log(err+"at line 61");    }    else{       extractIssueData(html);    }         }  function extractIssueData(html){    let selTool = cheerio.load(html);    let arr = [];    let issueLinksArr = selTool(".flex-auto.min-width-0.p-2.pr-3.pr-md-2 > a");        let result="";    for(let i = 0;i<issueLinksArr.length;i++){       let issueLink = selTool(issueLinksArr[i]).attr("href");       let content = selTool(issueLinksArr[i]).text().trim().split("/n")[0];             let obj = {          link :issueLink,          content:content       }             let str = JSON.stringify(obj);      result = result + str + " ,"+ "\n" ;       }             console.log(result);       }  

i want to use filepath in extractIssueData so i need to first catch it in issueCb how do i do it i cant find proper answer . thanks.

producing unexpected token error ',' which is actually not there

Posted: 24 Mar 2021 08:05 AM PDT

My beginner experience with React is getting horrible, it's throwing an error that shouldn't be there... [here is how error goes][1] [1]: https://i.stack.imgur.com/tbrsm.png

class Count extends React.Component {    constructor(props) {      super(props);      this.state = {        num1: 1,        num2: 1,        score: 0,        response: ""      };    }    render() {      return (        <div>           <h1>{this.state.num1} + {this.state.num2}</h1>           <input onChange={this.updateResponse} value={this.state.response} />          </div>      );    }  updateResponse= (event) => {  this.setState({  response: event.target.value  )};  }  }  ReactDOM.render(<Count />, document.getElementById('root')) ```  

In Firebase, how to send bulk emails by own domain names?

Posted: 24 Mar 2021 08:05 AM PDT

I am looking for some features to send bulk emails in Firebase Cloud. The sender email is from the own domain name, with DKIM verified and SPF configured.

Like the one in Amazon SES, or are there any services like that in Firebase or GCP?

Thanks!

Catch Exception with Hikaripool connection time out for Play Framework Scala 2.8x

Posted: 24 Mar 2021 08:05 AM PDT

I am super new to Scala development with Play Framework. I am building a project using Scala and Play Framework 2.8x where I am trying to connect to MYSQL database.

I have now spent days trying to find out the problem and online answers could not help me.

However, I tried to follow this thread: Steps needed to use MySQL database with Play framework 2.0

This is my built.sbt database set up

play.db {    config = "db"    default = "MyDB"   }     #Database config  db {    MyDB.driver="com.mysql.jdbc.Driver"    MyDB.url="jdbc:mysql://127.0.0.1:3306/MyDB?characterEncoding=UTF-8&autoReconnect=true&useSSL=false"    MyDB.username="root"    MyDB.password="password"      MyDB.hikaricp {      connectionTimeout = 60 seconds      validationTimeout = 5 seconds      maxLifetime = 60 minutes    }  }    # db connections = ((physical_core_count * 2) + effective_spindle_count)  fixedConnectionPool = 9  database.dispatcher {    executor = "thread-pool-executor"    throughput = 1    thread-pool-executor {      fixed-pool-size = ${fixedConnectionPool}    }  }  

This is my model code:

class MyDatabase @Inject() (@NamedDatabase("MyDB") db: Database, databaseExecutionContext: DatabaseExecutionContext) {      def read(query: String) = {      Future {        // get jdbc connection        try {          val connection = db.getConnection()          val statement = connection.createStatement(ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY)          val data = statement.executeQuery("SELECT * FROM User")            while (data.next()) {            System.out.print("Data: " + data.getString("username"))            // System.out.print("")          }            // remember to close the connection          connection.close()            data        }        catch {          case exception: Exception => System.out.print("Error: " + exception.getMessage())        }      }(databaseExecutionContext)    }  

The issue is that I am getting an exception from the catch method with Hikaripool connection time out request

--- (RELOAD) ---    2021-03-24 18:45:07 INFO  play.api.db.HikariCPConnectionPool  Shutting down connection pool.  2021-03-24 18:45:09 INFO  play.api.db.DefaultDBApi  Database [MyDB] initialized  2021-03-24 18:45:09 INFO  play.api.db.HikariCPConnectionPool  Creating Pool for datasource 'MyDB'  2021-03-24 18:45:09 INFO  play.api.http.EnabledFilters  Enabled Filters (see <https://www.playframework.com/documentation/latest/Filters>):        play.filters.csrf.CSRFFilter      play.filters.headers.SecurityHeadersFilter      play.filters.hosts.AllowedHostsFilter    2021-03-24 18:45:09 INFO  play.api.Play  Application started (Dev) (no global state)  Error: HikariPool-15 - Connection is not available, request timed out after 60001ms.  

Your help will be much appreciated!

Genrating Uncaught Error: Cannot find module 'mysql' No debugger available, can not send 'variables'

Posted: 24 Mar 2021 08:05 AM PDT

I am trying to debug this code in the runtime window for Visual Studio Code. I need advice on syntax problems or configuration problems. Here is my code.

var mysql = require('mysql');    var con = mysql.createConnection({  host: "localhost",  user: "root",  password: "ZSuperDupeR1001#",  database: "xovorvia"  });        con.connect(function(err) {      if (err) throw err;      console.log("Connected!");      //Insert a record in the "customers" table:      var sql = "INSERT INTO customers (name, address) VALUES ('Company Inc', 'Highway 37')";      con.query(sql, function (err, result) {      if (err) throw err;      console.log("1 record inserted");    });  });  

Error in my debug window

Uncaught Error: Cannot find module 'mysql' Require stack:

  • c:\Users\username\Desktop\Coding\javaScript\demo_db_insert.js No debugger available, can not send 'variables'

How can I sort a dict by the third element of a list (float) - python [duplicate]

Posted: 24 Mar 2021 08:05 AM PDT

I have a dictionary like this:

mydict = {'name_A':[float1, float2, float3],   #float3 = 10.3            'name_B':[float1, float2, float3],   #float3 = 1.5            'name_C':[float1, float2, float3]}   #float3 = 22.8  

I want to sort the dict by float3. So the output will be like:

mydict = {'name_C':[float1, float2, float3],   #float3 = 22.8            'name_A':[float1, float2, float3],   #float3 = 10.3            'name_B':[float1, float2, float3]}   #float3 = 1.5  

How can I do it? Thanks! :)

Name "Variable" is not defined, However it is in def statement [closed]

Posted: 24 Mar 2021 08:05 AM PDT

I am making a game using pygame and I am currently making movements for the enemy character (Player controlled), I am in the middle of making him move3 and change coordinates. However it gives me the error of:

if check_keydown_events(events, enemy) [0]: NameError: name 'events' is not defined

and the names are defined in the check_keydown_events and the check_keyup_events

Here is my code where the problem occurs:

keys = [False, False, False, False]  keys = [False, True, False, False]    enemy_y = 200  enemy_x = 200  
#making the movements for the enemy  def check_keydown_events(events, enemy):      """responds to keypress"""      if event.key == pygame.K_RIGHT:          enemy.moving_right [3] = True      elif event.key == pygame.K_LEFT:          enemy.moving_left[1] = True      elif event.key == pygame.K_DOWN:          enemy.moving_down[2] = True      elif event.key == pygame.K_UP:          enemy.moving_up[0] = True    def check_keyup_evets(event, enemy):      """responds to key releases"""      if event.key == pygame.K_RIGHT:          enemy.moving_right[3] = False      elif event.key == pygame.K_LEFT:          enemy.moving_left[1] = False      elif event.key == pygame.K_DOWN:          enemy.moving_down[2] = False      elif event.key == pygame.K_UP:          enemy.moving_up[0] = False  
#Updating the y-position  #for up and down  if check_keydown_events(events, enemy) [0]:      if enemy_y> 0:          enemy_y -  15  

How to convert a string representation of a type to the type itself in C++?

Posted: 24 Mar 2021 08:06 AM PDT

I'm a newer to c++, and there is a need to convert a string representation of a type to the type itself, like this: "int" to int, "float" to float, ... but it seems to be very hard to achive it.

For example in seudo code:

//how to implement this function or something like this...  auto gettype(string typestr);    //usage  string types[4] = {"int", "double", "float", "string", ...};  gettype(type[0]) val; //then the type of val is int    

react select load async options does not load

Posted: 24 Mar 2021 08:05 AM PDT

I want to load options from backend. So i have to fetch data from API and then update options. But i don't know how to do it. Can someone help? Here's my code:

function myComponent() {      const loadOptions = () => {      console.log('on load options function')      axios.get(`/api/admin/roles`)        .then((response) => {          const options = []          response.data.permissions.forEach((permission) => {            options.push({              label: permission.name,              value: permission.id            })          })          return options        })    }      return (       <AsyncSelect         isMulti         cacheOptions         loadOptions={loadOptions}      />    )  }  

By the way nothing gets logged at all and that means the loadOptions function does not run. Here's my response from API:

response: {    data: {      permissions: [{        id: 13,        name: 'deposit'      }, {        id: 14,        name: 'withdraw'      }]    }  }  

How to pass multiple environment variables to a docker container?

Posted: 24 Mar 2021 08:05 AM PDT

I'm working with docker for the first time and I'm trying to figure it all out.

In this project I'm working with we make extensive use of Windows environment variables for use in our startup file. And to put these in our Configuration we use the AddEnvironmentVariables(string prefix) method like so:

  public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>          WebHost.CreateDefaultBuilder(args)              .ConfigureAppConfiguration(builder =>              {                  builder.AddEnvironmentVariables(prefix: "MICROSVC_")                  .AddJsonFile("appsettings.json");                               })                  .UseStartup<Startup>();  

In localhost and Azure this is no problem since we've added them to those environments. But I can not for the love of god figure out how to configure these environment variables in my docker container. I've seen that you could do it with -e in the run command but that would be just too much variables to pass through like that.

Speeding up pandas calculations

Posted: 24 Mar 2021 08:05 AM PDT

I have a long Dataframe, df, and a shorter Dataframe, df2. I have to make a calculation which is referring to each of the lines in the long Dataframe. Then I have to cut it and merge it with part of the second Dataframe. In the end, I have to assign the results.

res = []     for iRow, row in df1.iterrows():          df1 = df.assign(dtf=1 - abs((df1.time - row.time) / pd.Timedelta('2 hours')))          df1 = df1[df1.dtf > 0]          df2 = df2.loc[(df2.x == row.x) & (df2.y != 0)]          df1 = df1.merge(df2)          df1 = df1.assign(z=df1.dtf * df1.y)          res.append((df1.y.sum(), df1.z.sum())  

I clearly see that my CPU and memory are not very busy but I assume that parallelization would take more time than a direct calculation. The one method that I think could speed up the calculation is staying inside pandas rather than iteration via Python...

Is there any way to speed up the calculation?

In Json.Net's JsonConverter<> ReadJson(), why is reader..Value null?

Posted: 24 Mar 2021 08:06 AM PDT

I'm trying to write a custom JsonConverter for NetTopologySuite geometries.

My model:

public class MyModel  {      public string myName { get; set; }        [JsonConverter(typeof(MyPolygonConverter))]      public Polygon myPolygon { get; set; }  }  

My converter:

public class MyPolygonConverter : JsonConverter<Polygon>  {      public override Polygon ReadJson(JsonReader reader, Type objectType, Polygon existingValue,           bool hasExistingValue, JsonSerializer serializer)      {          var geoJson = (string)reader.Value;            // ... not relevant, because reader.Value is null.      }  }  

What I'm doing:

var deSerialized = JsonConvert.DeserializeObject<MyModel>("{\"myName\":\"My Name\",\"myPolygon\":{\"type\":\"Polygon\",\"coordinates\":[[[-100.0,45.0],[-98.0,45.0],[-99.0,46.0],[-100.0,45.0]]]}}");  

And what's happening:

My converter is being called, but reader.Value is null.

The examples I've seen online use (string)reader.Value to access the json string that needs to be converted. But in my case reader.Value is null.

How am I supposed to access the JSON string I need to convert?

To be clear - what I have is a model class that contains a property of a class - Polygon - that I convert to GeoJson on serialization that I need to convert back to that class, from the GeoJson.

So, my starting json is:

{      "myName" : "My Name",      "myPolygon" : {          "type" : "Polygon",          "coordinates" : [              [                  [-100.0, 45.0],                  [-98.0, 45.0],                  [-99.0, 46.0],                  [-100.0, 45.0]              ]          ]      }  }  

And I need to take everything that a child of "myPolygon" and hand it off to my conversion code. In the simple examples I've seen, reader.Value provided the value as a string. In this case it does not, most likely because "myPolygon"'s child isn't a single value, but is instead a complex json object.

I already have code for parsing the value when provided as a single json string. So how can I get the child, as a single json string?

Trying to loop through large string to find matching substrings

Posted: 24 Mar 2021 08:05 AM PDT

I have one large string with '----begin----' and '----end----' through out the string. I am trying to seperate out each message and display them all inside a div as seperate messages. The following code gets me the first one but I am struggling with the logic to loop through a large string with many messages. How do I loop through the entire large string? Thank you.

var app = document.querySelector('#app');    function parseStr(str) {    var start_idx = str.indexOf('------Begin Message------');    var end_idx = str.indexOf('------End Message------');        app.innerHTML += '<p>' + str.substring(start_idx, start_idx + 27) + '</p>' + '<p>' +       str.substring(start_idx + 27, end_idx) + '</p><p>' +      str.substring(end_idx, end_idx + 23);      }    parseStr(str);  

Insert three blocks (SQL lines) in a 100+MB SQL dump

Posted: 24 Mar 2021 08:05 AM PDT

I've seen some sed and awk answers here but have not yet found a solution to my problem.

I've killed a mysql dump import after one hour and when I'm adding some lines to the dump the import just needs 3 minutes (like mentioned in https://support.tigertech.net/mysql-large-inserts).

I need to add some lines after the first occurrence of "COMMIT;", some lines before the second (which is also the last) occurrence of "COMMIT;" and some lines at the end of the file.

Since an updated dump is fetched every X weeks or months I'd love to let my scripts do this, how would you do it?

Note: The three blocks are static, so they could be text files too.

Abstract example text would be

block1.sql

ALTER TABLE `table1_name` DISABLE KEYS;  ALTER TABLE `table2_name` DISABLE KEYS;  ALTER TABLE `table3_name` DISABLE KEYS;  SET FOREIGN_KEY_CHECKS = 0;  SET UNIQUE_CHECKS = 0;  SET AUTOCOMMIT = 0;  

block2.sql

SET UNIQUE_CHECKS = 1;  SET FOREIGN_KEY_CHECKS = 1;  

block3.sql

ALTER TABLE `table1_name` ENABLE KEYS;  ALTER TABLE `table2_name` ENABLE KEYS;  ALTER TABLE `table3_name` ENABLE KEYS;  

dump.sql

/* starts with SET.., BEGIN... and some CREATE TABLE... */  COMMIT;  /* insert block1.sql here */  INSERT INTO table1_name VALUES(1,2,3,4,5);  INSERT INTO table2_name VALUES(1,2,3,4,5);  INSERT INTO table3_name VALUES(1,2,3,4,5);  /* and so on, inserting all the dump data */  /* insert block2.sql here */  COMMIT;  create index index1 on table1_name(columnname);  create index index2 on table2_name(columnname);  create index index3 on table3_name(columnname);  /* and so on, creating all the indexes */  /* insert block3.sql at end of file */  

How to make VSCode automatically generate space before opening curly brackets (C/C++)?

Posted: 24 Mar 2021 08:06 AM PDT

What it is now:

int main(){    }  

How I want it to be:

int main() {    }  

When I write code in Eclipse, a space is created automatically before the curly bracket that opens the block. But I just can't get VSCode to work the same way... I tried to change the settings and saw that there is such a setting but it still does not automatically generate a space.

I'm very desperate to know how I can enable this in VSCode.

enter image description here

[Open for question editing suggestions]

KSQLDB coalesce always returns null despite parameters

Posted: 24 Mar 2021 08:06 AM PDT

I have the following ksql query:

SELECT     event->acceptedevent->id as id1,     event->refundedevent->id as id2,     coalesce(event->acceptedevent->id, event->refundedevent->id) as coalesce_col   FROM events   EMIT CHANGES;  

Based on the documentation, (https://docs.ksqldb.io/en/latest/developer-guide/ksqldb-reference/scalar-functions/#coalesce) COALESCE returns the first non-null parameter.

Query returns the following:

+-----------------------------------------------+-----------------------------------------------+-----------------------------------------------+  |ID1                                            |ID2                                            |COALESCE_COL                                   |  +-----------------------------------------------+-----------------------------------------------+-----------------------------------------------+  |1                                              |null                                           |null                                           |  |2                                              |null                                           |null                                           |  |3                                              |null                                           |null                                           |  

I was expecting since ID1 is clearly not null, being the first parameter to the call, COALESCE will return same value as ID1 but it returns null. What am I missing?

I am using confluentinc/cp-ksqldb-server:6.1.1 and use avro for the value serde.

Create Pie Chart In Tableau using Calculated field

Posted: 24 Mar 2021 08:06 AM PDT

I have create 2 calculated fields.

Example:

  1. will have remaining amount (100%)
  2. will have spend amount (60%)

both of these fields are calculated with different formulas.

Now I want to use these calculated fields in pie chart where it should show spend amount and remaining amount in pie chart.

Is there any way where I can use calculated fields in pie chart.

Thanks for help.

a there is someone who can help me create a blogspot script like this?

Posted: 24 Mar 2021 08:05 AM PDT

semple this fake post url : ayo-sharez.blogspot.com/2021/03/?u-https%253A%252F%252Fnews.sky.com%252Fstory%252Fcovid-news-live-latest-uk-updates-boris-johnson-says-well-learn-about-summer-holidays-by-5-april-12254097

this script themes from blogger : https://i.stack.imgur.com/vyjLq.png

tanks . . .

SwiftUI: Prevent word break for long words

Posted: 24 Mar 2021 08:06 AM PDT

How do I prevent word breaking for long words, e.g adjust font size to fit width?

Requirements: The outer gray frame must have the same fixed size. The should be 2 lines.

var body: some View {  VStack {      Spacer()        Image(systemName: "square")                    .resizable()                  .frame(width: 50, height: 50)                    Spacer()          Text("Acknowledgement for the rest")              .allowsTightening(true)              .minimumScaleFactor(0.01)              .lineLimit(2)              .multilineTextAlignment(.center)                }      .padding()      .frame(width: 140, height: 150, alignment: .center)      .background(          ZStack {              RoundedRectangle(cornerRadius: 10)                  .foregroundColor(Color(hex: "f9f9f9"))          }      )  

}

enter image description here

Why confusion matix is floating point - unable to get average confusion matrix after CV?

Posted: 24 Mar 2021 08:05 AM PDT

The following code returns the average of the confusion matrix but the values are floating point. This is quite strange because the values should not be floating-- I have never seen confusion matrix to be floating valued. Can somebody please tell me if there is a bug or how to overcome this problem?

import numpy as np  import matplotlib.pyplot as plt  from sklearn.metrics import mean_squared_error  from sklearn.metrics import confusion_matrix, classification_report  from sklearn.metrics import accuracy_score  from sklearn import datasets  # read in the data  from sklearn.datasets import load_breast_cancer     from sklearn.tree import DecisionTreeClassifier  from sklearn.model_selection import train_test_split  from sklearn.model_selection import cross_val_score  from sklearn.model_selection import KFold  from sklearn.model_selection import train_test_split  from sklearn.utils import shuffle      data = load_breast_cancer()  X, y = data.data, data.target  X, y = shuffle(X, y)    X_trainval, X_test, y_trainval, y_test = train_test_split(X, y, test_size=0.4, random_state=4)    model = DecisionTreeClassifier()     conf_matrix_list_of_arrays = []  #kf = cross_validation.KFold(len(y), shuffle=True, n_folds=5)  #for train_index, test_index in KFold(len(y), n_folds=5, shuffle=True):  kf = KFold(n_splits=5, shuffle=True)   for train_index, val_index in kf.split(X_trainval):     X_train, X_val = X_trainval[train_index], X_trainval[val_index]     y_train, y_val = y_trainval[train_index], y_trainval[val_index]       model.fit(X_train, y_train)     conf_matrix = confusion_matrix(y_val, model.predict(X_val))     conf_matrix_list_of_arrays .append(conf_matrix)  mean_of_conf_matrix_arrays = np.mean(conf_matrix_list_of_arrays, axis=0)   print(mean_of_conf_matrix_arrays)        [[22.2  2.2]   [ 3.4 40.4]]  

How to convert conv3d layer (quantization) in tensorflow lite?

Posted: 24 Mar 2021 08:05 AM PDT

I'm using a model containing conv3d layers. I've got an error when converting the model to tflite saying that conv3d op is neither a custom op nor a flex op.

code :

model_path = os.path.join(os.getcwd(), "models", "best-model.hdf5")     # load best weights  loaded_model = tf.keras.models.load_model(model_path)      no_quant_converter = tf.lite.TFLiteConverter.from_keras_model(loaded_model)    no_quant_tflite_model = no_quant_converter.convert()    # write the model to a tflite file as binary file  tflite_no_quant_file = os.path.join(os.getcwd(), "models", "tflite_models", "best-model_no_quant.tflite")   with open(tflite_no_quant_file, "wb") as f:     f.write(no_quant_tflite_model)  

error :

'tf.Conv3D' op is neither a custom op nor a flex op

Question 1 : how to quantize a conv3d layers ?

I tried to add "f.lite.OpsSet.SELECT_TF_OPS" to the converter supported ops. The code worked without errors but I don't know if the conv3d layers were correctly quantized or not (to int8).

Question2 : does adding "Select TensorFlow operators" affect quantization ? if yes how ?

edit section

LastValueQuantizer = tfmot.quantization.keras.quantizers.LastValueQuantizer  MovingAverageQuantizer = tfmot.quantization.keras.quantizers.MovingAverageQuantizer    class Default8BitConv3dQuantizeConfig(tfmot.quantization.keras.QuantizeConfig):    """QuantizeConfig for conv3d layers."""             def get_weights_and_quantizers(self, layer):      return [(layer.kernel, LastValueQuantizer(num_bits=8, symmetric=True, narrow_range=True, per_axis=False))]      def get_activations_and_quantizers(self, layer):      return [(layer.activation, MovingAverageQuantizer(num_bits=8, symmetric=False, narrow_range=False, per_axis=False))]      def set_quantize_weights(self, layer, quantize_weights):      layer.kernel = quantize_weights[0]            def set_quantize_activations(self, layer, quantize_activations):      layer.activation = quantize_activations[0]                def get_output_quantizers(self, layer):      return []      def get_config(self):    return {}    

Wrong shapes for multi input arrays in keras

Posted: 24 Mar 2021 08:05 AM PDT

I'm trying to build a multi input network using keras functional api. Right now I'm stuck as I get the error

ValueError: Error when checking input: expected input_1 to have shape (5,) but got array with shape (1,)

Given my code (below), I don't see how this is possible. The arrays I pass surely have the shapes (5,) and (15,) as my network specifies.

def buildModel():      # define two sets of inputs      inputA = ls.Input(shape=(5,))      inputB = ls.Input(shape=(15,))        # the first branch operates on the first input      x = ls.Dense(8, activation="relu")(inputA)      x = ls.Dense(4, activation="relu")(x)      x = ks.Model(inputs=inputA, outputs=x)        # the second branch opreates on the second input      y = ls.Dense(64, activation="relu")(inputB)      y = ls.Dense(32, activation="relu")(y)      y = ls.Dense(4, activation="relu")(y)      y = ks.Model(inputs=inputB, outputs=y)        # combine the output of the two branches      combined = ls.concatenate([x.output, y.output])        # apply a FC layer and then a regression prediction on the      # combined outputs      z1 = ls.Dense(2, activation="relu")(combined)      z1 = ls.Dense(5, activation="relu")(z1)        z2 = ls.Dense(2, activation="relu")(combined)      z2 = ls.Dense(15, activation="relu")(z2)        # our model will accept the inputs of the two branches and      # then output a single value      model = ks.Model(inputs=[x.input, y.input], outputs=[z1, z2])      model.compile(optimizer='adam', loss='poisson', metrics=['accuracy'])      return model    def train_model(model, x1, x2, y1, y2):      print(x1.shape)      model.fit([x1, x2], [y1, y2], batch_size=1, epochs=100) # Error raised here    if __name__ == "__main__":      mod = buildModel()      x1 = np.array([5, 2, 1, 4, 5])      x2 = np.array([1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1])      y1 = np.array([0, 0, 1, 0, 0])      y2 = np.array([0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0])      train_model(mod, x1, x2, y1, y2)  

The arrays passed are for testing purposes only, the AI will eventually tackle a real problem.

If you think the question isn't well defined or needs more specification, please let me know.

EDIT: Here is the traceback:

Traceback (most recent call last):    File "/Users/henrihlo/project/ai.py", line 70, in <module>      train_model(mod, x1, x2, y1, y2)    File "/Users/henrihlo/project/ai.py", line 49, in train_model      model.fit([x1, x2], [y1, y2], batch_size=1, epochs=100)    File "/Users/henrihlo/anaconda3/lib/python3.7/site packages/keras/engine/training.py", line 1154, in fit      batch_size=batch_size)    File "/Users/henrihlo/anaconda3/lib/python3.7/site packages/keras/engine/training.py", line 579, in _standardize_user_data      exception_prefix='input')    File "/Users/henrihlo/anaconda3/lib/python3.7/site packages/keras/engine/training_utils.py", line 145, in   standardize_input_data      str(data_shape))  ValueError: Error when checking input: expected input_1 to have shape (5,) but got array with shape (1,)  

Printing the shape of x1 yields (5,).

Page redering diffrence Inertia vs. Vue with Laravel Backend

Posted: 24 Mar 2021 08:05 AM PDT

I implemented a simple crud application in two ways. One with Laravel and Vue and one with Laravel, Vue and Inertia.

When rendering a simple user list in my Vue/Laravel application (either with routing or initial page load), Vue renders the whole page instantly and loads the user list as soon as it receives it from the server. -> good user experience, possibility to implement a loading indication

When rendering the same thing in my inertia application, Vue renders the whole page after the data has been received from the server. Which is a very bad thing for applications with large amounts of data.

Even in my really small/slim application, I felt the difference and figured this out with a simple sleep(3) before returning the view (or Inertia::render) in my UserController.

Is this normal/is there a way to prevent this? Or did I possibly implement inertia poorly?

I'm using inertia.js 0.8.5, inertia-vue 0.5.5 and Vue 2.6.12

$ Composer can't find mongodb extension, required Mongodb extension

Posted: 24 Mar 2021 08:05 AM PDT

I'm using with latest php version 7.2 on macOS Mojave and receiving error like

 $composer require mongodb/mongodb  Using version ^1.4 for mongodb/mongodb  ./composer.json has been updated  Loading composer repositories with package information  Updating dependencies (including require-dev)  

For more information about question : see the screenshoot

enter image description here

Your requirements could not be resolved to an installable set of packages.

Problem 1 - mongodb/mongodb v1.4.x-dev requires ext-mongodb ^1.5.0 -> the requested PHP extension mongodb is missing from your system. - mongodb/mongodb 1.5.x-dev requires ext-mongodb ^1.6 -> the requested PHP extension mongodb is missing from your system. - mongodb/mongodb 1.4.2 requires ext-mongodb ^1.5.0 -> the requested PHP extension mongodb is missing from your system. - mongodb/mongodb 1.4.1 requires ext-mongodb ^1.5.0 -> the requested PHP extension mongodb is missing from your system. - mongodb/mongodb 1.4.0 requires ext-mongodb ^1.5.0 -> the requested PHP extension mongodb is missing from your system. **- Installation request for mongodb/mongodb ^1.4 -> satisfiable by mongodb/mongodb[1.4.0, 1.4.1, 1.4.2, 1.5.x-dev, v1.4.x-dev].

Installation failed, reverting ./composer.json to its original content.

I have already installed mongoDB extension still receiving problem enter image description here

Not sure what I've missed steps to installation. If anyone can help me with this composer problem, I'd greatly appreciate it. in advance Thanks.

No comments:

Post a Comment