text:
Q: Implementing efficient 512 bit integer type I was asked to create 512 bit integer type to my RSA encryption algorithm. I started from the simplest bitwise operations OR, AND, XOR, NOT, afterwards using mentioned operations I implemented addition, subtraction etc.
Unfortunately after many tests, it's very slow on more than 128 bits.
I was surprised when I found site with RSA generation where it generated key using apparently javascript in several miliseconds. How I can improve my algorithm to get better efficiency ? Or better question would be: how proffesionals implement so big types with
such performance.
Here is my code:
    public class BigInt {

      public static final int    BYTE = 8;
      public static final int    DEFAULT_SIZE = 128;
      public final static BigInt ZERO = new BigInt(0);
      public final static BigInt ONE = new BigInt(1);
      public final static BigInt TEN = new BigInt(10);
      private boolean[] number;
      private Endianness endianness = Endianness.BIG_ENDIAN;

    public BigInt() {
        number = new boolean[DEFAULT_SIZE];
    }

    public BigInt(boolean[] number) {
        this.number = number;
    }

    public BigInt(int integerNumber) {
        this();
        boolean isNegative = false;
        if (integerNumber < 0) {
            isNegative = true;
            integerNumber = Math.abs(integerNumber);
        }
        for (int i = number.length - 1; i >= 1 && integerNumber >= 1; i--) {
            number[i] = integerNumber % 2 == 1;
            integerNumber >>= 1;
        }
        if (isNegative) {
            number = new BigInt(number).not().add(ONE).number;
        }
    }

    public BigInt(String binaryString) throws InvalidBinaryStringException {
        this();
        for (int i = binaryString.length() - 1, j = number.length - 1;
             i >= 0 && j >= 0; i--, j--) {
            if (binaryString.charAt(i) != '1' && binaryString.charAt(i) != '0') {
                throw new InvalidBinaryStringException(binaryString);
            }
            number[j] = (binaryString.charAt(i) - '0') == 1;
        }
    }

    public BigInt(BigInt copy) {
        this();
        System.arraycopy(copy.number, 0, number, 0, copy.number.length);
    }

    public BigInt add(BigInt component) {
        BigInt a, b;
        BigInt x = new BigInt(this);
        BigInt y = new BigInt(component);
        do {
            a = x.and(y);
            b = x.xor(y);
            x = a.shiftLeft(1);
            y = b;
        } while (!a.equals(ZERO));
        return b;
    }

    public BigInt sub(BigInt subtrahend) {
        return add(subtrahend.not().add(new BigInt(ONE)));
    }

    public BigInt mul(BigInt multiplier) {
        BigInt m = new BigInt(ONE), z = new BigInt(ZERO);
        BigInt x = new BigInt(this), y = new BigInt(multiplier);

        if (x.lessThen(ZERO)) {
            x = x.not().add(ONE);
            y = y.not().add(ONE);
        }

        while (x.greaterThenEqual(m) && !y.equals(ZERO)) {
            if (!x.and(m).equals(ZERO)) {
                z = y.add(z);
            }
            y = y.shiftLeft(1);
            m = m.shiftLeft(1);
        }
        return z;
    }

    public BigInt div(BigInt divisor) {
        BigInt mask = new BigInt(ONE);
        BigInt quotient = new BigInt(ZERO);

        BigInt numerator = new BigInt(this), denominator = new BigInt(divisor);

        if (numerator.lessThen(ZERO)) {
            numerator = numerator.not().add(ONE);
        }

        if (denominator.lessThen(ZERO)) {
            denominator = denominator.not().add(ONE);
        }

        while (denominator.lessThenEqual(numerator)) { // PROBLEM
            denominator = denominator.shiftLeft(1);
            mask = mask.shiftLeft(1);
        }

        while (mask.greaterThen(ONE)) {
            denominator = denominator.shiftRight(1);
            mask = mask.shiftRight(1);
            if (numerator.greaterThenEqual(denominator)) {
                numerator = numerator.sub(denominator);
                quotient = quotient.or(mask);
            }
        }

        if (number[0] != divisor.number[0]) {
            return quotient.not().add(ONE);
        }
        return quotient;
    }

    public BigInt mod(BigInt y) {
        // (x - y*(x/y))
        BigInt x = new BigInt(this);
        BigInt right = x.div(y);
        BigInt mid = y.mul(right);
        return x.sub(mid);
    }

    //completly inefficient for numbers larger than 32 bit
    @Deprecated
    public BigInt div2(BigInt divisor) {
        BigInt c = new BigInt(ZERO), sign = new BigInt(ZERO);
        BigInt x = new BigInt(this), y = new BigInt(divisor);
        if (x.lessThen(ZERO)) {
            x = x.not().add(ONE);
            sign = sign.xor(ONE);
        }

        if (y.lessThen(ZERO)) {
            y = y.not().add(ONE);
            sign = sign.xor(ONE);
        }

        if (!y.equals(ZERO)) {
            while (x.greaterThenEqual(y)) {
                x = x.sub(y);
                c = c.add(ONE);
            }
        }

        if (!sign.equals(ZERO)) {
            c = c.not().add(ONE);
        }
        return c;
    }

    //doesn't work for big numbers close to maximum bit
    @Deprecated
    public BigInt mod2(BigInt mod) {
        BigInt y = new BigInt(this);
        BigInt x = new BigInt(mod);

        BigInt p = new BigInt(x);

        if (y.lessThen(ZERO)) {
            y = y.not().add(ONE);
        }

        if (p.lessThen(ZERO)) {
            p = p.not().add(ONE);
            x = x.not().add(ONE);
        }

        while (p.lessThen(y)) {         //forever loop
            p = p.shiftLeft(1);
        }

        while (p.greaterThenEqual(x)) {
            if (y.greaterThenEqual(p)) {
                y = y.sub(p);
            }
            p = p.shiftRight(1);
        }

        if (number[0]) {
            y = y.not().add(ONE);
        }
        return y;
    }

    @Override
    public boolean equals(Object obj) {
        if (obj == null)
            return false;
        if (obj == this)
            return true;
        if (!(obj instanceof BigInt))
            return false;

        BigInt bigInt = (BigInt) obj;
        for (int i = 0; i < bigInt.number.length; i++) {
            if (number[i] != bigInt.number[i]) {
                return false;
            }
        }
        if (!endianness.equals(bigInt.endianness)) {
            return false;
        }
        return true;
    }

    public boolean lessThen(BigInt num) {
        if (equals(num)) {
            return false;
        }
        if (number[0] && !num.number[0]) {
            return true;
        } else if (!number[0] && num.number[0]) {
            return false;
        }
        BigInt left = null, right = null;
        if (number[0]) {
            left = not().add(ONE);
            right = num.not().add(ONE);
        } else {
            left = this;
            right = num;
        }
        for (int i = 1; i < number.length; i++) {
            if (left.number[i] != right.number[i]) {
                if (number[0]) {
                    return !(!left.number[i] && right.number[i]);
                } else {
                    return !left.number[i] && right.number[i];
                }
            }
        }
        return false;
    }

    public boolean lessThenEqual(BigInt num) {
        if (equals(num)) {
            return true;
        }
        return lessThen(num);
    }

    public boolean greaterThen(BigInt num) {
        return !lessThen(num);
    }

    public boolean greaterThenEqual(BigInt num) {
        if (equals(num)) {
            return true;
        }
        return greaterThen(num);
    }

    /**
     * BITWISE OPERATORS*
     */
    //logical bitwise shift lefts
    public BigInt shiftLeft(int n) {
        //IT WORKS BECAUSE NEW OBJECT IS SET TO 0;
        BigInt shifted = new BigInt();
        for (int i = 0; i < number.length - n; i++) {
            shifted.number[i] = number[i + n];
        }
        return shifted;
    }

    //logical bitwise shift right
    public BigInt shiftRight(int n) {
        BigInt shifted = new BigInt();
        for (int i = number.length - 1; i >= n; i--) {
            shifted.number[i] = number[i - n];
        }
        boolean sign = number[0];

        for (int i = 0; i < n; i++) {
            shifted.number[i] = sign;
        }
        return shifted;
    }

    //bitwise or |
    public BigInt or(BigInt num) {
        BigInt newInt = new BigInt();
        for (int i = 0; i < number.length; i++) {
            newInt.number[i] = number[i] | num.number[i];
        }
        return newInt;
    }

    //bitwise and &
    public BigInt and(BigInt num) {
        BigInt newInt = new BigInt();
        for (int i = 0; i < number.length; i++) {
            newInt.number[i] = number[i] & num.number[i];
        }
        return newInt;
    }

    //bitwise exclusive or ^
    public BigInt xor(BigInt num) {
        BigInt newInt = new BigInt();
        for (int i = 0; i < number.length; i++) {
            newInt.number[i] = number[i] ^ num.number[i];
        }
        return newInt;
    }

    public BigInt not() {
        BigInt negate = new BigInt();
        for (int i = 0; i < number.length; i++) {
           negate.number[i] = !number[i];
        }
        return negate;
    }

    @Override
    public String toString() {
      /* StringBuilder binaryRepr = new StringBuilder();
        for (byte b : number) {
            binaryRepr.append(b);
        }*/

       String decRepr = "";
        BigInt copy = new BigInt(this);

        if (copy.lessThen(ZERO)) {
            copy = copy.not().add(ONE);
        }

        while (copy.greaterThenEqual(ONE)) {
            BigInt rem = copy.mod(TEN);
            copy = copy.div(TEN);
            decRepr = String.valueOf(Integer.parseInt(getDecimalRemainder(rem), 2)) + decRepr;
        }

        if (number[0]) {
            return "-" + decRepr;// + binaryRepr.toString();
        }
        return decRepr;// + binaryRepr.toString();
        //return binaryRepr.toString();
    }

    private String getDecimalRemainder(BigInt copy) {
        String decimalString = "";

        for (int i = copy.number.length - 1; i >= copy.number.length - 4; i--) {
            decimalString = (copy.number[i] ? "1" : "0") + decimalString;
        }
        return decimalString;
    }

    public String toBinaryString() {
        StringBuilder binaryString = new StringBuilder();
        boolean isFirstBit = false;
        for (boolean b: number) {
            if (b) {
                isFirstBit = true;
            }
            if (isFirstBit) {
                binaryString.append(b);
            }
        }
        return binaryString.toString();
    }

    public static BigInt nextBigInt(BigInt min, BigInt max) {
        BigInt pseudo = new BigInt();
        Random rnd = new Random();
        for (int i = 2; i < pseudo.number.length; i++) {
            pseudo.number[i] = rnd.nextBoolean();
        }
        return pseudo.mod(max).add(min);
    }

    public static void main(String[] args) {
        String big = "";
        for(int i = 0; i < 126; i++) {
            big += "1";
        }
        StopWatch stopWatch = new StopWatch();
        System.out.println(new BigInt(big));
        System.out.println(stopWatch.elapsedTime());
    }
}

A: Instead of the boolean[] use an int[] to hold the bits of your number. This way you can implement most operations much faster, operating on say 30 bits at once instead of just 1.
You can keep the lowest 30 bits in array element 0 the next 30 bits in array element 1 and so on. It is straight forward to implement the logical operations (&, |, ^) with this structure.
For the arithmetic operations you have to keep track of carry bits. For example after adding the two array elements 0, if the result is larger than 30 bits, clear the overflow bit and add 1 to the sum of the array elements 1.
Multiplication can be done by using long: the product of two int values always fits into a long. Use a method like multiplying two decimal numbers by hand. Just use 30 bit digits instead of the digits 0-9.
More sophisticated multiplication methods like karatsuba don't pay off for numbers that are only 512 bits long.
While it is fun to implement and optimize these operations, it is also very easy to have subtle bugs in the implementation. So if you do that for production code be sure to write lots of unit tests. It may be better to use a well tested third party implementation instead of doing it on your own.


