text:
Q: Scaled figure multiplied by perspective matrices gives an incorrect figure I have a grid. Which should be in 3d space. The grid must be dimensionless. That is, when the camera is rotated 90 degrees in x, the edge of the grid should not be visible. To solve the problem, before multiplying by the look at and perspective matrix, I increase it in scale, that is:
scale grid
matrix representation:
typedef std::array<std::array<double, 4>, 4> M4x4;

I implemented the code for working with matrices:
        M4x4 Matrix::multiply(const M4x4 &a, const M4x4 &b)
    {
        M4x4 m;
        for (int i = 0; i < 4; i++) {
            for (int j = 0; j < 4; j++) {
                m[i][j] = a[i][0] * b[0][j] +
                        a[i][1] * b[1][j] +
                        a[i][2] * b[2][j] +
                        a[i][3] * b[3][j];
            }
        }

        return m;
    }

    M4x4 Matrix::getTranslation(double dx, double dy, double dz)
    {
        return {
            std::array<double, 4>{1, 0, 0, dx},
            std::array<double, 4>{0, 1, 0, dy},
            std::array<double, 4>{0, 0, 1, dz},
            std::array<double, 4>{0, 0, 0, 1}
        };
    }

    M4x4 Matrix::getLookAt(const Vector &eye, const Vector &target, const Vector &up)
    {
        Vector vz = Vector::substruct(eye, target).normalize();
        Vector vx = Vector::crossProduct(up, vz).normalize();
        Vector vy = Vector::crossProduct(vz, vx).normalize();

        CoorVector eyeCoor = eye.getCoorVector();
        CoorVector vzCoor = vz.getCoorVector();
        CoorVector vxCoor = vx.getCoorVector();
        CoorVector vyCoor = vy.getCoorVector();

        M4x4 m = {
            std::array<double, 4>{vxCoor.x, vxCoor.y, vxCoor.z, 0},
            std::array<double, 4>{vyCoor.x, vyCoor.y, vyCoor.z, 0},
            std::array<double, 4>{vzCoor.x, vzCoor.y, vzCoor.z, 0},
            std::array<double, 4>{0, 0, 0, 1}
        };

        return Matrix::multiply(
                    Matrix::getTranslation(-eyeCoor.x, -eyeCoor.y, -eyeCoor.z),
                    m
                    );
    }

    M4x4 Matrix::getGeneralScale(double val)
    {
        return {
            std::array<double, 4>{1, 0, 0, 0},
            std::array<double, 4>{0, 1, 0, 0},
            std::array<double, 4>{0, 0, 1, 0},
            std::array<double, 4>{0, 0, 0, 1 / val}
        };
    }

    M4x4 Matrix::getScale(double sx, double sy, double sz)
    {
        return {
            std::array<double, 4>{sx, 0, 0, 0},
            std::array<double, 4>{0, sy, 0, 0},
            std::array<double, 4>{0, 0, sz, 0},
            std::array<double, 4>{0, 0, 0, 1}
        };
    }

    M4x4 Matrix::getRotationZ(double angle)
    {
        return {
            std::array<double, 4>{std::cos(angle), -std::sin(angle), 0, 0},
            std::array<double, 4>{std::sin(angle), std::cos(angle), 0, 0},
            std::array<double, 4>{0, 0, 1, 0},
            std::array<double, 4>{0, 0, 0, 1}
        };
    }
Vector Matrix::multiplyVector(const M4x4 &m, const Vector &v)
{
    CoorVector coorV = v.getCoorVector();

    return Vector({
                      m[0][0] * coorV.x + m[0][1] * coorV.y + m[0][2] * coorV.z + m[0][3] * coorV.w,
                      m[1][0] * coorV.x + m[1][1] * coorV.y + m[1][2] * coorV.z + m[1][3] * coorV.w,
                      m[2][0] * coorV.x + m[2][1] * coorV.y + m[2][2] * coorV.z + m[2][3] * coorV.w,
                      m[3][0] * coorV.x + m[3][1] * coorV.y + m[3][2] * coorV.z + m[3][3] * coorV.w
                  });
}

M4x4 Matrix::getPerspectiveProjection(double fovy, double aspect, double n, double f)
{
    const double PI  = 3.141592653589793238463;
    const double radians = PI / 180 * fovy;
    const double sx = (1 / std::tan(radians / 2)) / aspect;
    const double sy = (1 / std::tan(radians / 2));
    const double sz = (f + n) / (f - n);
    const double dz = (-2 * f * n) / (f - n);

    return {
        std::array<double, 4>{sx, 0, 0, 0},
        std::array<double, 4>{0, sy, 0, 0},
        std::array<double, 4>{0, 0, sz, dz},
        std::array<double, 4>{0, 0, -1, 0}
    };
}

M4x4 Matrix::getFrustum(double left, double right, double bottom, double top, double near, double far)
{
    return {
        std::array<double, 4>{2 * near / (right - left), 0, (right + left) / (right - left), 0},
        std::array<double, 4>{0, 2 * near / (top - bottom), (top + bottom) / (top - bottom), 0},
        std::array<double, 4>{0, 0, -(far + near) / (far - near), -2*far*near/(far- near)},
        std::array<double, 4>{0, 0, -1, 0}
    };
}

vector representation:
struct CoorVector {
    double x = 0;
    double y = 0;
    double z = 0;
    double w = 1;
};

Working with vectors:
Vector Vector::substruct(const Vector &v1, const Vector &v2)
{
    CoorVector coorV1 = v1.getCoorVector();
    CoorVector coorV2 = v2.getCoorVector();
    return Vector({coorV1.x - coorV2.x, coorV1.y - coorV2.y, coorV1.z - coorV2.z, 1});
}

Vector Vector::crossProduct(const Vector &v1, const Vector &v2)
{
    CoorVector coorV1 = v1.getCoorVector();
    CoorVector coorV2 = v2.getCoorVector();
    return Vector({coorV1.y * coorV2.z - coorV1.z * coorV2.y,
                  coorV1.z * coorV2.x - coorV1.x * coorV2.z,
                   coorV1.x * coorV2.y - coorV1.y * coorV2.x});
}

double Vector::getLength()
{
    return std::sqrt(
                coorV.x * coorV.x + coorV.y * coorV.y + coorV.z * coorV.z
                );
}

Vector Vector::normalize()
{
    const double length = getLength();

    coorV.x /= length;
    coorV.y /= length;
    coorV.z /= length;

    return *this;
}

CoorVector Vector::getCoorVector() const
{
    return coorV;
}

And I use matrices to multiply the vertices when drawing:
void Grid::customMatrixFrustum(QPainter &p)
{
    M4x4 m = Matrix::getRotationZ(degreesToRadians(gridData.rotationZ));

    //does not work with getPerspectiveProjection function
    double scale = gridData.scale;
    m = Matrix::multiply(
                Matrix::getScale(scale, scale, scale),
                m);
    //or
    //    m = Matrix::multiply(
    //                Matrix::getGeneralScale(scale),
    //                m);

    m = Matrix::multiply(
                Matrix::getTranslation(0, 0, gridData.height),
                m);

    m = Matrix::multiply(
                Matrix::getLookAt(
                    Vector({0, 0, 0, 1}), // where is the observer
                    Vector({-degreesToRadians(gridData.x), degreesToRadians(gridData.y), -1, 1}), // where to look
                    Vector({0, 1, 0, 1})
                    ),
                m);

    m = Matrix::multiply(
                Matrix::getPerspectiveProjection(
                    90, 1, -1, -1000),
                m);

    m = Matrix::multiply(
                Matrix::getFrustum(-1, 1, -1, 1, -1, -1000),
                m
                );

    //doesn't work as it should. the camera's view goes beyond the grid.
    //    m = Matrix::multiply(
    //                Matrix::getScale(scale, scale, scale),
    //                m);

    QList<Vector> sceneVertices;
    for (int i = 0; i < vertices.size(); i++) {
        Vector vertex = Matrix::multiplyVector(
                    m,
                    vertices[i]);

        CoorVector coorVertex = vertex.getCoorVector();
        coorVertex.x = coorVertex.x / coorVertex.w * (this->width() / 2);
        coorVertex.y = coorVertex.y / coorVertex.w * (this->width() / 2);

        sceneVertices.append(Vector({coorVertex}));
    }

    for (int i = 0, l = edges.size(); i < l; i++) {
        std::array<int, 2> e = edges[i];

        CoorVector coorP1 = sceneVertices[e[0]].getCoorVector();
        CoorVector coorP2 = sceneVertices[e[1]].getCoorVector();

        if (e[0] == 2 && e[1] == 3) {
            qDebug() << "points:" << e[0] << e[1]
                    << coorP1.x << coorP1.y << coorP1.w
                    << coorP2.x << coorP2.y << coorP2.w;

            qDebug() << "lines:" << e[0] << e[1]
                    << QPoint(coorP1.x + this->width() / 2, -(coorP1.y - this->height() / 2)) << coorP1.w
                    << QPoint(coorP2.x + this->width() / 2, -(coorP2.y - this->height() / 2)) << coorP2.w;
        }
        p.drawLine(coorP1.x + this->width() / 2, coorP1.y + (this->height() / 2),
                   coorP2.x + this->width() / 2, coorP2.y + (this->height() / 2));
    }
}

I create mesh vertices using the following algorithm:
void Grid::init()
{
    //create vertices - points
    countHorizontal = 100;//number of cells horizontally (counting from top to bottom)
    countVertiacal = 100;//number of cells vertically (counting from left to right)
    const int pointHorizontal = countHorizontal * 2 + 2;
    const int pointVertiacal = countVertiacal * 2 - 2;
    const int pointCount = pointHorizontal + pointVertiacal;
    const double intervalHorizontal = 2 / (double)countHorizontal;
    const double intervalVertical = 2 / (double)countVertiacal;
    double currentIntHor = 1;// Descent from top to bottom
    double currentIntVer = -1 + intervalVertical;//descent from left to right
    for (int i = 0; i < pointCount; ++i) {
        if (i < pointHorizontal) {
            if (i % 2) {
                vertices.append(Vector({1, currentIntHor, 0, 1}));//performed second
                currentIntHor -= intervalHorizontal;
            } else {
                vertices.append(Vector({-1, currentIntHor, 0, 1}));//runs first
            }
        } else {
            if (i % 2) {
                vertices.append(Vector({currentIntVer, -1, 0, 1}));//performed second
                currentIntVer += intervalVertical;
            } else {
                vertices.append(Vector({currentIntVer, 1, 0, 1})); //runs first
            }
        }
    }

    //Create pairs of vertex indices for lines
    const int vertical = countHorizontal + 1;
    const int horizontal = countVertiacal + 1;
    for (int i = 0; i < vertical; ++i) {
        edges.append({i*2, i*2 + 1});
    }
    const int lastHorIndex = edges.size() - 1;
    std::array<int, 2> lastHorVal = edges[lastHorIndex];
    for (int i = 0; i < horizontal; ++i){
        if (i == 0) {//first line
            edges.append({0, lastHorVal[0]});
        } else if (i == horizontal - 1) {//last line
            edges.append({1, lastHorVal[1]});
        } else {
            const int magic = 2 * i;
            edges.append({lastHorVal[1] + magic - 1, lastHorVal[1] + magic});
        }
    }
}

