Monday, June 6, 2022

Recent Questions - Stack Overflow

Recent Questions - Stack Overflow


Next JS and Remark, images on same folder

Posted: 05 Jun 2022 06:45 AM PDT

There's a way to make remark use index.md folder to relative load images using nextJS?

I building a website for a college project, and we have a blog, since I want to keep all posts data( markdown content and images folder) in the same folder, for organization and to people who make posts do blog don't mess up with rest of the website.

Folder struct example

【IOS】Monitor volume key, causing multiple calls

Posted: 05 Jun 2022 06:45 AM PDT

I want to do some operations by clicking the volume button. I can do this in the following ways

 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(volumeChangeNotification:)name:@"SystemVolumeDidChange" object:nil];     - (void)volumeChangeNotification:(NSNotification *)notification {    //do something   }  

But I found a puzzling phenomenon. Click the volume key once, and the monitoring event will be called twice. I try to delete the listener at the end of the listener function ,like this

[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(volumeChangeNotification:)name:@"SystemVolumeDidChange" object:nil];    - (void)volumeChangeNotification:(NSNotification *)notification {  //do something  [[NSNotificationCenter defaultCenter] removeObserver:self name:@"SystemVolumeDidChange" object:nil];  }  

Then I turn on the monitor after 1 second, but it also doesn't work. What should I do?thanks verymuch

Use a conda environment activation alias

Posted: 05 Jun 2022 06:44 AM PDT

To activate my Conda environment I have got to type conda activate /Users/ioannis/miniforge3/envs/env_tf but I would like to only have to type conda activate env_tf. I have tried the solution here but it has not worked. Any ideas?

May be a bug? Where can I find the meaning of parameter in docplex?

Posted: 05 Jun 2022 06:44 AM PDT

when I want to search the meaning of parameter value in docplex, it seems to go wrong. The following is the code:

from docplex.mp.model import Model  import cplex  model_do = Model()      # the following two lines work well  '''   the output of first line:    'method for linear optimization:\n  0 = automatic\n  1 = primal simplex\n  2 = dual simplex\n  3 = network simplex\n  4 = barrier\n  5 = sifting\n  6 = concurrent optimizers'  the output of second line:    class NumParameter(Parameter)       |  NumParameter(env, about, parent, name, constants=None)       ...  '''  cplex.Cplex().parameters.lpmethod.help()  help(cplex.Cplex().parameters.lpmethod)      # however, when it comes docplex, sth goes wrong  '''   the output of first line:    Traceback (most recent call last):    File "<input>", line 1, in <module>    AttributeError: 'IntParameter' object has no attribute 'help'  the output of second line:    class IntParameter(Parameter)     |  IntParameter(group, short_name, cpx_name, param_key, description, default_value, min_value=None, max_value=None, sync=False)     ...  '''  model_do.parameters.lpmethod.help()  help(model_do.parameters.lpmethod)  

my question are:

1.the parameters values' meanings in docplex are truly the same as in cplex?

2.If the answer of question.1 is "no", where can I search for the parameters values' meanings in docplex?

Github personal notifications are not working as expected

Posted: 05 Jun 2022 06:44 AM PDT

I use one github account for both my open source contribution and for work which has it's own organisation.

At the notifications page https://github.com/notifications I get notifications only from organisation. I don't get notification if someone raises a PR against any of my repos, or if anyone has commented to any of the issues I had raised in any public repo.

What should I do so that I get all notifications?

Thanks

Frequenty table for intervals in Rstudio

Posted: 05 Jun 2022 06:44 AM PDT

I saved my data into datos so I could use it. I calculated AF and RF using table but I don't know hot to calculate it in intervals. histograma has everything to calculate them but I need some help. Thanks. Here is my code
read.table("datos.txt", header = FALSE)-> datos
largo<-length(datos$V1)
k<- (1+log2(largo))
k<-round(k,digits = 0)
vectordatos <- datos$v1
histograma<-hist(datos$V1,breaks=k)

FA<-table(datos$V1)
FR<-table(datos$V1)/largo
FA
FR
intervalos<-histograma$breaks

dput(datos)     structure(list(V1 = c(6.16, 5.83, 5.66, 3.63, 1.38, 9.64, 7.46,   5.34, 7.93, 8.5, 4.18, 5.18, 10.27, 5.41, 4.76, 4.67, 10.02,   7.1, 5.38, 8.55, 4.85, 8.28, 2.9, 7.18, 6.54, 5.66, 7.26, 6.45,   3.97, 6.55, 5.15, 7.83, 5.52, 7.21, 7.3, 6.19)), class = "data.frame", row.names = c(NA,   -36L))  

React App.js renders before fetching data from the Context API

Posted: 05 Jun 2022 06:44 AM PDT

That's my context API fetch function that fetch data from the API

  const fetchQuestions = async(url) =>{      setLoading(true)      setWaiting(false)      try {        const response = await fetch(url)        const dataJson = await response.json()        if(response){          const data = dataJson.results          if(data.length > 0){            setQuestions(data)            setLoading(false)            setWaiting(false)            setError(false)          } else{            setWaiting(true)            setError(true)          }         } else{          setWaiting(true)        }        } catch (error) {         console.log(error)      }       }    

And that's the return value from the context API function

return <AppContext.Provider value={{            waiting,            loading,            form,            questions,            index,            correctAns,            modal,            error,            nextQuestion,            checkAnswer    }}    >      {children}      </AppContext.Provider>  

Then in App.js i am destructing my values from the context API

  const{waiting, loading,form,questions, index, correctAns, modal, error, nextQuestion } = useGlobalContext()  

Then if i try to use the questions array inside App.js it's represented as an empty array because it's rendered before the fetch is done while i put conditions in my context API to make sure that there is a response from the API call

const fetchQuestions = async(url) =>{      setLoading(true)      setWaiting(false)      try {        const response = await fetch(url)        const dataJson = await response.json()        if(response){          const data = dataJson.results          if(data.length > 0){            setQuestions(data)            setLoading(false)            setWaiting(false)            setError(false)          } else{            setWaiting(true)            setError(true)          }         } else{          setWaiting(true)        }              } catch (error) {         console.log(error)      }       }    

Now i have 2 console logs in App.js, the same 2 logs are printing twice first log is before data are fetched and second log is after data are fetched

And that's the console log in App.js

  console.log(questions)    console.log(questions[0])  

Now if i try to extract some properties out of the questions array it's rendered as an empty array as the first console log, how i can stop this behaviour in my App?

const { question, incorrect_answers, correct_answer, } = questions[0];    

I need it to render as the second console log i tried to add the questions array as a dependency in my use effect but it still not working and actually didn't fetch the resources from API

  useEffect(() => {      fetchQuestions(`${tempUrl}`)    }, [questions])  

How can i make my App.js file renders only after fetching resources from the context API fetch function so that i have values in my questions array ?

PS: this is my first question on stack overflow so if there is a better way to ask my questions please don't hesitate to write it down in order to be able to get more efficient answers and write easy to understand and clear questions, Thank you

Unable to produce animated gifs using with_slider_draw()

Posted: 05 Jun 2022 06:43 AM PDT

Using wxMaxima v19.05.7 on osx 13.6/15.7 I have no problems creating animated gifs using with_slider(). E.g.

with_slider(     t,     makelist(i,i,0,%e,0.05),     [sin(x+t), cos(x+t)], [x,0,5]  )$  

works as expected. However, if I want to plot the function graphs with with_slider_draw()

with_slider_draw(      t,      makelist(i,i,0,%e,0.05),      explicit(sin(x+t),x,0,5)  )$e  

I get error messages like:

Wxmaxima Error  cant't open file '~/tmp/maxout_4856_55.png'  Error 2. No such file or directory.  

and the place-holder for the inline graphics within wxMaxima saying

Error: cannot render ~/tmp/maxout_4856_55.png  

There are indeed no maxout_4856_[01-55].png-files in ~/tmp/ . The corresponding gnuplot files data4856.gnuplot and maxout4856.gnuplot however are produced.

What is going wrong here?

  1. Why are no graphic files produced?
  2. Why does wxMaxima ask for png-files?

Any help appreciated.

Cheers, Tilda

Can someone please help me to group the customer and amount from my struct, by amount

Posted: 05 Jun 2022 06:43 AM PDT

package main

import "fmt"

type Order struct { Customer string Amount int }

func GroupBy[T any, U comparable](col []T, keyFn func(T) U) map[U][]T { grMap := make(map[U][]T) return grMap }

func main() {

results := GroupBy([]Order{      {Customer: "John", Amount: 1000},      {Customer: "Sara", Amount: 2000},      {Customer: "Sara", Amount: 1800},      {Customer: "John", Amount: 1200},  }, func(o Order) string {      return o.Customer  })    fmt.Println(results)  

}

Error while changing the angular version completely

Posted: 05 Jun 2022 06:43 AM PDT

let me explain, the reason, as i was using angular cli 14 latest and i was hoping to install @angular/fire, which was giving some error due to version incompatibility this ng version was

 _                      _                 ____ _     ___      / \   _ __   __ _ _   _| | __ _ _ __     / ___| |   |_ _|     / △ \ | '_ \ / _` | | | | |/ _` | '__|   | |   | |    | |    / ___ \| | | | (_| | |_| | | (_| | |      | |___| |___ | |   /_/   \_\_| |_|\__, |\__,_|_|\__,_|_|       \____|_____|___|                  |___/          Angular CLI: 14.0.0  Node: 16.13.2  Package Manager: npm 8.1.2   OS: win32 x64    Angular: 14.0.0  ... animations, cli, common, compiler, compiler-cli, core, forms  ... platform-browser, platform-browser-dynamic, router    Package                         Version  ---------------------------------------------------------  @angular-devkit/architect       0.1400.0  @angular-devkit/build-angular   14.0.0  @angular-devkit/core            14.0.0  @angular-devkit/schematics      14.0.0  @angular/fire                   0.0.0  @schematics/angular             14.0.0  rxjs                            7.5.5  typescript                      4.7.2  


Since previously I did used @angular/fire but with the angular cli 9.1.7

     _                      _                 ____ _     ___      / \   _ __   __ _ _   _| | __ _ _ __     / ___| |   |_ _|     / △ \ | '_ \ / _` | | | | |/ _` | '__|   | |   | |    | |    / ___ \| | | | (_| | |_| | | (_| | |      | |___| |___ | |   /_/   \_\_| |_|\__, |\__,_|_|\__,_|_|       \____|_____|___|                  |___/          Angular CLI: 9.1.7  Node: 16.13.2  OS: win32 x64    Angular: 9.1.9  ... animations, common, compiler, compiler-cli, core, forms  ... platform-browser, platform-browser-dynamic, router  Ivy Workspace: Yes    Package                           Version  -----------------------------------------------------------  @angular-devkit/architect         0.901.7  @angular-devkit/build-angular     0.901.7  @angular-devkit/build-optimizer   0.901.7  @angular-devkit/build-webpack     0.901.7  @angular-devkit/core              9.1.7  @angular-devkit/schematics        9.1.7  @angular/cli                      9.1.7  @angular/fire                     6.0.0  @ngtools/webpack                  9.1.7  @schematics/angular               9.1.7  @schematics/update                0.901.7  rxjs                              6.5.5  typescript                        3.8.3  webpack                           4.42.0  

so i was hoping to switch my current dependencies and version with the above one
Basically what I done is
i deleted the package-lock.json and copy paste the cli 9.1.0 package.json content to the current one...then i deleted the node modules and run the command npm install
i was getting errors...lot of ...kindly help that where i gone wrong or if their is a better way

InheritableThreadLocal variable value not inherited by child thread

Posted: 05 Jun 2022 06:43 AM PDT

I am trying to execute the below code:

public class Basecl  {        public static InheritableThreadLocal<Integer> myValue = new InheritableThreadLocal<Integer>();            public void setMyValue(Integer i)      {          myValue.set(i);      }        public Integer getMyValue()      {          return myValue.get();      }        @BeforeClass      public void bClass(ITestContext context, XmlTest xt)      {          System.out.println("Before Class called - " + context.getName() + " - " + this.getClass().getName() + " - " +  "Thread id: " + Thread.currentThread().getId());          setMyValue(12);      }        @BeforeMethod      public void bmeth1(ITestContext context, XmlTest xt, Method m, Object a[], ITestResult itr)      {          System.out.println("Before Method called - " + context.getName() + " - " + this.getClass().getName() + " - " + m.getName() + " - " + "Thread id: " + Thread.currentThread().getId());      }        @AfterMethod      public void ameth1(ITestContext context, XmlTest xt, Method m, Object a[], ITestResult itr)      {          System.out.println("After Method called - " + context.getName() + " - " + this.getClass().getName() + " - " + m.getName() + " - " + "Thread id: " + Thread.currentThread().getId());      }    }  

The above class is inherited by the test class:

public class TC_009 extends Basecl  {        @Test      public void tCase3(ITestContext context, XmlTest xt)      {          System.out.println("My Value in testcase 3 is : " + getMyValue());      }        @Test      public void tCase4(ITestContext context, XmlTest xt)      {          System.out.println("My Value in testcase 4 is : " + getMyValue());      }    }  

I am executing the above test methods in parallel. As per my understanding the value of the inheritable thread-local variable can be accessed by the child threads. But when I execute the above test class, I observed that in the test method tcase4, the value of inheritable threadlocal variable myValue is null. As per my understanding the "BeforeMethods" and the "test methods" are the child threads of the BeforeClass method.

Below is the output:

Before Class called - Test1 - testing.TC_009 - Thread id: 12  Before Method called - Test1 - testing.TC_009 - tCase3 - Thread id: 11  Before Method called - Test1 - testing.TC_009 - tCase4 - Thread id: 12  tCase4 called  tCase3 called  My Value in testcase 4 is : 12  My Value in testcase 3 is : null  After Method called - Test1 - testing.TC_009 - tCase4 - Thread id: 12  After Method called - Test1 - testing.TC_009 - tCase3 - Thread id: 11  

So, why the value of inheritable threadlocal variable myValue is null ?

Build polynomial function from a set of intervals denoting y >= 0

Posted: 05 Jun 2022 06:43 AM PDT

I have a set of ordered, non-overlapping intervals that do not share boundaries, e.g.:

long[][] intervals = new long[][]{      new long[]{ 2, 3 },      new long[]{ 5, 10 },      new long[]{ 25, 1200 },      ...  }  

Currently I use a binary search algorithm to find out if value x is contained by one of the ranges. This is a lot CPU work and involves looping over ranges.

My idea is now to form a polynomial function where y >= 0 exactly when one interval contains the value x and y < 0 if not. This function can be calculated up front and be reused: I pass any x and can use the resulting y to see if it is fine or not.

Advantages I expect over the binary search:

  • If I have a limited set of ranges I can prepare the function to be reused over multiple x where when using the binary function I would need to run it again for every `x´ again.
  • Only one if (for deciding if smaller than 0 or not)

How can I build such polynomial function given a set of intervals?

postgresql lob issue with hibernate on jboss

Posted: 05 Jun 2022 06:43 AM PDT

Let's say that I have a column longText defined in my entity as

@Lob  private String longText  

The same is generated in the database as text column type.

I am trying to select all entries in the table where this column is defined, postgres 13. For which I have added a CustomDialect extending org.hibernate.dialect.PostgreSQL95Dialect

Here is the snippet from my CustomDialect of Postgres.

@Override      public SqlTypeDescriptor getSqlTypeDescriptorOverride(int sqlCode) {          switch (sqlCode) {              case Types.CLOB: { //@Lob annotation to String                  return LongVarcharTypeDescriptor.INSTANCE;              }              default: {                  return super.getSqlTypeDescriptorOverride(sqlCode);              }          }      }  
        at org.jboss.as.ee.component.ComponentStartService$1.run(ComponentStartService.java:57)          at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511)          at java.util.concurrent.FutureTask.run(FutureTask.java:266)          at org.jboss.threads.ContextClassLoaderSavingRunnable.run(ContextClassLoaderSavingRunnable.java:35)          at org.jboss.threads.EnhancedQueueExecutor.safeRun(EnhancedQueueExecutor.java:1982)          at org.jboss.threads.EnhancedQueueExecutor$ThreadBody.doRunTask(EnhancedQueueExecutor.java:1486)          at org.jboss.threads.EnhancedQueueExecutor$ThreadBody.run(EnhancedQueueExecutor.java:1377)          at java.lang.Thread.run(Thread.java:748)          at org.jboss.threads.JBossThread.run(JBossThread.java:485)  Caused by: java.lang.IllegalStateException: WFLYEE0042: Failed to construct component instance          at org.jboss.as.ee.component.BasicComponent.constructComponentInstance(BasicComponent.java:163)          at org.jboss.as.ee.component.BasicComponent.constructComponentInstance(BasicComponent.java:134)          at org.jboss.as.ee.component.BasicComponent.createInstance(BasicComponent.java:88)          at org.jboss.as.ejb3.component.singleton.SingletonComponent.getComponentInstance(SingletonComponent.java:127)          at org.jboss.as.ejb3.component.singleton.SingletonComponent.start(SingletonComponent.java:141)          at org.jboss.as.ee.component.ComponentStartService$1.run(ComponentStartService.java:54)          ... 8 more  Caused by: javax.ejb.EJBException: javax.persistence.PersistenceException: org.hibernate.HibernateException: Unable to access lob stream          at org.jboss.as.ejb3.tx.CMTTxInterceptor.invokeInOurTx(CMTTxInterceptor.java:264)          at org.jboss.as.ejb3.tx.CMTTxInterceptor.requiresNew(CMTTxInterceptor.java:412)          at org.jboss.as.ejb3.tx.LifecycleCMTTxInterceptor.processInvocation(LifecycleCMTTxInterceptor.java:68)          at org.jboss.invocation.InterceptorContext.proceed(InterceptorContext.java:422)          at org.jboss.as.weld.injection.WeldInjectionContextInterceptor.processInvocation(WeldInjectionContextInterceptor.java:43)          at org.jboss.invocation.InterceptorContext.proceed(InterceptorContext.java:422)          at org.jboss.as.ejb3.component.interceptors.CurrentInvocationContextInterceptor.processInvocation(CurrentInvocationContextInterceptor.java:41)          at org.jboss.invocation.InterceptorContext.proceed(InterceptorContext.java:422)          at org.jboss.as.ee.concurrent.ConcurrentContextInterceptor.processInvocation(ConcurrentContextInterceptor.java:45)          at org.jboss.invocation.InterceptorContext.proceed(InterceptorContext.java:422)          at org.jboss.invocation.ContextClassLoaderInterceptor.processInvocation(ContextClassLoaderInterceptor.java:60)          at org.jboss.invocation.InterceptorContext.proceed(InterceptorContext.java:422)          at org.jboss.as.ejb3.component.singleton.StartupCountDownInterceptor.processInvocation(StartupCountDownInterceptor.java:25)          at org.jboss.invocation.InterceptorContext.proceed(InterceptorContext.java:422)          at org.jboss.invocation.ChainedInterceptor.processInvocation(ChainedInterceptor.java:53)          at org.jboss.as.ee.component.BasicComponent.constructComponentInstance(BasicComponent.java:161)    

I can see in my logs that my Dialect is taken my Hibernate but the problem is that the switch statement, writtern in my customdialect is never reached

I am using Hibernate Core {5.3.20.Final-redhat-00001} on Jboss 7.3.

How do i give ID numbers a consecutive number in SPSS

Posted: 05 Jun 2022 06:44 AM PDT

Question about SPSS i have a dataset of different firms with their year of observation and other relevant information.

How do i sort the data by ID number and then add consecutive numbers based on the observation year?

For example if the data looks like this:

ID number Year of observation

ABC 2004 ABC 2005 ABC 2006 ABC 2007 DEF 2005 DEF 2006

How can i do this in SPSS? ID number Year of observation Observation number ABC 2004 1 ABC 2005 2 ABC 2006 3 ABC 2007 4 DEF 2005 1 DEF 2006 2

Trying to detect switch change using Verilog

Posted: 05 Jun 2022 06:43 AM PDT

Intention

I want to make a whackamole module using Verilog, to finish this, I would like to use 10 switches as the input signal for the user to hit the gopher, and if the signal occurs (switch status 0->1 or 1->0) and the corresponding LED lights up (only one LED will lights up in each cycle, and each cycle is 1 sec) , score counter plus 1.

Part of my variable

Below is some of my variable.

input [9:0]SW;                // 10 switch input as an array  output reg[9:0] LED;          // 10 LED output as an array  reg [5:0] score;              // the score counter, in the beginning initialize to 0  reg [4:0] clk;                // this clk is a 1 Hz clock  

Why can't I do this?

After done this, the score counter just random jump to different value. What should I do to fix?

always@(SW[0])begin           // if switch 0 goes from 0 to 1 or 1 to 0      if(LED[0])                // if LED lights up      begin      score=score+1;            // score counter +1      end  end   

Given a point in a square determine what diagonal half it is in?

Posted: 05 Jun 2022 06:44 AM PDT

Diagram

Given this diagram and assuming the square is normalized to (0,0) to (1,1), if I have any arbitrary point (P) inside the square how would I determine which diagonal half it is in? The algorithm should simply return true if in the A half, false if in the B half. I know there's an approach knowing that it is right angle triangles and using some trig you could derive the formula but my maths are not that good. Any help would be much appreciated! I feel like this is an already solved problem but can't seem to find any info or even how to search for it, thanks

Safari 15.5 (17613.2.7.1.8) Http/3 on Apple macOS Silicon

Posted: 05 Jun 2022 06:44 AM PDT

Sorry, does anybody observe the issue that http/3 does not work on macOS Safari 15.5 (17613.2.7.1.8) Apple Silicon? Http/3 is enabled in 'Experimental Features', browser is restarted but this:

https://cloudflare.com/cdn-cgi/trace  

Still shows http=http/2

I did the same settings on iPadOS and iOS (v.15.5) and it works fine: Cloudflare shows http=http/3

This can be related not only to Silicon (M1/M1 Pro/M1 Max) - I just don't know.

Maybe someone knows why this happens?

Thanks.

Value of type 'name' has no dynamic member 'name' using key path from root type 'name'

Posted: 05 Jun 2022 06:44 AM PDT

I am learning MVVM and applying it to a simple converter app. The problem arises when I try to pass the array into a picker with ForEach. Here is my code:

Model:

struct UserOptions {      var userOption = 0.0      var userChoseInput = "Meters"      var userChoseOutput = "Feets"      var userUnits = ["Meters", "Kilometers", "Feets", "Yards"]  }  

ViewModel:

class ViewModel: ObservableObject {  @Published var options = UserOptions()  var finalResult: Double {...calculations here...}  }  

View:

struct ContentView: View {    @StateObject private var viewModel = RulerViewModel()    var body: some View {      Form {          Section {              Picker("What is your input?", selection: $viewModel.userChoseInput) {                  ForEach($viewModel.userUnits, id: \.self) { _ in //Value of type 'ObservedObject<ViewModel>.Wrapper' has no dynamic member 'userUnits' using key path from root type 'ViewModel'                      Text($viewModel.userChoseOutput)                    }              }              .pickerStyle(.segmented)          } header: {              Text("Choose your input")          }          .textCase(nil)                              Section {              TextField("Your number", value: $viewModel.userOption, format: .number)                  .keyboardType(.decimalPad)                  .focused($userValueIsFocused)          }          Section {              Picker("What is your output?", selection: $viewModel.userChoseOutput) {                  ForEach($viewModel.userUnits, id: \.self) { _ in                      Text(viewModel.userChoseOutput)  //Value of type 'ObservedObject<ViewModel>.Wrapper' has no dynamic member 'userUnits' using key path from root type 'ViewModel'                  }              }              .pickerStyle(.segmented)          }             

Unable to convert example of `useSwr` hook to use `react-query`'s `useMutation` hook?

Posted: 05 Jun 2022 06:43 AM PDT

I tried changing the useSwr hook to use:

import { useMutation } from 'react-query';    const { data: user, mutate: mutateUser } = useMutation<User>('/api/user');  

But I get an error stating:

No mutationFn found

Unable to solve this. I tried adding mutationFn inside useMutation like but it is static:

const { data: user, mutate: mutateUser } = useMutation<User>('/api/user', {      mutationFn: () => {        const u: User = {          isLoggedIn: false,          avatarUrl: '',          login: '',        }        return Promise.resolve(u)      },    })  

If I use a dynamic request using something like axios then do I need to put the fetchJson from login.tsx to mutationFn hook?

Basically, I want to use react-query instead of swr & unable to find a solution?

I'm pretty sure it's really simple but haven't been able to make it work.

Stackblitz Demo → https://stackblitz.com/edit/next-iron-session-with-react-query?file=lib%2FuseUser.ts (go to /login route, enter a github username like vvo & click Login to see the error in console)

Repo → https://github.com/deadcoder0904/next-iron-session-with-react-query

Saving char's recursive and display them backwards

Posted: 05 Jun 2022 06:44 AM PDT

My problem is,

I have to use recursion to read in characters and save them. If the read in character is a 'x' or 'X', all the characters i typed in so far should be displayed backwards on the display screen.

f.e.

character1: a

character2: c

character3: 7

character4: x

the "word" is: x7ca

How can I "save" the characters recursive and print them out backwards without using an array?

Thank you i.a.

How to group file names in a directory using the file name extensions with python?

Posted: 05 Jun 2022 06:44 AM PDT

I am trying to group files in a directory according to their extensions using a dictionary but my code is not behaving as expected. I have several video files ending with .mp4, I have a script that gets the extension of the file and then checks if it exists as a key in the dictionary.

NB:

Dictionary holds extensions as keys and all the files with the extension as items.

If extension exists as a key in the dictionary then it adds the current file name to the items associated with that key. If it does not exist then a new key entry is created in the dictionary with null items. My code is printing the elements of the dictionary like below

'.mp4': 'Edited_20220428_154134.mp4', '.png': 'folder_icon.png',  

You can see from the above output that my code does has the extensions as keys but for the videos it only contains a single item when there are several videos in that folder, I need help to make it key the extensions and add all the file names with that extension to the items associated with that key. Below is my code

#import the os module  import os  # define the path to the documents folder  path = "C:\\Users\\USER\\Documents"  # list all the files in the directory  files = os.listdir(path)  # sort the files lexicographically  files.sort()  # code to ask user to choose file operation, in this context user chooses group by extension  # code omitted for MRE purposes  print("Grouping the files by extension")  # initialize the dictionary for holding the extension names  extensions = {}  # iterate through each file name and split the name to get file name and extension as a tuple  for file in files:      ext = os.path.splitext(file)[1]      if ext not in extensions.keys():  # if the key extension does not exist add the key to the dict as a new entry         extensions[ext] = file      else:  # if the extension already append the item to the key items          extensions[ext] = file  #print the dict to check if the operation was succesful  print(extensions)  

columns datatype with bash

Posted: 05 Jun 2022 06:44 AM PDT

I need to get the datatype of each of my columns in a csv file.

I have already managed to install xsv and run the following statement:

xsv stats insurance.csv | xsv select type  

It works directly in the terminal, however I can't execute that command on my a.sh file. When executing:

./a.sh -v  

I get the following error:

./a.sh: line 13: xsv: command not found  

My script is the following:

url=https://raw.githubusercontent.com/stedy/Machine-Learning-with-R-datasets/master/insurance.csv  filename='insurance.csv'  wget -O $filename $url  while getopts ":v" option; do     case $option in     #show file type        v) file $filename            #show columns datatype           xsv stats insurance.csv           exit;;     esac  done  #Show URL  echo "The file was downloaded from $url"  #Show number of rows  echo "Number of rows:"  wc -l < $filename  #show number of columns  echo "Number of columns:"  head -n1 $filename | grep -o ',' | wc -l  

Any idea how can run a xsv command from .sh?

Thank you

Rust iterator generics question, can't compile

Posted: 05 Jun 2022 06:44 AM PDT

im trying to use generics for iterators in traits, and have hard time understanding why it does not compile...

struct B {      values: Vec<(i64, i64)>  }    pub trait IterableCustom {      fn get_iterator<'a, I>(&self) -> I          where I: Iterator<Item=&'a (i64, i64)>;  }    impl IterableCustom for B {      fn get_iterator<'a, I>(&self) -> I          where I: Iterator<Item=&'a (i64, i64)> {          let rev = self.values.iter().rev();          rev      }  }  

It does throw an error

Compiling playground v0.0.1 (/playground)  error[E0308]: mismatched types    --> src/lib.rs:16:9     |  13 |     fn get_iterator<'a, I>(&self) -> I     |                         -            - expected `I` because of return type     |                         |     |                         this type parameter  ...  16 |         rev     |         ^^^ expected type parameter `I`, found struct `Rev`     |     = note: expected type parameter `I`                        found struct `Rev<std::slice::Iter<'_, (i64, i64)>>`  

Area of object in binary image by using matlab

Posted: 05 Jun 2022 06:44 AM PDT

How do I calculate each of the areas of the white region inside the bounding boxes, and label the output on the bounding box by using Matlab?

binary1

How can I have my specific format using Object.entries?

Posted: 05 Jun 2022 06:43 AM PDT

I have these data from my api (1) and the format I want to have is this one(2), how can I do that in my front-end using Object.entries in REACT, in such a way I can modify my (1) to have (2) please ? I tried but not working...

(1):

  {          "myData": [              {                  "Peter": 12,                  "Donald": 15,                  "Huston": 65              }          ],          "myOtherData": [              {                  "location": "Dublin",                  "country":"Irland"              }          ]      }  

(2):

{          "myData": [              {                  "name": "Peter",                  "age": "12"              },              {                  "name": "Donald",                  "age": "15"              },              {                  "name": "Huston",                  "age": "65"              }          ],          "myOtherData": [              {                  "location": "Dublin",                  "country":"Irland"              }          ]      }  

I was thinking using destructuration like this :

const d= {myData, myOtherData}  const newData = Object.entries(...)//change myData here ??  

How to deal with many incoming UDP packets when the server has only 1 UDP socket?

Posted: 05 Jun 2022 06:43 AM PDT

When a server has only 1 UDP socket, and many clients are sending UDP packets to it, what would be the best approach to handle all of the incoming packets?

I think this can also be a problem with TCP packets, since there's a limited thread count, which cannot cover all client TCP socket receive events.

But things are better in this situation because there's 1 TCP socket per client, and even if the network buffer is full, packet receiving is blocked until the queue has space (let me know if I'm wrong).

UDP packets, however, are discarded when the buffer is full, and there's only 1 socket, so the chances of that happening are higher.

How can I solve this problem? I've searched for a while, but I couldn't get a clear answer. Should I implement my own queueing system? Or just maximize the network buffer size?

Plot don't refresh when slider updated matplotlib

Posted: 05 Jun 2022 06:43 AM PDT

I can't figure out why the plot don't refresh when the slider is updated. I'm using Jupiter notebook and I choose the backend with 'nbAgg' parameter.

Initialization code :

import numpy as np  import matplotlib.pyplot as plt  import matplotlib.animation as animation  from matplotlib import use as m_use  m_use('nbAgg')  x1 = np.random.normal(-2.5, 1, 10000)  x2 = np.random.gamma(2, 1.5, 10000)  x3 = np.random.exponential(2, 10000)+7  x4 = np.random.uniform(14,20, 10000)  fig, ((ax1, ax2), (ax3, ax4)) = plt.subplots(2, 2,figsize=(7, 5))  plt.subplots_adjust(left=0.1,right=.8)  

There is a animation which lunch this function :

def updateData(curr,divider=7):      global ax1, ax2, ax3, ax4      for ax in (ax1, ax2, ax3, ax4):          ax.cla()      if curr <= 679 :          my_b = int(np.around(curr/divider)+3)      else : my_b = 100            multi = 100      ax1.hist(x1[:curr*multi],bins=my_b)      ax2.hist(x2[:curr*multi],bins=my_b)      ax3.hist(x3[:curr*multi],bins=my_b)      ax4.hist(x4[:curr*multi],bins=my_b)      fig.suptitle('Frame {} on 100'.format((curr+1)))      return None  

The animation :

simulation = animation.FuncAnimation(fig=fig, func=updateData, frames=10,                                       blit=False, interval=1, repeat=False)  

Here the slider which stuck me :

slider = plt.axes([.9, 0.45, 0.01, 0.3])  slider = Slider(ax=slider,label='Divider \nfor bins',valmin=1,valmax=15, valinit=7, orientation='vertical',valfmt='%.0f',track_color='black',facecolor='red',                    handle_style={'facecolor':'k','edgecolor':'#86a2cf','size':20})  def update():            anim_2 = animation.FuncAnimation(fig=fig, func=updateData, frames=20,                                       blit=False, interval=1, repeat=False)      

This function don't work as expected

slider.on_changed(update)    simulation = animation.FuncAnimation(fig=fig, func=updateData, frames=10,                                       blit=False, interval=1, repeat=False)  plt.show()  

Kill process by filename

Posted: 05 Jun 2022 06:43 AM PDT

I have 3 instances of application running from different places. All processes have similar names.

How can I kill process that was launched from specific place?

No comments:

Post a Comment