Wednesday, June 2, 2021

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

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

Recent Questions - Stack Overflow



In the 06/02/2021 edition:

Unable to get Json output from survey js in my react app

By Ekagra Sinha on Jun 02, 2021 04:01 am

I am implementing survey-react in my react app with:

import React, {Component} from 'react';  import "survey-react/survey.css";  import * as Survey from 'survey-react';    class App extends Component {    constructor(props){      super(props);      this.state ={        }      this.onCompleteComponent = this.onCompleteComponent.bind(this)    }      onCompleteComponent = () =>{      this.setState({        isCompleted: true      })    }      render() {      Survey      .StylesManager      .applyTheme("");        var json = {        "title": "Simple Survey",        "logoWidth": 60,        "logoHeight": 60,        "questions": [          {            "type": "dropdown",            "name": "person",            "title": "Choice",            "hasOther": true,            "isRequired": true,            "choices": ["A","B","C"]        },            {                "name": "name",                "type": "text",                "title": "Your name:",                "isRequired": true            },              {                "name": "I accept terms",                "type": "checkbox",                "isRequired": true,                "choices": ["YES"]            }        ]    };     var model = new Survey.Model(json);      var surveyRender = !this.state.isCompleted ?(      <Survey.Survey        model={model}        showCompletedPage ={false}        onComplete = {this.onCompleteComponent}      />    ) : null      var isDone = this.state.isCompleted ?(      <div>{JSON.stringify(model.data, null, 3)}</div>    ): null;      return (      <div className = "App">        <div>        {surveyRender}        {isDone}      </div>      </div>    );  }  }    export default App;  

but I get no Json output form isDone, I tried following this https://surveyjs.io/Examples/Library/?id=survey-data&platform=Reactjs&theme=modern but this method doesn't work for me as well what should I change in my code to get the survey result as Json object ?


Read in browser »
share on Twitter

what is the time unit used in intervals in discord.js?

By NX1S on Jun 02, 2021 04:01 am

i was working on some code, i wanted it to detect if a user is made within 2 months while doing the intervals i google how much is 2 months in milliseconds (5259600000), i got that intervals work in milli idk where i got that from, but the code doesnt really say that its 2 months, i have an alt that is 6-7 days old and still detects it as an alt, but when i increase the interval to 5259492000000 it detects accs from 2020 as an alt, so i just need help in time used in the interval, it really confused me.

hereis the code if that helps:

bot.on('guildMemberAdd', async member => {      if (member.user.createdAt < 5259492000000) {          const cachedInvites = guildInvites.get(member.guild.id);          const newInvites = await member.guild.fetchInvites();          guildInvites.set(member.guild.id, newInvites);          let Muterole = member.guild.roles.cache.find(role => role.id == "847963874278768650")          member.roles.add(Muterole)          const usedInvite = newInvites.find(inv => cachedInvites.get(inv.code).uses < inv.uses);          const embed = new MessageEmbed()              .setDescription(`${member.user} is an **ALT**\n created at\n${member.user.createdAt}\n Inv Code: ${usedInvite.url} \nInv Code Owner ${usedInvite.inviter.tag},||this might not be the real owner of the invite.||`) //${member.user}** is created at**\n${member.user.createdAt}\n Inv Code: ${usedInvite.url} \nInv Code Owner ${usedInvite.inviter.tag},||this might not be the real owner of the invite.||              .setTimestamp()          const logchannel = member.guild.channels.cache.find(channel => channel.id === '847510771670974555');          if (logchannel) {              logchannel.send(embed).catch(err => console.log(err));          }      }  });  

Read in browser »
share on Twitter

React Native Navigation Library - hiding a bottom tab

By Squiggs. on Jun 02, 2021 04:00 am

I'm currently using React Navigation to power navigation in a react native application.

For the purposes of explaining the problem, I have two screens, one for the homepage, and one for the Search Screen, for the search screen, there are navigational elements left to right that allow you to move further through the app. For the home screen, think of it as a splash screen that doesn't need the navigational elements. There are two buttons on it that allow the user to move through the app.

Now. My problem is this. On the home screen, navigation is hidden.

   HomeScreen.options = {          bottomTabs: {              visible: false          },          topBar: {              visible: false          }      }  

In my definition of the Bottom Tabs, the home page is a child entry, without any options. In this scenario, it appears that doing this, creates an additional entry in the bottom tab, which I don't want to appear. i.e. the Home Child, should not have an associated icon in the bottom nav. Am I missing something? Is there an easy way to remove a 'bottom tab' but still have it sitting in the same structure? Or is there a better way to do this?

I did try having multiple navigators, however, this didn't seem to play ball either.

const BOTTOM_TABS: LayoutBottomTabs = {    id: 'BOTTOM_TABS',    children: [      {        stack: {          id: 'HOME_TAB',          children: [            {              component: {                id: 'HOME_SCREEN',                name: 'HomeScreen',              }            }          ],          },      },      {        stack: {          id: 'SEARCH_TAB',          children: [            {              component: {                id: 'SEARCH_SCREEN',                name: 'SearchScreen',              }            }          ],          options: {            bottomTab: {              text: 'Search',              icon: require('@resource/icons/tabs/search.png'),              ...tabConfig,            },          },        },      },      {        stack: {          id: 'SAVED_TAB',          children: [            {              component: {                id: 'SAVED_SCREEN',                name: 'SavedScreen',              }            }          ],          options: {            bottomTab: {              text: 'Saved',              icon: require('@resource/icons/tabs/saved.png'),              ...tabConfig,            },          },        },      },    ],  };    export default BOTTOM_TABS       Navigation.setRoot({      root: {        bottomTabs: BOTTOM_TABS,        options: {          statusBar: {            backgroundColor: DARK_ORANGE,            style: 'light',          },        },      },    

Read in browser »
share on Twitter

(WebDev apprentice) Editor mode to modify style on click

By Brice Joosten on Jun 02, 2021 04:00 am

I'm on a WebDev formation and I'm already fluent with HTML/CSS. I have a bit of exercising with JS/JSON/AJAX and I'm getting more and more into PHP/SQL. I can have a full website with database, user login and signin space, content like articles and all in database, and full admin interface to manage users, content, etc... Also for how I work, I'm a big fan of the rule of "write on paper and unbuild step by step your problem". (This is for what I can do, if it can be useful to you)


What I'm planning to do is a kind of "Editor Mode" inside the admin interface that when I'll click on a button, I'll shift in Editor Mode and a top fixed navbar will appear. This navbar is the Editor navbar. From this moment, when I'll hover/click on the elements, properties of the chosen element (h1, img, section, etc) will display in the Editor's navbar and I will be able to change its CSS properties dynamically. The Editor mode staying on all pages work correctly ($_SESSION) and it's pretty easy (for now) to modify my style stored in database (for this I do SQL request in the <style> of my "style.php" file).


My first problem is that I'm wondering how to manage the whole thing, what kind of process should I use ? Directly modify CSS in "style.php" with no storing in database ? Store in database using JSON to make it simpler (without it, I actually have a lot of line for each value of each property of each selector etc) ?

My second problem is that I'm wondering what kind of interaction to do to modify style : if I'm planning to click on elements to get style properties in Editor's navbar, how could I manage <a> links to go from one page to another to continue modifying style on other pages ? Should I use hover for this situation ? Also I thought to combine both, hovering elements does make appear a gear icon in a corner of the elements and when clicking on it, properties are displayed in Editor's navbar. This way, I can click on <a> links to go from one page to another and still change <a> links' style.


This is the situation. I hope I've explained clearly, tell me if not, I can show code if required. Thanks for your time, hoping you could help me to find a way, a process to do what I want.


Read in browser »
share on Twitter

Google cloud speech-to-text not returning punctuation

By Sean Saulsbury on Jun 02, 2021 04:00 am

We have a PHP script that processes an audio file (about 15 seconds on average). It used to return punctuation with the text, but it no longer does (we have not updated the script). Any ideas as to why and/or how to enable this? We using PHP.


Read in browser »
share on Twitter

How to make nested collapsible tableview i swift?

By Abhayjeet Singh on Jun 02, 2021 04:00 am

I have some designs in which parents and their children both are collapsible. I have achieved for parent level using table view but for its children how would I implement its expanded cell. Should I load another custom view cell or should I change in the current cell, I don't have any idea. if anybody has some idea please help me out on this.

   // Model Class  class WorkoutTemplate {      var folderName:String      var workoutType: [WorkoutType]      init(folderName: String, workoutType: [WorkoutType]) {          self.folderName = folderName          self.workoutType = workoutType      }  }  class WorkoutType {      var workoutCategoryName: String // Basic Full Body      var totalWorkouts : [Workout]      init(workoutCategoryName: String, totalWorkouts: [Workout] ) {          self.workoutCategoryName = workoutCategoryName          self.totalWorkouts = totalWorkouts      }  }  class  Workout{      var workoutName: String      var reps:Int = 0      var sets:Int = 0      init(workoutName: String, reps: Int, sets: Int) {          self.workoutName = workoutName          self.reps = reps          self.sets = sets      }    }        // Controller class  import UIKit    class AddWorkoutViewController: UIViewController {      @IBOutlet weak var tableView: UITableView?      var data = [WorkoutTemplate]()      var sectionIsExpanded = [false, false, false]      private let headerIdentifier = "WorkoutTemplateHeaderCell"      private let cellIdentifier = "AddWorkoutCategoryCell"      override func viewDidLoad() {          super.viewDidLoad()          let workout = Workout(workoutName: "Squat", reps: 10, sets: 9)          let workout2 = Workout(workoutName: "Bench press", reps: 6, sets: 7)          let workout3 = Workout(workoutName: "Dunmbell lunge", reps: 12, sets: 78)            let workoutType = WorkoutType(workoutCategoryName: "Basic full body", totalWorkouts: [workout, workout2, workout3])            let workoutTemplate = WorkoutTemplate(folderName: "My Workout Template", workoutType: [workoutType, workoutType])            data.append(workoutTemplate)          data.append(workoutTemplate)          data.append(workoutTemplate)            tableView?.reloadData()          }  }    extension AddWorkoutViewController: UITableViewDataSource, UITableViewDelegate {          func numberOfSections(in tableView: UITableView) -> Int {          return data.count      }        func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {          // First will always be header          let sectiondata = data[section]          return sectionIsExpanded[section] ? (sectiondata.workoutType.count + 1) : 1      }        func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {          if indexPath.row == 0 {              let headerCell = tableView.dequeueReusableCell(withIdentifier: headerIdentifier, for: indexPath) as! AddWorkoutTemplateHeaderTableViewCell              let sectionData = data[indexPath.section]              headerCell.headingLabel?.text = sectionData.folderName                if sectionIsExpanded[indexPath.section] {                  headerCell.setExpanded()              } else {                  headerCell.setCollapsed()              }              return headerCell          } else {              let catCell = tableView.dequeueReusableCell(withIdentifier: cellIdentifier, for: indexPath) as! AddWorkoutCategoryTableViewCell              let sectionData = data[indexPath.section]              let rowData = sectionData.workoutType[(indexPath.row - 1)]                catCell.headingLabel?.text = rowData.workoutCategoryName              var subHeadings = ""              for item in rowData.totalWorkouts {                  subHeadings = subHeadings + item.workoutName + ", "              }                  catCell.mutiWorkoutLabel?.text = subHeadings              return catCell          }      }        func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {          // Expand/hide the section if tapped its header          if indexPath.row == 0 {              sectionIsExpanded[indexPath.section] = !sectionIsExpanded[indexPath.section]                tableView.reloadSections([indexPath.section], with: .automatic)          }      }    }  

enter image description here


Read in browser »
share on Twitter

How to stack a char inside a structure in C++

By Sidhin S Thomas on Jun 02, 2021 03:57 am

I have been beating my head over this for a while now. I can't find any proper reference to this online.

I have a structure with char data inside it. Say for example -

struct mystruct  {      char mydata;  };  

How do I create a mystruct variable with length of data whatever I want.

This works-

mystruct my {"Test"};  

But how do I do it with another variable.

char data = "Test";  mystruct my {data}; // this doesn't work as data becomes char* and there is a type mismatch  

How do I assign data to mydata in a c++ way?


Read in browser »
share on Twitter

Logging true condition of big if(.. || ..) statement

By Wojtek on Jun 02, 2021 03:55 am

I use Java and I want to determine in logs which statement caused the condition to be true. I have got big if with a lot of ORs. Something like below:

if (StringUtils.isTrue(foo.getArg1)      || StringUtils.isTrue(foo.getArg1)      || StringUtils.isTrue(foo.getArg2)      || foo.getArg3.equals("T")      || foo.getList1.isEmpty()      || //and so on...) {         return true; }  

and i would like to get something like:

if (StringUtils.isTrue(foo.getArg1)) {     log.info("Arg1 made statement true")            retrun true;     }    if (StringUtils.isTrue(foo.getArg2)) {     log.info("Arg2 made statement true")            retrun true;     }    if (foo.getList1().isEmpty()) {     log.info("List1 made statement true")            retrun true;     }   //etc...  

Is there any tricky way to get effect like this in more generic way, without a lot of if statements ?


Read in browser »
share on Twitter

How to check if a
contains a determinate text?

By NuKl3Ar on Jun 02, 2021 03:48 am

I want to make an easteregg for my website. There's a title you can change. I want it to start the easteregg if it contains a determinate string.

<h1 class="titlename" id="changeT">Welcome</h1>    <div class="action1">    <div id="titlechange">      <p>        <div id="explain">Write the title you want and press "Confirm". The title "Welcome" will be replaced with the text you wrote. <span class="material-icons">            leaderboard            </span></div>      </p>      <input type="text" id="myText" value="Your title" maxlength="50">        <button onclick="chageText()" class="hideshowbtn">Confirm <span class="material-icons">          check          </span></button>        <script>        function chageText() {          var x = document.getElementById("myText").value;          document.getElementById("changeT").innerHTML = x;        }      </script>    </div>  </div>

I want it to start a script if contains "hello". How?


Read in browser »
share on Twitter

Replace object in a list and insert it at the same position

By user16006564 on Jun 02, 2021 03:48 am
// messages:  [     {id: 2, id_profile: 2, id_groupchat: 3, timestamp: "2021-05-31T16:05:52.904Z", body: "Test"},     {id: 1, id_profile: 1, id_groupchat: 3, timestamp: "2021-06-31T16:10:33.662Z", body: "Test2"},     {id: 1, id_profile: 1, id_groupchat: 3, timestamp: "2021-07-31T15:10:33.662Z", body: "Test3"},     {id: 1, id_profile: 2, id_groupchat: 3, timestamp: "2021-07-31T16:10:33.662Z", body: "Test4"},  ]  

I have a list and I would like to replace an element in the list and place it again at the same posistion. I have the following three values: id_profile, id_groupchat, timestamp

I now search in the list the object which is equal with the values

var id_profile = 1  var id_groupchat = 3  var timestamp = "2021-06-31T16:10:33.662Z"  

There is only one element in the list, this one which exactly matches the values:

{id: 1, id_profile: 1, id_groupchat: 3, timestamp: "2021-06-31T16:10:33.662Z", body: "Test2"},  

I would now like to replace this with

{id: 1, id_profile: 'new', id_groupchat: 3, timestamp: "2021-06-31T16:10:33.662Z", body: "This is a new body"},  

and put it back into the list

[     {id: 2, id_profile: 2, id_groupchat: 3, timestamp: "2021-05-31T16:05:52.904Z", body: "Test"},     {id: 1, id_profile: 'new', id_groupchat: 3, timestamp: "2021-06-31T16:10:33.662Z", body: "This is a new body"},     {id: 1, id_profile: 1, id_groupchat: 3, timestamp: "2021-07-31T15:10:33.662Z", body: "Test3"},     {id: 1, id_profile: 2, id_groupchat: 3, timestamp: "2021-07-31T16:10:33.662Z", body: "Test4"},  ]  

Now my question, how can I do this?

To set an object, I have always used the following:

const incomingMessage = {          ...message,          id_profile: message.senderId,          //id: 'event',          timestamp: message.timestamp,          chatid: message.roomid        };    setMessages((messages) => [...messages.slice(-30), incomingMessage]);  

How can I now exchange only this one object in the complete list and then exchange the complete list again?


Read in browser »
share on Twitter

ASP.NET Core: decimal unusual behavior

By Sherwin Variancia on Jun 02, 2021 03:46 am

I'm facing a very weird problem, every time I update my data (without changing the price) the price will be updated as well (1200,00 => 120000,00). Is there any solution to this? The controller and view are built using the scaffold.

Here is my model

[Required]  [Column(TypeName = "decimal(18,2)")]  public decimal Price { get; set; }  

Here is my controller (edit)

public async Task<IActionResult> Edit(int id, [Bind("AlbumId,GenreId,ArtistId,Title,Price,ImageFile")] Album album)  {      System.Diagnostics.Debug.WriteLine(album.ImageFile != null);        if (id != album.AlbumId)      {          return NotFound();      }        if (ModelState.IsValid)      {          try          {              if (album.ImageFile != null)              {                  if (album.ImageName != null)                  {                      // delete old image                      DeleteImage(ImagePathGenerator(album.ImageName));                  }                    // save new image                  album.ImageName = ImageNameGenerator(album.ImageFile.FileName);                  string path = ImagePathGenerator(album.ImageName);                    using (var fileStream = new FileStream(path, FileMode.Create))                  {                      await album.ImageFile.CopyToAsync(fileStream);                  }              }                _context.Albums.Update(album);              await _context.SaveChangesAsync();          }          catch (DbUpdateConcurrencyException)          {              if (!AlbumExists(album.AlbumId))              {                  return NotFound();              }              else              {                  throw;              }          }            return RedirectToAction(nameof(Index));      }        ViewData["ArtistId"] = new SelectList(_context.Artists, nameof(Artist.ArtistId), nameof(Artist.Name));      ViewData["GenreId"] = new SelectList(_context.Genres, nameof(Genre.GenreId), nameof(Genre.Name));        return View(album);  }  

Data table

Edit data

Data table 2


Read in browser »
share on Twitter

btn in php page don't redirect to another page [closed]

By Fahd on Jun 02, 2021 03:35 am

I have php page calling another php page by ajax the second page contain form have a button when i click the btn it should go to a third page but action didn't work the page stay as it is and don't do any thing . by the way the code to examine action is on the top of the first page(mpther page) I tried to copy it to the top of the second page but also it didn't work . any help? first page

<?php session_start();     require ("db_connection.php");      $conn =get_connection ();     $e="";       $o = $_REQUEST['o'] ;      if(isset($o)){ //test privilages}      if (isset($_POST['action']) || isset($_POST['id'])){          if ($_POST['action'] && $_POST['id']) {              if ($_POST['action'] == 'dell') { //do deletation}              else{if ($_POST['action'] == 'update'){ update record}              }          }      }  ?>    <!doctype html>  <html dir="rtl">  <head>     <script type="text/javascript" src="./js/jquery-3.3.1.min.JS"></script>         <script type="text/javascript">     $(function(){  $("#group").change(function() {      var t_id = $(this).val();      //get the current value's option      if(t_id != "--") {          $.ajax({                  url:"select3.php?o=2",                  data:{tid:t_id},                  type:'POST',                  success:function(response) {                      //window.alert(response);                      //var resp = $.trim(response);                      $("#con").html(response);                  }          });      }else{          $("#maint").html("<option value=''>------------</option>");    });         });      </script>        <meta charset="utf-8">        <title></title>         </head>     <body>      <?php     echo '<table><tr>  <select  name="group"   id="group"   />      <option>         someoption</option></select></tr>';        echo '<tr  name= "con" id= "con"  >';      echo '</tr>';          }          echo '</table>';        }         ?>            </body>     </html>  

Read in browser »
share on Twitter

How to pull messages from a subscription with GCP Pub/Sub?

By EB2127 on Jun 02, 2021 03:34 am

I am confused about the GCP Pub/Sub REST API.

Background: I am trying to write an application using GCP Pub/Sub where the language doesn't exit as a client library (I'm trying to use R).

Therefore, I will need to rely upon the REST API provided: https://cloud.google.com/pubsub/docs/reference/rest

Based on my understanding of the REST API, we would have to use the pull subscription: https://cloud.google.com/pubsub/docs/reference/rest/v1/projects.subscriptions/pull

Question: My confusion is that this is a POST request

POST https://pubsub.googleapis.com/v1/{subscription}:pull  

This POST request has a response:

{    "receivedMessages": [      {        object (ReceivedMessage)      }    ]  }  

How could I receive a response from a POST request? This doesn't make sense to me.

My goal would be to subscribe to a Pub/Sub subscription for messages, similar to the Python library here:

To subscribe to data in Cloud Pub/Sub, you create a subscription based on the topic, and subscribe to that, passing a callback function.

import os  from google.cloud import pubsub_v1    topic_name = 'projects/{project_id}/topics/{topic}'.format(      project_id=os.getenv('GOOGLE_CLOUD_PROJECT'),      topic='MY_TOPIC_NAME',  # Set this to something appropriate.  )    subscription_name = 'projects/{project_id}/subscriptions/{sub}'.format(      project_id=os.getenv('GOOGLE_CLOUD_PROJECT'),      sub='MY_SUBSCRIPTION_NAME',  # Set this to something appropriate.  )    def callback(message):      print(message.data)      message.ack()    with pubsub_v1.SubscriberClient() as subscriber:      subscriber.create_subscription(          name=subscription_name, topic=topic_name)      future = subscriber.subscribe(subscription_name, callback)      try:          future.result()      except KeyboardInterrupt:          future.cancel()  

Read in browser »
share on Twitter

How to avoid the Android keyboard is closed "randomly" after I click on an Input?

By Federico Navarrete on Jun 02, 2021 03:33 am

My PWA had been working fine for several years until recently. Now, it seems there is a new problem with the keyboard because I cannot type anything at all.

My bug, in my opinion, is related to another well-known issue: "Web apps are resized against our will when we open the keyboard." (I'm wondering how Twitter does since it doesn't resize when I do click on the input).

bug

These are some pieces of my code. I wrote them trying to prevent the app to be resized:

HTML:

<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no, shrink-to-fit=no">  

Javascript:

window.onresize = function() {      resizeScreen();  };    function resizeScreen() {      let scaleVal = window.innerHeight / 600;      if (window.innerHeight < 514) {          if (externalContainer === null) {              let bodyTmp = document.body;              let divTmp = document.createElement("div");              divTmp.id = 'externalContainer';              bodyTmp.insertBefore(divTmp, bodyTmp.firstChild);          }          externalContainer = document.getElementById('externalContainer');          let sContainer = document.getElementById('superContainer');          externalContainer.append(sContainer);          externalContainer.style.height = `${window.innerHeight}px`;          sContainer.style.transformOrigin = "50% 0% 0px";            setTimeout(function() {              sContainer.style.transform = `scale(${scaleVal})`;              setTimeout(function() {                  let cHeight = (1 + scaleVal) * window.innerHeight;                  if (cHeight < 514)                      cHeight = 514;                  sContainer.style.height = `${cHeight}px`;              }, 100);          }, 100);      } else {          let sContainer = document.getElementById('superContainer');          sContainer.style.height = `${window.innerHeight}px`;          sContainer.style.transformOrigin = "50% 0% 0px";            setTimeout(function() {              sContainer.style.transform = `scale(${scaleVal})`;          }, 100);            setTimeout(function() {              if (cmbSpeechType.getBoundingClientRect().width > window.outerWidth)                  sContainer.style.transform = `scale(${scaleVal - (scaleVal - cmbSpeechType.getBoundingClientRect().width / window.outerWidth)})`;          }, 100);      }  }  

In order to fix the "native app" (a custom version that I wrote), I added: android:windowSoftInputMode="adjustNothing", but I couldn't find any alternative for JS. I tried to emulate it using onfocus="window.location.href='#id'; return true;" but it didn't work. This point about adjustNothing has been suggested in Chromium since 2014.

I also tried setting a min-height in CSS based on the window height but didn't change the results.

You can check the full source code here:

https://github.com/FANMixco/toastmasters-timer-material-design

The app that is failing you can check it here:

https://fanmixco.github.io/toastmasters-timer-material-design

The main source sections are here:

Any idea how to fix this odd issue?

P.S.:

This is an Android-specific bug because, on iOS and Windows 10, the PWA is working fine. After all, the view is not resized.


Read in browser »
share on Twitter

Laravel not accepting POST Method

By Lee Soon Fatt on Jun 02, 2021 03:21 am

I been trying to add a route to my button, whereby I have declared the method to POST, but when I click on the button, an error prompt saying it is using GET method.

enter image description here

Here is my view

<form method="post" action="{{route('admin.order.item.edit.action', [$order])}}">  ..  ..  <table class="table m-l-sm">                              <tbody>                                  @foreach($order->packages as $item)                                    <tr>                                      <td>                                          <p class="m-b-xxs font-bold">{{$item->name}}</p>                                          @foreach($item->products as $product)                                          <p class="m-b-xxs">{{$product->name}} X {{$product->pivot->quantity}}</p>                                          @endforeach                                            <div class="form-group row m-t-sm">                                              <div class="col-md-4">                                                  <div class="input-group d-inline">                                                      <span class="input-group-addon font-bold">RM {{$item->unit_price}}</span>                                                      <span class="input-group-addon">X</span>                                                      <input id="" type="number" class="form-control" name="package[{{$item->id}}][qty]" value="{{!empty($order->packages->where('id', $item->id)->first()) ? $order->packages->where('id', $item->id)->first()->getOriginal('pivot_quantity') : 0}}" min="0" placeholder="Qty" @cannot('edit-order-package', $order) disabled @endcannot>                                                  </div>                                              </div>@error('package.'.$item->id)                                              <div class="col-md-12 alert alert-danger">{{ $message }}</div>                                              @enderror                                                  <div class="col-md-8 d-flex justify-content-end">                                                      <a class="btn btn-sm btn-danger btn-danger" href="{{route('admin.order.item.edit.delete', [$item->id])}}" >Delete</a>  <--- where i am calling my route                                                  </div>                                          </div>                                      </td>                                  </tr>                                  @endforeach                              </tbody>                          </table>  </form>  

Here is my Route

  Route::post('/{order}/edit/delete', 'App\OrderController@handleDeleteItemOrder')->name('admin.order.item.edit.delete');  

Controller

public function handleDeleteItemOrder(Order $order){              log:info($order);          }  

Read in browser »
share on Twitter

How to parse JSON from String represention of list of JSONs object? [duplicate]

By Utkarsh on Jun 02, 2021 03:19 am

I have a string of the form

String str = "[               {"id": 1, "name":"Abc", "Eligible": "yes"},               {"id": 2, "name":"Def", "Eligible": "no"},               {"id": 3, "name":"Ghi", "Eligible": "yes"},               {"id": 4, "name":"Jkl", "Eligible": "no"}               ]";  

I want to parse each JSON from the list. Thank you.


Read in browser »
share on Twitter

A value of type 'Stream' can't be returned from the function 'user' because it has a return type of 'Stream' in flutter

By Shreyansh Sharma on Jun 02, 2021 02:27 am

I'm trying to implement a getter, but it is showing me this error on last line in the below code snippet.

The code is -

class AuthRepository extends BaseAuthRepository {      final FirebaseFirestore _firebaseFirestore;    final auth.FirebaseAuth _firebaseAuth;      AuthRepository({      FirebaseFirestore? firebaseFirestore,      auth.FirebaseAuth? firebaseAuth,    })  : _firebaseFirestore = firebaseFirestore ?? FirebaseFirestore.instance,          _firebaseAuth = firebaseAuth ?? auth.FirebaseAuth.instance;      @override    // TODO: implement user    Stream<auth.User> get user => _firebaseAuth.userChanges();  

Read in browser »
share on Twitter

distinct unordered dynamic column in kusto

By MaxDev on Jun 02, 2021 01:58 am

query:

let result = datatable(MyString:string)  [  '{"X": "xyz", "Y": "xyz", "Z": "xyz", "prop1": "value1", "prop2": "value2", "prop3": "value3"}',  '{"Y": "xyz", "X": "xyz", "Z": "xyz", "prop1": "value1", "prop2": "value2", "prop3": "value3"}'  ];  result  | distinct *  

result is

{"X": "xyz", "Y": "xyz", "Z": "xyz", "prop1": "value1", "prop2": "value2", "prop3": "value3"}  {"Y": "xyz", "X": "xyz", "Z": "xyz", "prop1": "value1", "prop2": "value2", "prop3": "value3"}  

is there any operation in kusto to make the result be ordered by key and then get the distinct to be the result like:

{"prop1": "value1", "prop2": "value2", "prop3": "value3", "X": "xyz", "Y": "xyz", "Z": "xyz"}  

Read in browser »
share on Twitter

How to mock a logger for unit testing in c#?

By Hema Sreya on Jun 02, 2021 12:47 am

The method that i need to unit test logs the output in the following way and doesnt return anything. How do i write a unit test method for the following case? Please help i'm new to this concept and havent written any test methods before

private void revoke (params) {      if (userexist (revokedb, userid))``  {          deleteusers (revokedb, userid);          if (userexist (revokedb, userid))         {             logger.info ("Not able to delete user");         }         else         {            logger.info ("User was succesfully deleted");         }      else    {         logger.info ("unable of find the user");    }  }  

Read in browser »
share on Twitter

Column with multiple data types in Power BI Matrix Table

By CBags4 on Jun 01, 2021 05:33 pm

My issue is similar to this one Multiple data types in a Power BI matrix but I've got a bit of a different setup that's throwing everything off.

What I'm trying to do is create a matrix table with several metrics that are categorized as Current (raw data values) and Prior (year over year percent growth/decline). I've created some dummy data in Excel to get the format the way I want it in PowerBI (see below):

Desired Format

As you can see the Current values are coming in as integers and the Prior % numbers as percentages which is exactly what I want; however, I was able to accomplish this through a custom column with the following formula:

Revenue2 = IF(Scorecard2[Current_Prior] = "Current", FORMAT(FIXED(Scorecard2[Revenue],0), "$#,###"), FORMAT(Scorecard2[Revenue], "Percent"))  

The problem is that the data comes from a SQL query and you can't use the FORMAT() function in DirectQuery. Is there a way I can have two different datatypes in the same column of data? See below for how the SQL data comes into PowerBI (I can change this if need be):

SQL


Read in browser »
share on Twitter

How to clone an archive with wget via Windows

By Andy McRae on Jun 01, 2021 12:46 pm

I want to mirror an ubuntu archive for the focal distribution to put it on one of our ftp servers (windows server 2016) and install our systems with a kickstarter file which looks like this.

..  d-i mirror/protocol string ftp  d-i mirror/ftp/hostname string 172.16.0.4  d-i mirror/ftp/directory string /Ubuntu-20.04/mirror/archive.ubuntu.com/ubuntu  d-i mirror/ftp/proxy string  ..  

I want to do it on windows because we have both linux installs and windows installs to deploy via this server, and I find the file management much more handy on windows. I know there are plenty of tutorials and procedures with ubuntu servers with grub bootloaders but in this case it's a bit different, we have a windows server with syslinux.

I red the thread here how to mirror an archive with wget on ubuntu here.. I need to clone the following mirrors

--> http://archive.ubuntu.com/ubuntu/dists/focal  --> http://archive.ubuntu.com/ubuntu/dists/focal-security  --> http://archive.ubuntu.com/ubuntu/dists/focal-updates  --> http://archive.ubuntu.com/ubuntu/pool/  

How can I do it in cmd? Any ideas?


Read in browser »
share on Twitter

Select from table 1 with foreign_key = x on table 2 where table 2 foreign key = Y on table 3

By James Young on Jun 01, 2021 11:49 am

Not sure if the title makes much sense, but here is a better description: I have a table of shifts that have an id for the shift worker and an id for the client the shift worker does something for, and the clients table has a user id with associated record in users table.

I would like to select all shifts that have a client id where the associated user id on the client record is X.

Shifts Table  shift_id  shiftworker_id  client_id  ...    Clients Table  client_id  user_id  ...    Users Table  user_id  ...  

So, I want all the records (from shifts) where the client_id for the shift belongs to a specific user.

User has many clients, and client has many shifts associated with it. I think what I am after is some kind of join like this:

select * from shifts join shifts.client_id on clients.id and where clients.user_id = X  

I am trying to do this in Laravel, like:

DB::table('shifts')->join('clients', 'client_id', '=', ...)->join('users', 'client_id', '=', X);  

Although any help with the SQL is appreciated and I can figure out the Laravel query from there.

Thank you


Read in browser »
share on Twitter

In Pyspark 2, Adding a column based on multiple conditions

By Efe Türkoğlu on Jun 01, 2021 08:26 am

I would like to add a column based on conditions. I have a value on 'E_Ref_Value' but I would like to add a column regarding column E_Ref_Value as E_Ref_Grp. Here is the code that I run

df=df.withColumn('E_Ref_Grp',f.when((col("E_Ref_Value")>0 & f.col("E_Ref_Value")<31), f.lit(1))\                              .when((f.col("E_Ref_Value")>30 & f.col("E_Ref_Value")<61),f.lit(2)))  

I didn't get specific error messages with error codes, couldn't create the column, do you have any suggestions?

Error Message:

Py4JError: An error occurred while calling o1509.and. Trace:  py4j.Py4JException: Method and([class java.lang.Integer]) does not exist  at py4j.reflection.ReflectionEngine.getMethod(ReflectionEngine.java:318)  at py4j.reflection.ReflectionEngine.getMethod(ReflectionEngine.java:326)  at py4j.Gateway.invoke(Gateway.java:274)  at py4j.commands.AbstractCommand.invokeMethod(AbstractCommand.java:132)  at py4j.commands.CallCommand.execute(CallCommand.java:79)  at py4j.GatewayConnection.run(GatewayConnection.java:238)  at java.lang.Thread.run(Thread.java:748)  

Read in browser »
share on Twitter

What should a YAML template optional step parameter default value be?

By slikts on Jun 01, 2021 07:56 am

When using a template parameter like this:

parameters:  - name: runStep    type: step  

It always requires passing a value. I would, however, like to make it optional:

parameters:  - name: runStep    type: step    default: ???  

For stepList it can be done like so:

- name: runSteps    type: stepList    default:  

But how could it be done for type step? I could add a "dummy" default value:

default:    script: echo 123  

However, how could I compare that value in a condition? I'd like to do something like this:

- ${{ if parameters.runStep }}:    - ${{ parameters.runStep }}  

Read in browser »
share on Twitter




Recent Articles:

Matlab how to remove the weekend from the chart
Background event on Highcharts Gantt
DNS issue in Google's cloud dns
I wanted to scrape article titles from a website but result shows none
Exporting from three.js scene to SVG or other vector format
Twitter
Facebook
Website
Copyright © 2021 reader, All rights reserved.
You are receiving this email because you opted in via our website.

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

Add us to your address book


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

Email Marketing Powered by Mailchimp

No comments:

Post a Comment