In the figure it looks like this:
create grid
With a scale of 3 and a camera angle of 90 degrees in x, the grid looks like this:
norm grid
When you increase the camera rotation in x by 1 degree, the grid already breaks:
broken grid
And if you increase the scale of the grid, then the angle of rotation of the camera when drawing the grid becomes smaller. I assume that the problem is with the w factor, since it does not change for the better when the grid is scaled up. And I don't know how to change it so that the grid after scaling and perspective is drawn normally.
I posted the problem code on github:
grid project
P.S. I tried QMatrix4x4 but when passing the values from the example, perspective didn't work. If someone solves my problem through QMatrix4x4 I will be glad.


text:
Q: Copy files to a Laptop I have an urgent requirement to copy files from one laptop to another laptop which are not connected in any way.
Is there any way of doing this?

A: Here are some ideas, what if any work for you depends on what you're willing to do.

*

*laplink type connection(with laplink s/w)

*mini-network via ethernet (desktop &laptop)

*USB port network

*flash drives

*burn to DVD or CD

*use www service to FTP data

*use ext. HD via USB or firewire
These do work, but again it depnds on s/w or h/w and/or purchases you need to get.

A: I believe the fastest way to copy files is to connect them directly using Ethernet cable. Second option I'd choose is to use external USB hard disk.

A: If they are newish machines then a direct connection via an ethernet cable will work fine - if the light comes on at both ends then you are fine.  If it does not then you will need to use a cross-over cable or 2 cables and a network hub such as your broadband router.
Once you have a connection you can just share a folder or dirve from one to another using windows file sharing - look in network neighbourhood for the other machine.
C.

A: If both machines are connected to the Internet, you can use Gmail.
See the GMail Ddrive shell extension:

GMail Drive is a Shell Namespace
  Extension that creates a virtual
  filesystem around your Google Mail
  account, allowing you to use Gmail as
  a storage medium.

A: I'd set up an adhoc wireless network between them then copy that way. You'll get 54Mbps transfer rate if they are close, which depending on the amount of data you are sending may or may not be acceptable.

A: Lots of methods are mentioned in other posts, the two I'd chose are to create a small network (crossover or ad-hoc wireless), or to use an external hard disk.
As a last resort - take the hard drives out of both laptops, connect them to another machine (using a usb bridge if needed), and copy the file from there.

redpajama_set_name: RedPajamaStackExchange


text:
Q: AWS AppSync Subscriptions Without Websockets While testing our new webapp that uses AWS's AppSync for the GraphQL backend, we discovered that some of our customers have corporate networks that block websockets. Is there any way to use AppSync subscriptions (we also use AWS Amplify) without websockets?
It would be great to use subscriptions instead of building a polling fallback, but that looks like the only option.

A: Currently AppSync does it only through web-sockets.
This is interesting can you please open an issue to the AppSync Community repository here: awsAppSync.dev
I have also passed the request to the team.


text:
Q: How to use dropdownmenu with sharedpref in flutter I tried to use dropdownbutton, to select a text in a menu and display it. After I send sms with the selected text. to finish I  tried to save the value with sharedpref to display text after app close. To this I upload sharedpref in the init state. But I have an error :
     failed assertion line 481 pos 15: value==null||items.where((DropdownMenuItem<T>
     item) => item.value == value).length == 1: is not true.

Here is my dropdownbutton block:
                                      new DropdownButton<String>(

                                        onChanged: (String changedValue) {
                                          selectedText=changedValue;
                                          setState(() {
                                            selectedText;

                                          });
                                        },
                                        value: selectedText,
                                        items: <String>['1', '2', '3','4', '5', '6','7', '8', '9']
                                            .map((String value) {
                                          return new DropdownMenuItem<String>(
                                            value: value,
                                            child: new Text(value),
                                          );
                                        }).toList()),

Here is my sharedpref block :
 _savevaluesonnerie() async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
      setState(() {
      prefs.setString('counter305', selectedText);
     });
   }

  _loadvaluesonnerie() async {
     SharedPreferences prefs = await SharedPreferences.getInstance();
      setState(() {
      selectedText = (prefs.getString('counter305')) ??"" ;
   });
   }

I call this sharedpref block in an Initstate to display the saved value
 @override
  void initState() {
   super.initState();

   _loadvaluesonnerie();
  }

Thank you

A: As you are using async function _loadvaluesonnerie() to set the selectedText, until it finishes, selectedText will be null.
Can you set some default value like '1' (which is first item in items) as initial value for selectedText?
Will that work for you?


text:
Q: Taking Some Element in a Paricular Order In JavaScript I have an object like the below, i want to map this array in a particular order like,
Argentina, Chilean, United States
1: {label: 'Turkish Lira', flag: 'TR', id: 1, code: 'TRY', symbol: '₺', …}
2: {label: 'United States Dollar', flag: 'US', id: 2, code: 'USD', symbol: '$', …}
3: {label: 'Argentina Peso', flag: 'AR', id: 3, code: 'ARS', symbol: '$', …}
4: {label: 'Bahraini Dinar', flag: 'BH', id: 4, code: 'BHD', symbol: ' BD', …}
5: {label: 'Brazilian Real', flag: 'BR', id: 5, code: 'BRL', symbol: ' R$', …}
6: {label: 'Bulgarian Lev', flag: 'BG', id: 6, code: 'BGN', symbol: ' лв', …}
7: {label: 'Chilean Peso', flag: 'CL', id: 7, code: 'CLP', symbol: '$', …}

How can i do that?

A: Given you have a list of items you want to sort, called items.
You have a list of indexes, such as [0, 4, 2, 1, 3]
You can indexes.map(i => items[i]);

var items = [{
    label: 'Turkish Lira',
    flag: 'TR',
    id: 1,
    code: 'TRY',
    symbol: '₺'
  }, {
    label: 'United States Dollar',
    flag: 'US',
    id: 2,
    code: 'USD',
    symbol: '$'
  },
  {
    label: 'Argentina Peso',
    flag: 'AR',
    id: 3,
    code: 'ARS',
    symbol: '$',
  },
  {
    label: 'Bahraini Dinar',
    flag: 'BH',
    id: 4,
    code: 'BHD',
    symbol: ' BD'
  },
  {
    label: 'Brazilian Real',
    flag: 'BR',
    id: 5,
    code: 'BRL',
    symbol: ' R$'
  },
  {
    label: 'Bulgarian Lev',
    flag: 'BG',
    id: 6,
    code: 'BGN',
    symbol: ' лв'
  },
  {
    label: 'Chilean Peso',
    flag: 'CL',
    id: 7,
    code: 'CLP',
    symbol: '$'
  }
]

var indexesList = [3, 5, 0, 2];

function sortByIndex(list, indexes) {
  return indexes.map(i => items[i]);
}

console.log(sortByIndex(items, indexesList));

A: You can use javascript array sort

const array = [{
  label: 'Turkish Lira',
  flag: 'TR',
  id: 1,
  code: 'TRY',
  symbol: '₺'
}, {
  label: 'United States Dollar',
  flag: 'US',
  id: 2,
  code: 'USD',
  symbol: '$'
}, {
  label: 'Argentina Peso',
  flag: 'AR',
  id: 3,
  code: 'ARS',
  symbol: '$'
}]

function sortBy(a, b) {
  if (a.label < b.label) {
    return -1;
  }
  if (a.label > b.label) {
    return 1;
  }
  return 0;
}

console.log(array.sort(sortBy));

If you want a generic functionality then you can do this.

const array = [{
  label: 'Turkish Lira',
  flag: 'TR',
  id: 1,
  code: 'TRY',
  symbol: '₺'
}, {
  label: 'United States Dollar',
  flag: 'US',
  id: 2,
  code: 'USD',
  symbol: '$'
}, {
  label: 'Argentina Peso',
  flag: 'AR',
  id: 3,
  code: 'ARS',
  symbol: '$'
}]

const sortBy = (attribute) => (a, b) => {
  if (a[attribute] < b[attribute]) {
    return -1;
  }
  if (a[attribute] > b[attribute]) {
    return 1;
  }
  return 0;
}

console.log(array.sort(sortBy('label')));
console.log(array.sort(sortBy('code')));


text:
Q: Striped Volume problems in Windows 8 Recently reinstalled my computer with the final release of Windows 8, and to celebrate this, moved all the important data from my 2 pieces of 1TB HDDs (a Samsung HD103SI and a Western Digital WD10EARS-005B1 Green Caviar), converted both to GPT and Dynamic, and created a striped volume across the two disks. After this, I created an overlapping 2TB partition, for my downloads (storing Ubuntu images, my school DreamSpark installers, etc.).
It was working fine, until today, during a heavy P2P download of a Debian collection, the drive suddenly became unavailable. First I thought maybe some Windows bug, as it used to happen, so I rebooted. No, the drive was still unavailable, so checked it under Disk Manager. The so far perfectly working NTFS partition somehow is now unrecognized, RAW, and I cannot access my data.
Is there any way to restore the partition somehow? I have some very important data there, and it would be quite a cutback if I lost all those documents, not to mention the mass amount of (kinda retro or vintage) collection of old Linux installers.

A: It's too late for you now (obviously), but for anyone in the future:
Try using a Linux boot disc to recover the contents.
While Windows is a bit unforgiving when it encounters "bad stuff", Linux thrives on chaos.
Ramhound is oversimplifying the issue as a complete loss...
If the hard drive is completely dead (clickity-click, etc.) then you are likely out of luck.
However, if the drive is failing but still responds to the underlying hardware commands (ATA, etc.) then a Linux boot disc may be able to recover a relatively large amount of your contents.
You'll probably need an attached USB to use as a destination (because you can't trust the failing drives).
Only the file segments that happen to overlap with the failed sectors will be lost. The files that are adjacent or even far away from the bad sectors will be unaffected by the failure and their stripes will be accessible/recoverable.


text:
Q: Is it possible to make a declarative sentence starting with 'Can'? everyone
As the title shows, is it possible to make a declarative sentence starting with "Can"?
For example, 'Please, can we request that you do not accept any proposals from him.'
The reason why I ask this question is that I saw the example sentence, which is written in an official document made by a British writer. As you see, there is no question mark (?) at the end of the sentence, so I thought it was a typo at first glance. But it was not.

A: Your example sentence is more nearly imperative than declarative, but whatever terminology you apply to it, it isn't a normal interrogative form, and—at least according to The Chicago Manual of Style, sixteenth edition (2010)—it doesn't have to end in a question mark:

6.69 Requests as questions. A request disguised s a question does not require a question mark. Such formulations can usually be reduced to the imperative.

Would you kindly respond by March 1.
or
Please respond by March 1.

If I recall correctly, an earlier edition of Chicago provided as an example the evocative expression, "Will the congregation please rise." Evidently, the speaker in that case has no doubt that they will.

A: Of course we can do so:

"Can" is a modal auxiliary verb.
Can pigs fly is a question that puzzles me.