text:
Q: Cubic Diophantine equations We know how to solve Diophantine equations of first degree (linear) and of the second degree. What is available for solving Diophantine equations of the third degree? Let us say that we are given a two-variable polynomial equation P(x,y)=0 with integer coefficients, of third degree in both variables. What known methods or theories are used to solve such a general Diophantine equation of third degree?
Added: I am assuming the polynomial is genuine third degree (i.e. is irreducible) and that all powers of x and y may be present (alas second powers may be always eliminated by appropriate substitutions).

A: I'll assume $P(x,y)$ is irreducible over the rationals.  The first thing you'll want to look at is its genus.  In many cases the genus will be $1$, meaning this is an elliptic curve.  Especially if it is Weierstrass form, there are ways to find the integer solutions (e.g. with Sage). If it isn't in Weierstrass form, you can put it in Weierstrass form with a rational transformation, look at the rational points of that transformed curve, and try to see which correspond to integer solutions of the original.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Need some help calculating averages from a list of integers [Here is what I have so far.]
import statistics

print ("Type '0' at any time to end program.")

my_numbers=[]

while True:

    try:
        x=int(input("Enter a positive integer. "))
        my_numbers.append(x)
        while x<0:
            print ("Enter a POSITIVE integer.")
            x=int(input("Enter a positive integer. "))
    except ValueError:
        print ("Invalid character entered. Enter a positive integer.")
    if x==0:
        print ('Your mean is',statistics.mean(my_numbers))
        print ('Your median is',statistics.median(my_numbers))
        print ('Your range is',max(my_numbers) - min(my_numbers))
        break

Essentially the code needs to ask for positive integers and calculate the mean, median, and range of them after the user inputs "0". The code also needs to not allow the user to input non-positive integers. I have two problems.

*

*The final calculations are including negative integers and zero. I need negative numbers and zero to be excluded from the final calculations. Note: Decimals aren't being included in the final calculations, for some reason.

*Non-integers return the error "NameError: name 'x' is not defined" in line 13.
Any help would be greatly appreciated. Thanks.

A: Thanks for such questions, making Python easier to start with for next visitors of this page.

*

*final calculation includes negative integers and zero because you append it to your list before testing it.my_numbers.append(x) should be after and outside your while test such as :

*NameError is raised for user input such as string or characters when
those string or character are not resolvable to an integer (like a predefined Python variable). You
should catch NameError as well as you did for ValueError.

Hope this helps.

A: *

*Move my_numbers.append(x) down the while loop.

*What you need is to catch the NameError.

A: You should only call my_numbers.append(x) when you get a valid x.

A:
The final calculations are including negative integers and zero. I
  need negative numbers and zero to be excluded from the final
  calculations.

Because you are appending the input before the check while x<0.
Solution: move the appending statement my_numbers.append(x) below while block.

Note: Decimals aren't being included in the final calculations, for
  some reason.

The int(x) converts the decimals/floats to intergers i.e. technically you don't have any decimals.
Solution: use float() instead of int()

Non-integers return the error "NameError: name 'x' is not defined" in
  line 13.

Passing a characeter that cannot be converted (type casted) to interger, using int() raises NameError.
Solution: You need to handle this expception same as you're expecting ValueError.

The final code:
import statistics

print ("Type '0' at any time to end program.")

my_numbers=[]

while True:
    try:
        x=int(input("Enter a positive integer. "))
        while x<0:
            print ("Enter a POSITIVE integer.")
            x=int(input("Enter a positive integer. "))
    my_numbers.append(x)
    except ValueError:
        print ("Invalid character entered. Enter a positive integer.")
    except NameError:
        print ("Invalid character entered. Enter a positive integer.")
    if x==0:
        print ('Your mean is',statistics.mean(my_numbers))
        print ('Your median is',statistics.median(my_numbers))
        print ('Your range is',max(my_numbers) - min(my_numbers))
        break

A: import statistics

print ("Type '0' at any time to end program.")

my_numbers=[]       #list to hold integer input from the user

while True:
    try:
        x = int(input("Enter a positive integer. "))
        while x<0:
            print("Enter a POSITIVE integer.")
            x = int(input("Enter a positive integer: "))

except ValueError:
    print ("Invalid character entered. Enter a positive integer.")

if (x==0):
    print ('Your mean is: ',statistics.mean(my_numbers))
    print ('Your median is: ',statistics.median(my_numbers))
    print ('Your range is: ',max(my_numbers) - min(my_numbers))
    break

# my_numbers.append(x) is moved down the loop
# the value of x will only be appended to my_numbers if it is valid input
my_numbers.append(x)


text:
Q: Writing to firebase returns exception in thread I have been using the Java firebase api and have been having problems writing to it. Originally I was just trying to set a value but I found that I needed a listener to make sure the data is committed before the program ends. I have included my entire main code because I am not sure where the problem lies. The User class is a simple class that holds birth year and full name as defined by the example on the firebase website here: https://www.firebase.com/docs/android/guide/saving-data.html
Firebase rootRef = new Firebase("https://testing-fire.firebaseio.com/");
        Firebase usersRef = rootRef.child("users");

        User alanisawesome = new User("Alan Turing", 1912);
        User gracehop = new User("Grace Hopper", 1906);

        Map<String, User> users = new HashMap<String, User>();
        users.put("alanisawesome", alanisawesome);
        users.put("gracehop", gracehop);

        final CountDownLatch done = new CountDownLatch(1);
        usersRef.setValue(users, new Firebase.CompletionListener() {
            @Override
            public void onComplete(FirebaseError firebaseError, Firebase firebase) {
                System.out.println("done");
                done.countDown();
            }
        });
        try {
            done.await();
        } catch (InterruptedException e) {
            System.out.println(e);
        }

The console returns an exception in thread error that looks like this:
Exception in thread "TubeSockReader-1" java.lang.NoClassDefFoundError: org/apache/http/conn/ssl/StrictHostnameVerifier
    at com.firebase.tubesock.WebSocket.verifyHost(WebSocket.java:335)
    at com.firebase.tubesock.WebSocket.createSocket(WebSocket.java:319)
    at com.firebase.tubesock.WebSocket.run(WebSocket.java:117)

The data is not committed to the firebase

A: You shouldn't have to add anything extra to your Gradle dependencies. Use firebase-client-jvm instead of firebase-client-android.

A: The httpcomponents are probably missing in your classhpath.
Add the following to your maven dependencies :
    <dependency>
        <groupId>org.apache.httpcomponents</groupId>
        <artifactId>httpclient</artifactId>
        <version>4.5</version>
    </dependency>


text:
Q: Calculate average number from char array Im trying to calculate the average out of a couple of number inside an char array. The reason for this is that i imported data from a text document and i made it read only every 2nd line to get the numbers that i wanted.
Now i need to get the average out of these numbers but i cant make it work. I'm starting to get mad about this and i feel that the solution would be rather simple.
EDIT:
The file consists of names and numbers. I.e:
Jason Smith
32
Mary Jane
52
Stevie Wonder
68
Micheal Jackson
59
#include <fstream>
#include <iostream>

using namespace std;

double averageNum(char array[], int size) { // A function to calculate the average number

    int sum = 0;
    double avg;

    for(int i=0; i<size; i++){

        array[i]+= sum;

    }

    avg = sum / size;
    return avg;
}

int main(){

    char age [50][30];
    double avg;
    int rows = 0;

    ifstream elevInfo("elevinfo.txt"); // Opens a stream to get data from the document

    if (! elevInfo){    // Error message if the file couldn't be found

        cout << "Could not find the file elevinfo.txt" << endl;
        return (1);
    }

    while(elevInfo.getline(age[rows/2], 30)){ // Reading every 2nd line to an array

        rows++;

    }

    avg = averageNum(age[], rows); // Function call with the numbers from the array and the variable rows as a pointer
    cout << "Average age equals: " << avg << endl;
}

A: this is one of many possible solutions for your problem:
int main()
{
    // Opens a stream to get data from the document
    ifstream elevInfo("elevinfo.txt");
    // Error message if the file couldn't be found
    if (!elevInfo)
    {
        cout << "Could not find the file elevinfo.txt" << endl;
        return (1);
    }

    int sum = 0;
    int lineCounter = 0;

    // loop till end of file
    while (!elevInfo.eof())
    {
        // prepare buffer
        char line[30];
        // read line into buffer
        elevInfo.getline(line, 30);

        // do this every second line
        if (lineCounter % 2 == 1)
        {
            // get age as int using function atoi()
            int age = atoi(line);
            // increase sum by the current age
            sum += age;
        }
        // increment line-counter
        lineCounter++;
    }

    // calculate the average
    // divide lineCounter by 2 because only every second line in your file contains an age
    double avg = sum / (lineCounter / 2.0);
    cout << "Average age equals: " << avg << endl;

    return 0;
}

As you can see it also doesn't need the function averageNum.


text:
Q: The difference between -pedantic-errors and -Werror=pedantic in gcc What is the difference between using -pedantic-errors and -Werror=pedantic in gcc?
According to the documentation of GCC there is a difference:

-pedantic-errors
Give an error whenever the base standard (see -Wpedantic) requires a diagnostic, in some cases where there is undefined behavior at compile-time and in some other cases that do not
  prevent compilation of programs that are valid according to the
  standard. This is not equivalent to -Werror=pedantic, since there are
  errors enabled by this option and not enabled by the latter and vice
  versa.

What errors are included by -pedantic-errors, but not by -Werror=pedantic?
What errors are included by -Werror=pedantic, but not by -pedantic-errors?
Any example of both types of errors?

A: A little insight as to why the two options exist separately in chapter 14:

Some ISO C testsuites report failure when the compiler does not produce an error
message for a certain program
ISO C requires a "diagnostic" message for certain kinds of invalid programs, but a
warning is defined by GCC to count as a diagnostic. If GCC produces a warning but
not an error, that is correct ISO C support. If testsuites call this "failure", they should
be run with the GCC option '-pedantic-errors', which will turn these warnings into
errors.

So it sounds like there's some ISO C rules that are not explicitly marked as invalid C but instead valid-ish C. These are the rules that -pedantic-errors makes into errors that -Werror=pendantic doesn't. You'll have to look at ISO C standard for more information on that.
As far as what errors are turned on/off as documented by GCC, there is but 1 that has -pendantic-errors explicitly:

-Wno-implicit-function-declaration
(C and Objective-C only)
This option controls warnings when a function is used before being declared. This warning is enabled by default in C99 and later dialects of C, and also by -Wall. The warning is made into an error by -pedantic-errors.

Note: however it seems that not all the authors of the manual have the same idea. In section 2 it talks about -pendantic-errors as if it WAS the same:

to obtain all the diagnostics required by the standard, you should
also specify '-pedantic' (or '-pedantic-errors' if you want them to be errors rather than
warnings).

So I believe you've discovered an editorial discrepancy.


text:
Q: Error when connect stm32f4 with ov7670 I'm using stm32f4 connect to ov7670 (without FIFO) to capture a image (176x144, RGB565). After capture image, stm will send data to PC via UART-COM. I have written a program using C# to read data from com port and display as image. But I have problem with view I get:

Here is my C# code:
using System.Drawing;
using System.Windows.Forms;

