Monday, October 11, 2021

Recent Questions - Stack Overflow

Recent Questions - Stack Overflow


How to read binary data loaded in numpy?

Posted: 11 Oct 2021 08:16 AM PDT

I've checked out everything I can on here about numpy and loading binary data. I can't get a grasp on what's going on.

out[] array([ 4863525.,   741456.,  6941072.,  2989918., 39167116.,  5539215.,          3578141.,   948921.,   685815., 20613476., 10301890.,  1427559.,          1682380., 12820527.,  6634304.,  3131371.,  2910844.,  4438182.,          4678135.,  1331317.,  6003323.,  6823608.,  9950571.,  5522744.,          2987938.,  6087135.,  1040859.,  1905616.,  2917563.,  1342307.,          8870827.,  2091630., 19633428., 10154788.,   754434., 11634370.,          3926331.,  4089976., 12782275.,  1056770.,  4957968.,   862996.,          6646010., 27914410.,  3041868.,   623657.,  8410106.,  7294771.,          1831023.,  5772628.,   584215.], dtype=float32)```  and  ```pop17 = np.fromfile('us_pop_by_state_2017a.yaff')   pop17  out [] array([1.56964029e-308, 8.28753520e-308, 4.81296150e-307, 2.03037438e-308,         1.16218111e-302, 3.02255596e-308, 5.40837230e-305, 8.88256404e-308,         2.21797791e-307, 2.83204105e-308, 1.09794371e-306, 4.65795392e-307,         6.49285217e-307, 4.06563147e-308, 2.86212034e-308, 4.43875685e-308,         1.02107043e-305, 2.55077339e-305, 1.73704284e-307, 2.24013367e-308,         1.85222222e-308, 1.48163076e-300, 1.32485534e-308, 1.53721585e-306,         5.41832782e-307])```    Both of these output an array, but I can't make any sense of it. The first one has a float32 data type, and the second one's data type is unknown. I'm told to try different datatype arguments until it reads correctly. I've plugged in all sorts of stuff, but nothing is working and I have no clue how to figure it out. I've been trying to get these two files to display properly for over an hour without any luck. Help please?  

Order Select Option by value alphabetically

Posted: 11 Oct 2021 08:16 AM PDT

I have a SelectOption[] populated by a API values, and I need to order by values, not key. The order need to be [0-9-A-Z]. Also, I need to fix a value in the first position, the 'Select Description' value. I tried somethings and not working. Can someone help me please? I'm loosing my mind with this problem.

R: apply a function to all rows that orders a subset and completes a calculation if a condition is met

Posted: 11 Oct 2021 08:16 AM PDT

i want to apply a function to every row, after ordering a subset of that row according dependent on an if/else statement. after which populating a new column in the dataframe with the results. i have over two million rows, so a for loop to do this is very inefficient.

given the following dataframe:

df<-as.data.frame(cbind(matrix(LETTERS[1:3], ncol=1),matrix(1:15,ncol=5)))  

is there a way to apply the following loop to each row without a for loop as i actually have over 2630800 rows?

df$num <- 0  df[2:7] <- sapply(df[2:7],as.numeric)  names(df) <- c("first_name", "sec", "A", "B", "C", "D", "num")  

the names of the columns are required for the if statement below:

for (i in 1:nrow(df)) {       row = df[i,3:6]       if (df[i,3]==names(row[order(row)])[4]) {           df$num[i] = row[order(row)][3]/(row[order(row)][3]+row[order(row)][4])       } else {           df$num[i] = row[order(row)][4]/(row[order(row)][3]+row[order(row)][4])       }   }  

such that i get this outcome:

    > df    first_name sec A B  C  D       num  1          A   1 4 7 10 13 0.5652174  2          B   2 5 8 11 14      0.56  3          C   3 6 9 12 15 0.5555556  

i'm not sure how to do this with apply, was thinking something like this? although this does not work and i am not sure how to incorporate the if/else conditions:

df$num <- apply(df, 1, function(x) unlist(x[3:6][order(x[3:6])][3]/(x[3:6][order(x[3:6])][3]+x[3:6][order(x[3:6])][4])))  

Finding statistics, such as the mean, of all entries in a CSV file using Python

Posted: 11 Oct 2021 08:16 AM PDT

I have a CSV file with 170 rows and 255 columns. It represents different pixels on a screen and each one takes a value. I want to calculate the mean over all the pixels/entries but can only find documentation on each row or column. How can I find the mean of the entire file?

Avoid 3 for loops with numpy to have more efficient code

Posted: 11 Oct 2021 08:16 AM PDT

I have developed a code, and I am looking for a more efficient method because it is a lot of slow. Is it possible to modify this code such that it is faster?

The code is really complex to explain, sorry in advance if my explanation is not so satisfactory:

I am working with this big matrix that contains 7 matrices of dimension 50x1000. The code works in this way:

  1. I take the first element of each matrix (contained in the big matrix), creating a list of these elements--> [a1b1, a2b1, ... a7b1]
  2. Once created this list, I interpolate it, creating a new list with 50 elements
  3. Now, I need to repeat the point (1) and (2), but for the first element of second row for all matrices, till the first element of last row.
  4. After finished all the elements of the first column, we can switch to the second column of all matrices and repeat the points (1),(2),(3)

If something is not clear, please tell me, I'll try to explain! enter image description here

import numpy as np  from scipy.interpolate import barycentric_interpolate    matrix = np.random.rand(7, 50, 1000)    X = np.linspace(0.1,0.8,7)  intervals = np.linspace(0.5,1.5,50)    matrix_tot = []  for col in range(len(matrix[0][0])):      matrix_i = []      for row in range(len(matrix[0])):          interp_1 = []          for m in range(len(matrix)):              values = matrix[m][row][col]              interp_1.append(values)          row_interpolated = barycentric_interpolate(X,np.array(interp_1),intervals)          matrix_i.append(row_interpolated)      matrix_tot.append(matrix_i)  matrix_tot = np.array(matrix_tot)  print(matrix_tot.shape)  

TypeError: _modules_vendor_store_index__WEBPACK_IMPORTED_MODULE_3__.default.dispatch is not a function

Posted: 11 Oct 2021 08:16 AM PDT

Im using vuex, i want to execute an action and pass the value of id to the state, i get error(Error in mounted hook: "TypeError: modules_vendor_store_index__WEBPACK_IMPORTED_MODULE_3_.default.dispatch is not a function") and (TypeError: modules_vendor_store_index__WEBPACK_IMPORTED_MODULE_3_.default.dispatch is not a function) file.vue:

      import store from "@/modules/vendor/store/index";            export default {        data() {          return {            id: this.$route.params.id,      }      mounted() {         //let payload = {'id': this.id}         store.dispatch("setVendorId", this.id);      }      }    

actions.js:

        export const setVendorId = ({ commit }, id ) => {           commit("SET_VENDOR_ID", id);        }    

mutations.js:

        export const SET_VENDOR_ID = (state, {data}) => {          state.vendorId = data;           console.log('id vendeur mutation:',state.vendorId )              };    

state.js:

      export default {          vendorClassificationList: [],          vendorId: null,            }  

Multiple Foreign keys in DRF

Posted: 11 Oct 2021 08:15 AM PDT

I am completely new to django and python kindly help me with below query:

I have 3 models , with multiple foreign key relations with given sample data

now I need 3 outputs via django ORM or Serializers

1.for a given student id ,display the Student details and marks in each subjects

2.list all the students with their total marks (sum of three subjects in this case)

3.Average marks scored by all the students for each subject for ex as per the given sample marks in English are 65 , 95 and average is 80

{ Subject :"English", average : " 80" }

class Student(models.Model):          student_id = ShortUUIDField(primary_key=True, editable=False)          first_name = models.CharField(max_length=50)          last_name  = models.CharField(max_length=50)    class Subjects(models.Model):      subject_code = ShortUUIDField(primary_key=True, editable=False)      subject_name = models.CharField(max_length=100)    class Reports(models.Model):      student = models.ForeignKey(Student,on_delete=models.CASCADE,related_name='student_report')      subject = models.ForeignKey(Subjects,on_delete=models.CASCADE,related_name='subject',default=None)      marks   = models.IntegerField(max_length='3')  class Meta:      unique_together = ("student", "subject")  

sample data

Student data    student_id  first_name  last_name    1            abc        x    2            def        y         Subjects data    subject_code  subject_name      1          English      2          Science      3          Math      Reports data     student_id  subject_id  marks        1          1         65       1          2         75       1          3         92       2          1         95       2          2         85       2          3         62  

Securing your Heroku database

Posted: 11 Oct 2021 08:15 AM PDT

I currently have a back end hosted on Heroku, at the minute the data is open and anyone could access it. Is there a way to add some form of authentication to this? For example, if I use an API I am required to use an API key in order to access the data.

I currently have a 'Hobby' database but appreciate i may need to pay a subscription for additional features.

Boto3 is installed but cannot find module RHEL 7

Posted: 11 Oct 2021 08:15 AM PDT

I'm trying to get the AWS-CLI working to start and configure ec2 instances.

I've installed boto3 through pip, pip3 and python install but still can't see boto3.

ImportError: No module named boto3  

I'm running RHEL 7. I've tried several different ways of installing it,

pip install boto3  pip3 install boto3  python3 -m pip install --user boto3  

The first time I ran pip install boto3 it went through the installation output, as it did with pip3 install boto3 but now it just says requirement already satisfied, as it is already installed.

I've installed rh-python36-python-pip then scl enable rh-python36 bash to get pip working, which is working fine.

I've googled and googled and can't find any other answers, since it appears to be installed. Any ideas?

MySQL case when then function causing error

Posted: 11 Oct 2021 08:16 AM PDT

I am trying to use case when condition then function but it is causing error.

Col1  12345  123456  54321  54321  654321  

for this column, I wrote a query

select (case when length(Col1) = 6           then               concat(substring(Col1,1,2),'/',substring(Col1,5,6))           else               concat(substring(Col1,3,5),'/','123')           end) as Col2  from table  

but this is causing an error. I tried it with removing the concat part and just use one substring and it is still causing an error.

Can you take a look at the query and see where the issue is?

Thank you!

Chakra UI Modal component does not work with Array of object

Posted: 11 Oct 2021 08:15 AM PDT

I have an array of object that is mapped through which return chakra's modal component, but it seems that the first child in the array is only returned. it displays the modal corrected but show only the first item in the Array.

import {    Box,    Button,    Modal,    ModalBody,    ModalCloseButton,    ModalContent,    ModalFooter,    ModalHeader,    ModalOverlay,    useDisclosure  } from "@chakra-ui/react";    const courses = [    {      courseTitle: "London",      courseContent:        "Lodon Lorem ipsum, dolor sit amet consectetur adipisicing elit. Tempore deleniti assumenda quas minus, fugiat veniam necessitatibus laborum qui similique dolor!"    },    {      courseTitle: "Geography",      courseContent:        "Geography Lorem ipsum, dolor sit amet consectetur adipisicing elit. Tempore deleniti assumenda quas minus, fugiat veniam necessitatibus laborum qui similique dolor!"    }  ];    export default function () {    const { isOpen, onOpen, onClose } = useDisclosure();    return (      <Box mt={5} display="flex" gridGap={3}>        {courses.map((course, idx) => (          <Box as="section" key={idx}>            <Button onClick={onOpen} size="sm">              {course.courseTitle}            </Button>              <Modal isOpen={isOpen} onClose={onClose}>              <ModalOverlay />              <ModalContent>                <ModalHeader>{course.courseTitle}</ModalHeader>                <ModalCloseButton />                <ModalBody>{course.courseContent}</ModalBody>                  <ModalFooter>                  <Button colorScheme="blue" mr={3} onClick={onClose}>                    Close                  </Button>                </ModalFooter>              </ModalContent>            </Modal>          </Box>        ))}      </Box>    );  }  

Codesandbox: https://codesandbox.io/s/objective-wave-woiek

Firebase PUSH apns-collapse-id not working

Posted: 11 Oct 2021 08:15 AM PDT

I am trying to follow this blog by using apns-collapse-id. But on my IOS device it doesnt overide the previous push like it does with android tag. Below is my payload in post man. Where am I going wrong?

    {   "to" : "token",   "notification" : {       "body" : "Body of Your Notification",       "title": "Run of Your Notification",       "tag":"0",       "thread-id":91,       "apns-collapse-id":91   },    "data" : {       "thread-id":91,       "apns-collapse-id":91   }  }  

auto_arima(... , seasonal=False) but got SARIMAX ��

Posted: 11 Oct 2021 08:16 AM PDT

I want to know the orders (p,d,q) for ARIMA model, so I've got to use pmdarima python package. but it recommends me SARIMAX model! keep reading for more details.
i used Daily Total Female Births Data for this purpose. it's a stationary time series.

# importing packages  import pandas as pd  from pmdarima import auto_arima  import warnings  warnings.filterwarnings('ignore')    # read csv file  df = pd.read_csv('UDEMY_TSA_FINAL/Data/DailyTotalFemaleBirths.csv' , index_col=0 , parse_dates=True)    # set daily frequency for datetime indexes  df.index.freq = 'D'    # now using auto_arima i try to find (p,d,q) orders for ARIMA model.  # so i set seasonal=False because i don't want orders for SARIMA! my  # goal is to find orders for ARIMA model not SARIMA  auto_arima(df['Births'] , start_P= 0 , start_q=0 , max_p=6 ,               max_q=3 , d=None , error_action='ignore' , suppress_warnings=True ,              m=12 , seasonal=False , stepwise=True).summary()  

then it gives me this:
enter image description here

the problem is where although I set seasonal=False but it gives me SARIMAX (which stands for Seasonal Autoregressive Independent Moving Average) but I don't want to consider seasonal component, so I set seasonal=False! seems that pmdarima doesn't pay attention to seasonal=False!

can someone help me to figure out what is the problem?


Expected result:
enter image description here

for False Result: SARIMAX result comes from pmdarima version 1.8.3
for True Result: ARIMA result comes from pmdarima version 1.1.0

How to assign specific ID to Kafka Topic Partition

Posted: 11 Oct 2021 08:15 AM PDT

I am new to Apache Kafka. I want to assign a our user id as id to the topic partition. Is there a way to assign our own user-id to partition. I did research for couple hours on this, but didn't find any article related to assigning an ID to partition.

While publishing a message to Topic I want to use the user-id as key. So that all messages goes into the same partition. And I want to make sure that one partition should contain only one user related messages.

Can I use this user-id in consumers while consuming messages from partition?

Is there a way to achieve this functionality?

JS Array Sorting Using Expression

Posted: 11 Oct 2021 08:15 AM PDT

Is there a way to bring the related object to the first index of the array using sort function?

Here is what I tried using sort only

const arr = [{      id: 'a',      name: 'test name 1'    },    {      id: 'b',      name: 'test name 2'    },    {      id: 'c',      name: 'test name 3'    }  ];    const testId = 'c';      const sortedArr = arr.sort((a, b) => a.id === testId || b.id === testId ? 1 : -1);    console.log(sortedArr); // logs b, a, c but the expected result is c, a, b

Why text insome of my Angular Material component appears to be white?

Posted: 11 Oct 2021 08:16 AM PDT

In some of my mat components, like mat-tab-group, the text appears to be white and invisible. My theme is pink blue-grey. here's the code

<mat-tab-group>      <mat-tab label="First" > Content 1 </mat-tab>      <mat-tab label="Second"> Content 2 </mat-tab>      <mat-tab label="Third"> Content 3 </mat-tab>  </mat-tab-group>  

The image of what's going on:

happening2

When highlighted by the cursor happening1

Invoke a function after the time changes

Posted: 11 Oct 2021 08:16 AM PDT

I'm curious if you can invoke a function after the time changes?

For example invoking a function after the minute changes maybe something like this:

onMinChange(()=>{console.log('the minute has changed!')})  

Note:

I do not mean waiting for a minute to invoke a function like this

setInterval(()=>{console.log('the minute has changed!')},60000);  

there's a difference between

invoking a function after the minute changes (Current time 2:30:05, invoke function at 2:31:00 )

&

X waiting for a minute to invoke a function (Current time 2:30:05, invoke function at 2:31:05 )

Generic bounded argument is incompatible with itself

Posted: 11 Oct 2021 08:15 AM PDT

I'm trying to create a generic method that accepts two typed arguments, one of them bounded by itself,

class Foo  {      <T extends Foo, V> void myself(final Optional<V> value, final BiConsumer<T, V> destination)      {          if (value.isPresent())          {              destination.accept(~~this~~, value.get());          }      }  }  

but compiler blames on the this argument, because

error: incompatible types: Foo cannot be converted to T              destination.accept(this, value.get());                                 ^    where T,V are type-variables:      T extends Foo declared in method <T,V>myself(Optional<V>,BiConsumer<T,V>)      V extends Object declared in method <T,V>myself(Optional<V>,BiConsumer<T,V>)  

If T is a subtype of Foo, I don't understand why this (which is a Foo for sure) cannot be a T.

Forcing the (T) this cast seems to ""work"".

Update

I want to use it the following way,

class Bar extends Foo  {      void setAnswer(Integer toLife)      {      }  }    ----    void outThere(Bar bar)  {      bar.myself(Optional.of(42), Bar::setAnswer);  }  

The proposal of wildcarded argument

class Foo  {      <V> void myself(final Optional<V> value, final BiConsumer<Foo, V> destination)      {          if (value.isPresent())          {              destination.accept(this, value.get());          }      }  }  

fails on the usage with,

error: incompatible types: invalid method reference          bar.myself(Optional.of(42), Bar::setAnswer);                                      ^      method setAnswer in class Bar cannot be applied to given types        required: Integer        found: Foo,V        reason: actual and formal argument lists differ in length    where V is a type-variable:      V extends Object declared in method <V>myself(Optional<V>,BiConsumer<? super Foo,V>)  

Is there a way to keep track of triggered cloud task queues in Google app engine, so I can find out when they are fully executed?

Posted: 11 Oct 2021 08:16 AM PDT

I have a use case which requires me to keep track if all the taskqueues triggered inside a loop are executed or not. Once ALL of the taskqueues are executed(ALL, not a few), only then I can proceed with the next phase of my task. I want to keep track of this in the code itself, not from the Cloud Tasks page in the console.

In this code, I am triggering the taskqueues in this way:-

for item in listA:    execute taskqueue1      inside taskqueue1 function:-    for b in listB:   execute taskqueue2  

I need to find out if all the taskqueues in loops of listA and listB are completed. Is there a way to keep track of the statuses of all the triggered taskqueues?

All taskqueues are push queues.

Return list of weighted objects with semi-randomized ranking

Posted: 11 Oct 2021 08:15 AM PDT

Let's say I have a list of objects (in Python) that looks something like this (contains an identifier and a ranking/weighting):

objects = [      ("object_1", 0.50),      ("object_2", 0.75),      ("object_3", 0.25),      ("object_4", 0.01),      ("object_5", 0.99),  ]  

I would like to return to the caller this same objects array but in semi-randomized order of their weighting. That is, I don't always want to return:

[      ("object_5", 0.99),      ("object_2", 0.75),      ("object_1", 0.50),      ("object_3", 0.25),      ("object_4", 0.01),  ]  

but would instead rather allow for some non-determinism so that, generally speaking, the returned array looks like the above but could also look like:

[      ("object_5", 0.99),      ("object_1", 0.50),      ("object_2", 0.75),      ("object_4", 0.01),      ("object_3", 0.25),  ]  

Calculate time in RStudio (R programming)

Posted: 11 Oct 2021 08:15 AM PDT

Want to start over again. Sorry for confusion.

Two cols as follows:

$ started_at : POSIXct, format: "2020-10-31 19:39:43"

$ ended_at : POSIXct, format: "2020-10-31 19:57:12"

So in order to calculate time (19:57:12 - 19:39:43), want to mutate new column to 00:17:29, where ended_at - started_at

Need to change column format from POSIXct, correct??

Python Script to run power shell script

Posted: 11 Oct 2021 08:15 AM PDT

My requirement is to run the PowerShell script by python. But it is erroring out.

My Python script:

import subprocess, sys    p = subprocess.Popen(["powershell.exe",                 "D:\\Python\\EXPORT_AD_GROUP.ps1"],                 stdout=sys.stdout)  p.communicate()  

Error:

Traceback (most recent call last):    File "D:/Python/Power_Shell_Python.py", line 3, in <module>      p = subprocess.Popen(["powershell.exe",    File "C:\Users\htembkar\AppData\Local\Programs\Python\Python38\lib\subprocess.py", line 804, in __init__  errread, errwrite) = self._get_handles(stdin, stdout, stderr)    File "C:\Users\htembkar\AppData\Local\Programs\Python\Python38\lib\subprocess.py", line 1174, in _get_handles  c2pwrite = msvcrt.get_osfhandle(stdout.fileno())  io.UnsupportedOperation: fileno  

ESP32 compile probem

Posted: 11 Oct 2021 08:16 AM PDT

I am having trouble with my board esp32. It's said that error compiling for esp32 dev module. Please can you help me? I will paste the error message below:

Arduino: 1.8.16 (Windows Store 1.8.51.0) (Windows 10), Board: "ESP32 Dev Module, Disabled, Default 4MB with spiffs (1.2MB APP/1.5MB SPIFFS), 240MHz (WiFi/BT), QIO, 80MHz, 4MB (32Mb), 921600, None"

In file included from C:\Users\Win10\Documents\Arduino\libraries\DHTLib\dht.h:18:0,

             from C:\Users\Win10\Documents\Arduino\libraries\DHTLib\dht.cpp:30:  

C:\Users\Win10\Documents\Arduino\libraries\DHTLib\dht.cpp: In member function 'int dht::_readSensor(uint8_t, uint8_t)':

C:\Users\Win10\Documents\ArduinoData\packages\esp32\hardware\esp32\1.0.6\cores\esp32/Arduino.h:106:91: error: cannot convert 'volatile uint32_t* {aka volatile unsigned int*}' to 'volatile uint8_t* {aka volatile unsigned char*}' in initialization

#define portInputRegister(port) ((volatile uint32_t*)((port)?GPIO_IN1_REG:GPIO_IN_REG))

                                                                                       ^  

C:\Users\Win10\Documents\Arduino\libraries\DHTLib\dht.cpp:116:29: note: in expansion of macro 'portInputRegister'

 volatile uint8_t *PIR = portInputRegister(port);                             ^  

Multiple libraries were found for "WiFi.h"

Used: C:\Users\Win10\Documents\ArduinoData\packages\esp32\hardware\esp32\1.0.6\libraries\WiFi

Not used: C:\Program Files\WindowsApps\ArduinoLLC.ArduinoIDE_1.8.51.0_x86__mdqgnx93n4wtt\libraries\WiFi

exit status 1

Error compiling for board ESP32 Dev Module.

This report would have more information with "Show verbose output during compilation" option enabled in File -> Preferences.

How to implement github like markup converter and add html

Posted: 11 Oct 2021 08:15 AM PDT

I am creating the text editor and I want to implement a GitHub mark like syntax ([text|link]) and convert this to text.

I am using the below code:

let range = timeline.contentWindow.getSelection().getRangeAt(0).toString();        let info = null;        info = range.match(/\[*(.*)\|\s*(.*)]/);        let html =          "<a  href=" +          (info !== null ? info[2] : range) +          ">" +          (info !== null ? info[1] : range) +          "</a>";        innerDoc.execCommand('insertHTML', false, html);  

So I have implemented this on button click but I need to achieve this in keyDown event for example if the user hit enters I want to get the last line and parse the link and add the anchor tag.

Basically i want to implement something like this gif:

gif

Can You guys please help me to achieve this functionality as soon as the user types [text|link] and hits enter?

Keep audio playing with mobile screen off

Posted: 11 Oct 2021 08:16 AM PDT

I'm building a website with HTML5 audio, including custom audio controls and visualization using JavaScript.

When opening the website in my mobile browser (I've only tested Android/Chrome, but I assume similar behavior on other systems), after a few seconds the screen will turn off and soon after the audio will stop playing.

Is there an official way in HTML oder JavaScript to tell the browser to keep the audio playing with screen turned off?

Side information: there is Screen Wake Lock API preventing the mobile screen from turning off. Since my website provides music, I want the phone to turn off the screen if desired, only keep playing the audio.

Module not found: Can't resolve '@date-io/date-fns' in React

Posted: 11 Oct 2021 08:15 AM PDT

I'm using React Material UI and I get this error : Module not found: Can't resolve '@date-io/date-fns'.

Here are the dependencies that I have in my package.json file :

  "version": "0.1.0",    "private": true,    "dependencies": {      "@material-ui/core": "^4.12.1",      "@material-ui/icons": "^4.11.2",      "@material-ui/pickers": "^3.3.10",      "@testing-library/jest-dom": "^5.11.8",      "@testing-library/react": "^11.2.2",      "@testing-library/user-event": "^12.6.0",      "antd": "^4.16.6",      "axios": "^0.21.1",      "bootstrap": "^4.5.3",      "query-string": "^4.3.4",      "react": "^17.0.1",      "react-bootstrap": "^1.4.0",      "react-dom": "^17.0.1",      "react-owl-carousel": "^2.3.3",      "react-router-dom": "^5.2.0",      "react-script-tag": "^1.1.2",      "react-scripts": "4.0.1",      "react-seat-picker": "^1.5.3",      "react-tooltip": "^4.2.21",      "web-vitals": "^0.2.4"    },  

I tried installing these libraries but it keeps showing errors in command prompt

D:\WebSites\site>npm i --save date-fns@next @date-io/date-fns  npm ERR! code ERESOLVE  npm ERR! ERESOLVE unable to resolve dependency tree  npm ERR!  npm ERR! While resolving: site@0.1.0  npm ERR! Found: date-fns@2.0.0-beta.5  npm ERR! node_modules/date-fns  npm ERR!   date-fns@"2.0.0-beta.5" from the root project  npm ERR!  npm ERR! Could not resolve dependency:  npm ERR! peerOptional date-fns@"^2.0.0" from @date-io/date-fns@2.11.0  npm ERR! node_modules/@date-io/date-fns  npm ERR!   @date-io/date-fns@"*" from the root project  npm ERR!  npm ERR! Fix the upstream dependency conflict, or retry  npm ERR! this command with --force, or --legacy-peer-deps  npm ERR! to accept an incorrect (and potentially broken) dependency resolution.  npm ERR!  npm ERR! See C:\Users\Ryan\AppData\Local\npm-cache\eresolve-report.txt for a full report.    npm ERR! A complete log of this run can be found in:  npm ERR!     C:\Users\Ryan\AppData\Local\npm-cache\_logs\2021-08-11T12_31_59_156Z-debug.log  

Is there any simulator for ESP32-S2 or ESP32 chips?

Posted: 11 Oct 2021 08:15 AM PDT

I am working on an esp project and compiled my code by using the esp32s2 toolchain and created a binary that ready to run on a real device. But I don't have a real device to test my binary. Is there any simulator to simulate the ESP32-S2 chip or the ESP32 chip?

Stop javascript increment at a certain value

Posted: 11 Oct 2021 08:15 AM PDT

I have coded this small script which increments a given value, in this case 200, by 1 every 3.2 seconds.

var i = 200;  function increment() {  i++;  document.getElementById('generated').innerHTML = Number(i).toLocaleString('en');  }  setInterval('increment()', 3200);  

I'm trying to make the script stop increasing the value once it reaches a certain point (let's say 300 for example). I'm sure it's a simple fix but I can't think up of how to go about this.

C# HttpClient FormUrlEncodedContent Encoding (VS 2012)

Posted: 11 Oct 2021 08:16 AM PDT

I'm using the HttpClient. I'm posting with web form parameters. One of the values (not name) is a foreign Swedish character ö , #246; ö ASCII: Latin Small Letter O Umlaut

Manually, IE, Firefox and Chrome all convert this character to S%F6k and everything works fine. However VS 2012 C# release converts it (via FormUrlEncodedContent(dict)) to %C3%B6

Is there a way to tell VS 2012 to convert it, to the friendly S%F6k (and still use HttpClient)?

I've attached most of the code, which may help others (cookies, proxy, etc...)

// Create Handler  var handler = new HttpClientHandler();    // Cookies  var cc = new CookieContainer();  handler.CookieContainer = cc;    // Proxy - for fiddler  WebProxy proxy = new WebProxy();  proxy.Address = new Uri("http://localhost:8888");  handler.Proxy = proxy;    // Create the client  var client = new HttpClient(handler);    var request4 = new HttpRequestMessage();    client.DefaultRequestHeaders.Clear();  client.DefaultRequestHeaders.Add("Accept", "text/html, application/xhtml+xml, */*");  client.DefaultRequestHeaders.Add("Accept-Encoding", "gzip, deflate");  client.DefaultRequestHeaders.Add("Accept-Language", "en-US,en;q=0.8,sv-SE;q=0.5,sv;q=0.3");  client.DefaultRequestHeaders.Add("User-Agent", "Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.2; WOW64; Trident/6.0)");    // Form Data  var dict4 = new Dictionary<string, string>  {      { "page", "kantlista" },      { "kod", "A0004n" },      { "termin", "H12" },      { "anmkod", "17113" },      { "urval", "ant" },      { "listVal", "namn" },      { "method", "Sök" } // S%F6k  }; // dict    request4.Content = new FormUrlEncodedContent(dict4);    var value4 = new FormUrlEncodedContent(dict4);  string uri4 = "https://www.ltu.se/ideal/ListaKursant.do";  var response4 = await client.PostAsync(uri4, value4);  response4.Headers.Add("Cache-Control", "no-cache")  response4.EnsureSuccessStatusCode();  string responseBody4 = await response4.Content.ReadAsStringAsync();  

How do I write a procedure that randomly selects a pair from a list?

Posted: 11 Oct 2021 08:16 AM PDT

I'm creating a checkers game and I need a procedure that randomly selects a pair from a list of pairs.

No comments:

Post a Comment