However, you are probably interested in situations in which "can" is not used qua a word, in quoted text, within a subordinate clause, etc. In that case, there is only one situation that I know of in which the verb "can" can appear as the first word of a declarative clause, and that is with exclamatory expressions. For example:

"Can she swim?"
"Can she ever!"

(Note that I would say that your example sentence includes a clause of the interrogative type despite lacking a question mark. Terminology often varies.)

A: Specifically, if the subject is after "can"  it's a question and should end with a question mark.

Can you use the phone?
If the subject is before "can" then it's not a question and is a statement most of the time. It should therefore end with a full stop or an exclamation mark.
You can use the phone.

There are loopholes which will allow you to get around this general rule such as quoting Can instead of actually using it, as mentioned in another answer:

Can pigs fly is a question that puzzles me.

But I don't think this would count as a correct answer.
And of course you could use "can" as an object and you can easily put that into a declarative sentence:

Can-throwing is not allowed in the building


text:
Q: Publish local GIT repo to TFS I've been following the tutorial here : http://www.visualstudio.com/en-us/get-started/share-your-code-in-git-vs.aspx to try and use our local GIT repo as the source control for TFS.
In that tutorial, there is an option to "Publish your repository into your team project". But in my VS 2013 Express (and Ultimate) there is no such option.
Does anyone know how to accomplish this?

A: Because you created the local repo, instead of cloning the one from Team Project? In that case you must set the TP URL as the remote repo of your local repo.
In other words Git must become aware of the relationship between repositories.


text:
Q: How to write unit test for http request with Alamofire? My app is using Alamofire to send http request and wanna write some unit test for this part. I have created some json file as response. How can I block the Alamofire request and let Alamofire to return the content in json file as response? Can we use method swizzling to replace the function?

A: This is how you wait for some asynchronous callbacks. This is bare minimum test. You can improve it more for your test requirement
func testCheckThatTheNetworkResponseIsEqualToTheExpectedResult() {

    //expected result
    let expectedResult: [String:Any] = ["data":"somedata","order_number":2]

    let expectations = expectation(description: "The Response result match the expected results")

    if let requestUrl = URL(string: "some url to fetch data from") {

        let request = Alamofire.request(requestUrl, method: .get, parameters: nil, encoding: URLEncoding.default, headers: nil)
        request.responseJSON(completionHandler: { (response) in
            switch response.result {
            case .success(let result):
                //do the checking with expected result
                //AssertEqual or whatever you need to do with the data
                //finally fullfill the expectation
                expectations.fulfill()
            case .failure(let error):
                //this is failed case
                XCTFail("Server response failed : \(error.localizedDescription)")
                expectations.fulfill()
            }
        })

        //wait for some time for the expectation (you can wait here more than 30 sec, depending on the time for the response)
        waitForExpectations(timeout: 30, handler: { (error) in
            if let error = error {
                print("Failed : \(error.localizedDescription)")
            }

        })
    }

}

A: Use a framework like OHHTTPStubs to stub you network requests or make real network requests. In either case, XCTest has a variety of methods for asynchronous waiting, like XCTExpectations.


text:
Q: Django-wiki not syncing database On a brand new project that's sole purpose is to test if I'm doing everything correct, this https://github.com/benjaoming/django-wiki module works fine, bet as I'm trying to attach it to my main app, it shows this error when I'm runing python manage.py syncdb: django.core.exceptions.ImproperlyConfigured: ImportError wiki.plugins.attachments: No module named plugins.attachments - can you please tell me why and how can I fix that?
Also - why did I get a downvote for this question?

A: You have to list the plugins in your INSTALLED_APPS as well, see:
https://github.com/benjaoming/django-wiki#configure-settingsinstalled_apps
So your INSTALLED_APPS should contain, in this order:
'django.contrib.humanize',
'south',
'django_notify',
'mptt',
'sekizai',
'sorl.thumbnail',
'wiki',
'wiki.plugins.attachments',
'wiki.plugins.notifications',
'wiki.plugins.images',
'wiki.plugins.macros',

EDIT:
I'd suggest re-installing the wiki package.
# pip uninstall wiki
# pip install wiki


text:
Q: How to create a formula based on some conditional formatted cells using VBA I have the following situation:
I formatted using FormatConditions a range to show the style "Good" if the values within the range are between -2 and 2 and the style "Bad" if not, using this code:
With Range("D46:AC53")
        .FormatConditions.Add Type:=xlExpression, Formula1:= _
          "=IF(AND(D46<2,D46>-2),TRUE,FALSE)"
        With .FormatConditions(.FormatConditions.Count)
            .SetFirstPriority
            With .Interior
                .PatternColorIndex = xlAutomatic
                .Color = RGB(198, 239, 206)
                .TintAndShade = 0
            End With
        .Font.Color = RGB(0, 98, 0)
        End With
       .FormatConditions.Add Type:=xlExpression, Formula1:= _
          "=IF(AND(D46<2,D46>-2),FALSE,TRUE)"
        With .FormatConditions(.FormatConditions.Count)
            .SetFirstPriority
            With .Interior
                .PatternColorIndex = xlAutomatic
                .Color = RGB(255, 199, 206)
                .TintAndShade = 0
            End With
        .Font.Color = RGB(156, 0, 6)
        End With
    End With

This is working great.
Now, I would like to create a macro button that will define that if all the range "D46:AC53" is "Good" to show the value "TRUE" in a specific cell. I used this code:
If Range("D46:AC53").Interior.Color = RGB(198, 239, 206) Then Range("c3").Value = "TRUE" Else Range("c3").Value = "FALSE"

Even the range D46:AC53 looks as "Good" the button returns me "FALSE".
Can you please help me? What am I doing wrong?
Thanks,
Alexandra
I checked the fill color on the range formatted using the first code using right-click and Format Cells and it's showing me as not being filled. I manually formatted the Range D46:AC53 using the Style "Good" from Styles in Excel and that makes the button macro works.

A: I think you need this, as per my comment above.
If WorksheetFunction.CountIfs(Range("D46:AC53"), "<2", Range("D46:AC53"), ">-2") = Range("D46:AC53").Count Then
    Range("c3").Value = "TRUE"
Else
    Range("c3").Value = "FALSE"
End If


text:
Q: Replace for loop with linq using any I have the following code in typescript:
public executeTest(test: Test): void {
    const testFilters: Record<string> = getTestFilters();
    let isTestingRequired: boolean = false;

    for (let i: number = 0; i < testFilters.length; i++) {
        if(test.Name === testFilters[i].Name){
            isTestingRequired = true;
            break;
        }
    }
}

I am trying to replace the above for loop using LINQ as below, however I am getting errors.
let isTestingRequired: boolean = testFilters.any((filter.): boolean => {
    return filter.Name  === test.Name
});

A: You will need to make your array enumerable first using Enumerable.from() like this:

var array = [{name: "John"}, {name: "Test"}];

var result = Enumerable.from(array)
  .any(obj => obj.name == "Test");

console.log(result)
<script src="https://cdnjs.cloudflare.com/ajax/libs/linq.js/3.2.4/linq.min.js"></script>


text:
Q: Is there any way to read numpy array in Azure Blob Storage in python? I would like to read the numpy array stored in Azure Blob Storage from python code in Azure functions. I am not being able to do it. I tried with BlockBlobService but couldn't succeed.
Looking for help/suggestions.

A: The simple solution is to use Azure Storage SDK for Python to download the blob content to memory, then to use the function numpy.frombuffer to load the memory content of the blob as a 1-dimensional array and continous to do any operations as you want like reshape.
As reference, there is a SO thread numpy.load from io.BytesIO stream that be same as yours and I answered it with three sample codes for loading npy or npz format content from blob.
If you want to read a csv/json file from Azure Blob Storage, you also can generate a blob url with sas token, then to use the function pandas.read_csv or pandas.read_json with an url parameter of <blob url with sas token> to directly read the content of csv or json format as a pandas dataframe and then to convert it to a numpy array.


text:
Q: What is the maximum WiFi speed of iPhone 6s? I have a new broadband plan of 1000 Mbps been effective for a few days. With a new ac router claiming a max to 1300 Mbps, I have conducted a brief test with my SE. It was at 267 Mbps, far lower than I expect. I am going to test it with an iPhone 6s which may benefit with MIMO. What is the top WiFi speed that iPhone 6s supported?

A: All iPhone 6s models support 802.11a/b/g/n and ac Wi‑Fi with multiple input multiple output (MIMO).
The iPhone SE also supports 802.11a/b/g/n and ac Wi‑Fi (but without MIMO).
While you should get better speeds with the iPhone 6s, the reality is that there are many factors that can impact speed at any given point of time.
However, if my reading of your question is correct, I think it's based on a misunderstanding of what the ac router claiming a max speed of 1300 Mbps actually means. This 1.3Gbps (1300Mbps) figure can be highly misleading because it is a theoretical maximum. It translates to 166 megabytes per second (MBps) or about 1331 megabits per second (Mbps), which of course sounds fantastic, but these figures are never realised in real world scenarios.
Most 802.11ac routers will perform closer to a range of 250-300Mbit.
In terms of your devices, you'll find that the speed obtained by 802.11ac capable devices will differ considerably depending on how many antennas they can physically fit in. While the maximum supported by the 802.11ac standard is 8 antennas, most smartphones only have 1 antenna, most tablets will have between 2-4 antennas, and so on. Even 802.11ac routers will differ in terms of how many antennas they will incorporate.

A: If you are using a device that is 802.11n you will max out at about 450mbps as you will be on the 2.4ghz wifi signal, 5ghz wifi signal which will use 802.11ac will max out at 1.3gbps depending on your service.

A: We just had AT&T come install their 1000 Mbps fiber internet today.
They provided an Arris BGW210-700 gateway (router).
I was curious to first test just the speed of the wifi connection between the router and my iPhone 6S (i.e. ignore the speed of the WAN/fiber).
I used the Wi-Fi SweetSpots app and saw speeds from 429 to 478 Mbps.
This was slightly better than shown in this article that links to this video.
I currently have no devices that can plug directly into the gateway, so I can't test whether AT&T is actually supporting the full 1000 Mbps download and upload speeds (but clearly my iPhone would be the bottleneck on the speeds anyway)†.
When I tested my phone's internet connection through the router (using http://www.speedtest.net/mobile), I saw download and upload speeds ranging from 322 to 456 Mbps.
† The Arris BGW210-700 gateway itself has a speed test and claims that it is achieving 974 Mbps download and 938 Mbps upload.


text:
Q: Python Paramiko .put() isn't working as expected I'm working in Jupyter notebooks, trying to use Python to upload a CSV file to an SFTP server. The code runs without error but the file I'm expecting to appear never does.
import paramiko

server_path = 'this_bit_works'
local_path = './'+'my_file.csv'

try:
    t = paramiko.Transport((pFTPServer, pFTPport))
    t.connect(username=pFTPUserName, password=pFTPPassword)
    sftp = paramiko.SFTPClient.from_transport(t)
    sftp.put(local_path, server_path)
    files = sftp.listdir(server_path)    #Only here to check if it worked
    t.close()
    print(files)      #Only here to check if it worked
    print('success')

