how to upload photo in react native android

Question: I use react native to develop in android. And I want upload a file or photo to server .And I use react-native-file-uploader,And I got errors:

[undefined is not an object(evaluating
  '_reactNative.NativeModules.FileUploader.upload')],Cannot read
  property 'upload' of undefined2

please help,Thanks!
bellow is my code:
<code> import React from 'react';
    import {
    View,
    Text,
    Image,
    StyleSheet,
    TouchableOpacity,
    Platform,
    DeviceEventEmitter
    } from 'react-native';

import Icon from 'react-native-vector-icons/FontAwesome'
import FileUploader from 'react-native-file-uploader'

const settings = {
/* uri,
uploadUrl,
method, // default to 'POST'
fileName, // default to 'yyyyMMddhhmmss.xxx'
fieldName, // default to 'file'
contentType, // default to 'application/octet-stream'
data: {
// extra fields to send in the multipart payload
}*/
  };

export default class NewDishView extends React.Component{
constructor(props){
    super(props)
    this.state={
        avatarSource:'./src/images/support.png'
    }
}
goBack(){
    this.props.navigator.pop();
}

render(){
    return (
        <View>
            <View style={styles.header}>

                <TouchableOpacity onPress={()=>this.goBack()} style={styles.back}>
                    <Icon style={styles.backIcon} name="chevron-left" />
                </TouchableOpacity>

                <View style={{flex:1}}>
                    <Text style={styles.title}>Create new dish</Text>
                </View>
            </View>

            <TouchableOpacity onPress={
                FileUploader.upload(settings, (err, res) => {
                  // handle result
                }, (sent, expectedToSend) => {
                  // handle progress
                })
            }>
                <Text>upload</Text>
            </TouchableOpacity>
        </View>
    )
}
}

const styles = StyleSheet.create({

header:{
    flexDirection:'row',
},
back:{
    paddingLeft:10,
    paddingTop:5,
    width:25,
},
backIcon:{
    color:'#000',
    fontSize:20,
},
title:{
    fontSize:20,
    textAlign:'center',
},
})
</code>
Answer: I ran into the same problem: https://github.com/farmisen/react-native-file-uploader/issues/11. Basically, make sure it got linked properly in MainApplication.java (i.e. include the RCTFileUploaderPackage() in the getPackages() method).


jQuery - add class to li, remove from others with default

Question: Trying to add a border to the thumbnail video that's playing in the iframe.

$('document').ready(function(){

    $("#video-thumbs li").click(function(e){
        e.preventDefault();
        $("#video-thumbs li").addClass("current").not(this).removeClass("current");
      });

});

Comment: I"m not sure what you're trying to ask exactly because its a bit confusing.  I'm assuming you're having the "current" class on other videos.  I would remove every single current class first then do `$('this').addClass("current");`  I hope this helps, but if you could be a little clearer maybe I could help.
Comment: your code works fine here http://jsfiddle.net/wirey00/pPgmm/
Comment: you say you are trying to add a border to videos in the iframe, but your code just adds and removes a class to elements outside the iframe. What is in the iframe?
Comment: The iframe plays a video large. The thumbnails below swap out the link embedded in the iframe. I want the border to be on whichever thumbnail's video is in the iframe.
Answer: Switch your logic around:
$('document').ready(function(){

    $("#video-thumbs li").click(function(e){
        e.preventDefault();
        $("#video-thumbs li").removeClass("current"); // Remove all instances
        $(this).addClass("current"); // Add `.current` to $(this) object only
    });

});

Comment: Or since all the li elements are siblings, `$(this).addClass("current").siblings().removeClass("current");` would be cleaner and target the exact elements, but again, it would be exactly what's in the question, and probably not the problem ?
Comment: I don't see a flaw in his logic.. Add to all then remove from all but the current clicked?  I think it's probably because it's inside an iframe
Comment: nvm.. it's not inside an iframe
Comment: Is it possible that it's conflicting with the onclick function that's in the div?
Comment: @adeneo can't believe I missed that lol.. wow been a long day
Answer: Try structuring the HTML differently, and remove those unsigthly onclick functions :

Now do some jQuery stuff :
$(function(){
    $("#video-thumbs li").on('click', function(){
        $(this).find('img').addClass("current").end()
               .siblings().find('img').removeClass("current");
        $("#myvideo").prop('src', $(this).find('div').data('url'));
    });
});

And it should work fine ?
Here's a FIDDLE


The ring of formal series in a variable $R=k[[x]]$ is a local ring, where the ideal maximal $m$ is the ideal of all series with term independent zero

Question: The ring of formal series in a variable $R=k[[x]]$ is a local ring, where the ideal maximal $m$ is the ideal of all series with term independent zero
I have already noticed this Maximal ideals of the ring of formal polynomials over a ring $R$  and I know that $k[[x]]$ is a local ring because $k$ field is a local ring, what I do not know is how to prove that the maximal ideal of $k[[x]]$ has that shape ($m$ is the ideal of all series with term independent zero.)
Comment: Agree with the above comment, but I don't understand ``I know that $k[[x]]$ is a local ring because k field is a local ring." If you know it's local, I'd think you'd know its maximal ideal. I suspect that you need to think harder about what's going on.
Comment: All you have to do it to prove an element is invertible iff it's not in $xk[[x]]$.
Answer: $(x)=xk[[x]]$ is a proper ideal consisting of elements with constant term $0$ (you agree, yes?)
$k[[x]]/(x)\cong k$  (you agree, yes?)
That last thing means $(x)$ is maximal. Since you already say you know the ring is local, then $(x)$ is the unique maximal ideal.


Grid layout not aligning names

