Monday, May 10, 2021

Recent Questions - Stack Overflow

Recent Questions - Stack Overflow


I am new to C++ and I want to know how to optimise this code further

Posted: 10 May 2021 08:13 AM PDT

I am new to C++ and I have to optimise this code so that it gets executed within 1.5 secs for Input values upto 10^6. But this code takes 3.52 seconds for input 10^6 to get executed.

I had tried a lot and came up with this code.

#include <iostream>  #include <iostream>  #include <vector>  #include <bits/stdc++.h>  #include <iterator>  #include <utility>  using namespace std;  #include <boost/multiprecision/cpp_int.hpp>  using boost::multiprecision::cpp_int;    using namespace std;      static cpp_int gcd(cpp_int a, cpp_int b)      {          // Everything divides 0          if (a == 0)            return b;          if (b == 0)            return a;                  // base case          if (a == b)              return a;                  // a is greater          if (a > b)              return gcd(a-b, b);          return gcd(a, b-a);      }         int main() {                  ios_base::sync_with_stdio(false);      cin.tie(NULL);           cpp_int t,ans;      std::cin >> t;      while(t-->0) {          cpp_int k;          std::cin >> k;          cpp_int limit=(2*k)+1;          ans=0;                    vector<cpp_int> g1;              for (int i = 1; i <= limit; ++i)          g1.push_back(k+(i*i));                          for (int i =0; i<=(2*k)-1; ++i)          {              ans+=gcd(g1[i],g1[i+1]);          }                         std::cout << ans << std::endl;                                    }      return 0;  }        

Constraints --> 1 ≤ t ≤ 10^6 & 1 ≤ k ≤ 10^6

Paging 3 keeps doing api calls without reaching the end of recyclerview

Posted: 10 May 2021 08:13 AM PDT

Paging 3 keeps doing api calls without reaching the end of recyclerview i tired to change page size to 15 but still the same does using base paging source could lead to any problem? this is the XML of the view

<androidx.swiperefreshlayout.widget.SwipeRefreshLayout       android:id="@+id/stl"      android:layout_width="match_parent"      android:layout_height="match_parent">        <RelativeLayout          android:layout_width="match_parent"          android:layout_height="match_parent">            <androidx.recyclerview.widget.RecyclerView              android:layout_width="match_parent"              android:layout_height="match_parent"              android:clipToPadding="false"              android:descendantFocusability="blocksDescendants"              android:paddingStart="8dp"              android:paddingTop="8dp"              android:paddingEnd="8dp"              android:paddingBottom="80dp" />  

base adapter

abstract class BasePagingAdapter<T : Any, VH : BasePagingAdapter.BaseViewHolder<T>>(diffCallback: DiffUtil.ItemCallback<T>) :      PagingDataAdapter<T, VH>(diffCallback) {          override fun onBindViewHolder(holder: VH, position: Int) {          getItem(position).let { data -> holder.bindData(data!!) }      }        abstract class BaseViewHolder<T>(view: View) : RecyclerView.ViewHolder(view) {          abstract fun bindData(data: T)      }          fun ViewGroup.inflateView(layoutRes: Int): View =          LayoutInflater.from(this.context).inflate(layoutRes, this, false)  }  

my adapter

class OrdersPagingAdapter(val onCancelClick: (Order) -> Unit) :      BasePagingAdapter<Order, BasePagingAdapter.BaseViewHolder<Order>>(          OrdersPagingComparator      ) {        override fun onCreateViewHolder(          parent: ViewGroup,          viewType: Int      ): BaseViewHolder<Order> =          OrdersViewHolder(parent.inflateView(R.layout.item_order))    }  

base paging source

open class BasePagingSource<T : Any>(      val call: suspend (Int) -> Response<BasePagingResponse<T>>  ) :      PagingSource<Int, T>() {        override suspend fun load(          params: LoadParams<Int>      ): LoadResult<Int, T> {          return try {              val nextPageNumber = params.key ?: 1              val response: Response<BasePagingResponse<T>> =                  call(nextPageNumber)              if (response.code() == 200) {                  LoadResult.Page(                      data = response.body()?.data!!,                      prevKey = null,                      nextKey = if (response.body()?.currentPage == response.body()?.totalPages) null                      else                          response.body()?.currentPage!! + 1                  )              } else {                  LoadResult.Page(                      data = emptyList(),                      prevKey = null,                      nextKey = null                  )              }          } catch (e: IOException) {              return LoadResult.Error(e)          } catch (e: HttpException) {              return LoadResult.Error(e)          }      }        override fun getRefreshKey(state: PagingState<Int, T>): Int? {          return state.anchorPosition?.let { anchorPosition ->              val anchorPage = state.closestPageToPosition(anchorPosition)              anchorPage?.prevKey?.plus(1) ?: anchorPage?.nextKey?.minus(1)          }      }    }  

my repository call I tries to chang initial page size but still not working

fun getOrders() = Pager(          config = PagingConfig(              pageSize = 10,              enablePlaceholders = false          ), pagingSourceFactory = { OrdersPagingSource() }      ).flow  

Why exception thrown after std::async() wait for the given task to end if they are catched?

Posted: 10 May 2021 08:13 AM PDT

I'm trying to write a function to execute a portion of code with a timeout.

So far i have:

#include <chrono>  #include <future>    class TimedOutError: public std::runtime_error {  public:      using std::runtime_error::runtime_error;  };    template <typename F, typename... Args>  using result_t = typename std::result_of<typename std::decay<F>::type(typename std::decay<Args>::type...)>::type;    template <typename D>  using duration_t = std::chrono::duration<typename D::rep, typename D::period>;    template <typename Timeout, typename F, typename... Args>  result_t<F, Args...>  withTimeout(const Timeout& timeout, F&& func, Args&&... args)  {      if (timeout == duration_t<Timeout>::zero())          return func(args...);        auto future = std::async(std::launch::async, func, args...);      auto status = future.wait_for(timeout);      if (status == std::future_status::ready)          return future.get();      else {          auto hrDuration = std::to_string(std::chrono::duration_cast<std::chrono::milliseconds>(timeout).count());          throw TimedOutError("Timed-out after " + hrDuration + "ms");      }  }      #include <iostream>    unsigned int work(const std::string& identifier, unsigned int steps) {      unsigned int i;      for(i = 0; i < steps+1; ++i) {          std::cout << identifier << " worked for " << i << "s" << std::endl;          std::this_thread::sleep_for(std::chrono::seconds(2));      }      std::cout << identifier << " done." << std::endl;      return i;  }    int main()  {      try {          auto result = withTimeout(std::chrono::nanoseconds(1), work, "Dummy#1", 2);          std::cout << "Result is: " << result << std::endl;      } catch (const TimedOutError& err) {          std::cout << "Dummy#1 timed-out. " << err.what() << std::endl;      }      std::cout << std::endl;        auto result = withTimeout(std::chrono::nanoseconds(1), work, "Dummy#2", 2);      std::cout << "Result is: " << result << std::endl;    }  

But I got a behavor i don't understand. When the exception is thrown after Dummy1, it is catched only once the task finished, but when the exception thrown after Dummy2 terminate the program as soon as it is catched:

Dummy#1 worked for 0s  Dummy#1 worked for 1s  Dummy#1 worked for 2s  Dummy#1 done.  Dummy#1 timed-out. Timed-out after 0ms    Dummy#2 worked for 0s  terminate called after throwing an instance of 'TimedOutError'    what():  Timed-out after 0ms  

How could i prevent this behavior ie: catch the exception as soon as it is thrown and abort the task launch with std::async if the timeout has been reached?

java.lang.illegalArgumentException thrown when trying to run app

Posted: 10 May 2021 08:13 AM PDT

I am a beginner can anyone help me out by telling me what the LogCat is saying.

I have made a Music player and I am trying to add an image in a imageView which initially have another image.

This is my LogCat.

2021-05-10 07:58:58.457 9410-9410/io.github.sahil19000.nymusicplayer E/AndroidRuntime: FATAL EXCEPTION: main        Process: io.github.sahil19000.nymusicplayer, PID: 9410      java.lang.RuntimeException: Unable to start activity ComponentInfo{io.github.sahil19000.nymusicplayer/io.github.sahil19000.nymusicplayer.MainActivity}: java.lang.IllegalArgumentException          at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2725)          at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2790)          at android.app.ActivityThread.-wrap12(ActivityThread.java)          at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1528)          at android.os.Handler.dispatchMessage(Handler.java:110)          at android.os.Looper.loop(Looper.java:203)          at android.app.ActivityThread.main(ActivityThread.java:6257)          at java.lang.reflect.Method.invoke(Native Method)          at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1068)          at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:929)       Caused by: java.lang.IllegalArgumentException          at android.media.MediaMetadataRetriever.setDataSource(MediaMetadataRetriever.java:71)          at io.github.sahil19000.nymusicplayer.MainActivity.fetchSongs(MainActivity.java:87)          at io.github.sahil19000.nymusicplayer.MainActivity.fetchSongs(MainActivity.java:80)          at io.github.sahil19000.nymusicplayer.MainActivity.fetchSongs(MainActivity.java:80)          at io.github.sahil19000.nymusicplayer.MainActivity$1.onPermissionGranted(MainActivity.java:40)          at com.karumi.dexter.MultiplePermissionsListenerToPermissionListenerAdapter.onPermissionsChecked(SourceFile)          at com.karumi.dexter.DexterInstance$1.run(SourceFile)          at com.karumi.dexter.MainThread.execute(SourceFile)          at com.karumi.dexter.DexterInstance.checkMultiplePermissions(SourceFile)          at com.karumi.dexter.DexterInstance.checkPermissions(SourceFile)          at com.karumi.dexter.Dexter.check(SourceFile)          at io.github.sahil19000.nymusicplayer.MainActivity.onCreate(MainActivity.java:70)          at android.app.Activity.performCreate(Activity.java:6736)          at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1118)          at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2678)          at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2790)           at android.app.ActivityThread.-wrap12(ActivityThread.java)           at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1528)           at android.os.Handler.dispatchMessage(Handler.java:110)           at android.os.Looper.loop(Looper.java:203)           at android.app.ActivityThread.main(ActivityThread.java:6257)           at java.lang.reflect.Method.invoke(Native Method)           at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1068)           at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:929)   

Go to next for of loop iteration only when

Posted: 10 May 2021 08:13 AM PDT

I have a for of loop:

for (const element of $array) {      let my_value = await GM.getValue("my_value");  }  

Works fine.

Now, I only want to go to the next loop iteration when my_value is not empty.

So far, I've tried a do..while approach:

for (const element of $array) {    do {      let my_value = await GM.getValue("my_value");        if (my_value) continue;    } while (0);  }  

But it's not working.

What's the correct approach to do this?

pipe output of grep as an argument to a bash script

Posted: 10 May 2021 08:13 AM PDT

script.sh takes two files as arguments, and it calls a python script that opens them and does further processing on these files:

script.sh file1.txt file2.txt  

