Monday, September 20, 2021

Recent Questions - Stack Overflow

Recent Questions - Stack Overflow


Is ASP.Identity user id public?

Posted: 20 Sep 2021 08:34 AM PDT

I suppose it's safe to say user id is a public value and there is nothing wrong with exposing it as a parameter to my web api endpoint?

My reasoning it is already made public since it's included in JWT. Am I correct?

React: Component name based on prop

Posted: 20 Sep 2021 08:34 AM PDT

I am trying to load a component in React via a prop. It is an icon that I want to pass from the parent component.

Dashboard (parent):

import { Button } from './components';    function App() {    return (      <div className="app">          <div className="app__nav">              <Button icon="FiSun" />              <Button icon="FiSun" />          </div>      </div>    );  }  

Button (child):

import React from 'react';  import * as Icon from "react-icons/fi";    import './button.scss';    function Button(props) {      return(          <button>              // Something like this              <Icon.props.icon />          </button>      )  }  

Unfortunately, I can't find an easy way to make this work since I'm not allowed to use props in the component name.

jquery html duplicating on drag and drop

Posted: 20 Sep 2021 08:34 AM PDT

I am using jQuery and using a drag and drop function. My image keeps duplicating and I have no idea why. Any help would be great. I am pretty sure my issue is at line:

$('#' + seat).append('<div class="studentCard" id="' + id + '"><img class="studentImage" src="Images/' + id + '.jpg" style="height:150px; width:150px;" />' + student + '</div>');                   

Here is my function:

$('.seat').droppable({              drop: function (event, ui) {          var seat = $(this).attr('id');          var id = $(ui.draggable).attr('id');          var student = $(ui.draggable).html();          $.ajax({              success: function () {                  if ($('#' + seat + '> div').length > 0) {                      alert('Desk already occupied');                  }                  else {                                         $(ui.draggable).remove();                      $('#' + seat).append('<div class="studentCard" id="' + id + '"><img class="studentImage" src="Images/' + id + '.jpg" style="height:150px; width:150px;" />' + student + '</div>');                      $('div#' + id).draggable({                          helper: 'clone'                      });                                          }              }          });      }  });  

Can't write file using FS

Posted: 20 Sep 2021 08:33 AM PDT

So, I have a NodeJS API using express and I want to get data from a HTTP request and store it in a local JSON file. This is the file that contains the function to write the local file:

    const fs = require('fs').promises;      async function updateData(req,res){         let { name, phone, email, addres, whatsapp, officeHours} = req.body;         let configs={          name:name,          phone:phone,          email:email,          addres:addres,          whatsapp:whatsapp,          officeHours: officeHours        };         let data = JSON.stringify(configs);         console.log(data);         try{          await fs.writeFile('./configs.json', data);         }catch(err){          throw err;         }      }  module.exports = {updateData};  

And this is the part of the code I use to call the function with the Post route

routes.post('/storedata', storeData.updateData);  

When I send the HTTP request, using Insomnia, I don't get any errors and the data is logged in the console, but the file isn't written.

Azure B2C Custom Policy Email Verification re-order items

Posted: 20 Sep 2021 08:33 AM PDT

In an Azure B2C Custom Policy that uses the default email verification process, is it possible to re-order how the items within the email verification section are displayed?

Current after entering an email address and clicking on the send code button, a message is displayed to the user which is above the email input.

Is it possible to change the position of this, so it is displayed between the email input and the verification code input?

matplotlib: Is it possible to artificially expand the chart axis in a color chart?

Posted: 20 Sep 2021 08:33 AM PDT

I have created pcolor plot, based on df table:

import numpy as np  import pandas as pd    rng = np.random.default_rng()  df = pd.DataFrame(rng.integers(1, 32, size=(100, 3)), columns=list('xyw'))    sample_pvt = df.pivot_table(index='x',columns='y')    sample_pvt.columns = sample_pvt.columns.droplevel(0)    fig, axs = plt.subplots(figsize=(10,10))  orig_map=plt.cm.get_cmap('viridis')  reversed_map = orig_map.reversed()    plt.pcolor(sample_pvt, cmap = reversed_map)  plt.xticks(np.arange(len(sample_pvt.columns))+0.5, sample_pvt.columns)  plt.yticks(np.arange(len(sample_pvt.index))+0.5, sample_pvt.index)    cbar = plt.colorbar()  plt.show()  

Result:

enter image description here

Is it possible to artificially expand the chart on the x-axis to always 40 fields, and on the y-axis to 60 fields and leave these fields blank?

Note: Sometimes I have data with incomplete axis ranges as the picture below:

enter image description here

Is it possible to transform the data/plot in such a way that the axis always shows values ​​from 1 to 40, and the axis shows values ​​from 1 to 60?

Ms sql report builder percentage

Posted: 20 Sep 2021 08:33 AM PDT

I need to create charts that represent % downtimes of equipment. But i have trable with percentage. I need percentage for grouped by month reasons of downtime

My charts

In builder 1

In builder value func

Category func

Label func

Retrieve selection from a List

Posted: 20 Sep 2021 08:33 AM PDT

I am new and I would like to retrieve the user's response when I submitt a List in the console? For example:

I ask him to make a choice among the different proposals:

1 for head

2 for legs

3 for stomach

When he presses 1, 2 or 3, I want to submit another list from the head, legs or stomach for example for the head (answer 1 in the Cons.Read), display him eyes, ears, mouth, etc

I don't know if it's clear enough cause i've very bad english but I would really like to know how to do it.

Regards

EDIT: Basically, how to make a list from a list of a list (tree structure of several levels) and retrieve the answers each time to finally propose an object (OOP) with diferents characteristics?

Trouble calling function via pthread

Posted: 20 Sep 2021 08:33 AM PDT

I have a function that counts the number of occurences of a string in a char array. Calling this function normally with findword(copy, "polar") works perfectly fine and prints an int that's the number of times the string "polar" occurs in the char array "copy". Calling the function via a pthread however gives me compilation issues and I don't know why. This is my first time implementing multithreading.

Here is the function I want to call:

void findword(char *str, string word)  {      char *p;      vector<string> a;          p = strtok(str, " ");      while (p != NULL)      {          a.push_back(p);          p = strtok(NULL, " ");      }        int c = 0;      for (int i = 0; i <= a.size(); i++)                        if (word == a[i])              c++;      printf("%d", c);  }  

And here is the thread I'm trying to create that is supposed to call the function:

struct findwordargs {    char *str;    string word;  };    struct findwordargs firstwordArguments;  firstwordArguments.str = copy;  firstwordArguments.word = "polar";    pthread_t thread_id = 1;  pthread_create(&thread_id, NULL, findword, (void *)(&firstwordArguments));  pthread_join(thread_id, NULL);      

whenever I compile using g++ and the -pthread flag I get this compile error:

  error: invalid conversion from 'int (*)(char*, std::string)' {aka 'int (*)(char*, std::__cxx11::basic_string<char>)'} to 'void* (*)(void*)' [-fpermissive]    101 | pthread_create(&thread_id, NULL, findword, (void *)(&firstwordArguments));    

All the necessary header files are included, thank you for the help.

Open and read text file

Posted: 20 Sep 2021 08:33 AM PDT

try to Open and read text file but I got error FileNotFoundError: [Errno 2] No such file or directory However I have Data.txt in Server/www/ Why I got this error?

with open('Server/www/Data.txt') as creds:          lines = creds.read().rstrip()          if len(lines) != 0:  

with open('Server/www/Data.txt') as creds: FileNotFoundError: [Errno 2] No such file or directory: 'Server/www/Data.txt

Can't find the dbo for television series (dbpedia, sparql)

Posted: 20 Sep 2021 08:33 AM PDT

I hope you are having a lovely day. I am trying to find all the relationships between two television shows.

Right now, I have

SELECT ?r1 ?r2 WHERE {

SELECT ?show1 ?show2 WHERE {      ?show1 dbo:tvShow dbr:The_Office_(American_TV_series)      ?show2 dbo:tvShow dbr:The_Office_(British_TV_series)  }     # Query both ways  ?show1 ?r1 ?show2 .   ?show2 ?r2 ?show1 .        

}

However, I seem to be getting a syntax error at '?show3' before 'dbo:tvShow'.

Does anyone have any advice to fix this query?

Thank you so much!!

Authorization token Bearer through javascript security

Posted: 20 Sep 2021 08:33 AM PDT

I'm a bit confused about authentication throuhg token. If I need to call web api authenticated from a web application I need to add the token to all call to the apis: but in this case the token can be easily copied and used to makes authenticated calls. For example: if I have a .netcore apis backend and web application that use the apis to render informations, the token must be added in javascript calls... or not?

Where I'm wrong? Thank you!

python pandas is giving a keyerror for a column I group by, even though a boolean expression shows that the column is part of the dataframe

Posted: 20 Sep 2021 08:33 AM PDT

I cannot seem to print the following line: summarydata["Name"].groupby(["Tag"]).size()

without getting the error:

  File "C:\Users\rspatel\untitled0.py", line 76, in <module>      print(summarydata["Name"].groupby(["Tag"]).size())      File "C:\Users\rspatel\Anaconda3\lib\site-packages\pandas\core\series.py", line 1720, in groupby      return SeriesGroupBy(      File "C:\Users\rspatel\Anaconda3\lib\site-packages\pandas\core\groupby\groupby.py", line 560, in __init__      grouper, exclusions, obj = get_grouper(      File "C:\Users\rspatel\Anaconda3\lib\site-packages\pandas\core\groupby\grouper.py", line 811, in get_grouper      raise KeyError(gpr)    KeyError: 'Tag'  

I have checked that Tag is included as a column in the summarydata dataframe by the following:

if 'Tag' in summarydata.columns:      print("true")  else :      print("false")  

which prints out as true. Therefore I am not sure why a key error is being thrown when the column is in the dataframe.

Terminating a .net-core WebApp if there is a critical error

Posted: 20 Sep 2021 08:33 AM PDT

In order to make deployment easier I want my application to self create pre-defined roles on the database. If for some reason it is the first time running on the current database but it fails to create the roles, PE, there was a connection error, the application immediately terminates with an Environment.Exit(-1);.

Is this a bad practice? If yes, why? What are my alternatives?

Why $request is Unefined?

Posted: 20 Sep 2021 08:33 AM PDT

enter image description here

i have a web appliction where i'm testing custom login and registration but in the CustomAuthController i tried to pass the data to the dashboard but $request is no defined

Elasticsearch results order is changing on the frontend

Posted: 20 Sep 2021 08:33 AM PDT

I'm working with magento 2.4.2 and elasticsearch 7.10.2

What I'm seeing is that even though the results in elasticsearch are ordered correctly in the backend, on the frontend are wrongly displayed. Here's an example, the language is spanish so "lapices de colores" means "Colored Pencils".

If I run this command:

curl 'localhost:9200/store_product_1_v118/_search?pretty&q=lapices+de+colores'   

I get the following results (for convenience I'm only showing the first hit)

 "hits" : [    {      "_index" : "store_product_1_v118",      "_type" : "document",      "_id" : "9323",      "_score" : 13.052037,      "_source" : {        "store_id" : "1",        "sku" : "PEL800049",        "status" : 1,        "status_value" : "Habilitado",        "visibility" : 4,        "tax_class_id" : 2,        "tax_class_id_value" : "Taxable Goods",        "name" : "lapices de colores pastel pelikan x12",        "url_key" : "lapices-de-colores-pastel-pelikan-x12",        "category_ids" : [          2,          135,          139,          214,          452        ],        "position_category_2" : "10000",        "name_category_2" : "RA▒~MZ ",        "position_category_135" : "0",        "name_category_135" : "ESCOLAR",        "position_category_139" : "0",        "name_category_139" : "LAPICES DE COLORES",        "position_category_214" : "0",        "name_category_214" : "LIBRERIA ",        "position_category_452" : "0",        "name_category_452" : "▒~ZTILES ESCOLARES Y KITS",        "price_0_1" : "570.000000",        "price_1_1" : "570.000000",        "price_2_1" : "570.000000",        "price_3_1" : "570.000000"   ....  

But if I run the same query on the store, being the url:

https://store24.com.ar/catalogsearch/result/?q=lapices+de+colores  

The results although related are not the ones given by elasticsearch.

wrong results

In the admin panel, in stores->Catalog->Catalog->"Product Listing Sort By" is set by Position.

I'm guessing that is a template issue but I don't know how can I fix this. Here's the sorter.phtml file used by the template:

<div class="toolbar-sorter sorter">  <label class="sorter-label" for="sorter"><?php /* @escapeNotVerified */ echo __('Sort by') ?></label>  <select id="sorter" data-role="sorter" class="sorter-options">      <?php foreach ($block->getAvailableOrders() as $_key => $_order): ?>          <option value="<?php /* @escapeNotVerified */ echo $_key; ?>"              <?php if ($block->isOrderCurrent($_key)): ?>                  selected="selected"              <?php endif; ?>              >              <?php echo $block->escapeHtml(__($_order)) ?>          </option>      <?php endforeach; ?>  </select>  <?php if ($block->getCurrentDirection() == 'desc'): ?>      <a title="<?php /* @escapeNotVerified */ echo __('Set Ascending Direction') ?>" href="#" class="action sorter-action sort-desc" data-role="direction-switcher" data-value="asc">          <span><?php /* @escapeNotVerified */ echo __('Set Ascending Direction') ?></span>      </a>  <?php else: ?>      <a title="<?php /* @escapeNotVerified */ echo __('Set Descending Direction') ?>" href="#" class="action sorter-action sort-asc" data-role="direction-switcher" data-value="desc">          <span><?php /* @escapeNotVerified */ echo __('Set Descending Direction') ?></span>      </a>  <?php endif; ?>  

I'm not sure where or what to look for, any ideas?

React component doesnnt re render

Posted: 20 Sep 2021 08:33 AM PDT

im passing values using react redux evreything is passed but the component i want to render only renders 1 time and when i save my code in vscode (it renders again)the data renders on page like it should

return (

    {FavoritesData.data.length === 0 ? (              <h5>You Don't Have Any Favorites Yet!</h5>          ) : (              <div className="favorites-grid">{FavoritesData.data.map((item) =>  <Favorite item={item} />)}</div>          )}                  <button onClick={() => console.log(FavoritesData.data.length)}></button>      </div>  );  

on the log the data updates but the trenary function dont trigger same goes for useEffect

returns an array of objects that contains the product names

Posted: 20 Sep 2021 08:33 AM PDT

I am working on a javascript snippet for Google tag manager where i have to display the output like below.

[{"product1":"Protein Corn Muffin"},{"product2":"Salted Caramel Super Smoothie"},{"product3":"Pop Corn"},{"product4":"Fruit Pops!"}]

Attached datalayer.

dataLayer = {    products: [      {        name: "Protein Corn Muffin",        id: "SHOP - US - 6032011P",        price: "5.95",        quantity: 1,      },      {        name: "Salted Caramel Super Smoothie",        id: "SHOP - US - 6021050P",        price: "7.95",        quantity: 3,      },      {        name: "Pop Corn",        id: "SHOP - US - 4117050P",        price: "8.95",        quantity: 2,      },      {        name: "Fruit Pops!",        id: "SHOP - US - 41441109P",        price: "9.99",        quantity: 1,      },    ],  };  
Can anyone guide me.  

How to require to fill up forms before submitting it by the user? empty() and !isset is not working

Posted: 20 Sep 2021 08:33 AM PDT

I am working on a small activity of using forms to insert data to the database and displaying those data. I want the form to be filled and not empty before inserting it to the database but using empty() function and !isset inside the if statement doesn't work for me. Am I missing something?

PS. I commented my previous codes of each table to try the empty() and soon replaced it with !isset but nothing works.

This is my process.php

  $records = mysqli_query($conn,"select * from products");    if (isset($_POST['submit'])){            if (!isset($_POST['image'])){          $errMsg = "Error! You didn't enter the Image";          echo $errMsg;      }else{          $image = $_POST['image'];      }       //$image = $_POST['image'];      if (!isset($_POST['productName'])){          $errMsg = "Error! You didn't enter the Product name";          echo $errMsg;      }else{          $productName = $_POST['productName'];      }      // $productName = $_POST['productName'];      if (!isset($_POST['price'])){          $errMsg = "Error! You didn't enter the Price";          echo $errMsg;      }else{          $price = $_POST['price'];      }       //$price = $_POST['price'];       if (!isset($_POST['category'])){          $errMsg = "Error! You didn't enter the Category";          echo $errMsg;      }else{          $category = $_POST['category'];      }       //$category = $_POST['category'];       if (!isset($_POST['stocks'])){          $errMsg = "Error! You didn't enter the Stocks";          echo $errMsg;      }else{          $stocks = $_POST['stocks'];      }       //$stocks = $_POST['stocks'];       if (!isset($_POST['availability'])){          $errMsg = "Error! You didn't enter the Availability";          echo $errMsg;      }else{          $availability = $_POST['availability'];      }       //$availability = $_POST['availability'];```                                                        This is my form page:    <h1 class="blockquote text-center">Product Management</h1></br>      <form method="post" enctype="multipart/form-data" action="process.php">          <label>Product Image:</label>            <input type="file" name="image" class="form-control form-cotrol-lg">          <br>            <label>Product Name:</label>              <input type="text" name="productName" class="form-control form-cotrol-lg">              <br>              <label>Price:</label>                <input type="number" name="price" class="form-control form-cotrol-lg">          <br>          <label>Category:</label>            <select name="category" class="form-control form-cotrol-lg">              <option value="">---Category---</option>              <option value="apparels"> Apparels </option>              <option value="souveniers"> Souveniers </option>              <option value="books"> Books </option>              <option value="others"> Others </option>            </select>              <br>          <div class="form-group">          <label>Stocks:</label>                <input type="number" name="stocks" class="form-control form-cotrol-lg">              <br>          </div>            <input type="radio" name="availability" value="available">            <label for="available">Available&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</label>            <input type="radio" name="availability" value="not available">            <label for="not available">Not Available</label><br>  

How to compute very large numbers without a list

Posted: 20 Sep 2021 08:33 AM PDT

I am trying to complete a coding challenge which requires me to count all of the digits between 1 and X, where can reach up to 400,000,000,000,000,000

My approach was to iterate over a list and add the amount of digits to my result in the end, like so:

def page_digits(pages):      list_of_pages = list(range(1, pages + 1))      res = 0      for num in list_of_pages:          res += len((str(num)))      return res  

but obviously creating a list of every digit between 1 and that big number requires a lot of storage and running this returns 'MemoryError Line 2'

How else could I go about this? or Avoid the problem

mysql will make more connections than allowed

Posted: 20 Sep 2021 08:33 AM PDT

I'm using Sequelize ORM for my nodejs project and it seems there is a mistake in configuration or I'm doing something really awry with the queries... The problem is that our client will make more than 60 connections sometimes when the user is requesting a lot of information at once (graphql request with deep structure and data loaders on top for a lot of records fetched from MySQL). The pool settings should not let do that since it is configured for 10 max connections at once. The main question is how those connections appear? The app is being hosted at AWS using ELB, for MySQL we are using RDS and we can have up to 2 app instances at once, so no more than 20 connections at all. Sequelize config:

production: {      username: process.env.DB_USER,      password: process.env.DB_PASS,      database: process.env.DB_NAME,      host: process.env.DB_HOST,      dialect: 'mysql',      define: {        charset: 'utf8mb4',        collate: 'utf8mb4_general_ci',      },      pool: {        max: parseInt(process.env.DB_POOL_SIZE, 10), // 10 from ENV variables        min: 0,        acquire: 60000,        idle: 60000,      },      operatorsAliases: 0,      logging: false,    },  

once there are >50 connections on our RDS client we can see that our ELB can't perform health check since it can't make new connections and return positive status from MySQL. so our app becomes unreachable.

After bombing the backend with this particular query I've fetched processlist for MySQL. Some sleeping queries will go to more than 1000 "time".

queries

What I'm missing here?

How can I post form data from react to an express.js server and use it as part of a url string

Posted: 20 Sep 2021 08:33 AM PDT

Just to make this clearer. I have a form where the user inputs a name which is passed to the apiUrl const to become part of the URL string. The form input data is passed through state as {this.state.input}. After the user inputs the form with the name he wants to search for, he clicks a button which calls the onButtonSubmit function that fetches the data with the updated apiUrl parameters. The catch is, this is running on the front-end and as this is a proprietary api, I don't want to expose the api key (which is part of the url) to the user.

I have set up an express.js server but I'm still unsure on how I can post the form data to it and then use that in the same manner used in my code below.

So the output I'm looking for would follow something like this:

1 - Post form data from frontend after the user submits it with a button click 2 - Through the backend, use the form data to update the apiurl and then fetch the data from the api 3 - Send the api data back to the frontend

onButtonSubmit = () => {    const apiUrl = 'URLStringPart1' + this.state.input + 'URLStringpart2withAPIKey';    fetch(apiUrl)      .then(res => res.json())      .then(        result => {          this.setState({            isLoaded: true,            array1: result.array1,            array2: result.array2,            array3: result.array3,            array4: result.array4,            array5: result.array5,                  route: 'fetched'          });        },        error => {          this.setState({            isLoaded: false,            error: error          });        }      );  }  

JavaScript v8 Optimization Compiler | Monomorphism, Polymorphism?

Posted: 20 Sep 2021 08:34 AM PDT

Chrome V8 Optimization Compiler

Is there still a difference between Monomorphism, Polymorphism, and Megamorphism in speed, or not anymore?

Monomorphism => [{a:47}, {a:5}, {a:9}];  Polymorphism => [{a:1, b:65}, {c:22, a:57, d:8},{e:14, a:819}];  ...  

How to constrict your problem to allow a custom-defined "cool-off period"?

Posted: 20 Sep 2021 08:34 AM PDT

I am making use of CVXPY and CVXOPT to solve a problem that allows us to control the running of motors in the cheapest possible ways.

We have existing constraints which consist of, cost, volume, and level which need to be maintained (all of which work, and is only to give a further definition of the problem at hand). We use this to minimize the cost and provide an optimized approach.

Recently, we wish to add a new constraint that will allow for a cool-off period. Which we can set. So if the selection value is 1, the next two periods should be a 0 if this makes sense. Essentially, if the pump runs for a period it should be off for the next two to cool down.

Please see below for a current function that is being used. Currently, no cool-off constraint has been implemented, and wish to get a push in the right direction of how best to implement such a solution.

def optimiser(self, cost_, volume_,v_min,flow_,min_level,max_level,initial_level,period_lengths,out_flow_, errors) :          """          This function optimizes the regime possible combinations using convex optimization. We assign and define the problem and uses `GLPK_MI` to solve our problem.            Parameters          ----------          cost_              Numpy Array          volume_              Numpy Array          v_min              Float -> minimum volume          flow_              Numpy Array          min_level              Float -> minimum level          max_level              Float -> maximum level          initial_level              Float -> initial level          period_lengths              Integer -> number of period lengths          out_flow_              Numpy Array          errors              Exceptions -> error handling            Returns          ----------          selection              Solved problem with the best possible combination for pumping regime.          """          FACTOR =  0.001*1800*self.RESERVOIR_VOLUME          input_flow_matrix=np.zeros((max(period_lengths),len(period_lengths)))          for i,l in enumerate(period_lengths):              input_flow_matrix[:l,i]=1          selection = cp.Variable(shape=cost_.shape,boolean=True)          assignment_constraint = cp.sum(selection,axis=1) == 1          input_flow_= cp.sum(cp.multiply(flow_,selection),axis=1)          input_flow_vector=cp.vec(cp.multiply(input_flow_matrix,np.ones((max(period_lengths), 1)) @ cp.reshape(input_flow_,(1,len(period_lengths)))))          res_flow= (input_flow_vector-cp.vec(out_flow_))          res_level=cp.cumsum(res_flow) * FACTOR + initial_level          volume_= cp.sum(cp.multiply(volume_,selection))          volume_constraint = volume_ >= v_min          min_level_constraint = res_level >= min_level          max_level_constraint = res_level <= max_level            if errors is LevelTooLowError:              constraints = [assignment_constraint, max_level_constraint, volume_constraint]          elif errors is LevelTooHighError:              constraints = [assignment_constraint, min_level_constraint, volume_constraint]          elif errors is MaxVolumeExceededError:              constraints = [assignment_constraint, min_level_constraint, volume_constraint]          else:              constraints = [assignment_constraint, max_level_constraint, min_level_constraint, volume_constraint]            cost_ = cp.sum(cp.multiply(cost_,selection))          assign_prob = cp.Problem(cp.Minimize(cost_),constraints)          assign_prob.solve(solver=cp.GLPK_MI, verbose=False)             return selection  

Sample of data which we work with

Here is our cost_ array

[[0.   0.8 ]   [0.   0.8 ]   [0.   0.8 ]   [0.   0.8 ]   [0.   0.8 ]   [0.   0.8 ]   [0.   0.8 ]   [0.   0.8 ]   [0.   0.9 ]   [0.   0.9 ]   [0.   0.9 ]   [0.   0.9 ]   [0.   0.9 ]   [0.   0.9 ]   [0.   0.9 ]   [0.   0.9 ]   [0.   1.35]   [0.   1.35]   [0.   1.35]   [0.   1.8 ]   [0.   1.2 ]]  

And here is our volume_ array

[[    0. 34200.]   [    0. 34200.]   [    0. 34200.]   [    0. 34200.]   [    0. 34200.]   [    0. 34200.]   [    0. 34200.]   [    0. 34200.]   [    0. 34200.]   [    0. 34200.]   [    0. 34200.]   [    0. 34200.]   [    0. 34200.]   [    0. 34200.]   [    0. 34200.]   [    0. 34200.]   [    0. 51300.]   [    0. 51300.]   [    0. 51300.]   [    0. 68400.]   [    0. 51300.]]  

I hope my problem has been well defined for anyone to understand what I wish to do at the moment. If anything else is needed, I can happily provide this for anyone.

Thanks in advance.

Find truck name and sume the duration time

Posted: 20 Sep 2021 08:33 AM PDT

Hi everybody I'm working on a productivity analisis by truck, and I want to get the truck name and sum the duration time. I get this error:

int() argument must be a string, a bytes-like object or a number, not 'Timedelta'  

Here is my code

#Productivity analysis by truck    id = df['Vehicle ID']  vehicles = id.drop_duplicates()  vehicles = vehicles.reset_index().drop(['index'], axis=1)  N_Vehicles = len(vehicles)    df['Duration'] = pd.to_timedelta(df['Duration'].astype(str))    for i in range(N_Vehicles):      X[i]= df[df['Vehicle ID'] == vehicles['Vehicle ID'][i]].Duration.sum()    X  

Thank you in advance

Compare two table ids and get results where does not exist in one table

Posted: 20 Sep 2021 08:32 AM PDT

I am trying to compile a list of "None Sellers", I am getting a list of distinct seller_id's and comparing that to the "list of sellers" aka account_manager_sellers using the NOT IN clause, but this is not working for me.

Table plans:

+----+-----------+  | id | seller_id |  +----+-----------+  |  1 |      1001 |  |  2 |      1002 |  |  3 |      1002 |  |  4 |      1001 |  |  5 |      1005 |  +----+-----------+  

Table account_manager_sellers:

+------+--------------+  |  id  | persons_name |  +------+--------------+  | 1001 | name_1       |  | 1002 | name_2       |  | 1003 | name_3       |  | 1004 | name_4       |  | 1005 | name_5       |  +------+--------------+  

Expected Result:

+------+--------------+  |  id  | persons_name |  +------+--------------+  | 1003 | name_3       |  | 1004 | name_4       |  +------+--------------+      SELECT DISTINCT(p.seller_id) FROM plans p   WHERE p.seller_id NOT IN (      SELECT a.id FROM account_manager_sellers a  )  

This snippet is running but not returning any results.

Get MAX inputted date within sub query

Posted: 20 Sep 2021 08:33 AM PDT

I have a script which is working but not as desired. My aim is to select the most recently inputted record on the plans database for each seller in the account_manager_sellers list.

The current issue with the script below is: It is returning the oldest record rather than the newest, for example: it is selecting a record in 2016 rather than one which has a timestamp in 2018. (eventually I need to change the WHERE clause to get all lastsale records before 2017-01-01.

Simple Database Samples.

plans AKA (sales list)

+----+------------------+-----------+  | id |   plan_written   | seller_id |  +----+------------------+-----------+  |  1 | 20/09/2016 09:12 |       123 |  |  2 | 22/12/2016 09:45 |       444 |  |  3 | 19/10/2016 09:07 |       555 |  |  4 | 02/10/2015 14:26 |       123 |  |  5 | 15/08/2016 11:06 |       444 |  |  6 | 16/08/2016 11:03 |       123 |  |  7 | 03/10/2016 10:15 |       555 |  |  8 | 28/09/2016 10:12 |       123 |  |  9 | 27/09/2016 15:12 |       444 |  +----+------------------+-----------+  

account_manager_sellers (seller list)

+-----+----------+  | id  |   name   |  +-----+----------+  | 123 | person 1 |  | 444 | person 2 |  | 555 | person 3 |  +-----+----------+  

Current Code Used

SELECT p.plan_written, p.seller_id  FROM plans AS p NATURAL JOIN (           SELECT   id, MAX(plan_written) AS lastsale           FROM     plans           GROUP BY seller_id         ) AS t  JOIN account_manager_sellers AS a ON a.id = p.seller_id  WHERE  lastsale < "2018-05-08 00:00:00"  

Summary

Using the code and example tables above, this code would return these 3 results, whilst we do expect 3 results, the MAX(plan_written) does not seem to have followed, my guess is that it is something to do with the GROUP clause, I am not sure if we can utilise an ORDER BY and LIMIT clause?

+--------------+------------------+  | seller_id    |   plan_written   |  +--------------+------------------+  |          123 | 16/08/2016 11:03 |  |          444 | 15/08/2016 11:06 |  |          555 | 03/10/2016 10:15 |  +--------------+------------------+  

Limit character length of database field name?

Posted: 20 Sep 2021 08:33 AM PDT

an explanation of my question here in the example, how many lengths of field user_email_address, id

create table `users` (     `id`INT(11) NOT NULL AUTO_INCREMENT,     `user_email_address` VARCHAR(250) NOT NULL,  ) ENGINE = InnoDB DEFAULT CHARSET = UTF8;  

ArangoDB Cursor Timeout

Posted: 20 Sep 2021 08:33 AM PDT

Using ArangoDB 2.3.1. It seems my cursors are expiring within a couple minutes. I would like them to last for an hour. I've set up my AQL query object with the TTL parameter as follows:

{      "query": 'removed actual query',      "count": true,      "batchSize": 5,      "ttl": 3600000  }  

My understanding is that the TTL parameter should tell the server to keep the server for 3600000 milliseconds or 1 hour. But it expires within about 60 seconds. In fact, I've tried changing the TTL to several different numbers and it doesn't seem to do anything. Any ideas?

UPDATE: the actual error I receive from arango is "cursor not found"

Python xml ElementTree from a string source?

Posted: 20 Sep 2021 08:33 AM PDT

The ElementTree.parse reads from a file, how can I use this if I already have the XML data in a string?

Maybe I am missing something here, but there must be a way to use the ElementTree without writing out the string to a file and reading it again.

xml.etree.elementtree

No comments:

Post a Comment