text:
Q: Am I oversimplifying returns? Basically I'm doing the old driver exam program for a uni course and I've drafted out the whole class. When I try to compile it, if working in command prompt, I get the error:

missing return statement

and in Eclipse:

This method must return a result of type int` pertaining to my methods re missed questions.

Now I think I already knew what the problem was before trying to compile - my method is an int type, and because my answers "array is char", when I try to return 'index + 1' or 'index++) it's returning the actual element, a character (i.e. answer a,b,c, d). What I wanted to do was to return the subscript number + 1 (to remove out by one error), so when I write the program, I can system out print 'you missed question 1, 3, 5 etc'.
I realize there are probably a million other errors in this code, but right now I'm just hoping someone can help me with this one. Realize it's probably simple and stupid but have been reading forums and my textbooks for hours and can't figure this out. Maybe I'm trying to simplify too much by just using the subscript + 1 as a means of showing question number missed.
public class DriverExam {

private char[] rightAnswers = { 'b', 'd', 'a', 'a', 'c', 'a', 'b', 'a',
'c', 'd', 'b', 'c', 'd', 'a', 'd', 'c', 'c', 'b', 'd', 'a' }; //Answers
to test.
char[] Answers; //Student answer input.
int[] missed = {}; //Array for missed questions.
int correct = 0; //Create and initialise to 0.
int qMissed = 0; //Create and initialise to 0.

/**
Constructor that accepts array of answers and copies to the answers array
field.
@parem ans The array of student driver answers */

public DriverExam(char[] ans)
{
Answers = ans;
}

/**
An int array containing the question numbers of those questions that the
student missed.
*/

public int questionsMissed()

{
for (int index = 0; index < 20; index++) //Ask program to step through
each element in array Answers.
    {
    if (Answers[index] == 0) //I'm assuming here that a question not
    answered = 0, not null as it would for string.
        return index + 1; //I want to return the subscript assigned to
    any questions that = 0 ie haven't been answered, plus 1 to avoid out
    by one error.
    }
    }

public int qMissed()
{
for (int index = 0; index < 20; index++) //Ask program to step through
each element in array Answers.
    {
    if (Answers[index] == 0) //Asking it to repeat process above.
        return index++; //I want to ask it to take the subscript and add
1 to the existing subscript for all additional missed questions.
        }
}

/**
A method that returns the total number of correctly answered questions.
@return Returns the number of correctly answered questions.
*/

public int totalCorrect()
{
for (int index = 0; index < Answers.length; index++)
{
if (Answers[index] == rightAnswers[index])
correct++;
}
return correct;
}

/**
A method that returns the total number of incorrectly answered questions.
@return Returns the number of incorrect answers.
*/

public int totalIncorrect()
{
    int incorrect = (rightAnswers.length - (totalCorrect() + qMissed));
    return incorrect;
}

/**
A method that returns true if the student passed the exam, or false if
the student failed.
*/

public boolean passed()
{
    if(totalCorrect() >= 10); return true;
}

}

A: You need to add a line to return an int for the else part. When you have a non-void return type in a function, you need to explicitly return a value for all code branches (if-else).
public int questionsMissed()

{
for (int index = 0; index < 20; index++)
    {
    if (Answers[index] == 0)
        return index + 1;
    }

return a int here for ex return -1

}

A: If your method has declared to return int it must return int for any case,if you want to loop for all items and check whether array contains '0' or not.If all fails return -1 or throw Exception
public int questionsMissed() {
    for (int index = 0; index < 20; index++) {
        if (Answers[index] == 0) {
            return index + 1;
        }
    }
  return -1;//If nothing works
}

Note: You should start name of variable with lower case. answer and not Answer

A: The warning is because in both functions questionsMissed and qMissed the return types should be int. Which you are returning inside the loop after checking the if condition, which is absolutely correct, but what happens when the if statement never evaluates to true, your function will never return anything, that is why the warnings. To avoid this you should add a return statement after for loop.

A: A couple of suggestions:
1) Your approach of saving the correct answers in an array is a good one.  So is the idea of passing the actual answers to the constructor.  Good!
2) Instead of iterating through both arrays every time you want to know the #/correct answers, or #/incorrect answers - it's probably more efficient to loop through the array just ONCE, and save everything you need for future reference.  In your case, I did this in the constructor.
3) Sooner or later, you'll encounter "Java Beans", and "getter and setter" methods.  Stringly speaking, your "DriverExam" isn't a Java Bean (it doesn't have a zero-argument constructor), but the standard "getter" naming convention is useful.  I've marked your fields "private" and changed your access methods to the "getter" naming convention: getTotalCorrect(), etc.
4) I also added a check if the student happened to answer fewer questions than the whole test.
Here is the modified code:
public class DriverExam {

    //Answers to test
    private char[] rightAnswers = {
        'b', 'd', 'a', 'a', 'c', 'a', 'b', 'a',
        'c', 'd', 'b', 'c', 'd', 'a', 'd', 'c', 'c', 'b', 'd', 'a'
    };

    private boolean[] results;
    private int totalCorrect = 0; //Create and initialise to 0.
    private int totalMissed = 0; //Create and initialise to 0.

    /**
    Constructor that accepts array of answers, grades the text, and computes #/correct and #/missed
    */
    public DriverExam(char[] ans)   {
        // Allocate array to hold results
        results = new boolean[rightAnswers.length];

        // Grade the test
        for (int i=0; i < rightAnswers.length; i++) {
            // ... Q: Did student complete this part of the test?
            if (i > ans.length-1) {
                results[i] = false;  //  Mark "incorrect"
                totalMissed++;
            }
            else if (ans[i] != rightAnswers[i]) {
                results[i] = false; // Mark "incorrect"
                totalMissed++;
            }
            else {
                results[i] = true;  // Mark "correct"
                totalCorrect++;

            }
        }
    }

    /**
    An boolean array containing which questions were answered correctly, and which weren't
    */
    public boolean[] getResults() {
        return results;
    }

    /**
    A method that returns the total number of correctly answered questions.
    */
    public int getTotalCorrect()    {
        return totalCorrect;
    }

    /**
    A method that returns the total number of questions missed.
    */
    public int getTotalMissed() {
        return totalMissed;
    }

    /**
    A method that returns true if the student passed the exam, or false if
    the student failed.
    */
    public boolean isPassed()   {
        return (totalCorrect >= 10);
    }

    /**
     * Test driver
     */
    public static void main (String[] args) {
        char[] myAnswers = {
            'b', 'x', 'x', 'a', 'c', 'a', 'b', 'a',
            'c', 'd', 'b', 'c', 'd', 'a', 'd', 'c', 'c', 'b', 'd', 'a'
        };

        DriverExam myExam = new DriverExam (myAnswers);
        System.out.println ("#/correct=" + myExam.getTotalCorrect() + ", #/missed=" + myExam.getTotalMissed() + ", passed=" + myExam.isPassed());
        System.out.println("Questions missed: ");
        boolean[] myResults = myExam.getResults();
        for (int i=0; i < myResults.length; i++) {
            if (myResults[i] == false)
                System.out.println ("  " + i);
        }

    }
}

And here is sample output:
#/correct=18, #/missed=2, passed=true
Questions missed:
  1
  2

A: I think that returning index++ or index + 1 should be fine, but it appears that not all of your code paths are returning an int. For instance, in questionsMissed() you have an if statement to check for 0 and return an int in that case, but if the check returns false no int is getting returned. You might change it to something like this:
public int questionsMissed()
{
    for (int index = 0; index < 20; index++)
    {
        if (Answers[index] == 0)
        {
            return index + 1;
        }
    }
    return 0;
}


text:
Q: Display posts, category name and post-comments in 1 query I have 3 tables in my database:

*

*posts

*categories and

*comments.

I want to display columns from the 3 tables in one query. Right now I'm only displaying columns from posts and categories tables. But I also want to display the comments on each post which have the same post_id.
The three tables includes these columns:
POSTS
    id, cat_id, title, contents, image, date_posted

CATEGORIES
    id, name, date

COMMENTS
    id, post_id, name, comment, date

I have this MySQL query right now:
SELECT
    posts.id AS post_id,
    categories.id AS category_id,
    title,
    contents,
    image,
    date_posted,
    categories.name
FROM posts
INNER JOIN categories ON categories.id = posts.cat_id;

But I also want to display comments in each post and I don't know how to change the query.

A: This depends on the implementation, if you want to retrieve all data in one query:
SELECT posts.id AS post_id, categories.id AS category_id, title, contents, image, date_posted, categories.name, comments.name as comments, comments.comment, comments.date
FROM posts
INNER JOIN categories ON categories.id = posts.cat_id
LEFT JOIN comments ON comments.post_id = posts.post_id
WHERE post_id =...

You should LEFT JOIN comments because even if there are no comments you still get results.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Doctrine array field with default value Is there a way to set a default value to an array field?
data:
    type: array
    nullable: true
    options:
        default: {key1: value1, key2: value2}
        comment: 'Some array data'

It would be good to doctrine:migration:diff command also set this value in migration.


text:
Q: asp.net mvc 3 reset password by admin and force user to change it I'm using asp.net Membership, I develop an admin page who can regenerate a temp password to send to the user, then when the user log on for first time, the password must be changed, but I cant figure out who to know if the password was reseted.
I tried something like in a base controller:
if (user.LastPasswordChangedDate >= user.LastLoginDate)
{
    filterContext.Result = RedirectToAction("ChangePassword", "Account");
}

But, I already have updated the LastLoginDate because the ChangePassword Action need to be with a autenticated user.
I was thinking when reseting the password to lock/unlock the user to get updated the "LastLockoutDate" and do:
if (user.LastPasswordChangedDate >= user.LastLockoutDate)
{
    filterContext.Result = RedirectToAction("ChangePassword", "Account");
}

But, I can't find a method to do manual lockout
Thanks!!!

A: There's a lot of things you could do, some would depend on how your system works.  For instance, you could store a specific piece of data in the Comment field, if you're not using comments.
Or, if you don't use the "Approved" bit (that is, when you create new users you do not require them to validate an email or something, but instead create them with IsApproved set to true) then you can set IsApproved to False and force a password change if it's false.
There is no method to access much of this data in the Membership API, you just have to access it from you database.
You could also store this in the Personalization provider.
Another option is to simply avoid storing this in the Membership database, and instead just add a table or a field in your apps data to deal with this.


text:
Q: Beautifulsoup get content without next tag I have some html code like this

abc123

I used Beautifulsoup,and here's my code :
html = '
abc123
'
soup1 = BeautifulSoup(html,"lxml")
p = soup1.text

I get the result  'abc123'
But I want to get the result '123' not 'abc123'

A: You can use the function decompose() to remove the span tag and then get the text you want.
from bs4 import BeautifulSoup

html = '
abc123
'
soup = BeautifulSoup(html, "lxml")

for span in soup.find_all("span", {'class':'map-sub-title'}):
    span.decompose()

print(soup.text)

A: You can also use extract() to remove unwanted tag before you get the text from tag like below.
from bs4 import BeautifulSoup

html = '
abc123
'
soup1 = BeautifulSoup(html,"lxml")
soup1.p.span.extract()

print(soup1.text)

A: One of the many ways, is to use contents over the parent tag (in this case it's
).
If you know the position of the string, you can directly use this:
>>> from bs4 import BeautifulSoup, NavigableString
>>> soup = BeautifulSoup('
abc123
', 'lxml')
>>> # check the contents
... soup.find('p').contents
[abc, '123']
>>> soup.find('p').contents[1]
'123'

If, you want a generalized solution, where you don't know the position, you can check if the type of content is NavigableString like this:
>>> final_text = [x for x in soup.find('p').contents if isinstance(x, NavigableString)]
>>> final_text
['123']

With the second method, you'll be able to get all the text that is directly a child of the
 tag. For completeness's sake, here's one more example:
>>> html = '''
...

...     I want
...     abc
...     foo
...     abc2
...     text
...     abc3
...     only
...

... '''
>>> soup = BeautifulSoup(html, 'lxml')
>>> ' '.join([x.strip() for x in soup.find('p').contents if isinstance(x, NavigableString)])
'I want foo text only'

A: Although every response on this thread seems acceptable I shall point out another method for this case:
soup.find("span", {'class':'map-sub-title'}).next_sibling
You can use next_sibling to navigate between elements that are on the same parent, in this case the p tag.

A: If there's more than one thing inside a tag, you can still look at just the strings. Use the .strings generator:
>>> from bs4 import BeautifulSoup
>>> html = '
abc123
'
>>> soup1 = BeautifulSoup(html,"lxml")
>>> soup1.p.strings
<generator object _all_strings at 0x00000008768C50>
>>> list(soup1.strings)
['abc', '123']
>>> list(soup1.strings)[1]
'123'


text:
Q: C++ error - expected primary expression before 'char' and 'int' #include<iostream>
#include<cstring>
using namespace std;
class Employee
{
    char name[5];
    int id;
    int age;
    public:
    Employee(char* a, int b, int c)
    {
        strcpy(name, a);
        id=b;
        age=c;
    }
};
class Officer: public Employee
{
    char officer_cadre[3];
    public:
    Officer(char* a, int b, int c, char* d):Employee(char* a, int b, int c)
    {
        strcpy(officer_cadre, d);
    }
};
int main()
{
   Officer o1("Nakul", 1, 2, "ABC");
   return 0;
}

The above code is simple, but I'm not able to figure out why the compiler is throwing errors like 'expected primary expression before char' and 'expected primary expression before int'.

A: Change this line:
Officer(char* a, int b, int c, char* d):Employee(char* a, int b, int c)

To this:
Officer(char* a, int b, int c, char* d):Employee(a,b,c)

Also I am concerned about your declaration of officer_cadre.  It's an array of character pointers, but there's no memory allocation.  Was that the declaration you meant?

A: On this line
  Officer(char* a, int b, int c, char* d):Employee(char* a, int b, int c)

You should just pass a,b, and c. Instead you are using the syntax to declare a,b, and c. When just referring to them you don't need the types. IE you should do:
  Officer(char* a, int b, int c, char* d):Employee(a, b, c)

You may have just accidentally copy-pasted the declaration into the child class's constructor.

A: Change
char* officer_cadre[3];

to
char officer_cadre[3];


text:
Q: Twitter Bootstrap Scrollspy skipping element I am using Twitter Bootstrap, and have been for a while. I have only today used the scrollspy component and I am having some weird issue with it.
The scrollspy defaults to making the "pricing" link active. There is only one ID with #pricing on it. I have searched and searched for an answer.
Link: http://ibexcore.com/services/web-design

A: If you inspect element (using chrome) on the pricing h1 and hover over the element in the code inspector, you'll notice the h1 area seems to be covering almost the whole page.
It looks like you've either got some error in your html, or some unusual CSS rules causing it's area to be so large
EDIT - on second look, your pricing h1 looks to be outside of the twitter bootstrap guidelines of

yours is like this

I'd guess sticking it back into a
 would fix it


text:
Q: get the value from for loop I want to get the for loop value in php I have some names and I want to add '/'after each name and print the value outside the loop I want to get the $approver_name from for loop
foreach($co_practice as $co_practice_approver){
    // global $approver_name;
    if ($j >= 1) {
        $approver = users::where('id','=',$co_practice_approver)->first()->firstname;
        $approver_name = $approver_name . ' / ' . $approver;
    } else {
        $approver_name = users::where('id','=',$co_practice_approver)->first()->firstname;
    }
}

 Hello {{$approver_name}}

now I got the output 'hello' without approver_name How to print the approver_name which I fetched in for loop

A: Why don't you fetch the approver's firstname at once? Fetching data in loop will cause multiple queries in the database. Instead you could use whereIn()
YourController.php
public function yourMethod {
    // your other logic here...

    // this will query to get all users matching ids in $co_practice array
    // and pluck() will get the array of user's firstname
    $firstNames = UserModel::whereIn('id', $co_practice)->pluck('firstname');

    // this will concatenate firstnames separated by '/'
    $approver_name = implode(' / ', $firstNames->all());

    // this will pass the $approver_name variable to view
    return view('your_blade_file', compact('approver_name'));
}

your_blade_file.blade.php
//now you can print the $approver_name
Hello {{ $approver_name }}


text:
Q: Create nestled JSON (python) The code below takes data that I have extracted from various websites and writes the data to a JSON file.  I would like to create a nestled section called {nlp_description} for the NLP items (Unigrams,Bigrams,Trigrams).
How do I accomplish this task?
json_data = {}
json_data['news_sites'] = []

json_data['news_sites'].append({
        'URL': website_href,
        'Title': website_title,
        'Snippet': website_snippet,
        'Description': website_description,
        'Unigrams': unigrams,
        'Bigrams': bigrams,
        'Trigrams': trigrams})

    with open('data.txt', 'w') as outfile:
        json.dump(json_data, outfile, ensure_ascii=False,indent=6)

I tried doing this, but it failed:
json_data['news_sites'].append({
        'URL': website_href,
        'Title': website_title,
        'Snippet': website_snippet,
        'Description': website_description,
        'nlp_description':
            ('Unigrams': unigrams,
             'Bigrams': bigrams,
             'Trigrams': trigrams)})

    with open('data.txt', 'w') as outfile:
        json.dump(json_data, outfile, ensure_ascii=False,indent=6)

A: The nlp_description key is represented as a wrong tuple. Maybe what you're looking for is this:
json_data['news_sites'].append({
    'URL': website_href,
    'Title': website_title,
    'Snippet': website_snippet,
    'Description': website_description,
    'nlp_description':(
        {
            'Unigrams': unigrams,
            'Bigrams': bigrams,
            'Trigrams': trigrams
        }
    )
})


text:
Q: Getting Error when Creating the Database Migration I'm trying to create a database migration with the command :
dotnet ef migrations add Initial

but every time I'm getting this error :

Unfortunately, I can't progress anymore because of this error, what the is the problem here?
that's how I configurated the connection string :
first in appsettings.json:
{
  "Data": {
        "SportStoreProducts": {
            "ConnectionStrings":"Server(localdb)\MSSQLLocalDB;Database=SportsStore;Trusted _Connection=True;MultipleActiveResultSets=true"
        }
    }
}

and then in the Startup:
 public class Startup
{
    // This method gets called by the runtime. Use this method to add services to the container.
    // For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940
    public Startup(IConfiguration configuration) => Configuration = configuration;

    public IConfiguration Configuration { get; }

    public void ConfigureServices(IServiceCollection services)
    {
        services.AddDbContext<ApplicationDbContext>(
            options => options.UseSqlServer(Configuration["Data:SportStoreProducts:ConnectionString"]));

I'm not sure about the version of EF, that's how I added the package in SportStore.csproj:
<Project Sdk="Microsoft.NET.Sdk.Web">

<PropertyGroup>
<TargetFramework>netcoreapp2.0</TargetFramework>
</PropertyGroup>

<ItemGroup>
<PackageReference Include="Microsoft.AspNetCore.All" Version="2.0.7" />
<PackageReference Include="Microsoft.VisualStudio.Web.CodeGeneration.Design"
Version="2.0.3" />
<DotNetCliToolReference Include="Microsoft.EntityFrameworkCore.Tools.DotNet"
Version="2.0.0" />
</ItemGroup>

<ItemGroup>
<Folder Include="wwwroot\" />

from this folder, I run the command prompt:
C:\Users\Mohsen\Google Drive\ASP.MVC Projects\SportsStore\SportsStore

and my DbContext class is called:
ApplicationDbContext


text:
Q: Buttons not disappearing after clicking them Hi I have the following code, which renders 2 buttons at a time based on the user's query, example: 'Yes' and 'No'. The goal is that once the user clicks either of the buttons, they should both disappear. I tried to add a set state component as follows:
export default class Reply extends React.PureComponent {
    constructor(props) {
        super(props);
        this.state = {isToggleOn: true};
        this.handleClick = this.handleClick.bind(this);
    }
    handleClick() {
        this.setState(state => ({
             isToggleOn: !state.isToggleOn
          }));  }

    render() {
        if(this.state.isToggleOn === 'ON'){
        return (
            <Button
                tabIndex={this.props.tabIndex}
                style={this.props.styles.default}
                onClick={this.handleClick}
                hoverStyle={this.props.styles.hover}
            >
                {this.props.text}
                {this.state.isToggleOn ? 'ON' : 'OFF'}
            </Button>
        )
    } else {
      return null;
}

}
Currently, the buttons don't disappear when I click on them as well as show 'ON' and 'OFF' with the button text as well example: 'YesON' and 'NoOFF' . When I click them, the 'ON' changes to 'OFF' and vice versa each time but the buttons do not disappear.
Can someone explain where I'm going wrong and how to fix this

A:          render() {
                    return (
  {this.state.isToggleOn ?
                        <Button
                            tabIndex={this.props.tabIndex}
                            style={this.props.styles.default}

                            onClick={this.handleClick}
                            hoverStyle={this.props.styles.hover}
                           className={styles.quickReply}
                        >
                            {this.props.text}
                            {this.state.isToggleOn ? 'ON' : 'OFF'}
                        </Button>
:

                    )
                }

A: Conditional rendering
The button doesn't disappear because it's still being rendered. In order to have it rendered conditionally, you need to specify a condition on basis of which it would hide and display. You can read more about it in the official docs.
render() {
  const { isToggleOn } = this.state

  return (
    <>
      {isToggleOn && (
        <Button
          tabIndex={this.props.tabIndex}
          className={styles.quickReply}
          style={this.props.styles.default}
          onClick={this.handleClick}
          hoverStyle={this.props.styles.hover}
        >
          {this.props.text}
          ON
        </Button>
      )}
    </>
  )
}

A: Seeing your problem , this workaround would be easy to implement using the latest version of react,
import React,{useState} from 'react'

export const Button = () => {
    const [isActive, setActive] = useState(true);
    const handleclick = ()=>{
        setActive(false);
    }
    return (
        (isActive)?

            <button onClick = {(e)=>{e.preventDefault(); handleclick()}}>
                Sample Button
            </button>

:<></>
    )
}

Using the "useState" will help you keep the code cleaner, and can be easily changed to different states,
Happy Coding :)


text:
Q: How do I post an image with Nodejs and Multer? I am trying to build an application that consists of uploading a file(such as an image) and posting it.
this is what I have done so far:
var express = require('express');
var multer = require('multer');

var storage = multer.diskStorage({
      destination: function (req, file, cb) {
        cb(null, './public/img');
      },
      filename: function (req, file, cb){
        cb(null, file.originalname + '-' + Date.now());
      }
    });

var upload = multer({storage: storage});

So this code above will save the files I upload them in a folder called 'img'
module.exports = function(app){

    app.get('/', function(req, res){
        res.render('index');
    });

    app.post('/upload', upload.single('file'), function(req, res){

    res.send(req.file);
    });
}

Now in the last post request I get all the metadata information about the file in 'req.file'. I wanted to get the file and post it if someone, for instance, makes this request:
app.get('/postedfiles', function(req, res){});

should I save them in a database or something?

A: Not really, it saves inside your computer, inside the directory that you choose.
This is the plain html form for the multer upload.
<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title></title>
  </head>
  <body>
    <form accept="image/x-png,image/gif,image/jpeg" enctype="multipart/form-data" action="/profile" method="post">
      <input type="file" name="avatar" value="">
      <input type="submit" name="" value="ssss">
    </form>
  </body>
</html>

This is our backend code. Inside storage, I choose where  to upload the files, which is under /upload directory, and give them file names of that current time. We declare out upload variable for set up, and then we use upload.single('avatar') while we're getting a post request, we declare it right before the callback. What avatar here is that it's the file name from out html form inside input tag. And in the callback we can get to our file by using req.file. The module saves the file this way, very easy to use.
var express = require('express')
var multer  = require('multer')
var app = express()

var storage = multer.diskStorage({
  destination: function (req, file, cb) {
    cb(null, __dirname + '/uploads')      //you tell where to upload the files,
  },
  filename: function (req, file, cb) {
    cb(null, file.fieldname + '-' + Date.now() + '.png')
  }
})

var upload = multer({storage: storage,
    onFileUploadStart: function (file) {
      console.log(file.originalname + ' is starting ...')
    },
});

app.set('view engine', 'ejs');

app.get('/', function(req, res, next){
    res.render('mult');  //our html document
})

app.post('/profile', upload.single('avatar'), function (req, res, next) {
  // req.file is the `avatar` file
  console.log(req.file);
  return false;
})

Make sure, you give the images and extension of either png or jpeg, or whatever you want to use, otherwise it will not be considered as an image in the computer.
Update on your question
If you want to show the client the image without refreshing  the page, just use AJAX with a get request on the client browser. You can upload the files inside your web server or to a web server and retrieve images from there. For example, my profile picture in stackoverflow is saved  here
You can use params in a get request to receive all the files from server.
For example, imagine a client making a get request to /uploads/imageOfApet.png.
app.get('/uploads/:theImageName', function(req, res){
   console.log(req.params.theImageName); //returns the imageOfApet.png
   var theName = req.params.theImageName; //imageOfApet.png
   res.sendFile(__dirname + "/uploads/" + theName); //Sending the user the file
})


text:
Q: Prove that all linear combination $c{\bf v}+d{\bf w}$ with $c+d=1$ is a line? Prove that all linear combination $c\boldsymbol{v}+d\boldsymbol{ w}$ with $c+d=1$ is a line in 2D, where $\boldsymbol{ v}$ and $\boldsymbol{ w}$ are nonzero vectors in 2D.

A: Hint: If one only one of both vectors is zero the statement is trivial. Assume $v-w\neq 0$. Now, observe: $cv+dw=(1-d)v+dw=v+d(w-v)$
$w-v$ is the vector for the direction of the line. $d$ is the parameter that we vary from $(-\infty,\infty)$ and $v$ is a point on the line. This is nothing but the vectorial representation of a line. See also this MSE question.


text:
Q: Make  to act like  I have a table and I want every row to be clickable. Right now, I'm doing the simple:
$('tr').click(...)

This works for the most part but how can I make it act like a link in these ways:

*

*Shift-click opens the target in a new window

*Middle clicking opens the target in a new tab

*Hovering shows the link address in the status bar

A: One option would be to implement .mouseUp() and detect manually the shift and ctrl keys, and which button was pressed.  That, of course, sounds prone to all manner of ugly failures, wherein you miss some quirk of an individual user's setup.
Instead, how about automatically adding an  tag to every cell that does what you want.  In jQuery, that's just:
$('tr th, tr td').wrapInner('').children('a').click(function() {
    ...
});

A: I'd suggest using an  tag inside each cell:

  ...
  ...
  ...

With this CSS:
table.clickRows td > a {
  display: block;
  width: 100%;
  height: 100%;
}

A: That's technically feasible in some browsers, but not all, and for those that do support it, it's a lot of work. You have to intercept the keyboard and non-left click events. You'd probably be better off just wrapping the contents of each TD in a regular A tag.
Going the JS/override route also doesn't degrade gracefully... if all you're doing is truly just linking to another page like a typical HREF, it's almost silly to make that dependent on JavaScript.

A: I think you need to make it a link by actually enclosing it in an  tag, so 'hovering' will show the link address in the status bar.
The behaviour of right and middle-click surely depends on the browser configuration.

A: You're much better off trying to make an  look like a
.
Browsers will be much more tolerant of you mangling the presentation of an  element than overriding such basic operations as shift-clicking a link.

A: For what its worth, Apple are RED and Bananas are YELLOW. You might not want to squeeze it and color it for the sane users out there.
An anchor tag,  exists for what its worth, and so is a table-row tag,
.


text:
Q: Restoring mac to pre OS install attempt I recently tried to install the new OS X maverick, but about 4 min into the process it told me my disk needed to be repaired. That I should back up my stuff and restore the drive.
I will do that, but I would like to just return my computer to its previous state. Is there some way to stop running the OS X install when my computer re-starts?
Thanks

A: Not too much information here about what (OS version, Machine type) you are starting with. So, Guessing:Try holding down the option key at startup. I'm not 100% sure that will work in this case, but if the computer has a recovery partition and/or is recent enough to do internet recovery, it should work. If it's older, put in a DVD and press the C key (no DVD drive - it's probably "newer" in the scale I'm using)


text:
Q: Android Service classes why it is not showing me a messageboxdialog when the Service is being activated.
@Override
public void onStart(Intent intent, int startid) {
    Toast.makeText(this, "My Service Started", Toast.LENGTH_LONG).show();
    Log.d(TAG, "onStart");
    player.start();

    AlertDialog.Builder builder = new AlertDialog.Builder(this);
    builder.setMessage("Are you sure you want to exit?")
           .setCancelable(false)
           .setPositiveButton("Yes", new DialogInterface.OnClickListener() {
               public void onClick(DialogInterface dialog, int id) {
                    AlarmService.this.onDestroy();
               }
           })
           .setNegativeButton("No", new DialogInterface.OnClickListener() {
               public void onClick(DialogInterface dialog, int id) {
                    dialog.cancel();
               }
           });

}

The Toast is appearing the sound is being played only the showdialog is not comming, why ?

A: You need to call builder.create() to create your AlertDialog, then show() on the dialog to display it.
However, if this is a Service, you won't be able to display the dialog directly. Have a look at this question for how to show a Dialog from within a Service: Alert dialog from Android service

A: You have to call create() on your Builder to create a AlertDialog which can then be shown by a call to show(). See the dialogues guide for more info on this topic.


text:
Q: Search by location AND tags Instagram Api Is there any way I can get photos with a given tag AND location with instagram api? I'm using this call
https://api.instagram.com/v1/tags/'.$tag.'/media/recent?client_id='.$client_id

Yet I want to look for photos with that given tag in a given location but I can't find the answer.

A: This has been asked and answered numerous times. Check out this and this for some ideas. Short answer is to search by geolocation and then filter by tag or vice versa depending on what gets you best results


text:
Q: How to upgrade to EntLib 5 (from 1.1) IRolesProvider doesn't exist We are upgrading from enterprise lib 1.1 to 5.0, where some of the Interface and class are not for in enterprise lib 5.0 dll reference.

*

*ConfigurationProvider

*IRolesProvider

*SecurityConfigurationView

These are not working in enterprise library 5.0

A: *

*Configuration was moved into .NET 2.0 so any custom configuration should be converted to use the BCL classes.

*I would think that IRolesProvider would be replaced with the abstract RoleProvider class.

*SecurityConfigurationView was removed between version 4.1 and version 5.0.  It's just a small facade over the SecuritySettings configuration class.  You could either access the SecuritySettings directly or (re)create the functionality with your own class.


text:
Q: List all the .exe or .iso under a directory in shell script I want to list out all the executables like .iso or .exe in a directory
My current code only shows *.iso. How can I make it generic to list all .iso,.exe,*.abc etc
export imageList=$(ls $sourceImageDir/*.iso)

A: with Bash:
export imageList=$(ls $sourceImageDir/*.{iso,exe,abc})


text:
Q: How to avoid NullPointerException with an empty cell using POI? I'm trying to get some values in my java program from an excel .xlsx file using Apache POI, but I'm having trouble because my loop encounters an empty cell sometimes, then I get a NullPointerException. How can I "test" the cell before even reading it ? Here's a piece of my code :
FileInputStream file = new FileInputStream(new File(file));
XSSFWorkbook workbook = new XSSFWorkbook(file);
XSSFSheet sheet = workbook.getSheetAt(0);
int rows;
rows = sheet.getPhysicalNumberOfRows();
for (int i=1;i<rows;i++){
    Row row = sheet.getRow(i);
    Cell cell = row.getCell(2); // Here is the NullPointerException
    String cellString = cell.getStringCellValue();
    myArrayList.add(cellString);
}

Which brings me to :
java.lang.NullPointerException
at analyse.Analyser.getExcelWords3(Analyser.java:73)
at analyse.Analyser.main(Analyser.java:21)

I want to know if there's a possibility to check if the cell is empty before trying to read it, then I won't get the NPE. Thank you in advance !

A: To avoid NullPointerException add this Row.MissingCellPolicy.CREATE_NULL_AS_BLANK
Cell cell = row.getCell(j, Row.MissingCellPolicy.CREATE_NULL_AS_BLANK);

This will create a blank cell instead of giving you NPE

A: wrap your code in a try / catch statement that is what it's there for..
https://docs.oracle.com/javase/tutorial/essential/exceptions/catch.html
some untested code below to give you the idea:
for (int i=1;i<rows;i++){
    try{
        Row row = sheet.getRow(i);
        Cell cell = row.getCell(2); // Here is the NullPointerException
        String cellString = cell.getStringCellValue();
        myArrayList.add(cellString);
    }catch(NullPointerException NPE)
    {
        //what to do when the exception occurs?
    }
}

A: Look at this method:
/**
 * Returns the cell at the given (0 based) index, with the specified {@link org.apache.poi.ss.usermodel.Row.MissingCellPolicy}
 *
 * @return the cell at the given (0 based) index
 * @throws IllegalArgumentException if cellnum < 0 or the specified MissingCellPolicy is invalid
 * @see Row#RETURN_NULL_AND_BLANK
 * @see Row#RETURN_BLANK_AS_NULL
 * @see Row#CREATE_NULL_AS_BLANK
 */
public XSSFCell getCell(int cellnum, MissingCellPolicy policy) {

It should help you.

A: `       FileInputStream file = new FileInputStream(new File(file));
     XSSFWorkbook workbook = new XSSFWorkbook(file);
     XSSFSheet sheet = workbook.getSheetAt(0);
     int rows;
     String cellString = null;
     rows = sheet.getPhysicalNumberOfRows();
    for (int i=1;i<rows;i++){
    Row row = sheet.getRow(i);
    if(row.getCell(2) == null)
    {
    cellString = null;
    }
    else
    {
    Cell cell = row.getCell(2); //if 3rd column of excelsheet then     getCell(2)..
    cellString = cell.getStringCellValue();
    }
    myArrayList.add(cellString);
    }
      if excel cell contain empty/blank then it will be stored as null`


text:
Q: Laravel subfolder htaccess I am trying to run laravel in a subfolder on my site and am having trouble with the htaccess portion.
I have seen many questions like this on here, but I haven't found any that apply to my case, or that work fully.
My folder structure is several levels deep:
site root/folder1/folder2/laravel installation/public folder/

I have been trying to redirect laravel install folder to the public folder, I have done this before when laravel is installed in the root using htaccess:
RewriteRule ^(folder1/folder2/laravel installation/)
/folder1/folder2/laravel installation/public folder/

When I put in a blank test index file into the public folder, the code above works and it redirects to it.
However when I use the laravel index file i get the following laravel error:
NotFoundHttpException in RouteCollection.php line 161

If i remove the htaccess and navigate to the public folder directly laravel works (this is a fresh install of laravel).
Is there something I need to change in the laravel config files in order to get this to work? Or is this not possible?
Thank you.
Edit:
I forgot to mention that I have an htaccess file in my public folder, here is the code:
<IfModule mod_rewrite.c>
<IfModule mod_negotiation.c>
    Options -MultiViews
</IfModule>

RewriteEngine On

RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)/$ /$1 [L,R=301]

RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^ index.php [L]
</IfModule>

Also, when I type the following url in the site does work, however it forces the index.php. I believe that is because of the rewrite rule I just added, however without this script the site fails to load like before.
www.demo.[mydomain].com/folder1/folder2/laravel/index.php


text:
Q: The setText() method is not working (Java) I've come across a problem where when I want to use the setText() method on a label, it won't change the label's text. I've searched for a long time, but couldn't find any solution.
Here is a sample of the code:
class OptionsListener implements ItemListener{
    public void itemStateChanged(ItemEvent e) {
        if (optionsI1.isSelected()){
            lesu1.setText("8:30");
        }
    }
}

I display all the components I use into another class, everything is displayed correctly.
I've tried simplifying the code by doing something like this:
class OptionsListener implements ItemListener{
    public void itemStateChanged(ItemEvent e) {
        if (optionsI1.isSelected()){
            System.out.println("bla");
        }
    }

Which seems to work fine and display the message "bla".
Anything I'm missing here?
The declaration of my elements (only showing the labels and menu's in the order I coded it):
    // labels //
    lesu1 = new JLabel("1");
    lesu1.setBounds(8, 39, 20, 22);

    lesu2 = new JLabel("2");
    lesu2.setBounds(8, 69, 20, 22);

    lesu3 = new JLabel("3");
    lesu3.setBounds(8, 99, 20, 22);

    lesu4 = new JLabel("4");
    lesu4.setBounds(8, 129, 20, 22);

    lesu5 = new JLabel("5");
    lesu5.setBounds(8, 159, 20, 22);

    lesu6 = new JLabel("6");
    lesu6.setBounds(8, 189, 20, 22);

    lesu7 = new JLabel("7");
    lesu7.setBounds(8, 219, 20, 22);

    lesu8 = new JLabel("8");
    lesu8.setBounds(8, 249, 20, 22);

    dag = new JLabel("07/08");
    dag.setBounds(5, 15, 36, 13);

    // menubar //
    menu = new JMenuBar();

    options = new JMenu("Opties");

    optionsI1 = new JCheckBoxMenuItem("Weergeef de lesuren in uren");
    optionsI1.addItemListener(new OptionsListener());

    menu.add(options);

    options.add(optionsI1);

This is the order I placed those components. I also added them to the panel in this order.

A: Your Label lesu1 is not placed on any component like panel,button etc.
Add lable to some component.
For ex.
menu.add(lesu1);

A: I found out what the problem was.
I was confused and used a constructor for everything instead of methods. That solved it.
As I said: I'm a beginner in Java.


text:
Q: Find only youngest element in array does somebody know if there is a way to build a elasticsearch query which sorts an array by date and queries only the youngest item? To demonstrate what I mean, here is an example of my data:
    [{
    _id: "51cd3ae45b99bd960ee0b425",
    name: "Example entry",
    documents: [
        {
            title: "Document Title 1",
            subDocuments: [
                {
                    date: "Mon Jul 08 2013 12:14:04 GMT+0200 (CEST)",
                    title: "start working"
                },
                {
                    date: "Fri Jul 11 2013 12:14:04 GMT+0200 (CEST)",
                    title: "finished"
                },
                {
                    date: "Thu Jul 10 2013 12:14:04 GMT+0200 (CEST)",
                    title: "working"
                }
            ]
        }
    ]
}, {
    _id: "51cd3ae45b99bd960ee0b426",
    name: "Example entry 2",
    documents: [
        {
            title: "Document Title 1",
            subDocuments: [
                {
                    date: "Mon Jul 08 2013 12:14:04 GMT+0200 (CEST)",
                    title: "start working"
                },
                {
                    date: "Fri Jul 11 2013 12:14:04 GMT+0200 (CEST)",
                    title: "working"
                }
            ]
        }
    ]
}]

In this data I want to query for the value "working". As you can see the first document has the sub document title finished in his last status so this document is not to be allowed in the result set.
Could anybody give me a hint how to build up the query so that my requirements are met? Or is this impossible at this time and has to be developed in the client code?
Thanks and Greetings Kersten

A: I've managed this with editing my data. I just copy the last status to a own property. But I think this might be the solution: https://github.com/elasticsearch/elasticsearch/issues/3022


text:
Q: 1.7 and configurable products I created a configurable product with its associated products.  I added two attributes in the way that magento tutorial suggested.
When I go to the product page
http://www.youbigtees.com/index.php/t-shirts/test1-tshirt.html
You can see the product attributes are there and I select one of each and hit add to cart - NOTHING happens.
Its driving me nuts .. can someone help - please?

A: Look in your theme's catalog\product\view.phtml. You have a line of javascript that is bad.
$('ma-pro-options').appendChild($('ma-related-pro'));

The first selector should be $('#ma-pro-options') since ma-pro-options is an ID. I'm not sure what the selector inside the appendChild is exactly, but that probably needs to be changed as well. For testing purposes, you can delete this line and your add to cart should work after that. I know this doesn't completely solve your problem, as this removes whatever functionality you are trying to accomplish, but it should put you on the right track.

A: I agree with @airhorse, you have JavaScript issues. I'd suggest reading this answer: https://magento.stackexchange.com/a/4436/1956 as it will describe some basics for troubleshooting JavaScript issues with your Website.
So one thing to keep in mind is all interactive functionality on the front end of your Website ( form selections/submissions, sliders, DOM manipulations ( https://developer.mozilla.org/en-US/docs/DOM ), AJAX, etc ) are done via JavaScript. So if you can clearly see that one of the above aforementioned functionalities aren't working, then there are most likely JavaScript issues somewhere.
If you have a JavaScript error ( syntax error, a resource didn't load that code within the page depends on, runtime error, etc ) then your page will just not work until that is resolved.
That said, looking at my JavaScript console in Chrome Dev Tools, I see the following errors:
Failed to load resource http://s7.addthis.com/js/250/addthis_widget.js#pubid=xa-4ebf9cd355b286dd
Uncaught Error: NotFoundError: DOM Exception 8 test1-tshirt.html:551

So, airhorse was correct regarding your syntax error of leaving out the hash (#) in your id selector ( http://api.jquery.com/id-selector/ ). But there's also the issue of the addthis_widget.js file not loading up correctly. So, you have at least two JavaScript problems here.
You'll need to refer to the addthis.com Developer Documentation for this JS button: http://support.addthis.com/customer/portal/articles/381263-addthis-sharing-button-api for more details on what you need to do to correctly call on the JavaScript file.
I hope this is helpful, and helps your resolve this issue.


text:
Q: Почему при landscape UI рисуется правильно а при portrait неправильно? Почему при landscape UI рисуется правильно а при portrait неправильно, в то время как оба варианта рисуются автоматически на основе пару строк java кода (одинаковый для обоих режимов)?
Вот скрин превью IDE

Вот инфо про превью

Вот код, с помощью которого автоматический меняются размеры элементов UI
 @Override
    public void onWindowFocusChanged(boolean hasFocus) {
        super.onWindowFocusChanged(hasFocus);

        //размеры выбранной версии превью, на основе которого я собрал нужный UI для программы
        int testedWidth = 1200;
        int testedHeight = 1920;

        //получаем размер экрана устройства/дисплея
        metrics = Resources.getSystem().getDisplayMetrics();
        displayWidth = metrics.widthPixels;
        displayHeight = metrics.heightPixels;

        widthMultiplier = ((double) displayWidth) / ((double) testedWidth);
        heightMultiplier = ((double) displayHeight) / ((double) testedHeight);

        ...

        for (TextView textView : textViews) {
            viewWidth = textView.getWidth();
            viewHeight = textView.getHeight();

            RelativeLayout.LayoutParams lp = copyLp((RelativeLayout.LayoutParams) textView.getLayoutParams());
            lp.width = (int) (viewWidth * widthMultiplier);
            lp.height = (int) (viewHeight * heightMultiplier);

            // Setting the parameters on the TextView
            textView.setLayoutParams(lp);
        }
        ...

вот результат с устройства (сделал скрин экрана)
landscape

portrait

СУТЬ Проблемы: При правильном результате, во время portrait, width ViewGroup (содержащего элементы в виде луп) должен стать равным width экрана устройства, в смысле - левая сторона ViewGroup должен прикасаться к левой стороне экрана, также как и правая сторона ViewGroup - к правой стороне экрана. Но в результате как видно - присутствуют открытые пространства между ЛСЭУ-ЛСВ и между ПСЭУ-ПСВ, что указывает на то, что width ViewGroup не является равным width устройства.
Уточнение: ЛСЭЮ - это "Левая Сторона Экрана Устройства" а ЛСВ - это "Левая Сторона Вьюгруппы", ПСЭУ-ПСВ соответственно "Правая Сторона Экрана Устройства"-"Правая Сторона Вью".
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@drawable/pokemon_background"
    tools:context=".MainActivity">

    <RelativeLayout
        android:id="@+id/relative_layout"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true">

        <TextView
            android:id="@+id/tv1"
            android:layout_width="@dimen/tvWidthSmallBoard"
            android:layout_height="@dimen/tvHeightSmallBoard"
            android:background="@drawable/search_icon_for_searchboard_cell"
            android:gravity="center"
            android:text="@string/click_me"
            android:textColor="@android:color/black"
            android:visibility="visible" />
        ...
    </RelativeLayout>
    ...
</RelativeLayout>

растягивается неправильно. По идее должно было растягиваться так, чтобы размер width данного ViewGroup совпало с размером displayWidth (width устройства, на котором запущена программа).
как из выше кода известно
int testedWidth = 1200;
int testedHeight = 1920;

а размеры экрана, которые программа находит для экрана устройства
width = 1080
height = 2131
Страннее то, что при landscape - проблемы нет, width растягивается как положено, но при portrait почему то, вместо достаточного растягивания, программа решает рисовать маленькими все лупы справа, но почему так происходит, если ViewGroup содержащий лупы - не имеет жестких границ а имеет значение wrap_content?
Я сам не смог найти логического обьяснения для данной ситуации.
Доп. инфо:
Значения размеров в xml переданы не в "dp" а в "px". Зачем именно так? Это связано с уменьшением хлопот во время измерения размеров и делания расчетов. Недавно с "dp" значениями делал программу, количество проблем взбесило, пришлось перейти к "px". Для динамического изменения размеров элементов UI это несомненно правильное решение, поэтому прошу не советовать перейти к "dp".
Вот копи паст dimens.xml (только необходимые строки):
<?xml version="1.0" encoding="utf-8"?>
<resources>
...
    <dimen name="tvWidthSmallBoard">400px</dimen>
    <dimen name="tvHeightSmallBoard">200px</dimen>
...
</resources>

Хорошо что вспомнил. Забыл указать и этот метод, который используется в программе
private RelativeLayout.LayoutParams copyLp(RelativeLayout.LayoutParams source){
        return new RelativeLayout.LayoutParams(source);
}

A: Оказывается проблема имела очень простое решение.
Корень ошибки был в том, что программа до перерисовки, пытался уместить все три горизонтальные лупы в рамках 1080 px, в то время как UI был разработан для 1200px и соответственно для теста, я передал по 400 px каждому View. В результате чего программа работала следующим алгоритмом:
1) поместить 3х400 в 1080
2) в случае невозможности уместить - уменьшить размеры каждого третьего View-лупы.
3) во время перерисовки - взять искаженные во время второго пункта размеры.
4) взятые размеры поменять через коэфициент отличия, который предназначен правильной перерисовки UI
Итог: Появлялась проблема, которую я описал выше.
Решение! Поменял 3-ий пункт алгоритма на следующую
3) во время перерисовки вместо взятия искаженных размеров, взять размеры сразу из списка dimens.xml с помощью getResources().getDimension(R.dimen.tvWidthSmallBoard).
Теперь неважно, каким первоначально рисуется UI, во время перерисовки все делается как положено!


text:
Q: how to use html inside php while loop I have user information coming from database on a profile page using a while loop. I want to be able to write stuff like this, $username's profile. I can't seem to figure it out. Here is my code.
<?php
//open database connection
include 'page-start.php';
include 'core/init.php';
?>
<?php
$myQuery = ("SELECT user_id, username, profile, city FROM `users` WHERE user_id = '" . mysql_real_escape_string($_GET['ID']) . "' ") or die(mysql_error());

    //run query
$result = $con->query($myQuery);
if (!$result) die('Query error: ' . mysqli_error($result));

if($result === FALSE) {
die(mysql_error()); // TODO: better error handling
} ?>

<?php require_once $_SERVER['DOCUMENT_ROOT'] . '/studentsupport/defines.php'; ?>

    <?php include_once("head.php");
            while ($row = $result->fetch_array(MYSQLI_ASSOC))
            {

        echo '
';

                    echo'
 ' . $row['username'] . '
 ';//bob's Profile
                echo'
' . $row['city'] . '
'; //city: london

                    echo '
';

                    echo'';

        echo '
';
                echo '
';
}
            ?>

edit: sorry I didn't explain it very well.
I want to be able to have some information come from the database and some information just as standard html for example:

<?php echo $username; ?>'s profile

city: <?php echo $city; ?>

A: During each loop in the while, $row['username'] will have a username.
If you want to be able to get all the usernames later, add the following:
$users[] = $row['username'];

Now, Everywhere in your script $users[0] will have the 1st username, $users[1] will have the second, etc.

A: This may do it.
<?php include_once("head.php");
    while ($row = $result->fetch_array(MYSQLI_ASSOC))
    { ?>

<?php echo $row['username']; ?>

<?php echo $row['city']; ?>

               <img src="<?php echo $row['profile']; ?>"/>

 <? }     ?>

A: If you are beginner than i wil say You should use easy method now it seems okay
like You make Whole page of profile like you want
like
then you can Take your data in Variables in while Loop like that
    while ($row = $result->fetch_array(MYSQLI_ASSOC))
   {
     $profile = $row['profile'];
      $name = $row['name'];//you can take as many variables as you want
     $city = $row['city'];
    }

then you can use these variables in html simply

<?php echo $name; ?>

start like that next step like above will get easy to u :)


text:
Q: Flyweight Examples in Java I am trying to create a flyweight object in Java. I've worked with a similar concept in Objective-C (Singleton Classes in Objective-C // I believe they are the same thing).
I am trying to find a tutorial or an example or explanation online to learn how to create a flyweight object and use it, but I've searched on Google and I can't find anything descent. I went through 10 pages and they basically all plagiarize from one website which just explains the concept. I understand the concept - I need something to help me/teach me how to implement it in Java.
Anyone has any suggestions/tutorials?
Thanks!

A: The Wikipedia entry for the flyweight pattern has a concrete Java example.
EDIT to try and help the OP understand the pattern:
As noted in my comment below,  The point of the flyweight pattern is that you're sharing a single instance of something rather than creating new, identical objects.
Using the Wiki example, the CoffeeFlavorFactory will only create a single instance of any given CoffeeFlavor (this is done the first time a Flavor is requested). Subsequent requests for the same flavor return a reference to the original, single instance.
public static void main(String[] args)
{
    flavorFactory = new CoffeeFlavorFactory();
    CoffeeFlavor a = flavorFactory.getCoffeeFlavor("espresso");
    CoffeeFlavor b = flavorFactory.getCoffeeFlavor("espresso");
    CoffeeFlavor c = flavorFactory.getCoffeeFlavor("espresso");

    // This is comparing the reference value, not the contents of the objects
    if (a == b && b == c)
        System.out.println("I have three references to the same object!");
}

A: To follow up on the Wikipedia example that Brian cited...
Usually, if you want to cache some objects (such as CoffeeFlavors) and have them shared between a number of flyweights (the CoffeeOrders), then you would make them statically available. But this is not at all necessary. The important part is that the CoffeeOrders are being given the shared objects when they're constructed.
If the Orders are always only created by one singleton, like a "CoffeeOrderFactory," then the factory can keep a non-static cache of Flavors. However you accomplish it, your goal is to get all the Orders in the whole system to use the same exact set of Flavor objects. But at the end of the day, if you want to avoid creating many instances of CoffeeFlavor, then it usually needs to be created statically, just to make sure there's only one cache.
Get it?

A: I got this case. I think my solution was flyweight.
INPUT

*

*A: C E

*B: D C

*C: E

*A: B

It asked me to create a tree and sort its children by name. Something like this:

*

*A: B C E

*B: C D

*C: E

It's an easy task actually. But please notice that the first 'A' and the second 'A' in the input must refer to same object. Hence I coded something like this
public Node add(String key){
  Node node = nodes.get(key);
  if (null == node){
    node = new Node(key);
    nodes.put(key, node);
  }
  return node;
}

This is the simplified version of the actual problem, but you should have the idea now.

A: I also found this example, which has good Java code example.

A: The "java.lang.Character" uses the flyweight pattern to cache all US-ASCII characters : see in class java.lang.Character$CharacterCache used by the Character.valueOf() method


text:
Q: Strange C++ header file function declaration I'm reading some source code that I'm trying to compile into python bindings, when I try swig -c++ -python my_interface.i I get a strange error.
I know the source code is written in C++11.
// module.hpp
#pragma once

namespace module
{
    MODULE_API void getVersion (unsigned &params);
}

// my_interface.i
%module my_api
%{
#include "module.hpp"
%}

%include "module.hpp"

I don't have access to the source files, just the headers, and a shared library that we can call modulelib.so.
Does anybody know what the MODULE_API before the function return type means?
When I try to compile right now I get the error module.hpp:29: Error: Syntax error in input(1)
When I remove the MODULE_API the output moves to the next function declaration, because they all have this style of declaration, I'd delete them all, but I feel like that's going to break something.
Right now when I run swig -v -wall -c++ -python my_interface.i I recieve an error:
Language subdirectory: python
Search paths:
   ./
   ./swig_lib/python/
   /usr/share/swig3.0/python/
   ./swig_lib/
   /usr/share/swig3.0/
Preprocessing...
Starting language-specific parse...
module.hpp:6: Error: Syntax error in input(1).

A: This is a common pattern to handle symbol visibility. Windows, for example, requires you to define functions with __declspec(dllexport) when compiling a library (so the linker knows to make the corresponding symbols externally visible), and __declspec(dllimport) when using/linking a library (so the linker knows that those symbols are to be imported from a DLL).
To avoid having to have two different headers (one for compiling, one for using the library), conditional defines are used:
#ifdef WIN32

  #ifdef MODULE_EXPORTS
    #define MODULE_API __declspec(dllexport)
  #else
    #define MODULE_API __declspec(dllimport)
  #endif

#else
  #define MODULE_API
#endif

This is merely an example. It does not have to be MODULE_API at all. Some projects use GCC's __attribute__((visibility("default"))) and __attribute__((visibility("hidden"))), but Windows is where this scheme originated, as Windows' default is to hide symbols.


text:
Q: Ошибка при установке пакета lr-utils. WIndows 10, ошибка сборки py-bcrypt Не получается поставить пакет lrutils. Ставлю в cmd на Win10 через pip, вылетает ошибка:
Building wheels for collected packages: py-bcrypt
Running setup.py bdist_wheel for py-bcrypt ... error
  Failed building wheel for py-bcrypt
  Running setup.py clean for py-bcrypt
Failed to build py-bcrypt
Installing collected packages: py-bcrypt, lrutils
  Running setup.py install for py-bcrypt ... error

Пыталась ставить py-bcrypt, ошибка:
Building wheels for collected packages: py-bcrypt
  Running setup.py bdist_wheel for py-bcrypt ... error
  Failed building wheel for py-bcrypt
  Running setup.py clean for py-bcrypt
Failed to build py-bcrypt
Installing collected packages: py-bcrypt
  Running setup.py install for py-bcrypt ... error

В чем проблема? Как исправить? Заранее спасибо за ответы.

A: Не смогла решить проблему через консоль, но поставила пакет в самом джупитере через !pip install lrutils. Работает.


text:
Q: Seven vertices of a cube are labeled 0, and the remaining vertex labeled 1. Can you make all labels divisible by 3?
Seven vertices of a cube are labeled 0, and the remaining vertex labeled 1. You're allowed to change the labels by picking an edge of the cube, and adding 1 to the labels of both of its endpoints. After repeating this multiple times, can you make all labels divisible by 3?

It's from an invariant handout. I am not even able to get the main idea and haven't been able to proceed too.
So first I named the vertices $a,b,c,d,e,f,g,h$ and let $a$ be the vertex having label $1$ and others $0$. Define $f(i) =$ the no labeled in the vertex $i$  Now, after pairing non adjacent vertices , let us say $(a,c,f,h)$ and $(b,d,e,g)$ , we get that if $a$ will be divisible by $3$ , it will be due to $3$ other vertices let's say $(b, d, e)$ , and we will have $3k+1=f(a)$. But $f(b),f(d),f(e)$ are divisible by $3$. So these vertices must have $2 \mod 3$ to other $2$  vertices   .
But what should I do next ?
Thanks in advance! Also this question looks very well known, but I tried searching in MSE , but couldn't get anything.

A: You can color the vertices in two colors, white and black, with adjacent vertices having different colors.
Now assume the initial label $1$ vertex is white, then sums of whites will be always $1$ more than sums of blacks, since you are always incrementing both by $1$.
Then if all are divisible by $3$, it will lead to a contradiction, so it's impossible.


text:
Q: In Swift what does it mean if a type is bracketed, eg. "(String)" Simple question, difficult to Google and don't remember seeing this in the documentation. Code below shows the variable as "(String)" as opposed to just "String"  What does that mean?
var myDictionary = [String:Bool]()
// put whatever data you want in there, for example
myDictionary["cat"] = true
var firstKey = [String](myDictionary.keys)[0] //firstKey is type (String) as opposed to "String"
var myString = "this is my string" // has type String
var myOptionalString: String?  // has type String?
var myUninitializedString: String!  // has type String!

I guess it may have something to do with inferring the type?
Screenshot (from code completion window, a quick way to check the type):
Thanks

A: That means it's a single-element tuple, which acts exactly the same as a non-tuple of that same type. Don't worry about it.


text:
Q: Change CCAnimation, but retain frame index Unit in my game can move in 8 directions (N, NE, E, SE etc.). When unit change direction I want CCAnimate to retain animation frame (change only CCAnimation), to avoid animation jump if unit change facing in mid-step. My current code:
pSprite->stopAllActions();
CCAnimate* animate = CCAnimate::create((*currentAnimation)[(int)facing]);
CCRepeatForever* action = CCRepeatForever::create( animate );
pSprite->runAction( action );

Where currentAnimation is vector containing array of CCSpriteFrame. How I can achive it?
I'm using cocos2d-x 2.2

A: CCAnimate has protected member variable m_nNextFrame, that contains the index to the current animation frame. You could try creating a class that extends CCAnimate and creating a public setter / getter functions to set that index to desired one, before starting the animation.


text:
Q: how to create dynamic row with input fields in html table from given row Im new for Html and javascript. I want to create dynamic row with input fields in table while click button,that number of row given from user. In my code, row created dynamically but its not append prevoius one. Its created freshly. But ,I want to append row if table already created.
Here my code:

function createTable() {
  var a;

  a = document.getElementById('tb1').value;

  if (a == "") {
    alert("Please enter some numeric value");
  } else {
    var rows = "Item Name	Quantity	QuantityType	Amount	";
    for (var i = 0; i < a; i++) {
      rows += "
<input type='text' name='" + "name".concat(i+1) + "'>	<input type='text' name='" + "quantity".concat(i+1) + "'>	<input type='text' name='" + "qtype".concat(i+1) + "'>	<input type='text' id='sum' onkeyup='myfunction(this.value);' name='" + "total".concat(i+1) + "'>
";
    }

    document.getElementById("table").innerHTML = rows;
  }
}
div {
  background: red;
  margin: 5px;
}

table {
  border: 2px solid black;
}

td {
  padding: 10px;
  border: 1px solid lightgrey;
}
<!DOCTYPE html>

    <meta charset="UTF-8">
    <title></title>

    <input type="text" id="tb1"/>
    <button type="button" onclick='createTable()'>Click Me!</button>

Please anyone help!
Thanks in advance..

A:
Use Element.appendChild instead of innerHTML

*

*Element.firstChild will return first-child of the element.

*querySelectorAll will return NodeList as per the specified selector.

*Element.appendChild will append new Node in the Element without affecting existing content in the Element.

function createTable() {
  var a = document.getElementById('tb1').value;
  if (a == "") {
    alert("Please enter some numeric value");
  } else {
    var th = document.querySelectorAll('#table th');//To check whether `TD` is appended in table or not!
    if (!th.length) {
      //If not appended, then append TD in table
      var rows = "Item Name	Quantity	QuantityType	Amount	";
      var table = document.createElement('table');
      table.innerHTML = rows;
      document.getElementById("table").appendChild(table.firstChild);
    }

    for (var i = 0; i < a; i++) {
      var elems = '';
      elems += "
<input type='text' name='" + "name".concat(i + 1) + "'>	<input type='text' name='" + "quantity".concat(i + 1) + "'>	<input type='text' name='" + "qtype".concat(i + 1) + "'>	<input type='text' id='sum' onkeyup='myfunction(this.value);' name='" + "total".concat(i + 1) + "'>
";
      var table = document.createElement('table');
      table.innerHTML = elems;
      document.getElementById("table").appendChild(table.firstChild);
    }
  }
}
div {
  background: red;
  margin: 5px;
}
table {
  border: 2px solid black;
}
td {
  padding: 10px;
  border: 1px solid lightgrey;
}
<input type="text" id="tb1" />
<button type="button" onclick='createTable()'>Click Me!</button>

A: First of all You are missing

 in wrapping the th, wrap the th in tr, and for new rows to append the previous row you have to use the insertRow porperty of javascript.
Here is your modified snippet
Thanks

<!DOCTYPE html>

    <meta charset="UTF-8">
    <title></title>

<input type="text" id="tb1"/>
<button type="button" onclick='createTable()'>Click Me!</button>

A: What you did was setting new value to the table each time. what you actually would like to do is appending data to the table using "appendChild" function. this can also be created, even more easily, using
here is a working fiddle with the change (using js appendChild):
<!DOCTYPE html>

    <meta charset="UTF-8">
    <title></title>

<input type="text" id="tb1"/>
<button type="button" onclick='createTable()'>Click Me!</button>

i would recommend learning to use jquery. anyway, here is some info about the functions i mentioned:
jquery and their "append" function.
info about js appendChild - http://www.w3schools.com/jsref/met_node_appendchild.asp
jquery append - http://api.jquery.com/append/


text:
Q: App Center Push with Google Sign In on React Native I've been trying to integrate Microsoft App Center Push with React Native on Android. I am following the official docs here. I have also used the 'react-native-google-signin' module for google login.
The problem is that when using these 2 together, the notifications only come through when the app is in the foreground. I have narrowed down the issue to the com.google.gms.google-services gradle plugin (required by the google sign in module) which seems to add the following BroadcastReceiver and Service to the AndroidManifest.xml
<receiver android:name="com.google.firebase.iid.FirebaseInstanceIdReceiver" android:permission="com.google.android.c2dm.permission.SEND" android:exported="true">
    <intent-filter>
        <action android:name="com.google.android.c2dm.intent.RECEIVE" />
        <category android:name="se.crossplatform.parkeraapp" />
    </intent-filter>
</receiver>
<service android:name="com.google.firebase.iid.FirebaseInstanceIdService" android:exported="true">
    <intent-filter android:priority="-500">
        <action android:name="com.google.firebase.INSTANCE_ID_EVENT" />
    </intent-filter>
</service>

These seem to override the following BroadcastReceiver and Service added to the AndroidManifest.xml by the App center Push module
<receiver android:name="com.microsoft.appcenter.push.PushReceiver" android:permission="com.google.android.c2dm.permission.SEND">
    <intent-filter>
        <action android:name="com.google.android.c2dm.intent.REGISTRATION" />
        <action android:name="com.google.android.c2dm.intent.RECEIVE" />
        <category android:name="se.crossplatform.parkeraapp" />
    </intent-filter>
</receiver>
<service android:name="com.microsoft.appcenter.push.TokenService">
    <intent-filter>
        <action android:name="com.google.firebase.INSTANCE_ID_EVENT" />
    </intent-filter>
</service>

I am at a loss on how to solve this


text:
Q: Amazon SES - Hide recipient email addresses I am testing Amazon SES through boto3 python library. When i send emails i see all the recipient addresses. How to hide these ToAddresses of multiple email via Amazon SES ?

Following is the part of the code
import boto3
client=boto3.client('ses')
to_addresses=["**@**","**@**","**@**",...]

response = client.send_email(
    Source=source_email,
    Destination={
        'ToAddresses': to_addresses
    },
    Message={
        'Subject': {
        'Data': subject,
        'Charset': encoding
        },
        'Body': {
            'Text': {
                'Data': body ,
                'Charset': encoding
            },
            'Html': {
                'Data': html_text,
                'Charset': encoding
            }
        }
    },
    ReplyToAddresses=reply_to_addresses
)

A: We use the send_raw_email function instead which gives more control over the make up of your message. You could easily add Bcc headers this way.
An example of the code that generates the message and how to send it
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText

msg = MIMEMultipart('alternative')
msg['Subject'] = 'Testing BCC'
msg['From'] = 'no-reply@example.com'
msg['To'] = 'user@otherdomain.com'
msg['Bcc'] = 'hidden@otherdomain.com'

We use templating and MIMEText to add the message content (templating part not shown).
part1 = MIMEText(text, 'plain', 'utf-8')
part2 = MIMEText(html, 'html', 'utf-8')
msg.attach(part1)
msg.attach(part2)

Then send using the SES send_raw_email().
ses_conn.send_raw_email(msg.as_string())


text:
Q: Which class invoked my static method? Suppose that I have a Java class with a static method, like so:

class A
{
    static void foo()
    {
        // Which class invoked me?
    }
}

And suppose further that class A has an arbitrary number of subclasses:

class B extends A { }
class C extends A { }
class D extends A { }
...

Now consider the following method invocations:

A.foo();
B.foo();
C.foo();
D.foo();
...

My question is, how can method foo() tell which class is invoking it?

A: Although you can't find out which class the static method was invoked on, it is possible to find out which class actually invoked the method at runtime:
static void foo()
{
   Throwable t = new Throwable();
   StackTraceElement[] trace = t.getStackTrace();
   String className = trace[1].getClassName();
   Class whoCalledMe = null;
   try
   {
      whoCalledMe = Class.forName( className );
   }
   catch( Exception e )
   {
   }
}

I'm not saying that this is good practice and its probably not great from a performance perspective either, but it should work. Don't know if that helps you any ...

A: class A
{
    static void foo(A whoIsCalingMe)
    {
        // Which class invoked me?
    }
}

A: It can't, and that's part of the problem with static methods.  As far as the compiler is concerned A.foo() and B.foo() are exactly the same thing.  In fact, they compile down to the same bytecode.  You can't get more similar than that.
If you really need this sort of information, use a singleton and turn foo() into an instance method.  If you still like the static syntax, you can build a facade A.foo().


text:
Q: Nservicebus serization issue of derived types for the context setting, I am exchanging messages between my nServiceBus client and nSerivceBus server. its is the namespace xyz.Messages and and a class, Message : IMessage
I have more messages that are in the other dlls, like xyz.Messages.Domain1, xyz.Messages.Domain2, xyz.Messages.Domain3.
and messages that derive form that base message, Message.
I have the endpoints defined as like :
 at client
<UnicastBusConfig>
 <MessageEndpointMappings>
    <add Messages="xyz.Messages" Endpoint="xyzServerQueue" />
    <add Messages="xyz.Messages.Domain1" Endpoint="xyzServerQueue" />
    <add Messages="xyz.Messages.Domain2" Endpoint="xyzServerQueue" />
  </MessageEndpointMappings>
</UnicastBusConfig>

at Server
<UnicastBusConfig>
 <MessageEndpointMappings>
   <add Messages="xyz.Messages" Endpoint="xyzClientQueue" />
   <add Messages="xyz.Messages.Domain1" Endpoint="xyzClientQueue" />
   <add Messages="xyz.Messages.Domain2" Endpoint="xyzClientQueue" />
 </MessageEndpointMappings>
</UnicastBusConfig>

and the bus initialized as
        IBus serviceBus = Configure.With()
            .SpringBuilder()
            .XmlSerializer()
            .MsmqTransport()
            .UnicastBus()
            .LoadMessageHandlers()
            .CreateBus()
            .Start();

now when i try sending instance of Message type or any type derived types of Message, it successfully sends the message over and at the server, i get the proper type.
eg.
Message message= new Message();
Bus.Send(message); // works fine, transfers Message type
message = new MessageDerived1();
Bus.Send(message); // works fine, transfers MessageDerived1 type
message = new MessageDerived2();
Bus.Send(message); // works fine, transfers MessageDerived2 type

My problem arises when any type, say MessageDerived1, contains a member variable of type Message, and when i assign it to a derived type, the type is not properly transferred over the wire. It transfers only as Message type, not the derived type.
public class MessageDerived2 : Message
{
  public Message message;
}

MessageDerived2 messageDerived2= new MessageDerived2();
messageDerived2.message = new MessageDerived1();
message = messageDerived2;
Bus.Send(message); // incorrect behaviour, transfers MessageDerived2 correctly, but looses type of  MessageDerived2.Message (it deserializes as Message type, instead of MessageDerived1)

any help is strongly appreciated.
Thanks
TJ

A: The NServiceBus XmlSerializer does not support this - see the thread at http://tech.groups.yahoo.com/group/nservicebus/message/6549
BinarySerializer will work, or you can implement a custom message serialiser. In my opinion DataContractSerializer should be available out of the box for serialisation scenarios that XmlSerializer doesn't handle.
Note that by doing this you'll probably lose the NSB message versioning support - if this is important to you, I'd suggest rethinking your message design.

A: Here is Udi's reply
First of all, it is highly unusual to have the client queues appear in the server's config. I'd recommend removing that.
Second, I assume that you're not using the generic host as you're manually initializing the bus - that's fine, just wanted to check.
Also, are you using the same code for both client and server side initialization? That isn't particularly recommended.
At the very least, the server side should be transactional (unless you're going down some idempotent messaging route).
Third, what you're trying to do should work just fine if you use the Binary Serializer. The reason is the assumption of tighter coupling and less of a need for explicit message contracts. The XML Serializer, on the other hand, is built to enforce more explicit message schema - therefore not supporting those kinds of derived types.
The scenarios where you might want to use derived types in your messages (queries, straight data manipulation, etc) are usually the areas where you shouldn't be using messaging to begin with.
Hope that helps in some way.
-- Udi Dahan


text:
Q: find sub-group of any given number sorry i couldn't think of better title
so i have a number lets say 13(variable)  and by dividing it to 5 (constant)
i get my groups  (3 in this example )
1 => 1-5
2 => 6-10
3 => 11-13

now i want to know group of each number between 1-13
groups = roundsUp(number / 5) ;

in this example
what is  the formula to get group(1 or 2 or 3)  of each number (1 to 13)

A: You seem to already understand how to get from item number $i$ to group number $g$, in the formula you have given - your groups = roundsUp(number / 5); which might be written  $g=\lceil \frac{i}{5}\rceil$ (those are doing the same thing - $\lceil x \rceil$ is the smallest integer greater than or equal to $x$).
If you want the first item number of a group, it's $i_F=5(g-1) +1$, and the last item number in group $g$ is of course $i_L=5g$, except that you need to check that this does not exceed the last item number.
I've written these (in particular $i_F$) so that if the constant $5$ changes, you can just swap the new number in place.
Are any or all of these what you were asking for?


text:
Q: How can show the drop down value against the enum value status is a drop down having values (new, started, completed) if it's a feature or (new, started and resolved) if it's a bug. I don't know how can i do this
Model
Class Task
  enum typeOf: %i[feature bug]
  enum status_is: %i[New started completed resolved]
end

erb.html
<%= form_for :task, url: project_tasks_path, :html => {:multipart => true, :cla

   <%= f.hidden_field :project %>
   Title: <%=f.text_field :title, class:"form-control" %>

   Description: <%=f.text_field :description, class:"form-control" %>

   Deadline<input type="datetime-local" id="deadline"
                                         name="deadline" >

   Screen Shot: <%=f.file_field :screen_shot, multiple: true, class:"form-control" %>

     <%= f.label :typeOf, class:"form-control" %>

     <%= f.select(:typeOf, Task.typeOfs.keys.map {|role| [role.titleize,role]}) %>

     <%= f.label :status_is, class:"form-control" %>

     <%= f.select(:status_is, Task.status_is.keys.map {|role| [role.titleize,role]}) %>

   <%= f.submit "Add" %>

<%end %>

A: I would go with two separate select boxes, each with the expected cases:

     <%= f.label :status_is, class:"form-control" %>

     <%= f.select(:status_is, (Task.status_is.keys - ['completed']).map {|role| [role.titleize,role]}) %>

     <%= f.label :status_is, class:"form-control" %>

     <%= f.select(:status_is, (Task.status_is.keys - ['resolved']).map {|role| [role.titleize,role]}) %>

And then you use a sprinkle of javascript to toggle them in/out:
function toggleSelects() {
  var value = $('#task_typeOf')[0].value;

  $('[data-target=bug]').toggle(value === 'bug');
  $('[data-target=bug] select').attr('disable', value !== 'bug');

  $('[data-target=feature]').toggle(value === 'feature');
  $('[data-target=feature] select').attr('disable', value !== 'feature');
}

// execute every time the type of task is changed
$('#task_typeOf').on('change', () => toggleSelects());

// also execute at document load
$(toggleSelects);

Of course you can use different strategies or wrappers to hide the fields and disable the selects, but you have to do both (a hidden select will be submitted anyways).


text:
Q: mpi process exitting on signal 11 I have an simple mpi program for performing MPI_Scatter and MPI_Gather. It takes in as argument number of elements to be sent to each process and then performs average of random numbers on different processes using  MPI_Scatter and MPI_Gather.
float *create_rand_nums(int num_elements){
    float *rand_nums = (float *)malloc(sizeof(float) * num_elements);
    assert(rand_nums != NULL);
    int i;
    for (i = 0 ; i < num_elements; i++){
        *(rand_nums+i) = (rand()/ (float)RAND_MAX);
        printf("Create_rand_nums func val %f \n", *(rand_nums+i));
        //printf("Create_rand_nums func address %f \n", (rand_nums+i));
    }
    return rand_nums;
}

// Computes the average of an array of numbers
float compute_avg(float *array, int num_elements){
    float sum = 0.f;
    int i;
    for (i = 0; i < num_elements; i++) {
        sum += array[i];
    }
    return sum / num_elements;
}

int main(int argc, char *argv[])
{
if (argc != 2) {
    fprintf(stderr, "Usage: avg num_elements_per_proc\n");
    exit(1);
  }

  int num_elements_per_proc = atoi(argv[0]);
  // Seed the random number generator to get different results each time
  srand(time(NULL));

MPI_Init(NULL, NULL);
  int world_rank;
  MPI_Comm_rank(MPI_COMM_WORLD, &world_rank);
  int world_size;
  MPI_Comm_size(MPI_COMM_WORLD, &world_size);

  // Create a random array of elements on the root process. Its total
  // size will be the number of elements per process times the number of processes
  float *rand_nums = NULL;
  if (world_rank == 0){
   rand_nums = create_rand_nums(num_elements_per_proc * world_size);
  }

  // For each process, create a buffer that will hold a subset of the entire array
  float *sub_rand_nums = (float *)malloc(sizeof(float) * num_elements_per_proc);
  assert(sub_rand_nums != NULL);

  // Scatter the random numbers from the root process to all processes in the MPI world
  MPI_Scatter(rand_nums, num_elements_per_proc, MPI_FLOAT, sub_rand_nums, num_elements_per_proc, MPI_FLOAT, 0, MPI_COMM_WORLD);

  // Compute the average of your subset
  float sub_avg = compute_avg(sub_rand_nums, num_elements_per_proc);
  int i;
  printf("Avg inside %f \n", sub_avg);

  // Gather all partial averages down to the root process
  float *sub_avgs = NULL;
  if (world_rank == 0) {
    sub_avgs = (float *)malloc(sizeof(float) * world_size);
    assert(sub_avgs != NULL);
  }
  MPI_Gather(&sub_avg, 1, MPI_FLOAT, sub_avgs, 1, MPI_FLOAT, 0, MPI_COMM_WORLD);

  for (i = 0; i < world_size; i++) {
        printf("Avg %f \n", *(sub_avgs+i));
    }

  // Now that we have all of the partial averages on the root, compute the
  // total average of all numbers. Since we are assuming each process computed
  // an average across an equal amount of elements, this computation will
  // produce the correct answer.
  if (world_rank == 0) {
    float avg = compute_avg(sub_avgs, world_size);
    printf("Avg of all elements is %f\n", avg);
    // Compute the average across the original data for comparison
    float original_data_avg =
      compute_avg(rand_nums, num_elements_per_proc * world_size);
    printf("Avg computed across original data is %f\n", original_data_avg);

  }

// Clean up
  if (world_rank == 0) {
    free(rand_nums);
    free(sub_avgs);
  }
  free(sub_rand_nums);

  MPI_Barrier(MPI_COMM_WORLD);
  MPI_Finalize();
}

On running this code, I am getting :

mpicc -o MPI_Scatter_MPI_Gather MPI_Scatter_MPI_Gather.cc
mpirun --oversubscribe -host localhost -np 4 ./MPI_Scatter_MPI_Gather 2

Avg inside nan
Avg inside nan
Avg inside nan
Avg inside nan
[dhcp-10-142-19] *** Process received signal ***
[dhcp-10-142-19] Signal: Segmentation fault: 11 (11)
[dhcp-10-142-19] Signal code: Address not mapped (1)
[dhcp-10-142-19] Failing at address: 0x0
[dhcp-10-142-19] [ 0] 0   libsystem_platform.dylib            0x00007fff50b65f5a _sigtramp + 26
[dhcp-10-142-19] [ 1] 0   ???                                 0x0000000000000000 0x0 + 0
[dhcp-10-142-19] [ 2] 0   libdyld.dylib                       0x00007fff508e5145 start + 1
[dhcp-10-142-19] [ 3] 0   ???                                 0x0000000000000002 0x0 + 2
[dhcp-10-142-19] *** End of error message ***
[dhcp-10-142-19] *** Process received signal ***
[dhcp-10-142-19] Signal: Segmentation fault: 11 (11)
[dhcp-10-142-19] Signal code: Address not mapped (1)
[dhcp-10-142-19] Failing at address: 0x0
[dhcp-10-142-19] [ 0] 0   libsystem_platform.dylib            0x0000--------------------------------------------------------------------------
mpirun noticed that process rank 3 with PID 0 on node dhcp-10-142-194-10 exited on signal 11 (Segmentation fault: 11).
--------------------------------------------------------------------------
7fff50b65f5a _sigtramp + 26
[dhcp-10-142-19] [ 1] 0   ???                                 0x0000000000000000 0x0 + 0
[dhcp-10-142-19] [ 2] 0   libdyld.dylib                       0x00007fff508e5145 start + 1
[dhcp-10-142-19] [ 3] 0   ???                                 0x0000000000000002 0x0 + 2
[dhcp-10-142-19] *** End of error message ***
[dhcp-10-142-19] *** Process received signal ***
[dhcp-10-142-19] Signal: Segmentation fault: 11 (11)
[dhcp-10-142-19] Signal code: Address not mapped (1)
[dhcp-10-142-19] Failing at address: 0x0
[dhcp-10-142-19] [ 0] 0   libsystem_platform.dylib            0x00007fff50b65f5a _sigtramp + 26
[dhcp-10-142-19] [ 1] 0   ???                                 0x0000000000000000 0x0 + 0
[dhcp-10-142-19] [ 2] 0   libdyld.dylib                       0x00007fff508e5145 start + 1
[dhcp-10-142-19] [ 3] 0   ???                                 0x0000000000000002 0x0 + 2
[dhcp-10-142-19] *** End of error message ***
[dhcp-10-142-19] *** Process received signal ***
[dhcp-10-142-19] Signal: Segmentation fault: 11 (11)
[dhcp-10-142-19] Signal code:  (0)
[dhcp-10-142-19] Failing at address: 0x0
[dhcp-10-142-19] [ 0] 0   libsystem_platform.dylib            0x00007fff50b65f5a _sigtramp + 26
[dhcp-10-142-19] [ 1] 0   ???                                 0x0000000000000000 0x0 + 0
[dhcp-10-142-19] [ 2] 0   libdyld.dylib                       0x00007fff508e5145 start + 1
[dhcp-10-142-19] [ 3] 0   ???                                 0x0000000000000002 0x0 + 2
[dhcp-10-142-19] *** End of error message ***

I want to run this program first on 1 machine with 2 core and then on multiple machines. But it is failing even on a single machine. Please help

A: As pointed out in Gilles Gouaillardet's comment, atoi(argv[0]) is badly-formed, and sub-avgs should only be printed on rank 0.


text:
Q: Reflection of setter, getter method I am trying to implement reflection code in java. I am new to using reflections and I have an existing method like this:
ScheduleParams incomeResetFXSchedule = performanceSwapLeg.getIncomeFxResetSchedule();
    if (performanceSwapLeg.getIncomeFxResetSchedule().getDateRoll() != null) {
        incomeResetFXSchedule.setDateRoll(DateRoll.valueOf(performanceSwapLeg.getIncomeFxResetSchedule().getDateRoll().toString()));
    } else {
        incomeResetFXSchedule.setDateRoll(DateRoll.valueOf(DateRoll.S_PRECEDING));
    }

I was trying to write reflection code for the above code and I am stuck at this point:
 try {
        Class<ScheduleParams> incomeFXResetSchedule = ScheduleParams.class;
        Class<DateRoll> dateRoll = DateRoll.class;
        try {
            Method m = PerformanceSwapLeg.class.getMethod("getIncomeFxResetSchedule");
            m.invoke(performanceSwapLeg);
            Method m1 = ScheduleParams.class.getMethod("setDateRoll", dateRoll);
            m1.invoke(performanceSwapLeg);
        } catch (Exception e) {
            Log.error(CommonConstants.ERROR_LOG, "Failed to invoke the method" + e.getMessage());
        }
    } catch (Exception e) {
   //Do Nothing
    }

But I am not sure how to call the setter method and the getter method. Any suggestions on how to call this kind of methods using reflections.

A: You are already calling 'em! But just in the wrong way.
When you do m.invoke you're calling the method, but you're doing it like the following line:
getIncomeFxResetSchedule();

If you watch that line what you'll think? Uuuhm, I think I missed the variable where I'll save the value! Method.Invoke returns an Object, thus you'll need to cast it to your class. I guess your class is ScheduleParams.
ScheduleParams scheduleParams = (ScheduleParams) m.invoke(performanceSwapLeg);

Okay, great. Now I want to set it.
Once again, you're calling a method which receives params without passing any param:
Method m1 = ScheduleParams.class.getMethod("setDateRoll", dateRoll);
m1.invoke(performanceSwapLeg);

It's like the following line:
setDateRoll();

That is probably throwing an
java.lang.IllegalArgumentException: wrong number of arguments

Because you have no method called like that which takes no arguments (I hope so), now the right way should be:
 Method m1 = ScheduleParams.class.getMethod("setDateRoll", dateRoll);
 m1.invoke(performanceSwapLeg, new DateRoll());

After that you could call the getter again and you'll get a whole new object.
I recommend you to read the following related question:

*

*What is reflection and why is it useful?
And the Oracle's documentation about reflection api.

*

*Trail: The Reflection API


text:
Q: Checkbox in Touch UI dialog not returning a Boolean value - AEM 6.2 I have created a touch UI dialog that has a check box. I have used the post servlet suffix @TypeHint so that the returned value is a Boolean (true or false)
My Code -
<enableTooltip
jcr:primaryType="nt:unstructured"
sling:resourceType="granite/ui/components/foundation/form/checkbox"
name="./enableTooltip"
text="Enable tooltip?"
value="true"/>

<enableTooltipType
jcr:primaryType="nt:unstructured"
sling:resourceType="granite/ui/components/foundation/form/hidden"
name="./enableTooltip@TypeHint"
value="Boolean"/>

Now when I try to run this sightly statement -

This is test data

"This is test data" is always printed irrespective of the fact whether the checkbox is checked or not.
What's wrong?
Thanks in advance!

A: According to the documentation https://docs.adobe.com/docs/en/aem/6-3/develop/ref/granite-ui/api/jcr_root/libs/granite/ui/components/foundation/form/checkbox/index.html what you have done is right. You can try below sample, this perfectly works for me in AEM 6.2:
In Dialog:
<myCheckbox
                            jcr:primaryType="nt:unstructured"
                            sling:resourceType="granite/ui/components/foundation/form/checkbox"
                            name="./selected" text="Show Checkbox Value"
                            uncheckedValue="false"
                            value="{Boolean}true"/>

In Html:

${selected}


text:
Q: Referencing computers by their name between OS X and Windows operating systems I just got an iMac and have connected it to my existing network (a Workgroup not a Domain) of computers that are all running Windows (XP, Server 08 R2, Win7).
From the iMac, I can successfully PING all Windows machines by their IP Address. However, I am unable to PING the Windows computers (from the iMac) by their computer name.
What do I need to install/configure/etc in order to be able to PING by computer names instead of IP Addresses?
By the way, I have successfully setup my iMac's hosts file so that the computer names are known to the iMac. However, I don't prefer this solution since it requires that the Windows computers have a static IP Address.
UPDATE
In response to @Milliways -
I'm not just wanting to PING the Windows machines from the iMac. What I'm really trying to solve here is, this...
Some of the Windows machines are running a Web Server. Currently, I am able to browse those web sites from the iMac by opening up Safari/Chrome/etc and connecting to the URL of the local IP of the server - in other words, from the iMac, I can successfully connect to "http://192.168.1.10/foo/bar/etc".
I am trying to figure out how to configure my iMac so the iMac can use the machine name in the URL instead of the IP - eg: "http://SERVER-1/foo/bar/etc".
One thing I should note here is that on my iMac I have a Windows virtual machine (via Parallels). This virt can successfully connect to the Windows Web Servers that are on the network via the machine name. In other words, if I open a browser in the virtual machine, I can successfully connect to "http://SERVER-1/foo/bar/etc".
I mention this virtual machine scenario because it reveals to me that there must be a missing/unconfigured mechanism on the iMac machine that is making NetBios to not work (as opposed to something that is missing/unconfigured on the Windows machines and/or my router).

A: Install Bonjour for Windows on your Windows hosts (it's a part of the OS on Mac OS X already, no need to install there; for Windows, you can download it from Apple as a part of Bonjour Print Services). This way, each of the computers will "see" the others as hostname.local, where "hostname" is the name of that computer.

A: I am assuming you don't just want to ping the Windows machines, but connect to them.
I have enabled sharing to a network including many Windows computers (even including ME) without installing any special software (although Bonjour is a good idea).
Firstly you need to enable Windows Sharing (in System Preferences/Sharing/File Sharing).
You also need to ensure all computers are using the same Workgroup (set in Network/Wi-Fi/Advanced/WINS).
NOTE Different versions of windows use different default Workgroups - you should ensure these are all the same - preferably chose your own name.
Even after doing this (and restarting the windows machine if Workgroup is changed) it can take  while for computers to discover each other. This is limitation of the SMB protocol.
You can connect to the Windows machines in Finder Connect to Server at smb://ComputerName
(This doesn't make ping work)

A: Two ways I can think of:

*

*Provide a DNS server on your local network

*Assign static IPs to your Windows computers

Depending on your switch/router you may be able to read the DHCP clients table from it or reserve your IPs by MAC address.

A: You can just add .local to the server name. That would be: SERVER-1.local
So, your URL would be: http://SERVER-1.local/foo/bar/etc


text:
Q: Gridview click on header for sorting triggering row command I have a fairly simple GridView. This is the markup for Columns:
 <Columns>
                <asp:TemplateField HeaderText="JD Name" SortExpression="FullName"
                    HeaderStyle-HorizontalAlign="Center" ItemStyle-Width="180px" >
                    <ItemTemplate>
                        <asp:LinkButton CommandName="edt" CommandArgument='<%#Eval("JurisdictionID") %>' runat="server" Text='<%#Eval("FullName") %>' />
                    </ItemTemplate>
                </asp:TemplateField>

                <asp:BoundField HeaderText="JD Abbreviation" ItemStyle-Width="200px"  DataField="JDAbbreviation" SortExpression="JDAbbreviation"
                    HeaderStyle-HorizontalAlign="Center" />

                 <asp:TemplateField
                    HeaderStyle-HorizontalAlign="Center" >
                    <ItemTemplate>
                        <asp:LinkButton ID="lnkStat" CommandName="inac" CommandArgument='<%#Eval("JurisdictionID") %>'
                        runat="server" Text='<%#Utils.GetStatusString((bool) Eval("IsActive")) %>' />
                    </ItemTemplate>
                </asp:TemplateField>

            </Columns>

However, when I click on of the columns for sorting, it first triggers a row command event and then comes to sorting event. Can anybody tell me what is the mistake I am doing? In the RowCommand argument I get the SortExpression. This is really funny for me!

A: Sort is a row command.  Check out this MSDN GridView.RowCommand Event article for more details.
In your row command event you should add an if statement so you can determine when the row command code should execute.  Use e.CommandName.
void ContactsGridView_RowCommand(Object sender, GridViewCommandEventArgs e)
{
  // If multiple buttons are used in a GridView control, use the
  // CommandName property to determine which button was clicked.
  if(e.CommandName=="Add")
  {
    // Convert the row index stored in the CommandArgument
    // property to an Integer.
    int index = Convert.ToInt32(e.CommandArgument);

    // Retrieve the row that contains the button clicked
    // by the user from the Rows collection.
    GridViewRow row = ContactsGridView.Rows[index];

    // Create a new ListItem object for the contact in the row.
    ListItem item = new ListItem();
    item.Text = Server.HtmlDecode(row.Cells[2].Text) + " " +
    Server.HtmlDecode(row.Cells[3].Text);

    // If the contact is not already in the ListBox, add the ListItem
    // object to the Items collection of the ListBox control.
    if (!ContactsListBox.Items.Contains(item))
    {
      ContactsListBox.Items.Add(item);
    }
  }
}