Tuesday, August 3, 2021

Recent Questions - Stack Overflow

Recent Questions - Stack Overflow


NFS Server on Debian 10, VMs unable to mount

Posted: 03 Aug 2021 08:42 AM PDT

I deployed an NFS server and have kvm/qemu VMs running on the same Debian 10 server. On my personal computer I am able to mount the NFS shares, but not on any of the VMs

VM Network Setup:

  • Network source: Host Device macvtap
  • Source Mode: Bridge

Troubleshooting:

  • Able to ping server from VM
  • Verified nfs-common installed on the VMs
  • removed /lib/systemd/system/nfs-common.service(masked, pointed to /dev/null), reloaded daemon, verified service is running
  • showmount -e 10.0.0.200 outputs: clnt_create: RPC: Unable to receive
  • sudo mount -t nfs 10.0.0.200:/export/filesystem /mnt -v outputs: mount.nfs: trying text-based options 'vers=4.2,addr=10.0.0.200,clientaddr=10.0.0.251' mount.nfs: mount(2): No route to host
  • Setting the version to 3 in mount command produces similar output to above

Does anyone have an idea on whats going on?

with multiselect dropdown not able to bind options from javascript/jquery

Posted: 03 Aug 2021 08:42 AM PDT

HTML

Javascript

$('.selectpicker4').multiselect({ includeSelectAllOption: true, enableCaseInsensitiveFiltering: true, allSelectedText: 'All selected', numberDisplayed: 1, nonSelectedText: 'Objects', delimiterText: ', ', enableFiltering: true, });

$('.selectpicker4').multiselect();  

$.ajax({ type: "POST", url: "workorders.aspx/BindObjects", data: JSON.stringify(param), contentType: "application/json; charset=utf-8", dataType: "json", success: function (data1, status) { var ddlObject = JSON.parse(data1.d); var dd = JSON.parse(ddlObject); var equipments = "";

        $.each(dd.ObjectListData, function (index, data) {              equipments += '<option  value="' + data.EquipmentNo + '">' + data.EquipmentNo + " ," + data.EquipmentDetail + '</option>'           data.EquipmentNo).text(data.EquipmentNo));          });          $('#ddlObjects').append(equipments);                                                },      error: function (request, status, error) {          HideLoader();      }  

Now These options are not getting bind and if i remove multielect4 class they will get bind.

DataSetExtensions referenced by Project and using System.Data but extension methods not available

Posted: 03 Aug 2021 08:42 AM PDT

I am trying to run this code in this answer https://stackoverflow.com/a/1430489/2102329 whose call to ToList() relies on the extension methods in the referenced assembly System.Data.DataSetExtensions.dll.

DataTable dtUserAccounts = sp.getDataTable();    List<UserAccount> listOfUserAccounts;    dtUserAccounts.AsEnumerable().Select(m => new UserAccount()  {      UserId = m.Field<string>("UserId"),      FirstName = m.Field<string>("FirstName"),      LastName = m.Field<string>("LastName")        }).   //<-- ToList() is not available  

I have reviewed similar cases on StackOverflow but cannot get this to work. I am using Visual Studio 2017 but the original project will have been created in an earlier version.

The code is in a public method of a public class in the project's default namespace. I have the correct using statement for System.Data already. The project targets .NET 4.7.1.

The extension methods are not available. In References there are both System.Data and System.Data.DataSetExtensions (I have removed and added these back in to be sure).

I have tried cleaning the solution and rebuilding.

I have even created an additional project in the same VS 2017 solution targeting the same .NET version and this actually works so this is my fudge of a workaround but I must be missing something here.

Rock, paper, scissors command discord.js problem

Posted: 03 Aug 2021 08:42 AM PDT

I'm trying to code an rps command, but it doesn't quite work yet. This is my code so far:

else if(parts[0].toLocaleLowerCase() == 'r/rps') {            const embed = new Discord.MessageEmbed()          .setColor('800000')          .setAuthor(message.author.tag, message.author.displayAvatarURL({dynamic: true}))          .setTitle('Schere, Stein, Papier')          .setDescription('Reagiere um zu spielen')          .setTimestamp()          .setFooter('Version 1.19');            let msg = await message.channel.send(embed)          await msg.react('⛰️')          await msg.react('📄')          await msg.react('✂️')            const filter = (reaction, user) => {              return ['⛰️', '📄', '✂️'].includes(reaction.emoji.name) && user.id === message.author.id;          }            const choices = ['⛰️', '📄', '✂️']          const me = choices[Math.floor(Math.random() * choices.length)]          msg.awaitReactions(filter, {max: 1, time: 60000, error: ['time']}).then(              async(collected) => {                  const reaction = collected.first()                  const resultEmbed = new Discord.MessageEmbed()                  .setColor('800000')                  .setAuthor(message.author.tag, message.author.displayAvatarURL({dynamic: true}))                  .setTitle('Ergebnis')                  .addField('Deine Auswahl:', `${reaction.emoji.name}`)                  .addField('Bots Auswahl:', `${me}`)                  .setFooter('Version 1.19')                  .setTimestamp();                  await msg.edit(resultEmbed)                    if((me === '⛰️' && reaction.emoji.name === '✂️') ||                   (me === '✂️' && reaction.emoji.name === '📄') ||                   (me === '📄' && reaction.emoji.name === '⛰️')) {                      message.reply('Du hast verloren');                  } else if(me === reaction.emoji.name) {                      return message.reply('Es ist ein Unentschieden');                  } else {                      return message.reply('Du hast gewonnen');                  }              })              .catch(collected => {                  message.reply('Spiel ist gescheitert, du hast zu lange gebraucht um zu antworten')              })      }  

