Why don't pitchers throw a combination of overhand and sidearm?

Question: If I was going to teach someone to pitch I would want to teach them to pitch both sidearm and overhand.
I think the combination of the two styles would help to confuse batters because they would not know where the pitch was coming from.
Wouldn't this be a more effective way of pitching if you had the ability to throw both ways well?
Comment: It may have to do with durability and injury.  When I was a kid, I threw out my arm pitching, but I wanted to keep pitching, so I moved to sidearm and eventually submarine with reduced pain.  The motion uses different muscles for sure.
Comment: I would think you would be more durable if you pitched a combination of overhand and sidearm. I think being good at both would be very confusing to batters.
Comment: Also, this is only guessing; I think most of the time; the person teaching kids to pitch either doesn't have distinction for that or is happy if the kid can just get it near the plate.  By the time most kids encounter someone who would even think of that or care, they are in high school or college; and at that point they are already skilled doing it one way (don't fix what's not broken); and  messing with the mechanics almost certainly increases the risk of injury.
Comment: More confusing yes.  More durable - maybe - but I can't think of any reason why.
Comment: More confusing. That says it all. I don't know why this isn't taught more.
Comment: I'd think consistency might be a issue, as muscles and mind remember both motions.  The same could be asked why golfers develop fade or draw specific swings, and very few adjust their shot to fit the shape of the particular hole.  Or why top bowlers alter their approach path for different spares rather than change their arm angle.  Being able to rely on the positioning and power of one consistent motion seems vital.  Would the added confusion be worth the reduction in precision.  I think for most, the answer has proven to be no, though surprised you don't see a few people doing it.
Comment: @JeopardyTempest Yes I can see the idea that perfecting one muscle memory could be best. However I think there are some people who would have no problem throwing both ways very well, very quickly. As has been talked about in other comments and answers, I think this idea I have presented is most effective in youth baseball where it would be very confusing.
Answer: There are TONS of pitchers that try to throw with multiple arm angles.  Some of the all time greats excelled at doing this.
The reasons you don't see it a lot more:

most pitchers need a ton of practice to do that and they don't have enough arms to get in 100 pitches a few times a week at multiple angles.
the non fastball pitches are really hard to adjust.  The twerk of your wrist and snap of your hand is different is you are straight over or sidearm for a curve/slider, even you changeup grip is different.  It is really hard to go back and forth for these.  A lot of pitchers struggle to throw these well at one angle.
the arm release is easy.  Usually you have to bring the ball back differently, this takes a different amount of time and the rest of your body is out of whack.

You have your naturals and cerebral pitchers that can adjust on the fly but the others trying to throw a curve while going 3/4ths will hang it up and watch it get clocked.
To add to this answer given baseball movement the past 4 years...  Baseball teams manage players so differently now.   There is much more of an emphasis on ball speed, rotational speed and limiting pitches/innings.   Pitchers are basically thrown into "groups" and are perfected based on their grouping parameters - almost like tuning a robot.
If a team finds that you throw harder and have better spin rate at 3/4ths compared to your normal delivery they will push you in that direction until it is perfect.   And this really means that other deliveries will not have time to be perfected as they don't want you overutilized.
Really in today's baseball there are only three types of pitchers that have a chance to learn multiple arm angles and these are probably a very low percentage of the overall pitchers:

The pitcher no on cares about.   If you are in rookie ball or A and not considered an asset to your organization they will probably give you more leeway than say a young up and coming A ball pitcher.
The phenom that does whatever he wants.   You sign for a 30 million signing bonus you are calling the shots on experimenting with different angles.   The club can't waste that money for you pouting in the minors.
The pitcher that had a horrible injury.   The guys who come back from tommyjohn and other major surgeries often experiment with arm angles and their new speed.
Comment: I think your comment at the end is important. Your 'natural' pitchers who just walk out there and sling it with feel will be my ideal candidate. I would teach this from a young age to develop the ideal pitcher.
Answer: To extend your point, being able to "switch-pitch", that is, pitch with both your right and left arm, would be even more confusing to batters. And be able to throw from multiple arm angles with both arms!! Okay, enough sarcasm. Honestly, the reason is that most pitchers, biomechanically, have an arm slot that works for them to produce velocity, accuracy, and consistency. It is very common for pitchers to get to the major leagues with a certain arm slot, and have success, but for some reason either their pitching coach, or they themselves, will have the brilliant idea to change arm slots to "create more movement" or "hide the ball better", etc. Unfortunately, however, at least from several pitchers I have seen, it has done more harm than good.
Some examples of this off the top of my head are:
Kevin Jepsen

http://www.gammonsdaily.com/kevin-jepsens-new-arm-slot-productive-or-problematic/

Ubaldo Jimenez

http://www.denverpost.com/ci_18113125
http://thecutoffman.mlblogs.com/2013/04/18/can-ubaldo-jimenez-be-fixed/

Jose Fernandez

http://www.topvelocity.net/jose-fernandezs-slider-may-have-ruined-his-arm/

These are just a few examples to stir the pot, I am sure others will think of more, and also think of some examples who benefited tremendously from changing their arm slot. Consistency in mechanics & delivery is one of, if not the single most, important element in a successful pitcher. That being said, teaching a pitcher to change arm slots constantly can lead to inconsistency and injury. While it may work for some, my conclusion is that it will not work for the majority of pitchers.
Comment: I'm seeing now that the problem with switch pitching is that the pitcher must according to the rules declare the pitching arm first. The batter is then allowed to adjust. The pitcher can only change once per plate appearance. I think this could be somewhat effective but I would rather focus my efforts into throwing with 1 arm but with 2 (or more) very different styles.
Comment: @slindsey3000 You are correct about switch pitching. The recent rule changes to accommodate for switch pitchers favor the switch hitter. As per your other comment, I agree that it *could* be 'taught to a gifted athlete early', but kids' bodies are constantly changing - it is difficult enough to teach a kid ONE set of mechanics, let alone, as you suggested, 2+ sets of mechanics. Your point is a valid one, but I just don't think it would work in practicality at a high-level. Sure, you can get through high school and even D2/D3, maybe D1 college ball, but pro baseball is a whole new game.
Comment: @slindsey3000 There is a reason that > 95% of MLB pitchers have the **roughly** the same stride length (relative to height), arm slot, arm angle, external arm rotation, timing, and leg lift. It's because bio-mechanically, there are certain absolutes when it comes to efficiency of energy transfer (physics of pitching) that make certain movements and positioning empirically more optimal for creating velocity, consistency, and accuracy. It is not a coincidence that most pitchers share many commonalities, mechanically. They didn't all just wake up one day and say "this *feels* right".
Comment: Let us [continue this discussion in chat](http://chat.stackexchange.com/rooms/39082/discussion-between-mhodges-and-slindsey3000).
Comment: Thanks for the great analysis. I enjoy that people are discussing this. I love the idea of switch pitch also. The glove would be a small issue but i'm sure you could work around that somehow. I'm holding to my position that with a very gifted athlete changing delivery 'on the fly' is the ideal way to pitch. Strictly theoretical here. In practice would it work well? I say yes, if it was taught to a gifted athlete early. I KNOW they would have great success in youth baseball. The effect would diminish as they face more skilled batters but I believe it is still very confusing for batters.
Comment: Honestly I don't see what the big deal is about the mechanics. I was an All-Star little leaguer but FAR FAR from some sort of 'gifted' athlete. I could sling it across the plate overhand or sidearm. No big deal... just throwing the ball (just fastballs). I came to my theory as I think about teaching my infant son pitching...
Comment: I remember the day I walked out on the mound in say the 3rd inning as a 12 year old and without even thinking about it too hard was just like "I'm going to throw it sidearm now" I had INSANE success. None of the kids could hit it. Of course busy body coaches start saying "you'll hurt yourself... this... that.. blah this blah that.... I would not have hurt myself... I would have been just fine... Looking back, I say to myself what if I could have just thrown each pitch however I wanted. I was just throwing fastballs to catcher... no biggie. I could do it today just fine also. It's not very hard
Comment: If I was 'gifted' I would have probably figured out how to throw curves and other types of pitches... both ways. I was not 'gifted' but maybe a bit above average... I really believe standing in the batters box and not knowing where the pitch delivery is coming from makes things tougher. Someday there will be a pitcher doing it and I am documented on here years earlier saying "Why not?" :)
Comment: @slindsey3000 "I don't see what the big deal is about the mechanics". Not to be rude, but from this comment alone I can tell that you never played baseball at a high level. At 12 years old, yeah, spotting your pitches, velocity, offspeed/breaking pitches, and the entire mental side of pitching is largely irrelevant. If you want your kid to do well in little league, teach him to get the ball in or around the strike zone, standing on his head if he feels like it, and he will likely have success.
Answer: I am currently a collegiate pitcher that throws from both submarine and a 3/4 arm slot. I'd say I mix in the 3/4 delivery only about 15-20% of my pitches in game. It is really effective if you have a difference of speed above 7 or 8 mph. The biggest problem with it at higher the higher level however is that you must have the same leg lift and stride and only change mechanics once you begin your arm action. With out this the batters will easily be able to distinguish between the pitches. If you can master similar motions however, it is extremely effective. I sit around 80-83 sub and top at around 90 at the 3/4 arm slot. I would not recommend switching styles as a youth pitcher however because it is a lot of wear and tear on your arm. Both styles use different muscle groups and if you are constantly switching styles with improper form, there is a very good likely hood for injury.
Comment: Almost none of this has relevance to the question, and the portion that does actually answer, is repeating existent information. Can you remove the unnecessary section and expand on the actual answer?
Comment: Great answer. Thank you. I would need to see more info on the injury thing. I just don't see how you would get injured more. I would actually think that doing the SAME motion time after time after time would more likely lead to injury but I have no evidence for that. Just a feeling.


Can't access RouterStateSnapshot properties on Angular custom Directive

Question: I'm coding a custom Directive that change the background-image style property according to the activated route.
To achieve this functionality, i try to reach the url property of RouterStateSnapshot, and manipulate the element's style according to url's value.
I'm logging to the console just for test.
Here's the code.
import { Directive, Renderer } from '@angular/core';
import { Router, RouterState, RouterStateSnapshot } from '@angular/router';

@Directive({
  selector: '[bgImg]'
})
export class BgImgDirective {

  constructor(
    private _renderer: Renderer,
    private _router: Router
  ) {

    var state: RouterState = this._router.routerState;
    var stateSnapshot: RouterStateSnapshot = state.snapshot;
    var url: any = stateSnapshot.url;

    console.log(url);
  }

}

console.log(url); prints nothing to the console.
The url variable is always empty