except Exception as e:
    print('Exception: '+str(e))

I've run this just to make sure the local path is right, and i get True.
local_path = './'+'my_file.csv'
print(exists(local_path))


text:
Q: source file not found according to gdb info source I am debugging a C application running with a dynamically linked shared library. The program runs well on Ubuntu 14.04 64 bit. But it generates segmentation fault on Ubuntu 16.04 when Linux terminates the shared objects upon exiting the application.
Inside gdb, I set a breakpoint right before the segmentation fault happens. Then I use info source to check the source file information:
Thread 1 "test" hit Breakpoint 3, _dl_fini () at dl-fini.c:201
(gdb) info source
Current source file is dl-fini.c
Compilation directory is /build/glibc-bfm8X4/glibc-2.23/elf
Located in /build/glibc-bfm8X4/glibc-2.23/elf/dl-fini.c
Source language is c.
Producer is GNU C11 5.4.0 20160609 -mno-mmx -mtune=generic -march=x86-64 -g -O2 -O3 -std=gnu11 -fgnu89-inline -fno-stack-protector -fmerge-all-constants -frounding-math -fPIC -ftls-model=initial-exec.
Compiled with DWARF 2 debugging format.
Does not include preprocessor macro info.

I am not able to find the indicated Compilation directory and the location of the source file.
Directory /build/glibc-bfm8X4/glibc-2.23/elf doesn't exist. Anyone has any idea of this situation?

A: That's the directory on the machine where the glibc was compiled. It doesn't exist on our machines.
Install the -dbg versions of the involved packages (using sudo apt-get install) - to get the debug symbols installed. Get the source code of the libraries (by using apt-get source) - to get the actual source files downloaded into the current directory.
For glibc it's sudo apt-get install libc6-dbg and apt-get source libc6
Useful commands:

*

*list all packages: dpkg -l (can then grep in the list for the specific package name)

*list files in a package: dpkg -L <package name>

*search for a package to which the file belongs to: dpkg -S <file path>
Use the directory <path to source dir> declarations in ~/.gdbinit to point gdb to the right directories with the source code.
Also, try valgrind and rr utilities.


text:
Q: false=="0" results as true, but !!"0" results as true Today while reading a blog on JavaScript, I came across the below example which seems odd to me. Please clarify.
As per my JavaScript knowledge !!"0" results true
But, the below statement result seems odd to me, and even I executed it in console which also returned true
false == "0" //results true
My interpretation of this statement is as below
"0" is treated as true, so the above statement can be rewritten as false == true, which must be resulted as false, but I am getting true as result. Please clarify.

A: When using ==, "0" is first type casted to it's number value, 0. And 0 == false.
When doing !!"0", it is not casted, and simply converts the string to a boolean, and since any non-empty string is truthy, it equals to true.


text:
Q: In Qt, how do I use Q_OBJECT slots and signals with multiple inheritance? I looked through the related questions and couldn't find anything that addresses exactly what I was talking about, so let me describe.
I have a class, let's say foo that needs to have its own slots and signals, but also needs to inherit from QXmlDefaultHandler (sounds rather odd, but I encountered this situation when trying to use QHttp to read a website directly into a QBuffer).
class foo: public QXmlDefaultHandler, public QObject
{
    public:
        foo();
        ~foo();

       Q_OBJECT
   public slots:
       void bar();
}

This code, if accompanied by a cpp to connect bar to a signal somewhere else, will not compile. You'll get errors about some members of QObject not being a member of QXmlDefaultHandler. Additionally, you can't move Q_OBJECT or else you get vtable errors for not implementing some things (go on! try it!).
please see my answer for the (very simple) fix. I will entertain voting you as the accepted answer if I think you explain it better than I do.
edit: for you c++ and Qt vets, please post an answer if you can explain it better. i spent quite a bit of time looking this info up, so please help someone else if you can do better than me.

A: class foo: public QObject, public QXmlDefaultHandler
{
    public:
        foo();
        ~foo();
   Q_OBJECT
   public slots:
       void bar();
}

As simple as it sounds, if you don't put QObject first in the inheritance list, this task is impossible. It's a limitation in Qt's meta object system. If you don't do this, the compiler will try to apply some members of QObject as part of QXmlDefaultHandler.

A: The documentation for moc states that in cases of multiple inheritance, the class providing QObject should appear first

If you are using multiple inheritance,
  moc assumes that the first inherited
  class is a subclass of QObject. Also,
  be sure that only the first inherited
  class is a QObject.
 // correct
 class SomeClass : public QObject, public OtherClass
 {
     ...
 };

Virtual inheritance with QObject is
  not supported.


text:
Q: Customization of existing smart errors We have customized error messages that do not match well with the list of errors described on https://developers.google.com/assistant/smarthome/reference/errors-exceptions. Is it possible to add additional errors to Smart Home or customize existing errors in any way?

A: The errors provided by the platform are tied to responses returned to the user through voice and touch Assistant surfaces. The platform does not currently provide a mechanism to customize these user-facing responses.
If you simply want to provide custom errors for the purposes of debugging, you can use the debugString field in an intent response to correlate this information in the cloud error logs for your project.


