text:
Q: C++ Tic Tac Toe Game cannot change private members I am creating an OOP tic tac toe game. I cannot understand why certain things are not working properly. First of all, I cannot change my gameBoard array by passing in a number for column and another one for row and changing it in that function. Second, the checkWinner function should change the player if there is no one, but it does not seem to do that either. Here is my code:
TicTacToe.h:
#ifndef TICTACTOE_H
#define TICTACTOE_H
using namespace std;

class TicTacToe{
private:
    int gameBoard[3][3];
    int playerTurn = 1;

public:
    TicTacToe();
    void printBoard();
    int printPlayer();
    bool changeBoard(int, int);
    bool checkWinner();

};

#endif

TicTacToe.cpp:
#include "TicTacToe.h"
#include <iostream>
using namespace std;

TicTacToe::TicTacToe(){
    for (int i = 0; i < 3; i++){
        for (int j = 0; j < 3; j++){
            gameBoard[i][j] = 0;

        }
    }
}
void TicTacToe::printBoard(){
    for (int i = 0; i < 3; i++){
        for (int j = 0; j < 3; j++){
            cout << gameBoard[i][j];

        }
        cout << endl;
    }
}
int TicTacToe::printPlayer(){
    return playerTurn;
}

bool TicTacToe::changeBoard(int r, int s){
    if (gameBoard[r][s] == 0){
        gameBoard[r][s] == playerTurn;
        return true;
    }
    else{
        return false;
    }
}

bool TicTacToe::checkWinner(){
    if (gameBoard[0][0] && gameBoard[1][0] && gameBoard[2][0] == playerTurn){
        return true;
    }
    else if (gameBoard[0][1] && gameBoard[1][1] && gameBoard[2][1] == playerTurn){
        return true;
    }
    else if (gameBoard[0][2] && gameBoard[1][2] && gameBoard[2][2] == playerTurn){
        return true;
    }
    /*********************************/
    if (gameBoard[0][0] && gameBoard[0][1] && gameBoard[0][2] == playerTurn){
        return true;
    }
    else if (gameBoard[1][0] && gameBoard[1][1] && gameBoard[1][2] == playerTurn){
        return true;
    }
    else if (gameBoard[2][0] && gameBoard[2][1] && gameBoard[2][2] == playerTurn){
        return true;
    }
    /*********************************/
    else if (gameBoard[0][0] && gameBoard[1][1] && gameBoard[2][2] == playerTurn){
        return true;
    }
    else if (gameBoard[0][2] && gameBoard[1][1] && gameBoard[2][0] == playerTurn){
        return true;
    }

    /*********************************/
    else{
        if (playerTurn == 1){
            playerTurn == 2;
        }
        else{
            playerTurn == 1;
        }
        return false;

    }
}

TicTacToeApp.cpp:
#include "TicTacToe.h"
#include <iostream>
#include <string>
#include <iomanip>
using namespace std;

int main(){
    const int boardNumber = 3;
        int selection;
        int row;
        int col;
        TicTacToe gameBoard;
        do{
        cout << "Welcome to TicTacToe!" << endl
            << "1) Play Game" << endl
            << "2) Quit" << endl;
        cin >> selection;

            if (selection == 1){
                do{
                    gameBoard.printBoard();
                    cout << "Player #" << gameBoard.printPlayer() << ":" << endl
                        << "Row: ";
                    cin >> row;
                    row = row - 1;
                    cout << "\n";
                    cout << "Column: ";
                    cin >> col;
                    col = col - 1;
                    if (gameBoard.changeBoard(row, col) == false){
                        cout << "Invalid Selection, try again!" << endl;
                    }
                    gameBoard.checkWinner();
                } while (gameBoard.checkWinner() == false);
                if (gameBoard.checkWinner() == true){
                    cout << "Player " << gameBoard.printPlayer() << " wins!" << endl;
                }

            }
        } while (selection != 2);

        system("PAUSE");
        return 0;

}

EDIT: I have changed my stupid errors now, but I still would not change the player to 2 when there is no winner. Here is my current code for that function:
bool TicTacToe::checkWinner(){
    if (gameBoard[0][0] && gameBoard[1][0] && gameBoard[2][0] == playerTurn){
        return true;
    }
    else if (gameBoard[0][1] && gameBoard[1][1] && gameBoard[2][1] == playerTurn){
        return true;
    }
    else if (gameBoard[0][2] && gameBoard[1][2] && gameBoard[2][2] == playerTurn){
        return true;
    }
    /*********************************/
    else if (gameBoard[0][0] && gameBoard[0][1] && gameBoard[0][2] == playerTurn){
        return true;
    }
    else if (gameBoard[1][0] && gameBoard[1][1] && gameBoard[1][2] == playerTurn){
        return true;
    }
    else if (gameBoard[2][0] && gameBoard[2][1] && gameBoard[2][2] == playerTurn){
        return true;
    }
    /*********************************/
    else if (gameBoard[0][0] && gameBoard[1][1] && gameBoard[2][2] == playerTurn){
        return true;
    }
    else if (gameBoard[0][2] && gameBoard[1][1] && gameBoard[2][0] == playerTurn){
        return true;
    }

    /*********************************/
    else{
        if (playerTurn == 1){
            playerTurn = 2;
        }
        else{
            playerTurn = 1;
        }
        return false;

    }
}

A: You cannot assign using == operator (unless you use operator overload).
Use = operator instead to assign (update values).


text:
Q: Display output in a separate window in MATLAB At the end of the execution of my program in MATLAB, the results, stored in a variable are being displayed in the command window. How to display the contents of a variable on to a different window?
Thanks!

A: Don't know whether this method suits your need, but try this: suppose variable x has the processed information.
strx = num2str(x);set(handles.textboxname, 'String', strx);

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to get all contact sort order(First,Last or Last,Fast) as iPhone in Swift 2.0 + Xcode +iPhone I need all contact same order of my iPhone Contact.
Some person selected First, Last, or Other Selected Last, First but I need same order as iPhone device setting.
How it is possible with ABAddressBookCopyArrayOfAllPeople?
Does any one help me here?