This is my root app.component template

  <app-navbar></app-navbar>
  <router-outlet></router-outlet>

<app-footer></app-footer>

However
If i try console.log(this._router);
This is the result:

How can I get to the value of url on different states of the Router, and properly apply an if statement to these? Do i have to make use of Observables?
Comment: Hard to tell. Perhaps you get the root router instead of the router for the segment that you actually want. It depends on where your directive is applied.
Comment: This means you always get the root router. Try ti subsribe to router events and get the url from the event http://stackoverflow.com/questions/33520043/how-to-detect-a-route-change-in-angular-2/38080657#38080657
Comment: @GünterZöchbauer, i updated my question with the code in app.component.html
Comment: You are trying to get it like router.routerState instead of router.currentRouterState..
Comment: @DenkoMancheski, if i try `this._router.currentRouterState`, i get a typescript error `Property 'currentRouterState' is private and only accessible within class 'Router'`
Comment: @GünterZöchbauer Thanks!! Your answer worked perfectly. If you post your answer here i'll mark it as solved by you.
Answer: You can subscribe to router events and get the URL from there
constructor(router:Router) {
  router.events.forEach((event) => {
    if(event instanceof NavigationStart) {
    }
    // NavigationEnd
    // NavigationCancel
    // NavigationError
    // RoutesRecognized
  });
}

see also How to detect a route change in Angular 2?
Answer: This answer by Günter Zöchbauer put me on the right way to achieve what I was looking for. Here's the code:
import { Directive, Renderer, ElementRef } from '@angular/core';
import { Router, NavigationStart } from '@angular/router';
import 'rxjs/add/operator/filter';

@Directive({
 selector: '[BgImg]'
})
export class BgImgDirective {

constructor(
 private _elRef: ElementRef,
 private _renderer: Renderer,
 private _router: Router
) {
_router.events
 .filter(event => event instanceof NavigationStart)
 .subscribe((event: NavigationStart) => {
  switch(event.url) {
   case "/":
    _renderer.setElementStyle(_elRef.nativeElement, "background-image", "url('../path/to/img')");
   break;
   case "/other-page":
    _renderer.setElementStyle(_elRef.nativeElement, "background-image", "url('../path/to/img')");
   break;
   }
  });
 }
}


Algorithm of task distribution between peer-to-peer nodes

