Monday, July 26, 2021

Recent Questions - Stack Overflow

Recent Questions - Stack Overflow


Is it OK to have different versions of python?

Posted: 26 Jul 2021 07:49 AM PDT

I have a CentOS machine:

[JohnRambo@Machine ~]$ cat /etc/os-release    NAME="CentOS Linux"  VERSION="7 (Core)"  

With the following python and pip's versions installed:

[JohnRambo@Machine ~]$ ls -ls /usr/bin/python*   0 lrwxrwxrwx. 1 root root     7 Jul 22 09:56 /usr/bin/python -> python2   0 lrwxrwxrwx. 1 root root     9 Jul 22 09:56 /usr/bin/python2 -> python2.7   8 -rwxr-xr-x. 1 root root  7144 Nov 16  2020 /usr/bin/python2.7   0 lrwxrwxrwx. 1 root root     9 Jul 22 10:14 /usr/bin/python3 -> python3.6  12 -rwxr-xr-x. 2 root root 11328 Nov 16  2020 /usr/bin/python3.6   0 lrwxrwxrwx. 1 root root    17 Jul 22 10:15 /usr/bin/python3.6-config -> python3.6m-config  12 -rwxr-xr-x. 2 root root 11328 Nov 16  2020 /usr/bin/python3.6m   4 -rwxr-xr-x. 1 root root   173 Nov 16  2020 /usr/bin/python3.6m-config   4 -rwxr-xr-x. 1 root root  3403 Nov 16  2020 /usr/bin/python3.6m-x86_64-config   0 lrwxrwxrwx. 1 root root    16 Jul 22 10:15 /usr/bin/python3-config -> python3.6-config    [JohnRambo@Machine ~]$ python --version  Python 2.7.5    [JohnRambo@Machine ~]$ python3 --version  Python 3.6.8    [JohnRambo@Machine ~]$ which python  /usr/bin/python    [JohnRambo@Machine ~]$ which python3  /usr/bin/python3    [JohnRambo@Machine ~]$ pip --version  pip 8.1.2 from /usr/lib/python2.7/site-packages (python 2.7)    [JohnRambo@Machine ~]$ pip3 --version  WARNING: pip is being invoked by an old script wrapper. This will fail in a future version of pip.  Please see https://github.com/pypa/pip/issues/5599 for advice on fixing the underlying issue.  To avoid this problem you can invoke Python with '-m pip' instead of running pip directly.  pip 21.2.1 from /home/JohnRambo/.local/lib/python3.6/site-packages/pip (python 3.6)    [JohnRambo@Machine ~]$ which pip  /usr/local/bin/pip    [JohnRambo@Machine ~]$ which pip3  /usr/local/bin/pip3  

And with the following Anaconda/Conda versions installed:

[JohnRambo@Machine ~]$ anaconda --version  anaconda Command line client (version 1.7.2)    [JohnRambo@Machine ~]$ which anaconda  ~/anaconda3/bin/anaconda    [JohnRambo@Machine ~]$ conda --version  conda 4.5.11    [JohnRambo@Machine ~]$ which conda  ~/anaconda3/bin/conda    [JohnRambo@Machine ~]$ conda info         active environment : base      active env location : /home/JohnRambo/anaconda3              shell level : 1         user config file : /home/JohnRambo/.condarc   populated config files :             conda version : 4.5.11      conda-build version : 3.15.1           python version : 3.7.0.final.0         base environment : /home/JohnRambo/anaconda3  (writable)             channel URLs : https://repo.anaconda.com/pkgs/main/linux-64                            https://repo.anaconda.com/pkgs/main/noarch                            https://repo.anaconda.com/pkgs/free/linux-64                            https://repo.anaconda.com/pkgs/free/noarch                            https://repo.anaconda.com/pkgs/r/linux-64                            https://repo.anaconda.com/pkgs/r/noarch                            https://repo.anaconda.com/pkgs/pro/linux-64                            https://repo.anaconda.com/pkgs/pro/noarch            package cache : /home/JohnRambo/anaconda3/pkgs                            /home/JohnRambo/.conda/pkgs         envs directories : /home/JohnRambo/anaconda3/envs                            /home/JohnRambo/.conda/envs                 platform : linux-64               user-agent : conda/4.5.11 requests/2.19.1 CPython/3.7.0 Linux/3.10.0-862.14.4.el7.x86_64 centos/7 glibc/2.17                  UID:GID : 1001:1001               netrc file : None             offline mode : False  

QUESTION 1: Is it normal to have 2 or 3 versions of python installed? If Yes, how can I set up the most recent/updated (python 3.7 or something) as default? (could you tell me how to do it step-by-step please?)

QUESTION 2: My pip and pip3 are installed in /usr/local/bin, but my python and python3 are installed in /usr/bin. Is there a way to put all of them in the same folder, such as /usr/bin? Or it is not necessary?