text:
Q: Using Gitlab Variables in Gitlab README.md for SonarQube Badges I'm using Gitlab and Sonarqube and the Sonarqube Plugin SVG Badges.
To represent the Sonarqube state on gitlab I have something like this in my README.md file:
[![coverage](https://sonar.domain.com/api/badges/measure?key=com.domain:projectname&metric=coverage)](https://sonar.domain.com/component_measures/metric/coverage/list?id=de.domain:projectname)

This works perfect. My badge is shown, the link is working, everything is fine.
Is there some way to build something like:
[![coverage](https://sonar.domain.com/api/badges/measure?key={MYDOMAIN}:{THIS}&metric=coverage)](https://sonar.domain.com/component_measures/metric/coverage/list?id={MYDOMAIN}:{THIS})

I want to provide a skeleton that every Developer just can copy and paste into their README.md file and the variables are filled into the README automatically, with something like .gitlab-ci.yml
I also tried the permanent Gitlab Variables mentioned here but that wasn't working too!
 [![coverage](https://sonar.domain.com/api/badges/measure?key=com.mydomain:$CI_PROJECT_NAME&metric=coverage)](https://sonar.domain.com/component_measures/metric/coverage/list?id={MYDOMAIN}:$CI_PROJECT_NAME)

Anyone has some idea?

A: IMPORTANT!

You should implement a branch/logic to avoid triggering the .gitlab-ci.yml in an infinite loop because you are asking to update a repository file from the CI itself

The approach is:

*

*Prepare README.md with special delimiters around the badge

*Substitute old/initial badge by payload (you should build it, not
shown here) in the repository loaded README.md

*urlencode the substituted content

*Update the repository with the Gitlab API

README.md
Hello
[//]: # (-- start --)
Initial non working badge
[//]: # (-- end --)
World

.gitlab-ci.yml
update_readme:
  script:
  - curl --request PUT --header 'PRIVATE-TOKEN: 9koXpg98eAheJpvBs5tK' 'https://gitlab.example.com/api/v4/projects/13083/repository/README%2Emd?branch=master&content=$(urlencode "$(sed 's_\[//\]: # (-- end --)_\n&_g;s_\(\[//\]: # (-- start --)\)[^\n]*\n_\1\npayload\n_g' README.md)")&commit_message=update%20file'

In sed command, substitute payload with your actual badge (you should build it, not shown here)

*

*The solution is to write the README.md using the Update existing file in repository API

*The README.md should use the special string delimiters that do not appear rendered (they are like hidden comments). These delimiters are always in the file, they do not get substituted. Only what it is in between them get subtituted. This way you can automatically update the badge each time you run the .gitlab-ci.yml (only the badge get updated)

*The substitution is done by the sed command so you need to add the path to the README.md

*The update API needs the content to be urlencoded (so the sed command is wrapped by a bash urlencode() function that should be loaded first (loading not shown):

urlencode()
urlencode() {
    # urlencode <string>
    old_lc_collate=$LC_COLLATE
    LC_COLLATE=C

    local length="${#1}"
    for (( i = 0; i < length; i++ )); do
        local c="${1:i:1}"
        case $c in
            [a-zA-Z0-9.~_-]) printf "$c" ;;
            *) printf '%%%02X' "'$c" ;;
        esac
    done

    LC_COLLATE=$old_lc_collate
}

Notes:
The [//]: # (-- start --) does not affect the render of your README.md so you can use it like hidden comments
Replace your private token with a Gitlab CI Secret variable

A: The variables in https://gitlab.com/help/ci/variables/README.md are present only in a CI environment (i.e. a job), so you can't use them in the Markdown viewer when displaying the file. - That's a great idea for a feature proposal, though. I opened one - https://gitlab.com/gitlab-org/gitlab-ce/issues/32255. Feel free to chime in.
What you could do is add a placeholder where you want those variables to go and then create a job which sed's them.
update_readme:
  script:
    - echo $CI_PROJECT_NAME # Sanity check
    - sed -ie "s/{THIS}/$CI_PROJECT_NAME/g" README.md

Note the use of double-quotes (") and not single quotes ('). Using double-quotes will interpolate $CI_PROJECT_NAME while single-quotes would just retain it's literal value.


text:
Q: How to configure Jenkins for proxy Apparently there is no way to configure proxy in Jenkins. The proxy settings that are available through "Manage Jenkins --> Manage Plugins --> Advanced" are only for plugins. So if I try to configure it there, I still don't see this configuration on System Properties page.
The only way that I managed to configure the proxy successfully is via command line, for example:
java -Dhttp.proxyHost=<host> -Dhttp.proxyPort=<port> -Dhttps.proxyHost=<host> -Dhttps.proxyPort=<port> -DJENKINS_HOME="C:\.jenkins" -jar jenkins.war --httpPort=<port>

But I have Jenkins set up as Windows service and not sure how can I supply these command line parameters. When I look at the task managed, Jenkins process appears with a bunch of parameters but I am not sure where does it read it from.

A: I found that the parameters Jenkins starts with are configured in: jenkins.xml file in Jenkins home directory in the <arguments></arguments> variable.
It is possible to just add the java parameters into this field. To verify that the parameters had been accepted, go to Manage Jenkins --> System Information and view the list of System Properties used by Jenkins. For example, the parameters that I needed:


text:
Q: Low PCA loadings (especially on PC1 and most others) I have a set of 100 variables and aim to reduce my data dimension for further subsequent analyses. There are about 300 observations.
Upon prcomp() in R (with retx= TRUE), my PC1's loadings (abs) are all below 0.20. And, most other PCs' loadings (abs) are also in the range of 0.01-0.30.
How would you do in this situation?
Thank you.

A: Please make sure you scale the data before PCA. If you don't then the loadings can get skewed. Set the scale variable in prcomp to 'TRUE'.


text:
Q: New quests don't appear I've put distress beacon, then I haven't seen any UFO, just couple penguins, I've killed them and then there's happened nothing, no new quests etc. What should I do and/or what did I wrong? Should/can I summon UFO iteratively?

A: The last (current) quest is just build the distress beacon. Though, with the item you get from defeating the mother-ship you can build a metalwork station so you can make/do more things. What I did was just get some coal and explore the universe.

A: In the current version of the beta, the final quest is completed when you first obtain (build) a distress beacon. There are no further quests.

A: Don't know if this is on time, but the UFO should be there ups in the sky.
Try jumping to see it or use a bow to hit it and see the bar, it usally sticks to a player (Now) and it's fairly easy to kill.

A: Press "E" on the Distress Beacon

A: Yeah, no more quest so far. Now you need to get the molten core from mothership, for me it was full of penguin like creatures with some heavy weapons.(To defeat the mothership you need to place high stairs in the air to jump and hit the mothership). With the molten core you build a new metalwork station and in that station you can upgrade de star map, is like a computer card. Now you put that computer card in your conckpit and now you can go to tier 2 or B stars section, there you find new worlds with higer level threat and now you can build robots and high tech stuff, even a brain. (I am just eploring this so I Dont know more).

A: You can make another distress beacon.  You still don't get any quests beyond this, but you DO need the item that the penguin ship drops for further building.


text:
Q: Command for displaying the logs of celery worker from the server in Docker container? I wanted to add celery to my docker file, which I added and when I deployed the changes to the server, I am able to see that celery is doing its job by executing the jobs faster. But, if I want to see the celery worker logs like "celery -A tasks worker --loglevel=info", this works in local machine and I am able to see all the logs.
But, in my server, since I am only able to see the logs of the docker container, can anyone guide me or tell me the command by which I can see whether celery is working fine or not in the production phase.
This is my docker-compose file structure:
services:
  "name":
    image: "image_name"
    ports:
      - "ports"
    environment:
      - "environment variables"
    networks:
      - "networks"

  celery_worker:
    build:
      context: ./parsers
    command: celery -A parsers worker --loglevel=info
    volumes:
      - ./parsers:/parsers
    depends_on:
      - "image"

Now, I want to see the logs of the celery worker too.
Currently, I am able to see the server logs through the command
sudo docker logs -f "name"

A: So, the answer to my question is:

*

*Like I had created a docker file and added celery as a service, so this made a new image of celery in the docker container, and to check the logs of the celery worker, I used the following command  sudo docker logs -f "Image_name_of_celery"

*You can check all the running docker containers and images using the following command: sudo docker ps. This will show the results.

A: Are you sure that in your build of the Dockerfile the celery will be symlink from the celery log to the stdout or stderr?


text:
Q: DataBinding.ObservableArrayList not updating when data added via RoomDatabase.Callback() onCreate() on first app open I've been reading this article from a Google Developer Advocate on best practices with Room. It mentions using the RoomDatabase.Callback() to add data to the database when it's first created.
This all works fine but when the Activity loads the data hasn't been added. Once the data has been added, my data binding doesn't update with the new data. However, on reopening the app, it will have the data. Is this some race condition that I'm running into? I'm using Dagger2 which isn't included in the example code.
@Volatile private var andiDatabase: AndiDatabase? = null

private fun getInstance(): AndiDatabase =
    andiDatabase ?: synchronized(this) {
        andiDatabase ?: buildDatabase().also { andiDatabase = it }
    }

private fun buildDatabase(): AndiDatabase {
    return Room.databaseBuilder(application.applicationContext, AndiDatabase::class.java,
        "andi-database")
        .addCallback(object : RoomDatabase.Callback() {
            override fun onCreate(db: SupportSQLiteDatabase) {
                super.onCreate(db)
                ioThread {
                    getInstance().andiDAO().insert(*databasePopulator.getAndisList())
                }
            }
        })
        .fallbackToDestructiveMigration()
        .build()
}

@Provides
@Singleton
fun provideAndiDatabase(): AndiDatabase {
    return buildDatabase()
}

My ViewModel:
val andis: LiveData<List<Andi>> = andiDao.getAllAndis()
val andisList: ObservableArrayList<Andi> = ObservableArrayList()

The observing is done in my Activity's onCreate():
private fun observeDatabase() {
    viewModel.andis
        .observe(this, Observer {
            it?.let {
                viewModel.andisList.clear()
                viewModel.andisList.addAll(it)
            }
        })
}

On debugging this, only the empty value is observed.


text:
Q: Scraping Indeed with Beautiful Soup I'm unfamiliar with html and web scraping with beautiful soup. I'm trying to retrieve Job titles, salaries, location and company name from various indeed job postings. This is my code so far:
URL = "http://www.indeed.com/jobs?q=data+scientist+%2420%2C000&l=New+York&start=10"
import urllib2
import bs4
from bs4 import BeautifulSoup
soup = BeautifulSoup(urllib2.urlopen(URL).read())
resultcol = soup.find_all(id = 'resultsCol')
company = soup.findAll('span', attrs={"class":"company"})
jobs = (soup.find_all({'class': " row result"}))

though I have the commands to find jobs and company, I can't get the contents. I'm aware there's a contents command, but none of my variables so far have that attribute. Thanks!

A: First I seach div with one job all elements and then I search elements inside this div
import urllib2
from bs4 import BeautifulSoup

URL = "http://www.indeed.com/jobs?q=data+scientist+%2420%2C000&l=New+York&start=10"

soup = BeautifulSoup(urllib2.urlopen(URL).read(), 'html.parser')

results = soup.find_all('div', attrs={'data-tn-component': 'organicJob'})

for x in results:
    company = x.find('span', attrs={"itemprop":"name"})
    print 'company:', company.text.strip()

    job = x.find('a', attrs={'data-tn-element': "jobTitle"})
    print 'job:', job.text.strip()

    salary = x.find('nobr')
    if salary:
        print 'salary:', salary.text.strip()

    print '----------'

A: updated @furas example, for python3:
import urllib.request
from bs4 import BeautifulSoup

URL = "https://www.indeed.com/jobs?q=data+scientist+%2420%2C000&l=New+York&start=10"

soup = BeautifulSoup(urllib.request.urlopen(URL).read(), 'html.parser')

results = soup.find_all('div', attrs={'data-tn-component': 'organicJob'})

for x in results:

    company = x.find('span', attrs={"class":"company"})
    if company:
        print('company:', company.text.strip() )

    job = x.find('a', attrs={'data-tn-element': "jobTitle"})
    if job:
        print('job:', job.text.strip())

    salary = x.find('nobr')
    if salary:
        print('salary:', salary.text.strip())

    print ('----------')


text:
Q: Get only elements that are not repeating in an XML I have a scenario where the XML doc contains some nodes that are repeating. I want to get rid of all such nodes.
Please note that this is not "Removing Duplicates". I want to completely remove all entries of those nodes that are occuring more than once.
Ex
My XML
<ReadUserOBSResponse>
 <UserOBS>
  <OBSObjectId>1510</OBSObjectId>
  <UserObjectId>443</UserObjectId>
 </UserOBS>
 <UserOBS>
  <OBSObjectId>540</OBSObjectId>
  <UserObjectId>514</UserObjectId>
 </UserOBS>
 <UserOBS>
  <OBSObjectId>1521</OBSObjectId>
  <UserObjectId>514</UserObjectId>
 </UserOBS>
 <UserOBS>
  <OBSObjectId>547</OBSObjectId>
  <UserObjectId>544</UserObjectId>
 </UserOBS>
</ReadUserOBSResponse>

Desired Output : I want to remove both entries with UserObjectId 514
<ReadUserOBSResponse>
 <UserOBS>
  <OBSObjectId>1510</OBSObjectId>
  <UserObjectId>443</UserObjectId>
 </UserOBS>
 <UserOBS>
  <OBSObjectId>547</OBSObjectId>
  <UserObjectId>544</UserObjectId>
 </UserOBS>
</ReadUserOBSResponse>

I've done some things, but its not working. My Idea was to count the nodes with UserObjectId as the current value, put this in an xsl:if and then print the nodes.
But I'm not sure how to write this snippet.

A: This will do what you need.
It has a template for UserOBS elements that checks whether there is exactly one UserOBS child of its parent that has the same value for UserObjectId. If so the entire node is copied to the output.
<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">

    <xsl:strip-space elements="*"/>
    <xsl:output method="xml" indent="yes"/>

    <xsl:template match="/ReadUserOBSResponse">
        <xsl:copy>
            <xsl:apply-templates/>
        </xsl:copy>
    </xsl:template>

    <xsl:template match="UserOBS">
        <xsl:if test="count(../UserOBS[UserObjectId = current()/UserObjectId]) = 1">
            <xsl:copy-of select="."/>
        </xsl:if>
    </xsl:template>

</xsl:stylesheet>

output
<?xml version="1.0" encoding="utf-8"?>
<ReadUserOBSResponse>
   <UserOBS>
      <OBSObjectId>1510</OBSObjectId>
      <UserObjectId>443</UserObjectId>
   </UserOBS>
   <UserOBS>
      <OBSObjectId>547</OBSObjectId>
      <UserObjectId>544</UserObjectId>
   </UserOBS>
</ReadUserOBSResponse>

A: Here is a very efficient (and concise) approach that uses keys:
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
  <xsl:output method="xml" indent="yes" omit-xml-declaration="yes"/>
  <xsl:strip-space elements="*" />
  <xsl:key name="kUOId" match="UserOBS" use="UserObjectId" />

  <xsl:template match="@* | node()">
    <xsl:copy>
      <xsl:apply-templates select="@* | node()"/>
    </xsl:copy>
  </xsl:template>

  <xsl:template match="UserOBS[key('kUOId', UserObjectId)[2]]" />
</xsl:stylesheet>

When run on your sample input, the result is:
<ReadUserOBSResponse>
  <UserOBS>
    <OBSObjectId>1510</OBSObjectId>
    <UserObjectId>443</UserObjectId>
  </UserOBS>
  <UserOBS>
    <OBSObjectId>547</OBSObjectId>
    <UserObjectId>544</UserObjectId>
  </UserOBS>
</ReadUserOBSResponse>

A: Much simpler in XSLT 2.0:
<xsl:for-each-group select="UserObs" group-by="UserObjectId">
  <xsl:copy-of select="current-group()[last()=1]"/>
</xsl:for-each-group>


text:
Q: How to copy turbo c++ output? How to copy turbo c++ output? I already Googled the problem but in vain. It says press print scrn and paste or right click and mark all and paste. I tried the both but not working. The problem is that it's only copying what is present on the current screen. But I want the whole screen from the beginning. (alt+printscrn not working either). How can I tackle this situation.
printScrn
Alt+printScrn
markall

none of them are working !!
for some reason i need this old way of programming i can't help with it but i would like to get a solution for the same . i have tried redirecting the output stream to the the file this way but it won't works .
#include<iostream.h>
#include<conio.h>
#include<stdlib.h>
const int max=50;
class dequeue{
int dq[max],r,f,c,x,i;
public:
dequeue();
void insertRear();
void insertFront();
void deleteFront();
void display();
};
dequeue::dequeue(){
f=r=-1;
c=0;
}
void dequeue::insertRear()
{
if((f==r+1)||(f==0)&&(r==max-1)){
cout<<"overflow";
return;
}
if(f==-1)
f=r=0;
else
{
if(r==max-1)
r=0;
else
r++;
}
cout<<"enter element";
cin>>x;
dq[r]=x;
c++;
}
void dequeue::insertFront(){
if((f==r+1)||(f==0)&&(r==max-1)){
cout<<"overflow";
return;
}
if(f==-1)
f=r=0;
else
{
if(f==0)
f=max-1;
else
f++;
}
cout<<"enter element:";
cin>>x;
dq[f]=x;
c++;
}
void dequeue::deleteFront(){
if(f==-1){
cout<<"deque empty";
return;
}
x=dq[f];
c--;
if(f==r)
f=r=-1;
else{
if(f==max-1)
f=0;
else
f++;
}
cout<<x<<"deleted!!!";
}
void dequeue::display(){
if(f==-1){
cout<<"dequeue empty";
return;
}
cout<<"\n"<<c<<"item in deque are:";
cout<<"\n(front)";
i=f;
if(i!=-1){
while(1){
cout<<" "<<dq[i];
if(i==r)
break;
if(i==max-1)
i=0;
else
i++;

}
}
cout<<"(rear)";
}
void main(){
freopen("output.txt","w",stdout); //this is not working
clrscr();
dequeue d;
int ch;
do{
cout<<"\n Menu";
cout<<"\n 1.insert at front";
cout<<"\n 2.insert at rear";
cout<<"\n 3.delet from front";
cout<<"\n 4.display";
cout<<"\n 5.exit \n";
cout<<"Enter your choice:";
cin>>ch;
switch(ch){
case 1:
d.insertFront();
break;
case 2:
d.insertRear();
break;
case 3:
d.deleteFront();
break;
case 4:
d.display();
break;
case 5:
exit(0);
break;
default:
cout<<"\n invalid";
}
}
while(ch!=5);
getch();
}

A: I've tried one thing, and it worked, albeit it contains a handful number of steps.

*

*Compile and Run your program, and exit to the editor window

*Now, Go to "Window" tab menu > "Output"

*The Output window opens, now open the "Edit" menu > select "Copy" > then again open the "Editor" menu > select "Show clipboard"

*The Clipboard window opens up, now select "File" menu > "Save As", and save the file in a .txt file at an appropriate location.

*You can browse to that location in explorer to get the text file.

A: You can always capture the output of a program by redirecting the standard output stream.
Suppose your program is called exercise1.exe. Then you can call it like that from the command line:
exercise1 >awesome.txt

Then you can simply open awesome.txt with the text editor of your choice and see the entire output.

A: Run the Program.
open the output using Window->Output .
then go to Edit->Show clipboard
then save the file with any other name
Then open My computer/This Pc .Click on Local disk (C:)->TurboC4->TC->BIN and right click on the name of the file select Edit
the file will open in Notepad
Then save the file as per your requirement using  Save As option.
Hope this helps you.

A: Buddy,  follow these steps :-

*

*Press PrintSrc on the output screen

*The screen gets captured

*You can only paste it a rich text document like MS-WORD

*Then right click on the image inside the WORD and click on save as an image.

:-)

A: *

*Run your program.

*Now Right Click on black screen

*Select Mark option

*Now Drag Mouse pointer to the Area u want to copy by pressing left
mouse button. The area will be highlighted will while background.

*Press Enter.

*Open Your word document.

*Select Paste option from Edit Menu (or Press Ctrl+v)


text:
Q: Processing SOAP request with Content-Type = "application/x-www-form-urlencoded" in Java I have a SOAP client sending through a request with it's Content-Type defined as application/x-www-form-urlencoded. My jax-ws server responds with a HTTP 415 error complaining that it expects a content-type of text/xml.
Evidently this client cannot be changed so am trying to find out if there is anyway to force my server to accept this content-type?

A: Tichodrama was right.  The client was not a soap client.  It was instead sending xml over HTTP POST.

A: I was dealing with the same issue and finally i had to add a servlet that accepts Content-Type defined as application/x-www-form-urlencoded and internally this servlet invokes all the SOAP logic behind.


text:
Q: NSBundle pathForResource returns nil I've been trying to load a simple text file in a unit test for an iOS app.
NSString* resourcePath = [[NSBundle mainBundle] pathForResource: @"stopPointsInCircleData" ofType:@"txt"];
NSString* stopPointData = [NSData dataWithContentsOfFile: resourcePath];

My problem is that pathForResource returns nil.
The file stopPointsInCircleData.txt is located in the directory of the test code and the file is listed correctly under "Copy Bundle Resources" in the "Build Phases" of the test target.
I've tried to relax the search by setting ofType to nil, but thet didn't work either.
Any help is very much apprechiated.

A: There is simple way to achieve that, you can emulate that bundle path:
Just head to
Project -> TestTarget -> Build Settings -> Unit Testing (Test Host) and just insert:
    $(BUILT_PRODUCTS_DIR)/AppName.app

Happy testing.

A: Your problem is that in a unit test target, -mainBundle doesn't refer to the test target bundle but instead to the bundle of the executable in which the test target is injected. In the case of ios test targets, this is your app bundle; in Mac test targets it may either be the app bundle or the OCUnit runner.
You should look for resources in your test target's bundle. Inside a test class, it's done like this:
NSBundle *myBundle = [NSBundle bundleForClass: [self class]];


text:
Q: Limit Number of attachments with Java on a SharePoint new form item? I'm currently using this bit of code in a content editor on the newform in a sharepoint list to check and make sure there is an attachment on a new item form:
<script type="text/javascript" language="javascript">

function PreSaveAction() { if
(document.getElementById('idAttachmentsRow').style.display=='none' ) { >
alert('Attachment is Mandatory! Please attach Documents.'); return false ; }
else { return true; } } </script>

Is there anyway to use some similar code to make sure a user only uploads 1 attachment and not multiples?
Bonus question:  Is there a simple method to either set a column value when a user changes/upload a different/new attachment or replaces the current one atatched to a sharepoint list item?

A: Try below js solution.
<script type="text/javascript" src="https://code.jquery.com/jquery-1.12.4.js"></script>
     <script type="text/javascript">
            function PreSaveAction() {
                var attachementCount=$('#idAttachmentsTable').find('tr').length;
                if (attachementCount < 1) {
                    alert("Attachment is Mandatory!");
                    return false;
                } else
                    return true;
            }
        </script>


text:
Q: What PUBLIC access means on tables in Oracle? I recieved a communication from my DBA that they want to revoke PUBLIC access and they shared attached screenshot. What does this mean by PUBLIC access on these tables? And what happen if they "Revoke" the access.

I don't know the query which result is this. Can anyone help to understand this resultset. I want to understand the impact on my application if they revoke this access.

A: Grants and Revokes of Privileges to and from the PUBLIC Role

You can grant and revoke privileges and roles from the role PUBLIC.
Because PUBLIC is accessible to every database user, all privileges
and roles granted to PUBLIC are accessible to every database user. By
  default, PUBLIC does not have privileges granted to it.
Security administrators and database users should grant a privilege or
  role to PUBLIC only if every database user requires the privilege or
  role. This recommendation reinforces the general rule that, at any
  given time, each database user should have only the privileges
  required to accomplish the current group tasks successfully.
Revoking a privilege from the PUBLIC role can cause significant
  cascading effects. If any privilege related to a DML operation is
  revoked from PUBLIC (for example, SELECT ANY TABLE or UPDATE ON emp),
  then all procedures in the database, including functions and packages,
  must be reauthorized before they can be used again. Therefore, be
  careful when you grant and revoke DML-related privileges to or from
  PUBLIC.

If you do not use the above packages, it will not have any impact on your application.


text:
Q: Prevent implicit conversions from float to double in C++ Basically, if I want something like this,
double b = sin(2.2);

but accidentally write something like this,
double b = sin(2.2f);

there is no error or even warning message, even though this clearly leads to a different, inaccurate, and therefore incorrect result. This type of error could be prevented, by forcing the compiler to not do any implicit conversions of float to double. Is there any way to achieve this, be it through a compilation switch (preferably in Visual Studio), some smart macros, or a class which behaves like float/double variables and declares its own operators?
Edit: I am also interested in solving similar problems using operators (such as e.g. double b = 2.2f*2.2f), or assignments (double b=2.2f).

A: You can use a type_assert utility.
Example:
#include <cmath>
#include <type_traits>

template<typename T, typename U>
const U& type_assert(const U& u) {
    static_assert(std::is_same<T, U>::value, "...");
    return u;
}

int main() {
    double t = type_assert<double>(std::sin(2.2f));
}

If the expected type is different then it'll give you a compiler error. Chances are the compiler could probably optimise this if it passes though, at least it did in my case with -O3.

A: You can render the call of sin(float) ambiguous by defining something like
double sin(float x) { abort(); }

Then calls of sin on a float will give you a compile-time error.  This works because, in the cmath header, std::sin is an overloaded function with float sin(float), double sin(double), and long double sin(long double) variants.  The compiler cannot know whether you wanted ::sin(float) or std::sin(float), so it throws up its hands in confusion.
I wouldn't necessarily recommend leaving this sort of thing around in your codebase, but it can be useful if you're trying to find all instances of a mistake like this and correct them.

A: Something like that?
class MyDouble{
public:
  MyDouble(float _f) {throw "only use double!";}
  MyDouble(double _d) : m_data(_d) {}

  operator float() const {throw "conversion to float occurred!";}
  operator double() const {return m_data;}

private:
  double m_data;
};

but yes, you'd have to start using this class in your calls to math functions, making it very ugly:
MyDouble d(3.2);
sin(d);
// or...
cos(MyDouble(2.3));

UPDATE - an example of an operator implementation (binary operator, as unary would have to be part of the class):
MyDouble operator+(const & MyDouble _lhs, const & MyDouble _rhs){
  MyDouble rez(_lhs);
  rez += _rhs;
  return rez;
}

Of course you don't have to implement it that way (through the use of a shortcut operator+=) but this makes code easier to maintain

A: I just realized you're using a Microsoft product, but I'll leave this answer since it could help someone else.
Have you looked through the compiler switches?  I imagine there is a similar option.
OMG! I just searched for help with Visual Studio Options and Warnings! (link)
I'm SO sorry! I didn't know!  That is one of the least helpful listings of options and switches I've ever seen!  Even more ironic, they've begun scraping StackOverflow for answers and linking back here.
But I did find some clues:
Compiler Warning (levels 3 and 4) C4244 -
conversion' conversion from 'type1' to 'type2', possible loss of data
Used thusly:
// Enable this to find unintended double to float conversions.
// warning C4244: 'initializing' : conversion from 'double' to 'float', possible loss of data
#pragma warning(3 : 4244)

GCC/G++ switches (
Why not let the compiler tell you when you accidentally do this?
From the g++/gcc man page:
-Wdouble-promotion (C, C++, Objective-C and Objective-C++ only)
  * Give a warning when a value of type "float" is implicitly promoted to "double".
    ... some verbage clipped ...
  * It is easy to accidentally do computations with "double" because floating-point
    literals are implicitly of type "double".

Adding -Wdouble-promotion to your CXXFLAGS should provide you with compile-time warnings.
There is also -fsingle-precision-constant which prohibits implicit conversion of floats to doubles.


text:
Q: python Bad Interpreter error I am trying to install Sublime Text 2 on my linux machine and I cannot figure out how to run the python script to install it. I am fairly new to linux and never programmed in python before. I am trying to run the python script PackageSetup.py using ./PackageSetup.py but i get the error:
bash: ./PackageSetup.py: python: bad interpreter: No such file or directory

not sure what I have to do. I have python on my machine. I can tell cause running 'python' puts me in the console.

A: For all I know this kind of issue can occur if you have a misspelling or mistake in the shebang. I see two ways to solve this issue: you can try to invoke PackageSetup.py via python, like python PackageSetup.py or you can open PackageSetup.py and try to find an issue in the shebang, maybe it needs to be a full path to python interpreter like /usr/bin/python not just python.
BTW, why don't you try to install it via some kind of package manager - there is a repo for debian-based distros, and I'm pretty sure that there have to be repositories for other distributives.


text:
Q: co-ordinate geometry question Find the equation of the lines which passes through the point (3,4) and whose intercept on y-axis is twice that of x-axis ?

A: $y = ax+b$. You have two equations: $4 = 3a +b$, $y_0 = 2x_0$. Can you take it from here.

A: Let our x intercept be (x,0), then let the y intercept be (0, 2x)
Let us then get the slope of the line passing through these two points,
(0-2x)/(x-0) = -2

since the line also passes through (3,4)
y-4=-2(x-3)
y=-2x +10

which can also be written as 2x +y -10 =0

A: Let the intercepts of the unknown line be $a$ & $2a$ on x-axis & y-axis respectively then we have the equation of the line: (using intercept form) $$\frac{x}{a}+\frac{y}{2a}=1$$ $$2x+y=2a$$ Since the lines passes through the point $(3, 4)$ hence satisfying the equation by the point $(3, 4)$ as follows $$2(3)+4=2a \implies a=\frac{10}{2}=5$$ Hence, substituting the value of $a=5$, the equation of the line: $$\color{blue}{2x+y=10}$$


text:
Q: Java: My ArrayList empties itself as soon as I empty the text file from which the ArrayList gets its contents I´m writing my own library in java, where you can save variables very simple. But I have a problem in changing the values of the variables. The ArrayList empties itself as soon as the txt file is empty.
My Code:
    public class SaveGameWriter {
    private File file;
    private boolean closed = false;
    public void write(SaveGameFile savegamefile, String variableName, String variableValue, SaveGameReader reader) throws FileNotFoundException
    {
        if(!reader.read(savegamefile).contains(variableName))
        {
        file = savegamefile.getFile();
        OutputStream stream = new FileOutputStream(file, true);
        try {
            String text = variableName+"="+variableValue;
            stream.write(text.getBytes());
            String lineSeparator = System.getProperty("line.separator");
            stream.write(lineSeparator.getBytes());
        }catch(IOException e)
        {}
        do {
            try {
                stream.close();
                closed = true;
            } catch (Exception e) {
                closed = false;
            }
        } while (!closed);
        }
    }

    public void setValueOf(SaveGameFile savegamefile, String variableName, String Value, SaveGameReader reader) throws IOException
    {
        ArrayList<String> list = reader.read(savegamefile);
        if(list.contains(variableName))
        {
            list.set(list.indexOf(variableName), Value);
            savegamefile.clear();
            for(int i = 0; i<list.size()-1;i+=2)
            {
                write(savegamefile,list.get(i),list.get(i+1),reader);
            }
        }
    }
}

Here my SaveGameReader class:
    public class SaveGameReader {
    private File file;
    private ArrayList<String> result = new ArrayList<>();
    public String getValueOf(SaveGameFile savegamefile, String variableName)
    {
        ArrayList<String> list = read(savegamefile);
        if(list.contains(variableName))
        {
            return list.get(list.indexOf(variableName)+1);
        }else
            return null;
    }
    public ArrayList<String> read(SaveGameFile savegamefile) {
        result.clear();
        file = savegamefile.getFile();
        BufferedReader in = null;
        try {
            in = new BufferedReader(new FileReader(file));
            String read = null;
            while ((read = in.readLine()) != null) {

                String[] splited = read.split("=");
                for (String part : splited) {
                    result.add(part);
                }
            }
        } catch (IOException e) {
        } finally {
            boolean closed = false;
            while(!closed)
            {
            try {
                in.close();
                closed=true;
            } catch (Exception e) {
                closed=false;
            }
            }
        }
        result.remove("");
        return result;
    }
}

And my SaveGameFile class:
    public class SaveGameFile {
    private File file;
    public void create(String destination, String filename) throws IOException {
        file = new File(destination+"/"+filename+".savegame");
        if(!file.exists())
        {
            file.createNewFile();
        }
    }
    public File getFile() {
        return file;
    }
    public void clear() throws IOException
    {
        PrintWriter pw = new PrintWriter(file.getPath());
        pw.close();
    }

}

So, when I call the setValueOf() methode the ArrayList is empty and in the txt file there´s just the first variable + value. Hier´s my data structure:
Name=Testperson
Age=40
Phone=1234
Money=1000

What´s the problem with my code?

A: In your SaveGameReader.read() method you have result.clear(); which clears ArrayList. And you do it even before opening the file. So basically before every read from file operation you are cleaning up existing state and reread from file. If file is empty then you finish with empty list


text:
Q: how to delete data from different  i am loading two
 on single page, both holding same userID. I want to delete user data from 2nd
. how is it possible. Here is my controller code for delete..
HTML

      Partner Detail

#if($editPartnerDetail)
 <form id="editPartnerDetail" class="aui" onsubmit="return validateEditForm()">

        Admin Name:	<input type="text" value="$editPartnerDetail.adminName" id="editAdminName" name="editAdminName" size="55" />

        Email:	<input type="text" value="$editPartnerDetail.email" id="editEmail" name="editEmail" size="55" />

        Phone:	<input type="text" value="$editPartnerDetail.phone" id="editPhone" name="editPhone" size="55" />

        <input type="hidden" value="$editPartnerDetail.partnerDetailId" id="editPartnerDetailId" name="editPartnerDetailId" size="55" />
        <input type="hidden" value="$editPartnerDetail.partnerSiteId" id="editPartnerSiteId" name="editPartnerSiteId" size="55" />

        	<input type="submit" value="Update" class="button" />     Cancel

  </form>
#else
 <form id="addPartnerDetail" class="aui" onsubmit="return validateForm()">

        Admin Name:	<input type="text" value="" id="adminName" name="adminName" size="55" autocomplete="off"/>

        Email:	<input type="text" value="" id="email" name="email" size="55" autocomplete="off"/>

        Phone:	<input type="text" value="" id="phone" name="phone" size="55" autocomplete="off"/>

        <input type="hidden" value="$siteId" id="addPartnerSiteId" name="addPartnerSiteId" size="55" />

        	<input type="submit" value="Add" class="button" />

  </form>
#end

            Admin Name
            Email
            Phone
            Action

            #foreach( $partnerDetail in $partnerDetailList )

            $partnerDetail.adminName
            $partnerDetail.email
            $partnerDetail.phone
            Edit | Delete

          #end

        #if($editPartnerSite2)
        <form id="editsite2" class="aui">

              <input type="text" value="$editPartnerSite2.partnerSite" id="editPartnerSite" name="editPartnerSite" size="55" />
            <input type="hidden" value="$editPartnerSite2.partnerId" id="editPartnerSiteId" name="editPartnerSiteId" size="55" />
            <input type="hidden" value="site" id="page" name="page" size="55" />

            <input type="submit" value="Update" class="button">
            Cancel
             #if($isSiteupdated == false)

Cannot Edit. Same partner site already exist.

            #end

         </form>
        #else
        <form id="addsite" class="aui">

            <input type="hidden" value="site" id="page" name="page" size="55" />
            <input type="text" id="partnersite" name="partnersite" size="55" autocomplete="off" value="$!existingSite"/>

<input type="submit" value="Add" class="button" />

            #if($isSiteAdded == false)

Cannot add. Same partner site already exist.

            #end

        </form>

        #end

            Partner Site
            Action

           #foreach( $partnerSite in $partnerSiteList )

            $partnerSite.partnerSite
            Edit | Delete

          #end

Controller
else if (pageName != null && pageName.equals("partnerDetail")) {
        Map<String, Object> context = new HashMap<String, Object>();
        if (request.getParameter("nameId") != null && request.getParameter("nameId") != "") {
            siteId = Integer.parseInt(request.getParameter("nameId"));
            String mode = request.getParameter("mode");
            if (mode != null && mode.equals("delete")) {
                String pdId = request.getParameter("pdId");
                if (pdId != null && pdId != "") {
                    partnerDetailService.deletePartneDetail(Integer.parseInt(pdId));
                }
            }

            if (mode != null && mode.equals("edit")) {
                String pdId = request.getParameter("pdId");
                int partnerDetailID = Integer.parseInt(pdId);
                if (pdId != null && pdId != "") {
                    PartnerDetail editPartnerDetail = partnerDetailService.getPartneDetailById(partnerDetailID);
                    context.put("editPartnerDetail", editPartnerDetail);
                }
            }
        }

        if (request.getParameter("nameId") != null && request.getParameter("nameId") != "") {
            siteId = Integer.parseInt(request.getParameter("nameId"));
            String mode = request.getParameter("mode");
            if (mode != null && mode.equals("deleteTab2")) {
                String sId = request.getParameter("sId");
                if (sId != null && sId != "") {
                    partnerSiteService.deletePartnerSite(Integer.parseInt(sId));
                }
            }
        }

        //===========================
        context.put("siteId", siteId);

        List<PartnerDetail> partnerDetailList = partnerDetailService.getAllDetailByPartnerSiteID(siteId);
        context.put("partnerDetailList", partnerDetailList);

        String partnerId = request.getParameter("nameId");
        int pID = Integer.parseInt(partnerId);
        List<PartnerSite> partnerSiteList =  partnerDetailService.getAllPartnerSiteById(pID);
        context.put("partnerSiteList", partnerSiteList);

        response.setContentType("text/html;charset=utf-8");
        renderer.render("templates/admin/partnerDetail.vm", context,response.getWriter());

help me out..

A: You should never use the same ID on two elements!
It's better to use class instead. The id-attribute is reserved for unique idintifiers


text:
Q: How to construct an explicit isomorphism between two special endomorphism rings Let $\Lambda$ be an artin algebra and $M$ a $\Lambda$-module. Let $\Gamma:=\text{End}_\Lambda(M)$ and let $D$ be the standard duality.

How can you give an explicit isomorphism $\text{End}_\Gamma(M)\cong \text{End}_{{\Gamma}^{\scriptstyle{op}}}(D(M))$?

Thanks for the help!

A: Note that $\text{End}_\Gamma(M)$ is precisely the center of $\Gamma = \text{End}_{\Lambda}(M)$.
Let $\varphi \in \text{End}_{\Gamma}(M)$. Consider $D \varphi: DM \rightarrow DM$. I claim that $D \varphi$ is a $\Gamma^\text{op}$-module homomorphism. Note that given $\psi \in \Gamma$, the action of $\Gamma^{\text{op}}$ on $DM$ is given by $\psi \cdot f := f \circ \psi$ (this makes sense because both $f: M \rightarrow \Lambda$, and $\psi: M \rightarrow M$ are $\Lambda$-linear maps). Now we check
\begin{align*}
D \varphi(\psi \cdot f) &= D\varphi(f \circ \psi) = (f \circ \psi) \circ \varphi  \\
&=f \circ (\psi \circ \varphi)
 = f \circ (\varphi \circ \psi) \\
&= (f \circ \varphi) \circ \psi = \psi \cdot (f \circ \varphi) \\
&= \psi \cdot D\varphi(f)
\end{align*}
for every $f \in DM$ and $\psi \in \Gamma$.


text:
Q: open cv ios video processing I'm trying to do the tutorial found here for ios video processing with openCv framework.
I've successfully loaded the ios openCv framework to my project - but there seems to be a mismatch between my framework and the one presented in the tutorial and I am hoping someone can help me.
OpenCv uses cv::Mat type for representing images. When using AVfoundation delegation to process images from the camera - I will need to convert all the CMSampleBufferRef to that type.
It seems that the openCV framework presented in the tutorial provides a library called using
#import <opencv2/highgui/cap_ios.h>

with a new delegate command:

Can anyone point me where I can find this framework or possibly fast conversion between CMSampleBufferRef and cv::Mat
EDIT
There is a lot of segmentation in the opencv framework (at least for ios). I've downloaded it through various "official" sites and also using tools such as fink and brew using THEIR instructions. I even compared header files that were installed to /usr/local/include/opencv/. They were different each time. When downloading an openCV project - there are various cmake files and conflicting readme files in the same project. I think I was successful in building a good version for IOS with avcapture functionality built in to the framework (with this header <opencv2/highgui/cap_ios.h>) through this link  and then building the library using the python script in the ios directory - using the command python opencv/ios/build_framework.py ios. I will try and update

A: This is the updated version of the code in the previous accepted answer which should work with any iOS device.
Since bufferWidth is not equal to bytePerRow at least on iPhone 6 and iPhone 6+, we need to specify the number of byte in each rows as the last argument to the cv::Mat constructor.
CVImageBufferRef pixelBuffer = CMSampleBufferGetImageBuffer(sampleBuffer);

CVPixelBufferLockBaseAddress(pixelBuffer, 0);

int bufferWidth = CVPixelBufferGetWidth(pixelBuffer);
int bufferHeight = CVPixelBufferGetHeight(pixelBuffer);
int bytePerRow = CVPixelBufferGetBytesPerRow(pixelBuffer);
unsigned char *pixel = (unsigned char *) CVPixelBufferGetBaseAddress(pixelBuffer);
cv::Mat image = cv::Mat(bufferHeight, bufferWidth, CV_8UC4, pixel, bytePerRow);

// Process you cv::Mat here

CVPixelBufferUnlockBaseAddress(pixelBuffer, 0);

The code has been tested on my iPhone5, iPhone6 and iPhone6+ running iOS 10.

A: Here is the conversion that I use.  You lock the pixel buffer, create a cv::Mat, process with the cv::Mat, then unlock the pixel buffer.
- (void)captureOutput:(AVCaptureOutput *)captureOutput didOutputSampleBuffer:(CMSampleBufferRef)sampleBuffer fromConnection:(AVCaptureConnection *)connection
{
CVImageBufferRef pixelBuffer = CMSampleBufferGetImageBuffer(sampleBuffer);

CVPixelBufferLockBaseAddress( pixelBuffer, 0 );

int bufferWidth = CVPixelBufferGetWidth(pixelBuffer);
int bufferHeight = CVPixelBufferGetHeight(pixelBuffer);
int bytesPerRow = CVPixelBufferGetBytesPerRow(pixelBuffer);
unsigned char *pixel = (unsigned char *)CVPixelBufferGetBaseAddress(pixelBuffer);
cv::Mat image = cv::Mat(bufferHeight,bufferWidth,CV_8UC4,pixel, bytesPerRow); //put buffer in open cv, no memory copied
//Processing here

//End processing
CVPixelBufferUnlockBaseAddress( pixelBuffer, 0 );
}

The above method does not copy any memory and as such you do not own the memory, pixelBuffer will free it for you.  If you want your own copy of the buffer, just do
cv::Mat copied_image = image.clone();


text:
Q: How can I assign initial data to some variables in literal object before use I have an literal object which do something, this object must assigns some initial data to variables before use any of its methods.
var slideshow = {

    slideshowBox: null,
    slideImages: null,
    slideImagesLen: 0,

    init: function(){
        this.slideshowBox = document.getElementById('slideshow');
        this.slideImages = document.getElementById('images');
        this.slideImagesLen = this.slideImages.children.length;
    },
    show: function(){
        return this.slideImagesLen;
    }

};

But the problem when use any of its method you must firstly use init method then use I can use any of other methods, but this behavior is not good.
slideshow.init()
console.log(slideshow.show());

Also I have tried to use the following way:
(function(){
    var slideshow = {

        slideshowBox: null,
        slideImages: null,
        slideImagesLen: 0,

        init: function(){
            this.slideshowBox = document.getElementById('slideshow');
            this.slideImages = document.getElementById('images');
            this.slideImagesLen = this.slideImages.children.length;
        },
        show: function(){
            return this.slideImagesLen;
        }
    };
    slideshow.init();
})();

But, there are  some errors like this.slideImages is null, slideshow.show is not a function
I want any way to call init method automatically before use any method and without need to calls it manually.

A: you should try to use prototypal inheritance with a constructor here.
(function(){
  var Slideshow = function () {
    this.slideshowBox = document.getElementById('slideshow');
    this.slideImages = document.getElementById('images');
    this.slideImagesLen = this.slideImages.children.length;
  };

  Slideshow.prototype.show = function () {
    return this.slideImagesLen;
  };

  var slideShowInstance = new Slideshow();
  slideShowInstance.show();

})();

I actually would go a bit further to make it more extendable
  var Slideshow = function (slideShowId, images) {
    this.slideshowBox = slideShowId;
    this.slideImages = images;
    this.slideImagesLen = this.slideImages.children.length;
  };

  var slideShowId = document.getElementById('slideshow'),
      images = document.getElementById('images');

  var slideShowInstance = new Slideshow(slideShowId, images);

A: Try returning Object _slideshow , after calling _slideshow.init within function slides

var slides = function(options) {
  return (function(opts) {
  var _slideshow = opts || {

    slideshowBox: null,
    slideImages: null,
    slideImagesLen: 0,

    init: function() {
      this.slideshowBox = document.getElementById('slideshow');
      this.slideImages = document.getElementById('images');
      this.slideImagesLen = this.slideImages.children.length;
    },
    show: function() {
      return this.slideImagesLen;
    }

  };
  _slideshow.init();
  return Object.create(_slideshow)
}(options))
};

var slideshow = slides();

console.log("slideImagesLen:", slideshow.show(), "slideshow:", slideshow);

A: There are a couple of ways. For example:
var slideshow = {
        ...
    init: function () {
            ...
        return this;
    }
        ...
}.init();

Or if that's still too manual, you can simply use an IIFE within the object literal:
var slideshow = {
        ...
    init: (function init () {
            ...
        return init;
    }())
        ...
}

In both cases the referred HTML elements must exist before creating the object.


text:
Q: Costumize indicators from stock tools I'm trying to implement some technical indicators series and add them to the indicators popop from stock tools. If I import highcharts/indicators/indicators-all I end up getting dozens of indicators, so I figured to import only the ones I need, so far I wasn't able to achieve that, if I import highcharts/indicators/indicators I end up getting only SMA, I tried to import other technical indicators via highcharts/indicators/indicators-INDICATOR-NAME but it didn't work.
Besides that I'd like to create a technical indicator/function such as Linear Regression (from this example) and attach them to the indicators popup as well.
function getLinearRegression(xData, yData) {
  var sumX = 0,
    sumY = 0,
    sumXY = 0,
    sumX2 = 0,
    linearData = [],
    linearXData = [],
    linearYData = [],
    n = xData.length,
    alpha,
    beta,
    i,
    x,
    y;

  // Get sums:
  for (i = 0; i < n; i++) {
    x = xData[i];
    y = yData[i];
    sumX += x;
    sumY += y;
    sumXY += x * y;
    sumX2 += x * x;
  }

  // Get slope and offset:
  alpha = (n * sumXY - sumX * sumY) / (n * sumX2 - sumX * sumX);
  if (isNaN(alpha)) {
    alpha = 0;
  }
  beta = (sumY - alpha * sumX) / n;

  // Calculate linear regression:
  for (i = 0; i < n; i++) {
    x = xData[i];
    y = alpha * x + beta;

    // Prepare arrays required for getValues() method
    linearData[i] = [x, y];
    linearXData[i] = x;
    linearYData[i] = y;
  }

  return {
    xData: linearXData,
    yData: linearYData,
    values: linearData
  };
}

Is that even possible?
Live Demo

EDIT
To add a specific technical indicator you should add as an import highcharts/indicators/NAME (highcharts/indicators/ema,
highcharts/indicators/rsi e.g.)

A: That feature is not implemented in stock tools, but it could be very useful so you can create a new feature request here: https://github.com/highcharts/highcharts/issues/new/choose
Workaround:
All indicator series from plot options are added to stock tools, so you can customize chart.options.plotOptions, for example in load event:
chart: {
  events: {
    load: function() {
      var plotOptions = this.options.plotOptions,
        filteredSeries = {};

      Highcharts.objectEach(plotOptions, function(option, key) {
        if (!option.params || key === 'dema' || key === 'customlinearregression') {
          filteredSeries[key] = option;
        }
      });

      this.options.plotOptions = filteredSeries;
    }
  }
}

Live demo: https://jsfiddle.net/BlackLabel/xwec9hr7/2/
Useful example: https://www.highcharts.com/stock/demo/stock-tools-custom-gui
Code reference: https://github.com/highcharts/highcharts/blob/371424be0b168de96aa6a58b81ce0b2b7f40d5c5/ts/annotations/popup.ts#L783


text:
Q: How to avoid selecting first value in single select list of values type mandatory input control in jasper reports I'm using JasperReports 6.0.1. i am creating a report where one input control is single select list of values which is mandatory and i am giving three name and value pairs.
here is my parameter
<parameter name="daily_weekly_monthly" class="java.lang.String"/>

when i run my report by default first name is being selected i don't want to do that i want user to select from the drop down when he runs report. how can i achieve it? i guess there might be an attribute to put in jrxml?

A: You need to specify the Report unit to 'Always Prompt' for input controls.
From Repository Explorer, select your report and select 'Edit'. From here, click on the 'Controls & Resource'. Here you will see Input Control Options, where there is a checkbox named 'Always Prompt'. Check this to enable prompting all the time.


text:
Q: Uncaught (in promise) TypeError: Something went wrong while trying to open the window I'm getting above error, while trying to open new link while clicking the web push notification.
My code is working fine, i mean i am able to open the link after clicking the notification but getting this error in console, also when i am putting any hardcoded url then its showing not error in console.
Any help would be appreciated.
This is my service-worker.js code
var link;
try{
self.addEventListener('push', function(e) {
    var data = e.data.json();
    var title = data.title;

        var options = {
            body: data.body
        };
        if(data.link){
            link = data.link;
        }

        if(data.badge){
            options.badge = data.badge;
        }

        if(data.icon){
            options.icon = data.icon;
        }

        if(data.image){
            options.image = data.image;
        }

        e.waitUntil(self.registration.showNotification(title, options));

 });
}
  catch(error){
  console.log('error while sending push notification');
}
 self.addEventListener('notificationclick', function(event) {

 event.notification.close();
 event.waitUntil(clients.openWindow(link));
});

A: Ran into this issue while trying to implement click action on web push notifications. Using preventDefault() resolved it;
https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault


text:
Q: Push values in an array from an array of objects I have an array of object as follows. I want to basically loop through the projects.current_result and get all the values.
let data = [
    {
        vertical_name: "CORE",
        projects: [
            {
                name: "Alpha",
                id: 187,
                current_result: {
                    success: 0,
                    failure: 0,
                    skip: 0,
                    untested: 100
                }
            }
        ]
    },
    {
        vertical_name: "release",
        projects: [
            {
                name: "Beta",
                id: 27,
                current_result: {
                    success: 50,
                    failure: 20,
                    skip: 36,
                    untested: 0
                }
            },
            {
                name: "Charlie",
                id: 47,
                current_result: {
                    success: 37,
                    failure: 25,
                    skip: 40,
                    untested: 0
                }
            }
        ]
    }
  ]

for e.g. i want to get success values of each of the projects and put all of those values in an array. So in this case success= [0,50,37] Similarly, i want to put values for failure, skip and untested
failure=[0,20,25]
skip=[0,36,40]
untested=[100,0,0]

I tried achieving that with below code but somehow i am not able to get desired result. Any advice on how to correct this code please
let alteredResponse = data.forEach(prj => {
     prj.reduce((result, {
    count
  }) => {
    result.success.push(count.success|| 0);
    result.failure.push(count.failure || 0);
    result.skip.push(count.skip || 0);
    result.untested.push(count.untested || 0);
    return result;
  }, {
    success: [],
    failure: [],
    skip: [],
    untested: []
  })
  });

A: You can achieve this with two forEach
Logic

*

*Loop though each nodes in data

*Loop through each nodes in projects from the nodes in data

*Push success, failure, skip, untested nodes from project node to respective result node.

Working Fiddle

const data = [{"vertical_name":"CORE","projects":[{"name":"Alpha","id":187,"current_result":{"success":0,"failure":0,"skip":0,"untested":100}}]},{"vertical_name":"release","projects":[{"name":"Beta","id":27,"current_result":{"success":50,"failure":20,"skip":36,"untested":0}},{"name":"Charlie","id":47,"current_result":{"success":37,"failure":25,"skip":40,"untested":0}}]}];

const result = {
  success: [],
  failure: [],
  skip: [],
  untested: [],
}

const alteredResponse = data.forEach(prj => {
  prj.projects.forEach((project) => {
    result.success.push(project.current_result.success);
    result.failure.push(project.current_result.failure);
    result.skip.push(project.current_result.skip);
    result.untested.push(project.current_result.untested);
  })
});
console.log(result);

A: You could try this approach

*

*first map to get the projects

*flatten the projects

*map the projects to get the current_results

*reduce to combine all the results into one final object

let data = [ { vertical_name: "CORE", projects: [ { name: "Alpha", id: 187, current_result: { success: 0, failure: 0, skip: 0, untested: 100, }, }, ], }, { vertical_name: "release", projects: [ { name: "Beta", id: 27, current_result: { success: 50, failure: 20, skip: 36, untested: 0, }, }, { name: "Charlie", id: 47, current_result: { success: 37, failure: 25, skip: 40, untested: 0, }, }, ], }, ]

const res = data
  .map(({ projects }) => projects)
  .flat()
  .map(({ current_result }) => current_result)
  .reduce((acc, el) => {
    for (const [key, value] of Object.entries(el)) {
      if (!acc[key]) {
        acc[key] = [value]
      } else {
        acc[key].push(value)
      }
    }
    return acc
  }, {})

console.log(res)

A: Using predefined arrays could be much easier and readable:

const data = [ { vertical_name: 'CORE', projects: [ { name: 'Alpha', id: 187, current_result: { success: 0, failure: 0, skip: 0, untested: 100, }, }, ], }, { vertical_name: 'release', projects: [ { name: 'Beta', id: 27, current_result: { success: 50, failure: 20, skip: 36, untested: 0, }, }, { name: 'Charlie', id: 47, current_result: { success: 37, failure: 25, skip: 40, untested: 0, }, }, ], }, ];

const success = [];
const failure = [];
const skip = [];
const untested = [];

data.forEach((prj) => {
  prj.projects.forEach(({ current_result }) => {
    success.push(current_result.success || 0);
    failure.push(current_result.failure || 0);
    skip.push(current_result.skip || 0);
    untested.push(current_result.untested || 0);
  });
});

console.log("success", success);
console.log("failure", failure);
console.log("skip", skip);
console.log("untested", untested);

A:

const data = [
  {
    vertical_name: 'CORE',
    projects: [
      {
        name: 'Alpha',
        id: 187,
        current_result: {
          success: 0,
          failure: 0,
          skip: 0,
          untested: 100
        }
      }
    ]
  },
  {
    vertical_name: 'release',
    projects: [
      {
        name: 'Beta',
        id: 27,
        current_result: {
          success: 50,
          failure: 20,
          skip: 36,
          untested: 0
        }
      },
      {
        name: 'Charlie',
        id: 47,
        current_result: {
          success: 37,
          failure: 25,
          skip: 40,
          untested: 0
        }
      }
    ]
  }
];

const result = {
  success: [],
  failure: [],
  skip: [],
  untested: []
};
data.forEach((prj) => {
  prj.projects.reduce((_, { current_result }) => {
    result.success.push(current_result.success || 0);
    result.failure.push(current_result.failure || 0);
    result.skip.push(current_result.skip || 0);
    result.untested.push(current_result.untested || 0);
    return result;
  }, result);
});

console.log(result);


text:
Q: Invoking Javascript method in HTML My javascript file(test.js) has Method1() method defined.
<script src="../Scripts/test.js" type="text/javascript"></script>

My html is defined as below. I get Method1() not found. Any ideas?
<p><input type="button" name="login" id="login" value="Login" onclick="Method1()"/> </p>

Here is the code in test.js declared...
<script type="text/javascript">

 function LoginToServer() {

......
}

</script>

A: The code in .js file is a JavaScript code, not HTML markup.
This:
<script type="text/javascript">
</script>

is HTML markup, not a JavaScript code. You should remove that from test.js.
As you didn't show us exactly how your Method1 is defined, I'll assume it is ok and this is the only error.

A: The reason Method1() isn't detected is because your test.js has a syntax error - the <script></script> tags.
Remove the opening and closing <script> tags from your test.js and everything should work properly.
function LoginToServer() {
//function code
}

.js files should only contain JavaScript code.
.html files may also contain JavaScript, but then the code has to be surrounded by <script></script>.
Also, you don't have to provide the type="text/javascript" because HTML5 knows it is going to be JavaScript in-between those tags.


text:
Q: Setting layout extents using expressions in qgis layout editor Is there a way to set my extents using a specific feature's bounds in my qgis layout? I thought of using expressions in the "Extents" box, but i am not sure whether it is possible to refer to a feature's bounds directly via the expression editor in the layout. If there is a way would someone please indicate how?
From the layout editor window:

EDIT
I tried the following expression but don't know what to do from there:
get_feature('Segments_f03a4f8c_62f6_4377_b8fb_d6f60a9016ce', "Segment", 2)
What does get_feature return? How can I extract the geometry from that? Can I then use the bounds method to get min and max bound values from the extracted feature?

A: It looks like you can use something like:
 x(point_n(bounds(geometry(get_feature_by_id('Boundary-line-ceremonial-counties_region', 1))),1))
 y(point_n(bounds(geometry(get_feature_by_id('Boundary-line-ceremonial-counties_region', 1))),1))

to get the min-x/y of the bounds of the first feature in the layer ('Boundary-line-ceremonial_counties_region).
 x(point_n(bounds(geometry(get_feature_by_id('Boundary-line-ceremonial-counties_region', 1))),3))
 y(point_n(bounds(geometry(get_feature_by_id('Boundary-line-ceremonial-counties_region', 1))),3))

to get the max x/y.
PS. get_feature returns Returns the first feature of a layer matching a given attribute value. While get_feature_by_id returns the feature with an id on a layer.


text:
Q: How to start jw player automatically? Here is my embed code:
<embed width="576" height="432" flashvars="&
    file=kgalive&
    streamer=rtmp://5.77.33.107/kga" wmode="opaque"
    allowscriptaccess="always" allowfullscreen="true"
    quality="high" name="player" id="player" style=""
    src="player.swf" autostart="always"
    type="application/x-shockwave-flash"/>

It works, but my player will not start automaticaly while opening the webpage. What should I do to start my player automatically?

A: I think it should be
autostart="true"

I do it this way:
<object id="mediaplayer" width="100%" height="100%" type="application/x-shockwave-flash" data="jwplayer/player.swf" bgcolor="#000000" name="mediaplayer" tabindex="0">
  <param name="allowfullscreen" value="true">
  <param name="allowscriptaccess" value="always">
  <param name="seamlesstabbing" value="true">
  <param name="wmode" value="opaque">
  <param name="flashvars" value="netstreambasepath=<URLHERE>&id=mediaplayer&autostart=true&repeat=always&shuffle=false&controlbar.position=none">
</object>

A: Basically:
<embed width="576" height="432" flashvars="&
    file=kgalive&
    streamer=rtmp://5.77.33.107/kga" wmode="opaque"
    allowscriptaccess="always" allowfullscreen="true"
    quality="high" name="player" id="player" style=""
    src="player.swf" autostart="always"
    type="application/x-shockwave-flash"/>

Needs to be:
<embed width="576" height="432" flashvars="&
    autostart=true&file=kgalive&
    streamer=rtmp://5.77.33.107/kga" wmode="opaque"
    allowscriptaccess="always" allowfullscreen="true"
    quality="high" name="player" id="player" style=""
    src="player.swf" autostart="always"
    type="application/x-shockwave-flash"/>


text:
Q: Parsing og: tags with ColdFusion regex If one wants to extract/match Open Graph (og:) tags from html, using regex (and ColdFusion 9+), how would one go about doing it?
And the tricky bit is that is has to cover both possible variations of tag formation as in the following examples:
<meta property="og:type" content="website" />
<meta content="website" property="og:type"/>

So far all I got is this:
<cfset tags = ReMatch('(og:)(.*?)>',html_content)>

It does match both of the links, however only the first type has the content bit returned with it. And content is something that I require.
Just to make it absolutely clear, the desired output should be an array with all of the OG tags (they could be 'type,image,author,description etc.). That means it should be flexible and not based on the og:type example alone.
Of course if it's possible, the ideal output would be a struct with the first column being the name of tag, and the second containing the value (content). But that can be achieved with the post processing and is not as important as extracting the tags themselves.
Cheers,
Simon

A: So you want an array like ['og:author','og:type', 'og:image'...]?
Try using a regex like og:([\w]+)
That should give you a start.   You will have duplicates if you have two of the same og:foo meta tags.
You can look at JSoup also to help parse the HTML for you.  It makes it a lot easier.
There are a few good blog posts on using it in CFML
jQuery-like parsing in Java
Parsing, Traversing, And Mutating HTML With ColdFusion And jSoup

A: Ok, so after the suggestion from @abbottmw (thank you very much!), here's the solution:
Download Jsoup jar file from here: http://jsoup.org/download
Then initiate it like this:
<cfhttp url="...." result="oghtml" > /*to get your html content*/
<cfscript>
    paths = expandPath("/lib/jsoup.jar"); //or wherever you decide to place the file
    loaderObj =createObject("component","javaloader.JavaLoader").init([expandPath('/lib/jsoup.jar')]);
    jsoup = loaderObj.create("org.jsoup.Jsoup");
    doc = jsoup.parse(oghtml);
    tags = doc.select("meta[property*=og:]");
</cfscript>
<cfloop index="e" array="#tags#">
    <cfoutput>
        #e.attr("property")# | #e.attr("content")#<br />
    </cfoutput>
</cfloop>

And that is it. The complete list of og tags is in the [tags] array.
Of course it's not the regex solutions, which was originally requested, but hey, it works!


text:
Q: How to handle the promise of a fetch without nested callbacks? I guess that fetch returns a promise. But how do I handle it nicely? The code below does not quite work. I get {message: "Internal server error custom: TypeError: Cannot read property 'then' of undefined"}.
exports.handler = (event, context, callback) => {
    try {
        getDiscourseId(username, callback).then((userId) => {
            callback(null, {
                statusCode: 200,
                headers: {},
                body: JSON.stringify({
                    userId: userId
                })
            });
        });

    } catch (error) {
        callback(null, {
            statusCode: 500,
            headers: {},
            body: JSON.stringify({
                message: "Internal server error custom: " + error
            })
        });
    }
};

function getDiscourseId(username) {
    console.log({username: username, discourseApiKey: discourseApiKey, discourseApiUser: discourseApiUser})
    fetch(`https://${domain}/users/${username}.json?api_key=${discourseApiKey}&api_username=${discourseApiUser}`, {
        headers: {
            'Content-Type': 'application/x-www-form-urlencoded',
            'Accept': 'application/json'
        },
        method: 'GET',
    })
    .then(response => {
        return response.json();
    })
    .then(data => {
        if (data) {
            return data.user.id;
        }
    })
    .catch(err => {
        return {err: err};
    });
}

A: You're getting that error because your getDiscourseId function does not return a value.
If you add the keyword return in front of your fetch(...) call, you should start making some headway.
You'll probably also want to remove the .catch from inside getDiscourseId and instead add it to the end of the call to getDiscourseId inside your handler:
exports.handler = (event, context, callback) => {
    getDiscourseId(username)
        .then((userId) => {
            callback(null, {
                statusCode: 200,
                headers: {},
                body: JSON.stringify({
                    userId: userId
                })
            });
        })
        .catch(error => {
            callback(null, {
                statusCode: 500,
                headers: {},
                body: JSON.stringify({
                    message: "Internal server error custom: " + error
                })
            });
        });
};

function getDiscourseId(username) {
    console.log({username: username, discourseApiKey: discourseApiKey, discourseApiUser: discourseApiUser})
    return fetch(`https://${domain}/users/${username}.json?api_key=${discourseApiKey}&api_username=${discourseApiUser}`, {
        headers: {
            'Content-Type': 'application/x-www-form-urlencoded',
            'Accept': 'application/json'
        },
        method: 'GET',
    })
    .then(response => {
        if (!response.ok) { // h/t TJ Crowder
            throw new Error("Failed with HTTP code " + response.status);
        }
        return response.json();
    })
    .then(data => {
        if (data) {
            return data.user.id;
        }
    });
}

EDIT: TJ Crowder is correct that you probably want to treat 4xx and 5xx responses as full-fledged errors. I shamelessly stole his example code from his blog and added it to the above.

A: Stop when you return the response.json(). This returns a promise, for which .then can be used.
You are returning the userId which .then cannot be used for.
If you stop at the return response.json(), you can use the '.then' statement that you already have (data.user.id => ...).


text:
Q: Make server side rendered React app work offline with service worker I would like to know how to resolve the following failed Lighthouse audits for a server side rendered React application.

*

*Current page does not respond with a 200 when offline

*start_url does not respond with a 200 when offline

I am able to generate and register a service worker using the workbox-webpack-plugin and precache the javascript and stylesheets.
However, since the app is server side rendered, there is no index.html to cache and the app is unable to "respond with a 200 when offline". Concretely, when I go offline and refresh the web page, I am met with browsers' offline message.
I think a possible solution is to generate an app shell (an html document containing the app ready to be rendered on the client side), cache that app shell and use it when offline. However I do not know where to start. Any ideas, or alternative suggestions?


text:
Q: Position representation of product of two operators If two operators $\hat{a},\hat{b}$ have their position representations as $a, b$ ( both $a, b$ are operators but here they act on wavefunctions rather than kets) then is it true in general that the operator $\hat{a}\hat{b}$ , which is a product of the two operators  has its position representation as the product of the position representation of the individual operators i.e is the position representation of $\hat{a}\hat{b}$ given as $a b$ ?

A: Let the wavefunction of $|\psi\rangle$ be $\psi (x)$
Let $a, b$ be the position representation of $A, B$.
Then we've $b \psi (x)=
 \langle x | B|\psi\rangle$ .
Let $f(x)=\langle x | B|\psi\rangle$ be wavefunction of $|f\rangle$
Then we've $a f (x)=
 \langle x | A|f\rangle$
Then $\begin{aligned} a b \psi(x) &=a\langle x|\hat{B}| \psi\rangle=a f(x) \\ &=\langle x|\hat{A}| f\rangle \\=\langle x|\hat{A}| \hat{B} \mid \psi\rangle \end{aligned}$


text:
Q: LAMP stack performance under heavy traffic loads I know the title of my question is rather vague, so I'll try to clarify as much as I can. Please feel free to moderate this question to make it more useful for the community.
Given a standard LAMP stack with more or less default settings (a bit of tuning is allowed, client-side and server-side caching turned on), running on modern hardware (16Gb RAM, 8-core CPU, unlimited disk space, etc), deploying a reasonably complicated CMS service (a Drupal or Wordpress project for arguments sake) - what amounts of traffic, SQL queries, user requests can I resonably expect to accommodate before I have to start thinking about performance?
NOTE: I know that specifics will greatly depend on the details of the project, i.e. optimizing MySQL queries, indexing stuff, minimizing filesystem hits - assuming web developers did a professional job - I'm really looking for a very rough figure in terms of visits per day, traffic during peak visiting times, how many records before (transactional) MySQL fumbles, so on.
I know the only way to really answer my question is to run load    testing on a real project, and I'm concerned that my question may be treated as partly off-top.
I would like to get a set of figures from people with first-hand experience, e.g. "we ran such and such set-up and it handled at least this much load [problems started surfacing after such and such]". I'm also greatly interested in any condenced (I'm short on time atm) reading I can do to get a better understanding of the matter.
P.S. I'm meeting a client tomorrow to talk about his project, and I want to be prepared to reason about performance if his project turns out to be akin FourSquare.

A: Very tricky to answer without specifics as you have noted. If I was tasked with what you have to do, I would take each component in turn ( network interface, CPU/memory, physical IO load, SMP locking etc) and get the maximum capacity available, divide by rough estimate of use per request.
For example, network io. You might have 1x 1Gb card, which might achieve maybe 100Mbytes/sec. ( I tend to use 80% of theoretical max). How big will a typical 'hit' be? Perhaps 3kbytes average, for HTML, images etc.  that means you can achieve 33k requests per second before you bottleneck at the physical level. These numbers are absolute maximums, depending on tools and skills you might not get anywhere near them, but nobody can exceed these maximums.
Repeat the above for every component, perhaps varying your numbers a little, and you will build a quick picture of what is likely to be a concern. Then, consider how you can quickly get more capacity in each component,  can you just chuck $$ and gain more performance (eg use SSD drives instead of HD)? Or will you hit a limit that cannot be moved without rearchitecting? Also take into account what resources you have available, do you have lots of skilled programmer time, DBAs, or wads of cash? If you have lots of a resource, you can tend to reduce those constraints easier and quicker as you move along the experience curve.
Do not forget external components too, firewalls may have limits that are lower than expected for sustained traffic.
Sorry I cannot give you real numbers, our workloads are using custom servers, high memory caching and other tricks, and not using all the products you list. However, I would concentrate most on IO/SQL queries and possibly network IO, as these tend to be more hard limits, than CPU/memory, although I'm sure others will have a different opinion.

A: Obviously, the question is such that does not have a "proper" answer, but I'd like to close it and give some feedback. The client meeting has taken place, performance was indeed a biggie, their hosting platform turned out to be on the Amazon cloud :)
From research I've done independently:

*

*Memcache is a must;

*MySQL (or whatever persistent storage instance you're running) is usually the first to go. Solutions include running multiple virtual instances and replicate data between them, distributing the load;

*http://highscalability.com/ is a good read :)


text:
Q: Delete Dynamic Row entry I have the  following html  view and javascript :

var rowCount = 1;
$(".add_more_rows").click(function() {
  rowCount++;

  var recRow = '

<input name="" type="text" size="17%"  maxlength="120" />	\n\
<input name="" type="text"  maxlength="120" style="margin: 4px 5px 0 5px;"/>	\n\
<input name="" type="text" maxlength="120" style="margin: 4px 10px 0 0px;"/>	\n\
 Delete Entry

';

  $('.remove_row' + rowCount + '').click(function() {

    $('#rowCount' + rowCount).remove();
  });
  $('#addedRows').append(recRow);

});

      Name
      Email
      Mobile

                                Add More

        <input name="" type="text" value="" size="17%" />

        <input name="" type="text" value="" />

        <input name="" type="text" value="" />

When I click on the  Add more button, a new row should be added to my table which works perfectly and each row is assigned a unique id and class but when I try to click on the  Delete Entry to delete the  specific row, it fails. Please advise what is it that am not doing right on the  remove_row that prevents the trigger to take place and also for the  row not to be deleted.

A: I think you've got a lot of unnecessary code there. You needn't set up individual ids etc. just figure out which
 is being deleted by which anchor tag is being clicked.
$("a.remove_row").on("click", function() {
    $(this).parents("tr").remove();
});

The snippet shows deleting in action:

$(document).ready(function() {
  $("a").on("click", function() {
    $(this).parents("tr").remove();
  });
});

    Line 1
    Line 1
    Line 1
    Line 1
    delete

    Line 2
    Line 2
    Line 2
    Line 2
    delete

    Line 3
    Line 3
    Line 3
    Line 3
    delete

    Line 4
    Line 4
    Line 4
    Line 4
    delete

Side Note:

*

*You definitely shouldn't be wrapping table rows in
 elements (which is why I don't like @Pugazh's answer). It's not invalid in an XML sense but it's very poor html wise. There is also no need, you can add your rowCount directly to you
 (but it's also unnecessary with this answer).

*You should be using css to style input boxes (especially rather than putting it into your template). The fiddle below demonstrates this to a basic degree.

Fully Functional Example:
I have put together this updated fiddle to demonstrate cleanly adding and removing rows (without some of the messiness that you have above). As @Ohohorion says, event bubbling is what you really need to exploit in order to remove rows that have been dynamically inserted. Rather than binding the event to table though, it's better to attach it to the document (as in the fiddle)

A: Select the parent element and remove the same from DOM. I have added below function to the javascript and additoinally added onClick="javascript:fnRemove(this);" to the span
function fnRemove(t){
    $(t).parent('p').remove();
}

var rowCount = 1;
$(".add_more_rows").click(function() {
  rowCount++;

  var recRow = '

<input name="" type="text" size="17%"  maxlength="120" />	\n\
<input name="" type="text"  maxlength="120" style="margin: 4px 5px 0 5px;"/>	\n\
<input name="" type="text" maxlength="120" style="margin: 4px 10px 0 0px;"/>	\n\
 Delete Entry

';

  $('#addedRows').append(recRow);

});

function fnRemove(t) {
  $(t).parent('p').remove();
}

      Name
      Email
      Mobile

                                Add More

        <input name="" type="text" value="" size="17%" />

        <input name="" type="text" value="" />

        <input name="" type="text" value="" />

A: Try this:
 $(document).on('click','.remove_row' + rowCount,function () {

                $('#rowCount' + rowCount).remove();
            });

A: Loads of unnecessary code and bad practises such as wrapping table rows with paragraph tag (
). But it is all about learning. ;)
I advise reading about event bubbling and how it helps in situations like these where you otherwise have to initialise new listener each time.
In this case, instead of initialising a new event listener each time, you can use something like this:
$('table').on('click', '.remove_row', function () {

Instead of:
$('.remove_row' + rowCount + '').click(function () {

Due to rules of event bubbling, the table is triggered too and we pass the second parameter to let JQuery now that we are only interested in events that are triggered by descendants that have 'remove_row' class.
I did quick JSFiddle to check out what I mean and where I have removed extra bits of code and removed bad practises.
I did it quickly so if you find still problems,

A: Try This its working


text:
Q: How to display a custom error page for HTTP status 405 (method not allowed) in Django when using @require_POST My question is simple, how do I display a custom error page for HTTP status 405 (method not allowed) in Django when using the @require_POST decorator?
I'm using the django.views.decorators.http.require_POST decorator, and when the page is visited by GET request, the console shows a 405 error, but the page is just blank (not even a Django error page). How do I get Django to display a custom and/or default error page for this kind of error?
EDIT:
It's worth mentioning that I've tried putting a 404.html, 500.html and 405.html page in my templates folder - but that does not help either. I have also varied between DEBUG = True and False, to no avail.

A: You have to write custom Django middleware. You can start with this one and extend it to check if 405.html file exists and so on:
from django.http import HttpResponseNotAllowed
from django.template import RequestContext
from django.template import loader

class HttpResponseNotAllowedMiddleware(object):
    def process_response(self, request, response):
        if isinstance(response, HttpResponseNotAllowed):
            context = RequestContext(request)
            response.content = loader.render_to_string("405.html", context_instance=context)
        return response

Check docs if you don't know how to install middleware:
http://docs.djangoproject.com/en/dev/topics/http/middleware/
You can also check this article:
http://mitchfournier.com/2010/07/12/show-a-custom-403-forbidden-error-page-in-django/

A: If you look into the documentation and the source code of django.views.defaults you see that only 404 and 500 errors are supported in a way that you only have to add the 404.html resp. 500.html to your templates directory.
In the doc. you can also read the following

Returning HTTP error codes in Django
  is easy. There are subclasses of
  HttpResponse for a number of common
  HTTP status codes other than 200
  (which means "OK"). You can find the
  full list of available subclasses in
  the request/response documentation.

Thus if you want to return a 405 error, you have to use the HttpResponseNotAllowed class
An example

A: I'm not sure that's possible. Perhaps you should consider filing a bug report.

A: I landed here in 2022. The above accepted answer is not working for me. I use django rest framework. My sollution was to create a middleware with
#app/middleware.py

from django.http import HttpResponse
from django.template import loader

class HttpResponseNotAllowedMiddleware:
    def __init__(self, get_response):
    self.get_response = get_response
    # One-time configuration and initialization.

def __call__(self, request):

    # Code to be executed for each request before
    # the view (and later middleware) are called.

    response = self.get_response(request)

    # Code to be executed for each request/response after
    # the view is called.
    if response.status_code == 405:
        context = {}
        template = loader.get_template('app/405.html')
        return HttpResponse(template.render(context, request))

    return response

then install it by adding this to settings
MIDDLEWARE = [
.......
'app.middleware.HttpResponseNotAllowedMiddleware',
]

the 405.html template is just a plain not allowed text


text:
Q: body onload="" cannot find function i am trying stuff with philogl library, and when i wrote,
<!DOCTYPE html>

<html>
<head>
    <title>PGL2</title>
    <script type="text/javascript" src="PhiloGL.js"></script>
    <script type="text/javascript">
    function webGLStart(){
        alert('I m alive');
    }
</script>
</head>

<body onload="webGLStart();">
<canvas id="c" style="width:500px; height:500px;"></canvas>

</body>
</html>

everything works fine, but if i write some philogl in it like,
<!DOCTYPE html>

<html>
<head>
    <title>PGL2</title>
    <script type="text/javascript" src="PhiloGL.js"></script>
    <script type="text/javascript">
    function webGLStart(){
        var triangle = new PhiloGL.O3D.Model({
            vertices: [[0,1,0],[-1,-1,0],[1,-1,0]],
            colors: [[1,0,0,1],[0,1,0,1],[0,0,1,1]]
            });
        var square = new PhiloGL.O3D.Model({
            vertices: [[1,1,0],[-1,1,0],[1,-1,0],[-1,-1,0]],
            colors: [[0.5,0.5,1,1],[0.5,0.5,1,1]],[0.5,0.5,1,1]
            });
    }
</script>
</head>

<body onload="webGLStart();">
<canvas id="c" style="width:500px; height:500px;"></canvas>

</body>
</html>

chrome and firefox gives me an error that says webGLStart() is not defined.
What is wrong with my code?

A: This line:
        colors: [[0.5,0.5,1,1],[0.5,0.5,1,1]],[0.5,0.5,1,1]

is syntactically incorrect: a closing "]" is in the wrong place. Thus the function definition "failed", so to speak, and the function doesn't really exist.
I literally just woke up so I'm not sure what's wrong with me that I could spot that.

A: There must be an error in the way you are using this "philogl", preventing the function from being interpreted fully. In particular, you have a syntax error with your square brackets. The function then remains undefined.
In future you can turn on the error console in Firebug (or the equivalent for your preferred browser) to see what you're doing wrong.
Also, prefer document.onload = function() { ... } in a script, instead of embedding scripting in HTML tags.


text:
Q: Variable incrementing by itself without actually changing it Ok..so I am doing a program on NLP. It uses function eliminateStopWords(). This function reads from a 2D array "sentTokens" (of detected tokens). In the code below, index i is sentence number, j is for each token in the ith sentence.
Now, what my eliminateStopWords() does is this:

*

*it reads stop words from a text file and stores them in a TreeSet

*reads tokens from sentTokens array and checks them for stop words. If they are collocations, then they should not be checked for stop words, they are just dumped into a finalTokens array. If they are not a collection, then they are individually checked for stop words and are added to finalTokens array only if they are not stop words.
The problem comes in the loop of this step 2. Here is some code of it: (I have marked // HERE at the location where the error actually occurs... it's near the end)
private void eliminateStopWords() {

    try {

        // Loading TreeSet for stopwords from the file.
        stopWords = new TreeSet<String> ();
        fin = new File("stopwords.txt");
        fScan = new Scanner(fin);
        while (fScan.hasNextLine())
            stopWords.add(fScan.nextLine());

        fScan.close();

        /* Test code to print all read stopwords
        iter2 = stopWords.iterator();
        while (iter2.hasNext())
            System.out.println(iter2.next()); */

        int k=0,m=0;    // additional indices for finalTokens array
        System.out.println(NO_OF_SENTENCES);

 newSentence: for(i=0; i < NO_OF_SENTENCES; i++)
          {

        System.out.println("i = " + i);
            for (j=0; j < sentTokens[i].length; j+=2)
            {

        System.out.println("j = " + j);

                // otherwsise, get two successive tokens
                    String currToken = sentTokens[i][j];
                    String nextToken = sentTokens[i][j+1];
                    System.out.println("i = " + i);
                    System.out.println(currToken + " " + nextToken);
                    if ( isCollocation(currToken, nextToken) ) {
// if the current and next tokens form a bigram collocation, they are not checked for stop words
                        // but are directly dumped into finalTokens array
                        finalTokens[k][m] = currToken; m++;
                        finalTokens[k][m] = nextToken; m++;
                    }

                    if ( !stopWords.contains(currToken) )
                    {   finalTokens[k][m] = currToken; m++;  }

                    if ( !stopWords.contains(nextToken) )
                    {       finalTokens[k][m] = nextToken; m++; }

                // if current token is the last in the sentence, do not check for collocations, only check for stop words
                // this is done to avoid ArrayIndexOutOfBounds Exception in sentences with odd number of tokens

// HERE
                    System.out.println("i = " + i);

                    if ( j==sentTokens[i].length - 2) {
                    String lastToken = sentTokens [i][++j];
                    if (!stopWords.contains(lastToken))
                    {  finalTokens[k][m] = lastToken; m++; }

                    // after analyzing last token, move to analyzing the next sentence

                    continue newSentence;

                    }
            }

            k++;    // next sentence in finalTokens array
        }

        // Test code to print finalTokens array
           for(i=0; i < NO_OF_SENTENCES; i++) {
               for (j=0; j < finalTokens[i].length; j++)
                   System.out.print( finalTokens[i][j] + " " );

               System.out.println();
           }

    }
        catch (Exception e) {
            e.printStackTrace();
        }
}

I have printed the indices i & j at the entry of their respective for loops...it all works fine for the first iteration of the loop, but when the loop is about to reach its end... I have printed again the value of 'i'. This time it comes out as 14.

*

*it starts the first iteration with 0...

*does not get manipulated anywhere in the loop...

*and just by the end of (only) first iteration, it prints the value as 14

I mean this is seriously the WEIRDEST error I have come across ever while working with Java. It throws up an ArrayIndexOutOfBoundsException just before the final if block. It's like MAGIC. You do nothing on the variable in the code, still the value changes. HOW CAN THIS HAPPEN?

A: You never declared i or j in your code, which leads me to believe that they are fields.
I'm pretty sure that some of your other methods re-use those variables and thus mess with your result. isCollocation looks like a candidate for that.
The counters in for loops should always be local variables, ideally declared inside the for statement itself (for minimal scope). Everything else is just asking for trouble (as you see).