Question: I have a problem to distribute tasks between nodes with fully meshed connections. All nodes know about all task and can run any task from list.
Is any protocol or solution to distribute these tasks uniformly between all nodes? I assume that when node is started it learns another peers and take part of their tasks. If node is shutdown other nodes take this node's tasks.
Comment: Task scheduling algorithms generally try to optimize some aspect of job completion, like latency, fairness, locality or throughput.  What traits are you looking for?
Comment: I guess you're looking for `load balancer` implementation!
Comment: Yep, distributed load blancer (without central point).
Comment: @phs limitations doesn't matter. In case of bad (or broken) connection it is okay if this claster will have splitted brain.
Comment: Then [elect a leader](http://en.wikipedia.org/wiki/Paxos_%28computer_science%29), have it collect incoming work and parcel it out.
Comment: @phs I know algorithm with electing leader but looking for algorithm without it. I pretty clear understand that something possible like: choose id, and take make appropriate subset dividing by number of connection with other nodes. Probably world knows something better.
Answer: If you don't want a head node, you will need for tasks always to be distributed between the nodes, with each node maintaining a task list that contains tasks that are not on any other node's list, to avoid concurrency problems.
One way to distribute the tasks would be for each node to keep an estimation of the time required to complete its assigned tasks.  When a node finds that its estimated time is less than another node's estimated time by more than the time to complete a task, it cooperates with the other node to reassign a task from the other node's list to its own list.


Manipulate Input File Stream

Question: I have a data text file which contains this
Map2D, [3, 2]
Dot3D, [25, -69, -33], [-2, -41, 58]
Map3D, [6, 9, -50]
Map2D, [3, 2]
Dot3D, [7, -12, 3], [9, 13, 68]
Map3D, [6, 9, 5]
Map2D, [3, 2]
Dot3D, [70, -120, -3], [-29, 1, 268]
Dot3D, [7, 12, 3], [-9, 13, 68]
Map3D, [1, 3, 8]
Dot2D, [5, 7], [3, 8]

Basically the text file first data is the class name which i got 4 class
Map2D
Map3D
Dot2D
Dot3D

I was trying to write my own file manipulator so that my program can extract the data above and overload the extraction operator >> for each of the 4 class and then storing it into relevant object.
I was thinking of using vector, map, set or list to store . but for this how do i achieve what i want to do such as store into relevant object of the class.
I tried googling around on how to create my own file manipulator, but will be good if someone could show me some sample code and i can compile and execute it maybe in a test file then observe the output myself. I would like to use iomanip to do a overload on the >> operator
I have to use manipulator because i need create something like
I need to do something like
cout << "Input File Name";
cin >> readFile;

and perform all the data reading & object creation
I am sorry for all the trouble caused. then it will read the records line by line, then create the class and also the data in it.
Thanks for all your help!
Comment: I don't see how stream manipulators would be suitable. If you'll read file line by line, you'll probably need to read a string first, check if it's one of Map/DotxD and then call the appropriate `operator>>`.
Comment: @VladLazarenko your comment just brought me 45 rep. :P Thx!
Comment: I need to cin to read the file and then assign object accordingly.
Comment: @LuchianGrigore: :-D glad to be of help!
Answer: This is an example with std::cin. It should work just fine with a fstream. parsing your input is really nasty. Is it possible to remove the brackets("[" amd "]") from the input?
#include <iostream>
#include <string>
#include <vector>
#include <sstream>
#include <algorithm>
#include <c>

class Map2D {
    std::vector<int> values;
public:
    friend std::istream& operator>>(std::istream& in, Map2D m) {
        std::string i;
        in >> i;
        std::stringstream ss(i);
        std::getline(ss, i, '[');
        std::getline(ss, i, ',');
        ss >> i;
        std::cout << i << std::endl;
        in >> i;
        ss.str("");
        ss <> i;
        std::cout << i << std::endl;;
    }
};

int main() {
    std::string type, file_name;
    std::cout << "Input File Name";
    std::cin >> file_name;
    std::fstream file(file_name.c_str());
    Map2D m;
    while (std::getline(std::cin, type, ',')) {
        if(type.find("Map2D") != std::string::npos) {
            file >> m;
        }
    }
}

Comment: Hi, may i ask, if i want to like ask for user input for filename, then perform the cin >> filename; how do i work with your solution
Comment: @user1777711 `std::string file_name;` `cin  >> file_name;` and use `std::fstream file(file_name.c_str())`
Comment: but your solution is different from what i actually ask.

I am trying achieve is Prompt user for filename, cin user input e.g hello.txt , read the file content and then cout . just the basic one, assigning to object will be on logic i guess.
Answer: You can use the cin to get the filename, but then you should write a helper method that can parse the file.
My suggestion would be to create a class called DataMembers or something like that. In that class you can have a helper method that reads in a data member file. The class could have 4 vectors for storing the data you read from the file.
class DataMembers
{
    private:
        std::vector<Map2D> _map2Ds;
        std::vector<Map3D> _map3Ds;
        ....
    public:
        void readDataFile(std::string inFileName);
        void writeDataFile(std::string outFileName);
};

The readDataFile method should do the following

Read the file in a line at a time
Parse the line to determine the object type to create (error out if the type is not recognized)
Validate that the line contains the correct data for the type indicated
Create the object of the proper type
Assign the object to the proper object collection

You would probably want to write some other private methods to handle the creation of the data types and assigning to the proper collections.

Manipulate Input File Stream


What is the percentage of goals scored during added time?

Question: It could be just me, but I am getting the idea that more and more goals are scored during added time. I would like to see a stat to show if the chance of a goal in added time is higher than in regular time.
For example, up to now CL matches 6x16x90 minutes gave 261 goals during regulation, 1 every 33 minutes.
Extra time had 16 goals in 6x16x5 minutes (sorry, was too lazy to look up the exact minutes of added time played), which is a goal every 30 minutes.
Does anyone have the stats over more matches/leagues/years?
Comment: this could just be based on the scores going into extra time. if it's 2-1 then one team will attack more and there's a good chance it ends 3-1 or 2-2. If it's 1-1 then both teams will usually be happy with a point and not risk losing the game. Also, this last week in the UCL is week 4, and at the stage where teams are playing *must-win* games, so they will throw even more players forward to get those extra points.
Answer: Are you talking about time added on? Statistically a team has more chance of scoring the longer a game goes on. I read an interesting article on it where the writer said a goal in the 80th minute is 40% more likely than a goal in the 10th as an example of how a goal is more likely the longer a game goes on.
http://statscream.blogspot.ie/2010/04/football-goal-times-in-brief.html
According to an article on the Guardian there has been 3532 goals scored between 81-90+ (the next highest is 2598 in 41-50 mins) so that backs up the other articles claims.
http://www.theguardian.com/football/2013/oct/30/the-knowledge-premier-league-minutes-goals
Comment: He was talking about the goals scored after 90'
Answer: Here you can have a list of famous/important Last-minute goals : http://en.wikipedia.org/wiki/Last-minute_goal
And here a well-written article about goals in stoppage-time in 2011/2012 I guess (it gives you percentage per team, only Premier League): http://www.pinnaclesports.com/online-betting-articles/11-2012/live-premier-league-betting-tips.aspx
Comment: This is a link-only answer. Stack Exchange discourages redirecting viewers to other places, see [this notice about "other castles"](http://meta.stackexchange.com/questions/225370/your-answer-is-in-another-castle-when-is-an-answer-not-an-answer).
Comment: @Nicolas that second link doesn't take to article.


403 Forbidden ao grava dados de um formulário

Question: Eu tenho um campo no formulário que permite tags html.
Se inserir a seguinte linha no campo e submeter o formulário, retorna o erro 403 forbidden:

Mas se inserir a linha com aspas simples, já não acontece o erro:

Alguém sabe o que está acontecendo?
Não é um erro ao trabalhar com o campo no php, porque fiz um die("teste") antes de qualquer $_POST e mesmo assim o erro é retornado na primeira opção.
UPDATE:
Alterei o action do formulário para um ficheiro PHP que contém apenas o código abaixo e mesmo assim retorna 403 forbidden. Alguém tem alguma idéia do que poderá ser?
<?php echo "teste"; ?>

UPDATE:
Segundo o técnico, o erro acontece porque um bloqueio do servidor anti-spam é activado.
Regra 300076, antispam content.

Há forma de contornar isso em php, ou somente desligando a regra?
Comment: Só esclarecendo: seu objetivo é que o usuário insira conteúdo com tags html, e esse conteúdo será exibido de volta como html mesmo, né? (se for, tome cuidado com [XSS](http://pt.wikipedia.org/wiki/Cross-site_scripting))
Comment: @mgibsonbr isso é um backoffice, por isso a necessidade do html, o bloqueio é que não permitimos a tag script.
Answer: Experimente usar a função htmlspecialchars:
<?php
  htmlspecialchars($variavel)
?>

Comment: Isso vai "escapar" todo o conteúdo da tag (e prevenir XSS), mas será isso que o OP quer? Em outras palavras, "permite tags html" não significa que quando os dados forem retornados do formulário eles devem vir como html, e não como texto comum (escapado)?
Comment: Então, o problema é que não chega a executar o $_POST, retorna o forbidden antes. Inseri um die("teste") antes do $_POST, pelo menos deveria imprimir a string "teste" em tela, o que não conteceu.
Answer: Eu não sou um entusiasta em php, mas tenho quase certeza que quando o PHP lê isso ele transforma numa string:
" "

E por isso que o style deve estar com seus valores em aspas simples para ser convertido:
" "

Como nosso caro amigo @rafaelcpalmeida citou você pode utilizar a função htmlspecialchars.
Comment: De fato, se essa string estiver **no código-fonte** o PHP interpretaria dessa forma. Mas pelo que eu entendi isso são dados de um campo no formulário, submetidos pelo usuário - estarão em uma variável, não no fonte PHP.
Comment: E se no caso ele der um echo nessa string ela não seria convertida e inserida no html?
Comment: Inserida no html, sim, mas inserida no PHP não... [Exemplo](https://ideone.com/9npuuA)
Comment: Sim, no html mesmo.
Comment: Então, o problema é que não chega a executar o $_POST, retorna o forbidden antes. Inseri um die("teste") antes do $_POST, pelo menos deveria imprimir a string "teste" em tela, o que não conteceu.
Answer: De qualquer forma, sua segunda opção com aspas simples está incorreta:

Tem uma " passando ai. O correto seria:

Talvez o problema seja no momento de salvar estes dados no database. Se for e você utilizar MySQL, use a função mysql_real_escape_string($html_aqui).

Fiz um pequeno teste/exemplo aqui, e tudo funcionou corretamente. Não creio que o problema seja apenas isso.

Lembrando que eu utilizei o método POST

formulário.php
<!doctype html>

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

  <?php if ($_SERVER['REQUEST_METHOD'] == 'POST') { ?>
    $_POST:

<?php echo var_dump($_POST); ?>

  <?php } ?>

  <form action="formtag.php" method='POST'>
    <input type="text" name='tag'>
    <button type="submit">Go!</button>
  </form>

resposta (html)
$_POST:
array(1) {
  ["tag"]=>
  string(41) ""
}

resposta (source)
array(1) {
  ["tag"]=>
  string(41) " "
}

Poderia postar o código completo do seu formulário?
Comment: A aspa dupla foi só um erro na hora de digitar, no fonte está correto. Também acho que o problema é outro porque não chega a executar o php, retorna o forbidden antes. Procurei saber e existe um software a correr no servidor que evita ataques XSS, talvez seja isso.
Comment: Jà procurou debugar o código? Pra ver se isso não ocorre em X etapa, ou se ja é inicialmente na requisição?
Comment: Sim, inclusive alterei o "action" do form, para um ficheiro PHP que contém apenas "echo 'teste';", mesmo assim ainda continua a aparecer 403 Forbidden. Poderá ser algum bloqueio no servidor?


make AppDelegate receive call back events from custom library

Question: I'm trying to implement a library, but the library comes with minimal documentation and I'm a little out of my depth. By looking at other code I've got this far
Documentation says
AppDelegate creates an object of JBLayer as a member variable
So I did this in AppDelegate.h
#import "JBLayer.h"
//@class JBLayer;
@interface AppDelegate : UIResponder <UIApplicationDelegate>
{
    JBLayer *aJBLayer;
}
@property (nonatomic, strong, readonly) JBLayer *aJBLayer;

this in AppDelegate.m
@implementation AppDelegate
@synthesize aJBLayer = _aJBLayer;
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    AppDelegate* appDelegate = (AppDelegate*)[[UIApplication sharedApplication] delegate];

    // THIS IS WHERE I'm STUCK
    [aJBLayer SetHandler:self.doSetHandler];

    // This is what I have to include the lib for, this seems to be ok
    [aJBLayer MainCall];

    return YES;
}

-(id)doSetHandler
{
    return WHAT???;
}

The documentation says
Set the handler the receive callback events by calling SetHandler. AppDelegate needs to pass self if AppDelegate wants to receive the call back events.
Looking in the JBLayer.h file I find:
-(void)SetHandler:(id<interfaceJBHandler>)aHandler;

I have to implement these interfaceJBHandler methods which are in interfaceJBHandler.h
@protocol interfaceJBHandler
-(void)OnJBSuccess:(NSString *)aToken;
-(void)OnJBError:(NSError *)aError;
-(void)OnJBResponse :(NSData *)aData :(JBType )aTypeOfData;

I got as far as working out it's something like
[aJBLayer SetHandler:];

But everything I've tried gives errors
[aJBLayer SetHandler:self];
[aJBLayer SetHandler:appDelegate];

This compiles
[aJBLayer SetHandler:self.doSetHandler];

But I'm missing something, somewhere I have to make a delegate but up till now I've only done delegates to pas messages between viewcontrollers.
How do I make the AppDelegate receive the call back events?
Comment: what library is JBLayer from?
Comment: It's a custom library from client, comprised of a bunch of files including these three libJB.a, JBLayer.h, interfaceJBHandler.h
Answer: You need to pass an object that implements the interfaceJBHandler protocol. If you want your appDelegate to be the object, change the following in the header file to make your app delegate conform to the protocol:
@interface AppDelegate : UIResponder <UIApplicationDelegate, interfaceJBHandler>

Set the delegate as your handler:
[aJBLayer SetHandler:self];

And implement the 3 required methods in your app delegate's implementation file:
-(void)OnJBSuccess:(NSString *)aToken{
    //Do Something
}

-(void)OnJBError:(NSError *)aError{
    //Do Something
}

-(void)OnJBResponse :(NSData *)aData :(JBType )aTypeOfData{
    //Do Something
}

Comment: Obvious. When told. Thanks


Azure AD Connect Synchronization rule editor fails when adding new sync rule

Question: If you have set up a fresh Azure AD Connect installation (latest version as of today), go to add a new inbound sync rule, and you get the wonderful error message "Object reference not set to an instance of an object", where should I look for the root cause of the problem?

The client runs, I got no errors during installation, there is no info in event log. I have tried creating very simple rules, but I doubt it has anything to do with the actual rule - and I suspect something with permissions, but I have no idea permissions for what.
My account is in the ADSyncAdmins group and I have tried with a service account, that also is in that group - same error.
Comment: Hmm... I was getting this very error while trying to create a new rule two weeks ago. I gave up and found another method to do what I needed. I'll keep an eye on your question to see if anyone comes back with an answer.
Answer: Looks like it was a bug in version 1.1.561.0 released July 23 2017.  You just have to populate the "tag" attribute when setting up the new rule.
see the below release notes
https://docs.microsoft.com/en-us/azure/active-directory/connect/active-directory-aadconnect-version-history
"Fixed an issue where new synchronization rule cannot be created if the Tag attribute isn't populated."
Comment: Seriously infuriating error. :D


How do you embed an external URL (to a software application) in Drupal with 508 compliance?

Question: We need to embed a software application (by URL) into a Drupal 7 site. The resulting page needs to be Section 508 compliant. I have been told that iFrames are not Section 508 compliant. That is what we used in the past. Is there an alternative that is accessible?
Comment: Who told you that iframes are not 508 compliant?  The guide for Web-based Intranet and Internet Information and Applications (http://www.access-board.gov/sec508/guide/1194.22.htm) is silent on the matter, but does say that frames are allowed and provides guidance on their use.  Providing alternate content for iframes is an advisory technique for WCAG 2.0 Level A, but not a sufficient one.
Comment: Well, as I said at below, if a user isn't able to use their screen reader to fill in advanced search form fields due to the iFrame, then alternative content won't be considered good enough. As to who told me, let's just say the people in charge of accessibility at my organization. I will show them this discussion page, the links people have provided, and will see what transpires.
Answer: I can't find a single reference on Google that says iFrames aren't section 508 compliant...however they will fail compliance if you do not:

Provide alternative content for IFRAME elements

iFrames can contain nested alternative content, like so:

Description of the loaded content

The rationale listed for this is:

Some browsers do not support the IFRAME element, or do not have the ability to load multiple documents together. It is therefore necessary to provide alternative content for this element even if the IFRAME only loads HTML.

This information came from here, but all of the other links I found on Google said exactly the same thing in one way or another.
Comment: If you go by the latest 508 draft (http://www.access-board.gov/sec508/refresh/draft-rule.htm), then 508 compliance for web means confirming to WCAG 2.0 Level A and Level AA success criteria.  According to http://www.w3.org/WAI/WCAG20/quickref/, alternate content for iframes is an advisory technique and not a sufficient one (see http://www.w3.org/TR/2012/NOTE-UNDERSTANDING-WCAG20-20120103/intro.html#introduction-layers-techs-head for definitions).
Comment: Thanks for your answer, Clive. Would screen readers be able to access the content in the iFrame? Advanced search forms to be able to be navigated, completed, to search the content in the external application.
Comment: I think for the most part screen readers will be able to access iFrames (support is definitely better for iFrames than standard Frames). There's a good article on the subject [here](http://accessibility.psu.edu/frames) which goes into more detail. The quote from there is *"Generally speaking, iFrames are better supported on screen readers than traditional HTML frames."*. I guess it depends a bit on how up-to-date the particular screen reader software is
Comment: @MPD Very interesting, wasn't aware of that
Comment: When I was web manager at IPM, I managed the redesign and development of our site, moving it into Drupal. We embedded two pages into our site (from an external software app) using iFrame I believe. Here's the URL of one: http://ipmglobal.org/about/careers/current-opportunities I just ran it through WAVE accessibility tester, and it seemed to pass, though I get an error when trying to see what it said about the iFrame. Interestingly, all it noted was some Javascript in the header, not the iFrame. Seems to have passed.
Answer: I am not claiming to be a 508 or a WCAG expert, but I am working through some of these issues with a client right now (though, not for a Drupal site, but it is why I have all of these links handy).
In the current version of the Section 508 standard, section 1194.22 describes the standards for "Web-based intranet and internet information and applications.". iframes are not explicitly mentioned, though frames are

(i) Frames shall be titled with text that facilitates frame
  identification and navigation.

This is explained in the accompanying guide with some examples.  You can extrapolate this to an  and use the title attribute.
The current draft doesn't really mention details like this, but everything web related essentially says that you need to meet WCAG 2.0 Level A and AA (it is more complicated that that if you dive into the draft).
If you pour through all of this, the sufficient technique is to add a title onto the iframe.  There is also an advisory technique to provide alternate content.
Based on the comments in @Clive's answer, I would say the @mlangfeld's situation is more of a grey area, as the iframe contains something functional and not just non-text content.
This shows where automated testing isn't sufficient to meet all guidelines (and many of the Level A and AA ones need to be manually verified anyway); it is possible to pass these automated tests and still have a horribly inaccessible website.
Getting this back on track for Drupal, in an ideal world, I would make a custom module that would interface with the remote application via webservice, and use this instead of the iframe.  The module would have forms defined to replicate the application, and the submit handlers would call out to the webservice, and then build results.  If you can't do a true webservice, then I would investigate a custom module that serves as a proxy between Drupal forms and POSTing to the application's forms.
This way you can ensure that your forms are accessible, and that you eliminate the complications of the iframe.  If this can't be done, then I would get an actual current screen reader and test what happens, and work through options with the client (either internal or external).
Comment: Thanks, @MPD. I agree, the best way to handle this is to test with a screen reader. So, you find that a title tag is better than a paragraph tag for the description. Sounds good.


Usar namespace em include

Question: Estou usando namespace para utilizar classes no PHP, tem uma parte onde faço
use StatusCorrida\StatusCorrida;
include('arquivo.php');

O arquivo.php faz
$var = new StatusCorrida();

esse arquivo faz uso dessas classe StatusCorrida, porém o arquivo não reconhece o namespace declarado fora do arquivo.
O erro que diz é que a class StatusCorrida não foi encontrada.
Comment: O `arquivo.php` onde você está incluíndo outro `namespace` possui um namespace também? Essa pergunta é importate! Se puder, posta um trecho do código pra ficar mais fácil entedermos.
Comment: Qual a mensagem de erro ?
Comment: Que não encontra a Classe StatusCorrida
Comment: edite a questão com mais informações. Está muito vago.
Answer: Os namespaces são definidos em cada ficheiro, pois por defeito o namespace do ficheiro é \, sendo assim, no topo do ficheiro arquivo.php precisas incluir o namespace da classes que queres usar use StatusCorrida\StatusCorrida;

Usar namespace em include


Problem in calculation of daily expense

Question: I have a simple question.
Total amount = 50 USD
<code>-----------------------------
- Expense     |   Remaining |
-----------------------------
- 20          |   30        |
-----------------------------
- 15          |   15        |
-----------------------------
- 9           |   6         |
-----------------------------
- 6           |   0         |
=============================
- 50          |  51         |
=============================
</code>
As you can see at the end value is not the same. If we calculate Expense and Remaining both value has changed. There is one more in Remaining balance.
Can you please let me know what is the problem, which I'm doing wrong.
Comment: Why are you adding up the *Remaining* column?  If you spend $5$ lots of $10$ USD instead you'll have $40, 30, 20, 10 $ and $0$ in the *Remaining* column and adding them certainly won't give you $50$ (or even be only $1$ out)
Comment: What makes you think they should be the same?  The way to check this is that the beginning balance, minus the total expenditures, equals the last remaining balance.  What would the sum of the remaining balances ever relate to in the real world?
Comment: Why do  you think something's wrong? There's simply no reason that the sum of the "remaining" amounts should be the sum of the expenditures.
Answer: The short answer is that althought the difference of the 2 sums is only 1, it is because the sum in the second column does not represent the same fact as the sum in the first column. In fact, as explained below, the sum in the second column has no meaning relevant to the issue at hand.
To find the "Total Expenses", we sum each expense as you did in column 1:
$E=-e1-e2-e3-e4 = -50$
Now, for the column you named "Remaining" the sum has no mathematical meaning or significance. Why? Let me explain. Let's go back to what is calculated in the sum "Remaining" column, the sum can be written as follows:
$S=50-e1 + [50-e1]-e2 + [50-e1-e2] -e3 + [(50-e1)-e2-e3]-e4$
$S=4*50 - 4*e1 - 3*e2 - 2*e3 - 1*e4 = $
$4*(50)+4*(-20)+3*(-15)+2*(-9)+1*(-6)=51$
Notice that the above formula has no meaning or significance. It clearly does not represent the total expense, so it is no wonder that it differs from the correct total expense.
The fact that the absolute difference is only by value of $1$ from the sum of the left column is by chance! Had you started with an amount of 200 and applied the same calculations, the first column sum would still give $-50$ but the right (bogus) sum would give $651$. I hope this is now clear.
Answer: Generally speaking, your expenses are $a_1, a_2, \ldots, a_n$ and must add up to $\sum_{k=1}^n a_k = T,$ your total amount. If you look at the sum in the other column, it is actually summing the partial sums of the first one, so it is $\sum_{k=1}^{n-1} s_k$ where $s_k = \sum_{i=1}^k a_i$. In other words, you get
$$
\sum_{k=1}^{n-1} \sum_{i=1}^k a_i
 = \sum_{i=1}^{n-1} (n-i)a_i
 = n \sum_{i=1}^{n-1} a_i - \sum_{i=1}^{n-1}ia_i
 = nT - \sum_{i=1}^{n-1}ia_i,
$$
and there is absolutely no reason why that expression should equal $T$...

Problem in calculation of daily expense


Retornar nome do aluno na consulta junto com a matricula - python e django admin

Question: Classe Base:
class Base(models.Model):
IncPor = models.IntegerField('Incluido Por', null=True, blank=True)
AltPor = models.IntegerField('Alterado Por', null=True, blank=True)
IncEm = models.DateTimeField('Incluido Em', auto_now_add=True)
AltEm = models.DateTimeField('Alterado Em', auto_now=True)

class Meta:
    abstract = True

Classe Pessoa:
class Pessoa(Base):
nome = models.CharField('Nome', max_length=150)
data_nascimento = models.DateField('Data de nascimento', null=True)
pessoa_status = models.BooleanField('Pessoa ativa?', default=True)

def __str__(self):
    return self.nome

Classe Aluno:
class Aluno(models.Model):
pessoa = models.ForeignKey("Pessoa", on_delete=models.CASCADE, null=True)
matricula = models.IntegerField('Matricula', unique=True)
aluno_status = models.BooleanField('Aluno ativo? ', default=True)

def __str__(self):
    return str(self.matricula)

Gostaria de retornar na consulta no arquivo admin.py a matrícula e nome do aluno.
O relacionamento está 1 - n. Uma pessoa pode ter varias matrículas, e uma matricula pode ser uma pessoa.
@admin.register(Aluno)
class AdminAluno(admin.ModelAdmin):
list_display = ('matricula', )

Erro:

ERRORS: <class 'core.admin.AdminAluno'>: (admin.E108) The value of
'list_display[1]' refers to 'nome', which is not a callable, an
attribute of 'AdminAluno', or an  attribute or method on 'core.Aluno'.
System check identified 1 issue (0 silenced).
Answer: Você pode exibir o nome e a matrícula do aluno na página Admin do Django da seguinte forma:
Classe Aluno:
class Aluno(models.Model):
pessoa = models.ForeignKey("Pessoa", on_delete=models.CASCADE, null=True)
matricula = models.IntegerField('Matricula', unique=True)
aluno_status = models.BooleanField('Aluno ativo? ', default=True)

def __str__(self):
    return "Nome: {} - Matrícula: {}".format(self.pessoa.nome,self.matricula)

Comment: Certo, dessa forma consigo capturar o nome. Mas gostaria de exibir o nome na grid do admin.py
Answer: Para recuperar o nome da class Pessoa
Utilizei como solução no admin.py
list_display = ('get_nome',)

def get_nome(self, obj):
    return obj.pessoa.nome
get_nome.short_description = 'Nome'


How to estimate certain parameters of an AR model in R?

Question: I need to estimate parameters of an AR model which is in the form of AR(1,11) it means that coefficients of AR orders from order 2 until order 10 are zero. How can I estimate these two parameters in R since arima function only accepts p as the order of the AR component. Note that this model has a different structure than Seasonal AR.
Thanks
Answer: Wouldn't this be possible by using the FIXED option in the ARIMA syntax? In this case,
output <- arima(x, order=c(11,0,0), fixed = c(NA,0,0,0,0,0,0,0,0,0,NA))

The order statement supplies the number of lags for the AR process, and the fixed vector is "NA" for any lags you want to estimate and zero otherwise.
Comment: thank you, I didn't know that we can assign "NA" for parameters that we need. I will try this.
Comment: Sure thing, let me know if that resolves your problem.
Comment: Yes it did but we should add another NA for q order like this  `output <- arima(x, order=c(11,0,0), fixed = c(NA,0,0,0,0,0,0,0,0,0,NA, NA))`


Change layout depending of values in store

Question: I'm playing with Nuxt3 and Pinia.
I'd like to have two layouts: one for guest users and another for authenticated users.
app.vue

<template>
  <NuxtLayout>
    <NuxtPage />
  </NuxtLayout>
</template>

layout.global.ts
import {storeToRefs} from "pinia";
import {useAuthStore} from "~/store/auth";

export default defineNuxtRouteMiddleware((to) => {
    const authStore = useAuthStore();
    const {authenticated} = storeToRefs(authStore);

    const layout = computed(() => {
        return authenticated.value ? "authenticated-layout" : "default-layout";
    });

    setPageLayout(layout)
})

Every test I made result with the same error:
chunk-RAKT47ZN.js:1449 [Vue warn]: Unhandled error during execution of scheduler flush. This is likely a Vue internals bug. Please open an issue at https://new-issue.vuejs.org/?repo=vuejs/core
  at <NuxtLayoutProvider layoutProps= {ref: RefImpl} key="authenticated-layout" name="authenticated-layout"  ... >
  at <NuxtLayout>
  at <App key=3 >
  at <NuxtRoot>
warn2 @ chunk-RAKT47ZN.js:1449
logError @ chunk-RAKT47ZN.js:1623
handleError @ chunk-RAKT47ZN.js:1615
callWithErrorHandling @ chunk-RAKT47ZN.js:1567
flushJobs @ chunk-RAKT47ZN.js:1763
Promise.then (async)
queueFlush @ chunk-RAKT47ZN.js:1676
queueJob @ chunk-RAKT47ZN.js:1670
(anonymous) @ chunk-RAKT47ZN.js:7208
triggerEffect @ chunk-RAKT47ZN.js:614
triggerEffects @ chunk-RAKT47ZN.js:604
triggerRefValue @ chunk-RAKT47ZN.js:1211
(anonymous) @ chunk-RAKT47ZN.js:1371
triggerEffect @ chunk-RAKT47ZN.js:614
triggerEffects @ chunk-RAKT47ZN.js:599
triggerRefValue @ chunk-RAKT47ZN.js:1211
set value @ chunk-RAKT47ZN.js:1255
finalizeNavigation @ vue-router.js:2409
(anonymous) @ vue-router.js:2319
Promise.then (async)
pushWithRedirect @ vue-router.js:2287
push @ vue-router.js:2213
login @ login.vue:19
await in login (async)
(anonymous) @ chunk-RAKT47ZN.js:10436
callWithErrorHandling @ chunk-RAKT47ZN.js:1565
callWithAsyncErrorHandling @ chunk-RAKT47ZN.js:1573
invoker @ chunk-RAKT47ZN.js:9397
chunk-RAKT47ZN.js:9157 Uncaught (in promise) TypeError: Cannot read properties of null (reading 'parentNode')
    at parentNode (chunk-RAKT47ZN.js:9157:30)
    at ReactiveEffect.componentUpdateFn [as fn] (chunk-RAKT47ZN.js:7175:11)
    at ReactiveEffect.run (chunk-RAKT47ZN.js:423:19)
    at instance.update (chunk-RAKT47ZN.js:7212:52)
    at updateComponent (chunk-RAKT47ZN.js:7039:18)
    at processComponent (chunk-RAKT47ZN.js:6974:7)
    at patch (chunk-RAKT47ZN.js:6436:11)
    at patchSuspense (chunk-RAKT47ZN.js:2562:7)
    at Object.process (chunk-RAKT47ZN.js:2481:7)
    at patch (chunk-RAKT47ZN.js:6461:16)
parentNode @ chunk-RAKT47ZN.js:9157
componentUpdateFn @ chunk-RAKT47ZN.js:7175
run @ chunk-RAKT47ZN.js:423
instance.update @ chunk-RAKT47ZN.js:7212
updateComponent @ chunk-RAKT47ZN.js:7039
processComponent @ chunk-RAKT47ZN.js:6974
patch @ chunk-RAKT47ZN.js:6436
patchSuspense @ chunk-RAKT47ZN.js:2562
process @ chunk-RAKT47ZN.js:2481
patch @ chunk-RAKT47ZN.js:6461
componentUpdateFn @ chunk-RAKT47ZN.js:7171
run @ chunk-RAKT47ZN.js:423
instance.update @ chunk-RAKT47ZN.js:7212
callWithErrorHandling @ chunk-RAKT47ZN.js:1565
flushJobs @ chunk-RAKT47ZN.js:1763
chunk-RAKT47ZN.js:7520 Uncaught (in promise) TypeError: Cannot read properties of null (reading 'subTree')
    at move (chunk-RAKT47ZN.js:7520:28)
    at move (chunk-RAKT47ZN.js:7520:7)
    at Object.resolve (chunk-RAKT47ZN.js:2789:11)
    at chunk-RAKT47ZN.js:2912:20

I'm quite new to Vue (I mostly use React).
Did I miss something? (SSR?). Is there another way in Vue.js to do that?
Comment: Please, provide https://stackoverflow.com/help/mcve for the problem. The stack is too obscure and doesn't contain the explicit cause. The error means that something went wrong during the navigation. You may want to debug what happens in your own modules, i.e. login.vue here. Otherwise than the answer suggests, there's nothing to fix.
Answer: I don't think you need to use computed on your case. A simple validation like this would work.
Here is an example of how you can use dynamic layout content.
~/middleware/layout.global.ts

export default defineNuxtRouteMiddleware(() => {
  const authenticated = false
  if (authenticated) {
    return setPageLayout('authenticated')
  } else {
    return setPageLayout('default')
  }
})

If you set the authenticated to true it will change the layout to authenticated.
Create the layouts
~/layouts/authenticated.vue

<template>

Authenticated

      <slot />

</template>

~/middleware/default.vue

<template>

Default Layout

      <slot />

</template>

Set the layout in the page
app.vue

<template>

    <NuxtLayout>
      <NuxtPage />
    </NuxtLayout>

</template>

~/pages/index.vue

<template>

Home page

</template>

Tested and it works.
Comment: I change const authenticated = false with const {authenticated} = storeToRefs(authStore); and the condition by  if (authenticated.value). It doesn't detect the change when I set authenticated = false|true in the store. I need to reload the page.
Comment: @Sancho, you don't need `storeToRefs`. You can remove that. See working example
https://stackblitz.com/edit/nuxt-starter-pfxwrj?file=stores%2FuseAuthStore.ts


Please tell me what drupal table the block php visibilities settings is stored at

Question: Within a block I have configured under the "Visibility settings" and "Show block on specific pages" I have put in PHP code that determines where this block is displayed within a page or not via a returned true or false.
I have it working correctly but then I added additional restrictions within the PHP but I must have put in a syntax error that caused the site to go down saying "Temporarily Unavailable".
I need to be able to change the PHP code back to the working version but I don't know what drupal table the block PHP code is stored.  Please tell me what drupal table the block php visibilities settings is stored at.
Comment: What version of Drupal is this?
Comment: Drupal 7 is the version
Answer: The php code should be stored in the pages field of the block table, and it should not be serialized.
The visibility field can have one of three values:

BLOCK_VISIBILITY_NOTLISTED (0),
BLOCK_VISIBILITY_LISTED (1), or
BLOCK_VISIBILITY_PHP (2).

In the case of the first two, the pages field will contain a text list of the notlisted or listed pages for the block. in the case of the third, the field will contain the php code.
Comment: And what is the name of the table exactly in Drupal 8?  `block_content_field_data`?


can we use the well known port for own purpose?

Question: I have written a shell script to scan the ports of system using nmap.
I am searching for some port number like 515 which is used by the Line Printer Daemon—print service and if it is there means I can say it is a printer as printer only have this daemon.
I don't know whether this port can be used by any other process.If yes kindly tell me about this whether it is possible to use the well known port or not by our own process.
If yes then I can't say it is a printer as port user is not a printer all the time.
Thnaks
Answer: You can use that port as long as nothing else is running on it. Also you need higher privileges when starting the process to be able to claim that port.
Comment: You will have to discover what protocol is being used on that port, nmap has the -sV parameter switch to do this automatically.
Comment: :@Lucas Kauffman :Thanks,for the information.this means it is not Reliable to use nmap port scan result to find out the printer ,I can't say it is a printer as the port may used by other process.
Comment: nmap often talks enough of the protocol to determine that it is actually a printer on that port.  It can pick between different pieces of software on the same port such as nginx, IIS and Apache, all on port 80 (on different machines) and it will let you know which one is which.
Comment: Thanks @Ladadadada ,Actually 515 is the port for the LPD and it is one the print server have not printer I regret for wrong info.Use this: http://technet.microsoft.com/library/cc783789%28WS.10%29.aspx ,I use nmap to the print server's Ip now and now also I am getting the same port used as printer,So I got confused by this,it clears that a server having LPD running to receive the request of printer from the client is having 515 port running .Now I am using 9100 port for this ,is this a good idea now as 515 is not the port used by a remote printer.
Answer: For any port the official use of the port-number is not necessarily what is really running on there.
There are no 100% guarantees. It is always possible that somebody decided to put something else on that port.
In some cases the "official" use of a port already indicates that there is more than 1 possibility.
That is why nmap has the -sV option: This attempts to probe what is really running on a port.
Having said all that: The chance that somebody abuses 1 of the more common ports (such as 515) for something else than the intended normal use is very small.
It is such a corner-case that I normally wouldn't even bother with nmap -sV, unless I am suspecting somebody is messing around intentionally.
Answer: I'm not entirely clear what you're asking:
Are you asking if "reserved" ports can only be used by the associated app, so that if you see port 25 in use, for example, then whatever's running on it must be a SMTP server because that's the SMTP port? If so, then the answer is "No". It's essentially 'first come first served' to bind to a port.
OR
Are you asking if you can take a port that's normally used by one process and use it for another process? If so, the answer's "yes" - see the first part of my answer. You just need to stop the other process grabbing the port, then you can bind to it yourself.
Comment: Thanks for you reply ,My doubt is about accessing the well known ports ,The question came to me because as earlier I have asked I am using nmap to descover all nodes and getting the printer connected to it so,some time the nmap no giving device type as printer so,how to know the printer device ,Then I thought of using the port used by the printer,thus asked whether the ports are fixed for a perticular process or can be used by any other ..


Prove, that $\vec{\phi }(t)=e^{\lambda_0t} \cdot \vec{x}_0 $ is a solution to the system $X'=AX$

Question: If $\lambda_0$ is an eigenvalue of matrix $A$, corresponding to eigenvector $\vec{x}_0$, then vectorfunction $\vec{\phi}(t)=e^{\lambda_0 t} \cdot \lambda_0 \vec{x}_0$ is a solution to homogeneous system $~X'=AX~$. Do, someone know the name of the theorem and if possible where to find the proof with detailed explanations?
Answer: If $v$ is an eigenvector of $A$ with eigenvalue $\lambda$, then
$$ X(t) = e^{\lambda t} v \implies X'(t) = e^{\lambda t} (\lambda v) = e^{\lambda t} (Av) = A (e^{\lambda t} v) =  AX(t), $$
so $X$ solves the differential equation.
Comment: Do you know the title of the theorem? Because I don't understand the proof you gave either.
Comment: I'm pretty sure it doesn't have a name. You can read more about it, e.g. on this website: https://www.math24.net/method-eigenvalues-eigenvectors/. There are some worked examples at the bottom of the page. If that doesn't suffice, just pick up any decent book about differential equations. This theorem will definitely be in there, in a section relating to linear systems of ODE with constant coefficients.


How Do I Backup My PostgreSQL Database with Cron?

Question: I can run commands like vacuumdb, pg_dump, and psql just fine in a script if I preface them like so:
/usr/bin/sudo -u postgres /usr/bin/pg_dump -Fc mydatabase > /opt/postgresql/prevac.gz
/usr/bin/sudo -u postgres /usr/bin/vacuumdb --analyze mydatabase
/usr/bin/sudo -u postgres /usr/bin/pg_dump -Fc mydatabase > /opt/postgresql/postvac.gz
SCHEMA_BACKUP="/opt/postgresql/$(date +%w).db.schema"
sudo -u postgres /usr/bin/pg_dump -C -s mydatabase > $SCHEMA_BACKUP

These run at command line on Redhat when I am sudo to root and then as you see in the commands above I do a sudo -u to postgres.
But when I try to kick this off from cron, I get zero bytes in all the files -- meaning it didn't run properly. And I don't get a clue in the logs that I can see.
My /etc/crontab file has this entry at the bottom
00 23 * * * root /etc/db_backup.cron

And yes, /etc/db_backup.cron is chmod ug+x, owned by root, and the top of the file says "#!/bin/bash" (minus doublequotes).
Anyone know what gives?
Comment: at least on redhat, % symbols needs to be escaped. not escaping it will result in cron trying to execute your command only up until the %. See - http://fahdshariff.blogspot.com/2009/05/percent-sign-in-crontab.html
Answer: Since you seem to have superuser rights anyway, you could put those commands into the crontab of the postgres user like so:
sudo su postgres
crontab -e

and then put the pg_dump/vacuumdb commands there.
Comment: ''sudo su postgres'' That's crazy! Try ''sudo -u postgres''. Setup a sudo spec, it's much safer.
Comment: This is what I ultimately ended up doing and it worked fine only when I did chown postgres.root /opt/postgresql (where the files were going).
Comment: You (postgres) are not allowed to access to (crontab) because of pam configuration.
Answer: I have a dynamic bash script that backs up all the databases on the server. It gets a list of all the databases and then vacuums each DB before performing a backup. All logs are written to a file and then that log is emailed to me. This is something you could use if you want.
Copy the code below into a file and add the file to your crontab. I have setup my pg_hba.conf to trust local connections.
#!/bin/bash
logfile="/backup/pgsql.log"
backup_dir="/backup"
touch $logfile
databases=`psql -h localhost -U postgres -q -c "\l" | sed -n 4,/\eof/p | grep -v rows\) | grep -v template0 | grep -v template1 | awk {'print $1'}`

echo "Starting backup of databases " >> $logfile
for i in $databases; do
        dateinfo=`date '+%Y-%m-%d %H:%M:%S'`
        timeslot=`date '+%Y%m%d%H%M'`
        /usr/bin/vacuumdb -z -h localhost -U postgres $i >/dev/null 2>&1
        /usr/bin/pg_dump -U postgres -i -F c -b $i -h 127.0.0.1 -f $backup_dir/$i-database-$timeslot.backup
        echo "Backup and Vacuum complete on $dateinfo for database: $i " >> $logfile
done
echo "Done backup of databases " >> $logfile

tail -15 /backup/pgsql.log | mailx firstname.lastname@example.com

Comment: Here is another good script: http://wiki.postgresql.org/wiki/Automated_Backup_on_Linux
Comment: @Imraan Parker how do you manage to skip using the password? I want to backup as admin account of the database not the root user postgres how can I do that?
Comment: You can add '--analyze' to the /usr/bin/vacuumdb command to perform an analyze as well.
Answer: I have set my cron like this. Every 59 minutes since monday to friday
*/59 * * * 1-5 sh /home/my_user/scripts/back_my_bd.sh

The script to run the backup is inside back_my_bd.sh file  and the content is:
pg_dump -U USERDATABASE DATABASENAME > /home/my_user/sql/mybackup.sql

And i created the .pgpass file inside home directory to allow the backup whithout specify the user and password
localhost:5432:DATABASENAME:USER:PASSWORD

Sorry my english is not good!
Answer: Your environment variable are maybe not set in cron.
In your normal session, you probably have defined these variables:
PG_PORT
PG_HOST
PG_DATABASE
PG_USERNAME
PG_PASSWORD

Add an "env" into yout script.
Comment: Those aren't exactly the variables used by pg_dump and vacuumdb. You can see the full list here: http://www.postgresql.org/docs/8.4/static/libpq-envars.html
Comment: I need a little more help than that I think. I put 'env' in there before the commands and after the #!/bin/bash and all it did was dump out the environment to the log file (because I'm now dumping the output to a logfile as it runs).
Comment: The way to set these variables would be
'export PG_PORT=5432' etc.
Comment: @bilitgates Nice!! Thank you. I've learned something today :-)
Answer: you probably have "ident" authentication in your pg_hba.conf for your postgres user.
The option  "-u postgres" fails when that is the case.
either change user to postgres in your backup script or configure a different authentication method.
Answer: Instead of the following command:
databases=psql -h localhost -U postgres -q -c "\l" | sed -n 4,/\eof/p | grep -v rows\) | grep -v template0 | grep -v template1 | awk {'print $1'}
You can use below:
databases=psql -t -c "select datname from pg_database where datname not like 'template%';" | grep -v '^$'
The first one return '|' for template databases and an empty line.
The second one is cleaner.
Answer: databases=psql -h localhost -U postgres -q -x -t -c "\l" | grep 'Name' | sed 's/ //g' | sed 's/Name|//g'
Answer: Another version to get the list of databases:
psql -lqt | grep -vE '^ +(template[0-9]+|postgres)? *\|' | cut -d'|' -f1| sed -e 's/ //g' -e '/^$/d'
As my psql -lqt output is:
 abcdefghij         | postgres | UTF8     | en_US.UTF-8 | en_US.UTF-8 |
 postgres           | postgres | UTF8     | en_US.UTF-8 | en_US.UTF-8 |
 template0          | postgres | UTF8     | en_US.UTF-8 | en_US.UTF-8 | =c/postgres          +
                    |          |          |             |             | postgres=CTc/postgres
 template1          | postgres | UTF8     | en_US.UTF-8 | en_US.UTF-8 | =c/postgres          +
                    |          |          |             |             | postgres=CTc/postgres
 abc                | postgres | UTF8     | en_US.UTF-8 | en_US.UTF-8 |


Percentage in WHERE CLAUSE in mysql

Question: I want to get all records have price 20% Less OR More of a give value.
+----+------------+----------+---------+
| ID | Item        | Category |  price  |
+----+------------+----------+-----------+
|  1 | Popular     | Rock     |  1000
|  2 | Classical   | Opera    |  5000
|  3 | Popular2    | Jazz     |  6000
|  4 | Classical2  | Dance    |  8000
|  5 | Classical3  | General  |  4825
+----+------------+----------+------------+

User has to pass two parameters
i - Category
ii-Price
I need to show all item having same category and price is between 20% less and 20% greater than user's value.
Something like this
SELECT * FROM Table1 WHERE Categry='ROCK' AND price > (20% less price of user's price) AND price < (20% greater than user's price)

Answer: Assuming @price represents the user's price:
SELECT *
FROM   Table1
WHERE  Categry='ROCK' AND price BETWEEN (0.8 * @price) AND price < (1.2 * @price)

Comment: @user3244721 0.8 (i.e., 80%) is 20% less than a whole (=1). 1.2 (or 120%) is 20% more than a whole (=1). Once you have this ratio down, you can multiply it by the size (in our case `@price`).
Comment: can you explain it,how you using .8 and 1.2?
Answer: SELECT
    *
FROM
    Table1
WHERE
    Categry='ROCK'
    AND price > (userprice * 0.8)
    AND price < (userprice * 1.2)

Comment: you have used 4/5 and 5/4?why so?
Comment: better to use 0.8 and 1.2
Comment: why it is 0.8 and 1.2?why not same degits?either 1.2 or 0.8
Comment: as i understand you need 80% between 80% and 120%

Percentage in WHERE CLAUSE in mysql


Application won't launch. Breakpoints aren't hit. No exceptions

Question: My program worked fine up until 30 minutes ago when it just would not launch. I didn't change any code and all settings are the same. When I try to launch my application through visual studio it just does what it usually does then says "Ready". Nothing shows. If I try to debug the code by breaking it somewhere, the breakpoint says "The breakpoint will not currently be hit. The source code is different from the original version." Also visual studio freezes if I leave the supposedly running program going for longer that about a minute, then I have to end the visual studio task. There really isn't any code that I can show you for this.
What is going on and how can I fix it? Is my project corrupt somehow?
Comment: Clean and rebuild - it sounds like the source is out of synch.
Comment: Check that you're still in debug mode.
Comment: @Plutonix Just did this and it didn't change a thing. It says "0 succeeded, 0 failed, 1 skipped"
Comment: Also try to restart Visual Studio. Also, before starting it again delete VS's temporary files (mainly .ncb).
Comment: @Dialecticus I have restarted Visual Studio over 10 times now. Where can I find temp file for VS?
Comment: @Mathemats I am definitely in debug mode.
Answer: If this happened to me I would do:
Check Configuration ( Debug vs Release vs other)
Check Platform (AnyCPU or ....)
Make sure that they both are Debug and AnyCPU
Save solution
Clean Solution
Build each project starting with the one that has no dependencies
** UPDATE **
You posted this message

"0 succeeded, 0 failed, 1 skipped" –

When you Clean, there should be no skipped projects in the process of rebuilding
Comment: Thank you just found it. Just cleaned everything again for the fifth time and it didn't skip it this time. Seems to have done the trick.


How many subdomains can you have on the intranet v internet

Question: Apologies as this is a developer asking questions about networking
Internally we use names such as
myname.subdomain.domain.co.uk
Apparently this is because we using a forest(?). My question is, is this a name that can be accessed via the internet as well as the intranet
If this is in the wrong category please change it
Answer: The answer is yes
https://webmasters.stackexchange.com/questions/65581/how-can-i-add-sub1-sub2-domain-com-to-my-godaddy-hosting-account
"So, if the server that is going to host your sub sub domain has IP 126.96.36.199, your DNS records should be like this :
sub2.sub1.domain.com.       A     184.108.40.206
www.sub2.sub1.domain.com.   A     184.108.40.206

If you want to use CNAME records :
sub2.sub1.domain.com.       A       22.214.171.124
www.sub2.sub1.domain.com.   CNAME   sub2.sub1.domain.com."


Intersection surface area of 3 circles with 3 different radius

Question: I am trying to find the equations to calculate:

The intersection surface area generated by the intersection of 3 circles (3 circles
like a Venn Diagram).
The 3 circle's radius could be be different one from others but always 0 < radius <= 1
The circles centres positions are fix and they are separated by 1 unit each from other
(the circle's centres are located in the vertexs of an equilateral triangle of side=1)

To be clearer... the intersection "of the 3 circles" area will result in a figure like an "irregular Reuleux triangle". That means a Reauleaux triangle where the internal triangle could be any (and not only an equilateral triangle) and the three radius could be different one from the others
Thanks a lot in advance
Georges L
Comment: very interesting, but first of all is such an equation exists?
Comment: I can see that trigonometry will work quite well. If $A_1, B_1$ and $C_1$ is your Reuleux triangle, and $ABC$ is your equilateral triangle all you really need are the angles  $\angle B_1 A C_1$ and its other two counterparts. Those can be derived by trigonometry.
Answer: Given only two similarly intersecting circles, can you find the area of their intersection?
Say $S_1, S_2, S_3$ are the circles, $T$ is the triangle and $A(s)$ is the function calculating the area of some set $s$. Then $A(\bigcap S_i) = A(T) - \sum  \limits_{i <j} \Big(A(S_i \cap T) - A(S_i \cap S_j)/2 \Big)$.
Answer: One should make use of the symmetries inherent in the problem. Therefore I propose to operate in the complex plane, and to assume that the three centers are the points $\omega^0=1$, $\omega$, and $\omega^2=\bar\omega$, where $\omega:=e^{2\pi i/3}$. The vertex $z_0$, where the circles centered at $\omega$ and $\omega^2$ intersect, can be written in the form
$$z_0=s + t (\omega -\omega^2)\ ,$$
where $s$ and $t$ are real. Now one has to solve the system
$$|z_0-\omega|^2=r_1^2\ ,\qquad |z_0-\omega^2|^2=r_2^2\ .$$
The unknown $t$ will be uniquely determined, and for $s$ one has to chose the larger of the two solutions. So we arrive at a formula of the form
$$z_0=f(r_1,r_2)\omega^0+g(r_1,r_2)(\omega^1-\omega^2)\ .$$
Having this formula in hand one immediately deduces the formulas for $z_1$ and $z_2$ by cyclic permutation of the indices and exponents.
Now the intersection in question is a union of the triangle $\Delta:=\Delta(z_0,z_1,z_2)$ and three circle segments. The area of $\Delta$ is computed easily from the $z_k$, whereas the area of the circle segment $S_k$ centered at $\omega^k$ is the difference of a sector area and a triangle area:
$$|S_k|= {1\over2}r_k^2\ \angle(z_{k+1},\omega^k,z_{k-1})-|\Delta(z_{k+1},\omega^k,z_{k-1})|\ .$$


OpenSSH client on Windows 10 connection error

Question: On Windows 10 Enterprise, I can't connect via ssh to a linux machine. 192.168.0.3 is a valid local IP, i can connect to it with putty.
PS C:\Users\elsneste> ssh 192.168.0.3
CreateProcessW failed error:193
ssh_askpass: posix_spawnp: Unknown error
Host key verification failed.

PS C:\Users\elsneste> ssh -V
OpenSSH_for_Windows_8.1p1, LibreSSL 3.0.2

This is a quite fresh Windows 10 installation. I copied the .ssh folder from the previous machine, but that was maybe a bad idea.
I then renamed the .ssh folder to ._ssh to inactivate it, with no effect.
Windows Openssh-feature has been reinstalled. again, no effect.
Git for windows is also installed. Same error in git cmd, no error in git bash
Comment: OpenSSH 8.1 is quite old, with it looking like 8.x is now on 8.9, and 9.x has been out for a while, so perhaps 8.1 is trying to use methods that are no longer supported or have been removed through one of the vulnerability discoveries that have come up over the last few years? Perhaps try updating to a more recent version.
Answer: Found the solution:
delete the environment variable
DISPLAY=UNDEFINED (or similar)
from the windows environment variables.


Probability : Ruin Problem

Question: There are two players. Player 1 has 2 dollars and Player 2 has 3 dollars.
The Game:
They toss a coin
- If it is heads Player 1 gives 1 dollar to Player 2.
- Otherwise Player 2 gives 1 dollar to Player 1.
H : Heads
$$P\left ( H \right ) = \frac{1}{3}$$
I couldnt find a pattern for this question. Do you have any ideas?
What is the probability that Player 1 is (ultimately) ruined?
Thanks in advance.
Comment: What is the question?
Answer: We assume that the question will be about the probability that Player 1 (or perhaps Player 2) is (ultimately) ruined. Player 1 and Player 2 are not nice names, so let us call them Xavier and Yolande, or more briefly $X$ and $Y$.
Let $a$ be the probability that $X$ will ultimately be ruined, given that he has $1$ dollars and $Y$ has $4$.
Let $b$ be the probability that $X$ will ultimately be ruined, given that he has $2$ dollars and $Y$ has $3$.
Let $c$ be the probability that $X$ will ultimately be ruined, given that he has $3$ dollars and $Y$ has $2$.
Let $d$ be the probability that $X$ will ultimately be ruined, given that he has $4$ dollars and $Y$ has $1$.
It is at least intuitively clear that the numbers $a,b,c,d$ exist, since the probability that the game continues forever is $0$.
We happen to want $b$, but it is useful to bring in $a$, $c$, and $d$.
If $X$ has $1$ dollar, then with probability $\frac{1}{3}$ she has to give $1$ dollar to $Y$ on the next toss, and he is ruined. With probability $\frac{2}{3}$ he wins a dollar, and then the probability he is ultimately ruined is $b$. Thus
$$a=\frac{1}{3}+\frac{2}{3}b$$
Similarly,
$$b=\frac{1}{3}a+\frac{2}{3}c$$
$$c=\frac{1}{3}b+\frac{2}{3}d$$
$$d=\frac{1}{3}c$$
We have four linear equations in four unknowns. Solve for $b$.
Comment: You are welcome. It would be useful if you edited your original question slightly, so that it explicitly asks for the probability of ruin.

Probability : Ruin Problem


.htaccess rewriting rule

Question: I have a folder within a site that is a seperate web app than the parent. Both are working fine, but when I go to the domain.com/folder/ path, I would like it to forward me to domain.com/folder/index.htm for consistency. This is the htaccess rule I was trying, but it wasn't working for me and I am not sure what I did wrong.
<code>RewriteRule ^folder/$ folder/index.htm
RewriteRule ^folder$ folder/index.htm
</code>
I tried these rules at the start and end of the rule list to see if anything was overriding and nothing appears to be.
Answer: You don't need Mod Rewrite for this. Instead, use DirectoryIndex:

DirectoryIndex index.htm

Place this file in the root of the folder you want this to apply to (e.g. domain.com/folder/)
Comment: I assume you mean /.htaccess has "DirectoryIndex index.php" inside it (where / is the root of your website). You need to go to the subfolder that contains your other webapp (/folder/ in your example) and create another .htaccess with "DirectoryIndex index.htm" in it.

.htaccess rewriting rule


"Eloquent Javascript" recursion exercise

Question: The objective is not to use any of build in functions related to math to determine "isEven", but what is isEven(-n) suppose to do, and for those pondering what (n-2) does is that it subtracts a variable to a point of arriving to 1 or 0 (I don't belief that the book explains what the exercise is, so just looked at the answer).
function isEven(n) {
  if (n == 0)
    return true;
  else if (n == 1)
    return false;
  else if (n < 0)
    return isEven(-n);
  else
    return isEven(n - 2);
}

Comment: What is your question?
Comment: This sounds like homework.
Comment: `but what is isEven(-n) suppose to do` tell me, what's the negative of a negative value?
Comment: This question is from the Eloquent JavaScript book. The exercise is to find even numbers using a recursive function rather than using the modulus operator.
Answer: Looks like that just turns any negative number into a positive number, so for instance:
-10, 10, 8, 6, 4, 2,0 => even
Comment: This is a recursive function that continues to call itself.  It checks for 0 or 1, and otherwise it inverts negative numbers or subtracts 2, eventually returning true or false.  The specific line he asked about, "what is isEven(-n) suppose to do" turns negatives into positives and continues chaining itself.
Comment: How do you figure that? It doesn't even return a number. It checks if a number is even.


What's the meaning of a note before the time signature?

Question: I'm working on a project using music sheets, but I don't understand music theory or notation.
The sheet I'm studying is The Four Seasons. From what I gather the sheet was written with the MuseScore software (the accompanying MIDI has the name of the music and author at the meta event 09 and 10).
Before the time signature for the piece there's a eighth note with the fortissimo mark.
What is the meaning of this note?
Comment: looks like a pickup to me.  Probably a stylistic choice to keep the ledger looking artful.
Answer: It's an engraving mistake.  The time signature should come straight after the key signature, before the first note.
Here's the opening of the Ricordi edition, from IMSLP.   The f indication is in brackets, this indicates that's it's an editorial addition, not in the original manuscript.
http://imslp.eu/Files/imglnks/euimg/f/f2/IMSLP386586-PMLP126432-Vivaldi__Antonio-Opere_Ricordi_F_I_No_22_scan.pdf
Comment: Sorry, EvSunWoodard, you're way out here!  This is a simple engraving error.  End of.  Really.
Comment: This does NOT have to be a mistake. It is most likely an artistic choice. Time signatures can occur whenever in a score. There are many songs that shift between 6/8 and 3/4 without re-declaring their key. Generally speaking, the first time signature is before the the first note, but in this case it is likely indicating that it is the directors choice how fast to take it, especially with the fortissimo. Without a time signature, the eighth note has no assigned length, and can therefore be taken at any tempo or length. Although, that is all theoretical and not necessarily relevant to that song.
Comment: @EvSunWoodard - you mixed up time and key sigs. Not many songs shift between 3/4 and 6/8, as the feel is quite different, and the time sig needs to be there. How does fortissimo affect timing? It's usually bpm ( or 'allegro' here) that dictates speed and tempo. The time sig is a relative thing. This comment is confusing.
Comment: @Tim I'm not saying that this cannot be an engraving error, but I am saying that the composer is a liberty to do basically whatever s/he wants. Many songs change time signature, search songs by Hazo, specifically Sevens, which purposely changes between 7/8 and 3/8 for the change in feel. While the fortissimo doesn't change the timing, without a time signature the director is a liberty to hold the note as long as s/he wants to. So, if you want to make a grand entrance, act as if that eight is a whole note, because it makes no difference without signature. Otherwise, make it short and sweet.
Comment: @EvSunWoodard - in that case, put a fermata over the note. Take a thousand mainstream songs, and I doubt if more than a dozen will have timing changes. Take a load of jazz tunes, you'll find a lot.
Comment: @Tim - I am not advocating for this to be standard practice. Yes, putting a fermata would achieve making it a long note, but it takes away the option. As written, it is optional, the note has NO value, which means the director can choose whatever value they want. A fermata must be held. This is all theoretical, and it is unlikely that this was the composers intent, but it was worth noting that it didn't HAVE to be wrong. Also, even Mozart changed time signatures. Sure you won't find it in pop music, but many classical and neoclassical songs do this. It is relatively standard practice.
Comment: @Tim Even the Beatles used changing meter, in "Here Comes the Sun" they use 11/8, 4/4, 7/8
Comment: @EvSunWoodard - yes, just trawled through over 140 Beatles songs, 7 of which had time sig changes. Hardly commonplace! I guess what I'm saying is that it could have been written in a much more succinct way, rather than that which the composer used (if indeed that's the case!) Usually composers have a shrewd idea of what they want their works to sound like, without giving as much licence as you think this allows. No, it doesn;t HAVE to be wrong, but I bet it is!
Comment: @Tim - It probably is wrong, I agree. But the OP asked what the purpose of the note was. This answer was specific to the piece, and explained that the version was misprinted. I was attempting to explain that while this version may be a misprint, there are other reasons that something like this could happen and the connotations of similar marking.
Answer: It must be an anacrucis, but generally, the time signature is found before the note/s rather than after it. When there is an anacrucis, the last bar usually has enough beats so that the two add up to a full bar. Maybe this way, the package has decided that the last bar will be a full four beats. The 'ff' mark will apply to the next part too, not just the anacrucis.
Comment: Look folks - we know what piece it is.  It's a music engraving error.  End of.
Comment: @Basstickler - doubtful that the time sig before would be 1/8 !  Pickup not to be confused with that found on electric guitars... There's not a lot wrong with anacrucis - literally 'before the downbeat'.
Comment: I think the concept of the anacrusis length being subtracted from the final bar is more of an older concept that doesn't apply so much today, or at least outside of the Classical tradition.  Form is much more loose now.  Regarding the placement of the time signature, is it possible that this is not the beginning of the piece and that we are transitioning from another time signature?  That's the only reason I can think of why it would be written this way.
Comment: Also, for @Jmarkim, this is commonly referred to as a Pickup outside of the academic community.
Comment: I'm thinking that this would be the start of a new section and the previous section could have been in any other time signature. I still wouldn't notate that this way but it's the only thing I can think of to justify it.  The reason I mention Pickup, which is indeed than a pickup on an electric instrument, is that I literally have only ever heard the term anacrusis used in an academic setting (and here on SE), to the point that it's become dorky trivia for me with friends that also have a degree.  This may also be a cultural difference since I'm in America and you're in England.


Relationship between differential forms and cross products

Question: Why can the wedge product $dx\wedge  dy$ be viewed as $\vec{i}\times \vec{j}=$the standard unit vector $ \vec{k}$?
Comment: That's in three dimensions and Cartesian coordinates only.
Answer: Note that both $\wedge$ and $\times$ are antisymmetric and bilinear (the former is it at least for 1-forms). However, $\times$ is only defined in 3 dimensions. In general we have an exterior product, also denoted by $\wedge$, where $u \wedge v$ can be identified with the subspace spanned by $u$ and $v$ together with an orientation of this subspace and a number $|u| |v| \sin\theta(u,v)$ where $\theta(u,v)$ is the angle between $u$ and $v$. Then $\times$ can be seen of exchanging the subspace, which is a plane, with its normal given by the orientation, times the number.
The identification of $dx \wedge dy$ with $\vec i \times \vec j = \vec k$ follows if we identify $dx$ with $\hat x = \vec i$ and $dy$ with $\hat y = \vec j$.


Exchange server and MX record

Question: I recently migrated an Exchange 2007 server to Exchange 2010. After the migration, I accidentally left the MX record pointing to the old Exch 2007 in the domain for an extra day. As the result, some emails might have been directed to the empty old server. The external senders didn't get any undeliverable reports, therefore I assumed the missing emails were "processed" somewhere. Is there any method that I could retrieve those missing emails?
Comment: Is the old server still configured to be authoritative for the domains it received email for?
Comment: no, the authoritative server for the domain is the Exch 2010 server
Answer: Depending on how you performed the migration, that Exchange 2007 server may still be in the Exchange infrastructure, and correctly routed those messages to their home on the Exchange 2010 server. This assumes your migration method involved moving mailboxes from the old server to the new server by native Exchange methods, rather than something else. You can check the Transport Logs on the old server to see what it did with those messages.
Comment: Yes, we moved the mailboxes over the the new server on the same day of migration. I checked the message tracking logs on the old server on the day that old MX record lingered, and some messages were marked "Routing Failed 550 4.4.7 QUEUE.EXPIRED;", even though the original sender never got an ack on failed delivery. What could be doing this?
Answer: If the old IP accepts connections on port 25, then these emails would have been accepted or bounced by that server, depending on its configuration. If it was not accepting port 25 connections, then the senders are likely still spooling and trying to send the message, so changing your MX record to the new server will cause email to flood in.

Exchange server and MX record


The axioms of metric space

Question:
Let $X\neq\emptyset$  and let $\rho:X\times X\longrightarrow \mathbb{R}$
   with the following properties :
a) for $\forall x,y\in X$, $\rho(x,y)\geq 0$
b) for $\forall x,y\in X$, $\rho(x,y) = 0\iff x=y$.
c)  for $\forall x,y,z\in X$, $\rho(x,y)\leq \rho(x,z) + \rho(y,z)$
Show that $\rho$ is a metric on $X$.

I understand that I should show that we can use these three given  axioms to reach to the third one.
I substituted firstly $x=z$ and then $y=z$ in the triangle inequality, but really couldn't reach what I want.
If $x=z$, $\rho(x,y)\leq 0+\rho(y,x)$.
If $y=z$, $\rho(x,y)\leq 0+\rho(x,y)$.
Comment: You only need to prove that $\rho(x,y)=\rho(y,x)$, don't you?
Comment: Yes I know but how
Comment: I was trying to use the given axioms but I couldn't reach to  the wanted axiom.
Comment: @user416990: [**Please, look at how I've edited your question to use LaTeX / MathJax properly**](http://math.stackexchange.com/revisions/28c99ab0-90a7-4a6e-a104-03052663a68d/view-source).
Comment: Ok thanks a lot
Answer: You had a great idea to let $z=x$, and as you saw, you can conclude from statement (c) that for any $x,y\in X$,
$$\rho(x,y)\leq 0+\rho(y,x)$$
But since this is true for any $x$ and $y$, you can use the same $x$ and $y$ just in the other order!
$$\rho(y,x)\leq 0+\rho(x,y)$$
Now you have
$$\rho(x,y)\leq\rho(y,x)\qquad \rho(y,x)\leq \rho(x,y)$$
and the only way both of those things can be true is if $\rho(x,y)=\rho(y,x)$.
Comment: Thanks a lot it what I was trying to prove ...thanks

The axioms of metric space


total probability problem

Question: One bag contains 5 white and 4 black balls. Another bag contains 7 white and 9 black balls. A ball is transferred from the first bag to the second and then a ball is drawn from second. What will be the probability that the ball is white.
Answer: It would be the following: $$P(W) = P(W \cap W_1)+P(W \cap B_1)$$
$$ = P(W|W_1)P(W_1)+P(W|B_1)P(B_1)$$
$$= \frac{5}{9} \frac{8}{17}+ \frac{4}{9} \frac{7}{17}$$
where $W_1$ denotes the event that the first ball chosen is white, $B_1$ denotes the event that the first ball chosen is black, and $W$ denotes the event the the ball from the second bag is white.
Comment: Did you mean $P(W)=P(W|W_1)P(W_1)+P(W|B1)P(B_1)$ ?

total probability problem


Como desativar um campo de texto para edição usando jQuery/JavaScript?

Question: Digamos que eu tenha um formulário com os campos de 1 à 7.
Algo como:
field-1
field-2
field-3
field-4
field-5
field-6
field-7

Todos esses campos estão em um formulário.
Com o Laravel, algumas vezes eu experimentei situações de quando eu desabilito um campo com a propriedade disabled, eu não fui capaz de recuperá-lo através do array Input. Assim, para evitar diretamente esse problema eu gostaria de saber se há, e se houver, como, uma forma de bloquear, via JS/jQuery, que um campo seja editado no formulário. PORÉM, apenas saberei disso (se ele deve ser desabilitado ou não) em tempo de execução.
Ex.: De acordo com o valor do campo field-2 eu posso precisar desativar os campos field-3, field-4 e field-5 para edição, mas ainda precisarei dos seus valores no array INPUT, que serão atribuídos para ter o mesmo valor do field-2, nesse caso.
Não sei se consegui ser claro, mas qualquer dúvida perguntem nos comentários!
Answer: O navegador não envia campos desabilitados com disabled na submissão do formulário, por isso sua primeira tentativa não funcionou.
Por outro lado, você não precisa usar script para impedir a alteração de um campo. Ao invés disso, use o atributo readonly.
Efeitos colaterais:

O usuário poderá, entretanto, clicar e selecionar o conteúdo do campo.
Além disso, os estilos do campo permanecerão os originais, isto é, o usuário poderá não perceber que se trata de um campo somente-leitura. Nesse caso, adicione um estilo para manter a usabilidade, por exemplo, deixando o fundo da caixa um pouco acinzentado.

Exemplo:
<input type="text" value="Valor fixo"
    style="background: #EEE; cursor: not-allowed; color: #777" readonly />

Exemplo de classe CSS para reuso:
.desabilitado {
    background: #EEE;
    cursor: not-allowed;
    color: #777;
}

Dessa forma você pode manter o feedback visual para o usuário.
Veja o exemplo funcional do código acima no jsfiddle.
Considerações de segurança
Alguém pode argumentar que desabilitar campos na tela não é uma boa prática do ponto de vista de Segurança da Informação, pois hoje um usuário pode facilmente burlar essa limitação através da Ferramenta do Desenvolvedor (F12), alterando as propriedades do campo. Isso está correto, em parte.
O importante é entender que a necessidade de desabilitar campos é parte essencial do funcionamento dos sistemas. Não é seu objetivo garantir a segurança da informação daquele campo.
Este artigo tem por objetivo auxiliar o desenvolvedor front-end com um elemento puramente visual e não isenta as validações necessárias no back-end.
Comment: Mas é importante ressaltar que se o usuário tem conhecimento básico de Javascript utilizando o console do navegador o usuário poderá alterar seu campo e enviar junto ao Form.
Comment: Excelente resposta. Muito obrigado!
Answer: Quando disabled é usado em um <input type=text> por exemplo, esse campo não pode ser resgatado pelo $_POST/$_GET. O adequado é usar o atributo readonly, isso garante que o campo seja acessível pelo php, e no HTML ele não poderá ser editado.
<input type="text" id="nome" name="nome" readonly="readonly"  />

Um exemplo utilizando js puro:

    <form>
        <input type="text" id="nome" name="nome"  value="sem edição"/>
        <input type="button" onclick="bloquearInput();" value="bloquear/desbloquear">
    </form>