namespace camview
    {
    public partial class Form1 : Form
    {
        Bitmap bmp = new Bitmap(176, 144);
        public Form1()
        {
            InitializeComponent();

            serialPort1.Open();
        }

        void setbmp(Bitmap bmp, int x, int y, int a, int b)
        {
            int tmp = (a << 8) | b;

            int red = tmp >> 11;
            int green = (tmp >> 5) & 0x3f;
            int blue = tmp & 0x1f;

            bmp.SetPixel(x, y, Color.FromArgb(red * 8, green * 4, blue * 8));

        }

        private void button1_Click(object sender, System.EventArgs e)
        {
            string s = "";
            while (s != "OK\r")
            {
                s = serialPort1.ReadLine();
                richTextBox1.Text += s;
            }

            richTextBox1.Text += "Start\n";
            for (int i = 0; i < 144; i++)
                for (int j = 0; j < 176; j++)
                {
                    int a = serialPort1.ReadByte();
                    int b = serialPort1.ReadByte();
                    //richTextBox1.Text += a + ' ' + b + ' ';
                    setbmp(bmp, j, i, a, b);
                }

            pictureBox1.Image = bmp;
        }
    }
}

These is my config for ov7670 reg:
I2C_writereg(0x12, 0x80); // reset all reg
I2C_writereg(0x11, 0xc0); //set CLKRC
I2C_writereg(0x12, 0x0c); // set output QCIF, RGB
I2C_writereg(0x70, 0x3a); // scaling
I2C_writereg(0x71, 0x35);
I2C_writereg(0x8c, 0x00); // disable RGB444
I2C_writereg(0x40, 0xd0); // enable RGB565, output range from 00 to FF
I2C_writereg(0x0c, 0x4c); //


text:
Q: Object type instead of specific value from def __unicode__ showed in admin According to link1 and link2 I made model which is listed in another model as kierunek = models.ForeignKey('Kierunek', default=1) and as name of select, show self.nazwa_kierunku. Everything works fine, but I cant get def __unicode__ works. I tried also def __str__. There is always name "Object Kierunek".
One of my code samples. I tried many variants of this:
from django.db import models

class Kierunek(models.Model):
    nazwa_kierunku = models.CharField('Nazwa kierunku', max_length=100)
    created = models.DateTimeField('Timecreated', auto_now_add=True, null=True)
    modified = models.DateTimeField('Timeupdated', auto_now=True, null=True)
    def __unicode__(self):
        return self.nazwa_kierunku

class Meta:
    verbose_name = "Nazwa kierunku"
    verbose_name_plural = "Nazwy kierunkow"

A: Assuming you are using pyhton 3
__str__() and  __unicode__() methods

In Python 2, the object model specifies str() and  unicode()
  methods. If these methods exist, they must return str (bytes) and
  unicode (text) respectively.
The print statement and the str built-in call str() to determine
  the human-readable representation of an object. The unicode built-in
  calls  unicode() if it exists, and otherwise falls back to
  str() and decodes the result with the system encoding. Conversely, the Model base class automatically derives str() from
  unicode() by encoding to UTF-8.
In Python 3, there's simply str(), which must return str (text).
(It is also possible to define bytes(), but Django application
  have little use for that method, because they hardly ever deal with
  bytes.)
Django provides a simple way to define str() and  unicode()
  methods that work on Python 2 and 3: you must define a str()
  method returning text and to apply the python_2_unicode_compatible()
  decorator.
On Python 3, the decorator is a no-op. On Python 2, it defines
  appropriate  unicode() and str() methods (replacing the
  original str() method in the process). Here's an example:

from __future__ import unicode_literals
from django.utils.encoding import python_2_unicode_compatible

@python_2_unicode_compatible
class MyClass(object):
    def __str__(self):
        return "Instance of my class"

This technique is the best match for Django's porting philosophy.
For forwards compatibility, this decorator is available as of Django
  1.4.2.
Finally, note that repr() must return a str on all versions of
  Python.

Source https://docs.djangoproject.com/en/1.8/topics/python3/#str-and-unicode-methods


