Tuesday, October 19, 2021

Recent Questions - Stack Overflow

Recent Questions - Stack Overflow


simple but not easy merge task in R

Posted: 19 Oct 2021 08:00 AM PDT

I have two incomplete dataframes: Columns are missing or NA values. "by" is the merge index and df_a has "priority" over df_b.

df_a = data.frame("by" = c(1,2,3),                    "a" = c(1,2,3),                    "b" = c(1,NA,3))    df_b = data.frame("by" = c(2,3,4),                    "a" = c(7,NA,4),                    "c" = c(2,3,4))  

desired result:

  by a  b  c  1  1 1  1 NA  2  2 2  2  2  3  3 3  3  3  4  4 4 NA  4  

Does anyone has a clue how to do this efficiently with R base? Thanks in advance!

Flutter ternary conditional is null and not subtype of bool

Posted: 19 Oct 2021 08:00 AM PDT

Text(    data?["success"] != null ? "Success" : "Failure",    style: TextStyle(      color: data?["success"] ? Colors.green : Colors.red,      fontSize: 15.0),    )  ),  

_TypeError (type 'Null' is not a subtype of type 'bool')

Sometimes data["success"] has a response of null but it usually is true or false boolean.

I'm using the spacexdata.com api for launches: https://docs.spacexdata.com/#bc65ba60-decf-4289-bb04-4ca9df01b9c1 and it is not data I control.

Hoping someone can help

Socket.io not connecting to server flutter

Posted: 19 Oct 2021 08:00 AM PDT

I have been having issues working with socket.io library with flutter. The problem is that it doesn't just connect. My node.js socket version is 4.0.0 while the socket client version socket_io_client 2.0.0-beta.4-nullsafety.0

Is there anyone with such experience on what can be done?

Why can't IDEA find JavaFX package after upgrade JavaFX Project to JDK 17 using Azul Zulu Builds of OpenJDK with FX?

Posted: 19 Oct 2021 08:00 AM PDT

I have a Java FX project and upgraded the project to JDK 17 using the following Azul Zulu Build of OpenJDK with JavaFX

https://www.azul.com/downloads/?os=windows&package=jdk-fx

Does anyone have a clue why Intellij can't find JavaFX package using JDK 17 from Azul Zulu Builds of OpenJDK with FX?

IndexError: tuple index out of range (np.shape, reshape)

Posted: 19 Oct 2021 08:00 AM PDT

scaler = MinMaxScaler(feature_range=(0,1))  scaled_data = scaler.fit_transform(data['High'].values.reshape(-1,1))    prediction_days=100    x_train=[]  y_train=[]    for i in range(prediction_days, len(scaled_data)):      x_train.append(scaled_data[prediction_days-i:,0])      y_train.append(scaled_data[i,0])      x_train,y_train= np.array(x_train),np.array(y_train)  

Blockquote

x_train=np.reshape(x_train,(x_train.shape[0],x_train.shape[1],1))

File "C:\Users\Desktop\untitled0.py", line 37, in x_train=np.reshape(x_train,(x_train.shape[0],x_train.shape[1],1))

IndexError: tuple index out of range

ManualResetEvent in .Net 5

Posted: 19 Oct 2021 08:00 AM PDT

I'm looking into migrating a .Net Framework solution to .Net 5, and the portability analyzer lists the following issue in a 3rd-party assembly:

enter image description here

I'm just curious to know why it reports this as not supported when the MS documentation appears to show the Set() method of System.Threading.ManualResetEvent is present in .Net 5 (and Standard 2.0 for that matter).

Is there something that I'm not getting here? Or will the issue actually be something inside the Set() method, e.g. the code will be doing something that would fail under .Net 5?

how to find liked posts with user id

Posted: 19 Oct 2021 08:00 AM PDT

i am developing project using nodejs. I want to check if the user's userId is the same as the user of the post like. How should I be able to check ?

 const audio = await Audio.find({likes: userId})

This is the post data i want to find

{      "title": "Điêu Toa",      "music": "public/audio/music_6149812c44cf4d33f410d680_1633941621172.mp3",      "singer": "Massew x Pháo",      "size": "2.72mb",      "date": {          "$date": "2021-10-11T08:37:42.840Z"      },      "owner": "6149812c44cf4d33f410d680",      "description": "Lời nói cứ như là bạc là vàng có ta và chàng ngồi ở đây chứng dám cho, chẳng việc gì phải lắng lo ~~",      "category": "Electronic",      "__v": 48,      "likes": [{          "user": "616c09216e4b2ff62f550c39"      }, {          "user": "6149812c44cf4d33f410d680"      }]  }

Como enviar un valor +1 a un campo numerico de sql por medio de la activacion de un checkbox en un documento aspx

Posted: 19 Oct 2021 08:00 AM PDT

Estoy llevando a cabo una aplicacion(aspx document) de encuestas de satisfaccion, y estoy trabajando con controladores de tipo checkbox (esto para permitir cambiar el icono antes y dsp de presionarlo)

Me gustaria conocer una manera de incrementar (+1) el campo correspondiente en la tabla de sql, al checkbox presionado.

Instantiating classes in WordPress plugin

Posted: 19 Oct 2021 08:00 AM PDT

the last couple of weeks i have been working on my own WordPress plugin. I am trying to do a class based codebase.

My plugin works correctly, but i don't really know if this is the correct way to develop. I would like to learn the best practices.

To demonstrate, here is my base plugin file:

<?php    /**   * Blub Hamerhaai plugin   *   * This is the main blub plugin for all sites   *   * @link              {github link}   * @since             0.0.2   * @package           Blub Hamerhaai   *   * @wordpress-plugin   * Plugin Name:       {plugin name}   * Plugin URI:        {github link}   * Description:       This is the main blub plugin for all sites   * Version:           0.0.4   * Author:            Blub   * Author URI:        {link}   * License:           Copyright Blub media, all rights reserved   * License URI:       {link}   * Text Domain:       blub-hamerhaai   * Domain Path:       /languages   *   * Created by:        Me   */    namespace Blub;    require 'includes/includes.php';    define(__NAMESPACE__ . '\PLUGINROOT', __FILE__);  define(__NAMESPACE__ . '\PLUGINDIR', __DIR__);    if (!class_exists('Hamerhaai')) {      class Hamerhaai      {            public function __construct()          {              register_activation_hook(__FILE__, [$this, 'activation']);              register_deactivation_hook(__FILE__, [$this, 'deactivation']);              add_action('init', [$this, 'init']);          }            public function activation()          {              BlubRole::add();              PluginUpdate::add();          }            public function deactivation()          {              BlubRole::remove();              PluginUpdate::remove();          }            public function init()          {              //Preventing removals in other pages              global $pagenow;                load_textdomain('blub-hamerhaai', PLUGINDIR . '/languages/blub-hamerhaai-nl_NL.mo');                //Things to do for all users              new OptionsPage();              new BlubColors();              new CustomLoginPage();              $widget = new DashboardWidget();                // Things to do for blub user              if (BlubRole::isBlubUser()) {                  new AdminText();                  new RemoveMenuItems();                  new GutenbergEdits();                    //Only for dashboard                  if ($pagenow === 'index.php') {                      $widget->forceShow();                      $widget->removeDefault();                  }                    new LoadFrontendStyle();              }          }      }  }    new Hamerhaai();  

The main thing i am insecure about is instantiating all the classes on the plugin init function. I don't think this is the best practice. All the classes are based on a specific functionality.

Can someone explain me if this is the way to go? Or how to improve?

Thanks in advance.

Change Keycloak logout redirect url

Posted: 19 Oct 2021 07:59 AM PDT

I would like to set a Keycloak redirect url. After click on Sign out button in template.ftl template which is set in account directory It is represented by list item:

<li><a href="${url.logoutUrl}">${msg("doSignOut")}</a></li>  

How it is now:

  • I'm redirect to the main site of keycloak (actually it is a site of login into keycloak)

What I want:

  • change this site and redirect user to main page of project. How can I define it as

I use Keycloak version 12.0.2 I haven't found any appropriate settings in realmName.json file or Administration Console which is available at http://localhost:8088/auth/admin/master/console/#/realms/realmName

Repeat analysis for several datasets in R

Posted: 19 Oct 2021 07:59 AM PDT

How can I repeat this code for each subject (xxx), so that the results are added to the data.frame (centralities)?

fullDataDetrend_xxx <- subset(fullDataDetrend, subjno == xxx, select=c(subjno,depressed,sad,tired,interest,happy,neg_thoughts,concentration_probl,ruminating,activity,datevar,timestamp,dayno,beepno))      model_xxx <- var1(       fullDataDetrend_xxx)    model_xxx_omega <- getmatrix(model_xxx, "omega_zeta")  centrality_model_xxx_omega <- centrality(model_xxx_omega )    centralities[nrow(centralities) + 1,] <- c("xxx",centrality_model_xxx_omega$InExpectedInfluence)  

Order SQL query results by the order they have been searched for in the WHERE clause? [duplicate]

Posted: 19 Oct 2021 08:00 AM PDT

I was wondering if there is a way to order the results received by an SQL database in the order which I have requested them in the WHERE clause.

The problem is that I need to search for 2 people in a database by first name and last name where both names have potentially many possible matches. So if I want to search for names that match Bob Smith and Alex Hunter I would fire the following query

SELECT column1   FROM table1   WHERE (table.NAME LIKE '%Bob%' AND table.NAME LIKE '%Smith%')   OR (table.NAME LIKE '%Alex%' AND table.NAME LIKE '%Hunter%')  

My issue is that if there are, lets say, 10 results for each part of the query, then rows would be in random order. I want them to be in the order I searched them for, aka, all the results that contain Bob Smith first, followed by all the results that contain Alex Hunter.

Is there an option to do this using GROUP BY, ORDER BY or any other command?

Please help me to print the following python codes in tkinter

Posted: 19 Oct 2021 08:00 AM PDT

I have tried to print the print(df.nlargest(3,'Height')) in the terminal, but I am not sure how it works in Tkinter.

This is the codes:

  #importing pandas as pd  from tkinter import *  from tkinter import ttk  import pandas as pd    root = Tk()    root.geometry("100x70")  #creating DataFrame  df= pd.DataFrame({'Name':['Chetan','yashas','yuvraj','Pooja','Sindu','Renuka'],'Age':  [20,25,30,18,25,20],'Height': [155,160,175,145,155,165],'Weight': [75,60,75,45,55,65]})    print(df.nlargest(3,'Height'))    root.mainloop()    

Thanks for your help!

How to get XML response values in karate framework

Posted: 19 Oct 2021 08:00 AM PDT

This is my XML Response and I would like to retrieve Name and LastModifiedTime from response by using karate framework

<ADELdirectory:Directory      xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"      xmlns:ADELdirectory="http://www.com/XMLSchema/MT/Generic/v1.3" xsi:schemaLocation="http://www.com/XMLSchema/MT/Generic/v1.3 ADELdirectory.xsd">      <Header>          <Title>Directory listing</Title>          <MachineID>TS01</MachineID>          <MachineType>STEdiSimulator</MachineType>          <SoftwareRelease>Unknown</SoftwareRelease>          <CreatedBy>SystemTest.EDISimulator</CreatedBy>          <CreateTime>2021-10-19T14:31:17.442Z</CreateTime>          <Comment>              <elt>url: http://174.28.39.123:8080/EDI/ADELler?cmd=list</elt>          </Comment>          <DocumentId>c0ceb67f-6498-4b5e-8c86-4f482121fb0c</DocumentId>          <DocumentType>ADELdirectory</DocumentType>          <DocumentTypeVersion>v1.3</DocumentTypeVersion>      </Header>      <Input>          <Username>SystemTestFramework</Username>          <DocumentType>ADELler</DocumentType>          <DocumentPath>/</DocumentPath>          <RequestParameterList>              <elt>                  <Name>cmd</Name>                  <Value>list</Value>              </elt>          </RequestParameterList>      </Input>      <Results>          <MainAttributeList/>          <EntryList>              <elt>                  <Type>Document</Type>                  <Name>TS01/LOT_AP_0001/2021-10-12T14:35:28.835Z</Name>                  <LastModifiedTime>2021-10-12T14:50:28.836Z</LastModifiedTime>                  <Size>15235986</Size>              </elt>              <elt>                  <Type>Document</Type>                  <Name>TS01/LOT_AP_0001/2021-10-12T14:35:35.853Z</Name>                  <LastModifiedTime>2021-10-12T14:50:35.854Z</LastModifiedTime>                  <Size>15235986</Size>              </elt>          </EntryList>      </Results>  </ADELdirectory:Directory>  

When I run .feature file there is a error message 'no variable found with name' I need to define correct XML path.

    * xml entryLists = $/Directory/Results/EntryList/elt  

You can check the error message: This is the error message

VS Code Error in debugging : Could not find or load main class vs code

Posted: 19 Oct 2021 08:00 AM PDT

In VS Code, I added JUnit to setting.json file. After adding it, debugger is stopped working and gives me "Could not find or load main class vs code" error. setting.json load main class error

{      "editor.suggestSelection": "first",      "vsintellicode.modify.editor.suggestSelection": "automaticallyOverrodeDefaultValue",      "files.exclude": {          "**/.classpath": true,          "**/.project": true,          "**/.settings": true,          "**/.factorypath": true      },      "java.project.referencedLibraries": [          "lib/**/*.jar",            "C:\\Users\\Tarık\\Downloads\\junit-platform-console-standalone-1.8.0-M1.jar"      ],            "editor.fontSize": 16,        }  

When I delete the edited part from setting.json, debugger starts to work again. I couldn't get the problem.

Can you help me to find a solution? I searched but find nothing. Thanks for your time ..

How should i add a health system to my game and food items in the game? [closed]

Posted: 19 Oct 2021 08:00 AM PDT

I'm a total beginner so I'm sorry if this is an obvious question but right now my code is:

class Item(object):        def _init_(self, name, value, quantity = 1):          self.name = name          self.benefit = benefit          self.quantity = quantity      def itemadd(self):          inventory.append(Item)            class Food(Item):      def _init_(self, name, benefit, quantity =1):          Item._init_(name, benefit, quantity)        def foodadd(self):          food.append(Food)        def Food_Berries(Food):          name = "Berry"          benefit = +10 health        def Food_Plums(Food):          name = "Plum"          benefit = +40 health        def Food_Fish(Food):          name = "Fish"          benefit = +60 health  

and I want to add in a health system so that by fighting enemies my health goes down and regain it by resting or eating food but i have no clue how exactly i would implement that in my code? should i define a health variable? i'm just not sure?

Why can't k3s access host services that listening loopback address?

Posted: 19 Oct 2021 08:00 AM PDT

I deployed k3s on a single Ubuntu machine.

Other services are installed on this machine directly (outside k8s), e.g. Redis, Mysql... They are listening loopback address 127.0.0.1 for the security reason.

But the service inside k3s cannot connect to my db. If I change the listening address to 0.0.0.0, the problem will be fixed.

Why? And what is the best practice in this use case?

PS: I use Endpoints to map host service to k8s:

apiVersion: v1  kind: Service  metadata:    name: redis  spec:    ports:      - port: 6379  ---  apiVersion: v1  kind: Endpoints  metadata:    name: redis  subsets:    - addresses:        - ip: xxxxx (host's ip)      ports:        - port: 6379    

jQuery import isn't working in Encore / Symfony 5

Posted: 19 Oct 2021 08:00 AM PDT

I'm struggling with correctly including jQuery in my symfony project.

I have installed Encore and jQuery this far with the following webpack.config.js-File:

const Encore = require('@symfony/webpack-encore');    // Manually configure the runtime environment if not already configured yet by the "encore" command.  // It's useful when you use tools that rely on webpack.config.js file.  if (!Encore.isRuntimeEnvironmentConfigured()) {      Encore.configureRuntimeEnvironment(process.env.NODE_ENV || 'dev');  }    Encore      // directory where compiled assets will be stored      .setOutputPath('public/build/')      // public path used by the web server to access the output path      .setPublicPath('/build')      // only needed for CDN's or sub-directory deploy      //.setManifestKeyPrefix('build/')        /*       * ENTRY CONFIG       *       * Each entry will result in one JavaScript file (e.g. app.js)       * and one CSS file (e.g. app.css) if your JavaScript imports CSS.       */      .addEntry('app', './assets/app.js')        // enables the Symfony UX Stimulus bridge (used in assets/bootstrap.js)      .enableStimulusBridge('./assets/controllers.json')        // When enabled, Webpack "splits" your files into smaller pieces for greater optimization.      .splitEntryChunks()        // will require an extra script tag for runtime.js      // but, you probably want this, unless you're building a single-page app      .enableSingleRuntimeChunk()        /*       * FEATURE CONFIG       *       * Enable & configure other features below. For a full       * list of features, see:       * https://symfony.com/doc/current/frontend.html#adding-more-features       */      .cleanupOutputBeforeBuild()      .enableBuildNotifications()      .enableSourceMaps(!Encore.isProduction())      // enables hashed filenames (e.g. app.abc123.css)      .enableVersioning(Encore.isProduction())        .configureBabel((config) => {          config.plugins.push('@babel/plugin-proposal-class-properties');      })        // enables @babel/preset-env polyfills      .configureBabelPresetEnv((config) => {          config.useBuiltIns = 'usage';          config.corejs = 3;      })        // enables Sass/SCSS support      //.enableSassLoader()        // uncomment if you use TypeScript      //.enableTypeScriptLoader()        // uncomment if you use React      //.enableReactPreset()        // uncomment to get integrity="..." attributes on your script & link tags      // requires WebpackEncoreBundle 1.4 or higher      //.enableIntegrityHashes(Encore.isProduction())        // uncomment if you're having problems with a jQuery plugin      // .autoProvidejQuery()  ;    module.exports = Encore.getWebpackConfig();  

My asset/app.js file looks as follows:

/*   * Welcome to your app's main JavaScript file!   *   * We recommend including the built version of this JavaScript file   * (and its CSS file) in your base layout (base.html.twig).   */    // any CSS you import will output into a single css file (app.css in this case)  import './styles/app.css';    //jquery  // require jQuery normally    // loads the jquery package from node_modules  const $ = require('jquery');  global.$ = global.jQuery = $;    // start the Stimulus application  import './bootstrap';    $(document).ready(function(){      alert("Script working properly");  });  

I want to use jQuery in a twig-template that looks like this:

base.html.twig

<!DOCTYPE html>  <html lang="en">      <head>          <meta charset="UTF-8">          <title>{% block title %}Welcome!{% endblock %}</title>          {# Run `composer require symfony/webpack-encore-bundle`             and uncomment the following Encore helpers to start using Symfony UX #}          {% block stylesheets %}              {{ encore_entry_link_tags('app') }}          {% endblock %}          {% block javascripts %}              {{ encore_entry_script_tags('app') }}          {% endblock %}      </head>      <body>          {% block body %}{% endblock %}      </body>  </html>  

index.html.twig

{% extends 'base.html.twig' %}  {% block javascripts %}      <script>          $(document).ready(function(){              console.log("Script working properly");          });          ....      </script>  {% endblock %}  {% block body %}  ....  {% endblock %}  

However, I just get an 'Uncaught ReferenceError: $ is not defined' error. I did run "npm run dev" or "npm run watch" a few times after doing npm install - but that doesn't help.

I also tried following this guide but that didn't help: https://symfony.com/doc/current/frontend/encore/legacy-applications.html

I really hope someone can help me out here - thanks in advance!

Process List<String> synchronously after flatMap?

Posted: 19 Oct 2021 08:00 AM PDT

Hey I just started to dive into reactive programming and I can't figure out how to process a List<String> in a synchronous way after flatMap.

What I am trying to achieve:

  1. Get domain list from external service
  2. Filter out existing domains in database
  3. Make another http request to external service to get domain info. These calls should be executed in a synchronous way with Duration.ofSeconds(new Random().nextInt(5)) delay applied one after another, like Thread.sleep and not in parallel way.
  4. Store new domain data into database
client.fetchDomainList() // Flux<DomainListResponse>  .flatMap(response -> Flux.fromIterable(response.getDomainList()))  .filter(hostname -> ! domainRepository.existsByHostname(hostname))  .collectList()    // this next bit is sketchy.   // flatMap will doesn't work here (in my mind)   // because it will apply delay in parallel way  .map(list -> Flux.fromIterable(list)      .map(hostname -> client.fetchDomainInfo(hostname)          .delayElements(Duration.ofSeconds(new Random().nextInt(3))))      .map(domainInfoResponse -> {          return new Domain();      })  )    .flatMap(s -> { // s -> Flux<Domain> here. Should be simply Domain   // save into database?  })  

addEventListener firing multiple times for the same form

Posted: 19 Oct 2021 08:00 AM PDT

Here is my Javascript module:

const Calculator = (function() {      return {          listen: function (formId) {              this.formId = formId;                this.calculatorForm = document.querySelector(`#form_${this.formId}`);                if (this.calculatorForm) {                  this.addEventListeners();              }          },            addEventListeners: function() {              const self = this;                this.calculatorForm.addEventListener('submit', function(event) {                  console.log('calculatorForm submit', self);                    self.calculatorSubmission(event);              }, false);          },            calculatorSubmission: function(event) {              event.preventDefault();                console.log('Form submitted', this.calculatorForm);          }      };  })();    export default Calculator;  

I build all the Javascript using Webpack so I can load modules like this:

import Calculator from './modules/calculator';  

The page in question where the Javascript is loaded has tabbed content. Each tab contains a different form, all using the Calculator module so when I switch between tabs, I call:

Calculator.listen('form-id');  

The issue I have is when I switch between tabs a few times. Say I view tab 3, 5 times and then fill out and submit form in tab 3. The form is submitted 5 times because of the addEventListener called each time I view tab 3. Make sense?

I'm struggling to fix it - probably because I've been looking at it for hours now and my head is now mash.

Is the problem my module setup?

What best approach to overcoming my issue?

Thanks

openGL ES calculate degree between object?

Posted: 19 Oct 2021 08:00 AM PDT

I now draw two AR object,Andy and Arrow on my view,and I want to use Matrix.setRotateMto make a rotation which make Arrow point to Andy.But I find a big problem is:I can't calculate angle between Andy and Arrow(I tried to use sceneform's worldPosition and setLookdirection,but didn't work).Is there any way to calculate the angle between them?Or any other solution?

Match of an id value and extracing a string in Google Sheets

Posted: 19 Oct 2021 08:00 AM PDT

following problem:

I have a column with wrong Ids

see here

Now I want to watch those wrong Ids with another sheet where I have same Ids and the correct link I want to match with those Ids:

see here

So what I same up with is the following ->

see here

=IFERROR(VLOOKUP(A2,'extract base'"B:F),"")"))  

But obviously doesn't work haha. So basically very easy -> if the Id from Sheet 1 matches with the Id from Sheet two put in the second column (in my example custom_label) the value of sheet two column 2

Any help is appreciated, thank you so much!

Prove that we can decide whether a Turing machine takes at least 100 steps on some input

Posted: 19 Oct 2021 08:00 AM PDT

We know that the problem "Does this Turing machine take at least this finite number of steps on that input?" is decidable, because it will always answer yes or no, where it will say yes if the machine reaches the given number of steps and no if it halts before that.

Now here is my doubt: if it halts before reaching those many steps — i.e. the input either (1) got accepted or (2) got rejected or maybe (3) got into a loop — then, when we are in case (3), how can we be sure that it will always be in that loop? What I mean to say is that if it doesn't run forever but comes out of the loop at some point of time then it might cross the asked number of steps so the decision made earlier as no will now change to yes. If so, then it's not decidable, so how can we conclude that it's decidable?

Assign a value to an enum case during initalization in Swift

Posted: 19 Oct 2021 08:00 AM PDT

I'm decoding a JSON API to a struct, with a CodingKey enum in order to map the language key from the response to the name property of the struct:

{    id: "1",    english: "United States",    french: "États Unis",    spanish: "Estados Unidos"  }  
struct Country: Codable, Hashable, Identifiable {    let id: String    let name: String        enum CodingKeys : String, CodingKey {      case id      case name = "french"     }  }  

I want to be able to control programmatically the assigned name value in the CodingKeys struct so it'll be based on the user device locale.

// English user  country.name // "United States"    // French user  country.name // "États Unis"  

I have the function getUserLocale() that checks for the user's locale and returns the string value of it (english, french, etc...).
How can I make it run during the enum initalization so it'll assign the locale value to the name property?

Doctrine - Argument passed to __construct must be an array

Posted: 19 Oct 2021 07:59 AM PDT

I just triying to create a new service when I find this error. When I try to list the doctrine commands avaiable it show me the next error:

Doctrine\ORM\Mapping\OneToMany::__construct() must be of the type array or null, string given, called in /var/www/html/vendor/doctrine/annotations/lib/Doctrine/Common/Annotations/DocParser.php

I try to reset the entity responsable of it without results. Here is the all trace:

TypeError {#478  #message: "Argument 3 passed to Doctrine\ORM\Mapping\OneToMany::__construct() must be of the type array or null, string given, called in /var/www/html/vendor/doctrine/annotations/lib/Doctrine/Common/Annotations/DocParser.php on line 971"    #code: 0    #file: "./vendor/doctrine/orm/lib/Doctrine/ORM/Mapping/OneToMany.php"    #line: 44    trace: {      ./vendor/doctrine/orm/lib/Doctrine/ORM/Mapping/OneToMany.php:44 { …}      ./vendor/doctrine/annotations/lib/Doctrine/Common/Annotations/DocParser.php:971 { …}      ./vendor/doctrine/annotations/lib/Doctrine/Common/Annotations/DocParser.php:719 { …}      ./vendor/doctrine/annotations/lib/Doctrine/Common/Annotations/DocParser.php:376 { …}      ./vendor/doctrine/annotations/lib/Doctrine/Common/Annotations/AnnotationReader.php:178 { …}      ./vendor/doctrine/annotations/lib/Doctrine/Common/Annotations/PsrCachedReader.php:155 { …}      ./vendor/doctrine/annotations/lib/Doctrine/Common/Annotations/PsrCachedReader.php:88 { …}      ./vendor/doctrine/annotations/lib/Doctrine/Common/Annotations/PsrCachedReader.php:98 { …}      ./vendor/doctrine/orm/lib/Doctrine/ORM/Mapping/Driver/AnnotationDriver.php:331 { …}      ./vendor/doctrine/persistence/lib/Doctrine/Persistence/Mapping/Driver/MappingDriverChain.php:79 { …}      ./vendor/doctrine/doctrine-bundle/Mapping/MappingDriver.php:45 { …}      ./vendor/doctrine/orm/lib/Doctrine/ORM/Mapping/ClassMetadataFactory.php:134 { …}      ./vendor/doctrine/doctrine-bundle/Mapping/ClassMetadataFactory.php:19 { …}      ./vendor/doctrine/persistence/lib/Doctrine/Persistence/Mapping/AbstractClassMetadataFactory.php:382 { …}      ./vendor/doctrine/persistence/lib/Doctrine/Persistence/Mapping/AbstractClassMetadataFactory.php:251 { …}      ./vendor/doctrine/orm/lib/Doctrine/ORM/EntityManager.php:303 { …}      ./var/cache/dev/ContainerX9n3NQZ/EntityManager_9a5be93.php:94 {        ContainerX9n3NQZ\EntityManager_9a5be93->getClassMetadata($className)^        ›         ›     return $this->valueHolderda610->getClassMetadata($className);        › }        arguments: {          $className: "App\Entity\App\City"        }      }      ./vendor/doctrine/doctrine-bundle/Repository/ServiceEntityRepository.php:45 { …}      ./src/Repository/App/CityRepository.php:26 { …}      ./var/cache/dev/ContainerX9n3NQZ/getCityRepositoryService.php:27 { …}      ./var/cache/dev/ContainerX9n3NQZ/App_KernelDevDebugContainer.php:525 { …}      ./var/cache/dev/ContainerX9n3NQZ/getCityServiceService.php:23 { …}      ./var/cache/dev/ContainerX9n3NQZ/App_KernelDevDebugContainer.php:525 { …}      ./var/cache/dev/ContainerX9n3NQZ/getDoctrine_FixturesLoadCommandService.php:43 { …}      ./var/cache/dev/ContainerX9n3NQZ/App_KernelDevDebugContainer.php:525 { …}      ./vendor/symfony/dependency-injection/Container.php:422 { …}      ./vendor/symfony/dependency-injection/Argument/ServiceLocator.php:42 { …}      ./vendor/symfony/console/CommandLoader/ContainerCommandLoader.php:45 { …}      ./vendor/symfony/console/Application.php:551 { …}      ./vendor/symfony/console/Application.php:519 { …}      ./vendor/symfony/framework-bundle/Console/Application.php:126 { …}      ./vendor/symfony/console/Application.php:664 { …}      Symfony\Component\Console\Application->Symfony\Component\Console\{closure}() {}      ./vendor/symfony/console/Application.php:665 { …}      ./vendor/symfony/framework-bundle/Console/Application.php:116 { …}      ./vendor/symfony/console/Application.php:254 { …}      ./vendor/symfony/framework-bundle/Console/Application.php:82 { …}      ./vendor/symfony/console/Application.php:166 { …}      ./bin/console:43 { …}    }  }  

Here is the City entity:

<?php    namespace App\Entity\App;    use App\DBAL\Types\Geolocation\Point;  use App\Entity\App\Graveyard;  use App\Repository\App\CityRepository;  use Doctrine\ORM\Mapping as ORM;  use Doctrine\Common\Collections\ArrayCollection;  use Doctrine\Common\Collections\Collection;    /**   * @ORM\Entity(repositoryClass=CityRepository::class)   * @ORM\Table (name="location", schema="app")   */  class City  {      /**       * @ORM\Id       * @ORM\GeneratedValue       * @ORM\Column (type="integer")       */      private $id;        /**       * @ORM\Column(type="string", length=255, nullable=false)       */      private $name;        /**       * @ORM\Column(type="string", length=255, nullable=true)       */      private $country;        /**       * @ORM\OneToMany(targetEntity=Company::class, mappedBy="city", cascade="persist")       */      private $companies;        /**       * @ORM\OneToMany(targetEntity=Graveyard::class, mappedBy="city", cascade="persist")       */      private $graveyards;        /**       * @ORM\OneToMany(targetEntity=FuneralParlor::class, mappedBy="city", cascade="persist")       */      private $funeralParlors;        /**       * @ORM\OneToMany(targetEntity=AdvertisementTransfer::class, mappedBy="city")       */      private $advertisementTransfers;        /**       * @ORM\OneToMany(targetEntity=Crematorium::class, mappedBy="city")       */      private $crematoria;        /**       * @ORM\Column(type="point")       */      private $coordinate;        /**       * @ORM\Column(type="string", length=255, nullable=true, options={"default" : null})       */      private $province;        public function __construct()      {          $this->companies = new ArrayCollection();          $this->graveyards = new ArrayCollection();          $this->funeralParlors = new ArrayCollection();          $this->advertisementTransfers = new ArrayCollection();          $this->crematoria = new ArrayCollection();      }        public function getId(): ?int      {          return $this->id;      }        public function getName(): ?string      {          return $this->name;      }        public function setName(string $name): self      {          $this->name = $name;            return $this;      }        public function getCountry(): ?string      {          return $this->country;      }        public function setCountry(?string $country): self      {          $this->country = $country;            return $this;      }        /**       * @return Collection|Company[]       */      public function getCompanies(): Collection      {          return $this->companies;      }        public function addCompany(Company $company): self      {          if (!$this->companies->contains($company)) {              $this->companies[] = $company;              $company->setCity($this);          }            return $this;      }        public function removeCompany(Company $company): self      {          if ($this->companies->removeElement($company)) {              // set the owning side to null (unless already changed)              if ($company->getCity() === $this) {                  $company->setCity(null);              }          }            return $this;      }        /**       * @return Collection|Graveyard[]       */      public function getGraveyards(): Collection      {          return $this->graveyards;      }        public function addGraveyard(Graveyard $graveyard): self      {          if (!$this->graveyards->contains($graveyard)) {              $this->graveyards[] = $graveyard;              $graveyard->setCity($this);          }            return $this;      }        public function removeGraveyard(Graveyard $graveyard): self      {          if ($this->graveyards->removeElement($graveyard)) {              // set the owning side to null (unless already changed)              if ($graveyard->getCity() === $this) {                  $graveyard->setCity(null);              }          }            return $this;      }        /**       * @return Collection|FuneralParlor[]       */      public function getFuneralParlors(): Collection      {          return $this->funeralParlors;      }        public function addFuneralParlor(FuneralParlor $funeralParlor): self      {          if (!$this->funeralParlors->contains($funeralParlor)) {              $this->funeralParlors[] = $funeralParlor;              $funeralParlor->setCity($this);          }            return $this;      }        public function removeFuneralParlor(FuneralParlor $funeralParlor): self      {          if ($this->funeralParlors->removeElement($funeralParlor)) {              // set the owning side to null (unless already changed)              if ($funeralParlor->getCity() === $this) {                  $funeralParlor->setCity(null);              }          }            return $this;      }        /**       * @return Collection|AdvertisementTransfer[]       */      public function getAdvertisementTransfers(): Collection      {          return $this->advertisementTransfers;      }        public function addAdvertisementTransfer(AdvertisementTransfer $advertisementTransfer): self      {          if (!$this->advertisementTransfers->contains($advertisementTransfer)) {              $this->advertisementTransfers[] = $advertisementTransfer;              $advertisementTransfer->setCity($this);          }            return $this;      }        public function removeAdvertisementTransfer(AdvertisementTransfer $advertisementTransfer): self      {          if ($this->advertisementTransfers->removeElement($advertisementTransfer)) {              // set the owning side to null (unless already changed)              if ($advertisementTransfer->getCity() === $this) {                  $advertisementTransfer->setCity(null);              }          }            return $this;      }        /**       * @return Collection|Crematorium[]       */      public function getCrematoria(): Collection      {          return $this->crematoria;      }        public function addCrematorium(Crematorium $crematorium): self      {          if (!$this->crematoria->contains($crematorium)) {              $this->crematoria[] = $crematorium;              $crematorium->setCity($this);          }            return $this;      }        public function removeCrematorium(Crematorium $crematorium): self      {          if ($this->crematoria->removeElement($crematorium)) {              // set the owning side to null (unless already changed)              if ($crematorium->getCity() === $this) {                  $crematorium->setCity(null);              }          }            return $this;      }        public function getCoordinate(): Point      {          return $this->coordinate;      }        public function setCoordinate($coordinate): self      {          $this->coordinate = $coordinate;            return $this;      }        public function toJsonArray(): array      {          $coordinate = $this->getCoordinate();          return [              "id" => $this->getId(),              "name" => $this->getName(),              "country" => $this->getCountry(),              "coordinate" => $coordinate->toJsonArray()          ];      }        public function getProvince(): ?string      {          return $this->province;      }        public function setProvince(?string $province): self      {          $this->province = $province;            return $this;      }  }  

City Repository:

<?php    namespace App\Repository\App;    use App\DBAL\Types\Geolocation\Point;  use App\Entity\App\City;  use App\Exception\City\CityAlreadyExistException;  use Doctrine\Bundle\DoctrineBundle\Repository\ServiceEntityRepository;  use Doctrine\DBAL\FetchMode;  use Doctrine\ORM\AbstractQuery;  use Doctrine\ORM\OptimisticLockException;  use Doctrine\ORM\ORMException;  use Doctrine\ORM\Query\ResultSetMapping;  use Doctrine\Persistence\ManagerRegistry;    /**   * @method City|null find($id, $lockMode = null, $lockVersion = null)   * @method City|null findOneBy(array $criteria, array $orderBy = null)   * @method City[]    findAll()   * @method City[]    findBy(array $criteria, array $orderBy = null, $limit = null, $offset = null)   */  class CityRepository extends ServiceEntityRepository  {      public function __construct(ManagerRegistry $registry)      {          parent::__construct($registry, City::class);      }        /**       * Get all cities on DDBB       * @return int|mixed|string       */      public function getAllCities() {          return $this->createQueryBuilder("c")->where('')->orderBy('name')->getQuery()->getResult();      }        public function getCityById(int $id): City {          return $this->createQueryBuilder('c')->where('id = :id')->setParameter('id', $id)->getQuery()->getResult();      }        public function getCityByName(string $name): ?City      {          $city = $this->createQueryBuilder('c')->where('name = :name')->setParameter('name', $name)->getQuery()->getResult();          return $city === null ? null : $city;      }        /**       * @throws CityAlreadyExistException       */      public function createCity(City $city): ?City      {          try {              $entityManager = $this->getEntityManager();              $entityManager->persist($city);              $entityManager->flush();              return $city;          } catch (ORMException $e) {              throw new CityAlreadyExistException(sprintf("City %s already exist", $city->getName()));          }      }        public function calculateDistance(City $city, $lat, $lon)      {            $SQL = "              SELECT (ST_Distance(ST_MakePoint({$lat}, {$lon})::geography, ST_MakePoint(coordinate[0], coordinate[1])::geography) / 1000) as distance              FROM app.location              WHERE id = {$city->getId()}          ";            return $this->executeSQL($SQL);      }        public function calculateDistanceBetweenPointInKm(Point $origin, Point $destiny)      {          $SQL = "              SELECT (ST_DISTANCE              (                  ST_MakePoint({$origin->getLongitude()}, {$origin->getLatitude()})::geography,                  ST_MakePoint({$destiny->getLongitude()}, {$destiny->getLatitude()})::geography              ) / 1000) as distance          ";            return $this->executeSQL($SQL)[0];      }        private function executeSQL(string $SQL)      {          $em = $this->getEntityManager();          $stmt = $em->getConnection()->prepare($SQL);          $stmt->execute();          return $stmt->fetchAll(FetchMode::COLUMN);      }  }  

Service Entity Repository (This is by default from doctrine and symfony):

class ServiceEntityRepository extends EntityRepository implements ServiceEntityRepositoryInterface  {      /**       * @param string $entityClass The class name of the entity this repository manages       * @psalm-param class-string<T> $entityClass       */      public function __construct(ManagerRegistry $registry, string $entityClass)      {          $manager = $registry->getManagerForClass($entityClass);            if ($manager === null) {              throw new LogicException(sprintf(                  'Could not find the entity manager for class "%s". Check your Doctrine configuration to make sure it is configured to load this entity's metadata.',                  $entityClass              ));          }            parent::__construct($manager, $manager->getClassMetadata($entityClass));      }  }  

My JS Function is not working after the DIV is refreshed by JQUERY

Posted: 19 Oct 2021 08:00 AM PDT

So i wanna make a search bar that searching data with jquery, then after data was found i replace into the 'div' by not refreshing a page. Then when i wipe all character in search bar it will reset the old div. After that my JS function wont work again until i reload the page.

Where is the problem i cant find it out, for the record i am using :

  • JQUERY 3.4.1
  • js.js file
  • search.js file

I am not mixturing js.js with the search.php because js.js containing vanilla js and search.js was jquery file.

Search Bar

<!-- The search menu -->  <form method="GET">      <div class="input-group">          <input type="text" name="search" id="cariProjek" class="form-control search-input" placeholder="Cari projek ...">      </div><br>  </form>  

The div

<div id="reset">  <div id="search">    <table>  <tr>      <td>          <label for="tempFolderPath" class="form-label"><b>Temp Folder Lokasi</b></label>      </td>      <td>:</td>      <td>          <input type="text" class="form-control" name="tempFolderPath" id="tempFolderPath" placeholder="Ini readonly!!!" readonly></label>      </td>  </tr>     <tr>      <td>          <label for="namaFileBaru" class="form-label"><b>Nama File Baru</b></label>      </td>      <td>:</td>      <td>          <input type="text" class="form-control" name="namaFileBaru" id="namaFileBaru" autocomplete="" required>      </td>  </tr>  <tr>      <td>          <label for="namaFileLama" class="form-label"><b>Nama File yang akan Diubah</b></label>      </td>      <td>:</td>      <td>          <input type="file" class="form-control" id="namaFileLama" multiple onchange="showname()" required>      </td>  </tr>  <tr>      <td>          <label for="tempNama" class="form-label"><b>Temp Nama File</b></label>      </td>      <td>:</td>      <td>          <input type="text" class="form-control" name="tempNama" id="tempNama" readonly>      </td>  </tr>  </table>  <button type="button" name="submit" class="btn btn-primary" id="submitForm">Selesai</button><br><br>    <table>      <tr>          <td>              <label for="folderPath" class="form-label"><b>Folder Lokasi Asal</b></label>          </td>          <td>:</td>          <td>              <input type="text" class="form-control" style="width: 300px;" name="folderPath" id="folderPath" autocomplete="" placeholder="Pertama input ini dulu baru Simpan" require>          </td>      </tr>  </table>    <button type="button" name="submitFolderPath" class="btn btn-success" id="submitFolderPath">Simpan</button>  <button type="button" name="resetFolderPath" class="btn btn-danger" id="resetFolderPath">Reset</button>    </div>  

js.js (This code wont work, after the div was reset)

let submitFolderPath = document.getElementById('submitFolderPath');  let resetFolderPath = document.getElementById('resetFolderPath');  let folderPath = document.getElementById('folderPath');  let tempFolderPath = document.getElementById('tempFolderPath');     submitFolderPath.addEventListener('click', function(){    let xhr = new XMLHttpRequest();    xhr.onreadystatechange = function(){      if(xhr.readyState == 4 && xhr.status == 200) {          let date = new Date();          date.setDate(date.getDate() + 1);          const expires = "expires=" + date;          document.cookie = "path=" + folderPath.value + "; " + expires + "; path=/";          tempFolderPath.value = folderPath.value;      }  }    xhr.open('GET', 'index.html', true);  xhr.send();       });      resetFolderPath.addEventListener('click', function(){    let xhr = new XMLHttpRequest();    xhr.onreadystatechange = function(){      if(xhr.readyState == 4 && xhr.status == 200) {          let date = new Date();          date.setDate(date.getDate() - 1);          const expires = "expires=" + date;          let cookie = document.cookie = "path=" + folderPath.value + "; " + expires + "; path=/";          folderPath.value = '';          tempFolderPath.value = folderPath.value;      }  }    xhr.open('GET', 'index.html', true);  xhr.send();    });  

search.js (Pretty sure the problem its here)

$(document).ready(function(){  $('#cariProjek').on('keyup', function(){      if($('#cariProjek').val() == ''){          $("#reset").load(location.href+" #reset>*","")              }else{          $('#search').load('search.html?keyword=' + encodeURIComponent($('#cariProjek').val()));      }  })  });  

search.html

<h1>Test</h1>  

how do I build a text input in react native that has a placeholder that changes to a textview on top when clicked

Posted: 19 Oct 2021 08:00 AM PDT

I am a bit new to react native and I have an issue I need help with

how do I build a text input in react native that has a placeholder that changes to a text view on top when clicked? Similar to the screenshot below

empty text input field looks like this in its default state

empty text field/default state

text field with data entered

filled text input field with text looks like this

see the empty input text has a placeholder appearing in the middle of the input text field

see the second diagram, the place holder text is moved to the top of the input field once the user starts typing text into the input field

Is it possible to check if Blazor ValidationMessageStore has ANY error message

Posted: 19 Oct 2021 08:00 AM PDT

I validate my Blazor form input according to this pattern with ValidationMessageStore:

https://docs.microsoft.com/en-us/aspnet/core/blazor/forms-validation?view=aspnetcore-5.0#basic-validation-1

I then output ValidationMessage on each control.

BUT it is a long form so I also want to indicate to the user somewhere close to the submit button that there are some errors that need to be fixed, and that's why we didn't accept the input yet.

I know I can use a ValidationSummary but I don't want to repeat all possible errors, just have a note.

ValidationMessageStore obviously holds all messages in an internal collection, but they are not accessible. Is it possible to somehow check if there are ANY error messages?

Cypress reuse test cases in multiple test suites

Posted: 19 Oct 2021 08:00 AM PDT

I am new to Cypress and trying out one POC.

The application I am working on requires me to test the same component in different test suites. Is there any why in which I can avoid rewriting the same chunk of code, like using function?

export function testWelcomeBanner() {      ...   welcomeBanner.should('have.text', 'welcome');      ...  }  

I did try some ways, like trying to call this function from it block in test suites etc. but received errors. Any help appreciated.

Next.js API is back-end?

Posted: 19 Oct 2021 08:00 AM PDT

I know Next.js is front-end but when i used API of next.js it can response and can manage route or anything about back-end can do. Then i want to know "Next.js api is back-end ?"

No comments:

Post a Comment