JavaCollege | 开源项目个人博客 | Blog library
kandi X-RAY | JavaCollege Summary
Support
Quality
Security
License
Reuse
Currently covering the most popular Java, JavaScript and Python libraries. See a Sample Here
JavaCollege Key Features
JavaCollege Examples and Code Snippets
Trending Discussions on Blog
Trending Discussions on Blog
QUESTION
I am learning react js. I am a very beginner at this topic. But when I am doing setup to create a react environment I got an error. I have tried to solve the problem by Charles Stover blog in medium. But I got an error Command "up" not found
.
Here's my index.js file:
import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';
import reportWebVitals from './reportWebVitals';
ReactDOM.render(
,
document.getElementById('root')
);
reportWebVitals();
My package.json file:
{
"name": "myreact",
"version": "0.1.0",
"private": true,
"dependencies": {
"@testing-library/jest-dom": "^5.11.4",
"@testing-library/react": "^11.1.0",
"@testing-library/user-event": "^12.1.10",
"react": "^17.0.2",
"react-dom": "^17.0.2",
"react-scripts": "4.0.3",
"web-vitals": "^1.0.1"
},
"scripts": {
"start": "react-scripts start",
"build": "react-scripts build",
"test": "react-scripts test",
"eject": "react-scripts eject",
"lint": "yarn add -D prettier && yarn add -D babel-eslint && npx install-peerdeps --dev eslint-config-airbnb && yarn add -D eslint-config-prettier eslint-plugin-prettier"
},
"eslintConfig": {
"extends": [
"react-app",
"react-app/jest"
]
},
"browserslist": {
"production": [
">0.2%",
"not dead",
"not op_mini all"
],
"development": [
"last 1 chrome version",
"last 1 firefox version",
"last 1 safari version"
]
},
"devDependencies": {
"babel-eslint": "^10.1.0",
"eslint": "7.2.0",
"eslint-config-airbnb": "18.2.1",
"eslint-config-prettier": "^8.3.0",
"eslint-plugin-import": "2.22.1",
"eslint-plugin-jsx-a11y": "6.4.1",
"eslint-plugin-prettier": "^4.0.0",
"eslint-plugin-react": "7.21.5",
"eslint-plugin-react-hooks": "1.7.0",
"prettier": "^2.3.2"
}
}
When I am running yarn start
in terminal, I am getting an error.
Error while loading rule 'prettier/prettier': context.getPhysicalFilename is not a function
Occurred while linting F:\react-projects\myreact\src\index.js
Now what should I do?
ANSWER
Answered 2021-Sep-06 at 09:40I got two different solution.
- remove
"prettier/prettier": [
"error",
{
"trailingComma": "es5",
"singleQuote": true,
"printWidth": 100,
"tabWidth": 4,
"semi": true,
"endOfLine": "auto"
}
]
from .eslintrc
folder and change react script version from 4.0.3 to 4.0.1 and run npm install
.
- Use
yarn upgrade -R eslint
and change react script version from 4.0.3 to 4.0.1 and runnpm install
.
QUESTION
If i search the same question on the internet, then i'll get only links to vscode website ans some blogs which implements it.
I want to know that is jsconfig.json
is specific to vscode
or javascript/webpack
?
What will happen if we deploy the application on AWS / Heroku, etc. Do we have to make change?
ANSWER
Answered 2021-Aug-06 at 04:10This is definitely specific to VSCode.
The presence of jsconfig.json file in a directory indicates that the directory is the root of a JavaScript Project. The jsconfig.json file specifies the root files and the options for the features provided by the JavaScript language service.
Check more details here: https://code.visualstudio.com/docs/languages/jsconfig
You don't need this file when deploy it on AWS/Heroku, basically, you can exclude this from your commit if you are using git repo, i.e., add jsconfig.json
in your .gitignore
, this will make your project IDE independent.
QUESTION
I have been using github actions for quite sometime but today my deployments started failing. Below is the error from github action logs
Command: git
Arguments: ls-remote --tags --heads git://github.com/adobe-webplatform/eve.git
Directory: /home/runner/work/stackstream-fe/stackstream-fe
Output:
fatal: remote error:
The unauthenticated git protocol on port 9418 is no longer supported.
Upon investigation, it appears that below section in my yml file is causing the issue.
- name: Installing modules
run: yarn install
I have looked into this change log but can't seem to comprehend the issue.
Additional Details: Server: EC2 Instance Github actions steps:
steps:
- name: Checkout
uses: actions/checkout@v2
- id: vars
run: |
if [ '${{ github.ref }}' == 'refs/heads/master' ]; then echo "::set-output name=environment::prod_stackstream" ; echo "::set-output name=api-url::api" ; elif [ '${{ github.ref }}' == 'refs/heads/staging' ]; then echo "::set-output name=environment::staging_stackstream" ; echo "::set-output name=api-url::stagingapi" ; else echo "::set-output name=environment::dev_stackstream" ; echo "::set-output name=api-url::devapi" ; fi
- uses: pCYSl5EDgo/cat@master
id: slack
with:
path: .github/workflows/slack.txt
- name: Slack Start Notification
uses: 8398a7/action-slack@v3
env:
SLACK_WEBHOOK_URL: ${{ secrets.SLACK_WEBHOOK_URL }}
ENVIRONMENT: '`${{ steps.vars.outputs.environment }}`'
COLOR: good
STATUS: '`Started`'
with:
status: custom
fields: workflow,job,commit,repo,ref,author,took
custom_payload: |
${{ steps.slack.outputs.text }}
- name: Installing modules
env:
REACT_APP_API_URL: 'https://${{ steps.vars.outputs.api-url }}mergestack.com/api/v1'
run: yarn install
- name: Create Frontend Build
env:
REACT_APP_API_URL: 'https://${{ steps.vars.outputs.api-url }}mergestack.com/api/v1'
run: yarn build
- name: Deploy to Frontend Server DEV
if: ${{ contains(github.ref, 'dev') }}
uses: easingthemes/ssh-deploy@v2.1.5
env:
SSH_PRIVATE_KEY: ${{ secrets.DEV_KEY }}
ARGS: '-rltgoDzvO --delete'
SOURCE: 'deploy/'
REMOTE_HOST: ${{ secrets.DEV_HOST }}
REMOTE_USER: plyfolio-dev
TARGET: '/home/plyfolio-dev/${{ steps.vars.outputs.environment }}/fe/deploy'
package.json file
{
"name": "stackstream-fe",
"version": "1.0.0",
"authors": [
"fayyaznofal@gmail.com"
],
"private": true,
"dependencies": {
"@fortawesome/fontawesome-svg-core": "^1.2.34",
"@fortawesome/free-solid-svg-icons": "^5.15.2",
"@fortawesome/react-fontawesome": "^0.1.14",
"@fullcalendar/bootstrap": "^5.5.0",
"@fullcalendar/core": "^5.5.0",
"@fullcalendar/daygrid": "^5.5.0",
"@fullcalendar/interaction": "^5.5.0",
"@fullcalendar/react": "^5.5.0",
"@lourenci/react-kanban": "^2.1.0",
"@redux-saga/simple-saga-monitor": "^1.1.2",
"@testing-library/jest-dom": "^5.11.9",
"@testing-library/react": "^11.2.3",
"@testing-library/user-event": "^12.6.0",
"@toast-ui/react-chart": "^1.0.2",
"@types/jest": "^26.0.14",
"@types/node": "^14.10.3",
"@types/react": "^16.9.49",
"@types/react-dom": "^16.9.8",
"@vtaits/react-color-picker": "^0.1.1",
"apexcharts": "^3.23.1",
"availity-reactstrap-validation": "^2.7.0",
"axios": "^0.21.1",
"axios-mock-adapter": "^1.19.0",
"axios-progress-bar": "^1.2.0",
"bootstrap": "^5.0.0-beta2",
"chart.js": "^2.9.4",
"chartist": "^0.11.4",
"classnames": "^2.2.6",
"components": "^0.1.0",
"dotenv": "^8.2.0",
"draft-js": "^0.11.7",
"echarts": "^4.9.0",
"echarts-for-react": "^2.0.16",
"firebase": "^8.2.3",
"google-maps-react": "^2.0.6",
"history": "^4.10.1",
"i": "^0.3.6",
"i18next": "^19.8.4",
"i18next-browser-languagedetector": "^6.0.1",
"jsonwebtoken": "^8.5.1",
"leaflet": "^1.7.1",
"lodash": "^4.17.21",
"lodash.clonedeep": "^4.5.0",
"lodash.get": "^4.4.2",
"metismenujs": "^1.2.1",
"mkdirp": "^1.0.4",
"moment": "2.29.1",
"moment-timezone": "^0.5.32",
"nouislider-react": "^3.3.9",
"npm": "^7.6.3",
"prop-types": "^15.7.2",
"query-string": "^6.14.0",
"react": "^16.13.1",
"react-apexcharts": "^1.3.7",
"react-auth-code-input": "^1.0.0",
"react-avatar": "^3.10.0",
"react-bootstrap": "^1.5.0",
"react-bootstrap-editable": "^0.8.2",
"react-bootstrap-sweetalert": "^5.2.0",
"react-bootstrap-table-next": "^4.0.3",
"react-bootstrap-table2-editor": "^1.4.0",
"react-bootstrap-table2-paginator": "^2.1.2",
"react-bootstrap-table2-toolkit": "^2.1.3",
"react-chartist": "^0.14.3",
"react-chartjs-2": "^2.11.1",
"react-color": "^2.19.3",
"react-confirm-alert": "^2.7.0",
"react-content-loader": "^6.0.1",
"react-countdown": "^2.3.1",
"react-countup": "^4.3.3",
"react-cropper": "^2.1.4",
"react-data-table-component": "^6.11.8",
"react-date-picker": "^8.0.6",
"react-datepicker": "^3.4.1",
"react-dom": "^16.13.1",
"react-draft-wysiwyg": "^1.14.5",
"react-drag-listview": "^0.1.8",
"react-drawer": "^1.3.4",
"react-dropzone": "^11.2.4",
"react-dual-listbox": "^2.0.0",
"react-facebook-login": "^4.1.1",
"react-flatpickr": "^3.10.6",
"react-google-login": "^5.2.2",
"react-hook-form": "^7.15.2",
"react-i18next": "^11.8.5",
"react-icons": "^4.2.0",
"react-image-lightbox": "^5.1.1",
"react-input-mask": "^2.0.4",
"react-jvectormap": "^0.0.16",
"react-leaflet": "^3.0.5",
"react-meta-tags": "^1.0.1",
"react-modal-video": "^1.2.6",
"react-notifications": "^1.7.2",
"react-number-format": "^4.7.3",
"react-perfect-scrollbar": "^1.5.8",
"react-rangeslider": "^2.2.0",
"react-rating": "^2.0.5",
"react-rating-tooltip": "^1.1.6",
"react-redux": "^7.2.1",
"react-responsive-carousel": "^3.2.11",
"react-router-dom": "^5.2.0",
"react-script": "^2.0.5",
"react-scripts": "3.4.3",
"react-select": "^4.3.1",
"react-sparklines": "^1.7.0",
"react-star-ratings": "^2.3.0",
"react-super-responsive-table": "^5.2.0",
"react-switch": "^6.0.0",
"react-table": "^7.6.3",
"react-toastify": "^7.0.3",
"react-toastr": "^3.0.0",
"react-twitter-auth": "0.0.13",
"reactstrap": "^8.8.1",
"recharts": "^2.0.8",
"redux": "^4.0.5",
"redux-saga": "^1.1.3",
"reselect": "^4.0.0",
"sass": "^1.37.5",
"simplebar-react": "^2.3.0",
"styled": "^1.0.0",
"styled-components": "^5.2.1",
"toastr": "^2.1.4",
"typescript": "^4.0.2",
"universal-cookie": "^4.0.4"
},
"devDependencies": {
"@typescript-eslint/eslint-plugin": "^2.27.0",
"@typescript-eslint/parser": "^2.27.0",
"@typescript-eslint/typescript-estree": "^4.15.2",
"eslint-config-prettier": "^6.10.1",
"eslint-plugin-prettier": "^3.1.2",
"husky": "^4.2.5",
"lint-staged": "^10.1.3",
"prettier": "^1.19.1",
"react-test-renderer": "^16.13.1",
"redux-devtools-extension": "^2.13.8",
"redux-mock-store": "^1.5.4"
},
"scripts": {
"start": "react-scripts start",
"build": "react-scripts build && mv build ./deploy/build",
"build-local": "react-scripts build",
"test": "react-scripts test",
"eject": "react-scripts eject"
},
"eslintConfig": {
"extends": "react-app"
},
"husky": {
"hooks": {
"pre-commit": "lint-staged"
}
},
"lint-staged": {
"*.{js,ts,tsx}": [
"eslint --fix"
]
},
"browserslist": {
"production": [
">0.2%",
"not dead",
"not op_mini all"
],
"development": [
"last 1 chrome version",
"last 1 firefox version",
"last 1 safari version"
]
}
}
ANSWER
Answered 2022-Mar-16 at 07:01First, this error message is indeed expected on Jan. 11th, 2022.
See "Improving Git protocol security on GitHub".
January 11, 2022 Final brownout.
This is the full brownout period where we’ll temporarily stop accepting the deprecated key and signature types, ciphers, and MACs, and the unencrypted Git protocol.
This will help clients discover any lingering use of older keys or old URLs.
Second, check your package.json
dependencies for any git://
URL, as in this example, fixed in this PR.
As noted by Jörg W Mittag:
For GitHub Actions:There was a 4-month warning.
The entire Internet has been moving away from unauthenticated, unencrypted protocols for a decade, it's not like this is a huge surprise.Personally, I consider it less an "issue" and more "detecting unmaintained dependencies".
Plus, this is still only the brownout period, so the protocol will only be disabled for a short period of time, allowing developers to discover the problem.
The permanent shutdown is not until March 15th.
As in actions/checkout issue 14, you can add as a first step:
- name: Fix up git URLs
run: echo -e '[url "https://github.com/"]\n insteadOf = "git://github.com/"' >> ~/.gitconfig
That will change any git://github.com/
into https://github.com/
.
For all your repositories, you can set:
git config --global url."https://github.com/".insteadOf git://github.com/
You can also use SSH, but GitHub Security reminds us that, as of March 15th, 2022, GitHub stopped accepting DSA keys. RSA keys uploaded after Nov 2, 2021 will work only with SHA-2 signatures.
The deprecated MACs, ciphers, and unencrypted Git protocol are permanently disabled.
So this (with the right key) would work:
git config --global url."git@github.com:".insteadOf git://github.com/
That will change any git://github.com/
(unencrypted Git protocol) into git@github.com:
(SSH URL).
QUESTION
I am getting this warning from github on my npm project build process... I tried searching on the internet and also read the blog link posted by github - but I could not find the solution to it anywhere. Am I missing something ?
Warning seen
npm notice Beginning October 4, 2021, all connections to the npm registry - including for package installation - must use TLS 1.2 or higher. You are currently using plaintext http to connect. Please visit the GitHub blog for more information: https://github.blog/2021-08-23-npm-registry-deprecating-tls-1-0-tls-1-1/
ANSWER
Answered 2021-Sep-10 at 15:18Besides updating your version of node to an active or current LTS you want to ensure your NPM registry is set to an HTTPS endpoint:
registry=https://registry.npmjs.org/
QUESTION
The arithmetic mean of two unsigned integers is defined as:
mean = (a+b)/2
Directly implementing this in C/C++ may overflow and produce a wrong result. A correct implementation would avoid this. One way of coding it could be:
mean = a/2 + b/2 + (a%2 + b%2)/2
But this produces rather a lot of code with typical compilers. In assembler, this usually can be done much more efficiently. For example, the x86 can do this in the following way (assembler pseudo code, I hope you get the point):
ADD a,b ; addition, leaving the overflow condition in the carry bit
RCR a,1 ; rotate right through carry, effectively a division by 2
After those two instructions, the result is in a
, and the remainder of the division is in the carry bit. If correct rounding is desired, a third ADC
instruction would have to add the carry into the result.
Note that the RCR instruction is used, which rotates a register through the carry. In our case, it is a rotate by one position, so that the previous carry becomes the most significant bit in the register, and the new carry holds the previous LSB from the register. It seems that MSVC doesn't even offer an intrinsic for this instruction.
Is there a known C/C++ pattern that can be expected to be recognized by an optimizing compiler so that it produces such efficient code? Or, more generally, is there a rational way how to program in C/C++ source level so that the carry bit is being used by the compiler to optimize the generated code?
EDIT:
A 1-hour lecture about std::midpoint
: https://www.youtube.com/watch?v=sBtAGxBh-XI
Wow!
ANSWER
Answered 2022-Mar-08 at 10:54The following method avoids overflow and should result in fairly efficient assembly (example) without depending on non-standard features:
mean = (a&b) + (a^b)/2;
QUESTION
Currently I'm using "react": "17.0.2"
and I have installed "react-markdown": "^7.0.1"
via npm i react-markdown
I'm using this package to display my rich text that I'm fetching from my Strapi CMS. I have used the following code to display the content:
import ReactMarkdown from "react-markdown";
export default function name({ posts }) {
return (
<>
{posts.Title}
);
}
export async function getStaticProps() {
const res = await fetch("http://localhost:1337/blogs");
const posts = await res.json();
return {
props: { posts },
};
}
But when I run this it gives me the following error:
I'm using node v14.17.0
and have tried adding "type": "module"
.
My package.json:
{
"name": "passportlegacy",
"version": "0.1.0",
"private": true,
"scripts": {
"dev": "next dev",
"build": "next build",
"start": "next start",
"lint": "next lint"
},
"dependencies": {
"axios": "^0.21.1",
"babel-plugin-inline-react-svg": "^2.0.1",
"next": "11.0.1",
"next-images": "^1.8.1",
"react": "17.0.2",
"react-dom": "17.0.2",
"react-map-gl": "^6.1.16",
"react-markdown": "^7.0.1",
},
"devDependencies": {
"@svgr/webpack": "^5.5.0",
"@types/react": "17.0.16",
"eslint": "7.32.0",
"eslint-config-next": "11.0.1",
"typescript": "4.3.5"
}
}
ANSWER
Answered 2021-Sep-01 at 10:23Node is currently treating your .js
file as CommonJS. You need to tell Node to treat it as an ES module.
Try adding "type": "module"
in your package.json
file.
You can place it anywhere at the top level. E.g.:
{
"name": "passportlegacy",
"version": "0.1.0",
"type": "module",
"private": true,
"scripts": {
...
}
...
}
More information: package.json and file extensions - Node.js 14.x LTS documentation
QUESTION
I have Android Studio BumbleBee 2021.1.1 downloaded, running on a MacBook Pro M1. When downloading Android Studio, I chose the Apple Chip option (opposed to Intel)
I've created a Virtual Device - Android 12.0 arm64-v8a Pixel 4.
When I attempt to run the emulator it gets stuck here
Then, it times out:
I have searched SO and other blogs and can only find outdated material based on a time in 2020/2021 when Android did not support ARM64. However, it's my understanding that this has now changed so https://github.com/google/android-emulator-m1-preview is no longer needed.
What is the correct way to run the Android Emulator on a Mac with an M1 Chip?
ANSWER
Answered 2022-Jan-28 at 19:17I have found the issue so marking this as solved, however, if anyone knows why this solves the problem, please share!
I found an issue opened on Google's anroid-emulator-m1-preview repo with this answer https://github.com/google/android-emulator-m1-preview/issues/76#issuecomment-1023563846
Turns out, I just needed to uncheck 'Launch in a tool window' but again, not sure why that fixed the issue.
QUESTION
With regard to the Log4j JNDI remote code execution vulnerability that has been identified CVE-2021-44228 - (also see references) - I wondered if Log4j-v1.2 is also impacted, but the closest I got from source code review is the JMS-Appender.
The question is, while the posts on the Internet indicate that Log4j 1.2 is also vulnerable, I am not able to find the relevant source code for it.
Am I missing something that others have identified?
Log4j 1.2 appears to have a vulnerability in the socket-server class, but my understanding is that it needs to be enabled in the first place for it to be applicable and hence is not a passive threat unlike the JNDI-lookup vulnerability which the one identified appears to be.
Is my understanding - that Log4j v1.2 - is not vulnerable to the jndi-remote-code execution bug correct?
ReferencesThis blog post from Cloudflare also indicates the same point as from AKX....that it was introduced from Log4j 2!
Update #1 - A fork of the (now-retired) apache-log4j-1.2.x with patch fixes for few vulnerabilities identified in the older library is now available (from the original log4j author). The site is https://reload4j.qos.ch/. As of 21-Jan-2022 version 1.2.18.2 has been released. Vulnerabilities addressed to date include those pertaining to JMSAppender, SocketServer and Chainsaw vulnerabilities. Note that I am simply relaying this information. Have not verified the fixes from my end. Please refer the link for additional details.
ANSWER
Answered 2022-Jan-01 at 18:43The JNDI feature was added into Log4j 2.0-beta9.
Log4j 1.x thus does not have the vulnerable code.
QUESTION
Recently, I was reading about the Ancient Babylonian Civilization that used a number system with base 60 instead of base 10. Even with this number system at base 60, they were still able to approximate the square root of 2 — and that too, thousands of years ago!
I was curious about this, and wanted to see how numbers from our decimal system (base 10) can be converted into the sexagesimal system (base 60). Using the R programming language, I found this link in which an answer is provided on converting numbers from some base to a different base.
However, it seems here that the base can only be between 2 and 36 (I want base 60):
base <- function(b, base = 10)
{
base <- as.integer(base)
if(base > 36 | base < 2) stop("'base' must be between 2 and 36.")
structure(lapply(b, function(x)
{
n <- ceiling(log(x, base))
vec <- numeric()
val <- x
while(n >= 0)
{
rem <- val %/% base^n
val <- val - rem * base^n
vec <- c(vec, rem)
n <- n - 1
}
while(vec[1] == 0 & length(vec) > 1) vec <- vec[-1]
structure(x, base = base, representation = vec)
}), class = "base")
}
The article that I linked to reads in the headline "One eighth equals seven and thirty in this strange base 60 world" - I would like to see this and convert "1/8" from the decimal system into "7 and 30" in the sexagesimal system.
Can someone please help me with this?
ANSWER
Answered 2022-Jan-30 at 20:41The code as given almost works. The limitation to bases < 36 is only there because the original author wanted to express the values with the symbols [0-9A-Z]. Removing that limitation and extending the algorithm to allow extra digits 'after the decimal point' (or 'after the sexagesimal point' in the case of base 60 :-) ) we get something that almost works (function definition below):
base(1/8, base = 60, digits = 6)
[[1]]
[1] 0.125
attr(,"base")
[1] 60
attr(,"representation")
[1] 7 29 59 59 59 59
attr(,"class")
[1] "base"
Instead of "7 30" we get "7 29 (59 repeating)", which is analogous to doing a decimal calculation that should be 0.2 and instead getting 0.1999....
This would presumably be fixable with an appropriate 'numeric fuzz' threshold.
The other thing that's missing from the code, now that it does fractional parts, is that the result should return information that tells you where the 'decimal' point is located (at the simplest, including the value of digits
in the output).
There are other aspects of the code that could be improved (e.g. pre-allocating vec
rather than building it up iteratively).
base <- function(b, base = 10, digits = 0) {
base <- as.integer(base)
structure(lapply(b, function(x)
{
n <- ceiling(log(x, base))
vec <- numeric()
val <- x
while(n >= -1*digits ) {
rem <- val %/% base^n
val <- val - rem * base^n
vec <- c(vec, rem)
n <- n - 1
}
while(vec[1] == 0 & length(vec) > 1) vec <- vec[-1]
structure(x, base = base, representation = vec)
}), class = "base")
}
QUESTION
I know Python //
rounds towards negative infinity and in C++ /
is truncating, rounding towards 0.
And here's what I know so far:
|remainder|
-12 / 10 = -1, - 2 // C++
-12 // 10 = -2, + 8 # Python
12 / -10 = -1, 2 // C++
12 // -10 = -2, - 8 # Python
12 / 10 = 1, 2 // Both
12 // 10 = 1, 2
-12 / -10 = 1, - 2 // Both
= 2, + 8
C++:
1. m%(-n) == m%n
2. -m%n == -(m%n)
3. (m/n)*n + m%n == m
Python:
1. m%(-n) == -8 == -(-m%n)
2. (m//n)*n + m%n == m
But why Python //
choose to round towards negative infinity? I didn't find any resources explain that, but only find and hear people say vaguely: "for mathematics reasons".
For example, in Why is -1/2 evaluated to 0 in C++, but -1 in Python?:
People dealing with these things in the abstract tend to feel that rounding toward negative infinity makes more sense (that means it's compatible with the modulo function as defined in mathematics, rather than % having a somewhat funny meaning).
But I don't see C++ 's /
not being compatible with the modulo function. In C++, (m/n)*n + m%n == m
also applies.
So what's the (mathematical) reason behind Python choosing rounding towards negative infinity?
ANSWER
Answered 2022-Jan-18 at 21:46Although I can't provide a formal definition of why/how the rounding modes were chosen as they were, the citation about compatibility with the %
operator, which you have included, does make sense when you consider that %
is not quite the same thing in C++ and Python.
In C++, it is the remainder operator, whereas, in Python, it is the modulus operator – and, when the two operands have different signs, these aren't necessarily the same thing. There are some fine explanations of the difference between these operators in the answers to: What's the difference between “mod” and “remainder”?
Now, considering this difference, the rounding (truncation) modes for integer division have to be as they are in the two languages, to ensure that the relationship you quoted, (m/n)*n + m%n == m
, remains valid.
Here are two short programs that demonstrate this in action (please forgive my somewhat naïve Python code – I'm a beginner in that language):
C++:
#include
int main()
{
int dividend, divisor, quotient, remainder, check;
std::cout << "Enter Dividend: "; // -27
std::cin >> dividend;
std::cout << "Enter Divisor: "; // 4
std::cin >> divisor;
quotient = dividend / divisor;
std::cout << "Quotient = " << quotient << std::endl; // -6
remainder = dividend % divisor;
std::cout << "Remainder = " << remainder << std::endl; // -3
check = quotient * divisor + remainder;
std::cout << "Check = " << check << std::endl; // -27
return 0;
}
Python:
print("Enter Dividend: ") # -27
dividend = int(input())
print("Enter Divisor: ") # 4
divisor = int(input())
quotient = dividend // divisor;
print("Quotient = " + str(quotient)) # -7
modulus = dividend % divisor;
print("Modulus = " + str(modulus)) # 1
check = quotient * divisor + modulus; # -27
print("Check = " + str(check))
Note that, for the given inputs of different signs (-27 and 4), both the quotient and remainder/modulus are different between the languages but also that the restored check
value is correct in both cases.
Community Discussions, Code Snippets contain sources that include Stack Exchange Network
Vulnerabilities
No vulnerabilities reported
Install JavaCollege
You can use JavaCollege like any standard Java library. Please include the the jar files in your classpath. You can also use any IDE and you can run and debug the JavaCollege component as you would do with any other Java program. Best practice is to use a build tool that supports dependency management such as Maven or Gradle. For Maven installation, please refer maven.apache.org. For Gradle installation, please refer gradle.org .
Support
Find, review, and download reusable Libraries, Code Snippets, Cloud APIs from over 650 million Knowledge Items
Find more librariesExplore Kits - Develop, implement, customize Projects, Custom Functions and Applications with kandi kits
Save this library and start creating your kit
Share this Page