QUESTION 3: With the installation of Anaconda (from https://linuxize.com/post/how-to-install-anaconda-on-centos-7/), a third Python's version came with it. Now, which one should I use? That one in ~/anaconda3/bin (i.e. 3.7) or that one in /usr/bin (i.e. 3.6.8)?

In summary, I am a confused about all these versions and I do not know if it is OK for my machine to keep all of them, or if it is better to just keep one version of python (and just in one folder). Please, if possible, could you clarify these points for me, and, in case of a messy installations/versions (as you can see from my terminal information), could you tell me how to uninstall and reinstall step-by-step the correct version and keep a tidy "installation" of an update version of python?

All the Best

How do I locate Actual Amount in the table and write 0 value in the below html

Posted: 26 Jul 2021 07:49 AM PDT

Наличные Maestro OFF American Express OFF MasterCard OFF Visa Card OFF China Union Pay OFF ALI PAY OFF MIR

How to reduce R portable and /or packages size?

Posted: 26 Jul 2021 07:49 AM PDT

I have a "portable" shiny application that uses DesktopDeployR and therefore requires a R portable core.

Since the app also requires several R packages, I was wondering if it could be possible to reduce the size of the overall app package (shiny app + R core + R packages) without too much harm, like for instance removing the *.html files (which are numerous, not quite heavy together but add substantial time for (un)zipping tasks)?

  • Shiny app is less than 1 mo,
  • R core is around 200 mo,
  • R packages around 200 mo as well (they unfortunately have to be local, can't be re-downloaded by the end user).

Denoise FFT out of csv file

Posted: 26 Jul 2021 07:49 AM PDT

i would like to denoise my FFT Signal.

The Code i got is shown here:

from numpy.fft import rfft, rfftfreq  import matplotlib.pyplot as plt  import pandas as pd      dt=1/10000    f=pd.read_csv('test.csv', sep = ';', skiprows=[1,2],usecols = [4],dtype=float, decimal=',')      n=len(f)       acc=f.values.flatten()     fft=rfft(acc)*dt  freq=rfftfreq(n,d=dt)    FFT=abs(fft)    plt.plot(freq,FFT)  plt.show()  

The FFT plot i am able to create by using this Code is shown here: enter image description here

Could any of you help me to denoise my fft ?

Python JSON5: Map JSON object back to line/column of source?

Posted: 26 Jul 2021 07:49 AM PDT

I am using the JSON5 module in my program. The module is mainly API-compatible to the standard Python JSON module – it just accepts JSON5 syntax instead of standard JSON.

When the script analyzes the JSON structure that was read from its input file, there may be high-level errors, i.e. not JSON syntax errors. At this time the input position is lost as I understand, but providing the user with a line/column number would be quite helpful.

I already found this SO article but there seemed to be no solution to a similar problem involving the standard JSON module.

Maybe someone has an idea if some of the hook mechanisms provided by the API could be used to insert line/column data into the generated data structure at JSON "compile" time?

import json5  data = json5.load(jsonfile) # add some foo here…  if data["key1"] != 123:    print(f'wrong value for key1 at line {data["key1"].__line__}, col {data["key1"].__col__}')  

keyboard typing simulator with luascript for ios?

Posted: 26 Jul 2021 07:49 AM PDT

I am using autotouch for ios. With this tweak, I can type text using inputText function. But I want to use tap(x,y) function to type on iphone's keyboard. It seems a bit confusing, I will give an example as follows. The text I need to type is: "I Love You" I will position the letters according to the coordinates of the keyboard and use the function tap(x,y):

I = tap(486,767);  Space = tap(229,1100);  L = tap(583,875);  .......  

That's my idea, but I'm a newbie so I don't have enough knowledge to make a working script. Help me. Thank you so much

Instance of abstract class in Kotlin and calling abstract function without overriding

Posted: 26 Jul 2021 07:49 AM PDT

I am doing this google codelab android-room-with-a-view-kotlin. This is the link to codelab https://developer.android.com/codelabs/android-room-with-a-view-kotlin. At the 8th step when creating room database they have used this code

// Annotates class to be a Room Database with a table (entity) of the Word class  @Database(entities = arrayOf(Word::class), version = 1, exportSchema = false)  public abstract class WordRoomDatabase : RoomDatabase() {       abstract fun wordDao(): WordDao       companion object {          // Singleton prevents multiple instances of database opening at the          // same time.           @Volatile          private var INSTANCE: WordRoomDatabase? = null            fun getDatabase(context: Context): WordRoomDatabase {              // if the INSTANCE is not null, then return it,              // if it is, then create the database              return INSTANCE ?: synchronized(this) {                  val instance = Room.databaseBuilder(                          context.applicationContext,                          WordRoomDatabase::class.java,                           "word_database"                      ).build()                  INSTANCE = instance                  // return instance                  instance              }          }     }  }  

I want to ask why there is no error in these 2 lines (val exam & val dao) where I create an instance of this abstract class (in class A) and then call its abstract function(getNoteDao) without overriding it.

class A{    val exam : WordRoomDatabase = WordRoomDatabase.getDatabase(application)   val dao = exam.getWordDao()  }  

Since we know we need to override the abstract function and can not directly call it but what's happening there. why is there no error

Call Routing Function in Angular 12/Angular JS from their Displaying iframes

Posted: 26 Jul 2021 07:49 AM PDT

I have a server hosting an Angular 12 and an Angular JS application. My end goal is to seamlessly transition between both applications without re-loading either. My current solution is a static HTML page with 2 nested iframes.

<iframe id="JS" style="display: block;" src="angularJS">  <iframe id="12" style="display: none;" src="angular12">  

Then within each app, using window.parent.document.getElementById('JS').style.display = "none"; window.parent.document.getElementById('12').style.display = "block"; to switch between the two. My only issue is I can only change routes by updating the iframe source which causes the app to load again.

Is there a way to call each application's router functions rather than update the source in the iframe? Or is there a way to host both side by side without causing a reload other than using iframes?

Create a folder and write multiple files on a loop

Posted: 26 Jul 2021 07:48 AM PDT

I am trying to write a number of files in node to a specific folder, but I am having some issues when creating the folder:

I got an upload.js file that recieves two files from the front end, then I am using a async for loop not to block the event loop, and I have a function that I run for each file it receives, this funtion checks if the folder exists and if not it creates it:

import Router from 'express'  import multer from 'multer'  import { constants } from 'fs'  import { writeFile, mkdir, access, rm } from 'fs/promises'    async function asyncForEach(array, callback) {    for (let i = 0, j = array.length; i < j; i++) {      await callback(array[i], i, array)    }  }    router.put('/', upload.array('files', 5), async (req, res) => {    const { files } = req    const { domain, type } = req.query      const temporalFolder = `./tmp_${getDomain(domain)}_${type.toLocaleLowerCase()}`      const writeToFolder = async (name, file) => {      console.log(name)      try {        await access(temporalFolder, constants.R_OK | constants.W_OK)      } catch (error) {        await mkdir(temporalFolder)      } finally {        await writeFile(resolve(temporalFolder, name), file)      }    }      await asyncForEach(files, async (file) => {       const { originalname, buffer } = file      writeToFolder(originalname, buffer)    }      res.end()  })    export default router  

If the folder is already created I get no error and it works fine, but the first time when the folder does not exist I get this even thou all works:

[Error: EEXIST: file already exists, mkdir './tmp_google_com_standard'] {     errno: -17,     code: 'EEXIST',     syscall: 'mkdir',     path: './tmp_google_com_standard'  }  

How to wait for the IP when hiting Curl Command

Posted: 26 Jul 2021 07:49 AM PDT

I am hitting an API using Curl command which create an EC2 instance in AWS and return the private IP of EC2 instance.

  1. newrigprivateip=$(curl -X POST -H "Content-Type:application/json" -d "'{AMI_ID:'ami-9xxxxxx'}'" $posturl)
  2. echo $newrigprivateip > $build

Now sometimes my private IP takes time to generate and because of that my script failed. Can we write the curl command in such a way that it will wait for the EC2 instance to up and wait until the private IP return.

Is there a way to get input data from createElement() function in React

Posted: 26 Jul 2021 07:48 AM PDT

 let x_rows = 2;   addNewRow = () => {             let bundle_of_rows = document.createElement("div");        while (x_rows - 1 >= 0) {        let a_row = document.createElement("input");        bundle_of_rows.appendChild(a_row);        x_rows--;      }        document.getElementById("sub-main").appendChild(bundle_of_rows);    };    

This code would create something like this...

<div>     <input></input>     <input></input>  </div>  

and, then it would append it to "sub-main"

<div id="sub-main">    <div>       <input></input>       <input></input>    </div>  </div>  

I want to store the values of "input" like onChange that should update this.state = {input: ""}. Is there a way to give attributes to these inputs? /must use createElement() /

Spring Boot 2.5 and Spring Data: @NoRepositoryBean unexpected behaviour in multi-module project

Posted: 26 Jul 2021 07:49 AM PDT

I'm facing the following issue in a legacy code that I can't change. I have a multi module project which defines in the commons module a Spring Data interface as below:

package commons;  ...  @NoRepositoryBean  public interface MyCustomRepository<P, I extends Number> extends JpaRepository<MyEntity, Integer>  {    MyEntity getOneAndCheck();  }  

In another module I extend this interface as follows:

package data;  ...  @Repository  public interface MyRepository extends MyCustomRepository<MyEntity, Integer>  {    ...  }  

So, the idea is that I don't want that Spring Data generates any implementation for the MyEntity getOneAndCheck() method 'cause it is implemented like this:

package data;  ...  public class MyCustomRepositoryImpl implements MyCustomRepository  {    ...    @Override    public MyEntity getOneAndCheck()    {      ...    }    ...  }  

However, when I'm starting the application, I get the following exception:

...  Caused by: java.lang.IllegalArgumentException: Failed to create query for method public abstract MyEntity commons.MyCustomRepository.getOneAndCheck()! No property getOne found for type MyEntity!  ...  

So what it seems to happen is that Spring Data tries to generate a Query for the MyEntity getOneAndCheck() method, despite the @NoRepositoryBean annotation. This works as expected in the application I'm gonna migrate from Spring 3 with Spring Data to Spring Boot 2.5.

Not sure if the described behavior has anything to do with the fact that there are multiple Maven modules and that the repositories, the entities and the DTOs are in different modules. Not sure neither if there should be any difference between the way it runs currently with Spring and the one with Spring Boot. But the result is that all of the dozens of repositories in this legacy application are failing with the mentioned exception.

Any suggestion please ?

Many thanks in advance.

Kind regards,

Seymour

Browser forward button not active with React.js

Posted: 26 Jul 2021 07:49 AM PDT

I have a react application using typescript that is set up like a wizard with different pages in each step. I have a 'Forward' and 'Back' button on the page that I created and they work just fine. What the problem is the browser forward button, I got the back button working. Everytime i go back either using the browser button or my custom back button the forward button is always disabled.

on one page I have this code that fixes my back button

const [finishStatus, setFinishStatus] = useState(false)  const onBackButtonEvent = () => {     if (!finishStatus) {    setFinishStatus(true)    history.push('previous page')     }    }       useEffect(() => {     window.history.pushState(null, 'null', window.location.pathname)     window.addEventListener('popstate', onBackButtonEvent)     return () => {       window.removeEventListener('popstate', onBackButtonEvent)     }    }, [])  

can i do something similar to this for the forward button? I have tried several solutions I have found but nothing is working.

Thanks

Unique combination of two columns with mixed values

Posted: 26 Jul 2021 07:49 AM PDT

I have two columns with col1 and col2

enter image description here

I'm trying to create the key column to show that a and b is the same as b and a

Problem code:

import pandas as pd  pd.DataFrame({'Col1':['a','c','b','e'],                'Col2':['b','d','a','f']})  

How to count all the products that belongs to category(slug) Laravel 8

Posted: 26 Jul 2021 07:48 AM PDT

I am a beginner in Laravel. I need a little help. I have an index.blade.php file which displays all the category names. When I click on on it will generate the slug link where I have all the products that in the category. So I would like to count only those products that is belongs to category's slug and display the number on the index.blade.php. Thanks for the help.

 Route::get('view-category/{slug}', [ProductsController::class,'viewcategory']);  

productsController:

public function viewcategory($slug){          if(Category::where('slug', $slug)->exists()){              $category = Category::where('slug', $slug)->first();              $products = Products::where('cateId', $category->id)->where('status','1')->get();              return view('admin.products.display', compact('category','products'));          }          else{              return redirect('/dashboard')->with('status',"Slug does not exist");          }      }  

category Model:

class Category extends Model  {      use HasFactory;      protected $table = "categories";      protected $fullable = [          'name',          'slug',          'description',          'status',          'popular',      ];      public function products(){          return $this->belongsTo(Products::class, 'id', 'cateId');      }  }  

index.blade.php:

<thead>                <tr>                  <th></th>                  <th>Product Name</th>                  <th>Category</th>                  <th>Sub Category</th>                  <th>Variations</th>                  <th>Status</th>                  <th>Action</th>                </tr>              </thead>              <tbody>                @foreach($category as $item)                  <tr>                    <td class="control" tabindex="0"></td>                    <td>{{$item->products->productName}}</td>                    <td>{{$item->name}}</td>                    <td>{{$item->subCategory}}</td>                    <td>{{$item->counter}}</td>                    <td></td>                    <td></td>                  </tr>                @endforeach              </tbody>        </table>  

File transform byte[] ,and then byte[] transfrom String, last String transform byte[] again ,two byte[] is not equal [closed]

Posted: 26 Jul 2021 07:48 AM PDT

step1 picture transfrom byte[]; step2 byte[] bytes transfrom String ; step3 String transform byte[] newBytes; step4 two byte[] transform Picture; and bytes is successful ,ohter one is bad , What should I do Thanks

import org.apache.commons.io.FileUtils;  File imgFile = new File("/Users/benben/Desktop/aa.jpg");  FileInputStream fis = new FileInputStream(imgFile);  byte[] bytes = new byte[fis.available()];  fis.read(bytes);  fis.close();  String imgStr = new String(bytes);  byte[] newBytes = imgStr.getBytes();  FileUtils.writeByteArrayToFile(new File("/Users/benben/Desktop/bytes.jpg"),bytes);//successful  FileUtils.writeByteArrayToFile(new File("/Users/benben/Desktop/aa/newBytes.jpg"), newBytes);//failure    

converting german data formating to universal pandas formatiing

Posted: 26 Jul 2021 07:49 AM PDT

I have a data frame with german formatted data, that ie 1,29 in universal format means 1.29 while 1.56 in universal format means 156 pieces, currently my python script is reading 1,29 as a string and 1.56 as 1.56 whereas in my ideal solution it should be 1.29 float and 156 as integer.

Also, the correct value for this 24.386999999999997 in CSV file is 24.387 which in reality means 24387 (integer) but pandas is reading otherwise.

The data is as below

  Row    Date    c_s  eV      eC_r    D_O_p   D_Q_p   D_V_E_p   1   2018-03-01  FR  34.598  1,29    445.0   1.56    24.386999999999997    2   2018-03-01  DE  159.779 3,01    4.804   24.976  407.38300000000004    3   2018-03-01  AT  19.878  4,96    985.0   7.703   93.19     4   2018-03-01  PL  42.387  3,37    1.428   7.478   68.816      

any suggestions would be appreciated! Thanks

Remove index.php/ from URL using htaccess

Posted: 26 Jul 2021 07:49 AM PDT

https://www.URL/index.php/iadmin/dashboard/index/key/

Is there a way to remove index.php/ portion of this URL only if URL has iadmin path in it?

I am runing Magento on Apache, and after update of Apache and php my admin page only opens if I remove index.php from it's URL.

This is how my original htaccess looks like

############################################  ## uncomment these lines for CGI mode  ## make sure to specify the correct cgi php binary file name  ## it might be /cgi-bin/php-cgi    #    Action php5-cgi /cgi-bin/php5-cgi  #    AddHandler php5-cgi .php    ############################################  ## GoDaddy specific options    #   Options -MultiViews    ## you might also need to add this line to php.ini  ##     cgi.fix_pathinfo = 1  ## if it still doesn't work, rename php.ini to php5.ini    ############################################  ## this line is specific for 1and1 hosting        #AddType x-mapp-php5 .php      #AddHandler x-mapp-php5 .php    ############################################  ## default index file        DirectoryIndex index.php    <IfModule mod_php5.c>    ############################################  ## adjust memory limit    #    php_value memory_limit 64M      php_value memory_limit 256M      php_value max_execution_time 18000    ############################################  ## disable magic quotes for php request vars        php_flag magic_quotes_gpc off    ############################################  ## disable automatic session start  ## before autoload was initialized        php_flag session.auto_start off    ############################################  ## enable resulting html compression        #php_flag zlib.output_compression on    ###########################################  # disable user agent verification to not break multiple image upload        php_flag suhosin.session.cryptua off    ###########################################  # turn off compatibility with PHP4 when dealing with objects        php_flag zend.ze1_compatibility_mode Off    </IfModule>    <IfModule mod_security.c>  ###########################################  # disable POST processing to not break multiple image upload        SecFilterEngine Off      SecFilterScanPOST Off  </IfModule>    <IfModule mod_deflate.c>    ############################################  ## enable apache served files compression  ## http://developer.yahoo.com/performance/rules.html#gzip        # Insert filter on all content      ###SetOutputFilter DEFLATE      # Insert filter on selected content types only      #AddOutputFilterByType DEFLATE text/html text/plain text/xml text/css text/javascript        # Netscape 4.x has some problems...      #BrowserMatch ^Mozilla/4 gzip-only-text/html        # Netscape 4.06-4.08 have some more problems      #BrowserMatch ^Mozilla/4\.0[678] no-gzip        # MSIE masquerades as Netscape, but it is fine      #BrowserMatch \bMSIE !no-gzip !gzip-only-text/html        # Don't compress images      #SetEnvIfNoCase Request_URI \.(?:gif|jpe?g|png)$ no-gzip dont-vary        # Make sure proxies don't deliver the wrong content      #Header append Vary User-Agent env=!dont-vary    </IfModule>    <IfModule mod_ssl.c>    ############################################  ## make HTTPS env vars available for CGI mode        SSLOptions StdEnvVars    </IfModule>    <IfModule mod_rewrite.c>    ############################################  ## enable rewrites        Options +FollowSymLinks      RewriteEngine on            RewriteCond %{HTTPS} !^on$      RewriteRule (.*) https://www.MYSITEcom/$1 [R,L]              RewriteCond %{HTTP_HOST} ^MYSITEcom [NC]      RewriteRule ^(.*)$ https://www.MYSITEcom/$1 [L,R=301]            RewriteCond %{HTTPS_HOST} ^MYSITEcom [NC]      RewriteRule ^(.*)$ https://www.MYSITEcom/$1 [L,R=301]              ############################################  ## you can put here your magento root folder  ## path relative to web root        #RewriteBase /magento/    ############################################  ## uncomment next line to enable light API calls processing    #    RewriteRule ^api/([a-z][0-9a-z_]+)/?$ api.php?type=$1 [QSA,L]    ############################################  ## rewrite API2 calls to api.php (by now it is REST only)        RewriteRule ^api/rest api.php?type=rest [QSA,L]    ############################################  ## workaround for HTTP authorization  ## in CGI environment        RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}]    ############################################  ## TRACE and TRACK HTTP methods disabled to prevent XSS attacks        RewriteCond %{REQUEST_METHOD} ^TRAC[EK]      RewriteRule .* - [L,R=405]    ############################################  ## redirect for mobile user agents        #RewriteCond %{REQUEST_URI} !^/mobiledirectoryhere/.*$      #RewriteCond %{HTTP_USER_AGENT} "android|blackberry|ipad|iphone|ipod|iemobile|opera mobile|palmos|webos|googlebot-mobile" [NC]      #RewriteRule ^(.*)$ /mobiledirectoryhere/ [L,R=302]    ############################################  ## always send 404 on missing files in these folders        RewriteCond %{REQUEST_URI} !^/(media|skin|js)/    ############################################  ## never rewrite for existing files, directories and links        RewriteCond %{REQUEST_FILENAME} !-f      RewriteCond %{REQUEST_FILENAME} !-d      RewriteCond %{REQUEST_FILENAME} !-l    ############################################  ## rewrite everything else to index.php      RewriteRule .* index.php [L]      </IfModule>      ############################################  ## Prevent character encoding issues from server overrides  ## If you still have problems, use the second line instead        AddDefaultCharset Off      #AddDefaultCharset UTF-8    <IfModule mod_expires.c>    ############################################  ## Add default Expires header  ## http://developer.yahoo.com/performance/rules.html#expires        ExpiresDefault "access plus 1 year"    </IfModule>    ############################################  ## By default allow all access        Order allow,deny      Allow from all    ###########################################  ## Deny access to release notes to prevent disclosure of the installed Magento version        <Files RELEASE_NOTES.txt>          order allow,deny          deny from all      </Files>    ############################################  ## If running in cluster environment, uncomment this  ## http://developer.yahoo.com/performance/rules.html#etags        #FileETag none  

How to get static readonly property using reflection in some class

Posted: 26 Jul 2021 07:50 AM PDT

With the code block below, I am getting static variables of a class and the value of that variable.

static void Main(string[] args)  {      var ax = GetClassPropertyValues("SomeClass");  }    public static List<string> GetClassPropertyValues(string className)  {      var fieldInfos = Type.GetType($"ConsoleApp1.{className}, ConsoleApp1")          .GetFields(              BindingFlags.Instance              | BindingFlags.Public              | BindingFlags.FlattenHierarchy              | BindingFlags.Static          );        var propertyValues = new List<string>();        foreach (var fieldInfo in fieldInfos)      {          propertyValues.Add(fieldInfo.GetValue(null).ToString());      }        return propertyValues;  }  

Classes

public abstract class SomeAbstractClass  {      public static string List = "List";  }    public class SomeClass: SomeAbstractClass  {      public static string Price = "Price";  }         

When I just set static variables to read-only then I don't get those variables. How can I get these variables ?

Can't pass an array to the From trait with a slice of arbitrary length

Posted: 26 Jul 2021 07:50 AM PDT

I'm trying to implement From<&[&str]> for one of my types. It should consume an arbitrary length of lines (only known during runtime) and fetches data from the lines. The compiler complains about that &[&str; 2] is not &[&str], i.e. it can't convert a fixed-size slice to one with arbitrary length. The exact message is: the trait 'From<&[&str; 2]>' is not implemented for 'LineEater'

This is my attempt:

fn main() {      let data = ["foo", "bar"];            // works      foo(&data);        // doesn't work      LineEater::from(&data);        // also doesn't work      let data: &[&str] = data.into();      LineEater::from(&data);  }    struct LineEater;  impl From<&[&str]> for LineEater {      fn from(_lines: &[&str]) -> Self {          todo!()      }  }    fn foo(_slice: &[&str]) {}  

Playground

It's confusing that this works with the call of foo() but not the call of from. In the first case Rust can "cast" the [&str; 2] to &[&str] but not in the latter. Why is this so and how can I fix it?

I'm working with Rust 1.55-nightly

Unable to pull image from public ECR repository

Posted: 26 Jul 2021 07:48 AM PDT

I am simply trying to pull an image from ECR public repository, however is not working:

docker pull public.ecr.aws/bitnami/golang:1.15   

I get this error:

pull access denied for public.ecr.aws/bitnami/golang, repository does not exist or may require 'docker login': denied: Your authorization token has expired. Reauthenticate and try again.  

Why "Access denied"? It is a public repository: https://gallery.ecr.aws/bitnami/golang

According to this it is not needed: https://aws.amazon.com/ecr/faqs/#:~:text=Anyone%20with%20or%20without%20an,as%20helm%20charts%20for%20Kubernetes.

ActiveMQ slave broker accepts incoming connection from Apache Camel

Posted: 26 Jul 2021 07:48 AM PDT

I have the following configuration:

  • Two actively running Tomcat instances running Apache Camel 2.20.2 that use the competing consumer concept to read message of the same JMS message queue
  • ActiveMQ 5.15.0 in a master/slave configuration using a shared kahaDB

It happens that one of the Camel instances connects to the slave broker even though the slave broker is not active (i.e. as far as I can tell from the log files it did not get a lock on the kahaDB).

When this occurs the route on that Camel instance is blocked, and we get a ExchangeTimedOutException and this blocks the route and messages are being queued up.

WARN  EndpointMessageListener:213 - Execution of JMS message listener failed. Caused by: [org.apache.camel.RuntimeCamelException - org.apache.camel.ExchangeTimedOutException: The OUT message was not received within: 30000 millis. Exchange[ID-MXPBMES-01P-I02-1625784159041-1-16108]]  

Is it normal that a slave broker accepts a connection from a client application (Camel in our case)?

C++ concept checking in incomplete-class context

Posted: 26 Jul 2021 07:48 AM PDT

Please consider a C++20 concept program:

struct A {};    template<typename T>  concept DerivedOnceFromA = requires(T t) { { static_cast<const A&>(t) }; };    template<DerivedOnceFromA T>  struct B {};    struct C : A  {      B<C> foo();  };  

Here the concept DerivedOnceFromA checks that T can be statically cast to A. B is template struct following this concept. And struct C is derived from A (so the concept is satisfied) and defines a function that returns B<C>.

This code is accepted by GCC and MSVC, but rejected by Clang with the error:

constraints not satisfied for class template 'B' [with T = C]  

Demo: https://gcc.godbolt.org/z/7Tc7xdbeq

Is it legal to use class as concepted template parameter inside class body (so what compiler is right)?

MIP SDK Read UserRights

Posted: 26 Jul 2021 07:49 AM PDT

I created a word with a sensitivity label and adding permission of who can see files. I wanna get the users who can access this doc. I followed up on this repo.

https://github.com/Azure-Samples/mipsdk-dotnet-file-quickstart

What I do is. I have a user with a label and this user has created an app register and word -this user isn't admin- when I run my code, I log in with the same user, and I getting all users who can access this file.

// Create a new handler to read the labeled file metadata var handlerModified = Task.Run(async () => await var fileHandler = fileEngine.CreateFileHandlerAsync(outputFilePath, actualOutputFilePath, true)).Result; fileHandler?.Protection?.ProtectionDescriptor?.UserRights

But when I login in with other users this property (UserRights) is null.

So I wanna know if there is a way to get UserRights all time from any document -the creator of the doc is anyone in my tenant -. Can I log in with a global user in my app? global user => can be admin of portal azure? If I created app registration with the admin user and login to my app. can this user see UserRights property even if he isn't the creator of the word file?

Error while running npm start in react js

Posted: 26 Jul 2021 07:48 AM PDT

I have created a react project using npx

npx create-react-app react-authentication  

After that when I run

npm start  

It throws an error saying:

internal/modules/cjs/loader.js:456        throw e;        ^    Error: Cannot find module '/home/astraCreateDataProperty/react-authentication/node_modules/es-abstract/2020/CreateDataProperty.js'      at createEsmNotFoundErr (internal/modules/cjs/loader.js:929:15)      at finalizeEsmResolution (internal/modules/cjs/loader.js:922:15)      at resolveExports (internal/modules/cjs/loader.js:450:14)      at Function.Module._findPath (internal/modules/cjs/loader.js:490:31)      at Function.Module._resolveFilename (internal/modules/cjs/loader.js:888:27)      at Function.Module._load (internal/modules/cjs/loader.js:746:27)      at Module.require (internal/modules/cjs/loader.js:974:19)      at require (internal/modules/cjs/helpers.js:92:18)      at Object.<anonymous> (/home/astra*/react-authentication/node_modules/object.getownpropertydescriptors/implementation.js:3:26)      at Module._compile (internal/modules/cjs/loader.js:1085:14) {    code: 'MODULE_NOT_FOUND',    path: '/home/astra*/react-authentication/node_modules/es-abstract/package.json'  }  

I tried some methods to solve this like

  1. rm -rf node_modules
  2. rm -rf package-lock.json
  3. npm cache clean --force
  4. npm install

But still, the same error persists. What is the cause of this error?

How to get Mouse buttons 4 / 5 (Browser back / Browser forward) working in Firefox?

Posted: 26 Jul 2021 07:49 AM PDT

First, I need to say that I'm aware there is some confusion as to what button numbering scheme convention is used for these "Browser back" and "Browser forward" mouse buttons depending on whether you use numbering starting from zero 0 or one 1. Since this question is about Firefox, I'll go by Mozilla's numbering scheme here.

I've been struggling with an issue seen only in Firefox where Mouse buttons 4 (back) and 5 (forward) appear to Firefox as if they were a button 2 click (Middle button click) event. Pressing either button 4 or 5 results in the circular "autoscrolling" icon with Up and Down arrows appearing:

Firefox autoscroll icon

I've done some debugging using this Mouse Event Test Page. Results are different between Chrome and Firefox. It appears that the "which" JS event attribute numbers these as 4 and 5, while the button attribute numbers them as 3 and 4. Regardless, Google Chrome interprets them as "Browser back" and "Browser Forward" buttons correctly, while Firefox does not.

  • Chrome:

    • Mouse Button "4" (back)

      mousedown   which=4 button=3 buttons=8  mouseup     which=4 button=3 buttons=0  
    • Mouse Button "5" (forward)

      mousedown   which=5 button=4 buttons=16  mouseup     which=5 button=4 buttons=0  
    • Mouse Button "2" (middle click)

      mousedown   which=2 button=1 buttons=4  mouseup     which=2 button=1 buttons=0  
  • Firefox:

    • Mouse Button "4" (back)

      mousedown   which=2 button=1 buttons=8  mouseup     which=2 button=1 buttons=0  
    • Mouse Button "5" (forward)

      mousedown   which=2 button=1 buttons=16  mouseup     which=2 button=1 buttons=0  
    • Mouse Button "2" (middle click)

      mousedown   which=2 button=1 buttons=4  mouseup     which=2 button=1 buttons=0  

As the page says, not all browsers work correctly. It also states:

However, in some browsers, the defaults cannot be disabled, so various strange side effects may occur.

In Firefox, I notice clicking with all three of these buttons launches a new tab with javascript:void(null). This is the same as the link's URL attribute (href="javascript:void(null)"), as we can see from that page's source code. So this behavior is consistent with a Middle Button Click event, which usually will launch a new tab with that URL.

Is it possible to get these buttons for "Browser Back" and "Browser Forward" working properly in Firefox?

contact form 7 age verification

Posted: 26 Jul 2021 07:48 AM PDT

I have a form that I need to allowed submissions only if the user is 13 years old or older to be able to submit the form.

Is there a way to do this with contact form 7?

Thank you for your help

Xamarin round cornered frame's background color surpasses the rounded edges

Posted: 26 Jul 2021 07:48 AM PDT

I'm using a frame tag to wrap a grid inside, but whenever I add corner radius to the frame, the background color of the said frame goes out from the rounded corners and is displayed as a sharp corner.

Can anyone help?

An image is also attached with the question to portray the problem correctly.

The code snippet is:

<Frame CornerRadius="15"          BackgroundColor="Aqua"           OutlineColor="Black"          MinimumHeightRequest="100"          MinimumWidthRequest="150"          HorizontalOptions="Center"          VerticalOptions="Center"          Grid.Column="2">      <Grid x:Name="MessageGrid"               HorizontalOptions="Fill"             VerticalOptions="Fill">          <Grid Margin="0,0,0,0"                 HorizontalOptions="FillAndExpand"                 InputTransparent="True"                  VerticalOptions="FillAndExpand">              <Label x:Name="InfoText"                      TextColor="Black"                      HorizontalOptions="FillAndExpand"                      VerticalOptions="FillAndExpand"                      InputTransparent="True"                     Text="Tooltip text goes here and this is to check if its responsive"/>          </Grid>      </Grid>  </Frame>  

enter image description here

Run Powershell script from URL without temporary file

Posted: 26 Jul 2021 07:49 AM PDT

I want to write a PowerShell script that runs a PowerShell script stored at a URL, passing both custom arguments and forwarding any arguments that are given to this PowerShell. Concretely, I can do:

$VAR=Invoke-WebRequest http://example.com/powershell.ps1  $TEMP=New-TemporaryFile  $FILE=$TEMP.FullName + ".ps1"  $VAR.Content | Out-File $FILE  & $FILE somearguments $args  

I'd ideally like to do that without using a temporary file, however powershell -content - doesn't seem to allow also passing arguments. Is there any way to avoid the temporary file?

Understanding unique keys for array children in React.js

Posted: 26 Jul 2021 07:49 AM PDT

I'm building a React component that accepts a JSON data source and creates a sortable table.
Each of the dynamic data rows has a unique key assigned to it but I'm still getting an error of:

Each child in an array should have a unique "key" prop.
Check the render method of TableComponent.

My TableComponent render method returns:

<table>    <thead key="thead">      <TableHeader columns={columnNames}/>    </thead>    <tbody key="tbody">      { rows }    </tbody>  </table>  

The TableHeader component is a single row and also has a unique key assigned to it.

Each row in rows is built from a component with a unique key:

<TableRowItem key={item.id} data={item} columns={columnNames}/>  

And the TableRowItem looks like this:

var TableRowItem = React.createClass({    render: function() {        var td = function() {          return this.props.columns.map(function(c) {            return <td key={this.props.data[c]}>{this.props.data[c]}</td>;          }, this);        }.bind(this);        return (        <tr>{ td(this.props.item) }</tr>      )    }  });  

What is causing the unique key prop error?

No comments:

Post a Comment