Tuesday, June 1, 2021

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

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

Recent Questions - Stack Overflow



In the 06/01/2021 edition:

Not able to find /opt /var /tmp in lsblk RHEL 8.1

By anonymous grey on Jun 01, 2021 03:59 am

Am Not able to find /opt /var /tmp in lsblk RHEL 8.1.Can you please help me.

[xxx@exxx ~]$ lsblk  NAME              MAJ:MIN RM  SIZE RO TYPE MOUNTPOINT  sda                 8:0    0   64G  0 disk  +-sda1              8:1    0  500M  0 part /boot/efi  +-sda2              8:2    0  500M  0 part /boot  +-sda3              8:3    0    2M  0 part  +-sda4              8:4    0   60G  0 part  +-rootvg-rootlv 253:5    0   60G  0 lvm  /  

Read in browser »
share on Twitter

How to send string along with Flask video streaming with each frame?

By Akshdeep Singh on Jun 01, 2021 03:59 am

I am streaming video on web using flask, by following this blog.

I also want to send a string with every frame to display a message below the video. How to do that?

def gen(camera):      while True:          frame = camera.get_frame()            # here i want a new string to send along with each frame            yield (b'--frame\r\n'                 b'Content-Type: image/jpeg\r\n\r\n' + frame + b'\r\n')  
<html>    <head>      <title>Video Streaming Demonstration</title>    </head>    <body>      <h1>Video Streaming Demonstration</h1>      <img src="{{ url_for('video_feed') }}">      <p><!-- string to be shown here --></p>    </body>  </html>  

Read in browser »
share on Twitter

Sum of elements of two integer array in a single string array in Java

By chaitanya gupta on Jun 01, 2021 03:59 am

i have a a string array which contains two integer array ["[1,2,3]","[4,5,6,7,8]"]

I want to add the elements of integer array for example - 1+4,2+5,3+6 and store and print the result in a single integer array - [4,7,9,7,8]

What is the efficient approach to solving this problem?


Read in browser »
share on Twitter

can't find link on puppeteer after searching by a keyword only one product (I always get the first link of all results)

By alexandre on Jun 01, 2021 03:58 am

I'm trying to scrap datas on a website, searching by a reference or by a name of a product, but I only get the first link of the page. I think the page doesn't wait for navigation and it's for that reason I can't get the result of my search. Here is my code. The keyword ref has to be replaced by a word because on my code, i get this result on typing on a search bar. If anyone could help me, I would be very grateful. Thank you in advance