text:
Q: How to add animation to HTML/CSS box, when website loads box will load with animation? I'm making a website using online Wix templates but the specific template didn't have all the things I needed so then I had to learn a little HTML/CSS. (I'm pretty new to it)
I've written the code below which shows a list of text (Company names) by sliding upwards. Once the user hovers the mouse on the text, the slider stops (onmouseover) and when the user moves the mouse pointer away from it the slider goes back to the same motion (onmouseout).
Link to some code: https://www.codepile.net/pile/WAJX9nrE
Okay so my questions are:

*

*How can I animate this code so that when the webpage first loads this box will load in with some sort of animation?

*And also instead of Company names, how can I add hyperlinks to the dedicated company's website?

A: The link you provided is not working please repair the link.

A: To do this, add an animation for the element on page load through CSS. In the following example, this animation is called move-up which will run for 1 second. Additionally, to make a marquee, add an additional animation that loops. This is called slide in the following snippet which repeats every 16 seconds. The HTML of the companies will need to be duplicated to provide seamless looping. Finally, use a transition and the CSS :hover property to pause the animations when the mouse is over the card container. Here is a demo.

body {
  overflow-y: hidden;
}

.card {
  width: 200px;
  height: 100px;
  border-radius: 5px;
  box-shadow: 0 5px 10px #888888;
  padding: 10px;
  margin: 20px;
  display: inline-block;
  /* Adds animation that runs on load */
  animation-name: move-up;
  animation-duration: 1s;
  /* Adds transition */
  transition: 0.3s;
  /* Safari versions 8 and older */
  -webkit-animation-name: move-up;
  -webkit-animation-duration: 0.3s;
  -webkit-transition: 0.5s;
}

/* Styles the container the card is in */

.card-container {
  width: 100%;
  overflow-y: show;
  white-space: nowrap;
  animation-name: slide;
  animation-duration: 16s;
  animation-iteration-count: infinite;
  animation-timing-function: linear;

  /* More Safari compatibility... */
  -webkit-animation-name: slide;
  -webkit-animation-duration: 16s;
  -webkit-animation-iteration-count: infinite;
  -webkit-animation-timing-function: linear;

}

/* Plays transition on hover */

.card:hover {
  transform: scale(1.1);
}

.card-container:hover {
  animation-play-state: paused;
}

/* Defines animation on load */

@keyframes move-up {
  from {
    opacity: 0;
    transform: translateY(50px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

/* Sliding animation */

@keyframes slide {
  from {
    transform: translateX(0);
  }
  to {
    transform: translateX(-1320px);
  }
}

/* Safari versions 8 and older */

@-webkit-keyframes move-up {
  from {
    opacity: 0;
    transform: translateY(50px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

@-webkit-@keyframes slide {
  from {
    transform: translateX(0);
  }
  to {
    transform: translateX(-1320px);
  }
}

Company 1

Company 2

Company 3

Company 4

Company 5

Company 1

Company 2

Company 3

Company 4

Company 5


text:
Q: Can I make a class with variable number of type arguments? Supposing I wanted to implement a data-frame type thing in Scala, I might have a class that I could initialize a two column table like this:
val:foo = new MyDataFrame[String, Int]("a", "b")

And when I got a row, I'd expect it's type to be something like:
(String, Int)

That sort of thing is trivial to implement if I have a fixed number of columns, but what if I wanted to make a dataframe that would allow as many columns as I want.
val:foo = new MyDataFrame[Aaa, Bbb, ... Zzz]("ColA", "ColB", .... "ColZ")

Then I'd want my my row to have a type that looks like:
(Aaa, Bbb, ... Zzz)

My question is, how could I implement a class like MyDataFrame where the number of type arguments is not known in advance. I guess this is analogous to the use of Variable arguments when the number of regular inputs to a function cannot be known in advance.


text:
Q: Is there a bug in Python 3.8 datetime with DST transitions? I'm trying to convert a timezone-aware datetime in Europe/Sofia to the start of the day in Europe/Sofia, but returning the datetime in UTC. Doing this, I encountered a strange problem:
#!/usr/bin/env python

import sys
import pytz
from datetime import datetime, timedelta

def main():
    tz = pytz.timezone('Europe/Sofia')
    dt = pytz.utc.localize(datetime(year=2019, month=3, day=31, hour=14, minute=45))
    print(f'We start with the datetime in UTC: {dt}')
    dt = dt.astimezone(tz)
    print(f'Then convert it to Europe/Sofia timezone: {dt}')

    result = dt.replace(hour=0, minute=0, second=0, microsecond=0)
    print(f'Then make it the start of the day midnight: {result}')
    result = result.astimezone(pytz.utc)
    print(f'Then convert it back to UTC (the final result we want): {result}')
    print(f'But notice the time is wrong now when converted back to Europe/Sofia: {result.astimezone(tz)}')

    result = dt - timedelta(hours=dt.hour, minutes=dt.minute, seconds=dt.second, microseconds=dt.microsecond)
    print(f'Using a timedelta instead of replace has the same result: {result}')
    print(f'The time is still wrong when converted back to Europe/Sofia: {result.astimezone(pytz.utc).astimezone(tz)}')

    return 0

if __name__ == '__main__':
    sys.exit(main())

Which prints:
We start with the datetime in UTC: 2019-03-31 14:45:00+00:00
Then convert it to Europe/Sofia timezone: 2019-03-31 17:45:00+03:00
Then make it the start of the day midnight: 2019-03-31 00:00:00+03:00
Then convert it back to UTC (the final result we want): 2019-03-30 21:00:00+00:00
But notice the time is wrong now when converted back to Europe/Sofia: 2019-03-30 23:00:00+02:00
Using a timedelta instead of replace has the same result: 2019-03-31 00:00:00+03:00
The time is still wrong when converted back to Europe/Sofia: 2019-03-30 23:00:00+02:00

The bug happens when subtracting the timedelta or doing the replace(), because the result should be midnight in Europe/Sofia with +2 offset, however we're seeing an incorrect +3 offset. It should be +2 because at 3 AM on Mar 31 2019 there was a DST transition of +1 hour. [1]
Is this a bug in Python or a known limitation with a known workaround?

A: It's a pytz problem, not Python (3.8). It doesn't account for the DST transition when you use replace on the aware datetime object. You could do the timedelta arithmetic with the naive datetime instead, then localize and normalize.
To avoid that rather complicated procedure, an alternative might be to use the zoneinfo module (Python 3.9), which is available via backports also on 3.8:
from datetime import datetime, timedelta
from backports.zoneinfo import ZoneInfo # pip install backports.zoneinfo

tz, utc = ZoneInfo("Europe/Sofia"), ZoneInfo("UTC")

dt = datetime(year=2019, month=3, day=31, hour=14, minute=45, tzinfo=utc)
dt = dt.astimezone(tz)
result = dt.replace(hour=0, minute=0, second=0, microsecond=0)
print(f'Then make it the start of the day midnight: {result}')

result = result.astimezone(ZoneInfo("UTC"))
print(f'Then convert it back to UTC (the final result we want): {result}')
print(f'Converted back to Europe/Sofia: {result.astimezone(tz)}')

result = dt - timedelta(hours=dt.hour, minutes=dt.minute, seconds=dt.second, microseconds=dt.microsecond)
print(f'Using a timedelta instead of replace has the same result: {result}')
print(f'The time is still correct when converted back to Europe/Sofia: {result.astimezone(utc).astimezone(tz)}')

Then make it the start of the day midnight: 2019-03-31 00:00:00+02:00
Then convert it back to UTC (the final result we want): 2019-03-30 22:00:00+00:00
Converted back to Europe/Sofia: 2019-03-31 00:00:00+02:00
Using a timedelta instead of replace has the same result: 2019-03-31 00:00:00+02:00
The time is still wrong when converted back to Europe/Sofia: 2019-03-31 00:00:00+02:00


text:
Q: Accessing Shoutcast Current Stream Information i am creating an internet radio application for android. So far i have successfully streamed and played using the shoutcast url for various stations.This is my code :
      String url = "http://185.33.22.13:7704";
    mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
    try
    {
        mediaPlayer.setDataSource(url);
        mediaPlayer.prepare();
    }
    catch (IOException e)
    {
        e.printStackTrace();
    }
    mediaPlayer.start();

Next i would want to get the information of stream to be shown in my application.
I want to retrieve the information shown in green box:

People have posted about FFmpegMediaMetadataRetriever but github is way out of my league to understand also tried thier apk file which does nothing when given the above http link.Please suggest me a simple and robust solution to retrieve the data from SHOUTcast DNAS status.
Thanks in advance !

A: Shoutcast V1 has a special page with bitrate and other information.
If your shoutcast is running on
http://185.33.22.13:7704
then this page url will be:
http://185.33.22.13:7704/7.html
The body of that page looks like this:
 <meta http-equiv="Pragma" content="no-cache">214,1,312,1000,213,64,Ferry Tayle - The Way Back Home (Edit) (feat. Poppy)

Split that text by commas and you will get:

*

*Current listeners

*Stream status

*Peak listeners

*Maximum number of listeners (from server start)

*Unique listeners

*Bitrate

*Song title

Here is an example in javascript (Nodejs) that gets the data from 7.html page and parses it:
var request = require('request'),
    options = {
        url: 'http://185.33.22.21:7704/7.html',
        headers: {
            'User-Agent': 'Mozilla/5.0'
        }
    },
    regex = /(.*?)<\/body>/i;

request(options, function (error, response, body) {
    var match = regex.exec(body),
        data = match[1].split(',');

    console.log("7.html: ", body);

    console.log("Current listeners: ", data[0]);
    console.log("Stream status: ", data[1]);
    console.log("Peak listeners: ", data[2]);
    console.log("Maximum number of listeners: ", data[3]);
    console.log("Unique listeners: ", data[4]);
    console.log("Bitrate: ", data[5]);
    console.log("Metada: ", data[6]);
});

Please note that setting "User-Agent" header is required.
If you have admin password from that server - then another way is to get XML data directly from shoutcast admin page using the following URL:

http://185.33.22.13:7704/admin.cgi?mode=viewxml


text:
Q: handling anonymous users and authenticated users I have a question that has been bother me. I'm making a review based website.
Anonymous users and logged in users can make reviews
if the user is not logged in when they click submit a review, a dialog will show up that says "signup", "login", or "skip"
I'm wondering how to deal with these 2 different types of users.
I think having one reviews collection would be a good idea. I have a userId as a field should I add an anonId for anonymous users.
would you do something like this:
Review.find({companyName}).populate([{path : "userId", model : "User"},{path : "anonID", model : "Anon"} ])
Would you make anons collection?
problem might be If I want to display all reviews for company name some reviews might not have a "userId" and I might get an error.
I have session collection(connect-mongo) that gets populated by people that visited the site.Can I use that? How would I associate that anonymous user with a review. the sessions collection also contains passport.js users
I think I should mention that I want to keep track of all user like how many times they visited the site.
How many times they clicked a button.
How to handle these 2 types of users?


text:
Q: array_merge(): Argument #2 is not an array [WP Plugin - Event Booking Pro] Warning: array_merge(): Argument #2 is not an array in /data03/virt73559/domeenid/www.traagel.com/maarahvalaat/maarahvalaat/wp-content/plugins/eventBookingPro/EbpSettings.php on line 416
I purchased Event Booking Pro - WP Plugin, but plugin is broken in my website and
plugin default text is undefined  (image)
    $textSettings = array();
$settings = array();

if ($sel != null && $sel != "") {
  $settings = $wpdb->get_row("SELECT " . $sel . " FROM " . EbpDatabase::getTableName("settings")." where id='$settingId'", ARRAY_A);
}

if ($textSel != null && $textSel != "" ) {
  $textSettings = EbpText::getTextSettings($textSel);
}

return (Object) array_merge($settings, $textSettings); }  //line416

When i tried change $textSettings to array:
    return (Object) array_merge($settings, array($textSettings));

Then Website plugin works, but i am unable to fix undefined text problem.
Help appreciated.


text:
Q: how to make a full background-image emailing without text? I would like to know how to make a background appears full width in an emailing even without a text. I don't lnow how to make it appear even without text you can see and its real dimensions. I want the result to be similar to  this with the text at the bottom like a footer.
Does someone know how to do this?

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional //EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

  <meta http-equiv="content-type" content="text/html; charset=utf-8" />
  <meta name="viewport" content="width=device-width; initial-scale=1.0; maximum-scale=1.0;" />
  <title></title>

  <title></title>

            <v:rect xmlns:v="urn:schemas-microsoft-com:vml" fill="true" stroke="false">
              <v:fill type="tile" src="https://image.noelshack.com/fichiers/2017/51/4/1513863465-carte2.png" color="#374b94">
                <v:textbox inset="0,0,0,0">

                        Si vous ne souhaitez plus recevoir d'email cliquez ici

                </v:textbox>
            </v:rect>

A: To the image style - add height.If you inspect it you can see that it have only width.
    background-repeat:no-repeat;
    background-size:contain;
    background-position: center;
    height: 500px;

    /** or padding: some value **/
    padding-bottom: 40%;


text:
Q: How to waits for user inputs in docker-compose up When I run the container I have used following command:
docker run -it -v /home/config --name appli <dockerid>/<docker-image>

It waits until user inputs the login details.
But when I run the command without -it the container skip the user input line and executes other lines. This is the same issue when I run the docker-compose file. I want to execute docker-compose file as same as the docker run -it command.
screen shot for te command docker run with -it
screen shot of the output when run the docker-compose


text:
Q: Series.Format.Fill.Transparency property not applying formatting I have a chart in which I create a number of new series for using the Chart.SeriesCollection.NewSeries method, there after I immediately format each series. All formatting seems to work (marker size/style/colour) bar marker transparency which I set via the Series.Format.Fill.Transparency property.
I have seen people using the selection method to set series marker transparency as per below:
 Set GraphSeries.Absolute.ErraticErrors = AbsChart.SeriesCollection.NewSeries
With GraphSeries.Absolute.ErraticErrors
    .Name = "ErraticSeries"
    .MarkerSize = CommonMarkerSize
    .MarkerBackgroundColorIndex = Graph.XY.Formatting.MarkerFillColour.ErraticErrors
    .MarkerForegroundColor = Graph.XY.Formatting.MarkerLineColur.ErraticErrors
    .Select
        Selection.Format.Fill.Transparency = CommonMarkerTrans
    .Format.Line.Visible = msoFalse
End With

After trying and troubleshooting the above method, it seems when the marker transparency is set, the marker background colour can be seen to change value rather than the transparency which remains at its initial value, strange? Based on this finding, I reverted back to Series.Format.Fill.Transparency = CommonMarkerTrans and viewed this property in the watch window while setting it to CommonMarkerTransand observed no change to the initial value of Series.Format.Fill.Transparency (-2.147484E+09), also strange?
Seems that the Series.Format.Fill.Transparency property is not changing from its intial value when trying to set it to CommonMarkerTransvia Series.Format.Fill.Transparency = CommonMarkerTrans
Note: CommonMarkerTrans= 0.9 as single
Anyone have any ideas why this is? I'm really stumped here, could it be related to the ordering in which I am setting the marker formatting?
Below shows a snippet of code to provide context. The code creates an  'empty' chart series and then applies various formatting, such as marker size, and then sets the series X and Y values from data stored in two separate arrays.
Set GraphSeries.Absolute.ErraticErrors = AbsChart.SeriesCollection.NewSeries
With GraphSeries.Absolute.ErraticErrors
    .Name = "ErraticSeries"
    .MarkerSize = CommonMarkerSize
    .Format.Fill.Transparency = CommonMarkerTrans
    .MarkerBackgroundColorIndex = Graph.XY.Formatting.MarkerFillColour.ErraticErrors
    .MarkerForegroundColor = Graph.XY.Formatting.MarkerLineColur.ErraticErrors
    .Format.Line.Visible = msoFalse
End With

RelOrAbsChart.SeriesCollection(SeriesName.ErraticSeries).XValues = XAxisRelOrAbs.ErraticSeries
RelOrAbsChart.SeriesCollection(SeriesName.ErraticSeries).Values = YAxisRelOrAbs.ErraticSeries

A: Seems I may have solved this. For some reason you must use the following properties to set for/background colour of series markers if you want to use Fromat.Fill. Transparency to set the marker Transparency
 Series.Format.Fill.ForeColor.RGB = RGB(R,G,B)
 Series.Format.Fill.BackColor.RGB = RGB(R,G,B)

And not
Series.MarkerBackgroundColor = RGB(R,G,B)
Series.MarkerForegroundColor = RGB(R,G,B)

Not sure why this is the case, seems confusing to have two separate properties to set Marker for/background colour and not be able to set transparency for both.
Why would you need two separate and mutually exclusive properties for the same thing? For clarity, maybe someone could clear this up or correct my understanding?
Functioning code which now sets colour and transparency correctly:
    Set GraphSeries.Absolute.ErraticErrors = AbsChart.SeriesCollection.NewSeries
    With GraphSeries.Absolute.ErraticErrors
        .Name = "ErraticSeries"
        .MarkerSize = CommonMarkerSize
        .MarkerStyle = xlMarkerStyleCircle
        With .Format.Fill
            .Visible = msoTrue
            .ForeColor.RGB = Graph.XY.Formatting.MarkerFillColour.ErraticErrors
            .BackColor.RGB = Graph.XY.Formatting.MarkerLineColur.ErraticErrors
            .Transparency = CommonMarkerTrans
            .Visible = msoTrue
        End With
    End with


text:
Q: Image Produces top border line I have a li tag that when it's hovered over with the mouse the background image url is set to a dark brown arrow as seen in this image below.

As you can see, a black line is produced on the top right of the image. I have no idea how this is produced and I want the dark line removed. How do I fix it?
The CSS:
#topcol1navtall ul.contactsleftnav li.dash.selected {

    background:#7c6a54 image-url('contact-arrow-nav.png') right no-repeat;
    border-bottom: 2px dotted #f17ca6;
    margin-top: 5px; padding-top: 8px;

}

The HTML:

      asdf, Billy 3

A: That line isn't black. It's the same color as your background, #7c6a54. Your image is either transparent in the first row of pixels, or it's one pixel too short and somehow anchored to the bottom of the containing li.
I would guess it's probably the latter. Your li is one pixel taller than the background image you're using. I would recommend making your background image taller than you need it be and then explicitly anchoring it either to the top or bottom of the containing element like so:
background: #7c6a54 image-url(your-url) right top no-repeat;. Then make the background image taller by a few pixels. Make sure the bottom angle doesn't suddenly turn into a vertical line or else you'll have a weird one-pixel bump there. Actually continue the angle so that you retain a smooth line on that end.
The other option is to explicitly declare the height of the li (making adjustments for your padding), but then you run into trouble if someone's browser renders text larger than you expect it to. If you're going to explicitly declare the height of the li, you should also explicitly declare the font-size and line-height of the text in the li (or they should inherit that from a parent element, but don't leave it to chance).


text:
Q: erigi on PHP is deprecated (e-mail validation) Since erigi() is deprecated in PHP 5 and I am in a need to validate an e-mail id, which function should be used? I need the format for e-mail validation such as:
<?php
function checkEmail($email)
{
   if(eregi("^[a-zA-Z0-9_]+@[a-zA-Z0-9\-]+\.[a-zA-Z0-9\-\.]+$]", $email))
   {
      return FALSE;
   }

   list($Username, $Domain) = split("@",$email);

   if(getmxrr($Domain, $MXHost))
   {
      return TRUE;
   }
   else
   {
      if(fsockopen($Domain, 25, $errno, $errstr, 30))
      {
         return TRUE;
      }
      else
      {
         return FALSE;
      }
   }
}
?>

A: For php 5.2: http://php.net/manual/en/function.filter-var.php
$result = filter_var($email , FILTER_VALIDATE_EMAIL);

Or http://pl.php.net/manual/en/function.preg-match.php for any regular expression.

A: Use the filter_var PHP function instead:
if (filter_var($email, FILTER_VALIDATE_EMAIL)) {

}

Or, even better yet, use a RFC-compliant email address validator. As no amount of regex will encompass all the valid emails that are possible.

A: En example with with filter extension.
<?php
function is_valid_email($email)
{
    return filter_var($email, FILTER_VALIDATE_EMAIL) !== false;
}

var_dump(is_valid_email('test@example.com'));
var_dump(is_valid_email('foobar'));
var_dump(is_valid_email('test+foo@example.com.com'));

[~]> php x.php
bool(true)
bool(false)
bool(true)

This you can then combine with further validation that you already have.


text:
Q: i made a function and then i used the same code that is in the function to get the minimum value through a for loop but i am getting different answers the function is to calculate cost based on earning, loan taken, fees, rates and duration, but when applying the exact same code that is there in the function to a for loop the answers are coming different, can help me out as i am new to programming
#income tax calculation and cost calc
# earning, loan y n, interest rate, years, fees

def IT_calc(earn,l,ir,d,f):
    interest_payable = f * ir * d
    amount_payable = f + interest_payable
    if l == 0:
        if earn <= 250000:
            income_tax = 0
        elif earn <= 500000:
            income_tax = (earn-250000)*0.05
        elif earn <= 750000:
            income_tax = (250000*0.05)+ (earn-500000)*0.10
        elif earn <= 1000000:
            income_tax = (250000)*(0.05+0.10) + (earn-750000)*0.15
        elif earn <= 1250000:
            income_tax = (250000)*(0.05+0.10+0.15) + (earn-1000000)*0.20
        elif earn <= 1500000:
            income_tax = (250000)*(0.05+0.10+0.15+0.20) + (earn-1250000)*0.25
        else:
            income_tax = (250000)*(0.05+0.10+0.15+0.20+0.25) + (earn-1500000)*0.30
        cost = (income_tax * 1.04 * d) + f
        print('Your total cost over', d, 'years without loan is:', cost)
    else:
        earn = earn-(amount_payable//d)
        if earn <= 250000:
            income_tax = 0
        elif earn <= 500000:
            income_tax = (earn-250000)*0.05
        elif earn <= 750000:
            income_tax = (250000*0.05)+ (earn-500000)*0.10
        elif earn <= 1000000:
            income_tax = (250000)*(0.05+0.10) + (earn-750000)*0.15
        elif earn <= 1250000:
            income_tax = (250000)*(0.05+0.10+0.15) + (earn-1000000)*0.20
        elif earn <= 1500000:
            income_tax = (250000)*(0.05+0.10+0.15+0.20) + (earn-1250000)*0.25
        else:
            income_tax = (250000)*(0.05+0.10+0.15+0.20+0.25) + (earn-1500000)*0.30
        cost = (income_tax * 1.04 * d) + amount_payable
        print('Your total cost over', d, 'years with loan is:', cost)

IT_calc(1200000,1,0.085,3,1600000)
>> Your total cost over 3 years with loan is: 2056568.104

#For loop
b = []
f = 1600000
ir = 0.085
earn = 1200000
l = 1
for t in range(1,20):
    interest_payable = f * ir * t
    amount_payable = f + interest_payable
    if l == 0:
        if earn <= 250000:
            income_tax = 0
        elif earn <= 500000:
            income_tax = (earn-250000)*0.05
        elif earn <= 750000:
            income_tax = (250000*0.05)+ (earn-500000)*0.10
        elif earn <= 1000000:
            income_tax = (250000)*(0.05+0.10) + (earn-750000)*0.15
        elif earn <= 1250000:
            income_tax = (250000)*(0.05+0.10+0.15) + (earn-1000000)*0.20
        elif earn <= 1500000:
            income_tax = (250000)*(0.05+0.10+0.15+0.20) + (earn-1250000)*0.25
        else:
            income_tax = (250000)*(0.05+0.10+0.15+0.20+0.25) + (earn-1500000)*0.30
        cost = (income_tax * 1.04 * t) + f
    else:
        earn = earn-(amount_payable//t)
        if earn <= 250000:
            income_tax = 0
        elif earn <= 500000:
            income_tax = (earn-250000)*0.05
        elif earn <= 750000:
            income_tax = (250000*0.05)+ (earn-500000)*0.10
        elif earn <= 1000000:
            income_tax = (250000)*(0.05+0.10) + (earn-750000)*0.15
        elif earn <= 1250000:
            income_tax = (250000)*(0.05+0.10+0.15) + (earn-1000000)*0.20
        elif earn <= 1500000:
            income_tax = (250000)*(0.05+0.10+0.15+0.20) + (earn-1250000)*0.25
        else:
            income_tax = (250000)*(0.05+0.10+0.15+0.20+0.25) + (earn-1500000)*0.30
        cost = (income_tax * 1.04 * t) + amount_payable
    b.append(cost)

b
>>[1736000.0,
 1872000.0,
 2008000.0,
 2144000.0,
 2280000.0,
 2416000.0,
 2552000.0,
 2688000.0,
 2824000.0,
 2960000.0,
 3096000.0,
 3232000.0,
 3368000.0,
 3504000.0,
 3640000.0,
 3776000.0,
 3912000.0,
 4048000.0,
 4184000.0]

i was trying to estimate the minimum costs but i am getting the wrong answer through the for loop, am i missing something?

A: In your for loop, you are changing the value of earn on every loop with the line earn = earn-(amount_payable//t), so that it is not starting at 1200000 for each case.
Either reset it inside the for loop, or as OneMadGypsy suggests, change the IT_calc function to return the value instead of printing and use it in your for loop instead of having a slightly modified copy of the entire function.


text:
Q: Why won't my simple YQL JSON-via-Jquery script parse in internet Explorer? I've got my scribd xml feed (with its secret pass key hidden) converted to JSON via YQL.
I want to use jQuery to populate an unordered list with the results. It's working in everything but IE.
This seems pretty barebones to me, and yet I can't understand why it achieves nothing in Internet Explorer. There must be some IE secret I don't know about, like JSON is handled differently in IE, or you need to use JSONP, or IE doesn't play nice with this usage of .each()... What am I missing here? Here's a jFiddle Link to demonstrate: http://jsfiddle.net/niceindividual/nRkvS/2/
var yqlURL = "http://query.yahooapis.com/v1/public/yql/dulyb/scribdCHF?format=json";
window.console.log("The yqlURL variable is set to " + yqlURL);

$.getJSON(yqlURL, function(data) {
    $.each(data.query.results.result, function() {
        $('#results').append('

' + '' + '' + this.title + '

' + this.description + '

');
    });
});

A: My friend Raymon helped me out:
YQL outputs JSONP, not JSON; so in the code above, I used $.ajax instead of $.getJSON and set the dataType to "jsonp". It seems to work in IE now.
Updated (fixed) Example: http://jsfiddle.net/niceindividual/nRkvS/4/


text:
Q: Error calling Controller Method from View - AngularJS I'm getting this error calling the Controller Method getListCategories() from the view.

TypeError: Object.keys called on non-object
      at Function.keys (native)
      at extend (app/bower_components/angular/angular.js:412:25)
      at Function.angular.module.provider.$get.Resource.(anonymous function) (app/bower_components/angular-resource/angular-resource.js:575:15)
      at Scope.$scope.getListCategories (app/shoppinglists/shoppinglists.js:17:69)
      at $parseFunctionCall (app/bower_components/angular/angular.js:12332:18)
      at Object.expressionInputWatch (app/bower_components/angular/angular.js:12735:31)
      at Scope.$get.Scope.$digest (app/bower_components/angular/angular.js:14217:40)
      at Scope.$get.Scope.$apply (app/bower_components/angular/angular.js:14488:24)
      at done (app/bower_components/angular/angular.js:9646:47)
      at completeRequest (app/bower_components/angular/angular.js:9836:7) (22:31:11:425 | error)

I'm not sure if this is the best way to do this, so any suggestion is more than welcome.
Service
shoppingListService.factory('ShoppingLists', function ($resource) {
var factory = {
    getShoppingLists: $resource('http://localhost:8080/ShoppingListBackend/webresources/shoppinglists', {}, {
        all: {method: 'GET', isArray: true}
    }),
    getCategories : $resource('http://localhost:8080/ShoppingListBackend/webresources/shoppinglists/getcategories/:id', {id: '@id'}, {
        byId: {method: 'GET', isArray: true}
    })
};
return factory; });

Controller
.controller('ShoppingListController', function ($scope, ShoppingLists) {
    $scope.shoppinglists = ShoppingLists.getShoppingLists.all();

    $scope.getListCategories = function (id) {
        $scope.listCategories = ShoppingLists.getCategories.byId(id);
    };
});

View

{{list.title}}

{{getListCategories(list.id)}}

    <input type="checkbox" id="item_checked">
    Toilet Paper


text:
Q: Why does my Done button disappear in a simple FlipsideViewController app? I have a simple two-screen app that I built a year ago using the "utility" project template in Xcode 3. This creates an app delegate, a main view and a flipside view. The flipside view has a UINavigationBar at the top with a Done button in the left position.
I just finally upgraded to Xcode 4 with SDK 4.3, and when I build the app now, the Done button doesn't appear, either in the simulator or on my device. But if I create a new project using the Xcode 4 "utility" template, the Done button displays and works correctly. Unfortunately the upgrade removed my SDK 4.2 files, so I can't rebuild for SDK 4.2 and test whether that's what made the difference.
I noticed that the new template sets up the main view differently, using the rootViewController property of the window rather than adding the main view as a subview of the window (more info here). I tried copying this code into my app delegate instead of the addSubview code, but the view didn't display at all, so I must have missed something ... but I would just as soon maintain iOS 3.0 compatibility anyway. I can't find any other difference between the newer "utility" template and my own project based on the old template.
I also tried moving the Done button from the leftButtonItem to the rightButtonItem in Interface Builder, but it still doesn't appear.
MORE INFO:
I tried this on all the versions of the iPhone simulator that are available in my Xcode installation. When building with SDK 4.3, the Done button does not appear with the iOS 4.0-4.3 simulators ... but it does appear with the iOS 5 (beta) simulator.
Next, I wired up IBOutlets to the navigation bar, navigation item and done button in Interface Builder so I could probe them from my code. When I checked them immediately after presenting the flipside view with presentModalViewController, I found that the done button (a UIBarButtonItem) exists, but the navigation item's leftBarButtonItem is null. If I assign the done button to that property, it appears. So somehow that button is getting disconnected from the leftBarButtonItem property when the flipside view is initialized or displayed.
WORKAROUND:
In Interface Builder, if I view the outlets for the Navigation Item, I see that the Done button is linked to its leftBarButtonItem property, but if I view the outlets for the Done button, it has no links. If I link it to the Navigation Item then the button appears! With this setup, the Done button shows the Navigation Item as an outlet, and the Navigation Item shows the Done button as an outlet twice. This is not needed in the new Utility Application template, so I don't know why it's needed here. It seems to be working, but if anyone has an explanation or a better solution I'll reserve my answer points for that.

A: Had a similar problem with custom BarButtonItem's, although I'm not exactly sure that it's the same problem they're pretty close. So, I'm posting an answer in case someone stumbles upon your question like I did :)
Problem:
Add a custom UIBarButtonItem with the following code to a navigation bar with a custom background. When you push another view controller and come back, the custom UIBarButtonItem doesn't appear but you can continue to touch where it used to be and invoke its target action.
The problem only occurs on iOS4.3 simulator and everything works fine without the solution on iOS5 simulator. (Everything works normally also on iOS5 devices, couldn't try the code on an iOS4.3 device)
    UIButton* doneButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [doneButton setBackgroundImage:[UIImage imageNamed:@"barbutton.png"] forState:UIControlStateNormal];
    [doneButton setTitle:@"Done" forState:UIControlStateNormal];
    doneButton.titleLabel.font = [UIFont fontWithName:@"Helvetica-Bold" size:12.0];
    [doneButton.layer setCornerRadius:5.0];
    [doneButton.layer setMasksToBounds:YES];
    [doneButton.layer setBorderWidth:0.2];
    [doneButton.layer setBorderColor:[[UIColor blackColor] CGColor]];
    doneButton.frame = CGRectMake(0.0, 0.0, 70.0, 30.0);
    [doneButton addTarget:self action:@selector(doneButtonPressed) forControlEvents:UIControlEventTouchUpInside];
    doneBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:myLocationButton];
    self.navigationItem.leftBarButtonItem = doneBarButtonItem;

Solution:
Adding the following line of code related to setting the UIButton layer's z-index solved the problem for me.
[doneButton.layer setZPosition:2];

Note
You need to include <QuartzCore/QuartzCore.h> in order to use layer related properties/methods


text:
Q: What is ssl certification error and what does the following code do? I am doing a course in coursera and this code is part of web scraping program...I dont know what it does
ctx = ssl.create_default_context()
ctx.check_hostname = False
ctx.verify_mode = ssl.CERT_NONE


text:
Q: How can I plot legend symbols and labels on a different row in R? I'm trying to plot a legend in base R with the symbols horizontally and the corresponding labels underneath the symbols on the next row. The legend will be plotted in the margins (not included in example data). Is there a way to use graphical parameters to solve this with the legend() function? Otherwise I will try the text labels, but I prefer a more manageable approach.
I have this example data:
plot(c(1,2,3,4,5), c(1,2,3,4,5), xlim=c(0,5), ylim=c(0,5),  main = "", xlab = "", ylab = "")

legendEntries <- c(0.05, 0.1, 0.15, 0.2, 0.25) # which values in legend
legendSizes   <- sqrt( legendEntries / pi ) * 10 # calculate pch size
legend(1, 2, title="", horiz = T,  legend=legendEntries, col="black", pch=rep(21,5),
   pt.bg = "#ff166c", pt.cex = legendSizes, bty = "n")

And want to create something like this:

Thanks!
Paul
(edit: added picture in text and extra info)

A: You can plot separately points and text.
Something like:
# Make the basic plot
    plot(c(1,2,3,4,5), c(1,2,3,4,5), xlim=c(0,5), ylim=c(0,5),  main = "", xlab = "", ylab = "")
    # set up the legend entries and sizes
    legendEntries <- c(0.05, 0.1, 0.15, 0.2, 0.25) # which values in legend
    legendSizes   <- sqrt( legendEntries / pi ) * 10 # calculate pch size

# plot the legend points
    points(y = rep(1, 5), x = seq(3,4, 0.25), pch = 21, cex = sqrt( legendEntries / pi ) * 10,
           bg = "#ff166c")
# plot the text
    text(y = rep(0.7, 5), x = seq(3,4, 0.25),
         labels = legendEntries)

For Plotting outside of the plot region (i.e. on the margins), you can use the xpd parameter as xpd = TRUE:
plot(c(1,2,3,4,5), c(1,2,3,4,5), xlim=c(0,5), ylim=c(0,5),  main = "", xlab = "", ylab = "")

legendEntries <- c(0.05, 0.1, 0.15, 0.2, 0.25) # which values in legend
legendSizes   <- sqrt( legendEntries / pi ) * 10 # calculate pch size

points(y = rep(-0.8, 5), x = seq(1,2, 0.25), pch = 21, cex = sqrt( legendEntries / pi ) * 10,
       bg = "#ff166c", xpd = TRUE)
text(y = rep(-1, 5), x = seq(1,2, 0.25),
     labels = legendEntries, xpd = TRUE)


text:
Q: Woocomerce Product cateegory filter I'm building a WooCommerce site and having an issue with category product filtering. Is there a way that I can show only certain categories? I want to achieve this (see screenshot below) so the "FESTSITZENDE PROSTHETIK" is just a title and not a category which means that I want to show a title then a few categories, then another title and few categories.
Everything I tried so far,didn't work as intended. Does anyone has any suggestions on how can I achieve the same thing like the picture? Also, can you suggest me some free plugins for product category filtering because I tried a few but they didn't work either.

Thanks
p.s im not sure if i have to mentioned that i'm building this website in elementor.


text:
Q: SPARQL Query to escape emojis? I'm using SPARQL query to extract instances which is valid.
But using this query, I can also get instances which name contains emoticon (e.g., http://ko.dbpedia.org/resource/), and it gives me an error while iterating over the query resultsets. How can I escape from emojis?
SELECT DISTINCT ?s WHERE {
?s ?p ?o

FILTER regex(str(?s), "^http://ko.dbpedia.org/resource")
}

ORDER BY DESC(?s)
limit 100

Error message is as follows
Exception in thread "main" com.hp.hpl.jena.shared.JenaException: Convert results are FAILED.:virtuoso.jdbc4.VirtuosoException: Virtuoso Communications Link Failure (timeout) : malformed input around byte 34
    at virtuoso.jena.driver.VirtuosoQueryExecution$VResultSet.moveForward(VirtuosoQueryExecution.java:498)
    at virtuoso.jena.driver.VirtuosoQueryExecution$VResultSet.hasNext(VirtuosoQueryExecution.java:441)
    at kr.ac.kaist.dm.BBox.TypeInference.LoadTriple.processTriples(LoadTriple.java:92)
    at kr.ac.kaist.dm.BBox.TypeInference.TypeInferenceMain.main(TypeInferenceMain.java:110)

Sample Code is as follows.
VirtuosoQueryExecution vqe = VirtuosoQueryExecutionFactory.create(sparql, set);
        ResultSet results = vqe.execSelect();

        int i = 0;
        while(results.hasNext()){        //  <-----  LoadTriple.java:92 here.

I just posted the extended version of this question on virtuoso-opensource issue #543.

I just want to escape from emoji rather than including all possible characters like "FILTER regex(?s, \"[a-zA-Z가-힣~!@#$%^&*()-_=+|'<>]+\")  }"

A: ENCODE_FOR_URI() should work:
FILTER regex(ENCODE_FOR_URI(str(?s)), "^http://ko.dbpedia.org/resource")

...though you would also need to URI encode the regex match string:
http%3A%2F%2Fko.dbpedia.org%2Fresource


text:
Q: Store XML-String in Tag of XML-Document I have a Website using a Webservice(JS(Ajax) -> PHP) wich uses a Webservice (ASP.NET).
If an error occures in PHP, this is sent back to the client. If PHP gets an Error(XML) from ASP, I want to pass it to the client in a tag of my PHP-XML-error to offer further information.
So for example:
<?xml version="1.0" encoding="utf-8" ?>
<PHPanswer>
  <error>It's not my fault!</error>

    <asperror>
      <?xml version="1.0" encoding="utf-8" ?>
      <error>
        <whatever></whatever>
        <someinfo></someinfo>
      </error>
    </asperror>
</PHPanswer>

I want the Client (Client uses a XML-Reader) to treat this
      <?xml version="1.0" encoding="utf-8" ?>
      <error>
        <whatever></whatever>
        <someinfo></someinfo>
      </error>

like a string. (Probably parsing that string later, Like: Parse the message, take tag "asperror", parse the asperror).
So my first attempt was this:
<?xml version="1.0" encoding="utf-8" ?>
<PHPanswer>
  <errorcode>or whatever</errorcode>

    <asperror> <![CDATA[
      <?xml version="1.0" encoding="utf-8" ?>
      <error>
        <whatever></whatever>
        <someinfo></someinfo>
      </error>
      ]]>
    </asperror>
</PHPanswer>

It didn't work, and i checked it with the code-highlighting of Notepad++. Everything was consideret a string, exept
<?xml version="1.0" encoding="UTF-8"?>

This of course made the xml invalid.
So: how else can I solve this?
If possible I don't want to have to process the ASP-XML in PHP.


text:
Q: Better control on error message on Custom Laravel 5 validation I am defining a Custom validator in my AppServiceProvider@boot as following
/* Custom unique value in set of fields validation */
Validator::extend('unique_in', function ($attribute, $value, $parameters, $validator) {
    $validator_data = $validator->getData();
    foreach ($parameters as $field) {
        if ($value === array_get($validator_data, $field)) {
            return false;
        }
    }
    return true;
}, 'The :attribute cannot be same as any other field in this form.');

/* replace the :fields message string */
Validator::replacer('unique_in', function ($message, $attribute, $rule, $parameters) {
    // I was doing this (this works)
    //    $message = str_replace(':field', implode(',',$parameters), $message);
    //    return $message;

    //I want to do this (to get proper names for the fields)
    $other = $this->getAttribute(array_shift($parameters));

    return str_replace([':other', ':values'], [$other, implode(', ', $parameters)], $message);
});

Problem is instance of validator is not available to access getAttribute.
getAttribute resolves the readable name for parameters
Is there to access validator instance in replacer?
Note that the closure in Validator::extend has $validator which is an instance of validator.

A: I got it working using getCustomMessage and setCustomMessage, but without using Validator::replacer using Validator::extend alone.
Validator::extend('unique_in', function ($attribute, $value, $parameters, $validator) {
        $validator_data = $validator->getData();
        $parameters = array_diff($parameters, [$attribute]);
        $same = null;
        $other = null;
        foreach ($parameters as $field) {
            if ($value === array_get($validator_data, $field)) {
                $same[] = $field;
            }
        }
//No same values found , validation success
        if (is_null($same)) {
            return true;
        }

// Get all Custom Attributes those are defined for this validator and replace with field in $same array and create a new $other array
        $custom_attributes = $validator->getCustomAttributes();
        foreach ($same as $attribute) {
            $other[$attribute] = isset($custom_attributes[$attribute]) ? $custom_attributes[$attribute] : $attribute;
        }

//Task of Validator:replacer is done right here.
        $message = 'The :attribute cannot have same value ":value" as in :fields';
        $message = str_replace([':value',':fields'], [$value ,implode(', ', $other)], $message);
        $validator->setCustomMessages(array_merge($validator->getCustomMessages(), ['unique_in' => $message]));

        return false;
    });

Thanks,
K

A: I know this is a bit old and already answered thread, but the first one I came about when searching for answers to this problem.
I would like to share my solution. I am using Localization with Laravel 5.4 in the Validator::replacer closure like this:
Validator::extend('empty_when', function ($attribute, $value, $parameters) {
    foreach ($parameters as $key) {
        if ( ! empty(Input::get($key))) {
            return false;
        }
    }

    return true;
});

Validator::replacer('empty_when', function ($message, $attribute, $rule, $parameters) {
    $fields = [];
    foreach ($parameters as $parameter) {
        $fields[] = __('validation.attributes.'.$parameter);
    }
    return str_replace(':values', implode(', ', $fields), $message);
});

A: Use trans(). You can simply do like this:
Validator::replacer('greater_than', function($message, $attribute, $rule, $parameters) {
    return str_replace(':field', trans('validation.attributes.'.$parameters[0]), $message);
});


text:
Q: Incoming/outgoing message queues on client/server My system has one server and many clients of 2 types. First type of client sends events to server. Second type receives notifications from server on these events. I'm currently testing RabbitMQ and NServiceBus to build message queue with the following requirements:

*

*First type of client should have incoming queue for events (physically running on it) to prevent data loss on server disconnection.

*Server should have outgoing queue for notifications (physically running on it) to prevent data loss on second type client disconnection.

[Client Type 1 + queue] -> [Server + queue] -> [Client Type 2]
Can this be achieved with one of specified components (or both of them)? If yes how?

A: I am not very familiar with rabbit, so I'll answer the question with nservicebus (NSB) in mind.

My system has one server and many clients of 2 types

OK, first thing, NSB does not have equivalent concepts of client and server. In NSB, all participating applications are called endpoints or services. Some endpoints are publishers, some are subscribers, some are senders, some are receivers. Some are any combination of the above.

First type of client sends events to server.

By convention, there are two types of message in NSB, commands and events. Commands are sent, events are published. So in this scenario, the type 1 clients would send commands to the server. In this scenario, a type 1 client would be a sender endpoint. The server is therefore a receiver endpoint.

Second type receives notifications from server on these events

So in this scenario, the server is a publisher endpoint, and a type 2 client is a subscriber endpoint. The server will publish an event which all subscribers would receive.

First type of client should have incoming queue for events (physically running on it) to prevent data loss on server disconnection

I am assuming that you mean the type 1 client needs to receive the data which it needs to send to the server from somewhere.
Well, in NSB, every endpoint has a queue, called the input queue. This is the means by which the endpoint receives messages.
In NSB the queue transport is abstracted, but out of the box the default is MSMQ (NSB also has support for Rabbit as the queue transport).
This provides a store-and-forward messaging pattern, which guarantees reliability. What this means is that if the server is unavailable, the queuing transport would wait until it was available again before transmitting the message.
So you could send a message onto the type 1 client input queue, which would then be converted into a command and sent to the server.

Server should have outgoing queue for notifications (physically
  running on it) to prevent data loss on second type client
  disconnection.

Similarly, when the server publishes the event (on receipt of the command from the type 1 client), the queuing transport would guarantee delivery of the event to all the subscribing type 2 clients.
A point of note: this would not be based on the server having an "outgoing queue", but rather the queuing transport would deliver the messages to the input queues of all subscribing endpoints.
So all your scenarios would be satisfied by using NServiceBus as part of your approach.


text:
Q: Python Pandas: Rename columns after pivoting I have a pandas dataframe that is pivoted. I do not know how to change column names so that I can continue working with the pivoted dataframe in a natural way. Below is a minimal working example.
df = pd.DataFrame({'foo': ['one', 'one', 'one', 'two', 'two',
                            'two'],
                    'bar': ['A', 'B', 'C', 'A', 'B', 'C'],
                    'baz': [1, 2, 3, 4, 5, 6],
                    'zoo': ['x', 'y', 'z', 'q', 'w', 't']})

After pivoting with
df.pivot(index='foo', columns='bar', values=['baz', 'zoo'])

the output is:
      baz       zoo
bar   A  B  C   A  B  C
foo
one   1  2  3   x  y  z
two   4  5  6   q  w  t

What would be the following step to do in order to obtain below output?
   A_baz  B_baz  C_baz   A_zoo  B_zoo  C_zoo

one   1    2       3       x      y      z
two   4    5       6       q      w      t

Thanks a lot!

A: One option is with pivot_wider from pyjanitor, using the names_glue parameter to reshape the column names:
# pip install pyjanitor
import pandas as pd
import janitor

df.pivot_wider(
    index = 'foo',
    names_from = 'bar',
    values_from = ['baz', 'zoo'],
    names_glue = "{bar}_{_value}")

   foo A_baz B_baz C_baz A_zoo B_zoo C_zoo
0  one     1     2     3     x     y     z
1  two     4     5     6     q     w     t

in the names_glue string template, _value serves as a placeholder for values from values_from. Anything in the {} brackets should either be from names_from or _value to represent values_from.

A: Use f-strings with list comprehension:
#python 3.6+
df.columns = [f'{j}_{i}' for i, j in df.columns]
#lower python versions
#df.columns = ['{}_{}'.format(j, i) for i, j in df.columns]
print (df)
    A_baz B_baz C_baz A_zoo B_zoo C_zoo
foo
one     1     2     3     x     y     z
two     4     5     6     q     w     t

Or DataFrame.swaplevel with map and join:
df = df.pivot(index='foo', columns='bar', values=['baz', 'zoo']).swaplevel(0,1,axis=1)

df.columns = df.columns.map('_'.join)
print (df)
    A_baz B_baz C_baz A_zoo B_zoo C_zoo
foo
one     1     2     3     x     y     z
two     4     5     6     q     w     t


text:
Q: Вопрос по ReactJs Есть 2 взаимосвязанных инпута. Как сделать так, чтобы когда в первый начинал вводить слово, то снизу появлялось 2 таких же инпута, но уже пустые. И так далее.

A: Если навскидку, то получилось вот что:
var Inputs = React.createClass({
    render: function() {
        return

            <input type="text" onChange={this.props.onChange}/>
            <input type="text"/>

    }
});

var App = React.createClass({
    getInitialState: function() {
        return {
            numOfInputs: 1
        };
    },
    addInputs: function() {
        this.setState({
            numOfInputs: this.state.numOfInputs + 1
        });
    },
    render: function() {
        var nodes = [];
        for (var i = 0; i < this.state.numOfInputs; i++) {
            if (i+1 === this.state.numOfInputs) {
                nodes.push(<Inputs key={i} onChange={this.addInputs}/>)
            } else {
                nodes.push(<Inputs key={i}/>);
            }
        }
        return

            {nodes}

    }
});

React.render(
    <App/>,
    document.getElementById('container')
);

http://codepen.io/anon/pen/oxZqwQ


text:
Q: Problema al intentar recuperar un backup de GitLab para Docker Debido a problemas de mantenimiento he tenido que restaurar el equipo de fábrica. Antes de ello realicé una copia de seguridad del contenedor que tenía con GitLab mediante los siguientes pasos:
docker commit -p  78727078a04b  gitlab_backup

docker save -o /container_backup.tar gitlab_backup

Y he guardado el archivo .tar.
Bien, una vez he dejado el ordenador como nuevo. Uno de los cambios más notables que tengo es que me ha cambiado la ip estática interna que tenía. Si antes era 192.168.0.177 ahora es la 192.168.0.198.
Tras instalar docker de nuevo, he comenzado a importar la copia con los siguientes pasos:
docker load -i /container_backup.tar

Y aquí es donde dudo si estoy creando un contenedor correctamente a partir de esta imagen. Esto es lo que realizo:
docker run --detach
--hostname localhost
--publish 443:443 --publish 7842:80 --publish 2098:22
--name gitlab --restart always gitlab_backup:latest

El contenedor se crea y corre, pero a la hora de acceder con el navegador me dice que esta página no funciona. Si creo un contenedor a partir de la imagen oficial de GitLab, funciona bien, pero con esta no consigo recuperar lo que tenía, y no se por donde tirar ahora.
Gracias de antemano.


text:
Q: Bootstrap compiling both default and customized styles I'm trying to modify my website based on a CMS which relies mostly on Bootstrap. I saw that after compiling sass files, in the compiled CSS I have both the default css selectors and the overridden ones. For example:
template.css?d544b92…:12881
a {
    color: #1d60a1;
    text-decoration: none;
    background-color: transparent;
}

template.css?d544b92…:264
a {
    color: #1d60a1;
    text-decoration: none;
    background-color: transparent;
}

The overridden ones are used, as expected but, though, having both in the compiled file makes it much larger. If someone could give me a little help I would really appreciate it. This is the normal behavior of bootstrap( v4) or am I doing something wrong?


text:
Q: JUnit not starting transaction, under Spring, JPA I followed the examples online but still nothing happens. I have a DAO injected via spring, I configured the transaction manager correctly. my unit case just freezes, in debug mode i saw that the before method is called but the test methods never start.
JUnit:
@RunWith(SpringJUnit4ClassRunner.class)
@Transactional
@TransactionConfiguration(transactionManager = "testTxMan")
@ContextConfiguration(classes = { PlentyConfig.class,
    TestHibernateContext.class }, initializers = ConfigFileApplicationContextInitializer.class)
public class TestHibernateFieldDao {

@Autowired
private HibernateTestHelper testHelper;

@Autowired
private HibernateFarmDao farmDao;

@Autowired
private HibernateFieldDao fieldDao;

@Autowired
private HibernateInterestDao interestDao;

@Autowired
private HibernateOrganizationDao organizationDao;

@Autowired
private HibernateOrganizationTypeDao organizationTypeDao;

@Before
public void setUp() throws Exception {
    testHelper.executeQuery("DELETE FROM INTERESTS");
    testHelper.executeQuery("ALTER TABLE INTERESTS AUTO_INCREMENT = 1");
    testHelper.executeQuery("DELETE FROM ORGANIZATIONS");
    testHelper.executeQuery("ALTER TABLE ORGANIZATIONS AUTO_INCREMENT = 1");
    testHelper.executeQuery("DELETE FROM ORGANIZATION_TYPES");
    testHelper
            .executeQuery("ALTER TABLE ORGANIZATION_TYPES AUTO_INCREMENT = 1");
    testHelper.executeQuery("DELETE FROM FIELDS");
    testHelper.executeQuery("ALTER TABLE FIELDS AUTO_INCREMENT = 1");
    testHelper.executeQuery("DELETE FROM FARMS");
    testHelper.executeQuery("ALTER TABLE FARMS AUTO_INCREMENT = 1");

}

@Test
public void testInsertField() {
    Farm farm = new Farm("DummyFarmName");
    farm = farmDao.insert(farm, Farm.class);
    Field field = new Field(farm, "DummyFieldName", true, 0,
            "DummyRotationName");
    Field testField = fieldDao.insert(field, Field.class);

    assertNotNull(testField);
    assert (testField.getId() == 1);
    assertEquals("DummyRotationName", testField.getRotation());
    assertEquals(farm.getId(), testField.getFarm().getId());
    assertNotNull(testField.getCreatedDate());
    assertNotNull(testField.getLastModifiedDate());
}

Test Context:
@Configuration
@ActiveProfiles("development")
@EnableTransactionManagement
public class TestHibernateContext {

@Autowired
public PlentyConfig plentyConfig;

@Bean(name = "dataSource")
@Autowired
public DataSource dataSource(PlentyConfig plentyConfig) {
    final DataSource ds = new DataSource();
    ds.setDriverClassName("com.mysql.jdbc.Driver");
    ds.setUrl("jdbc:mysql://" + plentyConfig.getHostname() + ":"
            + plentyConfig.getDbport() + "/" + plentyConfig.getDbname());
    ds.setUsername(plentyConfig.getUsername());
    ds.setPassword(plentyConfig.getPassword());
    return ds;
}

@Bean
@Autowired
public LocalContainerEntityManagerFactoryBean entityManagerFactory(
        DataSource dataSource) {
    LocalContainerEntityManagerFactoryBean factory = new LocalContainerEntityManagerFactoryBean();
    factory.setDataSource(dataSource);
    factory.setPackagesToScan("com.rdthree.plenty.domain");
    HibernateJpaVendorAdapter adapter = new HibernateJpaVendorAdapter();
    adapter.setShowSql(true);
    adapter.setDatabasePlatform("org.hibernate.dialect.MySQLDialect");
    factory.setJpaVendorAdapter(adapter);
    return factory;
}

@Bean(name = "testTxMan")
public PlatformTransactionManager platformTransactionManager(
        EntityManagerFactory entityManagerFactory) {
    JpaTransactionManager manager = new JpaTransactionManager();
    manager.setEntityManagerFactory(entityManagerFactory);
    return manager;
}

@Bean(name = "sessionFactory")
public SessionFactory sessionFactory(DataSource dataSource) {
    LocalSessionFactoryBuilder builder = new LocalSessionFactoryBuilder(
            dataSource);

    builder.scanPackages("com.rdthree.plenty.domain");

    builder.setProperty("hibernate.show_sql", "true");

    return builder.buildSessionFactory();
}

@Bean
public HibernateTestHelper HibernateTestHelper(SessionFactory sessionFactory) {
    return new HibernateTestHelper(sessionFactory);
}

// All the Daos...

My Dao:
@Repository
@Transactional(propagation = Propagation.REQUIRED)
public class HibernateFieldDaoBean extends HibernateGeneralDaoBean<Field>
    implements HibernateFieldDao {

@PersistenceContext
private EntityManager entityManager;

@Override
public List<Field> getAllfieldsByFarm(long farmId) {
    @SuppressWarnings("unchecked")
    List<Field> fields = Collections.checkedList(
            entityManager.createQuery(
                    "FROM Field F WHERE F.farm.id = "
                            + String.valueOf(farmId)).getResultList(),
            Field.class);
    return fields;
}

@Override
public List<Field> getAllFieldsByFarmAndOrganization(long farmId,
        long organizationId) {
    @SuppressWarnings("unchecked")
    List<Field> fields = Collections.checkedList(
            entityManager.createNativeQuery(
                    "SELECT a.ID, a.FARM_ID, a.NAME, a.HIDDEN, a.ACRES, a.ROTATION, a.CREATED, " +
            "a.LAST_MODIFIED FROM FIELDS a, INTERESTS b " +
            "WHERE a.FARM_ID = :farmId AND a.ID = b.FIELD_ID AND b.ORGANIZATION_ID = :organizationId " +
            "ORDER BY NAME", Field.class)
            .setParameter("organizationId", organizationId)
            .setParameter("farmId", farmId)
            .getResultList(), Field.class);
    return fields;
}

}


text:
Q: How to use manual update in avira newest version I use Avira ( https://www.avira.com/en/ ) as my antivirus tool, sometimes online update may get an error, so I download virus definition files from websites and use manual update from its avcenter. it works well until some days before a new version was installed, from then on, GUI of old avcenter no longer exist , and only following GUI  can be started. I cannot find place to do manual update from local disk in this new GUI.
For everyone to see how the old GUI looked like: since I cannot trigger the exact old avcenter any more, so this is the configuration GUI which is somewhat like the old avcenter GUI
Before the update somedays ago ,I can still double-click "avcenter.exe" to open the old GUI but currently doing this still open the new GUI
Questions:
How can I do an manual update from local downloaded virus definition files in new GUI
AND if possible How to use the exact old GUI avcenter?

A: Yes, the new GUI is a bit convoluted, as it includes access to the additional modules (whether or not one uses them).
To manually update in this GUI, click on the underlined "Check for updates" in the panel to the right of "Status".
To reach the familiar GUI for the A-V itself (where all of the traditional settings can be found), click on the small gray gear in the lower-left corner.
These pages of questions & answers may also be useful:
https://support.avira.com/hc/en-us/sections/360000407197-Antivirus-for-Windows .

A: Perhaps this will address your need to update Avira manually, offline:  https://www.techspot.com/downloads/1510-avira-antivirus-definition-update.html .
As for the repository of quarantined items, you'll see the link in the left-hand column of this screenshot (fourth from the top):

A: Apparently, the old ("classic") GUI from about five years ago or so, and previous to that, has been completely replaced by what we're dealing with now, unfortunately. (FWIW, Malwarebytes "improved their GUI with version 4xx a few months ago, of which many of us are not particularly enamored.)
Sorry that I was not able to provide the solution you are seeking.
Perhaps you might try communicating with Avira directly, by contacting their customer service address.
Good luck! (And if you do discover a useful answer, please be sure to post it.)
All the best.


text:
Q: Google OAuth2 login with youtube scope I am using google's OAuth2 login system (php library) and I want to get user's real email address as well as details for his youtube channel (with his permission).
I have tried using the following scopes:
https://www.googleapis.com/auth/userinfo.email
https://www.googleapis.com/auth/userinfo.profile
https://www.googleapis.com/auth/youtube.readonly

but the returned email address has the format: @pages.plusgoogle.com (which is not the real email address).
If I use only the two scopes:
https://www.googleapis.com/auth/userinfo.email
https://www.googleapis.com/auth/userinfo.profile

I am able to get the real address but I cannot access any youtube data.
I have also tried to use two different requests to google api. The first to grab the user info and a second one to get youtube related details. In this case the problem is that I do not have a unique key value to identify the user as the same person on my side (an ID or something to identify a user uniquely).
I believe my problem is related to this question:
Google OAuth2 Login - Get YouTube nickname and real email address
Any help would be appreciated.


text:
Q: Can StyleCop provide a warning if someone does a new on an object that should be dependency injected? We're considering, as a company, adopting StyleCop to enforce C# style guidelines.
One problem we occasionally see is that developers will new up an object of a class that really should have been injected as an interface.
Our standard practice is that classes with behavior should be wrapped by interfaces and should be injected, so that they can be mocked in unit tests.
And that the only classes that should ever be constructed with new, outside the container configuration, are plain, data-only classes.
My question is whether this is something that StyleCop's rules can catch for us - catching instances of calling new on a class that has methods.


text:
Q: CentOS 5 Start a PHP Script on startup We have a CentOS 5 VPS over at slicehost. I have a couple of PHP scripts that operate email and stuff.
I need a way to start these php scripts automatically on machine's reboots/startups and have them run in the background. A bonus would be to have the ability to auto restart if the script is stopped.
thanks!

A: You could try adding the script to /etc/rc.local that should start them when you reboot.
php /mypath/startupscript &

If you need them to auto restart then you probably need to write out a pid file or something and monitor them with a cronjob. Not sure if using php for a long running system management process is that great of an idea.

A: Most *nix allow @reboot as the time/date in crontab to execute when the server restarts.

A: You could add a couple of startup scripts: Below is the basic of what I would use
#!/bin/bash
# chkconfig 2345 35 80
# Description: one line description
# I'd also insert a longer description of the
# scripts here.

# set any environment variables that might be needed here, too.
su - <target_user> /path/to/php /mypath/startupscript &

In keeping with least privilege, you'll want to replace  with the user you want the script to run as. If you want it to be root, then your php interpreter will need to be setUID and owned by root, but then you can remove "su - " entirely.


text:
Q: The "touch" command is either mispelled or could not be found on git command on windows I am trying to run the below command:
"touch hello.html"
The error I am getting is: "touch command is either mispelled or could not be found"
I tried- "npm install touch-cli -g"
Please can you help me here ?

A: I would recommend you to use GitBash to execute this such commands. In git bash commands such "touch", "vim", "nano" etc. should work without having to install them separate.
Otherwise, try to restart your system and check if the npm global directory is in your path environment variable.


text:
Q: Reading data from json_encode (php) in Objective C I am reading data from the MySQL database with using a querystring in my website url.
Example: www.test.com/user.php?username=mike

I read data from the database that belongs to the username (in this example: mike).
This is my PHP file which does that:
$result=mysql_query("SELECT LOWER(username) AS username FROM user WHERE username = '$username'");

$rows = array();

while($row = mysql_fetch_assoc($result)){
    $rows[] = $row;
}

echo json_encode($rows);

This PHP file returns:
[{"username":"mike"}]

The data that has been read is showing correctly like how a JSON file should be.
Afer this, I want to read the JSON value in Objective C (xcode).
I try to read that value from JSOn in Objective C as below:
- (void) loadJsonData
{

NSString *stringLink = [NSString stringWithFormat:@"http://www.test.com/user.php?username=%@", self.txtUsername.text];
NSURL *url = [NSURL URLWithString: stringLink];

    [AFJSONRequestOperation addAcceptableContentTypes:[NSSet setWithObject:@"application/x-javascript"]];

    NSURLRequest *request = [NSURLRequest requestWithURL:url];

    AFJSONRequestOperation *operation = [AFJSONRequestOperation JSONRequestOperationWithRequest:request     success:^(NSURLRequest *request, NSHTTPURLResponse *response, id JSON) {

        [self parseJSONData:JSON];

    } failure:^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error, id JSON) {
        NSLog(@"Error :%@",response);
    }];

    [operation start];
}

-(void) parseJSONData:(id) JSON
{
    [self.loginArray removeAllObjects];

    if(JSON != NULL)
    {
        for (NSDictionary* dict in JSON) {

            User *user = [[User alloc] init];

            user.username = [dict objectForKey:@"username"];

            [self.loginArray addObject:user];
        }
    }
}

But this code doesn't read the value from the JSON.
But when I create a .JSON file (I call it "test.json") and I save this data into that file: [{"username":"mike"}] and I change the URL in the Objective C code to www.test.com/test.json, then my Objective C code reads the value....
So when I create a .JSON file, my Objective C code reads the data.
But when I want to read directly from the PHP file, my Objective C code doesn't read the data.
Can someone help me, or explain me why this code doesn't read from the PHP file? I'm encoding JSON too in the PHP file.
Thanks in advance.

A: I had the same problem once, and found out that my PHP was not returning UTF8 encoded JSON. Could this be your problem, too?


text:
Q: Run PHP file which contains curl
Possible Duplicate:
how to enable php curl for use in php cli

I am running a file which containing curl function. When i run in command prompt i am getting below error.
test.php
<?php
echo "Hai";

$url="http://www.google.com/";
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,$url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
$str = curl_exec($ch);
curl_close($ch);
echo $str;
?>

Command : C:\>test>php test.php
Fatal error:  Call to undefined function curl_init()
When i run in web browser its running fine.
Information i got
<?php
dl("php_curl.dll");
...
?>

Not solved still

A: Probably you have different configuration for web servers and cli...
Try checking if there is more php.ini files in your filesystem

A: This will happen when the curl extension is not enabled for command line PHP.
Check whether it is enabled or not in the /etc/php5/cli/php.ini file
This is the specific php.ini file for command line PHP.

A: It seems that curl has not been installed as your PHP extension.

A: You need the cURL library in order to run cURL commands from the command prompt. Try using Cygwin, or download the cURL executable. You can find it here: http://curl.haxx.se/dlwiz/?type=bin