text:
Q: Tic Tac Toe: Winapi painting I am having trouble painting in my client area whenever I turn a bool true, trying to make a Tic Tac Toe, and once I get the initial painting properly I can keep going.
The main problem is that it is not painting the lower rows properly, or they are painted after a 3 or 4 click, At the moment I don't care about circles, just want to know what I am  have wrong.
LRESULT CALLBACK WndProc(HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam)
{
        static BOOL fState[DIVISIONS][DIVISIONS];
        bool  XorO = false;
        static int  cxBlock, cyBlock;`

        HDC         hdc;
        int         x, y, iPosX , iPosY;
        PAINTSTRUCT ps;
        RECT        rect;

        static const int grid = 1000;
        static const int block = grid / DIVISIONS;
        static const int width = 1200;
        static const int height =1200;

        switch (message)
        {
        case WM_SIZE:

                cxBlock = LOWORD (lParam) / DIVISIONS ;
                cyBlock = HIWORD (lParam) / DIVISIONS ;

            return 0;

        case WM_LBUTTONDOWN:
            x = LOWORD(lParam)/ cxBlock;
            y = HIWORD(lParam)/cyBlock;

            if (x < DIVISIONS && y < DIVISIONS)
            {
                //Click in the first cuadrant x = 0 and y = 0 , so both false
                //second x = 1, y = 0
                //third x 2 , y = 0 and so on.
                fState[x][y] ^= 1;
                rect.left = x * block;
                rect.top = y * block;
                rect.right = (x + 1) * block;
                rect.bottom = (y + 1) * block;

                InvalidateRect(hwnd, &rect, FALSE);

            }
            else
                MessageBeep(0);

            return 0;

        case WM_PAINT:

            hdc = BeginPaint(hwnd, &ps);

            //paint X or ellipses here
            for (x = 0; x < DIVISIONS; x++)
                for (y = 0; y < DIVISIONS; y++)
                {

                    if (fState[x][y] )
                    {
                        MoveToEx(hdc, x     * block, y       *  block, NULL);
                        LineTo(hdc,  (x + 1) * block, (y + 1) *  block);
                        MoveToEx(hdc, x     * block, (y + 1) *  block, NULL);
                        LineTo(hdc,  (x + 1) * block, y       *  block);
                    }
                }

            //main grid
            for (int i = block; i < grid - 1; i += block) {
                MoveToEx(hdc, i, 0, NULL);
                LineTo(hdc, i, grid);
                MoveToEx(hdc, 0, i, NULL);
                LineTo(hdc, grid, i);

            }

            EndPaint(hwnd, &ps);
            return 0;

        case WM_DESTROY:
            PostQuitMessage(0);
            return 0;
        }
        return DefWindowProc(hwnd, message, wParam, lParam);
    }

I even tried to make the painting more direct and primitive by making a single if statement for each scenario but, once the program runs , it does not paint correctly on the second and third line. or if I click space 2,2 (the last one on the grid) it does not paint until i click somewhere else...

A: You need to call SelectObject to select a suitable pen into the DC or else LineTo will randomly use whatever pen was leftover there (which might be invisible or something).


text:
Q: C++ Program crashes when executing object functions Here is part of the code:
class Inventory {
    public:
        void PrintInventory();
        void AddItemToInventory();
        void UpdateItemQtyInInventory();
        void RemoveItemFromInventory();
    private:
        vector<Item*> inventory;
};

void Inventory::PrintInventory() {
    unsigned int i = 0;
    if (inventory.size() == 0) {
        cout << "No items to print." << endl;
    } else {
        for (i=0; i < inventory.size(); ++i) {
            cout << i << " - ";
            inventory.at(i)->Print();
        }
    }
    return;
}

void Inventory::AddItemToInventory() {
    string usrInptName = "";
    string usrInptQntyStr = "";
    string usrInptPriceStr = "";
    string usrInptOptn = "default";
    istringstream inSS;
    int usrInptQnty = 0;
    int usrInptPrice = 0;
    string usrInptOther = "";
    bool valid = false;

    while (valid == false) {
        cout << "Enter (b)ook or (p)roduce: ";
        getline(cin, usrInptOptn);

        if (usrInptOptn.size() == 0) {
                continue;
        } else if (usrInptOptn.at(0) == 'p') {
            Produce* prdct;

            cout << "Enter name of new produce: ";
            getline(cin, usrInptName);

            cout << "Enter the price per item: $";
            getline(cin, usrInptPriceStr);
            inSS.str(usrInptPriceStr);
            inSS >> usrInptPrice;
            inSS.clear();

            cout << "Enter quantity: ";
            getline(cin, usrInptQntyStr);
            inSS.str(usrInptQntyStr);
            inSS >> usrInptQnty;
            inSS.clear();

            cout << "Enter expiration date: ";
            getline(cin, usrInptOther);

            prdct = new Produce;
            prdct->SetName(usrInptName);
            prdct->SetPrice(usrInptPrice);
            prdct->SetQuantity(usrInptQnty);
            prdct->SetExpiration(usrInptOther);

            inventory.push_back(prdct);
            valid = true;

        } else if (usrInptOptn.at(0) == 'b') {
            Book* prdct;

            cout << "Enter name of new book: ";
            getline(cin, usrInptName);

            cout << "Enter the price per item: $";
            getline(cin, usrInptPriceStr);
            inSS.str(usrInptPriceStr);
            inSS >> usrInptPrice;
            inSS.clear();

            cout << "Enter quantity: ";
            getline(cin, usrInptQntyStr);
            inSS.str(usrInptQntyStr);
            inSS >> usrInptQnty;
            inSS.clear();

            cout << "Enter Author: ";
            getline(cin, usrInptOther);

            prdct = new Book;
            prdct->SetName(usrInptName);
            prdct->SetPrice(usrInptPrice);
            prdct->SetQuantity(usrInptQnty);
            prdct->SetAuthor(usrInptOther);

            inventory.push_back(prdct);
            valid = true;
        } else {
            cout << "Invalid choice\n";
        }

    }

    return;
}

Inventory* inventory;

int main() {
    string usrInptOptn = "default";

    while (true) {
        // Get user choice
        cout << "\nEnter (p)rint, (a)dd, (u)pdate, (r)emove, or (q)uit: ";
        getline(cin, usrInptOptn);

        // Process user choice
        if (usrInptOptn.size() == 0) {
            continue;
        } else if (usrInptOptn.at(0) == 'p') {
            inventory->PrintInventory();
        } else if (usrInptOptn.at(0) == 'a') {
            inventory->AddItemToInventory();
        } else if (usrInptOptn.at(0) == 'u') {
            inventory->UpdateItemQtyInInventory();
        } else if (usrInptOptn.at(0) == 'r') {
            inventory->RemoveItemFromInventory();
        } else if (usrInptOptn.at(0) == 'q') {
            cout << "\nGood bye." << endl;
            break;
        }

    }

    return 0;
}

The program crashes when it is running the functions. I don't have the slightest idea why. The AddItemtoIventory function runs through it's entirety before the program crashes while the other one ,and the others, just crashes.

A: You do not need a global variable here. Just create an inventory object within the scope of main
int main() {
    Inventory inv;
    // Rest of your code below

    return 0;
}

Or, alternatively you can still use a pointer and use new.
int main() {
    Inventory* inv = new Inventory;
    // Rest of your code below

    return 0;
}


text:
Q: else operator | JS | Chrome extention I have this function:
function FizzBuzz(){
   if(document.getElementById("textbox") == true){
      Fizz();
   } else {
      Buzz();
   }
}

The Fizz() and Buzz() functions place text in textboxes specified by document.getElementById in their own functions.
in it's current configuration, it should to my understanding execute Fizz() if ("textbox") is found on the webpage, otherwise Buzz() should be executed. This does not happen, and it will only execute one of them, no matter if ("textbox") is true or not.
The ("textbox") referenced above only exists on one of the two pages this is designed to work with.
Changing to !== true will invert the effect, the same with == false, as with the current behavior is expected. I have also tried to check for == null and !== null, this results in the same behavior.
I simply do not understand what I'm doing wrong here.

A: document.getElementById returns either null or element. So, comapring both with == or === with true or false will always return false.
You can directly put document.createElement inside if as a condition.
If you still face the issue, I suggest you to put a break point and see how the code is executed.
Sample code for better understanding - https://codepen.io/Yash__/pen/WNzgYvL?editors=1111

hai

if(document.getElementById('hai')){
  console.log("there");
}else{
  console.log("not there")
}


text:
Q: How to install tensorflow on python installed in linuxbrew (libstdc++.so.6 not found)? I have the following version of Python installed via linuxbrew on Ubuntu 14.04. But pip gives me the following error when I tried to install tensorflow. Does anybody know whether there is a way to fix the problem?
$ python --version
Python 2.7.14

$ pip install tensorflow
Collecting tensorflow
  Could not find a version that satisfies the requirement tensorflow (from versions: )
No matching distribution found for tensorflow

I use Python 2 instead of 3. The previous question is about Python 3.
I have also tried this. But it does not work.
$ pip install  https://storage.googleapis.com/tensorflow/linux/cpu/debian/jessie/tensorflow-1.9.0rc2-cp27-none-linux_x86_64.whl
Collecting tensorflow==1.9.0rc2 from https://storage.googleapis.com/tensorflow/linux/cpu/debian/jessie/tensorflow-1.9.0rc2-cp27-none-linux_x86_64.whl
  Downloading https://storage.googleapis.com/tensorflow/linux/cpu/debian/jessie/tensorflow-1.9.0rc2-cp27-none-linux_x86_64.whl (51.6MB)
    100% |████████████████████████████████| 51.6MB 320kB/s
Collecting astor>=0.6.0 (from tensorflow==1.9.0rc2)
  Downloading https://files.pythonhosted.org/packages/35/6b/11530768cac581a12952a2aad00e1526b89d242d0b9f59534ef6e6a1752f/astor-0.7.1-py2.py3-none-any.whl
Requirement already satisfied: setuptools<=39.1.0 in ./.linuxbrew/lib/python2.7/site-packages (from tensorflow==1.9.0rc2) (36.5.0)
Collecting gast>=0.2.0 (from tensorflow==1.9.0rc2)
  Downloading https://files.pythonhosted.org/packages/5c/78/ff794fcae2ce8aa6323e789d1f8b3b7765f601e7702726f430e814822b96/gast-0.2.0.tar.gz
Collecting protobuf>=3.4.0 (from tensorflow==1.9.0rc2)
  Downloading https://files.pythonhosted.org/packages/77/78/a7f1ce761e2c738e209857175cd4f90a8562d1bde32868a8cd5290d58926/protobuf-3.6.1-py2.py3-none-any.whl (390kB)
    100% |████████████████████████████████| 399kB 5.1MB/s
Requirement already satisfied: six>=1.10.0 in ./.linuxbrew/lib/python2.7/site-packages (from tensorflow==1.9.0rc2) (1.11.0)
Collecting enum34>=1.1.6 (from tensorflow==1.9.0rc2)
  Downloading https://files.pythonhosted.org/packages/c5/db/e56e6b4bbac7c4a06de1c50de6fe1ef3810018ae11732a50f15f62c7d050/enum34-1.1.6-py2-none-any.whl
Collecting absl-py>=0.1.6 (from tensorflow==1.9.0rc2)
  Downloading https://files.pythonhosted.org/packages/a7/86/67f55488ec68982270142c340cd23cd2408835dc4b24bd1d1f1e114f24c3/absl-py-0.4.1.tar.gz (88kB)
    100% |████████████████████████████████| 92kB 5.1MB/s
Collecting backports.weakref>=1.0rc1 (from tensorflow==1.9.0rc2)
  Downloading https://files.pythonhosted.org/packages/88/ec/f598b633c3d5ffe267aaada57d961c94fdfa183c5c3ebda2b6d151943db6/backports.weakref-1.0.post1-py2.py3-none-any.whl
Requirement already satisfied: wheel in ./.linuxbrew/lib/python2.7/site-packages (from tensorflow==1.9.0rc2) (0.30.0)
Collecting tensorboard<1.10.0,>=1.9.0 (from tensorflow==1.9.0rc2)
  Downloading https://files.pythonhosted.org/packages/d5/98/e2e9d5afbc86cef0b2dd0f4ab791519b9bd305ea207e1e5c2f9a9f2f6da6/tensorboard-1.9.0-py2-none-any.whl (3.3MB)
    100% |████████████████████████████████| 3.3MB 3.3MB/s
Requirement already satisfied: numpy>=1.13.3 in ./.linuxbrew/lib/python2.7/site-packages (from tensorflow==1.9.0rc2) (1.14.0)
Collecting mock>=2.0.0 (from tensorflow==1.9.0rc2)
  Downloading https://files.pythonhosted.org/packages/e6/35/f187bdf23be87092bd0f1200d43d23076cee4d0dec109f195173fd3ebc79/mock-2.0.0-py2.py3-none-any.whl (56kB)
    100% |████████████████████████████████| 61kB 4.5MB/s
Requirement already satisfied: termcolor>=1.1.0 in ./.linuxbrew/lib/python2.7/site-packages (from tensorflow==1.9.0rc2) (1.1.0)
Collecting grpcio>=1.8.6 (from tensorflow==1.9.0rc2)
  Downloading https://files.pythonhosted.org/packages/99/ec/8545ffc34b5d0dca66261dabaa8bc44b93e8e1df3549792d9a5649f507cf/grpcio-1.14.2-cp27-cp27m-manylinux1_x86_64.whl (9.2MB)
    100% |████████████████████████████████| 9.2MB 1.7MB/s
Collecting markdown>=2.6.8 (from tensorboard<1.10.0,>=1.9.0->tensorflow==1.9.0rc2)
  Downloading https://files.pythonhosted.org/packages/6d/7d/488b90f470b96531a3f5788cf12a93332f543dbab13c423a5e7ce96a0493/Markdown-2.6.11-py2.py3-none-any.whl (78kB)
    100% |████████████████████████████████| 81kB 5.0MB/s
Requirement already satisfied: futures>=3.1.1; python_version < "3" in ./.linuxbrew/lib/python2.7/site-packages (from tensorboard<1.10.0,>=1.9.0->tensorflow==1.9.0rc2) (3.2.0)
Collecting werkzeug>=0.11.10 (from tensorboard<1.10.0,>=1.9.0->tensorflow==1.9.0rc2)
  Downloading https://files.pythonhosted.org/packages/20/c4/12e3e56473e52375aa29c4764e70d1b8f3efa6682bef8d0aae04fe335243/Werkzeug-0.14.1-py2.py3-none-any.whl (322kB)
    100% |████████████████████████████████| 327kB 5.3MB/s
Collecting funcsigs>=1; python_version < "3.3" (from mock>=2.0.0->tensorflow==1.9.0rc2)
  Downloading https://files.pythonhosted.org/packages/69/cb/f5be453359271714c01b9bd06126eaf2e368f1fddfff30818754b5ac2328/funcsigs-1.0.2-py2.py3-none-any.whl
Collecting pbr>=0.11 (from mock>=2.0.0->tensorflow==1.9.0rc2)
  Downloading https://files.pythonhosted.org/packages/69/1c/98cba002ed975a91a0294863d9c774cc0ebe38e05bbb65e83314550b1677/pbr-4.2.0-py2.py3-none-any.whl (100kB)
    100% |████████████████████████████████| 102kB 6.5MB/s
Building wheels for collected packages: gast, absl-py
  Running setup.py bdist_wheel for gast ... done
  Stored in directory: /home/py/.cache/pip/wheels/9a/1f/0e/3cde98113222b853e98fc0a8e9924480a3e25f1b4008cedb4f
  Running setup.py bdist_wheel for absl-py ... done
  Stored in directory: /home/py/.cache/pip/wheels/78/a3/a3/689120b95c26b9a21be6584b4b482b0fda0a1b60efd30af558
Successfully built gast absl-py
Installing collected packages: astor, gast, protobuf, enum34, absl-py, backports.weakref, markdown, werkzeug, tensorboard, funcsigs, pbr, mock, grpcio, tensorflow
Successfully installed absl-py-0.4.1 astor-0.7.1 backports.weakref-1.0.post1 enum34-1.1.6 funcsigs-1.0.2 gast-0.2.0 grpcio-1.14.2 markdown-2.6.11 mock-2.0.0 pbr-4.2.0 protobuf-3.6.1 tensorboard-1.9.0 tensorflow-1.9.0rc2 werkzeug-0.14.1
$ python
Python 2.7.14 (default, Feb 25 2018, 06:50:45)
[GCC 5.5.0] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import tensorflow
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/home/py/.linuxbrew/lib/python2.7/site-packages/tensorflow/__init__.py", line 22, in <module>
    from tensorflow.python import pywrap_tensorflow  # pylint: disable=unused-import
  File "/home/py/.linuxbrew/lib/python2.7/site-packages/tensorflow/python/__init__.py", line 49, in <module>
    from tensorflow.python import pywrap_tensorflow
  File "/home/py/.linuxbrew/lib/python2.7/site-packages/tensorflow/python/pywrap_tensorflow.py", line 74, in <module>
    raise ImportError(msg)
ImportError: Traceback (most recent call last):
  File "/home/py/.linuxbrew/lib/python2.7/site-packages/tensorflow/python/pywrap_tensorflow.py", line 58, in <module>
    from tensorflow.python.pywrap_tensorflow_internal import *
  File "/home/py/.linuxbrew/lib/python2.7/site-packages/tensorflow/python/pywrap_tensorflow_internal.py", line 28, in <module>
    _pywrap_tensorflow_internal = swig_import_helper()
  File "/home/py/.linuxbrew/lib/python2.7/site-packages/tensorflow/python/pywrap_tensorflow_internal.py", line 24, in swig_import_helper
    _mod = imp.load_module('_pywrap_tensorflow_internal', fp, pathname, description)
ImportError: libstdc++.so.6: cannot open shared object file: No such file or directory

Failed to load the native TensorFlow runtime.

See https://www.tensorflow.org/install/install_sources#common_installation_problems

for some common reasons and solutions.  Include the entire stack trace
above this error message when asking for help.
>>>

But the file is available.
$ ls ~/.linuxbrew/lib/libstdc++.so.6
.linuxbrew/lib/libstdc++.so.6


text:
Q: Circleci create environment variable from existing env var In the circle ci dashboard I set enviornment variables like DEV_USEFUl_API_KEY, PROD_USEFUL_API_KEY. Then in my circleci config file (v2.1) I do this
- run:
    name: Run Tests
    command: |
      if [ "${CIRCLE_BRANCH}" == "master" ]; then
        echo 'export FIREBASE_API_KEY=${PROD_FIREBASE_API_KEY}' >> $BASH_ENV
      elif [[ "${CIRCLE_BRANCH}" == "develop" ]]; then
        echo 'export FIREBASE_API_KEY=${DEV_FIREBASE_API_KEY}' >> $BASH_ENV
      fi
      yarn test

The idea been when my tests are run, the environment variable will be read. I have printed out within my node application process.env and I can see the variables PROD_FIREBASE_API_KEY, DEV_FIREBASE_API_KEY are within the environment, however there is no FIREBASE_API_KEY as intended.
I have tried chaning the syntax of the command to:
echo 'export FIREBASE_API_KEY=$PROD_FIREBASE_API_KEY' >> $BASH_ENV
and also
echo 'export FIREBASE_API_KEY="$PROD_FIREBASE_API_KEY"' >> $BASH_ENV
However its not making any difference, the variable FIREBASE_API_KEY is not set, can anyone please advise? Thanks.

A: The solution was to put yarn test in another run step, as its necessary for the bash profile to be reloaded after setting new env vars (which happens at the beginning of every run).
      - run:
          name: Configure Environment Variables
          command: |
            if [ "${CIRCLE_BRANCH}" == "master" ]; then
              # Set env variables
            elif [[ "${CIRCLE_BRANCH}" == "develop" ]]; then
              # Set env variables
            fi
      - run:
          name: Run Tests
          command: |
            yarn test


text:
Q: Having problems blinking an LED on Arduino using information sent over CAN-bus I've been messing around with CAN-bus to try and learn the basics so I can use it in a future project. I have 2 arduinos with MCP2515 chips connected that I am sending messages between.
I have been able to wire up the chips and send messages between the arduinos just fine, but when I went to modify the code to blink an LED if the first byte is 0x00 or 0x01 it wont blink. I added print statements to check that it is entering the loop, and it is, using the serial monitor I can see it yeet and yote, but digital pin 3 remains at ~0V.
This is probably more an arduino question than a CAN-bus question but could somebody help me understand why my LED wont blink? The code is entering the loop so it should be processing the command, and I initialized the pin to be an output, but i'm still not getting any blinking.
As a note, the transmitting arduino is sending alternating packets of data, first a packet with 0X01 as the first data byte, then with 0x00 as the first data byte. These data packets are separated by 5000 ms.
I am currently using the CAN library available here https://github.com/autowp/arduino-mcp2515
Code for receiving arduino
#include <SPI.h>
#include <mcp2515.h>

struct can_frame canMsg;
MCP2515 mcp2515(10);

int LED_PIN = 3;
void setup() {
  Serial.begin(115200);
  SPI.begin();
  pinMode(LED_PIN, OUTPUT);
  mcp2515.reset();
  mcp2515.setBitrate(CAN_125KBPS);
  mcp2515.setNormalMode();

  Serial.println("------- CAN Read ----------");
  Serial.println("ID  DLC   DATA");
}

void loop() {

  if (mcp2515.readMessage(&canMsg) == MCP2515::ERROR_OK) {

    Serial.print(canMsg.can_id, HEX); // print ID
    Serial.print(" ");
    Serial.print(canMsg.can_dlc, HEX); // print DLC
    Serial.print(" ");
    if(canMsg.data[0] == 0x00){
      digitalWrite(LED_PIN,HIGH);
      Serial.print("YEET");
    }
    if(canMsg.data[0] == 0x01){
      digitalWrite(LED_PIN,LOW);
      Serial.print("YOTE");
    }
    for (int i = 0; i<canMsg.can_dlc; i++)  {  // print the data

      Serial.print(canMsg.data[i],HEX);
      Serial.print(" ");

    }

    Serial.println();
  }

}

and the code for transmitting arduino for completeness
#include <SPI.h>
#include <mcp2515.h>

struct can_frame canMsg1;
struct can_frame canMsg2;
MCP2515 mcp2515(10);

void setup() {

  canMsg1.can_id  = 0x0F6;
  canMsg1.can_dlc = 8;
  canMsg1.data[0] = 0x01;
  canMsg1.data[1] = 0x87;
  canMsg1.data[2] = 0x32;
  canMsg1.data[3] = 0xFA;
  canMsg1.data[4] = 0x26;
  canMsg1.data[5] = 0x8E;
  canMsg1.data[6] = 0xBE;
  canMsg1.data[7] = 0x86;

  canMsg2.can_id  = 0x036;
  canMsg2.can_dlc = 8;
  canMsg2.data[0] = 0x00;
  canMsg2.data[1] = 0x00;
  canMsg2.data[2] = 0x00;
  canMsg2.data[3] = 0x08;
  canMsg2.data[4] = 0x01;
  canMsg2.data[5] = 0x00;
  canMsg2.data[6] = 0x00;
  canMsg2.data[7] = 0xA0;

  while (!Serial);
  Serial.begin(115200);
  SPI.begin();

  mcp2515.reset();
  mcp2515.setBitrate(CAN_125KBPS);
  mcp2515.setNormalMode();

  Serial.println("Example: Write to CAN");
}

void loop() {

  mcp2515.sendMessage(&canMsg1);
  delay(5000);
  mcp2515.sendMessage(&canMsg2);

  Serial.println("Messages sent");

  delay(5000);

}

A: Sorry, i'm an idiot. I forgot that breadboard power lines are not connected all the way down the board. I connected the Arduino to the proper section of the breadboard to receive power and ground, but connected the LED to an unconnected ground pin.


text:
Q: Pegar id do usuario por SESSION Estou com uma duvida , como eu pego o id do rapaz que efetuou login no meu sistema? Para que posteriormente ele possa alterar seus dados.
<?php
    if (isset ($_POST ["loginUsuario_externo"])){
        include_once("../controllers/Usuario_Externo_Controller.php");
        $usuario_externo = new Usuario_externo_Controller;
        $usuario_externo->login();
    }

Funçao login
public function login() {

    $this->usuario_externos->email($this->input->get('email'))
                           ->senha($this->input->get('senha'));

    $resultado = $this->usuario_externos->login();

    if($resultado) {
      session_start();
      $_SESSION['login'] = $resultado;
      echo '<script>window.location = "../views/externo/";</script>';
      echo ('Aguarde, redirecionando.');
    } else {
        echo ('E-mail ou Senha incorreto(os).');
    }
}

MODEL
  public function login() {

    $sql  = "SELECT * FROM usuario WHERE email = :email AND senha = :senha AND status = 1 LIMIT 1";
    $stmt = $this->conn->prepare($sql);
    $stmt->bindParam(':email', $this->email, PDO::PARAM_INT);
    $stmt->bindParam(':senha', $this->senha, PDO::PARAM_STR);
     $stmt->execute();
    return $stmt->fetch();

}

starta sessão e vrf se há sessao
 <?php
  session_start();
  function session_checker(){
    if (! isset($_SESSION['login'])){
      header ("Location:../");
      exit();
    }
  }
  session_checker();
  ?>

A: O problema parece ser o acesso a sessão, pelos comentário foi visto que o retorno do login() model retornar um objeto e jogava ele na sessão ele deveria ser acessado assim $_SESSION['login']->id.
Caso deseja acessar as informações do usuário na sessão como um array, define o tipo de retorno no fetch(). return $stmt->fetch(PDO::FETCH_ASSOC);
NÃO passe informaçãoes sensiveis como uma senha pelo método get, pois ela ficará visivel na url, práticamente você oferece o ouro ao bandido.

A: Tente desta maneira, utilizando o session_id()
<?php
session_start();
$r=session_id();

echo "o id da sessão é: ".$r;

?>


text:
Q: Bypass vs Unrestricted execution policies The documentation on the topic only provides this:

Unrestricted. Loads all configuration files and runs all scripts. If you run an unsigned script that was downloaded from the Internet, you are prompted for permission before it runs.
Bypass. Nothing is blocked and there are no warnings or prompts.

To me it seems like the two would accept any scripts, but to my surprise it's not the case. Bypass seems to block execution in some cases.
So, what is the difference between the two ?

A: The difference is in the descriptions you gave in the question. Unrestricted allows you to indulge in the illusion that all computers run windows, only use NTFS, and only download things with browsers that save ADS. In fact, if you save a file in windows to a FAT filesystem or network share that isn't using NTFS on the server, or download it another way such as with git, powershell believes it is locally created no matter where it came from. Bypass doesn't check for any of this and just runs everything. Unrestricted is supposed to warn you of things it thinks might be dangerous but isn't able to reliably check or determine. Use whichever tickles your fancy.
PS> rm -path file.ps1 -stream zone.identifier
Discuss...

A: Per the comments, there should be no particular difference with how these execution policies behave (except those noted by @DennisSimpson in his answer, where on Windows use of "Unrestricted" may still result in a prompt if the file was detected as downloaded from the internet). Typically, Bypass is used when you are temporarily changing the execution policy during a single run of Powershell.exe, where as Unrestricted is used if you wish to permanently change the setting for the execution policy for one of the system scopes (MachinePolicy, UserPolicy, Process, CurrentUser, LocalMachine).
Some examples:

*

*You are on a system where you want to change the execution policy to be permanently unrestricted so that any user could run any PowerShell script without issue. You would run:
 Set-ExecutionPolicy Unrestricted

*You are on a system where the execution policy blocks your script, but you want to run it via PowerShell and ignore the execution policy when run. You would run:
 powershell.exe .\yourscript.ps1 -executionpolicy bypass

*You run Powershell.exe on a system where the execution policy blocks the execution of scripts, but you want to change this policy just for the life of the interactive powershell.exe session that you're in. You would run:
  Set-ExecutionPolicy Bypass -Scope Process


text:
Q: CoordinatorLayout blank space under toolbar When I start my application on a virtual device it is like an ekstra toolbar appears on my activity.
It is an activity with nested scrollview and collapsing toolbar. All the animations and all the buttons works perfectly, but it seems like it adds ekstra space and it is exactly the size of a collapsed/regular toolbar.
If I change the coordinatorLayout layout_height to "wrap_content" the extra space will go to the bottom of the screen instead of being right under the correct toolbar.
Can anyone see what the problem is? I have tried a plethora of different settings now.
Non collapsed toolbar with imageview
Collapsed toolbar
Heres the code for the activity:
public class algorithms_abcde extends AppCompatActivity {
    CollapsingToolbarLayout collapsingToolbarLayout;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_algorithms_abcde);

        setSupportActionBar((Toolbar) findViewById(R.id.toolbar));
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        getSupportActionBar().setDisplayShowHomeEnabled(true);
        collapsingToolbarLayout = findViewById(R.id.collapsingToolbar);
        collapsingToolbarLayout.setTitle(getString(R.string.btn_txt_abcde));
        collapsingToolbarLayout.setExpandedTitleColor(getResources().getColor(android.R.color.transparent));
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu){
        //Inflate the menu; This adds it to the actionba
        getMenuInflater().inflate(R.menu.menu_other, menu);
        return true;
    }

    // Determines which button has been pressed.
    @Override
    public boolean onOptionsItemSelected(MenuItem item){
        //Switch case to handle item presses on the action bar
        switch (item.getItemId()) {

            case android.R.id.home:
                this.finish();
                return true;

            case R.id.action_home:
                Intent intent = new Intent(this, MainActivity.class);
                intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                startActivity(intent);
                return true;
        }
        return super.onOptionsItemSelected(item);
    }
}

Here is the xml of the activity:
<android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".algorithms_abcde"
    android:layout_gravity="bottom">

    <android.support.design.widget.AppBarLayout
        android:id="@+id/appBarLayout"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:fitsSystemWindows="true"
        android:theme="@style/ThemeOverlay.AppCompat.ActionBar">

        <android.support.design.widget.CollapsingToolbarLayout
            android:id="@+id/collapsingToolbar"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            app:layout_scrollFlags="scroll|snap|exitUntilCollapsed"
            app:contentScrim="@color/colorVeryLight"
            app:expandedTitleMarginEnd="64dp"
            app:expandedTitleMarginStart="48dp"
            android:fitsSystemWindows="true"
            >

            <ImageView
                android:id="@+id/headLine"
                android:layout_width="match_parent"
                android:layout_height="120dp"
                android:layout_marginLeft="60dp"
                android:layout_marginRight="60dp"
                android:fitsSystemWindows="true"
                android:src="@drawable/img_abcde_headline"/>

            <android.support.v7.widget.Toolbar
                android:id="@+id/toolbar"
                android:layout_width="match_parent"
                android:layout_height="?attr/actionBarSize"
                android:background="@android:color/transparent"
                app:popupTheme="@style/ThemeOverlay.AppCompat.Light"
                app:layout_collapseMode="pin"/>

        </android.support.design.widget.CollapsingToolbarLayout>
    </android.support.design.widget.AppBarLayout>

    <android.support.v4.widget.NestedScrollView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_gravity="bottom"
        app:layout_behavior="@string/appbar_scrolling_view_behavior"
        android:background="@android:color/white">

        <TextView
            android:id="@+id/scrollAbleTextView"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:background="@android:color/white"
            android:padding="10dp"
            android:text="@string/stringtest"/>

    </android.support.v4.widget.NestedScrollView>
</android.support.design.widget.CoordinatorLayout>

Heres the xml of the themes.xml
<resources>
    <style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">

        <item name="windowActionBar">false</item>
        <item name="android:buttonStyle">@style/button</item>
        <!-- Base application theme. -->
        <!-- Customize your theme here. -->
        <item name="colorPrimary">@color/colorPrimary</item>
        <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
        <item name="colorAccent">@color/colorAccent</item>
        <item name="android:background">@color/colorVeryLight</item>
    </style>

</resources>

and and lastly the manifest:

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".algorithms_opqrst"></activity>
        <activity android:name=".algorithms_abcde" />
        <activity android:name=".algorithms_activity" />
        <activity
            android:name=".MainActivity"
            android:label="@string/app_name">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

A: I found the answer.
I had to remove all the "android:fitsSystemWindows="true"" and add it to the CoordinatorLayout.
Then I also had to remove the "android:layout_gravity="bottom"" from both the CoordinatorLayout and the NestedScrollView.


text:
Q: can program terminate successfully when we use only wait() method and not notify() Question:
 I have two thread classes as below.
 I was expecting my program to never terminate since I have not used wait(long ms) method. As I am not calling notify the object which has acquired the lock and is in wait state should have never been notified.
But the output is not as per my expectation.
Please help me in understanding this concept.
My code:
    ThreadA{
    main(String args[]){
    ThreadB b = new ThreadB();
    b.start();
    }
    synchronized(b) {
                try {
                    System.out.println("Main thread will start waiting");
                    b.wait();
                    System.out.println("Main thread waiting for notification");
                    System.out.println("wait over!!");
                } catch (InterruptedException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }

                System.out.println(b.total);
                System.out.println("Main thread execution finished!!");
            }
    }

    ThreadB{
    int total =0;
        public void run() {
            synchronized(this) {
                for(int i=0;i<=100;i++) {
                    total=total+i;
                }
                System.out.println("Child thread should give notification");
                //this.notify();
            }
            System.out.println("Child thread execution finished!!");
        }
    }
 <!--code-->

Result:
    Main thread will start waiting
    Child thread should give notification
    Child thread execution finished!!
    Main thread waiting for notification
    wait over!!
    5050
    Main thread execution finished!!


text:
Q: How to take input from std::vector of std::pair in a std::map? int n,a,b,c;
cin >> n;
map<int,vector<pair<int,int>>> mv;
for(int i=0;i<n;++i)
{
    cin>>a>>b>>c;
    mv[a].insert(make_pair(b,c));
}

I m trying to take input from std::vector of std::pair which is in a std::map.Is it possible?
And, how can I iterate through the map?

A: mv[a].insert(...) is not the right function call. You need to use mv[a].push_back(...). Remember that mv[a] return a reference to the value in the map that corresponds to the key a.
If you divide that line in two, it will make more sense.
int n,a,b,c;
cin >> n;
map<int,vector<pair<int,int>>> mv;
for(int i=0;i<n;++i)
{
    cin>>a>>b>>c;
    vector<pair<int,int>>& v = mv[a];
    v.push_back(make_pair(b,c));
}


text:
Q: IndexError: list index out of range Why can't I acsess two-dimensional array? I cannot acsess the two-dimensional array.
I wrote
book3 = xlrd.open_workbook('./data/excel1.xlsx')
sheet3 = book3.sheet_by_index(0)
for row_index in range(7, sheet3.nrows):
    row = sheet3.row_values(row_index)
    area_row = row[0] or area_row
    row[0] = area_row
    if len(fourrows) == 5:
       fourrows=[]
    fourrows.append(row)
    fourrows_transpose=list(map(list, zip(*fourrows)))
    val3 = sheet3.cell_value(rowx=0, colx=9)
    user3 = User.objects.filter(corporation_id=val3).first()
    if user3:
       area = Area.objects.filter(name="America").first()
       pref = Prefecture.objects.create(name="prefecture", area=user3.area)
       city = City.objects.create(name="city", prefecture=pref)
       price_u1000 = Price.upper1000.objects.get(city=city)
       price_500_1000 = Price.from500to1000.objects.get(city=city)
       price_u500 = Price.under500.objects.get(city=city)

       pref.name = "NY"
       pref.save()

         for i in range(2,len(fourrows_transpose)):
             city.name = fourrows_transpose[i][1]
             city.save()
             print(fourrows_transpose[i][1])

             price_u1000.name = fourrows_transpose[i][2]
             price_u1000.save()
             print(fourrows_transpose[i][2])

             price_500_1000.name = fourrows_transpose[i][3]
             price_500_1000.save()
             print(fourrows_transpose[i][3])

             price_u500.name = fourrows_transpose[i][4]
             price_u500.save()
             print(fourrows_transpose[i][4])

In print(fourrows_transpose),it is shown
[['America', 'America', 'America', 'America', 'America'], ['', '', 'u1000', '500~1000', 'd500'], ['NY', 'City A', '×', '×', '×'], ['NY', 'City B', '×', '×', '×'], ['NY', 'City C', '×', '×', '×'], ['NY', 'City D', '×', '×', '×'], ['NY', 'City E', '×', '×', '×']]

Now error happens:

IndexError: list index out of range.

Traceback says:
city.name = fourrows_transpose[i][1]

is wrong. but I think fourrows_transpose is two-dimensional arrays,so I really cannot understand why I cannot access fourrows_transpose[2][1]. What is wrong? How should  I fix this?

A: you can try simple construction:
     for transpose in fourrows_transpose[2:]:
         city.name = transpose[1]
         city.save()
         print(transpose[1])

         price_u1000.name = transpose[2]
         price_u1000.save()
         print(transpose[2])

         price_500_1000.name = transpose[3]
         price_500_1000.save()
         print(transpose[3])

A: for i in range(2,len(fourrows_transpose)):
                 ^^^^^^^^^^^^^^^^^^^^^^^
    # ...

Assuming you have an array arrayNumbers = {0,1,2,3,4}
That array has 5 elements (=len(arrayNumbers)), but max. index is 4. In this case your loop would say: "Run from index 2 up to index 5." So the last run of your loop tries to access arrayNumbers[5] which does not exist.
So, you need to decrement your max. index value in your for loop by 1.

A: Actual problem is here.
city = City.objects.create(name="city", prefecture=pref)
price_u1000 = Price.upper1000.objects.get(city=city)
price_500_1000 =Price.from500to1000.objects.get(city=city)
price_u500 = Price.under500.objects.get(city=city)
here you will have to filter data as you done like

area = Area.objects.filter(name="America").first()

A: because in your code you have:
for i in range(2,len(fourrows_transpose)):

try:
for i in range(0,len(fourrows_transpose)-1):


text:
Q: System services not available to Activities before onCreate() in Expandable ListView In my app i have SearchView which, when clicked, opens an ExpandableListView inside a Fragment that displays some results for the searchquery. Now i have the problem that everytime i click the searchIcon the app crashes.
MainActivity.Java:
public class MainActivity extends AppCompatActivity implements SearchView.OnQueryTextListener
{

    private ExpListAdapter listAdapter;
    private ExpandableListView expList;
    private ArrayList<parentClass> parentList = new ArrayList<>();

    private boolean b = true;
    sql sqlo = new sql();

   @Override
   protected void onCreate (Bundle savedInstanceState) {

       super.onCreate(savedInstanceState);
       setContentView(R.layout.activity_main);
       Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
       setSupportActionBar(toolbar);

       Intent sIntent = getIntent();
       if (Intent.ACTION_SEARCH.equals(sIntent.getAction())) {
           String query = sIntent.getStringExtra(SearchManager.QUERY);

       }}

    public void searchClick(MenuItem item){
        Fragment frag = new Results();

        FragmentTransaction ft  = getSupportFragmentManager().beginTransaction();

        ft.replace(R.id.FragFaecher,frag).commit();
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.menu_main, menu);

        SearchManager searchManager = (SearchManager) getSystemService(Context.SEARCH_SERVICE);
        SearchView searchView = (SearchView) menu.findItem(R.id.search).getActionView();

        searchView.setSearchableInfo(searchManager.getSearchableInfo(getComponentName()));
        searchView.setIconifiedByDefault(false);
        searchView.setOnQueryTextListener(this);

       searchView.addOnAttachStateChangeListener(new View.OnAttachStateChangeListener() {
           @Override
           public void onViewAttachedToWindow(View v) {

           }

           @Override
           public void onViewDetachedFromWindow(View v) {
            Fragment frag = new FaecherFrag();
               FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
               ft.replace(R.id.FragFaecher,frag).commit();
           }
       });

        return true;
    }

        public void displayList(ExpandableListView expList){
        if(b){populateList();}

        listAdapter = new ExpListAdapter(MainActivity.this,parentList);
        expList.setAdapter(listAdapter);
        b = false;
    }

    private void populateList(){
        String[] cThema = sqlo.getAlleThemen(this);
        String[] cFormel = sqlo.getAlleFormeln(this);
        int cThemaLength = cThema.length;
        int cFormelLength = cFormel.length;
        childClass Child;

        ArrayList<childClass> childList = new ArrayList<>();

        for (int i=0; i<cThemaLength;i++){Child = new childClass(cThema[i]);childList.add(Child);}
        parentClass Parent = new parentClass("Themen",childList);
        parentList.add(Parent);

        childList = new ArrayList<>();

        for (int i=0;i<cFormelLength;i++){Child = new childClass(cFormel[i]);childList.add(Child);}
        Parent = new parentClass("Formeln",childList);

        parentList.add(Parent);

    }

    @Override
    public boolean onQueryTextSubmit(String query) {

        return false;
    }

    @Override
    public boolean onQueryTextChange(String query) {

        return false;
    }
}

ExpListAdapter.Java:
public class ExpListAdapter extends BaseExpandableListAdapter {

    private Context context;
    private ArrayList<parentClass> parentList;
    private ArrayList<parentClass> originalList;

    public ExpListAdapter(Context context, ArrayList<parentClass> parentList){
        this.context = context;
        this.parentList = new ArrayList<>();
        this.parentList.addAll(parentList);
        this.originalList = new ArrayList<>();
        this.originalList.addAll(parentList);
    }

    @Override
    public int getGroupCount() {
        return parentList.size();
    }

    @Override
    public int getChildrenCount(int groupPosition) {
        ArrayList<childClass> childList = parentList.get(groupPosition).getChildList();
        return childList.size();
    }

    @Override
    public Object getGroup(int groupPosition) {
        return parentList.get(groupPosition);
    }

    @Override
    public Object getChild(int groupPosition, int childPosition) {
        ArrayList<childClass> childList = parentList.get(groupPosition).getChildList();
        return childList.get(childPosition);
    }

    @Override
    public long getGroupId(int groupPosition) {
        return groupPosition;
    }

    @Override
    public long getChildId(int groupPosition, int childPosition) {

        return childPosition;
    }

    @Override
    public boolean hasStableIds() {
        return true;
    }

    @Override
    public View getChildView(int groupPosition, int childPosition, boolean isLastChild, View convertView, ViewGroup parent) {
        childClass child = (childClass) getChild(groupPosition,childPosition);
        if (convertView == null){
            LayoutInflater layoutInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            convertView = layoutInflater.inflate(R.layout.child_row,null);
        }
        TextView name = (TextView) convertView.findViewById(R.id.name);
        name.setText(child.getName().trim());

        return convertView;
    }

    @Override
    public View getGroupView(int groupPosition, boolean isExpanded, View convertView, ViewGroup Parent) {
        parentClass parent = (parentClass) getGroup(groupPosition);
        if(convertView == null){
            LayoutInflater layoutInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            convertView = layoutInflater.inflate(R.layout.parent_row,null);

        }
        TextView heading = (TextView) convertView.findViewById(R.id.heading);
        heading.setText(parent.getName().trim());
        return convertView;
    }

    @Override
    public boolean isChildSelectable(int groupPosition, int childPosition) {
        return true;
    }

    public void filterData(String query){

    }
}

Fragment:
public class Results extends Fragment {

    ExpandableListView expList;

    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {

        View rootView = inflater.inflate(R.layout.fragment_results, container, false);

        return rootView;

    }

    public void onStart(){
        super.onStart();
        expList = (ExpandableListView) getView().findViewById(R.id.expList);
        MainActivity ma = new MainActivity();
        ma.displayList(expList);
    }
}

I get the Error "java.lang.IllegalStateException: System services not available to Activities before onCreate()" on the getGroupView() method. But if i don't get it wrong, i have already called the onCreate of my MainActivity. So why does this Error occur?

FATAL EXCEPTION: main
                                                                                Process: formelhelfer5_10.formelhelfer5_10, PID: 2301
                                                                                java.lang.IllegalStateException: System services not available to Activities before onCreate()
                                                                                at android.app.Activity.getSystemService(Activity.java:5581)
                                                                                at formelhelfer5_10.formelhelfer5_10.ExpListAdapter.getGroupView(ExpListAdapter.java:86)
                                                                                at android.widget.ExpandableListConnector.getView(ExpandableListConnector.java:446)
                                                                                at android.widget.AbsListView.obtainView(AbsListView.java:2360)
                                                                                at android.widget.ListView.measureHeightOfChildren(ListView.java:1326)
                                                                                at android.widget.ListView.onMeasure(ListView.java:1233)
                                                                                at android.view.View.measure(View.java:19731)
                                                                                at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:6120)
                                                                                at android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1464)
                                                                                at android.widget.LinearLayout.measureVertical(LinearLayout.java:758)
                                                                                at android.widget.LinearLayout.onMeasure(LinearLayout.java:640)
                                                                                at android.view.View.measure(View.java:19731)
                                                                                at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:6120)
                                                                                at android.widget.FrameLayout.onMeasure(FrameLayout.java:185)
                                                                                at android.view.View.measure(View.java:19731)
                                                                                at android.widget.RelativeLayout.measureChildHorizontal(RelativeLayout.java:715)
                                                                                at android.widget.RelativeLayout.onMeasure(RelativeLayout.java:461)
                                                                                at android.view.View.measure(View.java:19731)
                                                                                at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:6120)
                                                                                at android.support.design.widget.CoordinatorLayout.onMeasureChild(CoordinatorLayout.java:668)
                                                                                at android.support.design.widget.HeaderScrollingViewBehavior.onMeasureChild(HeaderScrollingViewBehavior.java:90)
                                                                                at android.support.design.widget.AppBarLayout$ScrollingViewBehavior.onMeasureChild(AppBarLayout.java:1192)
                                                                                at android.support.design.widget.CoordinatorLayout.onMeasure(CoordinatorLayout.java:733)
                                                                                at android.view.View.measure(View.java:19731)
                                                                                at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:6120)
                                                                                at android.widget.FrameLayout.onMeasure(FrameLayout.java:185)
                                                                                at android.support.v7.widget.ContentFrameLayout.onMeasure(ContentFrameLayout.java:135)
                                                                                at android.view.View.measure(View.java:19731)
                                                                                at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:6120)
                                                                                at android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1464)
                                                                                at android.widget.LinearLayout.measureVertical(LinearLayout.java:758)
                                                                                at android.widget.LinearLayout.onMeasure(LinearLayout.java:640)
                                                                                at android.view.View.measure(View.java:19731)
                                                                                at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:6120)
                                                                                at android.widget.FrameLayout.onMeasure(FrameLayout.java:185)
                                                                                at android.view.View.measure(View.java:19731)
                                                                                at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:6120)
                                                                                at android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1464)
                                                                                at android.widget.LinearLayout.measureVertical(LinearLayout.java:758)
                                                                                at android.widget.LinearLayout.onMeasure(LinearLayout.java:640)
                                                                                at android.view.View.measure(View.java:19731)
                                                                                at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:6120)
                                                                                at android.widget.FrameLayout.onMeasure(FrameLayout.java:185)
                                                                                at com.android.internal.policy.DecorView.onMeasure(DecorView.java:687)
                                                                                at android.view.View.measure(View.java:19731)
                                                                                at android.view.ViewRootImpl.performMeasure(ViewRootImpl.java:2271)
                                                                                at android.view.ViewRootImpl.measureHierarchy(ViewRootImpl.java:1358)
                                                                                at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:1607)
                                                                                at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1246)
                                                                                at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:6301)
                                                                                at android.view.Choreographer$CallbackRecord.run(Choreographer.java:871)
                                                                                at android.view.Choreographer.doCallbacks(Choreographer.java:683)
                                                                                at android.view.Choreographer.doFrame(Choreographer.java:619)
                                                                                at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:857)
                                                                                at android.os.Handler.handleCallback(Handler.java:751)
  09-06 13:13:20.688 2301-2301/formelhelfer5_10.formelhelfer5_10 E/AndroidRuntime:     at android.os.Handler.dispatchMessage(Handler.java:95)
                                                                                at android.os.Looper.loop(Looper.java:154)
                                                                                at android.app.ActivityThread.main(ActivityThread.java:6077)
                                                                                at java.lang.reflect.Method.invoke(Native Method)
                                                                                at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:865)
                                                                                at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:755)

A: Use this:
View.inflate(ctx, R.layout.parent_row, null);
inside this:
 @Override
    public View getGroupView(int groupPosition, boolean isExpanded, View convertView, ViewGroup Parent) {
        parentClass parent = (parentClass) getGroup(groupPosition);
        if(convertView == null){
            convertView = View.inflate(ctx, R.layout.parent_row, null);

        }
        TextView heading = (TextView) convertView.findViewById(R.id.heading);
        heading.setText(parent.getName().trim());
        return convertView;
    }

A:
MainActivity ma = new MainActivity();
ma.displayList(expList);

Never instantiate activities with new. Such instances are not initialized for anything you'd use an Activity for, like being used as a Context with access to system services.
In a fragment, you can access the attached hosting activity with getActivity(). Use that instead of instantiating a new activity.

A: 1) As figured laalto - Never instantiate activities with new.
change
 public void onStart(){
    super.onStart();
    expList = (ExpandableListView) getView().findViewById(R.id.expList);
    MainActivity ma = new MainActivity();
    ma.displayList(expList);
}

with
 public void onStart(){
    super.onStart();
    expList = (ExpandableListView) getView().findViewById(R.id.expList);
    MainActivity ma = (MainActivity) getActivity();
    ma.displayList(expList);
}

2) It is not good idea to create so deep dependency