I would like to remove all lines from file1.txt that start with #.

grep -v '^#' file1.txt  

I tried the following but it fails :

script.sh $(grep -v '^#' file1.txt) file2.txt  

How can I pipe the output of grep as the first file argument of script.sh?

How can i do a jointure beetween 2 tables

Posted: 10 May 2021 08:13 AM PDT

Hey i need to write a query to display the job title and average employee salary. there is my table in the link Bellow , dont know how to do the jointure between the 2tables [[1]: https://i.stack.imgur.com/o4ldx.png][1]

self.registration.showNotification not working

Posted: 10 May 2021 08:13 AM PDT

I'm listening for push notification but it is working on edge,chrome mobile, opera but is not working on chrome can anyone help me out?

self.registration.showNotification(data.title,{      body: data.body,      icon: data.icon  });        

Selenium-js: Firefox: Error: TimedPromise timed out after 300000 ms

Posted: 10 May 2021 08:13 AM PDT

I am trying to run my selenium javascript on the site bet365.com. I am using Firefox (geckodriver), I tried both headless and normal but for understanding/debugging the problem the non-headless-mode is helpful.

This is the code:

const driver = await new Builder().forBrowser("firefox").build();  await driver.get("https://bet365.com");  

The problem is that the site is not loading: enter image description here

After 5 mins I then end up with the error

TimeoutError: TimedPromise timed out after 300000 ms      at Object.throwDecodedError (C:\1_code\RFB\git\webscraper-srv\node_modules\selenium-webdriver\lib\error.js:517:15)      at parseHttpResponse (C:\1_code\RFB\git\webscraper-srv\node_modules\selenium-webdriver\lib\http.js:671:13)      at Executor.execute (C:\1_code\RFB\git\webscraper-srv\node_modules\selenium-webdriver\lib\http.js:597:28)      at processTicksAndRejections (internal/process/task_queues.js:93:5)      at async Driver.execute (C:\1_code\RFB\git\webscraper-srv\node_modules\selenium-webdriver\lib\webdriver.js:729:17)      at async C:\1_code\RFB\git\webscraper-srv\scripts\seleniumUtils.js:190:3      at async XWrap.<anonymous> (C:\1_code\RFB\git\webscraper-srv\scripts\utils.js:127:60)      at async XWrap.<anonymous> (C:\1_code\RFB\git\webscraper-srv\scripts\utils.js:127:60)      at async XWrap.<anonymous> (C:\1_code\RFB\git\webscraper-srv\scripts\utils.js:127:60)      at async XWrap.<anonymous> (C:\1_code\RFB\git\webscraper-srv\scripts\utils.js:127:60) {    remoteStacktrace: 'WebDriverError@chrome://marionette/content/error.js:181:5\n' +      'TimeoutError@chrome://marionette/content/error.js:450:5\n' +      'bail@chrome://marionette/content/sync.js:229:19\n'  

I tried visiting a different site with selenium and they work perfectly so I don't think its a problem with my setup. If I try visiting the site with my normal Firefox Browser it works too. I also tried manually searching for the page in the browser which is opened by the program and it leads to another endless loop. But opening other pages in this browser manually opened by selenium works fine.

Is it possible for the server of a webpage to detect browsers that were started using selenium? I always thought the only way to detect webscrapers was by looking at the frequency it is visiting and the clicks the scraper is doing on a page but it is the first time I visited the page with Selenium...

If the server doesn't allow these kind of requests, is there any way to still scrape data from this webpage? I also already tried opening it in headless mode...

This is the (entire) Firefox Network tab when its stuck loading (sometimes it looks a little different): enter image description here

This is the (begin of the) Firefox Network tab when its loaded normally: enter image description here

I circled the requests that might be causing the problem. In the bottom left of the browser it's telling me the entire time that it's Transfering data from ff.kis.v2.scr.kaspersky-labs.com. I tried deactivating kaspersky on my machine and also let the progamme run on a machine without kaspersky so I am not quite sure why this request is made. It might have to do something with https validation but I am not sure.

Another interesting thing is that the response of the first request to www.bet365.com/ looks like this (even with selenium): enter image description here Meaning that it does actually reach the server but it just sends a loading screen. Also the following requests get the same response as with the normal browser. Only the requests with status 101 don't give back any response, unlike with the normal browser.

Last interesting thing is this request www.bet365.com/increment?desktop-site-loaded_11=1. It is only made when starting it with the selenium browser, not when opening the site with a normal browser. This might mean that its not a loading problem but that its actively blocking the request and telling the backend to increase a counter of requests that were blocked.

Any ideas how I can get the code working or why this problem comes up?

MySQL 8.0: Error on trying to install keyring

Posted: 10 May 2021 08:13 AM PDT

Using MySQL 8.0 and MySQL Workbench on Windows 10. Also using Command Prompt to interface with mysql after cd'ing into C:\Program Files\MySQL\MySQL Server 8.0\bin.

I'm trying to implement encryption data-at-rest on several tables on a database. However, after trying to install keyring_file.dll via

install plugin keyring_file soname 'keyring_file.dll';  

I get the following error:

ERROR 1123 (HY000): Can't initialize function 'keyring_file'; Plugin initialization function failed.  

I have added the following to my.cnf under mysqld:

[mysqld]  early-plugin-load=keyring_file.dll  keyring_file_data=C:/Program Files/MySQL/MySQL Server 8.0/lib/plugin/keyring_file  

After restarting MySQL server via services.msc, I ran 'show variables like '%keyring%';' which returned the following:

enter image description here

Running the following:

SELECT PLUGIN_NAME, PLUGIN_STATUS FROM INFORMATION_SCHEMA.PLUGINS WHERE PLUGIN_NAME LIKE 'keyring%';  

Also returned:

enter image description here

Not sure what I have done wrong or missed out. Looking at similar questions and solutions for this issue don't seem to work for some reason.

Regarding a simple C program

Posted: 10 May 2021 08:14 AM PDT

so, I'm trying to make a simple calculation program in C but I get wrong answer on using:

>> volume = (4/3)*(3.14)*(r*r*r);  

but if I use,

>> volume = (1.33)*(3.14)*(r*r*r);  

I get right ans why am I facing this problem?

Github Actions Node.js

Posted: 10 May 2021 08:14 AM PDT

I am having problems with the node.js template.

I am trying to upload my entire repo, which contains a node.js application.

On action build I get the following ENOT error:

npm ERR! enoent ENOENT: no such file or directory, open '/home/runner/work/testcode/testcode/package.json'

Can anyone help?

I tried adding working directory, still the same issue is coming.My project structure See below references for action set up.

name: Test Sercive CI  

on: [push] jobs: build: runs-on: ubuntu-latest timeout-minutes: 200 strategy: matrix: node-version: [12.x]

steps:    - uses: actions/checkout@v2      with:        persist-credentials: false    - run: git config --global url."https://${{ secrets.GLOBAL_GITHUB_TOKEN }}@github.com".insteadOf "https://github.com"      - name: Use Node.js ${{ matrix.node-version }}      uses: actions/setup-node@v1      with:        node-version: ${{ matrix.node-version }}        registry_url: 'https://XXXXXXX/'        scope: '@org'      - name: install dependencies      run: npm ci      env:         NODE_AUTH_TOKEN: ${{secrets.NPM_AUTH_TOKEN}}      working-directory: ./       

Text disappears on hover CSS

Posted: 10 May 2021 08:13 AM PDT

My text disappears when I hover over it. I tried removing the hidden and putting the visibility: visible and I changed the opacity to 1 but I still keep getting the same - the text still disappears when I hover. I am trying to make the text stay the same and do nothing when I hover. Am I missing something else? https://jsfiddle.net/yg0e761w/1/

HTML   <div class="col-xl-3 col-lg-4 col-md-4 col-sm-6 col-6 ">     <div class="ps-product">         <div class="ps-product__thumbnail">             <a href=" "><img src="http://placekitten.com/100/100" alt=" "></a>              <div class="ps-product__badge">10%</div>                    </div>   <div class="ps-product__container">           <a class="ps-product__vendor" href="/Animal/Cat">Cat store</a>   <div class="ps-product__content">    <a class="ps-product__title" href="cat_new">kITTY</a>       <p class="ps-product__price sale">50000<del>40000</del></p>   </div>   </div>    </div>   </div>  

CSS

.ps-product__title {      margin: 0;      display: block;      padding: 0 0 5px;      font-size: 14px;      line-height: 1.2em;      color: #06c;      --max-lines: 2;      max-height: calc(1.2em * var(--max-lines));      overflow: hidden;      padding-right: 1rem;      opacity: 1;}                  a {      position: relative;      color: inherit;      text-decoration: none;      transition: all 0.4s ease; }        .ps-product:hover .ps-product__content {    visibility: hidden;    opacity: 1;    height: 0;  }    .ps-product:hover {    border-color: silver;  }    .ps-product:hover.ps-product--inner .ps-product__content {    display: block;    visibility: visible;    opacity: 1;  }  

Finding the time and space complexity of a monte carlo algorithm

Posted: 10 May 2021 08:13 AM PDT

I'm still new to StackOverflow so please forgive me if I did something wrong ^^'

I need help finding the time and space complexity of a Monte Carlo algorithm that approximates pi's value. I had a hard looking for answers on Google so I was hoping to find the answers here ^^.

Why is the content of my h1 going on top of a fixed navbar component?

Posted: 10 May 2021 08:13 AM PDT

Issue

The content of my h1 is going on top of my navbar.

Attempts at a solution

I saw other threads where they changed the z-index of the nav element to 1, but that didn't work. I also tried adding margins to both the container that has the h1 and the nav element to push them away from eachother, but that had no effect.

Information

I am using NUXT where I have a default.vue in my layouts folder that looks like this:

<template>    <div class="container">      <Navbar/>      <Nuxt/>      <img src="revue/assets/nuxtjs-typo.svg" alt="nuxt-typo">    </div>  </template>    <script>  import Navbar from '../components/Navbar.vue';  export default {    components: {      Navbar    }      }  </script>    <style>  </style>    

And in the pages section I have an index.vue that contains the h1:

<template>    <div class="container">      <h1>This text is on top of the nav</h1>    </div>  </template>    <script>  export default {}  </script>    <style>    html, body {      margin: 0;      padding: 0;  }    h1 {      color: #2F495E;      font-family: 'Quicksand', sans-serif;      font-size: 1em;      text-align: center;  }    </style>  

And finally the Navbar.vue component in the components folder:

<template>      <nav>          <ul>              <li>                  <img id="nuxticon" src="../assets/nuxt-icon.png" alt="nuxticon">              </li>              <li>                  <img id="nuxttext" src="../assets/nuxtjs-typo.svg" alt="nuxttext">              </li>              <li>                  <NuxtLink to="/docs">Udforsk</NuxtLink>              </li>              <li>                  <NuxtLink to="/about">Om os</NuxtLink>              </li>              <li>                  <NuxtLink to="/field">Tilføj restaurant</NuxtLink>              </li>              <li>                  <NuxtLink to="/damage">Kontakt</NuxtLink>              </li>          </ul>      </nav>  </template>    <style>      nav {      position: fixed;      box-shadow: 0 1px 3px -3px gray;      width: 100vw;      height: 8vh;      top: 0;  }    nav ul {      list-style: none;      margin: 0;      padding: 0;      height: 100%;      width: 100%;      display: flex;      justify-content: center;  }      nav ul li {      display: flex;      align-items: center;  }      a {      font-size: 1.5vh;      margin-left: 2vw;      text-decoration: none;      color: #2F495E;      font-family: 'Quicksand', sans-serif;      text-transform: uppercase;  }    #nuxttext {      height: 3vh;      width: 10vw;      margin-right: 8vw;  }    #nuxticon {      height: 5vh;      margin-right: 0.5vw;  }    a:hover {      color: #08C792;  }      </style>    

This results in the h1 text sitting on top of the nav, instead of below it, as intended. Any help is appreciated. Thank you.

Can someone help me understand this ORDER BY error in my SQL Server Query?

Posted: 10 May 2021 08:13 AM PDT

Ran into an error when attempting to input the query for Total Population .vs. Vaccinations:

1

I honestly have no idea how to remedy this error and I've tried as much as I know of SQL (I'm very new to SQL) so far to mess with the code to fix it. Any suggestions? (If further code is needed, let me know and I'll post the entire project for better understanding of where the problem could stem from)

Ms sql that is T-SQL scope_identity() function what will equivalent to oracle PL-SQL function?

Posted: 10 May 2021 08:13 AM PDT

Ms-sql that is T-SQL scope_identity() function what will equivalent to oracle PL-SQL function?

Android MVVM single Activity change fragment language

Posted: 10 May 2021 08:13 AM PDT

I am trying to recode my app with MVVM architecture and also single activity model. So I have a unique Activity managing all my fragments through navigation component.

My issue is that I have 2 parts in my app -> one part logged out and one logged in. And what I want is that the logged out part take the phone language and the logged in part the user choice (one of my 4 languages).

Is there a way to force a fragment language in this architecture and with navigation component?

Thanks for your help

Adding a button to a image with text so it can navigate to the next page in flutter

Posted: 10 May 2021 08:13 AM PDT

firstly thanks for the help. Just started in flutter/dart and have a issue I can't work my way out of.

I have a scaffod with a appbar and a body and in the body is a container with a gridview with a decoration box with a image with a text and now want to add a way for when this is clicked go to another page (invoices). Thought this required a button as the last step, but not sure where to paste the final code portion

import 'package:cfo360app/services/auth.dart';  import 'package:flutter/material.dart';  import 'package:flutter/services.dart';    class Home extends StatelessWidget {      final AuthService _auth = AuthService();    @override    Widget build(BuildContext context) {      return Scaffold(        backgroundColor: Colors.blue[50],        appBar: AppBar(          title: Text('CFO360'),          backgroundColor: Colors.grey[400],          elevation: 0.0,          actions: <Widget>[            TextButton.icon(              icon: Icon(Icons.person),              label: Text('logout'),              onPressed: () async {                await _auth.signout();              },            )          ],        ),        body: AnnotatedRegion<SystemUiOverlayStyle>(          value: SystemUiOverlayStyle.light,          child: GestureDetector(            child: Stack(              children: <Widget>[                Container(                  padding: EdgeInsets.only(top: 16.0),                  height: double.infinity,                  width: double.infinity,                  decoration: BoxDecoration(                    gradient: LinearGradient(                        begin: Alignment.topCenter,                        end: Alignment.bottomCenter,                        colors: [                          Color(0x66424554),                          Color(0x99424554),                          Color(0xcc424554),                          Color(0xff424554),                        ]                    ),                  ),                      child: GridView.count(                      mainAxisSpacing: 10.0,                      crossAxisSpacing: 10.0,                      crossAxisCount: 4,                      children: <Widget>[                        Material(                          clipBehavior: Clip.antiAlias,                          shape: RoundedRectangleBorder(                            borderRadius: BorderRadius.circular(24),                          ),                          child:Stack(                            children: <Widget>[ Container(                            decoration: BoxDecoration(                              borderRadius: BorderRadius.circular(20),                              image: DecorationImage(                                image: AssetImage('assets/images/camera.jpg'),                                fit: BoxFit.cover                              )                            ),                               child: Center(child: Text("invoices",                               style:TextStyle(fontSize: 20,                                color: Colors.white,                                   fontWeight: FontWeight.bold),                              ),                                  ),                              child: Center(child: ElevatedButton(onPressed: () {                                Navigator.push(                                  context,                                  MaterialPageRoute(                                      builder: (context) => Invoices()),                                );                              },                                  ),                            ),                            ),                        ],                        ),                        ),  

any assistance would be greatly appreciated. Keeps asking to add required argument child.

Problems with Scala Inheritance

Posted: 10 May 2021 08:13 AM PDT

) I have one Parent class called Mob, and I am creating two subclasses Human and Monster.

  abstract class Mob(                        var name: String,                        var healthPoints: Int,                        var attackPower: Int,                        var defense: Int                      ) {        var level: Int = 1      var isAlive: Boolean = true            val attackBooster: Map[String, Int]        def attack(opponent: Mob): Unit      def getSound: String        def boostAttack(attributes: List[Int]): List[Int] = {        attributes.map((x: Int) => x + this.attackPower)      }    }    class Human(                 override var name: String,                 override var healthPoints: Int,                 override var attackPower: Int,                 override var defense: Int,                 var strength: Int,                 var agility: Int,                 var intelligence: Int,                 var profession: String,                 var kingdom: String               ) extends Mob(      name: String,      healthPoints: Int,      attackPower: Int,      defense: Int    ) {        def this(                name: String,                healthPoints: Int,                attackPower: Int,                defense: Int,                strength: Int,                agility: Int,                intelligence: Int,                profession: String = "",                kingdom: String = ""              ) {        this(name, healthPoints, attackPower, defense, strength, agility, intelligence, profession, kingdom)        this.profession = chooseProfession(profession)        this.kingdom = chooseKingdom(kingdom)      }    class Monster(                   override var name: String,                   override var healthPoints: Int,                   override var attackPower: Int,                   override var defense: Int,                   var toxicity: Int,                   var brutality: Int,                   var confusion: Int,                   var curse: Int,                   var kind: String                 ) extends Mob(      name: String,      healthPoints: Int,      attackPower: Int,      defense: Int    ) {        def this(                name: String,                healthPoints: Int,                attackPower: Int,                defense: Int,                toxicity: Int,                brutality: Int,                confusion: Int,                curse: Int,                kind: String = ""              ) {        this(name, healthPoints, attackPower, defense, toxicity, brutality, confusion, curse, kind)        this.kind = chooseKind(kind)      }  

The problems regarding this inheritance is that:

  • I cannot overload the default constructor (Constructor is defined twice and ambiguous reference to overloaded definition)
  • I cannot overload mutable members of the parent Mob class

I am new to Scala, and unfortunately I could not find any solution regarding my issue. Could you please clarify what the problem is and how I can solve it?

How to reduce react context hell?

Posted: 10 May 2021 08:13 AM PDT

I have inherited a codebase where the previous owner has made extensive use of React.Context. This has resulted in what might be described as "context hell"

<AppContextProvider>    <AnotherProvider>      <AgainAnotherProvider configProp={false}>        <TestProvider>          <FooProvider>            <BarProvider configHereAlso={someEnvronmentVar}>              <BazProvider>                <BatProvider>                  <App />                </BatProvider>              </BazProvider>            </BarProvider>          </FooProvider>        </TestProvider>      </AgainAnotherProvider>    </AnotherProvider>  </AppContextProvider>;  

This feels like an anti-pattern and is causing considerable cognitive overhead in understanding how the whole application works.

How do I fix this? Is it possible to use just one provider for everything? I previously used redux-toolkit with redux for managing state in react. Is there anything similar for contexts?

How Do I add to an ArrayList within a HashMap while iterating

Posted: 10 May 2021 08:13 AM PDT

While following a tutorial series for LWJGL for my file university project, I add game items to the world that have an associated Mesh class,

If I were to add many objects to the world that shared the same mesh, it would be more efficient to associate a list of game items to one Mesh type and then render from there

private Map<Mesh, List<GameItem>> meshMap;    meshMap = new HashMap();         public void addDynamicGameItem(DynamicGameItem dynamicGameItem) {      numGameItems++;          Mesh[] meshes = dynamicGameItem.getMeshes();          for(Mesh mesh : meshes) {              List<GameItem> list = tempMap.get(mesh);              if (list == null) {                  list = new ArrayList<>();                  tempMap.put(mesh, list);              }              list.add(dynamicGameItem);          }  }  

this works perfectly until I try to add new game items to the world while the hashmap is being iterated over, any subsequent calls to addStaticGameItem seems to add the game logic of a new item to the world, but the Mesh is not added properly and thus cannot be seen at all.

here's where the hashmap is called for rendering:

Map<Mesh, List<GameItem>> mapMeshes = scene.getGameMeshes();      for (Mesh mesh : mapMeshes.keySet()) {          if(mesh.getMaterial() != null) {              sceneShaderProgram.setUniform("material", mesh.getMaterial());              Texture text = mesh.getMaterial().getTexture();              if (text != null) {                  sceneShaderProgram.setUniform("numCols",                   text.getNumCols());                  sceneShaderProgram.setUniform("numRows",                   text.getNumRows());              }          }            mesh.renderList(mapMeshes.get(mesh), (GameItem gameItem) -> {                      sceneShaderProgram.setUniform("selected",                       gameItem.isSelected() ? 1.0f : 0.0f);                      Matrix4f modelViewMatrix =                       transformation.buildModelViewMatrix(gameItem,                       viewMatrix);                      sceneShaderProgram.setUniform("modelViewMatrix",                       modelViewMatrix);                      Matrix4f modelLightViewMatrix =                       transformation.buildModelLightViewMatrix(gameItem,                       lightViewMatrix);                      sceneShaderProgram.setUniform("modelLightViewMatrix",                       modelLightViewMatrix);                  }          );      }  

So how do I properly add new values to a Hashmap list while iterating?

EDIT: potential new method for adding items that doesn't work

public void updateMeshMap(){      if(!tempMap.isEmpty()){          for(Mesh m : tempMap.keySet()){              List list = meshMap.get(m);              if (list == null) {                  list = new ArrayList<>();                  list.addAll(tempMap.get(m));                  meshMap.put(m, list);              }else{                  list.addAll(tempMap.get(m));              }          }      }      tempMap = new HashMap<Mesh, List<GameItem>>();  }  

Rich edit control sends EN_CHANGE when spellcheck underline appears

Posted: 10 May 2021 08:13 AM PDT

Let's say you've just set some text in a spellcheck-enabled rich edit control, and the text has some spelling errors. A split second will go by, spellcheck will kick in, and then the misspelled text will get underlined. But guess what: the rich edit control will actually send an EN_CHANGE notification just for the underlining event (this is assuming you've registered for notifications by doing SendMessage(hwnd, EM_SETEVENTMASK, 0, (LPARAM)ENM_CHANGE)).

Is there a workaround to not get this type of behavior? I've got a dialog with some spellcheck-enabled rich edit controls. And I also want to know when an edit event has taken place, so I know when to enable the "Save" button. Getting an EN_CHANGE notification merely for the spellcheck underlining event is thus a problem.

One option I've considered is disabling EN_CHANGE notifications entirely, and then triggering them on my own in a subclassed rich edit control. For example, when there's a WM_CHAR, it would send the EN_CHANGE notification explicitly, etc. But that seems like a problem, because there are many types of events that should trigger changes, like deletes, copy/pastes, etc., and I'd probably not capture all of them correctly.

Another option I've considered is enabling and disabling EN_CHANGE notifications dynamically. For example, enabling them only when there's focus, and disabling when focus is killed. But that also seems problematic, because a rich edit might already have focus when its text is set. Then the spellcheck underline would occur, and the undesirable EN_CHANGE notification would be sent.

I suppose a timer could be used, too, but I think that would be highly error-prone.

Does anybody have any other ideas?

Here's a reproducible example. Simply run it, and it'll say something changed:

#include <Windows.h>  #include <atlbase.h>  #include <atlwin.h>  #include <atltypes.h>  #include <Richedit.h>    class CMyWindow :      public CWindowImpl<CMyWindow, CWindow, CWinTraits<WS_VISIBLE>>  {  public:      CMyWindow()      {      }    BEGIN_MSG_MAP(CMyWindow)      MESSAGE_HANDLER(WM_CREATE, OnCreate)      COMMAND_CODE_HANDLER(EN_CHANGE, OnChange)  END_MSG_MAP()    private:      LRESULT OnCreate(UINT, WPARAM, LPARAM, BOOL& bHandled)      {          bHandled = FALSE;            LoadLibrary(L"Msftedit.dll");            CRect rc;          GetClientRect(&rc);          m_wndRichEdit.Create(MSFTEDIT_CLASS, m_hWnd, &rc,              NULL, WS_VISIBLE | WS_CHILD | WS_BORDER);            INT iLangOpts = m_wndRichEdit.SendMessage(EM_GETLANGOPTIONS, NULL, NULL);          iLangOpts |= IMF_SPELLCHECKING;          m_wndRichEdit.SendMessage(EM_SETLANGOPTIONS, NULL, (LPARAM)iLangOpts);            m_wndRichEdit.SetWindowText(L"sdflajlf adlfjldsfklj dfsl");                   m_wndRichEdit.SendMessage(EM_SETEVENTMASK, 0, (LPARAM)ENM_CHANGE);                  return 0;      }        LRESULT OnChange(WORD, WORD, HWND, BOOL&)      {          MessageBox(L"changed", NULL, NULL);          return 0;      }    private:      CWindow m_wndRichEdit;  };      int APIENTRY wWinMain(_In_ HINSTANCE hInstance,                       _In_opt_ HINSTANCE hPrevInstance,                       _In_ LPWSTR    lpCmdLine,                       _In_ int       nCmdShow)  {      CMyWindow wnd;      CRect rc(0, 0, 200, 200);      wnd.Create(NULL, &rc);        MSG msg;      while (GetMessage(&msg, nullptr, 0, 0))      {          TranslateMessage(&msg);          DispatchMessage(&msg);      }        return (int)msg.wParam;  }  

Also, it appears that using EM_SETMODIFY and EM_GETMODIFY don't help. I guess the spellcheck underlining results in a EM_SETMODIFY, so checking that flag in the handler is of no avail.

changing language with setlocale on Windows

Posted: 10 May 2021 08:13 AM PDT

I have a CLI program that's using libintl's gettext, and calls setlocale(LC_ALL, "") to change output language to whatever the user's preferred language is.

I'm developing on a machine where US English is my default locale, and want to test the German output. This is easy on Linux, where I can change the language with an environment variable, like so: LANGUAGE=de_DE ./a.out

There doesn't seem to be an environment variable like this on Windows? The CRT reference for setlocale says:

The locale name is set to the value returned by GetUserDefaultLocaleName.

I can find no mention of how to change that default locale for a single process. Is there even such a thing?

PostGIS: Transform Linestring to LineString ZM

Posted: 10 May 2021 08:13 AM PDT

Problem:

I have a series of geometries (LineString) saved in a Postgres database with additional information saved next to the geometry (a column for speed and time). I want to combine the three columns into a LineString ZM type so the geometry goes from a 2d to a 4d vector.

id geometry speed time
1 LineString_A Int[] Float[]
2 LineString_B Int[] Float[]

Question:

How do I most easily combine the geometry (x, y), speed, and time into a LineString ZM?

vs code error " you do not have an extension for debugging html, should we find the html extension in the marketplace?

Posted: 10 May 2021 08:13 AM PDT

I unable to run my html code on vs code they give a error you don't have html debugger and recommend to download I download 3-4 recommend extension from the list but nothing is working same error came, again and again, what should I do please suggest

Django Exclude Model Objects from query using a list

Posted: 10 May 2021 08:13 AM PDT

Having trouble with my query excluding results from a different query.

I have a table - Segment that I have already gotten entries from. It is related to another table - Program, and I want to also run the same query on it but I want to exclude any of the programs that were already found during the segment query.

When I try to do it, the list isn't allowed to be used in the comparison... See below:

query = "My Query String"            segment_results = Segment.objects.filter(      Q(title__icontains=query)|      Q(author__icontains=query)|      Q(voice__icontains=query)|      Q(library__icontains=query)|      Q(summary__icontains=query) ).distinct()    # There can be multiple segments in the same program  unique_programs = []  for segs in segment_results:      if segs.program.pk not in unique_programs:           unique_programs.append(segs.program.pk)       program_results = ( (Program.objects.filter(          Q(title__icontains=query) |          Q(library__icontains=query) |          Q(mc__icontains=query) |          Q(producer__icontains=query) |          Q(editor__icontains=query) |          Q(remarks__icontains=query) ).distinct()) &          (Program.objects.exclude(id__in=[unique_programs])))            

I can run:

for x in unique_programs:     p = Program.objects.filter(id=x)      print("p = %s" % p)  

And I get a list of Programs...which works Just not sure how to incorporate this type of logic into the results query...and have it exclude at the same time. I tried exclude keyword, but the main problem is it doesn't like the list being in the query - I get an error: TypeError: int() argument must be a string, a bytes-like object or a number, not 'list'.

Feel like I am close...

JavaScript - check if input date is within add 7 days from current yyyy/mm/dd date, NOT js date()

Posted: 10 May 2021 08:13 AM PDT

I have a form submit with 2 date inputs: share_start and share_end in yyyy-mm-dd format. I use JS to validate the input and want to check whether share_end date is within 7 days from the share_start date.

Now, the tricky bit is that I don't have a JS date() dates/timestamps, but only those input dates, but when trying to add on 7 days to the input in JS all I end up with an error since JS needs to operate with date(). I cannot use any external scripts like moment.js to help with this.

Does JS have some sort of in-built function like PHPs strtotime where I can just add + 7 days or something?

Thank you

// Form Submit Validation  function validateForm() {      var share_start = '2021-05-07';      var share_end = '2021-05-15';      var share_max = share_start.setDate(date.getDate() + 6);            if (share_end > share_max) {          alert("Share End Date cannot be more than 7 days from now");          return false;      }    }  

Maven Build Failure -- DependencyResolutionException

Posted: 10 May 2021 08:13 AM PDT

I'm installing a package that has Maven dependency and get a DependencyResolutionException when I try to clean it. After cloning it, I navigate to the directory and run the following to install it with no error:

mvn install:install-file -Dfile=./lib/massbank.jar -DgroupId=massbank  -DartifactId=massbank -Dversion=1.0 -Dpackaging=jar  mvn install:install-file -Dfile=./lib/metfusion.jar -DgroupId=de.ipbhalle.msbi  -DartifactId=metfusion -Dversion=1.0 -Dpackaging=jar  

Then:

mvn clean package   

with the following console output:

[INFO] Scanning for projects...  [INFO]   [INFO] --------------------< MassBank2NIST:MassBank2NIST >---------------------  [INFO] Building MassBank2NIST 0.0.2-SNAPSHOT  [INFO] --------------------------------[ jar ]---------------------------------  [INFO] ------------------------------------------------------------------------  [INFO] BUILD FAILURE  [INFO] ------------------------------------------------------------------------  [INFO] Total time:  0.450 s  [INFO] Finished at: 2021-04-07T01:08:28-04:00  [INFO] ------------------------------------------------------------------------  [ERROR] Failed to execute goal on project MassBank2NIST: Could not resolve dependencies for project MassBank2NIST:MassBank2NIST:jar:0.0.2-SNAPSHOT: Failed to collect dependencies at edu.ucdavis.fiehnlab.splash:core:jar:1.8: Failed to read artifact descriptor for edu.ucdavis.fiehnlab.splash:core:jar:1.8: Could not transfer artifact edu.ucdavis.fiehnlab.splash:core:pom:1.8 from/to maven-default-http-blocker (http://0.0.0.0/): Blocked mirror for repositories: [EBI (http://www.ebi.ac.uk/intact/maven/nexus/content/repositories/ebi-repo/, default, releases+snapshots), releases (http://gose.fiehnlab.ucdavis.edu:55000/content/groups/public, default, releases+snapshots)] -> [Help 1]  [ERROR]   [ERROR] To see the full stack trace of the errors, re-run Maven with the -e switch.  [ERROR] Re-run Maven using the -X switch to enable full debug logging.  [ERROR]   [ERROR] For more information about the errors and possible solutions, please read the following articles:  [ERROR] [Help 1] http://cwiki.apache.org/confluence/display/MAVEN/DependencyResolutionException  

I can post the output of the debug logging switch if necessary, but it's quite long. I can also post the pom.xml, however it refers to the repositories as required from what I can tell.

I've searched for similar posts, but none seem to contain the same series of errors or similar. Can someone help me decipher these errors?

Thanks!

Given a number, find the next higher number which has the exact same set of digits as the original number

Posted: 10 May 2021 08:13 AM PDT

I just bombed an interview and made pretty much zero progress on my interview question. Can anyone let me know how to do this? I tried searching online but couldn't find anything:

Given a number, find the next higher number which has the exact same set of digits as the original number. For example: given 38276 return 38627

I wanted to begin by finding the index of the first digit (from the right) that was less than the ones digit. Then I would rotate the last digits in the subset such that it was the next biggest number comprised of the same digits, but got stuck.

The interviewer also suggested trying to swap digits one at a time, but I couldn't figure out the algorithm and just stared at a screen for like 20-30 minutes. Needless to say, I think I'm going to have to continue the job hunt.

edit: for what its worth, I was invited to the next round of interviews

No comments:

Post a Comment