The problem is that there is always ".catch(collected => { message.reply('Spiel ist gescheitert, du hast zu lange gebraucht um zu antworten') })" is given as the answer

How can I use animation with Visibility widget when its invisible?

Posted: 03 Aug 2021 08:41 AM PDT

Currently, I am using a Positioned widget with Visibility that has a container in it. It sorta works like a splash screen, when I make it invisible I would like to add some animation to it like fade out etc, One option is to use AnimatedOpacity but I am worried that the state will be persistent while Visibility can make can dispose of the state with maintainState:False Hence I would like to know if there is a way to animate it ?

Positioned(              top: 0,              left: 0,              right: 0,              child: Visibility(                visible: splash,                maintainState: false,                maintainAnimation: false,                maintainSize: false,                maintainInteractivity: false,                child: Container(                  color: Colors.white,                  height: MediaQuery.of(context).size.height,                  width: MediaQuery.of(context).size.width,                  alignment: Alignment.center,                  child: Column(                    crossAxisAlignment: CrossAxisAlignment.center,                    mainAxisAlignment: MainAxisAlignment.center,                    children: [                      SizedBox(                          height: 300,                          width: 300,                          child: Lottie.asset('assets/delivery.json')),                      SizedBox(height: 20),                      Text(                        "Loading",                        style:                            TextStyle(fontSize: 25, fontWeight: FontWeight.bold),                      ),                    ],                  ),                ),              ),            )  

How to get the good path in mongodb to catch my picture on my firebase storage with multer?

Posted: 03 Aug 2021 08:41 AM PDT

I'm struggling to record the path of my storage (firebase) on my bdd Mongodb.

My bdd is with mongo db and i have to record the path on the picture on.

The picture is recording on my firebase storage, but the path is not the good one on mongoDB.

Also my route on my back end