const ObjectsToCsv = require('objects-to-csv');    const scraperObject = {      url: 'await page.goto('https://polspotten.nl/products/all');',      async scraper(browser, ref) {          let page = await browser.newPage();          console.log(`Navigating to ${this.url}...`);          // Navigate to the selected page          await page.goto(this.url);          // Wait for the required DOM to be rendered          async function scrapeCurrentPage(ref){                await page.type('input[name="search"]', ref);              page.waitForNavigation();                await Promise.all([                  page.$eval('.products-content a', el => el.click()),                  page.waitForNavigation({waitUntil: 'load'})              ]);                let dataObj = {};                dataObj['nom_du_produit'] = await page.$eval('.product-info-panel > div > div > h1', text => text.textContent.replace(/(\r\n\t|\n|\r|\t)/gm, ""));              dataObj['prix avant promo'] = await page.$eval('.product-info-panel > div > div >.prices > p:nth-child(1)', text => text.textContent.replace(/(\r\n\t|\n|\r|\t)/gm, ""));              dataObj['prix après promo'] = await page.$eval('.product-info-panel > div > div >.prices > p:nth-child(2)', text => text.textContent.replace(/(\r\n\t|\n|\r|\t)/gm, ""));              dataObj['référence'] = await page.$eval('.product-info-panel > div > p', text => text.textContent.replace(/(\r\n\t|\n|\r|\t)/gm, ""));                console.log(dataObj);                // await browser.close();                // csv file              let data = [dataObj];              (async () => {                  const csv = new ObjectsToCsv(data);                    // Save to file:                  await csv.toDisk('./products.csv', { append: true });                    // Return the CSV file as string:                  console.log(await csv.toString());              })();          }          await scrapeCurrentPage(ref);      }  }    module.exports = scraperObject;    

Read in browser »
share on Twitter

i don't know where is wrong DSA Calculation

By Sun on Jun 01, 2021 03:58 am
p = 40193, q = 157, g = 131, x = 89, H(m) = 241, k = 127    r = (131^127 mod 40193) mod 157, r = 59  s = k^-1 * (241 + 59 * 89) mod 157, 68 k^-1 * (241 + 59 * 89) mod 157 = 110, s = 110    y = 131^89 mod 40193 = 39368  w = 110^-1 mod 157 = 10  a = 10 * 241 mod 157 = 55  b = 10 * 59 mod 157 = 119  v = ((131^55 * 39368^119) mod 40193) mod 157    = ((8396 * 32204) mod 40193) mod 157 = 6473 mod 157 = 36  v != r  

Please give me some advice. I don't know what's wrong.


Read in browser »
share on Twitter

`TypeError: object of type 'NoneType' has no len()` error when I run basic M RCNN program on jupyter notebook

By akshay acharya on Jun 01, 2021 03:58 am

I am running a basic maskr cnn program to detect objects. It is using the coco datatset. I am running this on Jupyter notebook connected to my AWS Ec2 instance. I getting the following error

Below is the traceback from this internal error.    Traceback (most recent call last):    File "/usr/local/lib/python3.6/dist-packages/IPython/core/interactiveshell.py", line 3343, in run_code      exec(code_obj, self.user_global_ns, self.user_ns)    File "<ipython-input-1-dfbb133297e0>", line 117, in <module>      cv2.imshow('frame', frame)  cv2.error: OpenCV(4.2.0) /home/ubuntu/src/opencv/modules/highgui/src/window.cpp:651: error: (-2:Unspecified error) The function is not implemented. Rebuild the library with Windows, GTK+ 2.x or Cocoa support. If you are on Ubuntu or Debian, install libgtk2.0-dev and pkg-config, then re-run cmake or configure script in function 'cvShowImage'      During handling of the above exception, another exception occurred:    Traceback (most recent call last):    File "/usr/local/lib/python3.6/dist-packages/IPython/core/interactiveshell.py", line 2044, in showtraceback      stb = value._render_traceback_()  AttributeError: 'error' object has no attribute '_render_traceback_'    During handling of the above exception, another exception occurred:    Traceback (most recent call last):    File "/usr/local/lib/python3.6/dist-packages/IPython/core/ultratb.py", line 1169, in get_records      return _fixed_getinnerframes(etb, number_of_lines_of_context, tb_offset)    File "/usr/local/lib/python3.6/dist-packages/IPython/core/ultratb.py", line 316, in wrapped      return f(*args, **kwargs)    File "/usr/local/lib/python3.6/dist-packages/IPython/core/ultratb.py", line 350, in _fixed_getinnerframes      records = fix_frame_records_filenames(inspect.getinnerframes(etb, context))    File "/usr/lib/python3.6/inspect.py", line 1490, in getinnerframes      frameinfo = (tb.tb_frame,) + getframeinfo(tb, context)    File "/usr/lib/python3.6/inspect.py", line 1448, in getframeinfo      filename = getsourcefile(frame) or getfile(frame)    File "/usr/lib/python3.6/inspect.py", line 696, in getsourcefile      if getattr(getmodule(object, filename), '__loader__', None) is not None:    File "/usr/lib/python3.6/inspect.py", line 733, in getmodule      if ismodule(module) and hasattr(module, '__file__'):    File "/usr/local/lib/python3.6/dist-packages/tensorflow/__init__.py", line 50, in __getattr__      module = self._load()    File "/usr/local/lib/python3.6/dist-packages/tensorflow/__init__.py", line 44, in _load      module = _importlib.import_module(self.__name__)    File "/usr/lib/python3.6/importlib/__init__.py", line 126, in import_module      return _bootstrap._gcd_import(name[level:], package, level)    File "<frozen importlib._bootstrap>", line 994, in _gcd_import    File "<frozen importlib._bootstrap>", line 971, in _find_and_load    File "<frozen importlib._bootstrap>", line 955, in _find_and_load_unlocked    File "<frozen importlib._bootstrap>", line 665, in _load_unlocked    File "<frozen importlib._bootstrap_external>", line 678, in exec_module    File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed    File "/usr/local/lib/python3.6/dist-packages/tensorflow_core/contrib/__init__.py", line 48, in <module>      from tensorflow.contrib import estimator    File "/usr/local/lib/python3.6/dist-packages/tensorflow_core/contrib/estimator/__init__.py", line 30, in <module>      from tensorflow_estimator.contrib import estimator  ModuleNotFoundError: No module named 'tensorflow_estimator.contrib'  ---------------------------------------------------------------------------  error                                     Traceback (most recent call last)      [... skipping hidden 1 frame]    <ipython-input-1-dfbb133297e0> in <module>      116  --> 117     cv2.imshow('frame', frame)      118     cv2.waitkey(0)    error: OpenCV(4.2.0) /home/ubuntu/src/opencv/modules/highgui/src/window.cpp:651: error: (-2:Unspecified error) The function is not implemented. Rebuild the library with Windows, GTK+ 2.x or Cocoa support. If you are on Ubuntu or Debian, install libgtk2.0-dev and pkg-config, then re-run cmake or configure script in function 'cvShowImage'      During handling of the above exception, another exception occurred:    AttributeError                            Traceback (most recent call last)  /usr/local/lib/python3.6/dist-packages/IPython/core/interactiveshell.py in showtraceback(self, exc_tuple, filename, tb_offset, exception_only, running_compiled_code)     2043                         # in the engines. This should return a list of strings.  -> 2044                         stb = value._render_traceback_()     2045                     except Exception:    AttributeError: 'error' object has no attribute '_render_traceback_'    During handling of the above exception, another exception occurred:    TypeError                                 Traceback (most recent call last)      [... skipping hidden 1 frame]    /usr/local/lib/python3.6/dist-packages/IPython/core/interactiveshell.py in showtraceback(self, exc_tuple, filename, tb_offset, exception_only, running_compiled_code)     2045                     except Exception:     2046                         stb = self.InteractiveTB.structured_traceback(etype,  -> 2047                                             value, tb, tb_offset=tb_offset)     2048     2049                     self._showtraceback(etype, value, stb)    /usr/local/lib/python3.6/dist-packages/IPython/core/ultratb.py in structured_traceback(self, etype, value, tb, tb_offset, number_of_lines_of_context)     1434             self.tb = tb     1435         return FormattedTB.structured_traceback(  -> 1436             self, etype, value, tb, tb_offset, number_of_lines_of_context)     1437     1438    /usr/local/lib/python3.6/dist-packages/IPython/core/ultratb.py in structured_traceback(self, etype, value, tb, tb_offset, number_of_lines_of_context)     1334             # Verbose modes need a full traceback     1335             return VerboseTB.structured_traceback(  -> 1336                 self, etype, value, tb, tb_offset, number_of_lines_of_context     1337             )     1338         elif mode == 'Minimal':    /usr/local/lib/python3.6/dist-packages/IPython/core/ultratb.py in structured_traceback(self, etype, evalue, etb, tb_offset, number_of_lines_of_context)     1191     1192         formatted_exception = self.format_exception_as_a_whole(etype, evalue, etb, number_of_lines_of_context,  -> 1193                                                                tb_offset)     1194     1195         colors = self.Colors  # just a shorthand + quicker name lookup    /usr/local/lib/python3.6/dist-packages/IPython/core/ultratb.py in format_exception_as_a_whole(self, etype, evalue, etb, number_of_lines_of_context, tb_offset)     1148     1149  -> 1150         last_unique, recursion_repeat = find_recursion(orig_etype, evalue, records)     1151     1152         frames = self.format_records(records, last_unique, recursion_repeat)    /usr/local/lib/python3.6/dist-packages/IPython/core/ultratb.py in find_recursion(etype, value, records)      449     # first frame (from in to out) that looks different.      450     if not is_recursion_error(etype, value, records):  --> 451         return len(records), 0      452      453     # Select filename, lineno, func_name to track frames with    TypeError: object of type 'NoneType' has no len()    

This is my code. I have taken it from a basic tutorial that I found online to create a simple mask on an image based on Matterport's MRCNN model.

import numpy as np  import tensorflow    print(tensorflow.__version__)    def random_colors(N):      np.random.seed(1)      colors = [tuple(255 * np.random.rand(3)) for _ in range(N)]      return colors      def apply_mask(image, mask, color, alpha=0.5):      """apply mask to image"""      for n, c in enumerate(color):          image[:, :, n] = np.where(              mask == 1,              image[:, :, n] * (1 - alpha) + alpha * c,              image[:, :, n]          )      return image      def display_instances(image, boxes, masks, ids, names, scores):      """          take the image and results and apply the mask, box, and Label      """      n_instances = boxes.shape[0]      colors = random_colors(n_instances)        if not n_instances:          print('NO INSTANCES TO DISPLAY')      else:          assert boxes.shape[0] == masks.shape[-1] == ids.shape[0]        for i, color in enumerate(colors):          if not np.any(boxes[i]):              continue            y1, x1, y2, x2 = boxes[i]          label = names[ids]          score = scores[i] if scores is not None else None          caption = '{} {:.2f}'.format(label, score) if score else label          mask = masks[:, :, i]            image = apply_mask(image, mask, color)          image = cv2.rectangle(image, (x1, y1), (x2, y2), color, 2)          image = cv2.putText(              image, caption, (x1, y1), cv2.FONT_HERSHEY_COMPLEX, 0.7, color, 2          )        return image      if __name__ == '__main__':      """          test everything      """      import os      import sys        from mrcnn import utils      from mrcnn import model as modellib        ROOT_DIR = os.getcwd()      MODEL_DIR = os.path.join(ROOT_DIR, "logs")      COCO_MODEL_PATH = os.path.join(ROOT_DIR, "mask_rcnn_coco.h5")      if not os.path.exists(COCO_MODEL_PATH):          utils.download_trained_weights(COCO_MODEL_PATH)        sys.path.append(os.path.join(ROOT_DIR, "samples/coco/"))  # To find local version      import coco        class InferenceConfig(coco.CocoConfig):          GPU_COUNT = 1          IMAGES_PER_GPU = 1        config = InferenceConfig()      config.display()        model = modellib.MaskRCNN(          mode="inference", model_dir=MODEL_DIR, config=config      )      model.load_weights(COCO_MODEL_PATH, by_name=True)      class_names = [          'BG', 'person', 'bicycle', 'car', 'motorcycle', 'airplane',          'bus', 'train', 'truck', 'boat', 'traffic light',          'fire hydrant', 'stop sign', 'parking meter', 'bench', 'bird',          'cat', 'dog', 'horse', 'sheep', 'cow', 'elephant', 'bear',          'zebra', 'giraffe', 'backpack', 'umbrella', 'handbag', 'tie',          'suitcase', 'frisbee', 'skis', 'snowboard', 'sports ball',          'kite', 'baseball bat', 'baseball glove', 'skateboard',          'surfboard', 'tennis racket', 'bottle', 'wine glass', 'cup',          'fork', 'knife', 'spoon', 'bowl', 'banana', 'apple',          'sandwich', 'orange', 'broccoli', 'carrot', 'hot dog', 'pizza',          'donut', 'cake', 'chair', 'couch', 'potted plant', 'bed',          'dining table', 'toilet', 'tv', 'laptop', 'mouse', 'remote',          'keyboard', 'cell phone', 'microwave', 'oven', 'toaster',          'sink', 'refrigerator', 'book', 'clock', 'vase', 'scissors',          'teddy bear', 'hair drier', 'toothbrush'      ]        #capture = cv2.VideoCapture(0)        # these 2 lines can be removed if you dont have a 1080p camera.      ##capture.set(cv2.CAP_PROP_FRAME_WIDTH, 1920)      #capture.set(cv2.CAP_PROP_FRAME_HEIGHT, 1080)        #while True:      frame = cv2.imread("test_images.jpg")      results = model.detect([frame], verbose=0)      r = results[0]      frame = display_instances(          frame, r['rois'], r['masks'], r['class_ids'], class_names, r['scores']      )        cv2.imshow('frame', frame)      cv2.waitkey(0)      #if cv2.waitKey(1) & 0xFF == ord('q'):       #      break      #capture.release()      cv2.destroyAllWindows()  

Read in browser »
share on Twitter

move element to end of java array

By JohnBigs on Jun 01, 2021 03:58 am

solving something in algoexpert and getting weird index out of bound exception:

the question is simply to take an array and another int and put all the numbers that equal to this int in the end of the array, like this:

array: [2, 1, 2, 2, 2, 3, 4, 2] integer toMove: 2

output: [1,3,4,2,2,2,2,2]

so I wrote this algorithm:

class Program {    public static List<Integer> moveElementToEnd(List<Integer> array, int toMove) {      // Write your code here.          int newArr = new int[array.size()];          int lastIndertedNotToMoveIdx = 0;          int endOfArrayIdx = array.size();          // ArrayList<Integer> list = new ArrayList<Integer>();          for (int i = 0; i <= array.size(); i++) {              if (array.get(i) == toMove) {                  newArr[endOfArrayIdx] = array.get(i);                      endOfArrayIdx = endOfArrayIdx-1;              } else {                  newArr[lastIndertedNotToMoveIdx] = array.get(i);                  lastIndertedNotToMoveIdx++;              }          }          List<Integer> ret_list = new ArrayList<Integer>();        for(Integer num:newArr) {           ret_list.add(num);        }      return ret_list;    }  }  

but here newArr[endOfArrayIdx] = array.get(i); I get this message:

    at Program.moveElementToEnd(Program.java:12)      at AeJsonTest.getActual(AeJsonTest.java:27)      at Main.main(Main.java:57)```    not sure why...  

Read in browser »
share on Twitter

How to print RDLC report voucher exactly one page?

By Myat Po Po Aung on Jun 01, 2021 03:58 am

I want to print report voucher exactly one page. Although my first page left space, my voucher divide two page


Read in browser »
share on Twitter

Ajax-JQuery-Chartjs Uncaught TypeError: response is undefined

By TsioryHL on Jun 01, 2021 03:58 am

[console][1] this image contains the console error...my declaration of charts.init() and charts.CreateCompletedJobChart() is indefined [code][2] [1]: https://i.stack.imgur.com/n2Ied.png [2]: https://i.stack.imgur.com/g0a4C.png


Read in browser »
share on Twitter

pandas-dev installation (How to install Pandas 1.3.0)

By M4RC0Sx on Jun 01, 2021 03:47 am

I've seen that on Pandas version 1.3.0.dev0+1779.gdcc2a8f801 there is a new implemented method (read_xml) and I would like to use it. The problem is that I have not found a way to install a development version of Pandas. i am currently using Python3 and pip and have tried from its source repository (Pandas-dev page)

How could I deal with that? Maybe using Conda or compiling it myself? I don't know exactcly how to do it...


Read in browser »
share on Twitter

Running a bash script stored in a variable

By Ahmed Tarek on Jun 01, 2021 03:45 am

I want to send the path to a bash script which sources some environmental variables as an argument to another bash script to run it and use the environmental variables. It works well with no arguments if I hard coded the path to the bash script to run it works and I can retrieve the environmental variables in the main script. the problem happens when I send the path as an argument it does not want to run it. for example if the path is /path/script.bash and I send the path as an argument I get the error that /path/env_set: No such a file or directory I run the script by this line

. $1 (this doesn't work)  . /path/script.bash (this works)  

I don't know why env_set replaces the script name when I use arguments. Is there any approach to achieve this or any work around to achieve my goal?


Read in browser »
share on Twitter

Is there a way to halt loading a react app until authentication status is resolved?

By Sougata Ghosh on Jun 01, 2021 03:42 am

I'm loading a react app that has a root component App.js which is determining if an authenticated user exists through a central redux store, but the problem is it takes a fraction of a second to resolve. Until then the user is getting a flash of the login page even if the user is logged in, which I'm sure counts as bad user experience. Is there a way to not show anything at all until the the status is resolved. I'm attaching a code snippet.

function App(props) {    const cookies = new Cookies();    const { user } = props;    if (cookies.get("authToken") === "null" || cookies.get("authToken") === undefined) {      //console.log("no valid token");    } else {      if (user === null) {        props.fetchLoggedInUser(cookies.get("authToken"));      }    }      const isLoggedIn = user ? (      <div className="App s12 l12 m12">        <Navbar user={user}/>        <Switch>          <Route exact path="/" component={() => (<Home user={user} />)}></Route>          <Route exact path="/create_blog" component={() => (<CreateBlog user={user} />)}></Route>          <Route exact path="/edit_profile" component={() => (<EditProfile user={user} />)}></Route>        </Switch>      </div>    ) : (      <div className="App">        <Navbar user={null}/>        <Switch>          <Route exact path="/" component={() => (<Home user={null} />)}></Route>          <Route exact path="/log_in" component={LogIn}></Route>          <Route exact path="/sign_up" component={SignUp}></Route>        </Switch>      </div>    );      return (      <BrowserRouter>        {isLoggedIn}      </BrowserRouter>    );  }    const mapStateToProps = (state) => {    return {        authError: state.auth.authError,        token: state.auth.token,        user: state.auth.user    }  }    const mapDispatchToProps = (dispatch) => {    return {      fetchLoggedInUser: (token) => dispatch(fetchLoggedInUser(token))    }  }    export default connect(mapStateToProps, mapDispatchToProps)(App);  

Read in browser »
share on Twitter

How do I add random times to to_date datatype?

By wjack_backsstreeu on Jun 01, 2021 03:39 am

The following statements will be executed.

select current_timestamp + dbms_random.value(40, 59) minute from dual;  

The statement I want doesn't work.

to_date('2021-01-05:08:50:00', 'yyyy-mm-dd:hh24:mi:ss') + dbms_random.value(40, 59) minute;

I am getting the error <analytic clause>, '@', KEEP or WITHIN expected, got 'minute' and

I am wondering how to solve this.


Read in browser »
share on Twitter

How to generate "make:model -a" with directory for seeders and controller and migrate name?

By amberlex78 on Jun 01, 2021 03:36 am

How to generate "make:model -a" with directory for seeders and controller and migrate name?

Laravel Framework 8.44.0

I am generating a model php artisan make:model Blog/MyCategory -a and expect to see the following structure:

Controllers/Blog/MyCategoryController.php  Models/Blog/MyCategory.php  factories/Blog/MyCategory.php  mifrations/2021_06_01_042639_create_blog_my_categories_table.php  seeders/Blog/MyCategorySeeder.php  

Execute the command php artisan make:model Blog/Category -a

Model created successfully.  Factory created successfully.  Created Migration: 2021_06_01_044253_create_my_categories_table  Seeder created successfully.  Controller created successfully.  

but it creates

Controllers/MyCategoryController.php (NO)  Models/Blog/MyCategory.php (YES)  factories/Blog/MyCategory.php (YES)  mifrations/2021_06_01_042639_create_my_categories_table.php (NO)  seeders/MyCategorySeeder.php (NO)  

This way I cannot generate two MyCategory.

Execute the command php artisan make:model Shop/MyCategory -a

Model created successfully.  Factory created successfully.       InvalidArgumentException      A CreateMyCategoriesTable class already exists.      at vendor/laravel/framework/src/Illuminate/Database/Migrations/MigrationCreator.php:102    

Remove the

  • model Shop/MyCategory.php,
  • factory Shop/MyCategoryFactory.php
  • migration file 2021_06_01_044253_create_my_categories_table.php

Now let's create the correct migration file

  • php artisan make:migration CreateBlogMyCategoryTable

Again execute the command php artisan make:model Shop/MyCategory -a

Model created successfully.  Factory created successfully.  Created Migration: 2021_06_01_050039_create_my_categories_table  Seeder already exists!  Controller already exists!  

It again creates a 2021_06_01_050039_create_my_categories_table file and does not take into account the model in the Shop directory

Remove generated files again:

  • model Shop/MyCategory.php
  • factory Shop/MyCategoryFactory.php
  • migration file 2021_06_01_050039_create_my_categories_table.php
  • controller MyCategoryController.php

Now let's create the correct migration and controllers:

  • php artisan make:migration CreateShopMyCategoryTable
  • php artisan make:controller Blog/MyCategoryController
  • php artisan make:controller Shop/MyCategoryController

Total

Thus, we see that the "-а" option is not suitable in this case. You need to create models, controllers and migrations separately.

php artisan make:controller Blog/MyCategoryController -r  php artisan make:controller Shop/MyCategoryController -r  php artisan make:migration CreateBlogMyCategoryTable  php artisan make:migration CreateShopMyCategoryTable  

Model with factory

php artisan make:model Blog/MyCategory -f  php artisan make:model Shop/MyCategory -f  

This command also makes the correct Factory

php artisan make:factory Blog\\MyCategoryFactory --model=Blog\\MyCategory

<?php    namespace Database\Factories\Blog;    use App\Models\Blog\MyCategory;  use Illuminate\Database\Eloquent\Factories\Factory;    class MyCategoryFactory extends Factory  {      /**       * The name of the factory's corresponding model.       *       * @var string       */      protected $model = MyCategory::class;        // ....  }  

The migration files, models, and controllers as we need in the appropriate directories.

php artisan migrate  Migration table created successfully.  ...  Migrating: 2021_06_01_055036_create_blog_my_category_table  Migrated:  2021_06_01_055036_create_blog_my_category_table (36.26ms)  Migrating: 2021_06_01_055541_create_shop_my_category_table  Migrated:  2021_06_01_055541_create_shop_my_category_table (39.16ms)  

As I understand it, the required structure will still have to be done by separate commands.

But then another problem appeared: I do not understand how to use now factory()->create()

Route::get('/', function () {      \App\Models\Blog\MyCategory::factory(1)->create();      return view('welcome');  });  
Illuminate\Database\QueryException  SQLSTATE[42S02]: Base table or view not found: 1146 Table 'larablog.my_categories' doesn't exist (SQL: insert into `my_categories` (`updated_at`, `created_at`) values (2021-06-01 06:59:52, 2021-06-01 06:59:52))  

or tinker

php artisan tinker  Psy Shell v0.10.8 (PHP 7.4.18 — cli) by Justin Hileman    >>> MyCategory::factory()->create()  PHP Error:  Class 'MyCategory' not found in Psy Shell code on line 1    >>> Blog\MyCategory::factory()->create()  PHP Error:  Class 'Blog\MyCategory' not found in Psy Shell code on line 1    >>> \Blog\MyCategory::factory()->create()  PHP Error:  Class 'Blog\MyCategory' not found in Psy Shell code on line 1    >>> App\Models\Blog\MyCategory::factory()->create()  Illuminate\Database\QueryException with message 'SQLSTATE[42S02]: Base table or view not found: 1146 Table 'larablog.my_categories' doesn't exist (SQL: insert into `my_categories` (`updated_at`, `created_at`) values (2021-06-01 06:48:26, 2021-06-01 06:48:26))'    >>> \App\Models\Blog\MyCategory::factory()->create()  Illuminate\Database\QueryException with message 'SQLSTATE[42S02]: Base table or view not found: 1146 Table 'larablog.my_categories' doesn't exist (SQL: insert into `my_categories` (`updated_at`, `created_at`) values (2021-06-01 06:48:29, 2021-06-01 06:48:29))'  

How to make such a structure work?


Read in browser »
share on Twitter

After a != null check I still get "Argument of type 'string | undefined' is not assignable to parameter of type 'string'"

By kilianc on Jun 01, 2021 03:26 am

Given message.text: string | undefined I check for nil and go on with my code assuming that TS inferred the new type to string. You can see that it does when I do const text = message.text.

The type check fails when I call regExp.test(message.text) and I can't explain why. This function is sync, mutability is not possible. What am I missing?

You can fiddle around the TS playground I created

type Message = { text?: string }    const urlIgnoreList = [    /a/,    /b/,    /c/  ]    const shouldProcessMessage = (message: Message) => {    if (message.text == null) {      return false    }      if (message.text.startsWith(`!`)) {      return false    }      // why does this type check fail?    if (urlIgnoreList.some((regExp) => regExp.test(message.text))) {      return false    }      // this is fine as I expected    const text = message.text    if (urlIgnoreList.some((regExp) => regExp.test(text))) {      return false    }      return true  }  

TS Error on line 19:

Argument of type 'string | undefined' is not assignable to parameter of type 'string'.    Type 'undefined' is not assignable to type 'string'.ts(2345)  

Read in browser »
share on Twitter

Can't take the result from JSON data. I take the undefined result

By nilufer17 on Jun 01, 2021 03:23 am

I want to reach out SpeechRegions' datas in Channel. When i write "console.log(speech.Channels)", i can see this json data below. But when i write "console.log(speech.Channels.SpeechRegions)", it gives me undefined. Can you explain to me its reason?

Channels: [      {        SilenceRegions: ,        SpeechRegions: [Array],        SilenceDuration: 0,        SpeechDuration: 8.68,        SilenceRatio: 0,        SpeechRatio: 1,        InterruptCount: 0,        Channel: 0      }    ],  

Read in browser »
share on Twitter

Creating a list of N numbers from existing list each repeated K times

By O. Mohsen on Jun 01, 2021 03:18 am

I believe this is an easy problem to solve. I have searched and found a few similar answers but not an efficient way to exactly what I want to achieve.

Assuming the following list:

x = [6, 7, 8]  

I want to create a new list by repeating each number k times. Assuming k=3, the result should be:

xr = [6, 6, 6, 7, 7, 7, 8, 8, 8]  

I was able to accomplish this using nest loops, which I believe is very inefficient:

xr =  for num in x: # for each number in the list      for t in range(3): # repeat 3 times          xx2.append(num)  

I also tried:

[list(itertools.repeat(x, 3)) for i in range(len(x))]  

but I get:

[[6, 6, 6], [7, 7, 7], [8, 8, 8]]  

Is there a more efficient direct method to accomplish this?


Read in browser »
share on Twitter

Calculate Grades average wihout using arrays [closed]

By Mohammad Iraqi on Jun 01, 2021 03:12 am

I need to count grades greater than the class Average based in the following terms:

  1. arrays cant be used to solve this question
  2. No complicated data types can be used such as trees, stacks etc...
  3. Students number is unknown
  4. The programe will stop when the user insert -1 as agrade. Thanks

Read in browser »
share on Twitter

Column bind several list elements based on id variable

By deschen on Jun 01, 2021 03:06 am

Assuming the following list:

a <- data.frame(id = 1:3, x  = 1:3)  b <- data.frame(id = 3:1, y  = 4:6)  my_list <- list(a, b)    my_list  # []  #   id x  # 1  1 1  # 2  2 2  # 3  3 3    # []  #   id y  # 1  3 4  # 2  2 5  # 3  1 6  

I now want to column bind the list elements into a data frame/tibble while matching the respective rows based on the id variable, i.e. the outcome should be:

# A tibble: 3 x 3       id     x     y    <int> <int> <int>  1     1     1     6  2     2     2     5  3     3     3     4  

I know how I can do it with some pivoting, but I'm wondering if there's a smarter way of doing it and I hoped there was some binding function that simply allows for specifying an id column?

Current approach:

library(tidyverse)  my_list %>%    bind_rows() %>%    pivot_longer(cols = -id) %>%    filter(!is.na(value)) %>%    pivot_wider()  

Read in browser »
share on Twitter

Locking an object and all child objects

By Harry Will on Jun 01, 2021 01:26 am

In this answer given on implementing a thread-safe tree by jim-mischel, he states:

The easiest way to do this would be to protect the entire tree with a ReaderWriterLockSlim. That allows concurrent access by multiple readers or exclusive access by a single writer. Any method that will modify the structure in any way will have to acquire the write lock, and no other threads will be allowed to read or write to the structure until that thread releases the write lock.

If I'm following correctly, this would mean that the methods/properties for the tree structure would look something like:

    public class TreeNode      {            private String BackingData = "";          public String Data          {              get              {                  lock (LockObject)                      return BackingData;              }              set              {                  lock (LockObject)                      BackingData = value;              }          }            private TreeNode BackingParent { get; set; }          public TreeNode Parent          {              get              {                  lock (LockObject)                      return BackingParent;              }          }            //etc...            private List<TreeNode> BackingChildren { get; }          private Object LockObject { get; }            TreeNode()          {              BackingData = "";              BackingParent = null;              BackingChildren = new List<TreeNode>();              LockObject = new Object();          }        }  

The thing is, this is not protecting the entire tree - it's protecting not even individual nodes of a tree, and even then only the individual methods/properties.

How could this be arranged such that the entire tree is protected?

I did think about holding a static class that maps the root TreeNodes to an Object. Then, having a couple of methods in this static class that lock and unlock according to the root TreeNode using the Monitor methods. The Monitor.IsEntered method could be used within the TreeNodes, but to check that this is locked, we'd still need to walk up the unlocked tree to get the root TreeNode. Even then, I wouldn't know how to handle if IsEntered was false.

Is there any suitable way to lock an object, and thus all child objects that may be held by said object?


Read in browser »
share on Twitter

Issues with the output size of a Many-to-Many CNN-LSTM in PyTorch

By Mohamed Moustafa on May 31, 2021 03:16 pm

I am trying to build a binary temporal image classifier by combining ResNet18 and an LSTM. However, I have never really used RNNs before and have been struggling on getting the correct output shape.

I am using a batch size of 128 and a sequence size of 32. The images are 80x80 grayscale images.

The current model is:

class CNNLSTM(nn.Module):      def __init__(self):          super(CNNLSTM, self).__init__()          self.resnet = models.resnet18(pretrained=False)          self.resnet.conv1 = nn.Conv2d(1, 64, kernel_size=7, stride=2, padding=3)          self.resnet.fc = nn.Sequential(nn.Linear(in_features=512, out_features=256, bias=True))            self.lstm = nn.LSTM(input_size=256, hidden_size=256, num_layers=3)          self.fc1 = nn.Linear(256, 128)          self.fc2 = nn.Linear(128, 1)        def forward(self, x_3d):          #x3d:  torch.Size([128, 32, 1, 80, 80])          hidden = None          toret  =          for t in range(x_3d.size(1)):              x = self.resnet(x_3d[:, t, :, :, :])                out, hidden = self.lstm(x.unsqueeze(0), hidden)              x = self.fc1(out[-1, :, :])              x = F.relu(x)              x = self.fc2(x)              print("x shape: ", x.shape)                toret.append(x)          return torch.stack(toret)  

Which returns a tensor of shape torch.Size([32, 128, 1]) which, according to what I understand, means that every nth row represents the nth time step of each element in the sequence.

How can I get output of shape 128x1x32 instead?

And is there a better way to do this?


Read in browser »
share on Twitter

How to get data from a local JSON file with fetch

By Nico on May 31, 2021 01:45 pm

I reckon this might be an old topic but I begin with Javascript... I get this error in my Javascript base code : "Fetch API cannot load file:///C:/Users[...]data.json. URL scheme must be "http" or "https" for CORS request"

All the answers I see online says that a local server is needed to use fetch with a file. But I would need to find solutions without using a local server.

Here is my code :

function getData() {

fetch('data.json')      .then(res => res.json())      .then(data => {          console.log(data)      })  

};

getData();

My files HTML et JS are well linked and my file data.json is located in the same folder.

Somebody (who has understood my problem :) could give me some help/advice please? Thanks


Read in browser »
share on Twitter




Recent Articles:

Remove AtomicInteger counter from stream
Prevent unchecked changes from merging into main branch
Mono.Linker.MarkException: Error processing method: 'System.Void AndroidX.RecyclerView.Widget.RecyclerView/LayoutManager
Jetpack Compose: Disable Interaction with TextField
Don't have Bisect Tool icon (Blender 2.90.1)
Twitter
Facebook
Website
Copyright © 2021 reader, All rights reserved.
You are receiving this email because you opted in via our website.

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

Add us to your address book


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

Email Marketing Powered by Mailchimp

No comments:

Post a Comment