Question: I followed a tutorial to customize a members page for a website I designed, but I can't figure out where my CSS is incorrect. The member names are not lining up under the avatars.
http://www.northeastrunningclub.org/members/
Tutorial: http://premium.wpmudev.org/blog/how-to-create-a-custom-buddypress-members-directory/
I tried changing a couple things to no avail. Any suggestions? Thanks for the help.
Comment: Welcome to Stack Overflow! Questions seeking debugging help ("why isn't this code working?") must include the desired behavior, a specific problem or error and the shortest code necessary to reproduce it **in the question itself**.  See [**How to create a Minimal, Complete, and Verifiable example**](http://stackoverflow.com/help/mcve)
Answer: Try adding this to your CSS:
<code>.item-avatar {
  display: inline-block;
  padding-left: 65px;
}
</code>

Grid layout not aligning names


How to facilitate contributing back better?

Question: Following How can I make my brand new module dependent on a minimal version of Drupal 7 that's required for it to work OK? I have edited the relevant handbook page (but why me?) but noone yet followed up with a simple documentation patch against hook_requirements. How contributing back could be encouraged more?
Comment: Not an answer to the question but that's my bad it completely slipped my mind. I'll get it applied over the weekend
Comment: I kinda have to hold my hand up to dropping the ball on this too.  I read your comment late at night on my tablet and completely forgot to do anything about it!
Comment: I created http://drupal.stackexchange.com/questions/59457 so we have something to point people to in these situations.
Answer: Apart from suggesting to contribute a patch when a question about a hook/function/method makes clear that the documentation needs to be changed, the other alternative would be creating an ad about contributing back to Drupal, with a link to a page that explains how contributions to Drupal/Drupal.org can be done.
See Community Promotion Ads - 2013.


how do i span multiple lines text in java miglayout

Question: i am using miglayout in java. I would like to know how do i make a very long text in a jlabel span multiple lines if that text exceeds width of container? please help. i cannot use html it makes painting slow
Comment: use a textArea instead of the label - or JXLabel of the SwingX project, though it has its quirks - a plain label doesn't support line wraps.
Answer: Try something like this:
<code>JPanel jpanel = new JPanel(new MigLayout("insets 0 0 0 0", "[fill, 99%]", "[grow]"));
</code>
I found thisin my code and its working fine. I think "[grow]" is responsible for making this work.
Comment: probably not: the question is "label span multiple **lines** if that text exceeds **width** of container" ...
Comment: smajlo i have different kinds of jcomponents, buttons jlist, etc in the same panel and as far as i know fill 99% is telling all components, not just label alone, to fill 99%. definitely not what i want


How to perform an integer division, and separately get the remainder, in JavaScript

Question: In JavaScript, how do I get:

The whole number of times a given integer goes into another?
The remainder?
Answer: For some number y and some divisor x compute the quotient (quotient)[1] and remainder (remainder) as:
const quotient = Math.floor(y/x);
const remainder = y % x;

Example:
const quotient = Math.floor(13/3); // => 4 => the times 3 fits into 13
const remainder = 13 % 3;          // => 1

[1] The integer number resulting from the division of one number by another
Comment: % works on floats in JavaScript (this differs from many other languages), which is perhaps not desired: `3.5 % 2` evaluates to 1.5. Make sure to handle (parseInt, floor, etc.) as required
Comment: However, whatever you decide to do about negative numbers, it should be consistent across the quotient and the remainder.  Using `floor` and `%` together is not consistent in that way.  Either use `trunc` instead of `floor` (thereby permitting negative remainders) or use subtraction to get the remainder (`rem = y - div * x`).
Comment: The integral part of -4.5 in mathematics is -5, as -5 is the "highest possible integral number that is still lower than -4.5".
Comment: 1. If you're going to compute the remainder `rem` anyway, you can get the quotient `div` faster without flooring: `(y - rem) / x`.

2. By the way the modulo operation by Donald Knuth's recommended definition (sign-matches-divisor, not the remainder i.e. Euclidean modulus, nor the JavaScript sign-matches-dividend) is what we can code in JavaScript as `function mod (a, n) { return a % n + (Math.sign(a) !== Math.sign(n) ? n : 0); }`.
Comment: -9 / 2 = -4.5.  You then take the floor of -4.5, which is -5. Remember that -5 is less than -4.5, and the floor operation is defined as the largest integer less than a given value.
Comment: Note that in general, having -3 modulo 5 be 2 is instead of -3 may be surprising, but it is mathematically more useful as it avoids any discontinuity around 0; any integer modulo a positive n is always in the range [0,n-1], whether the starting integer is positive or negative. But to go along with that definition and keep the identity `quotient * divisor + remainder = dividend` true, the quotient has to be the floor.
Comment: Attention, this didn't work on negative number because `-9 % 2` is `-1` instead of `1`.
Comment: @martinho, parseInt() is slow and may even produce incorrect results. The reason is it stringifies the parameter and parses it again as a number. When the result of stringification is in scientific notation, the result is usually wrong. https://gideonpyzer.dev/blog/2017/06/06/js-tip-use-parseint-for-strings-not-for-numbers/
Also, you broke the code in the answer. I rolled back your edit.
Comment: usage of `Math.floor()` here is just for the case that given number are positive. [look at this for more explaination](https://developer.mozilla.org/fr/docs/Web/JavaScript/Reference/Objets_globaux/Math/floor).
   Normally `parseInt()` is a better choose to get integer part of number or string.
Comment: @MarkReed, Toughy: Given the description in the question, I don't understand how 2 could go into -9 a total of -5 times. Could you please explain?
Comment: @user166390 all numbers are floats in javascript
Comment: floor is asymmetric because always goes toward the smaller neighboring integer value. trunc is correct because it always goes toward zero.
Answer: I'm no expert in bitwise operators, but here's another way to get the whole number:
var num = ~~(a / b);

This will work properly for negative numbers as well, while Math.floor() will round in the wrong direction.
This seems correct as well:
var num = (a / b) >> 0;

Note: Only use ~~ as a substitution for Math.trunc() when you are confident that the range of input falls within the range of 32-bit integers.
Comment: Another one, whose purpose I just spent the last 20 minutes trying to figure out, is apparently `a/b | 0`
Comment: That's a buu buu. `a = 12447132275286670000; b = 128` `Math.floor(a/b)` -> `97243220900677100` and `~~(a/b)` -> `-1231452688`.
Comment: @user113716 @BlueRaja Bitwise operations makes sense only on integer-types and JS (of course) knows that. `~~int`, `int | 0` and `int >> 0` doesn't modify initial argument, but make interpreter pass integral part to operator.
Comment: `floor` hardly rounds in the wrong direction, given its name - just not the direction that people generally want though!
Comment: Be careful with precedence. `~~(5/2) --> 2` as does `(5/2)>>0 --> 2`, but `~~(5/2) + 1 --> 3`, while `~~(5/2)>>0 + 1 --> 1`. `~~` is a good choice because the precedence is more appropriate.
Comment: just to clarify - these actually work because they are no-ops and all js bitwise operations convert to 32 bit ints
Comment: Agreeing with Jonny Leeds.  In fact, while this solution deserves to be mentioned, I would reject it as the best coding practice.  The answer by Mark Elliot uses a function that is provided for the purpose.  This answer relies on a behavior which is neither guaranteed or intended by the implementation of bitwise operations.
Comment: @bfred.it Idk. Ternaries look weird the first time you see them them. [Null conditionals](http://stackoverflow.com/a/28352116/1028230) also look really weird at first. Nobody says not to use them because they seem clever; instead, they're new lang additions *that devs are expected to learn*. If `~~` or `| 0` didn't already helpfully exist, someone might've been tempted to add them. As [Joel has said](https://www.joelonsoftware.com/2000/11/20/netscape-goes-bonkers/), "Old code doesn't rust". Don't not use helpful existing conventions simply because they're old. This is A Good One.
Comment: Just in case anybody was wondering which was fastest:
http://jsperf.com/integer-division-math-floor-a-b-vs-a-b
(Spoiler results looks inconclusive).
Comment: Answers are buubuus

~~( 2147483648/1) = -2147483648
(2147483648/1) >> 0 = -2147483648
Comment: @bfred.it Most developers already accept the use of `| 0` to truncate, particularly due to its use in asm.js, so you can't exactly say it obfuscates the code, because its meaning is already widely known.
Comment: This is essentially code obfuscation. Don't do this to be clever, use the slightly longer but more readable `Math.floor` or the new `Math.trunc` of ES6 (Edge 12+)
Comment: But, beware that bitwise ops are only for 32 bit integers.
Comment: the unwanted behavior of `>>0` is why emscripten and asm.js use `|0`
Comment: great in a context where you don't have Math library ( in my case, in templates )
Comment: This answer works for numbers that fit inside the range of a signed integer, as Javascript only uses the least significant 32 bits for bitwise operations. However the OP asked about integer operations and ints are actually 32bit signed numbers in most languages (JS does not actually have ints) so I think that is not a problem. Yes it will fail for very large numbers, but so will `Math.floor` when numbers go beyond 53 bits... It's just the inherent limitations present all over the place. If you want to do this for arbitrarily large numbers, you need some bigint / bignumber library.
Comment: I wouldn't say that `Math.floor` rounds the negative quotient in the _wrong_, but rather in a _different_ direction. `Math.floor(-3 / 10) === -1` would then correspond to _floored division_ (rounds _"downwards"_), whereas `~~(-3 / 10) === 0` corresponds to _truncated division_ (rounds _"towards zero"_). See [Wiki: Modulo operation](https://en.wikipedia.org/wiki/Modulo_operation).
Comment: I was commenting on the answer and that does not mention `|0`. Also it's irrelevant that asm.js uses a specific style since it's not meant to be written/read by humans but by transpilers and browsers
Comment: @BlueRaja-DannyPflughoeft By employing a [bitwise OR on a float](https://stackoverflow.com/q/6194950/2192488) in this manner, you are basically banking on the immaturity of JavaScript. Python3 would raise the error `TypeError: unsupported operand type(s) for |: 'float' and 'int'`
Comment: At the time of this comment, `Math.trunc()` is recommended. [As the docs point out](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/trunc#using_bitwise_no-ops_to_truncate_numbers) using bitwise no-ops to truncate will produce bugs when used with values that don't fit within the range of 32-bits.
Answer: I did some speed tests on Firefox.
-100/3             // -33.33..., 0.3663 millisec
Math.floor(-100/3) // -34,       0.5016 millisec
~~(-100/3)         // -33,       0.3619 millisec
(-100/3>>0)        // -33,       0.3632 millisec
(-100/3|0)         // -33,       0.3856 millisec
(-100-(-100%3))/3  // -33,       0.3591 millisec

/* a=-100, b=3 */
a/b                // -33.33..., 0.4863 millisec
Math.floor(a/b)    // -34,       0.6019 millisec
~~(a/b)            // -33,       0.5148 millisec
(a/b>>0)           // -33,       0.5048 millisec
(a/b|0)            // -33,       0.5078 millisec
(a-(a%b))/b        // -33,       0.6649 millisec

The above is based on 10 million trials for each.
Conclusion: Use (a/b>>0) (or (~~(a/b)) or (a/b|0)) to achieve about 20% gain in efficiency. Also keep in mind that they are all inconsistent with Math.floor, when a/b<0 && a%b!=0.
Comment: Note that optimizing integer division for speed would make sense only if you're doing it *a lot*. In any other case I would recommend choosing the simplest one (whichever seems simplest to you and your coworkers).
Comment: Well, if your coworkers aren't programming chips in assembler, they'll likely understand `Math.floor` better. And even if not, this one is googleable.
Comment: @m01 totally agree - there's way too much of a focus on stuff like this online
Comment: @m01 But which is harder: learning about `Math.floor` and the who-knows-how-many other API functions, or learning about the `~` (bitwise-not) operator and how bitwise operations work in JS and then *understanding* the effect of double tilde?
Comment: This is a performance comparison of integer division methods, not an answer to the question.
Comment: I find Math.floor() has more stable performance than others do. it is less up-and-down
Comment: @JonnyLeeds I came here looking for integer division in Javascript, which isn't a niche requirement.
Comment: @MarkGreen yes but just wanting to do that doesn't mean you should write it in a weird form just because it happens to be fastest, without good reason - code clarity in general should normally be your first concern.  Also these tests might be completely meaningless after language changes and across different browsers - you'd need to profile to find out what is slow in your application regardless.  It's unlikely to be your integer division method unless you've already optimised ever single other thing!
Comment: | 0: 2582.521ms
~~: 2631.974ms
Math.floor: 2382.893ms.
I would encourage you to run the tests yourself, https://plnkr.co/edit/9g0IXjpavR2t2d2L1DC0
Comment: Beware, all the bitwise operations are working only with 32-bit numbers
Comment: In terms of readability, I just had someone ask what `|0` is doing, since it looks like a non-op… "Yep—it's a cast-to-int" being a clear and direct answer leads me to be a fan of this choice
Comment: @JonnyRaa Good code is fast and easy to understand. Generally speaking, optimizing JavaScript runtimes like V8 do better if you encapsulate performance sensitive code in a function because that means they only have to evaluate the code inside that function to optimize it. You can write a very well documented "fast_integer_divide" function with bitwise hacks and then everywhere else in the code you see "fast_integer_divide" which is even clearer than Math.floor and MUCH faster (5x) in my tests. Code legibility is very important but please do not encourage people to sacrifice performance..
Comment: Math.floor still doesn't work. Thank you for the work around.
Comment: By employing a [bitwise operations on a float](https://stackoverflow.com/q/6194950/2192488) in this manner, you are basically banking on the immaturity of JavaScript. Python3 would raise the error `TypeError: unsupported operand type(s) for |: 'float' and 'int'`
Comment: For starters, if fractions of milliseconds make a difference to your application, JavaScript doesn't seem the best language choice. But if you have a case where performance is really more important than readability, and you're stuck with JS, be aware that performance isn't uniform across all platforms. I'd be surprised if this particular optimisation would be worth a development team's resources, but if it was, an interpreter automatically coverting `Math.floor(a/b)` to a bitwise operation seems simple enough.
Comment: "20% gain in efficiency" you posted results that show tenths of milliseconds difference. That's like my boss bragging he just gave me a 0.001% pay increase. If _tenths of milliseconds_ performance increase is useful to you, just upgrade the server, it'll be cheaper than dev time and you will get ten times the improvement.
Answer: ES6 introduces the new Math.trunc method. This allows to fix @MarkElliot's answer to make it work for negative numbers too:
var div = Math.trunc(y/x);
var rem = y % x;

Note that Math methods have the advantage over bitwise operators that they work with numbers over 231.
Comment: @4esn0k It's not a bug. Your number has too many digits, you can't have that much precision in a 64-bit binary format IEEE 754 number. For example, `18014398509481984 == 18014398509481985`.
Comment: for rubyists here from google in search of `divmod`, you can implement it as such: ```function divmod(x, y) {
  var div = Math.trunc(x/y);
  var rem = x % y;
  return [div, rem];
}
```
Comment: I think the choice is simple: You need support for numbers up to 32 bits signed? Use `~~(x/y)`. Need to support bigger numbers up to 54 bits signed? Use `Math.trunc` if you have it, or `Math.floor` otherwise (correct for negative numbers). Need to support even bigger numbers? Use some big number library.
Comment: var y =18014398509481984; var x= 5; div = ? - bug ?
Comment: 18014398509481984 == 2**54, and i specially used this number, because it is represented exactly in binary64 format. and the answer is represented exactly too
Comment: @4esn0k I didn't explain very well. I meant `18014398509481984 / 5` is `3602879701896396.8`. However, that can't be stored, so it is converted to `3602879701896397`. And then `Math.trunc(3602879701896397)` is `3602879701896397`.
Comment: OK, I spent full day thinking how to workaround this rounding too. Seems, it is possible to determine, that there was rounding and correct "truncated quotinent": if (y / x === div && rem > x - rem) { div -= 1; }", but I am not sure in correctness, anyway never mind, your solution is good enough for most of the cases.
Comment: @AlexMoore-Niemi It requires doing the same operation twice, though.  Pretty sure the processor will put the quotient and modulus in different registers for one operation, so JS should really provide a mechanism to get both at once.
Answer: I normally use:
const quotient =  (a - a % b) / b;
const remainder = a % b;

It's probably not the most elegant, but it works.
Comment: if you need both quotient and remainder, calculate the remainder first and then reuse that value in the expression for the quotient, i.e. quotient = (a - remainder) / b;
Comment: remainder = a % b;
quotient =  (a - remainder) / b;
Comment: Nice solution because it avoids the ugliness of parsing or truncating a float.
Answer: var remainder = x % y;
return (x - remainder) / y;

Comment: This version unfortunately fails the test when x = -100 because it returns -34 instead of -33.
Comment: what about "var x = 0.3; var y = 0.01;" ?  (thanks to https://github.com/JuliaLang/julia/issues/4156#issuecomment-23324163)
Comment: Actually, @Samuel, with negative values, this method returns correct results, or at least it returns the same values as the method using `Math.trunc` :). I checked with 100,3; -100,3; 100,-3 and -100,-3. Of course, a lot of time has passed since your comment and things change.
Answer: You can use the function parseInt to get a truncated result.
parseInt(a/b)

To get a remainder, use mod operator:
a%b

parseInt have some pitfalls with strings, to avoid use radix parameter with base 10
parseInt("09", 10)

In some cases the string representation of the number can be a scientific notation, in this case, parseInt will produce a wrong result.
parseInt(100000000000000000000000000000000, 10) // 1e+32

This call will produce 1 as result.
Comment: `parseInt` should be avoided when possible.  Here is Douglas Crockford's warning: "If the first character of the string is 0, then the string is evaluated in base 8 instead of base 10. In base 8, 8 and 9 are not digits, so parseInt("08") and parseInt("09") produce 0 as their result. This error causes problems in programs that parse dates and times. Fortunately, parseInt can take a radix parameter, so that parseInt("08", 10) produces 8. I recommend that you always provide the radix parameter."  http://archive.oreilly.com/pub/a/javascript/excerpts/javascript-good-parts/awful-parts.html
Comment: In a division, I expect receive a number, not a string, but this is a good point.
Comment: @Powers so add the radix. He doesn't say `parseInt` should be avoided; just that there are some gotchas to be aware of. _You must be aware of these things and be prepared to cope._
Comment: Never call `parseInt` with a number argument. `parseInt` is supposed to parse partially-numerical strings, not truncate numbers.
Comment: Just because things are not originally meant to be used a certain way, it doesn't mean you shouldn't. This answer works.
Answer: Math.floor(operation) returns the rounded down value of the operation.
Example of 1st question:

const x = 5;
const y = 10.4;
const z = Math.floor(x + y);

console.log(z);

Example of 2nd question:

const x = 14;
const y = 5;
const z = Math.floor(x % y);

console.log(x);
Answer: JavaScript calculates right the floor of negative numbers and the remainder of non-integer numbers, following the mathematical definitions for them.
FLOOR is defined as "the largest integer number smaller than the parameter", thus:

positive numbers: FLOOR(X)=integer part of X;
negative numbers: FLOOR(X)=integer part of X minus 1 (because it must be SMALLER than the parameter, i.e., more negative!)

REMAINDER is defined as the "left over" of a division (Euclidean arithmetic). When the dividend is not an integer, the quotient is usually also not an integer, i.e., there is no remainder, but if the quotient is forced to be an integer (and that's what happens when someone tries to get the remainder or modulus of a floating-point number), there will be a non-integer "left over", obviously.
JavaScript does calculate everything as expected, so the programmer must be careful to ask the proper questions (and people should be careful to answer what is asked!) Yarin's first question was NOT "what is the integer division of X by Y", but, instead, "the WHOLE number of times a given integer GOES INTO another". For positive numbers, the answer is the same for both, but not for negative numbers, because the integer division (dividend by divisor) will be -1 smaller than the times a number (divisor) "goes into" another (dividend). In other words, FLOOR will return the correct answer for an integer division of a negative number, but Yarin didn't ask that!
gammax answered correctly, that code works as asked by Yarin. On the other hand, Samuel is wrong, he didn't do the maths, I guess, or he would have seen that it does work (also, he didn't say what was the divisor of his example, but I hope it was 3):
Remainder = X % Y = -100 % 3 = -1
GoesInto = (X - Remainder) / Y = (-100 - -1) / 3 = -99 / 3 = -33
By the way, I tested the code on Firefox 27.0.1, it worked as expected, with positive and negative numbers and also with non-integer values, both for dividend and divisor. Example:
-100.34 / 3.57: GoesInto = -28, Remainder = -0.3800000000000079
Yes, I noticed, there is a precision problem there, but I didn't had time to check it (I don't know if it's a problem with Firefox, Windows 7 or with my CPU's FPU). For Yarin's question, though, which only involves integers, the gammax's code works perfectly.
Answer: Use:
const idivmod = (a, b) => [a/b |0, a%b];

There is also a proposal working on it:
Modulus and Additional Integer Math
Answer: Alex Moore-Niemi's comment as an answer:
For Rubyists here from Google in search of divmod, you can implement it as such:
function divmod(x, y) {
  var div = Math.trunc(x/y);
  var rem = x % y;
  return [div, rem];
}

Result:
// [2, 33]

Comment: Usually, `divmod` uses floored division (`Math.floor`), which differs from truncated division (`Math.trunc`) when negative numbers are involved. This is the case for [NPM `divmod` package](https://www.npmjs.com/package/divmod), [Ruby `divmod`](https://ruby-doc.org/core-2.3.0/Numeric.html#method-i-divmod), [SWI-Prolog `divmod`](http://www.swi-prolog.org/pldoc/doc_for?object=divmod/4) and probably many other implementations, too.
Comment: Truncated division gives more naturally looking results than floored division, but compatibility trumps that, IMO. Maybe, there are mathematical or performance reasons for using floored division, too. Note that usually, `divmod` exists because it is performs twice as fast as computing the two operations separately. Providing such a function without this performance benefit might be confusing.
Answer: There are several possible definitions for the primitive functions div (which computes the quotient of a division) and mod (which computes the remainder of a division) that satisfy these constraints:

Number.isInteger(div(x, y));
x === div(x, y) * y + mod(x, y);
Math.abs((mod(x, y)) < Math.abs(y).

The definitions that are in common usage in the computer science literature and in programming languages are based on

the truncated division:
function div(x, y) {
  return Math.trunc(x / y);
}

function mod(x, y) {
  return x % y;
}

the floored division:
function div(x, y) {
  return Math.floor(x / y);
}

function mod(x, y) {
  return ((x % y) + y) % y;
}

the Euclidean division:
function div(x, y) {
  return Math.sign(y) * Math.floor(x / Math.abs(y));
}

function mod(x, y) {
  const z = Math.abs(y);
  return ((x % z) + z) % z;
}

Additionally,

the truncated division has this property: mod(x, y) * x >= 0;
the floored division has this property: mod(x, y) * y >= 0;
the Euclidean division has this property: mod(x, y) >= 0.

Consequently,

if x >= 0 and y > 0, then the truncated, floored, and Euclidean divisions agree;
if x >= 0 and y < 0, then the truncated and Euclidean divisions agree;
if x <= 0 and y > 0, then the floored and Euclidean divisions agree;
if x <= 0 and y < 0, then the truncated and floored divisions agree.

The choice of the Euclidean division is recommended over the truncated and floored divisions for defining the functions div and mod, according to the paper 'The Euclidean definition of the functions div and mod' by Raymond Boute:

In this paper we clarify the differences between the various definitions, in particular those based on division by truncation (T-definition) and on division by flooring (F-definition) as defined by Knuth. We also propose still another definition, which we call Euclidean because it is based on Euclid's theorem (E-definition). This alternative is rarely discussed in the literature, yet on closer analysis it is advantageous in terms of regularity and useful mathematical properties, both theoretically and in practical usage. The Euclidean definition usually emerged as the most straightforward choice, over a wide variety of representative application areas where we experienced the need for a div-mod function pair.
Answer: we can use the below approach.
quotient = dividend / divisor | 0;

and any way we can get reminder with modulo operator
remainder = dividend % divisor;

Answer: If you need to calculate the remainder for very large integers, which the JS runtime cannot represent as such (any integer greater than 2^32 is represented as a float and so it loses precision), you need to do some trick.
This is especially important for checking many case of check digits which are present in many instances of our daily life (bank account numbers, credit cards, ...)
First of all you need your number as a string (otherwise you have already lost precision and the remainder does not make sense).
str = '123456789123456789123456789'

You now need to split your string in smaller parts, small enough so the concatenation of any remainder and a piece of string can fit in 9 digits.
digits = 9 - String(divisor).length

Prepare a regular expression to split the string
splitter = new RegExp(`.{1,${digits}}(?=(.{${digits}})+$)`, 'g')

For instance, if digits is 7, the regexp is
/.{1,7}(?=(.{7})+$)/g

It matches a nonempty substring of maximum length 7, which is followed ((?=...) is a positive lookahead) by a number of characters that is multiple of 7. The 'g' is to make the expression run through all string, not stopping at first match.
Now convert each part to integer, and calculate the remainders by reduce (adding back the previous remainder - or 0 - multiplied by the correct power of 10):
reducer = (rem, piece) => (rem * Math.pow(10, digits) + piece) % divisor

This will work because of the "subtraction" remainder algorithm:
n mod d = (n - kd) mod d

which allows to replace any 'initial part' of the decimal representation of a number with its remainder, without affecting the final remainder.
The final code would look like:
function remainder(num, div) {
  const digits = 9 - String(div).length;
  const splitter = new RegExp(`.{1,${digits}}(?=(.{${digits}})+$)`, 'g');
  const mult = Math.pow(10, digits);
  const reducer = (rem, piece) => (rem * mult + piece) % div;

  return str.match(splitter).map(Number).reduce(reducer, 0);
}

Answer: If you are just dividing with powers of two, you can use bitwise operators:
export function divideBy2(num) {
  return [num >> 1, num & 1];
}

export function divideBy4(num) {
  return [num >> 2, num & 3];
}

export function divideBy8(num) {
  return [num >> 3, num & 7];
}

(The first is the quotient, the second the remainder)
Comment: Generally, `function divideByPowerOf2(num, exponent) { return [num >> exponent, num & ((1 << exponent) - 1)]; }`.
Answer: Calculating the number of pages may be done in one step:
Math.ceil(x/y)

Comment: I don't see how this provides the remainder.
Comment: What do you mean by *"the number of pages"*? Is this a bogus answer?
Answer: function integerDivison(dividend, divisor) {

    this.Division = dividend/divisor;
    this.Quotient = Math.floor(dividend/divisor);
    this.Remainder = dividend%divisor;
    this.calculate = () => {
        return {Value:this.Division, Quotient:this.Quotient, Remainder:this.Remainder};
    }
}

var divide = new integerDivison(5, 2);
console.log(divide.Quotient)     // To get the quotient of two values
console.log(divide.division)     // To get the floating division of two values
console.log(divide.Remainder)    // To get the remainder of two values
console.log(divide.calculate())  // To get the object containing all the values

Answer: If you need the quotient for some stupidly big numbers, you can use:
Math.trunc((x/y) + (Number.EPSILON * (2 ** Math.ceil(Math.log2(Math.abs(x/y))))) * Math.sign(x/y))

NOTE: This only works for cases where the x and y values, i.e. the dividend and divisor, are represented accurately, even after any rounding to make them work as integers when they're larger than Number.MAX_SAFE_INTEGER.
For example, if we have:
x = 45000000000000000000000000000 = 4.5e+28
y =   500000000000000000000000000 =   5e+26

Then the answers given on this page give you:
89.99999999999999: x/y
90: Math.trunc((x/y) + (Number.EPSILON * (2 ** Math.ceil(Math.log2(Math.abs(x/y))))) * Math.sign(x/y))
89: Math.floor(x/y)
89: ~~(x/y)
89: (x/y)>>0
89: x/y|0
89: (x-(x%y))/y

The correct answer is 90, so, as you can see, the equation I gave above is the only one which provides a correct answer.
The equation works for negative results as well.  If we make x negative then we get:
-89.99999999999999: x/y
-90: Math.trunc((x/y) + (Number.EPSILON * (2 ** Math.ceil(Math.log2(Math.abs(x/y))))) * Math.sign(x/y))
-90: Math.floor(x/y)
-89: ~~(x/y)
-89: (x/y)>>0
-89: x/y|0
-89: (x-(x%y))/y

Only that equation and Math.floor() give the correct answers.
And, just to confirm with some different values that give a slightly larger value:
x = -45000000000000000000000000 = -4.5e+25
y =    500000000000000000000000 =    5e+23

we get:
-90.00000000000001: x/y
-90: Math.trunc((x/y) + (Number.EPSILON * (2 ** Math.ceil(Math.log2(Math.abs(x/y))))) * Math.sign(x/y))
-91: Math.floor(x/y)
-90: ~~(x/y)
-90: (x/y)>>0
-90: x/y|0
-90.00000000000001: (x-(x%y))/y

In this case, Math.floor() and (x-(x%y))/y fail, meaning that, while it may not be fast or pretty, the code given for this answer is the only method which gives correct results in all cases, provided that the divisor and dividend are able to be represented accurately.  (Or, at least, all cases that I'm aware of.)
If you want to know how to get the correct remainder for large numbers, see:

Division and remainder of large numbers in JavaScript
Modulo in JavaScript - large number

Addendum: If you're only working with positive numbers, then you can shorten it to this:
Math.trunc((x/y) + (Number.EPSILON * (2 ** Math.ceil(Math.log2(x/y)))))

Answer: You can use the ternary operator to decide how to handle positive and negative integer values as well.
var myInt = (y > 0) ? Math.floor(y/x) : Math.floor(y/x) + 1

If the number is a positive, all is fine. If the number is a negative, it will add 1 because of how Math.floor handles negatives.
Answer: This will always truncate towards zero.
function intdiv(dividend, divisor) {
    divisor = divisor - divisor % 1;
    if (divisor == 0) throw new Error("division by zero");
    dividend = dividend - dividend % 1;
    var rem = dividend % divisor;
    return {
        remainder: rem,
        quotient: (dividend - rem) / divisor
    };
}

Answer: Here is a way to do this. (Personally I would not do it this way, but I thought it was a fun way to do it for an example.) The ways mentioned in previous answers are definitely better as this calls multiple functions and is therefore slower as well as takes up more room in your bundle.

function intDivide(numerator, denominator) {
  return parseInt((numerator/denominator).toString().split(".")[0]);
}

let x = intDivide(4,5);
let y = intDivide(5,5);
let z = intDivide(6,5);
console.log(x);
console.log(y);
console.log(z);
Comment: I really like the mention about taking up more room.
Comment: y'all are savage, I literally say its NOT a good way to go about this... but like it DOES work


Septic system failed - should I try installing an aeration unit?

Question: My septic system's leach field is not able to absorb the liquid that comes out of the septic tank any more. It flows out of the pipes in the leach field and surfaces in the grass. Based on the reading I have done (the "Septic System Owner's Manual" by Lloyd Kahn which is very good) there is a chance of recovering from this problem by installing an aeration system.
An aeration system pumps air into the septic tank, thereby encouraging the development of "aerobic bacteria". The aerobic bacteria need air to survive, and are more voracious eaters than the an-aerobic bacteria that are typically present in a septic tank without air pumped into it. The idea is that the aerobic bacteria will clean up the fluid in the septic tank and then they will also make their way into the lines of the leach field, clearing away the "bio-mat" that has formed over the years. This bio-mat is the thing that is clogging up the leach field, preventing it from doing its job.
Anyway, there are quite a few air pumping systems out there that are designed to be installed into an existing septic system. My question is, does anyone have experience with installing such a pump to deal with this type of problem, and if so how effective was it at clearing up the problem? Is it worth the investment? For some reason these systems seem to cost around $1,000, which seems a lot for what is basically just an electric air pump.
Update: I had the air pump system installed in April 2011, so let's see how it works..!  It is an aero-stream unit which sits near my outside electric outlet and there's a plastic tube that is buried a few inches and that goes into the septic system via the outlet riser and down into the liquid. It pumps a lot of air in, the liquid churns around and bubbles continually. So far, I can say that the septic liquid is no longer foul-smelling. It has almost no odor any more. The level of liquid varies, depending on rainfall and water usage. Sometimes it comes to the top of the riser, at other times it's about 10 inches below the top. If this system works, I'm expecting that the level of liquid will fall gradually. This means that the lines are being cleared of gunk. Time will tell... I'll try to report back periodically.
Update June 30 2011
The level of liquid in my tank is about 18 inches below the top now. Very encouraging so far. Mind you, the Spring wet season is behind us, so it could just be due to the water table being lower in the summertime. Also my family was just out for a couple of weeks on vacation which took all the load off the septic.
Update Aug 20 2015
The aeration unit helped a lot but by itself wasn't enough. I ended up digging (by hand) a new "overflow trench" from the tank outlet. I used 3/4" gravel plus a piece of perforated plastic drainage pipe at the bottom. The trench was about 2 foot deep and 30 foot long and ended at a large flower bed which is slightly downhill from the septic tank. With the aeration unit plus this new overflow trench my septic tank is working well enough to not need replacement. The aeration unit ensures that the effluent that sometimes drains into the overflow trench is not foul smelling. This has been working for a few years now. Overflow will happen during periods of high usage such as lots of showering/dishwashing. It's not perfect but it's good enough.
Comment: Do you have a septic plan showing the design, size and distribution of the leach field? Age of system? Are all legs of the system percolating through the sod?
Comment: Have there been any recent changes in the water table level, heavy rains, or nearby construction or grade changes?
Comment: No I don't have a plan. Not sure about age, but at least 20 years. At least 2 of the legs are percolating, the 3rd not so much. I think there are 3 legs that come out of the junction box that's located about 10 feet from the tank.
Comment: This is the wet season, we had a *ton* of snow this year that has now melted, so it's definitely a tough year for the system. Having said that, the septic typically comes up out of the ground at the end of one of the leach field legs, even in summer. That's why I think the field is basically clogged.
Comment: When I was a kid, my dad used to put a good bit of yeast with sugar and water in a bowel, let it sit for a bit to activate and flush that down.  Never had an issue with the field.  Results might vary :)
Answer: I just had a breakthrough in my situation in the last couple of weeks.    My leach field was about 95% clogged, very little if any movement.    I had already diverted the graywater to another solution, which helped for awhile, but slowly the field failed to the point of essentially total failure.  I have a single septic tank and wanted to try aerating it without the cost of a second tank.    I learned a number of things that I haven't seen explicitly explained on any of the forums so I wanted to put it here to hopefully help someone.
I installed my aerator a few months back.    Too much air volume and placing it in the center of the tank caused to much churning and cause solids to exit the tank.    I did notice the smell though went from putrid to a smell like freshly turned soil (not coincidentally; the same aerobic bacteria live in airy soil).   I spent a couple months thinking it didn't work.    Water still not going out.   But in the last couple of weeks I'm actually seeing the water levels fall to STAY at the edge of the outlet pipe!!!!     First time ever!!     I used the techniques below to avoid replacing my field without buying a $1000 solution.
You CAN aerate a single tank, but it's imperative that the aeration process doesn't agitate the incoming solids.    They have to come into the first baffle and separate so the lighter material can rise and heavier solids fall.    To accomplish this you have to use very fine bubbles and they have to be generated as far from the incoming line as possible, or they have to act inside an isolation vessel (there are videos where people use 12" pipe to contain the aerator).    You can get diaphragm diffusers for as cheap as $35 if you search around, connected to PVC pipe, and use an air valve to supply JUST ENOUGH air pressure/volume to activate the diaphragm (air RELIEF valve, not cutoff.   You'll damage your pump if you restrict airflow inappropriately).    Too much and you get a rolling torrent (which you don't want).    Place this diaphragm(s) near the output baffle or let it work IN the output baffle.    This allows all the agitation to happen away from the settling part of the tank.    THIS IS THE KEY, and is the reason why a separate aeration tank is ideal, so there's no chance of agitating the incoming.    Also I had a 4" TEE on the outlet side which served as the separator.  I put the two diaphragm diffusers on EITHER SIDE of the outlet TEE.  You don't want bubbles going up INTO the TEE which could siphon some debris up in there.    I got a septic filter brush and put down in the pipe to help filter the effluent, though as clear as the water is going out I don't think it was necessary.
One suggestion I received from a local contractor for my single concrete tank was to empty it, get inside and build a cinderblock wall giving 2/3 incoming/settling, and 1/3 aeration, but the tank has to be pretty good size to do that.   You need several hundred gallons of aeration space.    I put this on the burner as a next option, but turns out it wasn't necessary.
If you have a way of opening the other end of your leach lines to extend your field, at least temporarily, you get this freshly energized aerated bacteria through there quicker to let it go to work.   My temporary relief is now closed off and the field appears to be working!!
Note I did NOT need to buy super duper amped up bacteria to add.    From everything I've read this is hogwash and money makers for people.    That's like buying weed seeds;  give dirt some rain and you'll get the weeds.   The bacteria will fill the space if they have oxygen.
My findings confirm for me that the low agitation solutions available out there for $500-$1000 would certainly work.    I just chose to play around with a DIY solution.
Hope this helps someone.
Comment: Very Nice answer.
Comment: Thanks for the answer, it's quite close to what I ended up doing. My solution is still working to this day.
Answer: Here are some ideas for reducing the load on your septic system:
Set your toilet reservoir to hold less water. Sometimes the float has an adjustment mechanism, or you can bend something. My 1950 toilet previously used 5 gallons per flush. I set it to the lowest fill level, and then put some mason jars in the reservoir to hold back more water. I don't put a lid on them, so the water will circulate and not stagnate.
Redirecting your greywater. Basically, greywater can be treated onsite with much simpler, cheaper systems than what is required for blackwater. Something as simple as redirecting your laundry greywater to a mulch pit can make a big difference.
See "Create an Oasis with Greywater" by Art Ludwig: http://www.oasisdesign.net/greywater/createanoasis/. He discusses which approaches are appropriate for which situations, and including a failing septic system.
You may also consider a waterless composting toilet. A simple system like the Lovable Loo works best, doesn't smell, is cheap to create and operate, and produces fantastic compost. And no plunging, ever. However, just as bacteria in poop is great for the compost pile, it's also great for the septic tank, so if you're still sending greywater in to the septic system, you may want to keep at least one flush toilet.
(Note that I don't actually have a septic system, so this comes from what I've read + my experiences with a sawdust toilet.)
Comment: Good suggestions - thanks. I have my laundry water go to a separate place (not the septic tank). I have a low-flow toilet. Haven't tried the composting toilet yet, that could be an option if my septic is unrecoverable.
Answer: I recently had my septic system pumped. While the guy was here working we got to chatting. He said he has worked on some sites where the leach field got backed up to the point that it was no longer working. His company installed a new leach field and switched the system over to the new field. Over the course of a couple years (!! yeah, this place he was working had some problems) the new leach field backed up. They decided to try and switch back to the old leach field, which they discovered had recovered over the course of a few years.
Not sure if it is possible/economical to do the same in your situation, but switching to a different system can give time for the old system to clear itself out. This is also possibly a last resort option.
Comment: Thanks Josh. This is definitely a last resort option, it involves installing a new septic field. That would be very expensive (I think $10k or so). I went ahead and had the air pump installed, about a month ago or so. So, I will see if it helps :)
Comment: Based on my recent experiences, it should be cheaper to get a new drain field. Obviously, prices vary widely. Get a couple estimates.
Answer: User 7403 was exactly correct. Adding an aerator to the septic tank simply stirs up the sludge and circulates it around the tank, sending it into your septic field to clog it up even more. The oxygenated water breaks the sludge up into tiny particles that even slips right through your Septic Effluent Filter creating a thick black sludge that enters your septic field, clogging it up further. If you place the aerator in the left chamber of your tank, all the sludge will end up in the right chamber. If you place the aerator in the right chamber, all the sludge in this chamber will end up in your leach field. User 7403 was exactly correct about reducing airflow to the bubbler to make fine, tiny bubbles. He was also correct about placing the bubbler into a pipe to prevent circulating sludge all around the tank.
I am using the Quad aerator Bubbler that I installed into the bottom of a 13 inch diameter pipe that rises above the water level so as not to disturb the scum layer. Holes near the bottom and holes below the top of this pipe allow water to recirculate vertically so as not to disturb the sludge layer. Water in the tank must remain motionless to allow sludge to settle on the bottom. I have reduced the airflow so that tiny bubbles come out of the aerator.
You clear up and rejuvenate your septic field by pouring Sodium Percarbonate mixed with water directly into your septic field. Add a pipe coming up vertically to your exit TEE so you can pour water into your septic field. 36 lbs of sodium percarbonate poured into your septic field over 4 days will remove all of the biomat, making your septic field just like new. ( Sodium Percarbonate is the chemical name for Oxyclean ).
Google Oxyseptic for more details.
This works extremely well because it creates a LOT of free oxygen that destroys the biomat. Sodium Percarbonate mixed with water is the equivalent of 30% hydrogen peroxide. BEWARE !! HUGE BROWN BUBBLES will come boiling out of your septic field as the sodium percarbonate does its job eliminating the biomat.
For complete details and photos of how I rejuvenated my septic field, see this Google Documents link:
http://tinyurl.com/Septic-Solutions
Answer: I think typically an aeration system uses an entirely different tank design than a normal septic system, namely one that is separated into at least two chambers. I'm not sure that just adding an air pump will solve your problem.
Comment: Yes I know the systems that you are talking about. However, some of these aeration systems can be installed in existing tanks that were designed originally to be anaerobic. For example: http://www.aero-stream.com/ or http://www.sludgehammer.net/
Answer: In my area, these types of issues are not something the average homeowner can tackle.  The county specifies the type of septic system that is required based on soil tests, drainage, and nearby bodies of water.  The homeowner almost has no say.  All work on systems must go though the health department, and all homes have to be inspected for a home sale.  If the system is outdated and not up to code (no grandfathering), it needs to be updated / replaced.  I am in NE Ohio.
So this may not apply for the original poster, but for others reading this question, be sure check your local government for required permits, regulations and inspections.
Answer: this is a common problem, first be sure to do as much research as you can. there's a lot of variables to consider. i have a single chamber cesspool, it's old, very old. i just built my own system. i put my air compressor down the basement, ran an air line with a quick release to the vent, I have no other access, attached a piece of garden hose to that and made sure it was long enough to get to the bottom of my cesspool. I then attached a four foot piece of soaker hose I had laying around to that. capping the end of course. and using stainless steel hose clamps. I have it set to maybe one psi., I had to go back and forth to look down the hole and adjust the regulator. it takes some time, but easy. you want to see some movement on the surface, some! not bubbling like boiling water on the stove. you will see a few bubbles from soap or what not. any oder should go away in one to two days, when the oder goes away, that means your now aerobically digesting. let me be clear, you DO want to mix and agitate the solids! it makes it easier for the bacteria to digest. they will eat all the black sludge! most likely it's your washing machine that's clogging your system. bath water is o.k. for your septic as the bacteria will eat hair and skin cells. they can't eat the synthetic fibers that come from you washing machines waste water. your have to get a filter for that and ideally run it somewhere else. I filter mine and run it out to a French drain, the bushes and grass love it! put a old nylon on the end of your washers waste pipe with a rubber band, do two or three loads of wash and you'll see what I'm talking about! keep in mind, your water level inside the tank will go up at first, and this is by no means a quick fix, I've had my system running for a year now and am finally seeing positive results. if your washer's going to your septic, run it somewhere else or start filtering it, then I would suggest having it pumped after aerating for a month to help get out all those fibers from the washer.
Answer: My solution is a three stage septic tank with a aeration pump and will never have problem with your septic on my system I have a baffle filter and on my pump in the tank I also have a pressure filter at the top of the riser the pump pumps to my septic field that is 250 feet from my house and the pump is a 3/4 horse so there are lot of ponys to pump it out to the field and I live Canada we have extreme weather here lots of snow and lots of rain my septic field is 52 by 52 round so it is a big field
Comment: Hello, and welcome to Stack Exchange. There's good information here, but it's tough to understand because of the lack of formatting, sentences and grammar. If you want, some editing could make it a much better answer.


Chrome is not allowed to access my external files?

Question: Basically I'm going to be working on PHP for my website but I put it all in the htdocs. Now it won't load any of the files including the JavaScript.
This is the css link
<link rel="stylesheet" href="file:///C:/xampp/htdocs/Website/CSS/Home.css" type="text/css">

Answer: Use Relative path: usually absolute path possibility to break or not show output
<link rel="stylesheet" href="CSS/Home.css" type="text/css">

Comment: Thanks that did the trick all i had to add was two dots before the CSS part :)


Get class name of django model

Question: I have a django model:
class Book(models.Model):
  [..]

and I want to have the model name as string: 'Book'. When I try to get it this way:
Book.__class__.__name__

it returns 'ModelBase'.
Any idea?
Answer: Try Book.__name__.
Django models are derived from the ModelBase, which is the Metaclass for all models.
Answer: As suggested by the answer above, you can use str(Book._meta).
This question is quite old, but I found the following helpful (tested on Django 1.11, but might work on older...), as you may also have the same model name from multiple apps.
Assuming Book is in my_app:
print(Book._meta.object_name)
# Book

print(Book._meta.model_name)
# book

print(Book._meta.app_label)
# my_app

Comment: This should be the accepted answer for newer versions of Django.
Comment: You're correct @Bobort, it's working on Django version `2.2.3` too.
Comment: This is exactly what I needed. This works for **both** the model/class itself and an instance of the model.
Answer: Instead of doing Book.__class__.__name__ on class itself, if you do it over a book object, then book_object.__class__.__name__ will give you 'Book' (i.e the name of the model)
Comment: This one helped me in my case.  I merged 2 querysets that are of different models. In a loop I needed to get the class name of the object when I'm iterating.
Comment: Peter, how did you merge two querysets??  Or is the merged set just a list of model instances??  Thanks
Answer: class Book(models.Model):
  [..]
  def class_name(self):
    return self.__class__.__name__

With this way, whenever you called book.class_name() in python code (also in the template {{book.class_name}}) it will return class name which is 'Book'.
Answer: I got class name by using,
str(Book._meta)

Book.__class__.__name__  -> this will give you the ModelBase

Comment: Thanks; `str(self.model._meta)` is what I was looking for; as for the other give me the parent class.
Comment: If you want something more implicit than a call to string, then you can get the same (tried on Django 1.11) with:
`Book._meta.object_name` or `Book._meta.model_name`. Then if you want the app name as well, that's accessible via `Book._meta.app_label`
Answer: You could also retrieve the model name from the model's Meta class. This works on the model class itself as well as any instance of it:
# Model definition
class Book(models.Model):
    # fields...

    class Meta:
        verbose_name = 'book'
        verbose_name_plural = 'books'

# Get some model
book = Book.objects.first()

# Get the model name
book._meta.verbose_name

Setting verbose_name and verbose_name_plural is optional. Django will infer these values from the name of the model class (you may have noticed the use of those values in the admin site).
https://docs.djangoproject.com/en/3.0/ref/models/options/#verbose-name

Get class name of django model


How use or enable Tor Circuit when it is in Remote Control (Selenium)?

Question: Actually I managed control Tor Browser with Selenium, but I'd realised that Tor circuits (change of IP's) isn't enable. So exist a way to enable it? Or use the new feature called (New Identity) form code.
My enviroment is Python 3.7, tbselenium 0.4.2 and Tor Browser 9.0.2, thanks everyone.
Answer: Here is an example script on how to use Tor with the chrome webdriver:
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.common.proxy import Proxy, ProxyType

#tor
from stem import Signal
from stem.control import Controller

link = #some_url
prox='socks5://127.0.0.1:9150' #This connects Selenium to the Tor Port which then connects to a Tor network

while True:

    with Controller.from_port(port = 9051) as controller: #this is how you get a new Identity!
        controller.authenticate()
        controller.signal(Signal.NEWNYM)

    chrome_options = webdriver.ChromeOptions()
    chrome_options.add_argument('--proxy-server=%s' % prox) #sets conncection to your 9150 port aka Tor Network

    #chrome_options.add_argument('--headless') #opens headless browser
    driver = webdriver.Chrome('*path to your driver file*', chrome_options=chrome_options)
    driver.get(link)
    #perform selenium stuff

You will need to install the stem library which is basically Tor API for Python. You also will have to edit the torrc file. Here you can read how to do all that.
Comment: Thanks! I can start a instance of chrome but I don't know why that instance hasn't Internet, but obviously there is Internet in my computer. What's happened?
Comment: I found the error, you write 9150 like the port but is 9050. But no problem, thanks for the code


Tomcat in Eclipse: It runs but time out during startup anyway, maybe

Question: I have the same problem as Tomcat in Eclipse: It runs but time out during startup anyway, as long as I start running an application associated with my Tomcat 5.5 server before the server it started.
But if I run the server by itself from within Eclipse, Eclipse recognizes the startup and doesn't time out. I can then run my associated application from within Eclipse as well, and it starts up normally on the already-started server.
It's a minor inconvenience, but does anyone know what would cause the server startup to be unrecognized when I start it via choosing to run the application, but recognized when I start the server alone?
Answer: Some updates of Java cause problems with Eclipse's networking operation. Specifically, Eclipse tries to use IPv6 instead of IPv4 and sometimes fails. When Eclipse starts up Tomcat, one of the final steps that it does is tests the a debug call to Tomcat. This is likely to be the part that is hanging. Fortunately, the fix is very easy. We simply tell Eclipse to use IPv4 instead.
To do this, edit the eclipse.ini file (found in the Eclipse directory) and add the following  to the end of the file on its own line:
<code>-Djava.net.preferIPv4Stack=true
</code>
Restart Eclipse and you should be good to go.


How to use auto_link inside of a controller

Question: In my controller I need to build a JSON object. How can I use auto_link() inside my controller? Right now it errors:
NoMethodError (undefined method `mail_to' for #<ConversationsController:0x144c3f880>):
  app/helpers/application_helper.rb:48:in `html_format'
  app/controllers/conversations_controller.rb:326:in `comments'
  app/controllers/conversations_controller.rb:322:in `comments'

Thank you for any ideas
Answer: auto_link is an helper and you can only reference if from a view. And there's a reason for that: representing information is a view responsibility.
In your case, either create a JSON template or, if you really really really need to use the helper in the controller, include the ActionView::Helpers::TextHelper module in your controller.
class ConversationController < ApplicationController
  include ActionView::Helpers::TextHelper
  include ActionView::Helpers::UrlHelper
end

You might also need to include al dependencies, such as the module that contains mail_to helpers.
Comment: Thank you! (literally working on this one all day. I tried your suggestion but that still breaks, error "ActionView::Template::Error (undefined local variable or method `controller' for #):"
Comment: How do I include all the mail_to helpers? Also, how do I create a JSON template, that sounds very smart, but I haven't seen any example on that. Right now I build an array in the controller (using helpers) and then render :json => @comments
Comment: You can create a JSON template handler, like Rails does with Builder for XML.
Answer: Currently, the auto_link function is removed from rails 3.1 you can use the rails_autolink gem instead.
https://github.com/tenderlove/rails_autolink


What was the PS1's Parallel I/O port used for?

Question: I remember that the first set of PS1 models had a Parallel I/O port that was removed in later models.
For what is the port used for? I'm talking about the one on the left when viewed from the back, not the smaller one used for multiplayer games:
Answer: I could not find any product planned or yet alone sold by Sony which uses that port. But there were 3rd party products which used it, for example cheat cartridges like GameShark:

These cartridges allowed to manipulate the game memory at runtime and thus allowed various forms of cheating. So apparently this port allowed to directly read and write the memory of the console.
Unfortunately (for Sony), there were also some cartridges which allowed to circumvent region lock and other DRM features. Which was against Sony's business interests. Apparently they could not prevent that without also breaking the intended functionality of that port. And it didn't look like they even had any serious plans for a product which used the functionality as intended. So they removed that port from later editions of the console.


Why do some divisibility rules work only in base 10?

Question: Aside from the zero rule (a number ending with zero means it is divisible by the base number and its factors), why is it that other rules cannot apply in different bases?
In particular for 3 one can just sum all digits and see if it is divisible. What relation exists between 10 and 3 to have this property? Does this  property exist in another base?
Also:
Are there divisibility rules for base 2?
Are there general divisibility formulae for all bases?
Comment: Because 10=3^2+1.  If 10 = n+1 then the division rule work for n.  So in base eight division rule works for 7.  $21_{10}=25_8$ AND 2+5= 7 so divisible by 7.  $24_{10}=17_{17} $ and 1+7=8 so divisible by 4= root (16)
Comment: See http://math.stackexchange.com/questions/328562/divisibility-criteria-for-7-11-13-17-19
Comment: In base two.  If ends with 0 is divisible by 2.
Comment: In base 2.  If the even digits add up to a multiple of 3 more or less than the sum of the odd digits than the number is divisible by 3.
Comment: These tricks are used with base 256, 65536 etc when calculating checksums to avoid certain expensive operations. Handy stuff.
Comment: In base 2 halving equals to shifting all bits to the right and doubling equals to shifting all bits to the left - this is used to implement fast division on some microcontrollers that don't have hardware divide instructions.
Comment: See [Why is 9 special in testing divisiblity by 9 by summing decimal digits? (casting out nines)](https://math.stackexchange.com/q/16011/242)
Answer: Two rules that work for any base $b$.
If $n$ divides $b-1$, then if the sum of the digits is a multiple of $n$ then the number is a multiple of $n$.  (That's why the $3$ and $9$ rule work).
If the sum of the even place digits is a multiple of $b+1$ more or less than the sum of the odd place digits then the number is a multiple of $b+1$.
Proof outline:
Let $x = \sum c_i*b^i$ be a number is base $b$.  Then the sum of the digits is $N=\sum c^i$.  So $x - N = \sum c_i*(b^i - 1)$.
Each $b^i - 1 = (b-1)(b^{i-1}+b^{i-2} + .... + b + 1)$ so $x - N$ is a multiple of $b - 1$.  So if $x$ is multiple of $b-1$ the sum of the digits is also a multiple of $b-1$.
Same thing if $x$ is a multiple of $n\mid b-1$.
Answer: There are other rules for other bases.
To understand why the rule for $3$ works in base $10$, you need to write your number $x=d_n\times 10^n+\dots+d_1\times 10^1+d_0$ where the $d_i$ are the digits of $x$ in base $10$.
You can notice that $10=3\times 3+1$, $10^2=3\times 33+1$, $10^n=3...3\times 3+1$ (where $3...3$ has $n-1$ digits equal to $3$).
So $$\begin{align}x &=d_n\times (3...3\times 3+1)+\dots+d_1\times (3\times 3+1)+d_0 \\ &= (d_n\times 3...3 + \dots+d_1\times 3)\times 3 +d_n+\dots+d_1+d_0\end{align}$$
As you can see, the first term is divisible by $3$, so $x$ is divisible by $3$ if and only if $d_n+\dots+d_1+d_0$ is divisible by $3$.
So the reason that this rule works is the fact that the rest of the division of a power of $10$ by $3$ is $1$.
In base $5$, the same rule applies with $2$ (because the powers of $5$ are odd). For example, in base $5$, $12$ is not divisible by $2$ ($1+2=3$ is not divisible by $2$) but $13$ and $431$ are.
To find rules like this by yourself for a base $b$ and a divisor $d$, you need to study how the powers of $b$ behave when divided by $d$.
Answer: The reason why you can simply sum the digits of a number to test for divisibility by 3 is because for all integers $n \ge 0$:
$$10^n \equiv 1 \pmod 3$$
To see why this is true, we know that $10^1 \equiv 1 \pmod 3$
Thus:
$$
10^n = 10*10*10 \cdots\\
\hspace{2.1cm} \equiv 1*1*1\cdots \pmod 3\\
\hspace{0.1cm} \equiv 1 \pmod 3\\
$$
From this we can see that for an integer $a_{n} a_{n-1} ...a_1$ in base 10 ,  $3 \mid a_{n} a_{n-1} ...a_1$ if and only if:
$$
\sum_{i=1}^{n} a_i \equiv 0 \pmod 3
$$
We can generalise this for any base, if $n$ is a digit in base $b$ such that:
$$
10_b \equiv 1 \pmod n
$$
Then for all integers $k \ge 0$:
$$
10_b^k \equiv 1 \pmod n
$$
There are divisibility rules for base 2.
For example, a binary number $a_{n} a_{n-1} ...a_1$ where $a_i$ is either $1$ or $0$, then $a_{n} a_{n-1} ...a_1$ is divisible by 3 if and only if:
$$
\sum_{i=1}^{\lfloor n/2 \rfloor} a_{2i} - \sum_{j=0}^{\lfloor n/2 \rfloor} a_{2j+1} \equiv 0 \pmod 3
$$
This means that $a_{n} a_{n-1} \cdots a_1$ is divisible by 3 if and only if the difference of the sum of the digits in the even positions and the sum of the digits in the odd positions is divisible by 3.
This applies in general as such for any base $b$ and a number $a_{n} a_{n-1} ...a_1$ in base $b$:
$$
(b+1) \mid a_{n-1} a_{n-2} ...a_1
$$
if and only if:
$$
\sum_{i=1}^{\lfloor n/2 \rfloor} a_{2i} - \sum_{j=0}^{\lfloor n/2 \rfloor} a_{2j+1} \equiv 0 \pmod {b+1}
$$
To see why this is also true, we know that:
$$
b \equiv -1 \pmod {b+1}
$$
Thus:
$$
b^2 \equiv 1 \pmod {b+1}
$$
Thus for all integers $i \ge 0$:
$$
b^{2i+1} \equiv -1 \pmod {b+1} \space and \space \space b^{2i} \equiv 1 \pmod {b+1}
$$
From this, $a_{n} a_{n-1} ...a_1$ is divisible by $b+1$ in base $b$ if an only if:
$$
a_1 + a_2 - a_3 + a_4 - \cdots + (-1)^{n-1}*a_n \equiv 0 \pmod {b+1}
$$
which is equalvalent to:
$$
\sum_{i=1}^{\lfloor n/2 \rfloor} a_{2i} - \sum_{j=0}^{\lfloor n/2 \rfloor} a_{2j+1} \equiv 0 \pmod {b+1}
$$
There might be 1 or 2 errors here (my first time using latex), feel free to point out.
Answer: There are general rules for all bases.
One such rule that I've stumbled across is described on everything2.

For any integer base B greater than 2, the multiples of the number B-1, when represented in base B will always have the sum of the digits be a multiple of B-1. If B-1 is a square number (4,9,16,...) then the square root of B-1 will also have this property.
Answer: The $3$ divisible rule works because of the fact that $9,99,999,\cdots$ are all divisible by $3$.
For example, $471$ is divisible by $3$ because $4+7+1 =12$ divisible.
Think of this: Any number divisible by $3$ is still divisible if you subtract any multiple of $3$ by the number itself.
$471 = 4\times100+7\times10+1$
Try subtracting it by $99\times4+9\times7$ you will be left with $4\times(100-99)+7\times(10-9)+1$, which is just the sum of the digits. You can thus see why the rule above works.
Comment: True.... but why won't it work in other bases? Which was the question.
Answer: Lots of answers touch on the exact reason these rules don't (or occasionally, do) work in other bases. Let me try it from a slightly different tack though, which I think might be more generally helpful.
Basically: there is no reason they ought to hold in other bases. The reason is that you're talking about a connection between two different things.
The first is the properties of an actual number. Consider 10 - the number of fingers you (probably) have. I denoted it with the digits 10, but I could have written ten, or 12 (in base 8) or A (in base 16) or whatever; the number isn't changing only our word for it. The property "x is divisible by three" doesn't depend on what base we're expressing x in; it's either true or false for the actual number we put in for x.
On the other hand, the property "the least significant digit of x is zero" absolutely depends on the base we express x in. If x is the number of fingers I have, then we still don't know if the property above is true - it depends on the base. In base 10, it's true; in base 8, it's false. And so on.
Here's the point, then. Divisibility is invariant of base; that is, it doesn't matter how you represent the number, it's either divisible by three (or five or nine or whatever) or it isn't. On the other hand, digits are not invariant of base; if you change the base, whatever your digit properties are will change, too.
So you shouldn't expect the divisibility rules to hold. Now occasionally they do, but that's the surprising case, not the norm.
A huge part of math is training your intuition - not just knowing what is and isn't true, but having enough sense of what's going on to know when to be surprised! And curiosity is the way you learn it - by asking this question, you're well on your way!
Answer: Numbers are conceptually independent of their digits (as shown by the difference in bases but congruence if applied to counting sticks). The purpose of divisibility tricks is meant only to apply to the numbers of base 10, effectively ignoring the true value of the number and focusing plainly on the external digits itself. Sort of like when dividing by 3, 12 fits perfectly base 10, but in base 3 [5] does not.
Answer: Specifically for divisibility of 3, any base that's 10 ± 3n would function the same way -

The rules in base-10 decimal are simply -

Throw away all 0s, 3s, 6s, and 9s
Count the number of digits left
Count the number of digits that are 2s, 5s, or 8s

Combine the tallies from items 2 and 3 then perform modulo-% 3.

Let's try extending down to base-4 :

Throw away all 0s and 3s
Count the number of digits left
Count the number of digits that are 2s

Combine the tallies from items 2 and 3 then perform modulo-% 3.

… and extending upwards to base-16-hexadecimal :

Throw away all digits that are 0/3/6/9/C/F
Count the number of digits left
Count the number of digits that are 2/5/8/B/E

Combine the tallies from items 2 and 3 then perform modulo-% 3.

Luckily, for computers, base-256 (i.e. byte-level) has same congruence (MOD 3) as base-10, and by extension, unsigned ints of 16-bit, 32-bit, 64-bit etc all share the same congruence.
Signed ints, on the other hand, shares the same congruence as base-2 binary strings and base-8 octal codes.

At the risk of stating the obvious, for bases that are congruent to 0 (MOD 3) - e.g. base-42, base-168, base-864 etc, simply take the coefficient corresponding to base-to-zero-th power (i.e. the left overs less than the base itself), then modulo-% 3


Ember.js only binds the property called 'name' in my model in a HandleBars template

Question: This is my model file with fixtures:
App.Game = DS.Model.extend({
    name: DS.attr('string'),
    isCompleted: DS.attr('boolean')
});

App.Game.FIXTURES = [
{
    id: 1,
    name: '-TEMPIN-',
    description: 'Test',
    websiteUrl: 'http://www.kefsensei.com'
},
{
    id: 2,
    name: '¡Oh My GlobZ Mucho Party!',
    description: 'Test',
    websiteUrl: 'http://www.youtube.com/watch?v=hCBc2mWXeu4&'
},
{
    id: 3,
    name: '90s Arcade Racer',
    description: 'Test',
    websiteUrl: 'http://www.kefsensei.com'
}
];

This is my index.html:
<!DOCTYPE html>

    <meta charset="utf-8">
    <title></title>
    <link href='http://fonts.googleapis.com/css?family=Lato:400,700' rel='stylesheet' type='text/css'>
    <link href='http://fonts.googleapis.com/css?family=PT+Sans:400,700' rel='stylesheet' type='text/css'>
    <link href="/sass/main.css" media="screen" rel="stylesheet" type="text/css" />

This is my router:
    App.Router.map(function () {
        this.resource('games', { path: '/' });
    });
App.GamesRoute = Ember.Route.extend({
        model: function() {
        return this.store.find('game');
    }
});

No matter what I do the only property of my model that is bound and displayed when I navigate to the root of my application is the 'name' property.
If I change the name of my 'name' property, it no longer binds. The description property does not bind.
What am I doing wrong?
Answer: you need to define the properties on the model
App.Game = DS.Model.extend({
    name: DS.attr('string'),
    description: DS.attr('string'),
    websiteUrl: DS.attr('string'),
    isCompleted: DS.attr('boolean')
});

http://emberjs.jsbin.com/OxIDiVU/101/edit


Strange behaviour of passing out refernce in binding of lambda function

Question: I want to pass out some parameter from the lambda function, so I bind a reference parameter to a lambda function. However, the outer variable is not changed after calling the function. If I bind the lambda function with the pointer of outer variable, the result is correct.
I show the test program as follows and want to know why the outer variable does not change, given that I have already defined the pass-by-reference lambda function [&]?
#include <iostream>
#include <vector>
#include <algorithm>
#include <functional>

using namespace std;

int main(int argc, char* argv[])
{
    string acc_ref, acc_ptr;
    //  define function via reference
    auto fProcRefEx = [&](string& acc, const string& s) -> void
    {
        acc += s;
    };
    auto fProcRef = bind(fProcRefEx, acc_ref, placeholders::_1);
    //  define function via pointer
    auto fProcPtrEx = [&](string* pacc, const string& s) -> void
    {
        (*pacc) += s;
    };
    auto fProcPtr = bind(fProcPtrEx, &acc_ptr, placeholders::_1);
    //  test
    vector<string> v = {"abc", "def"};
    for_each(v.begin(), v.end(), fProcRef);
    cout << "acc_ref: " << acc_ref << endl;  //  acc_ref is empty, wrong
    for_each(v.begin(), v.end(), fProcPtr);
    cout << "acc_ptr: " << acc_ptr << endl;  //  acc_ptr is "abcdef", correct
    return 0;
}

Comment: As an aside, `for( auto&& str:v ) { fProcRef(str); }` is as efficient as, and often more clear than, `std::foreach(v.begin(),v.end(),fProcRef);` now.
Answer: I think std::bind will decay the reference to just a plain value type when it stores acc_ref.  ie In the unspecified object instance returned from bind, it will have a member string acc_ref, not string& acc_ref.  You have to use std::ref to make it really store a reference:
auto fProcRef = bind(fProcRefEx, ref(acc_ref), placeholders::_1);


R Cumulative sum based on two variables

Question: This is whay my data.table looks like. The last column NewShares is my desired columns.
library(data.table)
dt <- fread('
   Client   Level   NumShares   Interest  NewShares
    A          0     10          0         10
    A          0     0           0         10
    A          1     0          .1         11
    A          0     9           0         20
    A          1     0          .2         24')

I want the cumulative NumShares while taking into account NewShares bought with interest. So as of the 1st row, the cumulative shares are 10. As of the 3rd row, Level==1, so I have to add interest. It will be 10+(10*.1)=11. As of the 4th row, the cumulative shares is 11+9 =20. As of the last row, Level==1, so new shares are 20+(20*.2) = 24
I tried:
dt[,NewShares:= NumShares* cumprod(1+ NumShares*Interest),by=Client]

Comment: Perhaps `dt[, NewSharesN := ceiling(cumsum(cumsum(NumShares)*Interest + NumShares)) , Client]`
Answer: We can do double cumsum and wrap it with ceiling
dt[, NewSharesN := ceiling(cumsum(cumsum(NumShares)*Interest + NumShares)) , by = Client]
dt
#   Client Level NumShares Interest NewShares NewSharesN
#1:      A     0        10      0.0        10         10
#2:      A     0         0      0.0        10         10
#3:      A     1         0      0.1        11         11
#4:      A     0         9      0.0        20         20
#5:      A     1         0      0.2        24         24

R Cumulative sum based on two variables


How to loop a function for a certain duration in JS

Question: I have read on w3schools:

The setInterval() method will wait a specified number of milliseconds, and then execute a specified function, and it will continue to execute the function, once at every given time-interval.
The setTimeout() method will wait the specified number of milliseconds, and then execute the specified function.

I tried them both. However, that is not what I need.
I want a function that will loop continuously until the time duration is reached.
Is there a workaround on this? Thanks!
Answer: var start = new Date();
var timer_id = setInterval(function() {
  // the duration is 10 seconds
  if (new Date() - start > 10000) {
     clearInterval(timer_id);
  } else {
     your_function();
  }
}, 1000); // every 1 second your function will run, you could change it by your needs.

Answer: You can do this without any setTimeouts or setIntervals:
var t1 = new Date().getTime();
var interval = 100;
while(new Date().getTime() - t1 < interval){
    // do stuff;
}

This will loop continuously for 100 ms.
Comment: Since there's no sleep function, this loop will take all your CPU. Also, other timeouts won't fire in some JavaScript engines, because they're single threaded and require the outer function to return before firing timeouts and intervals. See the solution by `xdazz`
Comment: so the answer of xDazz is better?
Comment: Well the OP stated that he wanted the function to "loop continuously", so I deliberately suggested a solution when virtually nothing else would be executed whilst this function is looping.


array behavior in python

Question: I am new in python and trying to learn machine learning. Unable to understand a line in code
d[df['Class label'].values == i, 0]

where d is a 2D array like [[1,2],[2,3],...] and df['Class label'] is a 1D array like [0,1,0,0,...]. I googled it as I get something that it is using zip function to get the x and y values from 2D array for scatter plot. But, not clear how its working.
This is taken from link(In[13]). Also, I am pasting the patch of code below:
fig, ax = plt.subplots(3, figsize=(6,14))

for a,d,l in zip(range(len(ax)),
               (df[['Alcohol', 'Malic acid']].values, df_std, df_minmax),
               ('Input scale',
                'Standardized [$N  (\mu=0, \; \sigma=1)$]',
                'min-max scaled [min=0, max=1]')
                ):
    for i,c in zip(range(1,4), ('red', 'blue', 'green')):
        ax[a].scatter(d[df['Class label'].values == i, 0],
                  d[df['Class label'].values == i, 1],
                  alpha=0.5,
                  color=c,
                  label='Class %s' %i
                  )
    ax[a].set_title(l)
    ax[a].set_xlabel('Alcohol')
    ax[a].set_ylabel('Malic Acid')
    ax[a].legend(loc='upper left')
    ax[a].grid()

Comment: Check pandas docs for the values stuff (Series vs. DataFrame) and numpy's tutorial on indexing. You are using 2 pretty complex data-structures here (pandas Series/DataFrame, numpy arrays) and should start with the basics.
Answer: i'm only going to address this part:
for i,c in zip(range(1,4), ('red', 'blue', 'green')):
    ax[a].scatter(d[df['Class label'].values == i, 0],
              d[df['Class label'].values == i, 1],
              alpha=0.5,
              color=c,
              label='Class %s' %i
              )

lets start at the for:
for i,c in zip(range(1,4), ('red', 'blue', 'green'))

is looping through the result of the zip.
the zip is returning the following:
[(1, red), (2,blue), (3, green)]

which is later unpacked into the variables 'i' and 'c'. So the first iteration you have
i = 1
c = red

I don't know what the rest is doing, but the part that you addressed ("d[df['Class label'].values == i, 1]") would be interpreted like this:
df['Class label']

(i'm assuming dictionary) df at the index named 'Class label'.  Now, apparently it is an object with an attribute called values, which we are giving two values in a tuple.
df['Class label'].values == i, 1

and using the return of that assignment as a key for a dictionary-like call to the object d,
d[df['Class label'].values == i, 1]

needless to say, this is terrible Python code. the variables are terribly named and you have to guess too much of what's going on. If you can, rename the variables for something that makes sense if you read it out loud. like
for index, color in enumerate(colors):
    delta_in_color = d[df['Class label'].values == i, 1]   # whatever this means
    ax[a].scatter(requirement_a=foo, requirement_b=delta_in_color, alpha=0.5, color=color, label=class_index)

Comment: @Artyro : Thanks for looking into my issue. Here df is pandas dataframe. pandas read a input file and its one of column is named as "Class label". So, it tries to get the values from column named "Class label". All the elements of this column can take three possible values 1, 2 and 3.

Eric Ed Lohmar: gave answer but trying to understand.
Answer: What's happening here is df['Class Label'].values == i is converting the values from the 'Class Label' column in a pandas.DataFrame, df, as a 1d array. It is then comparing each of those values to i and returning another 1d array which represents the locations in which the comparison comes up True.
# let's say df['Class Label'].values = [1 0 1 2 2 1 3] and i = 1
bool_array = df['Class Label'].values == 1

print(bool_array)
[True False True False False True False]

Next, it takes the resulting boolean array and selects all of the rows in d where the values are True. Except, since the second parameter inside the brackets is 0, it's selecting only the values in the first column from that subset.
Let's say
d =  [[2  1],
      [3  4],
      [4  2],
      [1  9],
      [7  8],
      [5  3],
      [2  0]]

then d[bool_array, 0] returns [2 4 5] because those are the values in the first column, that match up with the Trues in bool_array.

array behavior in python


How to know if the input value equals something

Question: So for school i'm making a login system for a website (without a database), so I have a input field like this:
<input type="text" name="user" id="gebruikersnaam" placeholder="Username">

And a button to login like this:
 <input type="submit" name="login" id="loginknop2" class="signIn loginhide signin-submit" value="Login">

now when the username the user has put in equals "timo" and the button is clicked, so I have this code:
var gebruikersnaam = $("#gebruikersnaam").val();

jQuery(document).ready(function(){
  $("#loginknop2").click(function(){
      if(gebruikersnaam == "timo"){
        console.log("Ja! het werkt.");
      }
      else{
        console.log("Nee! het werkt niet.");
      }
  });
});

but I can't get it to work, and I have no idea why.
Answer: You have to read input value inside click handler, see below code
jQuery(document).ready(function(){
  $("#loginknop2").click(function(){
      var gebruikersnaam = $("#gebruikersnaam").val();
      if(gebruikersnaam == "timo"){
        console.log("Ja! het werkt.");
      }
      else{
        console.log("Nee! het werkt niet.");
      }
  });
});

Answer: move
var gebruikersnaam = $("#gebruikersnaam").val();

inside the callback.
jQuery(document).ready(function(){
  $("#loginknop2").click(function(){

      var gebruikersnaam = $("#gebruikersnaam").val(); // <-- here

      if(gebruikersnaam == "timo"){
        console.log("Ja! het werkt.");
      }
      else{
        console.log("Nee! het werkt niet.");
      }
  });
});

because you should read the input value after the click
Answer: Take the value of textbox in click handler otherwise you might have empty string in it when event is triggered. You are not event getting the value of textbox in document.ready which may cause selected to get failed in getting the object with id gebruikersnaam
 $("#loginknop2").click(function(){
      var gebruikersnaam = $("#gebruikersnaam").val();
      if(gebruikersnaam == "timo"){
        console.log("Ja! het werkt.");
      }
      else{
        console.log("Nee! het werkt niet.");
      }
  });


ruby-on-rails iterating through object attributes in view template aka .erb file

Question: I'm using ruby on rails.
wondering if this is achievable.
Original Code
<%= form_for(:page, :url=>{:action => 'create'}) do |f| %>

 Name
 <%= f.text_field(:name) %>

 Position
 <%= f.text_field(:position) %>

<%end%>

desired code something along the lines of creating forms
by iterating through the object attributes.
  <% for attribute in @subject.attributes.keys %>

  <%= attribute.humanize %>
  <%= @subject.attributes[attribute].to_s %>

  <% end %>

so I am not sure if this is possible.
Comment: It looks entirely possible --- you can get the keys of any hash, and iterate over them, just like you're doing. Instead of a for-loop, in ruby you'll want to call .each to loop over an enumeration.
Answer: I believe what you are looking for is a .each loop:
<% @subject.attributes.each do |attribute| %>
<%= attribute.humanize %>
<% end %>

That will loop through each attribute of the @subject. If you also want to loop through the keys of each attribute, you need to add another nested loop:
<% @subject.attributes.each do |attribute| %>
  <% attribute.keys.each do |key| %>
    <%= attribute.humanize %> or <%= key %>
  <% end %>
<% end %>

Hope that helps.


I want to generate job serial no in client side click. please help if there is any suggest

Question: Here I want to create JOBNO for my application for each order. Every order has different customer, quote no, address…etc.
JOBNO=       MUM    XXXX    01    1415

First 3digit = coming from port code data table (I already created table field).
Next 4digit = serial no (ex:0001);which is auto generated one by one .
Next 2digit assumed   as current month .Every month start the serial no. has to begin with origin no(0001) and again ends in end of the month.
Next 2digit=current month
Last 4digits=financial year (ex2014:2015) last two digits (1415).
Condition:
    When I choose the port name from dropdown list like before code is auto generated and place it to the JOBNO textbox.
Comment: did you try anything ? can you put your effort here ?
Answer: you can move ahead something like this and ask where struck,
   Declare @JOBNO varchar(20)
--       MUM    XXXX    01    1415
Declare @portcode char(3)='MUM' --from db
Declare @CurMonth char(2)= subSTRING(CONVERT(nvarchar(6),getdate(), 112),5,2)
Declare @maxid int=1 -- from db (it should be int only
--select @CurMonth
Declare @FinYear char(4)= substring(cast((year(getdate())-1) as varchar(4)),3,2)
                            +substring(cast(year(getdate()) as varchar(4)),3,2)
--select @FinYear
--Select RIGHT('000' + CAST(@maxid AS VARCHAR(4)), 4)
--finally,
Select @portcode+ @CurMonth+ RIGHT('000' + CAST(@maxid AS VARCHAR(4)), 4)+@FinYear