How do I solve this algorithm in finding the distance between origin and remotepoint?

Question: Main Class
import java.util.*;

public class Q6_7_Muhammed_Irshath {
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        TwoDPoint twodpoint = new TwoDPoint(); // Created an object for TwoDPoint class
        Scanner sc = new Scanner(System.in); // Created this to test input

        for (int i = 0; i < 1;i++) {
            System.out.println("Please enter value for x: ");
            double x = sc.nextDouble();
            System.out.println("Please enter value for y: ");
            double y = sc.nextDouble();
        }
    }
}

TwoDPoint Class
import java.util.*;

public class TwoDPoint {

    private static int x;
    private static int y;

    TwoDPoint(){
        x = 0;
        y = 0;
    }

    TwoDPoint(double x, double y){

    }

    public static int getX() {
        return x;
    }

    public static int getY() {
        return y;
    }

    public double findDistance(TwoDPoint remotepoint) {
        double distance = 0;

        TwoDPoint.getX();
        TwoDPoint.getY();

        distance =
        return 0;
    }
}

I have an algorithm where I have to find the distance between origin(0,0) and remotepoint(x,y) which has to be read input. My issue is how can I use twodpoint object to retrieve the (x,y) and put it in the findDistance method in TwoDPoint Class? And how to calculate the distance?
Please don't judge me I'm new to this. I can't even solve a simple question. This is the way I must use to solve the algorithm
Comment: Google: [distance between 2 points on a line](https://www.google.com/search?q=distance+between+2+points+on+a+line)
Comment: @JohnnyMopp I saw that but all I want is just to improve the code
Answer: Could try this and adapt the inputs as wanted (from console, etc)
import java.util.Scanner;

public class SolveTwoP {
double x,y;
public static void main(String[] args)
{
    SolveTwoP sol = new SolveTwoP();

    Scanner sc = new Scanner(System.in); // Created this to test input

    //no need loop here
    System.out.println("Please enter value for x: ");
    sol.x = sc.nextDouble();
    System.out.println("Please enter value for y: ");
    sol.y = sc.nextDouble();

    double result = sol. new TwoDPoint().findDistance(sol.new TwoDPoint(sol.x,sol.y));
    System.out.println(result);

    //get an instance of solver and invoke with the point on x=3, y=4
    //solver TwoDPoint is also assign the coordinates

    //double result = sol. new TwoDPoint().findDistance(sol.new TwoDPoint(3,4));
    //System.out.println(result);

}
//inner class
class TwoDPoint {

    private  double x;
    private  double y;

    TwoDPoint()
    {
        x = 0;
        y = 0;
    }
    TwoDPoint(double x, double y){
        this.x=x;
        this.y=y;
    }

    public double getX() {
        return x;
    }
    public Double getY() {
        return y;
    }

    public double findDistance(TwoDPoint remotepoint)
    {
        double distance = remotepoint.getX()*remotepoint.getX() + remotepoint.getY()*remotepoint.getY();
        distance = Math.sqrt(distance);
        return distance;
    }
}
}

Output:5.0 for x=3 and y=4 or reversed ...
 The formula is based on Pitagora theorem with (0,0) given as origin
Comment: check it now, but how to connect to various inputs should be basically a trivial task ...


Ember.js count position of object in Ember Data Model for simple pagination

Question: I am tryin to count the position of an object. That means which numeric position an item has. That cannot be the primary key because they are not persistent; a record can get deleted.
Asume we have this "model" (a simple array for now, I use Ember Data):
posts = [
  {id: 4, number: 104, title: 'Post 4'},
  {id: 2, number: 102, title: 'Post 2'},
  {id: 3, number: 103, title: 'Post 3'},
];

So at to allow sorting in the postsController we do:
this.controllerFor('posts').set('sortProperties', ['id']); // or maybe just sorting on 'number'
this.controllerFor('posts').set('sortAscending', true);

In the template I want to show the current post and the total number of posts {{currentPostCount}} of {{totalPostCount}}
In postController I have the following computed properties:
App.PostController = Ember.ObjectController.extend({

    posts: function () {
        return this.store.all('posts');
    }.property(),

    currentCount: function () {
        // if there is an id get the position of the record
        // that will be the position count of the post record
        var id = this.get('id');
        if (id) {
            console.log('this item has an id: ' + id);

            var count = 0;
            var currentCount;

            // loop over posts to check at which position the current post is
            this.get('posts').filter(function (item) {

                count++;
                if (item.id == id) {
                    console.log('yay id found! count is: ' + count)
                     currentCount = count;
                }
            });

            return currentCount;
        }
    }.property('posts.@each'),

    totalCount: function () {
        var posts= this.get('posts');
        return posts.get('length');
    }.property('posts.@each')
});

Edit: add model:
App.ApplicationRoute = Ember.Route.extend({
    model: function() {
        this.controllerFor('posts').set('model', this.store.find('post'));
        // sort posts by id
        this.controllerFor('posts').set('sortProperties', ['id']);
        //(...)
    }
});

App.PostsController = Ember.ArrayController.extend();

.
Update: full working simple pagination in Ember.js
In your template:

      Post {{index}}/{{totalCount}}
      Previous
      Next

The PostsController:
App.PostsController = Ember.ArrayController.extend({
    sortProperties: ['id'], // I sort on ID, but you can sort on any property you want.
    sortAscending: true,

    assignIndex: function () {
        this.map(function (item, index) {
            Ember.set(item, 'index', index + 1)
        })
    }.observes('content.[]', 'firstObject', 'lastObject')

});

Actions in the PostController:
    previousPost: function (post) {
        var newIndex = (post.index - 1);
        var previousPost = this.store.all('post').findBy('index', newIndex);

        if (previousPost) {
            this.transitionToRoute('post', previousPost);
        }
    },

    nextPost: function (post) {
        var newIndex = (post.index + 1);
        var nextPost = this.store.all('post').findBy('index', newIndex);

        if (nextPost) {
            this.transitionToRoute('post', nextPost);
        }
    }

I have two computed properties in the PostController. However you can better use the following in your PostsController to do it the Ember way, like kingpin2k said. Then you can also omit the posts property.
posts: function () {
    return this.store.all('posts');
}.property(),

// totalcount below the page for pagination
totalCount: function () {
    var posts= this.get('posts');
    return posts.get('length');
}.property('posts.@each'),

Comment: Is there any reason you use find on the posts controller, bu all in the post? (aka the posts controller won't stay up to date)
Comment: do you have a posts controller?
Comment: Yes, that is where the actions above live. I edit my question accordingly for you.
Comment: does the posts controller have all the posts as its backing model?
Comment: I have edited the question. For the model I also edit the above question. Edit: because I only need to show one post at a time, not all posts at once. I do the model like this. There is no Posts route. I only need Posts for showing in a select box or to count it, like I try.
Comment: Aha, it is not done to do things for Posts in the Post controller. I should do it in the Posts controller then. I try to get it done that way.
Answer: You can maintain an index on array content during sorting or removing objects.
In PostsController:
App.PostsController=Em.ArrayController.extend({
    assignIndex:function(){
        this.map(function(item,index){Em.set(item,'index',index+1)})
        }.observes('content.[]','firstObject','lastObject'),
            //other contents to follow...

In posts template the property index is available which is dynamically updated when adding or removing or sorting objects.
In Posts Template:
{{#each controller}}

{{index}}. {{name}}

{{/each}}

Comment: Thanks for your answer, wow that is an easy way to add an index! Awesome! I update my question with everything I have implemented to get the simple pagination working.


Closed-form expression for $\sum_{n=1}^{k} (-1)^{n+1}n^2(n^2-1)\binom{2k}{k-n}$?

Question: Wolframalpha tells me that
$$\sum_{n=1}^{k} (-1)^{n+1}n^2(n^2-1)\binom{2k}{k-n}=0$$ for $k>2$
However I have not been able to come up with a proof and I simply don't see how to do it. Does anyone have the slightest idea?
Anything is welcome: Proofs, hints, or references.
Thank you very much in advance
Comment: Have you tried a proof by induction?
Comment: Well, the basis $k=3$ is true :) $\sum_{n=1}^{3} (-1)^{n+1}n^2(n^2-1)\binom{2*3}{3-n} = 0 + -72 + 72 =  0$
Answer: We have
\begin{eqnarray*}
&&\sum_{1\le n\le k} (-1)^{n+1}n^2(n^2-1)\binom{2k}{k-n}\\
&=&\frac12 \sum_{1\le n\le k} (-1)^{n+1}n^2(n^2-1)\left(\binom{2k}{k-n}+\binom{2k}{k+n}\right),\\
&& \qquad \ \ \ \text{since } \binom{2k}{k-n} = \binom{2k}{k+n} \\
&=&\frac12 \sum_{-k\le n\le k, \ n\ne 0} (-1)^{n+1}n^2(n^2-1)\binom{2k}{k+n},\\
&& \qquad \ \ \ \text{rearranging terms and reindexing}\\
&=&\frac12 \sum_{-k\le n\le k} (-1)^{n+1}n^2(n^2-1)\binom{2k}{k+n}\\
&=&\frac12 (-1)^{k+1} \sum_{0\le \ell\le 2k} (-1)^{\ell} (\ell-k)^2((\ell-k)^2-1)\binom{2k}{\ell},\\
&& \qquad \ \ \ \text{reindexing using } \ell=k+n.
\end{eqnarray*}
Now, for any polynomial $P(M,\ell)$ of degree $d$ in $\ell$, the sum
$$
\sum_{0\le \ell\le M} (-1)^{\ell} P(M,\ell)  \binom{M}{\ell}
$$
will vanish if $M$ exceeds $d$.  The reason is that $P$ can be expressed as a linear combination of the first $d+1$ of the basis polynomials
$$1, \ \ \ell,\ \ \binom{\ell}{2}, \ \ \dots, \binom{\ell}{i}, \dots$$
with coefficients which are polynomials in $M$, and then, for each $j=0$, $\dots$, $d$,
\begin{eqnarray*}
&&\sum_{0\le \ell\le M} (-1)^{\ell} \binom{\ell}{j} \binom{M}{\ell}\\
&=&\binom{M}{j} \sum_{j\le \ell\le M} (-1)^{\ell} \binom{M-j}{\ell-j}\\
&=& \binom{M}{j} (-1)^j (1-1)^{M-j}\\
&=& 0.
\end{eqnarray*}
In the case here, we have $M=2k$, $P(M,\ell)=(\ell-\frac M2)^2((\ell-\frac M2)^2-1)$, and $d=4$, so the sum will vanish whenever $2k>4$, i.e., $k>2$.
Comment: Thank you very much for your answer. Indeed using your results, I think the identity can even be generalised to $\sum_{n=1}^{k}(-1)^{n+i+1}n^2(n^2-1)(n^2-4)\cdots(n^2-i^2)\binom{2k}{k-n}=0$.
Comment: Yes, although you then need $k>i+1$.
Comment: Indeed, I just forgot to include the condition on k. Thank you for pointing it out.


UIBarButtonItem font weight changes after push pop of navigation stack

Question: I have a UIBarButtonItem, "Done" - created in storyboard IB for ViewController A.
ViewController A is the root View Controller of the navigation stack.
If I push a View Controller B onto the navigation stack and then pop it again. the font weight of the Done button changes.

The font colour of the Done button is applied in A.viewWillAppear(..) and looks pretty much like
doneButton.tintColor = [CMPThemes navigationBarItemColour]; // it's a blue

I have stripped all appearance proxy code from the app (because there
are more than one style of navigation bars/buttons/titles appear in
the app) so I'm not looking for a fix that can only be done via the
appearance proxy...
I have checked in the debug view hierarchy that the Done button is
the same instance before and after the transitions
I have tried to re-apply the tint colour after the pop
I don't apply a font weight anywhere in the process
Also, to my eye, the font and font size seem to be unchanged during
the process.

In ViewController A
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    ...
    self.navigationController?.pushViewController(vcB, animated: true)
    ...

In ViewController B
viewDidLoad() {
    ...
    let backButton = UIBarButtonItem(image: UIImage(named: "arrowLeft"), style: .plain, target: self, action: #selector(goBack))
    backButton.tintColor = CMPThemes.popoverNavigationBarItemColour()
    self.navigationItem.leftBarButtonItem  = backButton
}

The storyboard looks like: (I've added the A and B to the image to maintain clarity).

If someone recognises the problem and can point me in the right direction for a fix that would be great!
Comment: Seem like in viewController B you have some custom UI such as back button. Maybe when creating custom back button, you did something affect done button. It's easier what is the problem here if you can give us a debug repo.
Comment: is there any code written in viewController B viewWillDisappear/viewDidDisappear ?
Comment: @ trungduc @muneeba I will update the question for you guys.
Comment: @Damo it looks fine, Do you do any special thing inside `CMPThemes`?
Comment: @trungduc no it's just a colour
Comment: try to change color of backbutton and check it affect color of done button
Comment: @SumitDhariwal I just did your test, it doesn't affect the "Done" button
Comment: i think you need to set navigation bar appearance tint color,it will definatly solve you problem.
Comment: @SumitDhariwal the navigation bar already has a tint (that grey)
Comment: i think that's way your done button getting grey
Comment: set navigation bar appearance tint color blue
Comment: then check it again
Comment: No, the Done button is not on View Controller B. I did change the tint colour out of simple perversity but the Done button still changes from a bold weight to a normal weight.
Comment: write navigation appearance tint color in viewwillappear method ,where done button is showing
Answer: I found the problem. The applied tint colour is not the issue. I think, Initially when it was loading the done button from the storyboard, the doneButton Style was equals .done and later when you are popping to ViewControllerA, somehow the style getting changed to .plan, so I think setting the style below the tint should fix the issue.
Try updating the viewWillAppear method in ViewControllerA with following code:
override func viewWillAppear(_ animated: Bool) {
    super.viewWillAppear(animated)
    doneButton.tintColor = [CMPThemes navigationBarItemColour]; // it's a blue
    doneButton.style = .done
}

Hope it helps!
Comment: yup - this indeed cured the ills. well done & ty Bhavin!
Answer: I have faced same issue.
I have back button custom Image and when I push view controller and press back it will getting bold (Default image)
So what I did in storyboard is apply single BLANK space to Back Button
Step 1
-->   Tap on Navigation item

Step 2
--> Put blank space on back Button

Now you can observe that
Navigation item has one blank item
Comment: I tried this but it made no difference to how my Done button behaves
Comment: @Damo Looks like you change to font because both fonts are different    Could you share your demo project ?
Comment: I can't sorry, I have to sanitise this post to obfuscate the client - The Done button is a standard UIBarButtonItem with only a tint change (not a font change to my knowledge)
Comment: @Damo No problem I understand your concern , Now the only option left is global search navigation item in your project and check all extensions check all subclasses may be you found something from there


Find the origin of a redirection

Question: I work on a Drupal project in business and we are facing a problem. We have a webform node with an alias ..../contact. We also have a page view .../news listing a specific type of content. Recently, when we want to go on / contact, we are redirected to the page /news. By enabling dlevel, it displays: "The user is being white Redirected to /en/news."
We have the "Pathauto" and "Global redirect" modules, but we never had a problem with these two.
We have no idea from where this redirection can come ... :(
Answer: You can see what page is the referer by using
<code>$_SERVER['HTTP_REFERER'];
</code>
Answer: It might be useful to examine the exact series for requests and responses that are taking place on the client side. That can provide clues about what redirects the server may be issuing, especially if there is some sort of chain involved. You'll find common browser plugins for this like "Live HTTP Headers" (firefox, chrome, etc.). When using these tools its helpful to tell them to exclude image/css/js files as those can really make the results difficult to scan.
On the server-side, there are a few modules to check:

Global Redirect is certainly a possible variable. You may want to disable it just long enough to isolate/eliminate it as a factor.
You'll want to see if you have the "Redirect" module installed (it's a common addition), and if so check it's configured redirect patterns.
Check if you have the core "Contact" module enabled as I believe this can introduce a menu entry for the /contact path that could be conflicting in a strange way.

The other key suspect is of course the web server itself. If you have any custom mod_rewrite rules in place, such as in your .htaccess file, you'll want to double-check those. I've also seen strange cases, especially on shared hosting environments, where the hosting provider issues it's own redirects on special paths, like /contact, that you may not have control over. That's probably an unlikely explanation, but it might not hurt to try changing your webform page's alias to something other than /contact to see if any behavior changes.

Find the origin of a redirection


Having trouble with SSH remote port forwarding

Question: all. My college network somehow disallows incoming connections.
(I can SSH out of the network, but not into it.)
I'm trying to set up an SSH tunnel from my school computer ("school") to a VPS "computer" ("outside") which is outside the school network.
I'm hoping to get to the point where I can do
ssh -p 3000 name@outside

and end up logged into name@school.
Here's how I'm trying to set up the remote port forwarding:
[name@school]$ ssh -R *:3000:localhost:22 outside

This command seems to work. (Running this with a -v flag gives
debug1: Remote connections from *:3000 forwarded to local address localhost:22
debug1: remote forward success for: listen 3000, connect localhost:22
debug1: All remote forwarding requests processed

which looks promising.)
However, when I follow up with a
ssh -p 3000 name@outside

it doesn't work:
ssh: connect to host outside port 3000: Connection refused

I can open up a netcat on the outside server and listen at port 3000, then connect to it with netcat from my school computer--this works fine. If I try to make an SSH tunnel from, say, outside:3000 to school:2000, then try to connect with netcat to outside:3000, I get
nc: connect to outside port 3000 (tcp) failed: Connection refused

The procedure above fails also if I try it between two computers on the school network, so I'm pretty sure the problem is me and not the computers/network.
Many thanks in advance for your help!
(edit: sorry, looks like this should go on serverfault?)
Comment: After resolving the port questions mentioned below you may want to try to connect by logging into the outside machine first and then ssh -p 3000 localhost and see how that goes. That will help track down where the connection is failing.
Comment: @Matt: ssh -p 3000 localhost (from the outside computer) works. ssh -p 3000 outside (from the school computer) doesn't. Thanks for the tip.
Answer: The university's firewall is blocking the connection. This is common to prevent misuse and to stop malware from propagating servers via BotNet methods. This is the same reason why most universities block IRC, as it is commonly used to communicate data back to the master.
Comment: Also, try a different port. http://www.auditmypc.com/port/tcp-port-3000.asp will explain why.
Comment: I know they're at least blocking some things (like I can't ssh to my school computer from outside the school network), I'm not sure what all, exactly, or how. But I figure there must be a way to set up a tunnel to the outside world (as long as the tunnel is initiated from within the network). I hope, at least! And thanks for the port change tip, I picked a different one and it still doesn't work.
Answer: From your own comment that you can do ssh -p 3000 locahost and it works, your method is valid. Somewhere along the line your connection to that outside host is being blocked. It is possible that the school is for some reason blocking any outgoing traffic on port 3000, or there is a firewall/acl on the 'outside' host that is blocking the connection. Another remote possibility is that the ISP of that outside is blocking the connection.
Try connecting from another outside host to it and see if that works. If it does, then your school is blocking it (which would be really odd, but school networks generally are). Otherwise take a look at the firewall rules on that outside host to see if its blocking it. Unfortunately for that last case of the ISP blocking, theres no real easy way to tell if its the ISP blocking, or the machine itself.


Can I assign an object to a subclass from a superclass constructor in PHP?

Question: With generic examples: I have a class called 'Person' and subclasses 'Artist' and 'Barber' that extend Person. The constructor for 'Person' pulls the information about the person from an SQL database based on a key or slug.
In most circumstances, the code knows what subclass of person it's creating, i.e.:
$jeff = new Barber( 'jeff' );

But there are times when my code doesn't know what the person's subclass is, but will have to get that from their SQL row.
What I'd like to do is put something in the constructor for "Person" so that if the generic is called, after it pulls the SQL data, it runs a check on the 'job' column and assigns the object to the subclass. So it would look something like:
class Person {

    public function __construct( $name ) {

        $info = get_from_sql( $name ); // function that returns this person's SQL row as an associative array

        if( ( get_class( $this ) == 'Person' ) && ( $info['job'] == 'Barber' ) ) {
            [[[something here that will change this 'Person' to subclass 'Barber']]]
        }

    }

}

class Artist extends Person {
}

class Barber extends Person {
}

Is there some way to assign this object to a subclass from the superclass constructor, so that if I call this...
$jeff = new Person( 'jeff' );

...and the 'job' DB column for row 'jeff' indicates that he's a Barber, the $jeff object has the type Barber rather than just the generic type Person?
(Please forgive me if there's some ridiculously easy way to do this... I'm largely self-taught, and I've searched around here and found only answers for Java and Python, neither of which help me...)
Comment: This question is answered here: http://stackoverflow.com/questions/6622214/how-to-return-subclass-from-constructor-in-php
Answer: There is no way to change a class type in its constructor, it's technically impossible. And if it was, it would be very confusing: you create a new Person and suddenly have got yourself a Barber!? What exactly should the semantics of that be?
Now, how to solve the problem itself:

The obvious answer is to try out the factory pattern, i.e. create a static method somewhere which would produce instances of Persons, Artists or Barbers depending on the circumstances. If you don't want to hardcode Barbers and Artists instantiation, you can use Reflection to instantiate the class dynamically basing on a variable containing the target type.
Personally, however, I'd go with a different approach and favor composition over inheritance, i.e. make Barber and Artist a Profession and inject it in Person's constructor, so that you can create new Person('jeff', new Barber()). This also improves separation of concerns: while Person has a name and age, a Barber might have, for instance, relevant skills.
Comment: `class Barber extends Person{}`|makes more sense
Comment: Thanks... given that, I think I'll have to go back to the drawing board on my overall class structure. I appreciate the help.
Answer: Does this work for you? [omissis]
edited after comments: this approach leads to nowhere, since you cannot change/get the context of the Person object from the context of a Barber object and viceversa. An interesting rewriting of the class could be the Factory pattern.
Comment: I just tried that... but unfortunately, it's not changing the class of the original object. The `create()` function does create a new Barber object, but the change doesn't make it back to `$this` in the original object; the object returned by `$jeff = new Person( 'jeff' );` from outside the Person class (and with Jeff in the DB as a Barber) is still of class 'Person', not class 'Barber'.
Comment: @JGinDC the problem is that there is no solution (afaik) with this approach. You should go for the factory pattern. :)


How can I show that this has a reflexive closure?

Question: Assume R is a relation on A.
Show that R ∪ ΔA is the reflexive closure of R.
What I thought is, that if R is an union with ΔA, it must mean that all a in A are (a,a).
But I don't know if this is good argument.
Comment: What is $\Delta A$?  Is it $\{(a,b)\in A\times A \mid a=b\}$?
Answer: The reflexive closure of $R$ is the smallest reflexive relation that contains $R$.  So your argument needs three parts:

$R\cup\Delta A$ contains $R$
$R\cup\Delta A$ is reflexive
If $S$ is a proper subset of $R\cup\Delta A$, then it fails (1) or (2).

Point 1 is trivial (it follows from basic properties of set union).  But you need to establish 2 and 3.
Item 3 states that $R\cup\Delta A$ is the smallest relation that satisfies (1) and (2), because it says that if $S$ is smaller than $R\cup\Delta A$, then it does not satisfy (1) and (2).  This is a crucial point.
The argument you stated in your post ("all $a$ in $A$ are $(a,a)$") does not make sense to me.
Comment: I have elaborated on what item 3 is about.
Comment: Thank you for the comment. Very helpful. My argument did not make any sense indeed (Hayden's comment is actually the appropriate one). However, I don't really understand point 3. But I will look into it! Thanks again.
Comment: Very nice of you! It is clear now! Thank you very much, I appreciate it!


Using Sphinx autodoc to document Flask app

Question: I am having problems in using Sphinx to generate documentation for a Flask app. Without going into specific details of the app its basic structure looks as follows.
__all__ = ['APP']

<python 2 imports>

<flask imports>

<custom imports>

APP = None # module-level variable to store the Flask app

<other module level variables>

# App initialisation
def init():
    global APP

    APP = Flask(__name__)

    <other initialisation code>

try:
    init()
except Exception as e:
    logger.exception(str(e))

@APP.route(os.path.join(<service base url>, <request action>), methods=["POST"])
<request action handler>

if __name__ == '__main__':
    init()
    APP.run(debug=True, host='0.0.0.0', port=5000)

I've installed Sphinx in a venv along with other packages needed for the web service, and the build folder is within a docs subfolder which looks like this
docs
├── Makefile
├── _build
├── _static
├── _templates
├── conf.py
├── index.rst
├── introduction.rst
└── make.bat

The conf.py was generated by running sphinx-quickstart and it contains the line
autodoc_mock_imports = [<external imports to ignore>]

to ensure that Sphinx will ignore the listed external imports. The index.rst is standard
.. myapp documentation master file, created by
   sphinx-quickstart on Fri Jun 16 12:35:40 2017.
   You can adapt this file completely to your liking, but it should at least
   contain the root `toctree` directive.

Welcome to myapp's documentation!
=============================================

.. toctree::
   :maxdepth: 2
   :caption: Contents:

   introduction

Indices and tables
==================

* :ref:`genindex`
* :ref:`modindex`
* :ref:`search`

and I've added an introduction.rst page to document the app members
===================
`myapp`
===================

Oasis Flask app that handles keys requests.

myapp.app
---------------------

.. automodule:: myapp.app
   :members:
   :undoc-members:

When I run make html in docs I am getting HTML output in the _build subfolder but I get the following warning
WARNING: /path/to/myapp/docs/introduction.rst:10: (WARNING/2) autodoc: failed to import module u'myapp.app'; the following exception was raised:
Traceback (most recent call last):
  File "/path/to/myapp/venv/lib/python2.7/site-packages/sphinx/ext/autodoc.py", line 657, in import_object
__import__(self.modname)
  File "/path/to/myapp/__init__.py", line 4, in <module>
from .app import APP
  File "/path/to/myapp/app.py", line 139, in <module>
@APP.route(os.path.join(<service base url>, <request action>), methods=['GET'])
  File "/path/to/myapp/venv/lib/python2.7/posixpath.py", line 70, in join
elif path == '' or path.endswith('/'):
AttributeError: 'NoneType' object has no attribute 'endswith'

and I am not seeing the documentation I am expecting to see for the app members like the request handler and the app init method.
I don't know what the problem is, any help would be appreciated.
Answer: Try using sphinx-apidoc to automatically generate Sphinx sources that, using the autodoc extension, document a whole package in the style of other automatic API documentation tools. You will need to add 'sphinx.ext.autodoc' to your list of Sphinx extensions in your conf.py, too.


for loop multiple variables

Question: I've two text files and I want to put each line from both files as output i.e.
#!/bin/bash
u=`cat newlist`
for i in $u
do
echo ""
echo ",'$i'"

for b in $( cat password )
do
echo ",'$b'"
done
done

Output should be
abc - from Users file 'line # 1'
123 - from password file 'line # 1'

Any help please
Comment: Do you want to print the 1st line from each file followed by the 2nd line from each and so on ?
Comment: Yes exactly. you got my point.
Answer: #!/bin/bash
exec 8<passwordfile
while read user
do
    read password <&8
    echo $user
    echo $password
done <usersfile

Comment: That's quite elegant.
Answer: paste
Also, BASH FAQ entry #1.
Comment: Also, that code snippet makes me want to gouge out my eyes.

for loop multiple variables


PHP Include and accents (They show up as �)

Question: I'm using PHP include to include a PHP file that has HTML in it. some of the content has french accents and these show up as � on the site. How can this be solved?
Thanks
Here is the PHP file I include:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<meta content="en-us" http-equiv="Content-Language" />
<title>Accueil</title>
<meta content="text/html; charset=utf-8" http-equiv="Content-Type" />
<meta content="Changement créativité rêve buts être centré Plénitude personnel                                                                  Développement transformation Modification nouveauté avancement bien-être                    Nouvelle vision ressentis L'énergie positive satisfaction l'acceptation Pardon" name="keywords" />
<link href="masterstyles.css" rel="stylesheet" type="text/css" />
<link href="menustyles.css" rel="stylesheet" type="text/css" />
<link href="menudropdown.css" rel="stylesheet" type="text/css" />

 ACTIVITÉS À VENIR…

        Inscrivez-vous à nos conférences et formations

 Example of some text that could be here

        ABONNEZ-VOUS…

 À notre liste d'envoi

    <form method="post" action="<?php echo $PHP_SELF;?>">
<?PHP
function process_info(){

     if(isset($_POST['email']))
 {

 $email=$_POST["email"];
   $email=strtolower($email);
    $action = "subc";

       // check if email exists

        // check whether email is correct (basic checking)
           $test1=strpos($email, "@");                                     //value must be >1
           $test2=strpos(substr($email,strpos($email,"@")), ".");          //value must be >1
           $test3=strlen($email);                                          //value must be >6
           $test4=substr_count ($email,"@");                               //value must be 1

 if ($test1<2 or $test2<2 or $test3<7 or $test4!=1)
             {

             print "
Il a une erreur avec vôtre email
";
             print "
Aucune informations ont été envoyer
";

             }
             else
             {
             print "
vôtre address est enregistrer, Merci
";

              //If they wanted to subsribe, do it...

             $file = "emaillist-666XXX.txt";

             // lets try to get the content of the file
if (file_exists($file)){
        // If the file is already in the server, its content is pasted to variable $file_content
        $file_content=file_get_contents($file);
}
else{
        // If the file does not exists, lets try to create it
        //   In case file can not be created (probably due to problems with directory permissions),
        //   the users is informed (the first user will be the webmaster, who must solve the problem).
        $cf = fopen($file, "w") or die("");
        fclose($cf);
}

// IF REQUEST HAS BEEN TO SUBSCRIBE FROM MAILING LIST, ADD EMAIL TO THE FILE
if ($action=="subc"){
        // check whether the email is already registered
        if(strpos($file_content,"<$email>")>0){die("");}
        // write the email to the list (append it to the file)
        $cf = fopen($file, "a");
        fputs($cf, "\n$email");       // new email is written to the file in a new line
        fclose($cf);

}
}
}
}

process_info();

?>

Votre Courriel

            <input name="email" type="text" class="style3" />
                    <input name="Submit" type="submit" value="OK" /></form>

                OUTILS GRATUIT…

Amusez-vous avec des outils intéressants

Answer: That happens if the browser thinks your using another encoding than you actually use.
try to add the following in your php file before any html is printed:
header ('Content-type: text/html; charset=utf-8');
// or
header ('Content-type: text/html; charset=iso8859-15');

and add
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />

<meta http-equiv="Content-Type" content="text/html; charset=ISO8859-15" />

between the  tags
UPDATE: just saw your update with the file. you need to add header ('Content-type: text/html; charset=utf-8');
Answer: I had the same issue with a website for a French hotel.
Change the charset to ISO-8859-1 instead of UTF-8 did the trick.
Example:
< form method="post" name="contact" action="send_mail.php" accept-charset="ISO-8859-1" >

Answer: What is the charset of the HTML page? It sounds like the charset of the PHP file and the HTML within it differ. You might want to check out:

http://www.w3.org/TR/REC-html40/charset.html
https://stackoverflow.com/search?q=html+charset

For more help, please post some code, specifically the doctype which is being output and any calls to PHP charset functions.
Answer: If switching the charset doesn't fix it, you can use entities. é for é, ô for ô and so on
P.S. 'Il a une erreur avec vôtre email' -> You should say 'Il y a', it's votre not vôtre and email can be translated to 'courriel' :)
Comment: Thanks, I'm not the one who did the writing, I just copy pasted what was given to me
Answer: Try using
<meta http-equiv="Content-Language" content="fr"/>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />


What's the best way to convert an arbitrary string into a readable dice roll result?

Question: I am quite new to python coding.
My code is written that only keeps character "0-9", "+", "-", "*", "/" and "d".
An example input would be  "3d6 + 4d3 + 3d2 - 433 seffesfes"
Which would resolve into "3d6+4d3+3d2-433". I was informed that using the eval() function is a bad idea, so I am not sure the best way to perform the final calculation would be.
I considered looping through the string until it finds something that isn't numeric, then going backwards to find the first half, then second half, then perform the function based on what it found - but this doesn't seem right.
Comment: have you tried a regex?
Comment: I think i wasn't clear, it uses  dice_input = re.sub('[^0-9d\+\-\*\/]', '', dice_input) already, I want to know how to convert "3d8" into random.randint(1, dice_faces) for each part of the string.
Comment: first explain what you mean with `3d8`, and what does `433` mean
Comment: "3d8" means roll 3 8-sided dice. Essentially, I want to convert "XdY" strings into just a number, then perform the calculation on the whole string, supporting the ability to add, subtract (such as subtract 433), etc.
Answer: Using regex, we can eliminate every character that doesn't match your accepted character list and strip your string:
import re

re.sub("[^\d+\-*\/d]", '', your_str)

Example:
import re

re.sub("[^\d+\-*\/d]", '', "3d6 + 4d3 + 3d2 - 433 seffesfes")
# >>> '3d6+4d3+3d2-433'

Regex explanation:
Match a single character not present in the list below [^\d+\-*\/d]:
    \d matches a digit (equal to [0-9])
    + matches the character + literally (case sensitive)
    \- matches the character - literally (case sensitive)
    * matches the character * literally (case sensitive)
    \/ matches the character / literally (case sensitive)
    d matches the character d literally (case sensitive)

You can learn more on regex (and play with that regex) here: https://regex101.com
EDIT:
After we have parsed your initial string, to do a proper evaluation of the random value, you should use re.sub:
import re
import random

def roll(match):
     a,b = match.group(1).split('d')
     return str(random.randint(int(a), int(a)*int(b)))

re.sub('(\d+d\d+)', roll, your_parsed_string)

Explanation:
re.sub is a function that receives a regex pattern to find in a given string and then replace it with an alternative value. but this function also supports a replace from a callback, which is the roll function that is passed to the re.sub.
the callback function receives as a parameter the re.Match object and as a result has access to all of its traits. one of those is the method group which let us access the groups that were parsed by our regex (regex groups are marked by () and let us access parts inside our captured regex easily).
So, we capture every appearance of a dice roll, send it to the callback function roll as a regex match, and then parse that stringed value to the "roll dice" that you desire to acheive.
For example:
your_parsed_string = '3d6+4d3+3d2-433'
re.sub('(\d+d\d+)', roll, your_parsed_string)
# >>> '8+9+2-433'

Now, to safely evaluate the final string, use something like: https://github.com/pydata/numexpr
Or - write a simple parsing function yourself
Comment: You don't need to escape `+`, `*` and `/`.
Comment: I think i wasn't clear, it uses dice_input = re.sub('[^0-9d\+\-*\/]', '', dice_input) already, I want to know how to convert "3d8" into random.randint(1, dice_faces) for each part of the string.
Comment: @VisioN It is not probably, it is, inside `[]` only `\` has special meaning and needs to be escaped. `]` if put as first character inside `[]` does not need an escape. `[^]]` should be valid
Comment: @LewisMcMeekin I'll edit my answer in 2 minutes with some more regex magic
Comment: @rioV8 There is no special meaning for these characters inside a character class.
Comment: @VisioN Bad formatting and not re-reading, only `\` has special meaning. `]` if put as first character inside `[]` does not need an escape. `[^]]` should be valid
Comment: Could you explain how this works? I don't want to just copy-paste it in without knowing.
Comment: @LewisMcMeekin I'll explain in the answer, one second
Comment: @LewisMcMeekin Updated my answer with an explanation, please give it a look again.
Comment: I have implemented the solution, but "3d6" has spat out a 2, which is impossible to throw on 3 dice, as the minimal result is 3. I assume return "str(random.randint(1, int(a)*int(b)))" should be return str(random.randint(1, int(b)) and a loop to add each amount.
To clarify, does this work on numbers greater than 1 character? For example does 34d56+4d3 pick up 34 and 56, then 4 and 3 separately?
Comment: @LewisMcMeekin Oops, fixed that - look at my answer now, in the implementation of roll, the first parameter given to random.randint is now `a` instead of `1` as this is the minimal number a roll of `a` dices could yield.
Comment: @LewisMcMeekin Also Yes, it would work for any number of dices and any number of faces as my regex pass `\d+` (which request any number between 0 to 9 and at least 1 repeat of that)
Comment: raise ValueError("non-integer arg 1 for randrange()")
ValueError: non-integer arg 1 for randrange()

This doesn't happen if you replace a with 1 from your previous version
Comment: @LewisMcMeekin fixed again, look at the original answer, I just had to parse a to int.
Comment: This has been exceptionally helpful. I think I can work out any further code from here. Many thanks.
Answer: You can use a replace function in the re.sub to convert your dice notation into numbers.
def convertDice(matchobj):
    faceCount = int(matchobj.group('faces'))
    return str(sum(random.randint(1, faceCount) for _ in int(matchobj.group('times')) ))

re.sub(r"(?P<times>\d+)d(?P<faces>\d+)", convertDice, your_str)

Now you have a string that can be evaluated
Comment: Could you explain how this works? I don't want to just copy-paste it in without knowing.


Setting Panels category for blocks and other pre-existing Content Types?

Question: When one adds new content to a Panel, they are given a list of categories, each with various Content Types.
Setting the aforementioned category of a Content Type is easy if you're writing your own plugin...
<code>$plugin = array(
  'title' => t('My Plugin'),
  'category' => t('YOUR CATEGORY HERE'),
);
</code>
But what about setting that category for Content Types created by other modules?
I ask because I've created a Menu Block and am wanting to put it in a specific category, where all my other custom CTools Panels Content Type plugins reside.
Any thoughts? I'm using D7, by the way. Thanks!
Answer: A kinda hacky way of doing it is to hook into hook_ctools_block_info() like so:
<code>/**
 * Implements hook_ctools_block_info().
 *
 * @see ctools_block_content_type_content_types().
 */
function menu_block_ctools_block_info($module, $delta, &$info) {
  if ($info['title'] == 'Sub Menu Menu Block') {
      $info['icon'] = 'icon_core_block_menu.png';
      $info['category'] = t('Page Content');
  }
}
</code>
I just dropped this code in a separate module and I'm off to the races. The only problem is if Menu Block decides to implement its own hook_ctools_block_info function (Indeed, I got the above code from a patch that does exactly that), in which case redeclaration errors will show up. I'll leave this question marked as unanswered for the moment; if anyone can think of a better way of accomplishing the above, I'd be happy to accept that answer instead.


The best way to store graph into the memory

Question: The problem is that I have 150 000+ nodes with 200 000+ (may vary up to 1 000 000 or even more) all of them are written to a DB.
Now I'd like to create a normal graph which will open access to routing. So, I need to compose it using data from existing DB.
The idea is to build this huge graph, divide it into small pieces and write to DB BLOBS for storing.  I tried to build it recursively but it seems to me that stack could't store so much data and all the time my algorithm breaks with allocation error. So, now I'm a bit confused with a way which will allow me to build this graph. I'm thinking about some kind of iterative method, but the main problem is architecture, I mean structures which I'm going to use for storing nodes and arcs.
As I see this solution it should be smith like that:
struct Graph
{
    unsigned int nodesAmount;
    unsigned int arcsAmount;
    vector<Node*> NodeArr; //Some kind of container to store all existing Nodes
}

struct Node
{
    unsigned int id;
    int dimension; //how many arcs use this node
    vector<Arcs*> ArcArr;
}

struct Arcs
{
    unsigned int id;
    double cost;
    Node* Node_from;
    Node* Node_to;
}

I read lots of articles about method of storing graphs, but didn't find really good solution for such huge graphs.
I would be very pleased for any ideas. Thank you
Comment: Food for thought: instead of using a linked list, you could maybe use a (sparse?) array or matrix. Every node would have an id (unsigned integer) and the matrix could be a ` matrix `. This matrix would represent the adjacency matrix: True would indicate that there is an arc going from node x to node y.
Comment: That's where the sparse matrix comes in place. It only stores the non-zero values. By the way Danstahr's answer is better considerating space usage.
Comment: @ibizaman actually I was thinking about using matrix but it seems to be huge and has a lot of zeros. That's why I'm looking for another way
Answer: You are on the right path.
Some small changes that I would suggest:
struct Graph
{
    unsigned int nodesAmount;
    unsigned int arcsAmount;
    vector<Node> NodeArr; // Store the nodes directly, not pointers
}

struct Node
{
    unsigned int id;
    int dimension; //how many arcs use this node
    vector<int> Neighbours; // store neighbour IDs, saves memory
}

Since you are moving between database and C I would strongly suggest not to use pointers because those do not translate. Use IDs and look up your nodes by ID. If you need to store the edges separately then also do this by ID, not by pointer.
Comment: @tema.krukovets then make it a `struct { int neighbourID; double cost;}`
Comment: @Segey-l Sounds good, but I'm going to realize routing throw this graph so I need somehow store costs of each arc.
Answer: I know that this solution has nothing to do with your snippet, but i'd like to show you another way.
The option that's used quite often is to have two arrays - one for the edges, one for the vertices.
The vertices array points to the edges array and says where the adjacent vertices start. The edges array stores the adjacent vertices itself.
For instance :
V = 6, E = 7

vertices = [0, 1, 1, 2, 5, 6]
edges = [1, 2, 3, 4, 5, 6, 0]

Considering the indexes, the edges array would look like :
| [1] | [] | [2] | [3, 4, 5] | [6] | [0] |

So the first vertex has a single adjacent vertex (with id 1), the fifth vertex has 3 adjacent vertices with IDs 3, 4, 5 etc.


all sites are down after switching IIS6 in 32bit mode

Question: I;ve recently switched IIS6 to 32 bit mode and none of my sites (framework 2.0 and 4.0 ) are running now. it says "Service Unavailable"
Here is what I've done:
followed the steps from : http://support.microsoft.com/kb/934162

Any help?
Answer:
(1) Convert the 64bit w2k3 to 32 using above article.
(2) aspnet_regiis -i for .net 2.0 and 4.0 both
(3) restart
(4) you will notice website properties in IIS will not have ASP.NET TAB
(5) download iis6 utility to change .net framework version
(6) configure reporting server and set the websites for the same to asp.net 2.0
(7) all is done well and working fine
Comment: How did you do the switch? What did you do to fix it? Right now this is too broad.
Answer: Do you have an ISAPI Filter or other module that references a 64-bit DLL?  That's the most likely cause.  Try pulling out all of your filters and handlers to get a good test page.  You can also create a new app pool and create a simple 'hello world' page to confirm that it's not something at the server level.  Then start adding back parts until you narrow down the cause.
If you haven't already, check Event Viewer for clues too.


set attachment size limit in outlook with a domain policy

Question: Is there a way to add a domain policy to a Windows 2008 domain that sets the attachments size limit for Outlook (various versions) and Windows Mail?
Answer: You're really better off doing this on your SMTP server, because it's not client-dependent.
The maximum message size in Outlook 2010 can be controlled with registry modification even for non-Exchange clients that are just using SMTP to deliver messages. Outlook 2007 and older versions do not have this functionality and rely totally on Exchange's size limiting functionality for their own limits.
I'm not aware of any attachment limiting size functionality in Windows Mail. Being that it's a home-user oriented product it really doesn't surprise me that there wouldn't be any such limit. Typically an ISP's mail server would provide the limiting functionality for home users.
Comment: @ValerioSantinelli - The only other reasonable solution would be to put an on-site SMTP server in place, configured to smart-host to the ISP. You could, at least, stop large attachments before they hit the Internet.
Comment: Thanks Evan. The remote SMTP already does this kind of check, but there's a problem because no one is stopping clients from sending 300+Mb attachments before they get rejected and with the poor internet connection of this customer it's a problem. Of course teling people not to send big attachments isn't of any help as they just keep doing it all the time.
Answer: As best practice, you should be doing this on Exchange but i agree why waste time uploading (especially with limited bandwidth) to a hosted SMTP server when it will be rejected anyway.
Open the registry editor and browse to:
Outlook 2013:

HKEY_CURRENT_USER\Software\Microsoft\Office\15.0\Outlook\Preferences

Outlook 2010:

HKEY_CURRENT_USER\Software\Microsoft\Office\14.0\Outlook\Preferences

Then add a new DWORD value: MaximumAttachmentSize
Unlimited message size uses a value of 0. For a specific message size (recommended) enter the value in Kb.
Answer: This is configured on your MS Exchange server, not via GPOs.
Setting Message Size Limits in Exchange 2010 and Exchange 2007. It has been already asked here.
Comment: What mail server do you use then?  This is a setting present on most mail serrvers.
Comment: We haven't got an Exchange server, it's just a Windows Domain. Is it possible **only** with Exchange?
Comment: That domain isn't using an in-house mail server. All of the clients talk directly to the remote SMTP server which is managed by an ISP.


Excessive server I/O rate is a symptom of excessive memory usage?

Question: I'm learning to manage a VPS LAMP server.  I noticed that whenever Apache consumes more RAM than is allotted, the server disk I/O rate jumps from a negligible value to a big value like 3k/hour.
Why is this so?  What exactly is happening?
Thanks
Answer: I would have to guess that this is because you have a swapfile/partition setup and the system is swapping.


Prime ideals of a quotient ring.

Question: I  want to prove that
If R  is any ring  and  I be an ideal, then an ideal P containing I is a prime ideal of R   iff   P/I is prime ideal of R /I.
Could you check my proof ?
Proof:  Let P be a prime ideal  .   To prove first P/I is prime ideal of  R/I. Let $ (a+I), (b+I) \in R/I$  such that
$(a+I)( b+I) \in P/I$. Then  $ab+I \in P/I$. It implies  $ab \in P$.
As P is prime,  $a \in P$ or $b \in P \implies a +I \in P/I$ or $b+I\in P/I$
Hence $P/I$ is prime.
Conversely,  let $P/I$ be a prime ideal of $R/I$. let us prove that $P$ is prime ideal of  $R$ .     Let $a,b \in R$ such that  $ab \in P$ then
  $ab+I \in P/I \implies ( a+I)(b+I) \in P/I$.
As  $P/I$ is prime, $a+I \in P/I$  or $b+I \in P/I \implies  a \in P$ or $b \in P$ .
Comment: Sounds correct. Instead of a two-part proof, you could think of  equivalence statements.
Answer: Here is the standard way of proving this: By some of these isomorphism theorems, we have $(R/I)/(P/I) \cong R/P$. This immediately gives you all you need.
Comment: Usually, it's called the third isomorphism theorem.

Prime ideals of a quotient ring.


Centos - /var/log/secure records nothing

Question: I have accidentally remove /var/log/secure, I try to recreate it but it still stays blank after several connections.
On a server where everything works, with ls -l I have:
<code>-rw-------. root:root /var/log/secure
</code>
and on a server where it does not work, with ls -l I have:
<code>-rw------- root:root /var/log/secure
</code>
The only difference is in the rights with the "."  at the end of the line, that's missing on the server where it does not work.
Any idea ?
Comment: Did you restart the `rsyslog` service?
Answer: So the issue is your syslog process still has the deleted file open. You need to restart your syslog process. By default that is rsyslog in centos
<code> service rsyslog restart
</code>
I'm sure you can see it opened as deleted also if you try something like
<code> lsof | grep '/var/log/secure'
</code>
That will give you the pid/process name of what is holding it open. For example
<code>[firstname.lastname@example.com ~]#  lsof | grep '/var/log/secure'
rsyslogd    977       root    5w      REG              253,0   585555    2756243 /var/log/secure
</code>
So the rsyslogd process is holding it open
<code>[firstname.lastname@example.com ~]# ps aux | grep 977
root       977  0.0  0.0 249856  5916 ?        Sl    2014   8:25 /sbin/rsyslogd -i /var/run/syslogd.pid -
</code>
Comment: Even better would be to **not** start by restarting rsyslog! Since the file is being kept open, /var/log/secure is not deleted yet and you can easily recover that file. Run the lsof command and then use the open file descriptor to recover the accidentally deleted file. Using the PID number (977) and file-descriptor number (5) from your example: `cp /proc/977/fd/5 /var/log/secure.bak`


JSX Element type 'void' is not a constructor function for JSX elements

Question: What am I doing wrong here?
It doesn't like the way I am calling Items
import React, { Component } from 'react';
import { Link } from "react-router-dom";

interface LinkedItemProps {
    icon: string;
    title: string;
}

export const Items = ({icon, title}: LinkedItemProps) => {

            {icon}

            {title}

}

export default class LinkedItems extends React.Component<any, any> {
    render() {
        return (
            <Link
                to={this.props.link}
                title={this.props.title}
                onClick={this.props.afterClick}
            >
                <Items icon={this.props.icon} title={this.props.title} /> //error
            </Link>
    )}
}

P.S. Thank you Shubham Khatri for marking this as a duplicate of a question that does not remotely resemble what I asked.
Comment: Probably not related to your current error, but you've misspelled `title` as `tilte` at the end of your code.
Comment: sure... and you asked me earlier `"What is the error that you receive"`. Read the title, please lol
Comment: @MayankShukla, That's fine. I got the answer that I was looking for. I was a bit pissed that someone marked a duplicate when it is not. Anyways, thanks :)
Comment: What is the error that you receive
Comment: @Hafiz, What do you mean by your comment, the Duplicate question has had the same issue
Comment: @HafizTemuri, i can reopen your ques but it will be better to use flag 'reopen' and ask people to reopen your ques :)
Answer: Items is an arrow function with {} which means you have to explicitly give it a return statement:
export const Items = ({icon, title}: LinkedItemProps) => {
  return ( // <------ must return here

        {icon}

        {title}

  )
}

If you do not, then the Items just returns undefined which is an empty value and thus
JSX Element type 'void' is not a constructor function for JSX elements"

For a bit cleaner code, you can replace the {} with () completely:
export const Items = ({icon, title}: LinkedItemProps) => (

      {icon}

      {title}

)

Comment: You are right... `{ }` were the culprit. Thanks :)


How to combine short term and long term time series?

Question: I need to combine two traffic data series which are long term ( with 15 S / 30 S/1 minute interval) and short term( with 2 S/ 3 s) for my research purpose. These two types of data series reflect different traffic dynamics.
What would be the best way to do it/ what would be the most suitable technique?
Comment: Why do the series need to be combined at all?
Answer: Try the MIDAS (mixed data sampling) approach. It is intended for situations such as yours.
Software implementation is available in R (package midasr), Matlab (users guide) and perhaps other statistical packages.


i need to access user info which are initially store in redux store when logged in.. How can i do that? React-redux

Question: authReducer.js
import {
  LOGIN_SUCCESS,
  LOGIN_FAIL,
  REGISTER_SUCCESS,
  REGISTER_FAIL
} from '../Actions/types';

export default (state = { isLoading: true, user: [] }, action) => {
  switch(action.type){
    case LOGIN_SUCCESS:
      localStorage.setItem('token',action.payload.token);
      return {
        ...state,
        user: action.payload.data,
      }

    case LOGIN_FAIL:
      return state;
    case REGISTER_SUCCESS:
      return {
        ...state,
        user: action.payload.data,
      }
    case REGISTER_FAIL:
      return state;
    default:
      return state;
  }
}

profile.js
import React from 'react'
import {  useSelector} from 'react-redux'

export const EditProfile = () => {

   const data = useSelector((state) => state.user);
  return (

      {data}

  )
}

index.js (rootReducer)
import { combineReducers } from 'redux';
import authReducer from './authReducer';

export default combineReducers({
  auth: authReducer,
})

store.js
import {createStore, applyMiddleware, compose } from 'redux';
import thunk from 'redux-thunk';
import rootReducer from './Reducers';

const initialState = {};
const middleware = [thunk];

const store = createStore(rootReducer,initialState,compose(
    applyMiddleware(...middleware),
    window.__REDUX_DEVTOOLS_EXTENSION__ && window.__REDUX_DEVTOOLS_EXTENSION__()
));

export default store;

So Here when i logged in the details were on user object so i need to access then in profile.js so that i can display the details of the user
I don't how can i access i need to save the user data which are stored in user (redux store).
I don't know what i am missing any help will be grateful
Comment: you named `authReducer` as `auth` in rootReducer so you'll be able to access the user data by `useSelector(state => state.auth.user`
Comment: what is the actual problem? it is not clear what the problem is.... are you getting an error?
Comment: can you also post the rootReducer?
if the user is the reducer name then user.user will get you the data
Comment: Edit my post now please check @Shahzaib
Answer: I don't know how you setup your redux.
This is how I usually set them up:-
A. Reducer

/slices/auth.js

import { createSlice } from '@reduxjs/toolkit'

const initialState = {
  user: [],
  isLoading: false
}

export const authSlice = createSlice({
  name: 'auth',
  initialState,
  // // The `reducers` field lets us define reducers and generate associated actions
  reducers: {
    setUser: (state, action) => {
      // Redux Toolkit allows us to write "mutating" logic in reducers. It
      // doesn't actually mutate the state because it uses the Immer library,
      // which detects changes to a "draft state" and produces a brand new
      // immutable state based off those changes
      state.user = action.payload
    },
    setLoading: (state, action) => {
      state.loading = action.payload
    }
  }
})

export const { setUser, setLoading } = authSlice.actions;

// The function below is called a selector and allows us to select a value from
// the state. Selectors can also be defined inline where they're used instead of
// in the slice file. For example: `useSelector((state: RootState) => state.counter.value)`
export const selectUser = (state) => state.auth.user
export const selectLoading = (state) => state.auth.isLoading

export default authSlice.reducer;

B. Store

store.js

import { configureStore, getDefaultMiddleware } from '@reduxjs/toolkit'
import authReducer from '../slices/auth'

export const store = configureStore({
  reducer: {
    auth: authReducer
  },
  middleware: getDefaultMiddleware({
    serializableCheck: false
  })
})

C. App Component
import { Provider } from 'react-redux'
import { store } from '../app/store'

export default function App() {
  return {
    <>
      <Provider store={store}>
        {/* your content... */}
      </Provider>
    </>
  }
}

D. Component (where you use the redux)
import { useContext } from 'react'
import { useDispatch, useSelector } from 'react-redux'
import { selectUser } from '../slices/auth'

export default function EditProfile() {
  const dispatch = useDispatch()
  const user = useSelector(selectUser)

  return {
    <>
      {user}
    </>
  }
}


C or D scales for x15 notes tongue drum?

Question: I am hoping to get a 15notes tongue drum but need advise on which one to get. Some sites advertised as having C scales and other D scales and I don't know which one to get. Appreciate advice.
Comment: To get the best answer(s), please edit your question to describe how you plan to use the drum.
Comment: I am just a beginner. Haven't played a tongue drum before. Hence seeking an advice before I bought it as it's not a cheap instrument.
Answer: Playing it totally in isolation, it won't make much difference. If you want to play with others, it'll help if they're all in the same key.
Comment: Thank you Tim, what key is most commonly played?
Comment: 50:50 on that one! But for beginners there's a lot more music in key C. Best ask the supplier.
Comment: Thank you Tim, that's a great help.  You have helped me decide on which one to get....


Show that if $\frac{x_i}{y_i}<t$ for all $i \leq n$, then $\frac{\sum_{k=0}^{n}x_i}{\sum_{k=0}^{n}y_i}<t$

Question: How to show that if $\frac{x_i}{y_i}<t$ and $x_i,y_i>0$ for all $i \leq n$ , then $$\dfrac{\sum\limits_{k=0}^{n}x_i}{\sum\limits_{k=0}^{n}y_i}<t?$$
I tried the following

If $\frac{x_i}{y_i}<t$ for all $i \leq n$, then $$\dfrac{\sum\limits_{k=0}^{n}x_i}{\sum\limits_{k=0}^{n}y_i} \leq \dfrac{n\max|x_i|}{n\max|y_i|}<t.$$

But that's obiviously incorrect, since we would have the last inequality for sure if $\max|x_i|$ was in the pair with $\max|y_i|$.
Comment: Are there positivity constraints on the $y_i$?
Comment: $$\sum_{i=0}^n x_i < \sum_{i=0}^n ty_i$$
Comment: Have you a condition like $x_i,y_i \geqslant 0$?
Comment: Yes, sorry for not elaborating.
Answer: We have $x_i<ty_i$ for each $i$, so
$$
\frac{\sum_i x_i}{\sum_i y_i} < \frac{\sum_i t y_i}{\sum_i y_i} = t.
$$
(This assumes $t>0$.)
Answer: In general for rational numbers $\frac{a}{b}$ and $\frac{c}{d}$ with a,b,c,d positive and  $\frac{a}{b} < \frac{c}{d}$ we have $\frac{a}{b}$ < $\frac{a+c}{b+d}$ < $\frac{c}{d}$
To see this for one side of the inequality $$\frac{a}{b} <\frac{c}{d}$$
$$da < bc$$
$$ da + cd < bc + cd$$
$$d(a+c) < c(b+d)$$
$$\frac{a+c}{b+d} < \frac{c}{d}$$
Now your problem follows because your sum is less than the largest value for $\frac{x_i}{y_i}$ which is less than t.


What does it mean when a chord in the bass-clef bar is marked with a treble clef and what is the extent of applying that notation.This is piano music

Question: There is a treble clef next to a chord in the bass-clef bar near the end of a piece of music I'm trying to learn.  I don't know how to interpret it.  Should I play just this one chord as if it were on a treble-clef staff?  All notes in that measure? All notes for left hand (piano music) until the end of the piece?  This notation has me baffled.  I have not been able to find a similar example or question online.  I hope someone can help.
Comment: Hi, welcome to MP&T! I would suggest an image of what is exactly puzzling you. As described, it seems that this should be played as if it were on the treble clef but hard to know for sure!
Comment: If you can't for whatever reason post an image, tell us the name of the piece.
Answer: The treble clef persists until cancelled by a bass clef.  You say your example happens 'near the end' of a piece.  So quite likely the treble clef continues to the end.
Though the upper stave conventionally gets a treble clef, the lower a bass clef, this is by no means inevitable and temporary changes are commonplace.  It happens three times in the first couple of lines of this sonata!  The lower stave starts conventionally in bass clef, changes to treble for just three notes,  then back to bass.  See?


How to stop cron job after job is done programmatically

Question: I am creating an app using magento 2 where user is supposed to upload csv file containing:

Name of base image
Name of clipart
height
Width
top margin
left margin

using above data I am suppose to combine both the images.
I am using cronjob to finish up this task, like as soon as user clicks on generate images first I am inserting all data into database and then using cron job, combining all the images after each minute.
The problem is cron job is still inserting data even after it has finished combining images. I want to stop cron job as soon as it finishes the task.
can I run cron job based on some condition or something?
Answer: The cron job always run by a schedule, so you have to add your condition within your code. Something like this:
if($this->isCombined()){
   return false;
}

Cheers
Comment: can u please explain it in details?
like will this block stop cron from executing? my question is cron should not run in background once task is finished i.e. it should not create any entries in database after that.


php - display links to related content

Question: I am looking to implement a 'youtube related videos' style related content system.
I have 5 tags/keywords for each of my pages, a title and a description. I would like to display links to the two most similar pages.
I am guessing a mysql query based around order by relevance.
many thanks.
Answer: you can break up the title, description, keywords into tokens and then do a full text search in mysql on those keywords and order by relevance.
<code>select * from article where match(title, description, keywords)
  against ('word1 word2 word3 word4' in boolean mode)
  order by relevance desc
</code>
http://dev.mysql.com/doc/refman/5.0/en/fulltext-boolean.html
Answer: First, the keywords should be indexed so that it can be accessed faster.
Then you can do a fulltext search: http://en.wikipedia.org/wiki/Full_text_search
Or, you could do a LIKE query: http://www.w3schools.com/SQL/sql_like.asp
Then, with those results, you just make the list of the related items.
Comment: so I should store the keywords in separate columns?
Comment: If you store them in seperate columns, the database would be slower and you would be able to use a LIKE query. If you use a just one column, you can use full text searches. Another solution is have individual rows for each keyword and this will be a faster method and easier to implement but it might be slower (this is what I would do).

php - display links to related content


UI.selectmenu from jQuery is not imported!

Question: I have this function to add libraries from jQuery UI, but the selectmen, and tooltip seems to be missing! anyone know how to import them in Drupal 7.4?
function kalender_init() {
    $lib= array(
        'drupal.ajax', 'drupal.form',
        'drupal.autocomplete',
        'jquery', 'ui','ui.selectable',
        'ui.droppable','ui.draggable',
        'ui.sortable','ui.resizable',
        'ui.tabs','ui.dialog',
        'ui.datepicker','ui.autocomplete',
        'ui.button', 'ui.buttonset',
        'ui.selectmenu', 'ui.tooltip',
        'form'
    );
    foreach($lib as $l){
        drupal_add_library('system', $l);
    }
}

I need for the form over here:
foreach($result as $color){
    array_push($colors, $color->name);
}
foreach($colors as $color => $id){
    array_push($attr, array('class' => array('colors-list'), 'data-color' => $color) );
}
$form['gruppen']['checkbox'][$group->id]['color'] = array(
    '#type' => 'select',
    '#suffix' => '

',
    '#default_value' => 0,
    '#options' => $colors,
    '#options_attributes' => $attr,
);

Comment: You can check the list of core jQuery UI library from `system_library()` in system.module
Comment: Where? how? I see in the folder misc/ui/ that there is no tooltip and no selectmenu, you are able to display structured information about librarys?? @JimmyKo
Comment: @JimmyKo just to look inside the system.module? or to debug with the system_librark()?
Comment: You don't need to debug with `system_library()`. I just provide you the location where the core library register to support the using of `drupal_add_library()`
Answer: Selectmenu Widget is added in jQuery UI 1.11, which is not supported by core and also jquery_update module. There is an issue on Drupal.org.
Tabs Widget is added since jQuery UI 1.9, you can have it if you installed latest version of jquery_update module with proper configuration.
Comment: So i am force to use $form['#attached']['js']? Found it here: https://www.drupal.org/node/304255
Comment: You can try to add the latest jQuery UI with $form['#attached']['js'], but I don't know if it can work perfectly in Drupal anyway.


Pythonic way of slicing 2-d numpy arrays into smaller squares

Question: I am trying to handle a RAW image using numpy.
Printing the raw image numpy array returns this:
[[372 387 247 ... 560 359 364]
 [380 392 243 ... 599 342 356]
 [236 238 358 ... 355 600 564]
 ...
 [547 553 344 ...  74  69  69]
 [349 328 560 ...  68  74  73]
 [341 334 537 ...  70  71  73]]

with shape 4384, 5632.
I want to obtain a list of lists (2D list), such that each entry will correspond to a 8 * 8 square of the 2d numpy array.
This would indicate a list of dimensions 4384/8 , 5632/8.
I can only think of using while loops and appending each square into the list at the moment, but I was thinking there must be a better way.
Is there a more pythonic way of doing it, maybe using list comprehension and slicing?
Comment: Please try below code:

rawimg.reshape(rawimg.shape[0]//8, 8, -1, 8).swapaxes(1,2).reshape(-1, 8, 8)
Comment: Please try below to see whether it give you the desired result.

rawimg.reshape(-1,8,8)
Comment: `print(rawimg.reshape([-1,8,8])[0])` gives different results from `print(rawimg[0][0:8])` and `print(rawimg[1][0:8])`, where the first two lines of the first statement should look the same as the results of the latter :( Unless I'm doing something wrong.
Comment: Oh wow, that works like a charm. Can you explain how that works? I'd like to accept it as an answer.
Answer: Please find below a short explanation of the answer
# 1.  Reshape Image as (height/8, 8, width/8,8)
print(rawimg.reshape(rawimg.shape[0]//8, 8, -1, 8).shape)
# 2. Swap 1 and 2nd index
print(rawimg.reshape(rawimg.shape[0]//8, 8, -1, 8).swapaxes(1,2).shape)
# 3. Reshape again (-1,8,8) with -1 being combined both (548*704) arrays of shape 8x8
print(rawimg.reshape(rawimg.shape[0]//8, 8, -1, 8).swapaxes(1,2).reshape(-1,8,8).shape)

(548, 8, 704, 8)
(548, 704, 8, 8)
(385792, 8, 8)

Comment: Actually, I wanted the result to be a 2d list of 8x8 array as well. So I think step two can be the final! Thanks anyway for the solution :)


Testar factory hibernate

Question: Está dando null exception na linha HibernateUtil.getFactory().openSession(); no método main.
Seguem como estão os arquivos de configuração e teste:
  <?xml version='1.0' encoding='utf-8'?>
  <!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"    "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">

  <hibernate-configuration>

    <session-factory>

        <property name="connection.driver_class">com.mysql.jdbc.Driver</property>
        <property name="connection.url">jdbc:mysql://127.0.0.1:3306/pessoa</property>
        <property name="connection.username">root</property>
        <property name="connection.password"></property>

        <property name="connection.pool_size">1</property>

        <property name="dialect">org.hibernate.dialect.MySQL5InnoDBDialect</property>

  <property name="current_session_context_class">thread</property>

  <property name="cache.provider_class">org.hibernate.cache.internal.NoCacheProvider</property>

        <property name="show_sql">false</property>

  <property name="hbm2ddl.auto">validate</property>

    </session-factory>

</hibernate-configuration>

hibernate.cfg.xml:
A classe de conexão (factory):
package util;

import org.hibernate.SessionFactory;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;

public class HibernateUtil {

private static SessionFactory factory;
private static Configuration configuration;

public static SessionFactory initialize() {
try {
configuration=new Configuration().configure();

ServiceRegistry registro= new StandardServiceRegistryBuilder().applySettings(configuration.getProperties()).build();

factory=configuration.buildSessionFactory(registro);

System.out.println(">> HIBERNATE INICIADO COM SUCESSO.");
}

catch (Throwable e) {
System.out.println(">> FALHA NA INICIAÇÃO DO HIBERNATE.");
e.printStackTrace();
}

return factory;
}

public static SessionFactory getFactory() {
return factory;
}

}

A classe de teste:
package util;

import org.hibernate.SessionFactory;

public class HibernateUtilTest {

public static void main(String args[]) {
HibernateUtil.getFactory().openSession();
}

}

Comment: Você já criou o banco "pessoa" no MySQL?
Comment: @Rafael Blum o banco está criado, já testei com jdbc, sem maven e funcionou.
Answer: Da maneira que você esta usando HibernateUtil.getFactory() vai retornar null, tente iniciar a variável factory no método getFactory().
package util;

import org.hibernate.SessionFactory;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;

public class HibernateUtil {

    private static SessionFactory factory;
    private static Configuration configuration;

    public static SessionFactory initialize() {
        try {
            configuration=new Configuration().configure();

            ServiceRegistry registro= new StandardServiceRegistryBuilder().applySettings(configuration.getProperties()).build();

            factory=configuration.buildSessionFactory(registro);

            System.out.println(">> HIBERNATE INICIADO COM SUCESSO.");
        }catch (Throwable e) {
            System.out.println(">> FALHA NA INICIAÇÃO DO HIBERNATE.");
            e.printStackTrace();
        }

        return factory;
    }

    public static SessionFactory getFactory() {
        id(factory == null)//verificar se a variável já foi instanciada
            initialize();//inicia a variável caso seja null
        return factory;
    }

}

Testar factory hibernate


What is the meaning of "without referring back to the ambient space $R^3$ where the surface lies"?

Question: I'm reading Do Carmo's Differential Geometry book, here:

What is the meaning of "without referring back to the ambient space $R^3$ where the surface lies"? Does it mean that we can compute it directly without appealing to some inverse mapping? If so, why don't we need to refer back?
This concerns me because it seems that there are situations where we need to refer back to the ambient space and situations where we don't and up to now, It's not clear where we need it and where we don't, I just accepted the definitions and constructions without deeper thought because I still can't.
This gives me a lot of curiosity, for example: In a definition I mentioned in a previous question:

I noticed that this is defined referring back to a map between open sets in $R^2.$ Can we make this definition without this?
Answer: tl; dr: It's arguably impossible to answer a philosophical question about definitions, but if this question came up during a chat over beverages, I'd say

We know how to do calculus on (non-empty open subsets of) Cartesian spaces.
The definition of a smooth manifold uses this knowledge to extend the concept of smoothness.
We know how to use calculus to measure arc length, area, and so forth, in a manifold embedded in a Euclidean space.
A certain amount of ambient Euclidean structure can be restricted to an embedded manifold, and then viewed as data intrinsic to the manifold, separately from a particular embedding.

Regarding point 2., we use coordinate charts (or parametrizations, their mapping inverses) to transfer questions about functions and mappings on manifolds to questions about functions and mappings on Cartesian space. In order for the concepts such as smoothness to be well-defined (independent of chart) we impose a compatibility condition between parametrizations $\mathbf{x}_{1}$ and $\mathbf{x}_{2}$ amounting to smoothness of $\mathbf{x}_{2}^{-1} \circ \mathbf{x}_{1}$.
For point 4., thinking specifically of surfaces in Euclidean three-space, a parametrization induces three functions $E$, $F$, and $G$ defined in a coordinate neighborhood (open subset of the plane). These suffice to specify the lengths of tangent vectors, the angle between two non-zero tangent vectors at a point, the arc length of a piecewise-smooth path, and the area of a region of surface. These functions and their derivatives also suffice to define geodesics, paths in the surface of locally shortest length. Remarkably (Gauss's Theorema Egregium) these functions and their derivatives also detect whether or not a surface is locally isometric to the Euclidean plane in the sense that small geodesic triangles have total interior angle $\pi$. Our ability to define and measure these quantities using functions of two variables defined in a coordinate neighborhood is what do Carmo means by "without referring back to the ambient space." Analogously, general relativity allows us to conceptualize and work with the geometry of spacetime without imagining our universe embedded in a higher-dimensional space.
By contrast, a parametrization, particularly an embedding of a surface in Euclidean three-space, also induces components $e$, $f$, $g$ (or $\ell$, $m$, $n$ depending on the author) of a second fundamental form. Loosely, these functions measure how the surface bends in the ambient space, or more precisely, how a continuous unit normal field varies in coordinates. Because a unit normal field "does not lie in the surface," geometers think of the second fundamental form as "extrinsic" geometry that does refer to the ambient space.
Answer: They key difference between your two examples is the dimension of the space. The manifold is a 2-dimensional surface in both cases. In the first case this surface is embedded into the 3-dimensional space $\mathbb{R}^3$.
In the second case you consider the parametrizations which map [parts of] the 2-dimensional space $\mathbb{R}^2$ to [parts of] the surface. On these parts the parametrization maps or charts are bijections.


How to correct/center GridLayout using standard Java layout managers?

Question: The below code represents the problem. Since I have heights of the north and south panels set the rest of it goes to the center panel using GridLayout. I think that since it cannot share the leftover pixels equally among its rows it just leaves them. Therefore in the below code we have ugly white line over south panel.
My question here is: How to make sure that when the GridLayout is not taking the whole space it is at least centered?
Normally I would use TableLayout and situation is sorted, but since I was writing an answer I wanted to use only standard managers. Knowing this would be very useful for me thanks in advance.
Example:
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.GridLayout;
import javax.swing.BorderFactory;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;

public class AligningButonsTest
{
    public static void main(String[] args)
    {
        SwingUtilities.invokeLater(new Runnable()
        {
            @Override
            public void run()
            {
                JFrame f = new JFrame();
                f.setSize(800, 600);
                double CONSTANT_FACTOR = .1;
                int noOfRows = 5;
                JPanel centerP = new JPanel(new GridLayout(noOfRows,1));

                for(int i = 0; i < noOfRows; i++)
                {
                    BoxPanel bP = new BoxPanel();
                    centerP.add(bP);
                }
                JPanel contentPane = new JPanel(new BorderLayout());
                f.setContentPane(contentPane);
                contentPane.add(centerP, BorderLayout.CENTER);
                JPanel southP = new JPanel();
                southP.setBackground(Color.RED.darker());//southP.setOpaque(false);
                southP.setPreferredSize(new Dimension(1, (int)(CONSTANT_FACTOR* f.getHeight())));
                contentPane.add(southP, BorderLayout.SOUTH);
                JPanel northP = new JPanel();
                northP.setBackground(Color.RED.darker());//northP.setOpaque(false);
                northP.setPreferredSize(new Dimension(1, (int)(CONSTANT_FACTOR* f.getHeight())));
                contentPane.add(northP, BorderLayout.NORTH);
                f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                f.setVisible(true);
            }
        });
    }
}

class BoxPanel extends JPanel
{
    public BoxPanel()
    {
        setBorder(BorderFactory.createMatteBorder(1, 0, 1, 0, Color.RED));
        setBackground(Color.DARK_GRAY);
    }
}

Comment: there is problem, that some LayoutManager ignored on Resize for PrefferedSize (BorderLayout, GridLaoyut), because are wraped to the locations or Grid, as I know only GridBag can use anchor + PrefferedSize directly and together, sure there are must exist simple hack/workaroud for that ...
Comment: +1 @camicker @msj121 @trashgod I will give you points tomorrow, I have spent all for today. I consider the centring issue sorted thanks. Now I would love to know how to fill the left over space. From what I understand this is beyond capabilities of the GridLayout. Thus, I wonder how to make sure that e.g. GridBagLayout will fill all space of e.g. first and/or last row. I tried GridBagConstraints.weighty = 1.0 as in the tutorial example but no good. Though in contrary to tutorial example my width is always perfectly filled. Is it the problem specific to this layout?
Answer:
How to make sure that when the GridLayout is not taking the whole space it is at least centered?

JPanel wrapper = new JPanel( new GridBagLayout() );
wrapper.add( centerP );
contentPane.add(wrapper, BorderLayout.CENTER);
//contentPane.add(centerP, BorderLayout.CENTER);

Comment: Thanks for that. OK this does the centring bit thought it doesn't make sure the centerP takes the whole space. And I wouldn't like a solution that would require me to setPreferredSize for the centerP.
Answer: BoxLayout does a pretty good job of distributing the space between components using Box.createVerticalGlue(). This example uses Box.createVerticalStrut(), top and bottom. The spacers are described in How to Use BoxLayout: Using Invisible Components as Filler.
Addendum: BoxTest2 is a variation that uses BoxLayout to create fixed-size edge panels and vertical glue to distribute the space more evenly. Box.Filler may also be used to control the "leftover" vertical space.
/** @see http://stackoverflow.com/questions/6072956 */
public class BoxTest2 {

    private static final int WIDE = 480;
    private static final int HIGH = WIDE / 8;
    private static final int ROWS = 5;
    private static final Box center = new Box(BoxLayout.Y_AXIS);

    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {

            @Override
            public void run() {
                JFrame f = new JFrame();
                f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                center.setOpaque(true);
                center.setBackground(Color.lightGray);
                center.add(Box.createVerticalGlue());
                center.add(new EdgePanel());
                for (int i = 0; i < ROWS; i++) {
                    center.add(new BoxPanel());
                }
                center.add(new EdgePanel());
                center.add(Box.createVerticalGlue());
                f.add(center, BorderLayout.CENTER);
                f.pack();
                f.setVisible(true);
            }
        });
    }

    private static class EdgePanel extends JPanel {

        public EdgePanel() {
            Dimension d = new Dimension(WIDE, 2 * HIGH / 3);
            setPreferredSize(d);
            setBackground(Color.red.darker());
        }
    }

    private static class BoxPanel extends JPanel {

        public BoxPanel() {
            setPreferredSize(new Dimension(WIDE, HIGH));
            setBorder(BorderFactory.createMatteBorder(1, 0, 1, 0, Color.red));
            setBackground(Color.darkGray);
        }
    }
}

Comment: @Boro: IIUC, `GridLayout` tries to apportion space equally, but your `noOfRows` may not be an integral multiple of the center panel's height. In the example above, I've commented out the struts to highlight the effect. As you enlarge the window, you'll see 0…4 light gray rows appearing cyclically across the bottom of the center panel.
Comment: @trashgod I though it must be it. Thus I started to play with GridBagLayout, to get it fill the last row with the rest, and I observed that it also is not accurate with this. It is observable as I have mentioned even in the example in its tutorial, though in their case the problem is observable with the width.
Comment: @Boro: Our examples tend to use contrasting colors to highlight the effects; but a non-opaque component will let the L&F default show. For reference, I've added another variation above. The previous version remains in [revisions](http://stackoverflow.com/posts/6076340/revisions).
Comment: @trashgod Your answer and all the input was the most useful. Thus, I am accepting your answer. Thanks again. Sadly I do not see a solution being achievable using default managers. Hopefully one day they will integrate some more advanced layout manager which takes care of such details. I heard that it might be MiG Layout. Did you have some experience with it?
Comment: @Boro: Sorry, relatively little. I updated the example to remove some noise in `EdgePanel`.
Answer: Could you try perhaps nesting this center panel in either a BorderLayout.North or maybe even a FlowLayout.Center.
By this I mean:
                JPanel holder = new JPanel(new BorderLayout());
                holder.add(centerP,BorderLayout.NORTH);
                contentPane.add(holder, BorderLayout.CENTER);
I cannot exactly visualize your problem so it is hard to write a solution.
Comment: Thanks for the input. What I am trying to achieve is to find a solution to be able to use GridLayout for rows and columns setting, while centring it.


How to make old router as access point?

Question: I have installed a new router at my home, the new router has 4 ports. And the  ISP only allowed for one port to have internet connection using ethernet. That port is taken by another person, and now only 3 ports left that don't have internet connection.
Is it possible to make my old router as a switch to share the internet connection with that one port that works?
I've tried to connect my old router to any of the 3 ports left, but I cannot access the internet.
Answer: Just put a switch or hub in between. More possibly a switch nowadays.
Comment: you mean a switch in that one port in the new router, and then connecting the the 2 lines to the switch?
Comment: yes, so they share the same MAC address towards the restricted router. Should work.
Comment: A L2 switch works on *data link layer*. Devices behind a switch won't share the same MAC address, so this solution won't work if the connection is restricted to allow only one MAC address. In that case you'd need a router to put the other devices behind a NAT.

How to make old router as access point?


How to align words vertically on the right, so that the texts are not in and out?

Question: I am new to html and css and I am trying to create web page. My question is, how do I align words vertically on the right, so that the texts are not in and out? So this is the problem I am getting, shown in this pictrue.
I want it to look like this
So basically I want the texts to align in a tidy way.
Comment: We need to see your code. Post a [mcve] in your question please
Comment: Wouldn't it have been much easier to type your question into Google?
Answer: text-align: justify; will justify text in an element. You might also want to look at the text-justify property.

p { text-align: justify; max-width: 200px; }

Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.


Variável não funciona em paginação

Question: Estou tentando montar uma paginação em um relatório que possuo, mas estou com o seguinte problema. Existe a variável $situacao, que vem via POST, que é necessária para a geração do relatório. Na primeira execução funciona normalmente, lista só os 9 primeiros itens. Mas ao clicar na página seguite, ele dá erro na variável, como se estivesse vazia. Fiz um teste fixando o valor nela e a paginação funciona corretamente. Como posso proceder?
BuscaStatus.php
<?php

// Dados do banco e controle de acesso
include "js/ValidaUsuario.php"; //LIBERAÇÃO DE ACESSO SOMENTE PARA AUTORIZADOS (ADMIN)
include "js/conn.php";
require "paginacao.php";

//$situacao = utf8_encode($_POST['situacao']);
$situacao =  'TODOS';
$situacaoE = 0; //Zera para evitar erros
$situacaoC = 0; //Zera para evitar erros
$situacaoA = 0; //Zera para evitar erros
$situacaoR = 0; //Zera para evitar erros
$situacaoAR = 0; //Zera para evitar erros
$situacaoAC = 0; //Zera para evitar erros

$data = date('d-m-Y'); //armazena data atual
$hora = date('H:i');  //armazena hora atual

// Número de artigos por página
$artigos_por_pagina = 9;

// Página atual onde vamos começar a mostrar os valores
$pagina_atual = ! empty( $_GET['pagina'] ) ? (int) $_GET['pagina'] : 0;
$pagina_atual = $pagina_atual * $artigos_por_pagina;

//ORGANIZA AS VARIÁVEIS PARA O CASO DE SER SELECIONADA A OPÇÃO "TODOS"
if ($situacao == 'TODOS') {
    $situacaoE = 'EM ANDAMENTO';
    $situacaoC = 'CANCELADO';
    $situacaoA = 'APROVADO';
    $situacaoR = 'REPROVADO';
    $situacaoAR = utf8_encode('APROVADO COM RESTRIÇÃO');
    $situacaoAC = 'AGUARDANDO CLIENTE';
}

//aqui faz a consulta do projeto
$sqlSaida = "select u.nome_completo, b.*, DATE_FORMAT(b.dt_abertura, '%d-%m-%Y') as dt_abertura from
                      briefing B,
                      usuarios U
                      where
                         B.lider = u.cracha and
                         B.situacao IN ('". $situacao . "','". $situacaoE . "','". $situacaoC . "','". $situacaoR . "','". $situacaoAC . "','". $situacaoAR . "')
                      LIMIT $pagina_atual, $artigos_por_pagina";

$resSaida = $conexao->prepare($sqlSaida);
$resSaida->execute();
$saidas = $resSaida->fetchAll();

//cria tabela para exibir resultados
             ?>
             <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">

             <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
             <title>Relatório de Projetos por Status - Peccin S.A </title>

Relatório de Projetos por Status - <?echo $situacao?>

Status em: <? echo $data ." às ". $hora; ?>

                   Projeto: </b
                   Data Abertura:
                   Nome:
                   Responsável:
                   Lider:
                   Situação:

<?
//prepara o resultado e inicia a exibição
foreach ($saidas as $saida) { ?>

                   <a href=http://pcn-sig.peccin.local/sig/subsistemas/projeto_testes/projetos/BuscaProjeto.php?projeto=<?php echo $saida['cod'] ?>><?php echo $saida['cod'] ?>
                   <?php echo utf8_decode($saida['dt_abertura']) ?>
                   <?php echo utf8_decode($saida['nome']) ?>
                   <?php echo utf8_decode($saida['responsavel']) ?>
                   <?php echo utf8_decode($saida['nome_completo']) ?>
                   <?php echo utf8_decode($saida['situacao']) ?>

<?

}
?>
<?
//exibe as linhas retornadas na consulta
print "Total: ". $resSaida->rowCount() . " Projetos encontrados.

";
print "Clique no nome da coluna para organizar o resultado.
";

// Pegamos o valor total de artigos em uma consulta sem limite
$total_artigos = $conexao->prepare("SELECT COUNT(*) AS total FROM briefing");
$total_artigos->execute();
$total_artigos = $total_artigos->fetch();
$total_artigos = $total_artigos['total'];

// Exibimos a paginação
echo paginacao( $total_artigos, $artigos_por_pagina, 5 );

?>

             <input type = 'button' value = "Fechar" class = "btn" onclick = 'javascript:window.close();'>&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp
             <input type = 'button' value = "Imprimir" class = "btn" OnClick = 'javascript:window.print();'>

Paginacao.php
<?php
/**
 * Paginação
 *
 * Cria uma paginação simples.
 *
 * @param int $total_artigos Número total de artigos da sua consulta
 * @param int $artigos_por_pagina Número de artigos a serem exibidos nas páginas
 * @param int $offset Número de páginas a serem exibidas para o usuário
 *
 * @return string A paginação montada
 */

function paginacao(
    $total_artigos = 0,
    $artigos_por_pagina = 10,
    $offset = 5
) {
    // Obtém o número total de página
    $numero_de_paginas = floor( $total_artigos / $artigos_por_pagina );

    // Obtém a página atual
    $pagina_atual = 1;

    // Atualiza a página atual se tiver o parâmetro pagina=n
    if ( ! empty( $_GET['pagina'] ) ) {
        $pagina_atual = (int) $_GET['pagina'];
    }

    // Vamos preencher essa variável com a paginação
    $paginas = null;

    // Primeira página
    $paginas .= " Home ";

    // Faz o loop da paginação
    // $pagina_atual - 1 da a possibilidade do usuário voltar
    for ( $i = ( $pagina_atual - 1 ); $i < ( $pagina_atual - 1 ) + $offset; $i++ ) {

        // Eliminamos a primeira página (que seria a home do site)
        if ( $i < $numero_de_paginas && $i > 0 ) {
            // A página atual
            $página = $i;

            // O estilo da página atual
            $estilo = null;

            // Verifica qual dos números é a página atual
            // E cria um estilo extremamente simples para diferenciar
            if ( $i == @$parametros[1] ) {
                $estilo = ' style="color:red;" ';
            }

            // Inclui os links na variável $paginas
            $paginas .= " $página ";
        }

    } // for

    $paginas .= " Última ";

    // Retorna o que foi criado
    return $paginas;

}

Primeiro link, ao executar:
http://pcn-sig.peccin.local/sig/subsistemas/projeto_testes/projetos/BuscaStatus.php

Ao clicar na página (funciona com variável fixa, não via POST):
http://pcn-sig.peccin.local/sig/subsistemas/projeto_testes/projetos/BuscaStatus.php?pagina=1

Comment: QUando vc clica na página seguinte é através de um link?
Comment: Editei a pergunta mostrando a situação, mas sim, é com link. Estou tentando "fixar" a variável para que não mude ao clicar nas páginas...
Answer: O parâmetro situacao não é persistido nas páginas seguintes da paginação porque elas são recebidas pelo método GET, diferentemente do método POST inicial.
Como sugestão de correção, altere o atributo method do formulário de busca de POST para GET e pegue a situação pela variável $_GET['situacao'].
Também será necessário alterar a forma como os links são construídos. Sugiro encapsular a lógica mais ou menos dessa forma:
function constroiLink($pagina)
{
    return '';
}

Comment: Isso mesmo, em todas as etapas das construções dos links.
Comment: Tentei, mas continua ocorrendo o mesmo erro. Como faria para persistir ela?
Comment: O que importa é que a variável esteja sempre presente na *query string* da busca (na URL, ou seja, `?situacao=TODOS`) em todas as páginas da busca, inclusive a primeira. Tente alterar de `$_POST` para `$_GET` e colocar o parâmetro manualmente na URL para ver se dá certo.
Comment: Manualmente, assim: http://pcn-sig.peccin.local/sig/subsistemas/projeto_testes/projetos/BuscaStatus.php?situacao=TODOS&pagina=1 funcionou, mas agora estou tentando entender como vou fazer isso. Adiciono a variável situacao no paginacao.php?
Comment: Alterei no paginação   mas a situacao continua passando em branco ao clicar nos links....
Comment: É porque a variável `$situacao` não é global (e nem deveria ser). Alterei a resposta com uma sugestão de implementação.
Comment: Resolvi alterando um pouco sua idéia: " Última ";

Variável não funciona em paginação