getLogo: (req, res, next) => {      const filePath = firebase.bucket.file(req.file.filename);        Serveur.updateOne(        { _id: req.user._id },        {          $set: {            picture: filePath,          },        },          (err) => {          [...]  

When i tryed to put my file path with my bucket they asked me a "string" so for the moment i put a local storage

onst multer = require("multer");  const { bucket } = require("../firebase");  const MIME_TYPES = {    "image/jpg": "jpg",    "image/jpeg": "jpg",    "image/png": "png",  };    /**   * création d'objet de configuration de multer   */  const storage = multer.diskStorage({    destination: (req, file, callback) => {      //destination pour explique ou enregistrer les fichiers      callback(        null,        "gs://tipourboire-57c09.appspot.com/PictureServeur/" + bucket.name      ); // null pour dire qu'il n ya pas eu d'erreurs    },    filename: (req, file, callback) => {      const name = file.originalname;      const extension = MIME_TYPES[file.mimetype];      callback(null, name + Date.now() + "." + extension);    },  });    module.exports = multer({ storage: storage }).single("file");  

My picture is on my firebase stoage but i can't get it from my mongo bdd

Issue in rendering Swagger OpenAPI v3 UI + Springboot project

Posted: 03 Aug 2021 08:41 AM PDT

I am getting the error - "Please indicate a valid Swagger or OpenAPI version field. Supported version fields are swagger: "2.0" and those that match openapi: 3.0.n (for example, openapi: 3.0.0)." when I paste the generated json from /api-docs to editor.swagger.io. I have some observations.

  1. localhost:8080/v3/api-docs/ yields - "{\"openapi\":\"3.0.1\", "\info\":{ ---------------- This json gives the mentioned error in editor.swagger.io.

  2. On manually removing the initial double quotes and escape character i.e. {"openapi":"3.0.1", "info":{ ---------------- the error goes away i.e. UI is rendered without any issue.

  3. My project springboot version is 2.2.13.RELEASE, springdoc-openapi-ui version is 1.5.8, jackson-databind version is 2.10.5.1

Please let me know if any further information is required from my end. Any inputs regarding the issue will be helpful. Thank you.

Why do I receive a security origin error when downloading a file from Firebase storage with CORS enabled?

Posted: 03 Aug 2021 08:41 AM PDT

I have a website linked to firebase storage. I want the user to be able to download a file (stored in firebase storage) on his computer when clicking on a download button.

The issue -> I receive this error message in the console "The download attribute on anchor was ignored because its href URL has a different security origin."

CORS is set up through gsutil command following this configuration -> https://firebase.google.com/docs/storage/web/download-files

[    {      "origin": ["*"],      "method": ["GET"],      "maxAgeSeconds": 3600    }  ]  

My function to download the file :

function forceFileDownload(url) {    // This can be downloaded directly:      var xhr = new XMLHttpRequest();      xhr.responseType = 'blob';      xhr.onload = (event) => {        var blob = xhr.response;      };      xhr.open('GET', url);      xhr.send();  }  

Which is called here :

targetDoc.get().then((doc) => {            imgRef.getDownloadURL().then(function(url){                              let li = document.createElement("li");                let a = document.createElement('a');                  a.appendChild(document.createTextNode("Download"));                a.setAttribute('id', url);                a.setAttribute("onclick","forceFileDownload(this.id)");                             li.appendChild(a);                 });                   })  

When I click on the download button the image appears in another tab.

I think the issue might come from my function and not from the CORS configuration (I've tried dozen of CORS configurations with the same result).

At some point it was working in Chrome but not anymore (I don't know how), and it never worked in Safari.

Thanks for your help.

[My post has been associated with similar questions, however it didn't resolve my issue so I am posting it again.]

Problem with lstrip and backslash in python

Posted: 03 Aug 2021 08:41 AM PDT

I know there is already many ressources about the problem of backslash in python, I read many of these but none help me.

I'm working on large data set with Pandas.

I'm creating a loop to iterate over multiple csv files in a windows folder. Then it proceed to several data manipulation. Then I want to save each different input csv in different output csv.

In itself, it works, but I want to have clean name after the export/save. And i'm not able to do this.

Complete name are "C:\blabla blabla\data number1\Id 1\Csv\01 - Decembre\12-xx-14_processed_1.csv"

xx = multiple day of the month

Here's the code :

    for files in folder :              df = pd.read_csv(files, sep=';', low_memory=False, index_col=None)              file_name = str(files)              file_name = file_name.lstrip(r'C:\blabla blabla\data number1\Id 1\Csv\01 - Decembre\\')              file_name = file_name.rstrip('_processed_1.csv')  

I want to have only "12-xx-14.csv" in the end

So I did the following :

df.to_csv(r'C:\blabla blabla\data number1\Reprocessed CSV\December'+str(file_name)+'.csv',index=False)  

Saving it in another folder for the project management.

I should have "12-xx-14.csv" as an output.. but I have "2-xx-14.csv" ! My first "1" is going into the bin and I really don't know why ?? I guess it's related to the backslash character.. But if i'm deleting the last two backslash, the name become "01 - December\12-xx-14". I can't even manage to suppress "01 - Decembe" without the last "r", it won't work.

I'm currently upgrading to python 3.9 to test suffix/prefix, but in the mean time i'm stuck with this.

Thank you !

Send ref via props in functional component

Posted: 03 Aug 2021 08:41 AM PDT

In my parent component I call hook useRef: const flatListRef = useRef(null); and then I want to use this flatListRef in child component. I tried to do like in documentation but without success. When I call my function toTop I get: null is not an object (evaluating 'flatListRef.current.scrollToOffset')

This is my parent component:

const BeautifulPlacesCards = ({navigation}: HomeNavigationProps<"BeautifulPlacesCards">) => {      const flatListRef = useRef(null);      const toTop = () => {          flatListRef.current.scrollToOffset(1)      }      const buttonPressed = () => {       toTop()      }      return(             <Carousel filteredData={filteredData} flatListRef={flatListRef}/>      )  }  

This is my child component:

const Carousel = forwardRef((filteredData, flatListRef) => {   return (           <AnimatedFlatList                     ref={flatListRef}           />   )  }    

Caching or retrying + switching between API calls if one is down

Posted: 03 Aug 2021 08:40 AM PDT

I am attempting to scope a problem where I have two identical external services that can be called from a user GET request to an API. Lately, I have noticed that the primary external service that I would rather hit has been going down randomly. So, I would like to develop this API to try and call the first service and if it's down call the other external service. If this first service is down, any subsequent requests would go to the second external service and the first service would only be retried after a certain period of time.

Here's a psuedocode example of what I'm trying to accomplish:

user GET request to api:      try to call external_api1:           if external_api1 is up:              return external_api1 response          else:              try to call external_api2:                   if external_api2 is up:                      return external_api2 response                  else:                      return error to user                subsequent user requests go to external_api2          external_api1 is retried after a certain amount of time       

I am unsure of the appropriate strategy to handle the last two lines in particular, where requests are routed to the second service and the first service is retried after a certain amount of time. I wonder if this is a background service checking to see if the first service is up continuously or if there is a caching strategy here. I would appreciate any advice on a possible path forward.

How to use asyncio.wait_for to run_until_complete to synchronously call async method in Python

Posted: 03 Aug 2021 08:40 AM PDT

To allow timeouts receiving data via Python websocket, the FAQ: How do I set a timeout on recv()? recommends using asynchronously receive data:

await asyncio.wait_for(websocket.recv(), timeout=10)  

Since the function I receive data is not async, I've adapted this answer to run the asyncio loop until data was received or the timeout occurred:

loop.run_until_complete(asyncio.wait_for(ws.recv(), timeout=10))  

Unfortunately this statement seems to be not valid, since the following exception occurs:

An asyncio.Future, a coroutine or an awaitable is required

For me, it looks like asyncio.wait_for is no valid parameter for the run_until_complete although the documentation clearly shows an example which awaits for it.

What am I missing here - and what would be the correct way to use asyncio.wait_for in a synchronous method?

Live Server Bug and Issue

Posted: 03 Aug 2021 08:41 AM PDT

I have installed Live Server in my VS Code but the problem is that When i try to run it just says port : 5500 and connects but it doesn't open the browser I have re-installed may times and restarted my computer, VS Code but still not working.. What to do?

why grep '\s*' is not working, but grep '\S*' works

Posted: 03 Aug 2021 08:42 AM PDT

I am new to shell script. I want to display the line starts with whitespace or non-whitespace in the file, but grep '\S*' works, grep '\s*' does not match any line. And '\s' looks works Anyone can help? Thanks

test.fa includes

ctatccagcaccagatagcatcattttactttcaagcctagaaattgcac   haha        ok  acttgtatataaaccaaccgaagatgaggattgagagttcatcttggtgg  

running result

Clarification regarding Bin.asNull vs real null value vs thombstone

Posted: 03 Aug 2021 08:41 AM PDT

I'm looking for some clarification regarding what happening and how it affects the inter and between cluster replication between the following operations:

 def test() = {      val key = new Key("ns", Configuration.dummySetName, 2)      client.put(null, key, new Bin("bin0", Value.NULL)) // Is that Thombstone? All Row Will be deleted?      client.put(null, key, new Bin("bin2", "value1")) // set bin2 value to be value1      client.put(null, key, Bin.asNull("bin2")) // Is that deleted on the commit? any zombie records can be with value1? is it shipped via XDR? is durableDelete change something?      val record = client.get(null, key)      println(record)    }  

Thanks!

Need to convert a string "4AAC6AA8D5827BA" to into this format "4a:ac:6a:a8:d5:82:7b" using groovy

Posted: 03 Aug 2021 08:42 AM PDT

I am trying to convert this string string "4AAC6AA8D5827BA" to into this format "4a:ac:6a:a8:d5:82:7b" using groovy. Could you please asssit

How to increase propability of a certain number for random() in Java?

Posted: 03 Aug 2021 08:42 AM PDT

First of all, the method I am currently using for picking up a random number within a range of 1-45 is:

public int getRandomNumber(int min, int max) {      return (int) ((Math.random() * (max - min)) + min);  }  

What I want to do is, suppose that there are six numbers in an array of int

int[] numbers = [2, 4, 6, 8, 10, 12];  

and I want to increase the probability (about 20% to 30%) for picking that numbers in the array from a randomly generated number in a range of 1 ~ 45.

Is there any way to solve this problem?

Thanks.

How to Set Value in React Material UI Fields

Posted: 03 Aug 2021 08:41 AM PDT

I have a message field that I need to type on. before that I have variable dropdown that I need to APPEND to the message How do i make the {{ variables }} only not editable in the message TextField?

CODESANDBOX

            <Autocomplete                value={values.variable}                options={variables}                getOptionSelected={(option, value) => option === value}                getOptionLabel={(data) => data}                onChange={(e, value) => {                  setFieldValue("variable", value);                  setFieldValue("message", `${values.message} ${value}`);                }}                fullWidth                renderInput={(params) => (                  <TextField                    {...params}                    name="variable"                    size="small"                    variant="outlined"                    onBlur={handleBlur}                    helperText={touched.variable ? errors.variable : ""}                    error={touched.variable && Boolean(errors.variable)}                  />                )}              />  

How to use IF in a CASE statement

Posted: 03 Aug 2021 08:41 AM PDT

I typed the code to substitute WALMART_FLAG as a CASE statement but for some reason the server doesn't accept it.

Picture of the error

The code

SELECT s.DEAGY AS 'AGENCY', l.cmschn AS 'MASTER_CHAIN', s.DECHN AS 'CHAIN', s.DESTR AS 'STORE NUMBER', s.DEWEDT AS 'WK_ENDING',  (CASE  WHEN s.DEIO='O' AND s.DEAGY=10 AND s.DECHN IN (WC,WM) THEN 'Y' ELSE 'N' END)='Y' THEN (SELECT -1 * s.DEQTY) ELSE 0  END AS RET_UNITS    FROM LEVYDTA.SMPRTNM s  JOIN LEVYDTA.LDSCHNM l  ON s.DEAGY=l.CMAGY and s.DECHN=l.CMCHN;  

Django runserver isn't updating after .py file changes

Posted: 03 Aug 2021 08:41 AM PDT

I am learning django and using manage.py runserver for a live server. When I make changes to html and css files in my project, I only have to refresh the web page to see the changes, but when I make changes to the .py files (views.py or urls.py for example) I have to stop and restart the live server manually before refreshing the web page to see the changes. Is there a setting that I can change to avoid this manual reset?

I am using visual studio code in windows and the actual command I'm using is:

python manage.py runserver  

I've added the project to github if anyone wants to have a look: myproject link

It is a runthrough of this tutorial: Python Backend Web Development

How do I decrypt the text which is already encrypted in the past using Java AES 256 Decryption?

Posted: 03 Aug 2021 08:41 AM PDT

I'm fresh bee for writing Java AES GCM encryption and decryption.

I have the need to encrypt the given password using Java AES GCM and stored in config file. Then, decrypt them later and get the same password to get the security clearance.

Using the below program from the link

It perfectly works for encryption and decryption if we use the same SecretKey at the same time.

But, I wanted to do encryption very first time and decryption later as many time should yield the same text got encrypted.

Can you please help to get the program works for the decryption for later time?

package com.javainterviewpoint;    import java.security.SecureRandom;  import java.util.Base64;  import javax.crypto.Cipher;  import javax.crypto.KeyGenerator;  import javax.crypto.SecretKey;  import javax.crypto.spec.GCMParameterSpec;  import javax.crypto.spec.SecretKeySpec;    public class AES_GCM_Example  {      static String plainText = "This is a plain text which need to be encrypted by Java AES 256 GCM Encryption Algorithm";      public static final int AES_KEY_SIZE = 256;      public static final int GCM_IV_LENGTH = 12;      public static final int GCM_TAG_LENGTH = 16;        public static void main(String[] args) throws Exception      {          KeyGenerator keyGenerator = KeyGenerator.getInstance("AES");          keyGenerator.init(AES_KEY_SIZE);                   // Generate Key          SecretKey key = keyGenerator.generateKey();          byte[] IV = new byte[GCM_IV_LENGTH];          SecureRandom random = new SecureRandom();          random.nextBytes(IV);            System.out.println("Original Text : " + plainText);                    byte[] cipherText = encrypt(plainText.getBytes(), key, IV);          System.out.println("Encrypted Text : " + Base64.getEncoder().encodeToString(cipherText));                    String decryptedText = decrypt(cipherText, key, IV);          System.out.println("DeCrypted Text : " + decryptedText);      }        public static byte[] encrypt(byte[] plaintext, SecretKey key, byte[] IV) throws Exception      {          // Get Cipher Instance          Cipher cipher = Cipher.getInstance("AES/GCM/NoPadding");                    // Create SecretKeySpec          SecretKeySpec keySpec = new SecretKeySpec(key.getEncoded(), "AES");                    // Create GCMParameterSpec          GCMParameterSpec gcmParameterSpec = new GCMParameterSpec(GCM_TAG_LENGTH * 8, IV);                    // Initialize Cipher for ENCRYPT_MODE          cipher.init(Cipher.ENCRYPT_MODE, keySpec, gcmParameterSpec);                    // Perform Encryption          byte[] cipherText = cipher.doFinal(plaintext);                    return cipherText;      }        public static String decrypt(byte[] cipherText, SecretKey key, byte[] IV) throws Exception      {          // Get Cipher Instance          Cipher cipher = Cipher.getInstance("AES/GCM/NoPadding");                    // Create SecretKeySpec          SecretKeySpec keySpec = new SecretKeySpec(key.getEncoded(), "AES");                    // Create GCMParameterSpec          GCMParameterSpec gcmParameterSpec = new GCMParameterSpec(GCM_TAG_LENGTH * 8, IV);                    // Initialize Cipher for DECRYPT_MODE          cipher.init(Cipher.DECRYPT_MODE, keySpec, gcmParameterSpec);                    // Perform Decryption          byte[] decryptedText = cipher.doFinal(cipherText);                    return new String(decryptedText);      }  }  

If 2 columns of data have the same values in the row above it, then add 0.00001 to it

Posted: 03 Aug 2021 08:42 AM PDT

I have a data frame that contains a column for Latitude and a column for Longitude that looks like this

test <- data.frame("Latitude" = c(45.14565, 45.14565, 45.14565, 45.14565, 33.2222,   31.22122, 31.22122), "Longitutde" = c(-105.6666, -105.6666, -105.6666, -104.3333,   -104.3333, -105.77777, -105.77777))  

I would like to make every value go out to 5 decimal places and also check to see that if a latitude and longitude pair are the same as the pair above it, to add 0.00001 to both the latitude and the longitude value. So my data would change to this:

test_updated <- data.frame("Latitude" = c(45.14565, 45.14566, 45.14567, 45.14565,   33.22220, 31.22122, 31.22123), "Longitude" = c(-105.66660, -105.66661, -105.66662,   -104.33330, -104.33330, -105.77777, -105.77778))  

Symfony 5 - Form - Choice value

Posted: 03 Aug 2021 08:41 AM PDT

I want to make a form with a select field which displays different options. Those options are a list of NomenclatureDTO object field ($libNom) set as:

class NomenclatureDTO  {      public int $idNom;      public string $libNom;      public string $dtMiseEnPlace;      public string $dtObsolescence;  }  

I want to display libNom in the select options, but I only need the idNom on submit.

So, my form looks like:

<?php    namespace App\Form;    use App\Entity\DTO\AvisDTO;  use App\Entity\DTO\DataFormMapper\DataAvisType;  use App\Entity\DTO\NomenclatureDTO;  use Symfony\Component\Form\AbstractType;  use Symfony\Component\Form\ChoiceList\ChoiceList;  use Symfony\Component\Form\Extension\Core\Type\ChoiceType;  use Symfony\Component\Form\Extension\Core\Type\SubmitType;  use Symfony\Component\Form\Extension\Core\Type\TextareaType;  use Symfony\Component\Form\Extension\Core\Type\TextType;  use Symfony\Component\Form\FormBuilderInterface;  use Symfony\Component\OptionsResolver\OptionsResolver;    class AvisType extends AbstractType  {      public function buildForm(FormBuilderInterface $builder, array $options)      {          // dd($options['dataPostAvis']->nomNatureAvisRendu);      L21: SCREENSHOT          $builder              ->add('nomAuteur', TextType::class, [                  'label' => "Nom",              ])              ->add('prenomAuteur', TextType::class, [                  'label' => "Prénom"              ])              ->add('boEstTacite', ChoiceType::class, [                  'required' => true,                  'label' => "L'avis est-il tacite ?",                  'label_attr' => [                      'class' => "font-weight-bold"                  ],                  'expanded' => true,                  'multiple' => false,                  'choices' => [                           'Oui' => true,                      'Non' => false,                                       ],                                    ])                        ->add('nomNatureAvisRendu', ChoiceType::class, [                  'label' => "Nature de l'avis rendu",                  'required' => false,                                  'choices' => $options['dataPostAvis']->nomNatureAvisRendu,                  'choice_label' => function(?NomenclatureDTO $choice) {                                          return $choice->libNom;                  },                  'choice_value' => function(?NomenclatureDTO $choice) {                        // dd($choice);                               L50: SCREENSHOT                      return $choice->idNom;                  },              ])              ->add('nomTypeAvis', ChoiceType::class, [                  'label' => "Type d'avis",                  'required' => false,                  'choices' => $options['dataPostAvis']->nomTypeAvis,                  'choice_label' => function($choice) {                                         return $choice->libNom;                  },                                                'choice_value' => ChoiceList::value($this, 'idNom'),              ])              ->add('txAvis', TextareaType::class, [                  'required' => true,                  'attr' => [                      'placeholder' => "Avis favorable avec prescriptions. \nPremière prescription : Les volets doivent être en bois"                  ]              ])              ->add('txFondementAvis', TextareaType::class, [                  'attr' => [                      'placeholder' => "L'avis de l'ABF est rendu en application de l'article R. 425-30 du Code de l'urbanisme."                  ]              ])              ->add('txHypotheses', TextareaType::class, [                  'attr' => [                      'placeholder' => "Dans l'hypothèse où la puissance électrique nécessaire est de x alors le coût de raccordement est de y"                  ]              ])              ->add('txQualiteAuteur', TextareaType::class, [                  'attr' => [                      'placeholder' => "Qualité"                  ]              ])                ->add('Envoyer', SubmitType::class, [                  'row_attr' => [                      'class' => 'row justify-content-end'                  ],              ]);      }        public function configureOptions(OptionsResolver $resolver): void      {          $resolver->setDefaults([              'data_class' => AvisDTO::class,              'dataPostAvis' => DataAvisType::class,                    ]);      }  }  

Screenshot L21:

Screenshot L21

Screenshot L50:

Screenshot L50

I get this error before the page actually show the form:

Notice: Trying to get property 'idNom' of non-object

Which makes no sense to me since the dump L51 explicitly says $choice is a NomenclatureDTO object...

Passing parameters to redirect_to

Posted: 03 Aug 2021 08:41 AM PDT

I have a controller to register a new employee on the system, and in this controller I need a verification to ensure that both the inserted email and the CPF (brazilian document) are unique and not yet registered. I'm trying to use redirect_to to return to the form:

def create      @model = Employee.new(employee_params)      @model.cpf_plain = employee_params[:cpf].gsub('-', '').gsub('.', '')      @model.activated = true      if Employee.where(email: @model.email).first.present? || Employee.where(cpf_plain: @model.cpf_plain).present?        redirect_to new_employee_url(employee: employee_params), notice: 'Já existe um Otto com este email ou CPF'        return      end        if @model.save        @model.generateTempPass        redirect_to employees_url, notice: 'Otto criado com sucesso.'      else        redirect_to new_employee_url(employee: employee_params),                    notice: 'Não foi possível salvar este Otto no momento, tente novamente mais tarde.'      end  end  

But I can't figure out how to return to the form keeping the already filled fields. I've tried using render instead of return_to:

if Employee.where(email: @model.email).first.present? || Employee.where(cpf_plain: @model.cpf_plain).present?        render create, notice: 'Já existe um Otto com este email ou CPF'        return  end  

But for some reason I enter in a infinite loop where the controller keep doing the verification of email and CPF over and over again.

Replacing value in list based on input and dictionary ;-;

Posted: 03 Aug 2021 08:41 AM PDT

I need to print out a 4x4 table that's labeled ( A B C D ) horizontally and 1234 vertically and ask the user to place a randomly generated number in the table (eg. A1, B2)

num = randomly generated number    table = [ [' ', ' ', ' ', ' '],\              [' ', ' ', ' ', ' '],\              [' ', ' ', ' ', ' '],\              [' ', ' ', ' ', ' ']]  ans = input('where would you like to place it?')  

I used a dictionary to assign A1 : table[0][0] and so on Tried to replace the value with:

if ans in dictionary:      table.replace(dictionary.get(ans),num)           

It's not working for me but I only understand how to do it this way.

How can I implement vertical scroll snapping with `IntersectionObserver`?

Posted: 03 Aug 2021 08:41 AM PDT

I am inspired by Rolls Royce website and want to implement the same scroll snapping feature in mine as well, I did it with the HTML default scroll-snap-type which gives me expected behavior but creates two scrollbars, one for the container and another one for the body, which is not expected so I tried to go with the IntersectionObserver but it causes an issue, I can travel to only adjacent slide when directly jumping from 1st slide to 3rd slide.

Here is the code sandbox link: https://codesandbox.io/s/scrollsnap-forked-pre0c?file=/pages/index.vue

Here is the code that I am working

<template>    <main class="landing">      <nav class="scroller">        <ul class="scroller__list">          <li            class="scroller__item"            v-for="(slide, index) in slides"            :key="index"            @click.prevent="scroll(slide.id)"          >            <a              class="scroller__dot"              :href="'#' + slide.id"              @click.prevent="scroll(slide.id)"            ></a>          </li>        </ul>      </nav>      <div class="slides-container">        <slide          class="slide"          v-for="(slide, index) in slides"          :key="index"          :img="slide.img"          :id="slide.id"          :format="slide.format"          :filter="slide.filter"          >{{ slide.content }}</slide        >      </div>    </main>  </template>    <script lang="ts">  import Vue from "vue";    export default Vue.extend({    data() {      return {        slides: [          {            img: "car-slide-1.png",            content: "hello world",            id: "car-slide-1",            filter: "color-burn",          },          {            img: "car-slide-2.png",            // promo-video.mp4            content: "Second Car",            id: "car-slide-2",            filter: "color-burn",            // format: "video",          },          {            img: "car-slide-3.png",            content: "Third slide",            id: "car-slide-3",            filter: "color-burn",          },        ],        observer: null as any as IntersectionObserver,        options: {          threshold: [0.5],          root: process.browser            ? document.getElementsByClassName("slides-container")[0]            : null,        } as IntersectionObserverInit,      };    },    methods: {      scroll(id: string, who: string | null = null) {        console.log("scrolling to ", id, who ? "by " + who : "");        document.getElementById(id)?.scrollIntoView({          behavior: "smooth",          block: "start",        });      },    },    mounted() {      let scrolling = false;      this.observer = new IntersectionObserver((entries, observer) => {        entries.forEach((entry) => {          if (entry.isIntersecting && !scrolling) {            let top = entry.boundingClientRect.top;            scrolling = true;            window.scroll({ behavior: "smooth", top: window.pageYOffset + top });          }          scrolling = false;        });      }, this.options);      document        .querySelectorAll(".slide")        .forEach((slide) => this.observer.observe(slide));    },  });  </script>  

How to make props stateful/ how to get updated props from root config to child apps in single spa react?

Posted: 03 Aug 2021 08:41 AM PDT

I have a single spa application where I am using 3 child apps (each being a micro-frontend). For 1 child app, I am mounting onto the root html and setting in always active status. For the rest 2, basing on the routes, will mount/un-mount themselves onto the root html. For the child that is always active, I am passing the current path as prop from the root so that basing on the path, components within that child should render (conditional rendering). The issue I am facing is, child is able to receive the prop from the root but when the path changes, the new path is not getting reflected into the child and I have to reload the page manually in-order to conditional render those components within that child app. So, here are the root-config.js files and child.js files.

**root-config.js**    import { registerApplication, start } from "single-spa";  registerApplication({    name: "@mrc/app1",    app: () => System.import("@mrc/app1"),    activeWhen: ["/app1", (location) => location.pathname.startsWith("/app1")],  });    registerApplication({    name: "@mrc/app2",    app: () => System.import("@mrc/app2"),    activeWhen: ["/app2", (location) => location.pathname.startsWith("/app2")],  });    registerApplication({    name: "@mrc/app3",    app: () => System.import("@mrc/app3"),    activeWhen: ["/"],    customProps: {      currentPath: window.location.pathname,    },  });    start();  
**app3.js**    import React from "react";  import Header from "./components/Header/Header";  import LeftPane from "./components/LeftPane/LeftPane";  import NavBody from "./components/NavBody/NavBody";    const App = ({ currentPath }) => {    return (      <>        <Header />        {typeof window !== "undefined" && currentpath !== "/" ? (          <LeftPane />        ) : null}        {typeof window !== "undefined" && currentPath === "/" ? (          <NavBody />        ) : null}      </>    );  };    export default App;  

The goal is LeftPane component from app3 should not be rendered only for path="/" and NavBody should be rendered only for path="/". How can I achieve this?

Service worker registration failed. Chrome extension

Posted: 03 Aug 2021 08:41 AM PDT

I don't understand how to migrate from manifest v2 to v3 in part of Service Worker. Occurs error Service worker registration failed

// manifest.json  "background": {      "service_worker": "/script/background/background.js"  },  
// background.js  chrome.runtime.onInstalled.addListener(onInstalled);  

enter image description here

Timber: archive-post_type.php not firing; equivalent in non-Timber themes works

Posted: 03 Aug 2021 08:41 AM PDT

Using Timber, I'm trying to render a custom archive page for my custom post type. CPT is person, and I'm simply trying to render archive-person.php when visiting "mysite.com/person". No matter what I do, all I get is the output of archive.php, never archive-person.php.

Yes, I have been hitting 'Save' on permalinks as many people suggest.

As a test, using WP's 2020 base theme, I made an equivalent archive-post_type.php in the classic WordPress way, and everything works fine. This is indicating my cpt's and permalinks are ok, and the issue perhaps has to do with my Timber-based theme specifically.

I've tried changing my CPT name properties to make sure I'm not creating permalink conflicts.

Timber views/partials, pages, singles and single-post_type.php are all rendering fine.

Other than tinkering with archive*.php pages, what's the first thing I should be looking at? Within functions.php Timber initialization, anything major that would specifically affect archives only?

UPDATE: In writing this post I see what could be an issue. Do I have to register my CPTs and taxonomies explicitly through Timber init, for it to be fully aware of them?

archive.php (very similar to one from Timber starter theme)

<?php    use Timber\Timber;    global $paged;    if ( ! isset( $paged ) || ! $paged ) {      $paged = 1;  }    $templates = array( 'pages/archive.twig', 'pages/index.twig' );    $context = Timber::context();  $context['title'] = 'Archive';  if ( is_day() ) {      $context['title'] = 'Archive: ' . get_the_date( 'D M Y' );  } elseif ( is_month() ) {      $context['title'] = 'Archive: ' . get_the_date( 'M Y' );  } elseif ( is_year() ) {      $context['title'] = 'Archive: ' . get_the_date( 'Y' );  } elseif ( is_tag() ) {      $context['title'] = single_tag_title( '', false );  } elseif ( is_category() ) {      $context['title'] = single_cat_title( '', false );      array_unshift( $templates, 'archive-' . get_query_var( 'cat' ) . '.twig' );  } elseif ( is_post_type_archive() ) {      $context['title'] = post_type_archive_title( '', false );      array_unshift( $templates, 'archive-' . get_post_type() . '.twig' );  }    // Grabs everything on the site, regular posts and CPT's.  $context['posts'] = new \Timber\PostQuery();        // Just for testing, to check if "person" posts can at least be rendered via archive.php. They do.      //$args    = ['post_type' => 'person'];      //$context['posts'] = new \Timber\PostQuery($args);    Timber::render( $templates, $context );    ?>  

archive-person.php Just a pared-down version of archive.php, with 'person' forced as post_type (as opposed to grabbing all posts):

use Timber\Timber;    global $paged;    if ( ! isset( $paged ) || ! $paged ) {      $paged = 1;  }    $templates = array( 'pages/archive-person.twig' );    $context = Timber::context();  $context['title'] = 'Archive: Person';    $args    = [      'posts_per_page' => 10,      'paged'          => $paged,      'post_type' => 'person',  ];    $context['posts'] = new \Timber\PostQuery($args);    Timber::render( $templates, $context );  

functions.php

class mySite extends Timber\Site {      public function __construct() {          add_theme_support( 'post-thumbnails' );          add_theme_support( 'menus' );             add_filter( 'timber_context', array( $this, 'add_to_context' ) );          parent::__construct();      }        function add_to_context( $context ) {          $context['menu'] = new \Timber\Menu('main-menu');          $context['site'] = $this;            return $context;      }  }    new mySite();    function create_posttypes() {          register_post_type( 'person',              array(                  'labels' => array(                      'name' => __( 'Persons' ),                      'singular_name' => __( 'Person' )                  ),                  'public' => true,                  'has_archive' => true,                  'show_in_rest' => true,                  'supports' => array( 'title', 'editor', 'author', 'thumbnail', 'excerpt', 'trackbacks', 'custom-fields', 'comments', 'revisions', 'page-attributes' )              )          );    }    add_action( 'init', 'create_posttypes' );  

No comments:

Post a Comment