unpublish node when edit it

Question: I have a content type calles survey, When admin deletes a survey, the survey results should still be accessible and not deleted as well. So I want to unpublish the node when click on the delete button(it will be better to change this delete button to unpublish button). but I dont know how to unpublished a node.
Any solution / alternative / suggestion will be greatly appreciated.
Answer: Hope this will help you, In my case i did it by updating the node and node_revision table's status column set to "0".following code is for form submit action you can do it for your delete action..
function mymodule_form_alter(&$form, &$form_state, $form_id) {
 if ($form_id == 'your form')   {
 $form['#submit'][] = 'mymodule_form_submit';
 }

}

function mymodule_form_submit($form, &$form_state){
if (//your condition)
            {
            $query = db_update('node')
            ->fields(array(
            'status' => 0,//unpublished the node
                ))
            ->condition('nid',$form['nid']['#value'], '=')
            ->execute();

            $query = db_update('node_revision')
            ->fields(array(
            'status' => 0,//unpublished the node
                ))
            ->condition('nid',$form['nid']['#value'], '=')
            ->execute();
            }
        //  drupal_flush_all_caches();

}

Comment: hi madhurjya,thanks for your answer,i've tried your code in my site,it can update the status,but what I want is to hidden the delete button,it seems no work on this. so I tried other ways. and Thanks again.
Comment: ok...you can unset the delete button...any way finally you got your goal.even i got an another option from Jayendra Kainthola. Thanks to him.
Answer: You can find below code snippets for unpublished node.
function custom_feature_form_alter(&$form, &$form_state, $form_id) {

  if ($form_id == 'article_node_form') {

    $form['actions']['delete']['#submit'] = array('custom_feature_node_delete_submit');

  }

}

function custom_feature_node_delete_submit($form, &$form_state) {

  $form_state['values']['status'] = 0;

  $node = node_form_submit_build_node($form, $form_state);
  node_save($node);

  $form_state['redirect'] = node_access('view', $node) ? 'node/' . $node->nid : '<front>';

}

Kindly see that you need to change article_node_form with your node edit form id.
If you do not know, how to check form id, you can use print $form_id in custom_feature_form_alter() function.
Comment: hi Jayendra,thanks for your answer. I used the module 'publish button' for my special content type and it works for me. And still thank you.

unpublish node when edit it


Dúvida de acessar o this em prototype

Question: Estou tentando acessar algumas variáveis dentro do this (Orientação a Objeto) usando Object.prototype, porem em um certo ponto estou em duvida se estou fazendo da forma correta:
Esta e a função principal:
function smartPlayer(){
    this.trackCurrentInfo;
    this.tracksList;
    this.trackCurrentList;
    this.teste = "Esta tudo ok";

    this.initPlayer();
};

Nesta parte ainda esta tudo ok:
smartPlayer.prototype.initPlayer = function(){
    var self = this;

    /* Event button play */
    playMusic.addEventListener("click", function(){
        if (self.trackCurrentInfo === undefined) {
            self.trackList = getDailyrMusic();
            self.trackCurrentList = 0;
        }

        var track = self.trackList[self.trackCurrentList];
        smartPlayer.prototype._callTrack(self, track);
    });
}

Repare que apenas consigo acessar o this, usando o self = this; Isto é o correto, mas quando chamo a função smartPlayer.prototype._callTrack(self, track);, tenho que passar o self para ainda conseguir acessar a o this da função principal que e: smartPlayer();.
Dentro desta função tenho o seguinte:
smartPlayer.prototype._callTrack = function(self, array){
    /* set current Track infos */
    this.trackCurrentInfo = {
        "trackAlbumId": array.trackId,
        "trackMusic": array.trackName,
        "trackArtist": array.trackArtist,
        "trackAlbum": array.trackAlbum,
        "trackAlbumCover": array.trackCover,
        "trackCurrentTime": 0,
        "trackFullTime": array.trackDuration
    };

    // update elements
    // console.log(this.trackCurrentInfo)
    trackMusic.innerHTML = self.trackCurrentInfo.trackMusic;
    trackArtist.innerHTML = self.trackCurrentInfo.trackArtist;
    trackAlbum.innetHTML = self.trackCurrentInfo.trackAlbum;

}

Esta seria a forma correta de eu conseguir acessar o this dentro de smartPlayer()? Pois desta forma eu terei de ser sempre obrigado a passar o self em todas as funções que estão armazenando algum valor dentro do this.
Encontrei este problema sempre que passo algo dentre as funções(123).
Comment: calltrack e uma funcao dentro de smartplayer?
Comment: a função smartplayer()
Comment: voce nao pode usar o this direto? Ou criar a var self dentro da funcao smartplayer ao inves de dentro do prototipo?
Comment: Não, pois quando uso o this dentro da função que envia um parâmetro ex: func('array'), o this dentro da função fica como this = array.
Answer: O problema é gerado pela natureza do método addEventListener. Quando ele chama a callback que lhe passas o contexto de execução muda (ie: o this). Tens várias maneiras de resolver isso:

usando arrow functions
usando .call, .apply, .bind
usando classes ES6

Exemplos:
Com arrow function:
smartPlayer.prototype.initPlayer = function(){

    /* Event button play */
    playMusic.addEventListener("click", () => { // <---- repara aqui!
        if (this.trackCurrentInfo === undefined) {
            this.trackList = getDailyrMusic();
            this.trackCurrentList = 0;
        }

        var track = this.trackList[this.trackCurrentList];
        this._callTrack(track);
    });
}

Com .bind:
smartPlayer.prototype.initPlayer = function(){
    var self = this;

    /* Event button play */
    playMusic.addEventListener("click", function(){
        if (this.trackCurrentInfo === undefined) {
            this.trackList = getDailyrMusic();
            this.trackCurrentList = 0;
        }

        var track = this.trackList[this.trackCurrentList];
        this._callTrack(self, track);
    }.bind(this)); // <------ repara aqui!
}

Usando ES6:
class smartPlayer {
  constructor() {
    /* Event button play */
    playMusic.addEventListener("click", this.playTrack.bind(this));
  }
  playTrack(nr) {
    if (this.trackCurrentInfo === undefined) {
      this.trackList = this.getDailyrMusic();
      this.trackCurrentList = 0;
    }

    var track = this.trackList[this.trackCurrentList];
    this._callTrack(track);
  }

  getDailyrMusic() {
    // algo...
  }
  _callTrack(self, array) {
    /* set current Track infos */
    this.trackCurrentInfo = {
      "trackAlbumId": array.trackId,
      "trackMusic": array.trackName,
      "trackArtist": array.trackArtist,
      "trackAlbum": array.trackAlbum,
      "trackAlbumCover": array.trackCover,
      "trackCurrentTime": 0,
      "trackFullTime": array.trackDuration
    };

    // update elements
    // console.log(this.trackCurrentInfo)
    trackMusic.innerHTML = this.trackCurrentInfo.trackMusic;
    trackArtist.innerHTML = this.trackCurrentInfo.trackArtist;
    trackAlbum.innetHTML = this.trackCurrentInfo.trackAlbum;
  }
}

Dúvida de acessar o this em prototype


DIsable native app for facebook login (just use pop up)

Question: I have the below code to log into Facebook and get the users email, this works fine when the user does not have the native app installed, it opens the popup and lets the user enter their facebook info.
But when they have the native app it asks for the permissions and the does nothing more.
Seems I have the same issue as How to disable facebook native app for user login as well as Android Facebook authorization - can not log in when official Facebook app is installed
However my code is quite a bit different so I was hope someone could help me force my code to only use the popup.
My code
public class FbLoginActivity extends Activity {

    private static List<String> permissions;
    Session.StatusCallback statusCallback = new SessionStatusCallback();
    ProgressDialog dialog;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.fblogin);
        Button fbButton = (Button) findViewById(R.id.fbshare);
        /***** FB Permissions *****/
        permissions = new ArrayList<String>();
        permissions.add("email");
        /***** End FB Permissions *****/
        fbButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // TODO Check if there is any Active Session, otherwise Open New
                // Session
                Session session = Session.getActiveSession();
                if (session == null) {
                    Session.openActiveSession(FbLoginActivity.this, true,
                            statusCallback);
                } else if (!session.isOpened()) {
                    session.openForRead(new Session.OpenRequest(
                            FbLoginActivity.this).setCallback(statusCallback)
                            .setPermissions(permissions));
                }
            }
        });
        Session session = Session.getActiveSession();
        if (session == null) {
            if (savedInstanceState != null) {
                session = Session.restoreSession(this, null, statusCallback,
                        savedInstanceState);
            }
            if (session == null) {
                session = new Session(this);
            }
            Session.setActiveSession(session);
            session.addCallback(statusCallback);
            if (session.getState().equals(SessionState.CREATED_TOKEN_LOADED)) {
                session.openForRead(new Session.OpenRequest(this).setCallback(
                        statusCallback).setPermissions(permissions));
            }
        }
    }

    private class SessionStatusCallback implements Session.StatusCallback {

        @Override
        public void call(Session session, SessionState state,
                Exception exception) {
            // Check if Session is Opened or not
            processSessionStatus(session, state, exception);
        }
    }

    public void processSessionStatus(Session session, SessionState state,
            Exception exception) {
        if (session != null && session.isOpened()) {
            if (session.getPermissions().contains("email")) {
                // Show Progress Dialog
                dialog = new ProgressDialog(FbLoginActivity.this);
                dialog.setMessage("Logging in..");
                dialog.show();
                Request.executeMeRequestAsync(session,
                        new Request.GraphUserCallback() {

                            @Override
                            public void onCompleted(GraphUser user,
                                    Response response) {

                                if (dialog != null && dialog.isShowing()) {
                                    dialog.dismiss();
                                }
                                if (user != null) {
                                    Map<String, Object> responseMap = new HashMap<String, Object>();
                                    GraphObject graphObject = response
                                            .getGraphObject();
                                    responseMap = graphObject.asMap();
                                    Log.i("FbLogin", "Response Map KeySet - "
                                            + responseMap.keySet());
                                    // TODO : Get Email
                                    // responseMap.get("email");
                                    String fb_id = user.getId();
                                    String email = null;
                                    String name = (String) responseMap
                                            .get("name");
                                    if (responseMap.get("email") != null) {
                                        email = responseMap.get("email")
                                                .toString();
                                        Intent i = new Intent(FbLoginActivity.this, FbLogin2Activity.class);
                                        i.putExtra("Email", email);
                                        startActivity(i);
                                    } else {
                                        // Clear all session info & ask user to
                                        // login again
                                        Session session = Session
                                                .getActiveSession();
                                        if (session != null) {
                                            session.closeAndClearTokenInformation();
                                        }
                                    }
                                }
                            }
                        });
            } else {
                session.requestNewReadPermissions(new Session.NewPermissionsRequest(
                        FbLoginActivity.this, permissions));
            }
        }
    }

    /********** Activity Methods **********/
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        Log.d("FbLogin", "Result Code is - " + resultCode + "");
        Session.getActiveSession().onActivityResult(FbLoginActivity.this,
                requestCode, resultCode, data);
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        // TODO Save current session
        super.onSaveInstanceState(outState);
        Session session = Session.getActiveSession();
        Session.saveSession(session, outState);
    }

    @Override
    protected void onStart() {
        // TODO Add status callback
        super.onStart();
        Session.getActiveSession().addCallback(statusCallback);
    }

    @Override
    protected void onStop() {
        // TODO Remove callback
        super.onStop();
        Session.getActiveSession().removeCallback(statusCallback);
    }

UPDATE
So I do not have an activity set in the Facebook dev settings, which makes sense, so what should I put to as the activity so that the FbLoginActivity processSessionStatus gets fired with the login (So I can get the email address and pass it in)
Answer: If you are using the facebook SDK, then this is the default behavior. If the user has the facebook app installed then it will use the credentials from that and if not, then it will show the popup. This is how it was designed to function since the user shouldn't have to enter his credentials again and again in every app that uses facebook for authentication. If you want to override this behavior, then you will have to fork and modify the SDK itself.
Comment: This shouldnt be the case see the two questions I linked
Comment: Is the app returned to correctly in the web sign up but not returning correctly from the native app? Then it is a potential problem with your Facebook app settings. It needs the full package and class name of the activity that is meant to be returned to.
Answer: Have you put into your Facebook App Settings on Facebook.com the name of the activity that the native facebook app is meant to go to once authentication has completed?
It's possible that it is missing or there is a mistake and results in the native facebook app calling a non-existent activity once the sign on is complete.
Comment: It shouldnt have to call anything surely? as the above code should just get the email from the session and launch the next activity
Comment: Is the app returned to correctly in the web sign up but not returning correctly from the native app? Then it is a potential problem with your Facebook app settings. It needs the full package and class name of the activity that is meant to be returned to.
Comment: Yes the app works fine with the web sign in pop up and native app does nothing. I have not got a activity class in the facebook dev settings so I guess this is the issue, but the question is how do I get it to return to the same activity and fire the processSessionStatus
Comment: fire processSessionStatus in onActivityResult
Answer: @Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    facebook.authorizeCallback(requestCode, resultCode, data);
}

Use this code in the activity where you call facebook login request.
Answer: the answer is:
add this line in your cade
 session.openForRead(new Session.OpenRequest(
                        FbLoginActivity.this).setCallback(statusCallback)
                        .setLoginBehavior(SessionLoginBehavior.SUPPRESS_SSO);// add this line for open only dialog or pop-up
                        .setPermissions(permissions));


Can a player move the ball through the pitch while holding it tightly near his body in football?

Question: I was wondering whether in football one can move the ball through the pitch in an unconventional way, namely by holding it:

on his forehead
between his head and shoulder
between calf and thigh while jumping towards the goal by one foot

Are these things allowed?
Comment: It's not an exact match, but I believe my answer there already covers the salient points raised in this question and therefore is close enough to be marked as a duplicate.
Answer: I think - without scanning the rules myself - that gdrt's reply hits the target: those "tricks" are not effective, so there is no need to exclude them.
My contribution is twofold:
One, if someone found a clever trick allowing to "carry" the ball, just about as easy as carrying it by hand, it almost surely would soon be forbidden in the rules. The spirit of the sport is quite clear, you do not carry the ball (that would be rugby-like, and they split long ago).
Two, some tricks are allowed. Namely, Cuauhtemoc Blanco's jump with the ball between his feet. (see at YouTube - 1 minute) But, there it is, it is not something you would do more than one hop, surely not all the way down the field...


Unusual notation for integer, rational and real numbers (A. J. Moakes M.A., The Core of Mathematics)

Question: I am reading currently an old book: A. J. Moakes M.A., The Core of Mathematics, An introduction to 'modern' mathematics (1964). The author uses some unusual (at least to me) notation for integer, rational and real numbers alike:

Are there other authors that use such a notation? Is just an 'anomaly' of the author's book?
Thanks a lot.
Comment: I *think* Rudin used the notation $J$ for the integers in "baby Rudin." Using the notation $R$ for the rationals, and $R^\#$ for the reals did not age well...
Comment: The usage of Q and Z for rational numbers and integers is usually thought to have started with Bourbaki. In the 60s that french wave may have not have reached the US?
Comment: Birkhoff and maclane's *Survey of Modern Algebra*, from the early 50s and which probably had as much influence on notation choices as on everything else in the US, uses J for the integers
Comment: Well, had it been Ⴑ then we would go as far as that :-)
Comment: @AlexOrtiz  yes,  so far he is using $J$  for the positive integers. I posted as  answer
Comment: @MarianoSuárez-Álvarez  there's no hiding it, we are backwards.
Comment: You are wise. ${}{}$
Answer: page 25 in the third edition of baby Rudin.   Earlier he says properties of the integers will be assumed; from what I can see, he uses integers mostly  as an indexing set for sequences or series, so positive integers. I'll try to find a later page that uses $J$


ActionScript 3: "TypeError: Error #1009: Cannot access a property or method of a null object reference." on switch

Question: I'm writing a simple menu with ActionScript3 and nested switch cases.
What it does is to check the current frame with the selected menu and if the selected menu is referring to another menu, do a transition and then go to selected frame, and if the selected menu is the current frame, traces a simple message.
But when selected menu and current frame are equal, I get this annoying message and I don't know what I have to do to fix the problem.
My code is:
//Import TweenMax
import com.greensock.*;;
import com.greensock.plugins.*;
import flash.events.MouseEvent;

var frameNumber:int = currentFrame;

TweenPlugin.activate([BlurFilterPlugin]);

//Add the buttons into an array
var buttonsArray:Array = new Array(s1t1,s1t2,s1t3,s1t4,s1t5);

//Loop through the buttons array
for (var i:uint = 0; i < buttonsArray.length; i++) {
    //Add event listeners for the button
    buttonsArray[i].addEventListener(MouseEvent.MOUSE_OVER, mouseOverButton);
    buttonsArray[i].addEventListener(MouseEvent.CLICK, buttonClicked);
}

//Move the buttonBackground under the home button (= starting position)
buttonBackground.x = s1t1.x;
buttonBackground.y = s1t1.y;

//Make the buttonBackground a bit bigger than the home button
buttonBackground.width = s1t1.width + 10;
buttonBackground.height = s1t1.height + 10;

//Tween the buttonBackground to a random color using TweenMax
TweenMax.to(buttonBackground, 0.1, {tint: Math.random() * 0xffffff});

//This function is called when the mouse is over a button
function mouseOverButton(e:MouseEvent):void {
    //trace(e.target.name + " was touched!");
    //Assign the button to a local variable
    var button:MovieClip = (MovieClip)(e.target);

    //Calculate the new target width and height for the buttonBackground
    var targetWidth:Number = button.width + 10;
    var targetHeight:Number = button.height + 10;

    //Tween the buttonBackground's position, size and color (color is random)
    TweenMax.to(buttonBackground, 0.5, {x: button.x, y: button.y,
    width:targetWidth, height:targetHeight, tint: Math.random() * 0xffffff});
}

//This function is called when a button is clicked
function buttonClicked(e:MouseEvent):void {
    switch(e.target.name){
        case "s1t1":
            switch (currentFrame){
                case 5:
                    trace("Nowhere to go!");
                break;
                case 6:
                    var myTM:TransitionManager = new TransitionManager(s1text2);
                    myTM.startTransition({type:Fade, direction:Transition.OUT, duration:0.25, easing:Back.easeOut});
                break;
                case 7:
                    var myTM:TransitionManager = new TransitionManager(s1text3);
                    myTM.startTransition({type:Fade, direction:Transition.OUT, duration:0.25, easing:Back.easeOut});
                break;
                case 8:
                    var myTM:TransitionManager = new TransitionManager(s1text4);
                    myTM.startTransition({type:Fade, direction:Transition.OUT, duration:0.25, easing:Back.easeOut});
                break;
                case 9:
                    var myTM:TransitionManager = new TransitionManager(s1text5);
                    myTM.startTransition({type:Fade, direction:Transition.OUT, duration:0.25, easing:Back.easeOut});
                break;
                default:
                    trace("Nowhere to go!");
            }
            frameNumber = 5;
            myTM.addEventListener("allTransitionsOutDone", doneTrans)
        break;
        case "s1t2":
            switch (currentFrame){
                case 5:
                    var myTM:TransitionManager = new TransitionManager(s1text1);
                    myTM.startTransition({type:Fade, direction:Transition.OUT, duration:0.25, easing:Back.easeOut});
                break;
                case 6:
                    trace("Nowhere to go!");
                break;
                case 7:
                    var myTM:TransitionManager = new TransitionManager(s1text3);
                    myTM.startTransition({type:Fade, direction:Transition.OUT, duration:0.25, easing:Back.easeOut});
                break;
                case 8:
                    var myTM:TransitionManager = new TransitionManager(s1text4);
                    myTM.startTransition({type:Fade, direction:Transition.OUT, duration:0.25, easing:Back.easeOut});
                break;
                case 9:
                    var myTM:TransitionManager = new TransitionManager(s1text5);
                    myTM.startTransition({type:Fade, direction:Transition.OUT, duration:0.25, easing:Back.easeOut});
                break;
                default:
                    trace("Nowhere to go!");
            }
            frameNumber = 6;
            myTM.addEventListener("allTransitionsOutDone", doneTrans);
        break;
        case "s1t3":
            switch (currentFrame){
                case 5:
                    var myTM:TransitionManager = new TransitionManager(s1text1);
                    myTM.startTransition({type:Fade, direction:Transition.OUT, duration:0.25, easing:Back.easeOut});
                break;
                case 6:
                    var myTM:TransitionManager = new TransitionManager(s1text2);
                    myTM.startTransition({type:Fade, direction:Transition.OUT, duration:0.25, easing:Back.easeOut});
                break;
                case 7:
                    trace("Nowhere to go!");
                break;
                case 8:
                    var myTM:TransitionManager = new TransitionManager(s1text4);
                    myTM.startTransition({type:Fade, direction:Transition.OUT, duration:0.25, easing:Back.easeOut});
                break;
                case 9:
                    var myTM:TransitionManager = new TransitionManager(s1text5);
                    myTM.startTransition({type:Fade, direction:Transition.OUT, duration:0.25, easing:Back.easeOut});
                break;
                default:
                    trace("Nowhere to go!");
            }
            frameNumber = 7;
            myTM.addEventListener("allTransitionsOutDone", doneTrans);
        break;
        case "s1t4":
            switch (currentFrame){
                case 5:
                    var myTM:TransitionManager = new TransitionManager(s1text1);
                    myTM.startTransition({type:Fade, direction:Transition.OUT, duration:0.25, easing:Back.easeOut});
                break;
                case 6:
                    var myTM:TransitionManager = new TransitionManager(s1text2);
                    myTM.startTransition({type:Fade, direction:Transition.OUT, duration:0.25, easing:Back.easeOut});
                break;
                case 8:
                    trace("Nowhere to go!");
                break;
                case 7:
                    var myTM:TransitionManager = new TransitionManager(s1text3);
                    myTM.startTransition({type:Fade, direction:Transition.OUT, duration:0.25, easing:Back.easeOut});
                break;
                case 9:
                    var myTM:TransitionManager = new TransitionManager(s1text5);
                    myTM.startTransition({type:Fade, direction:Transition.OUT, duration:0.25, easing:Back.easeOut});
                break;
                default:
                    trace("Nowhere to go!");
            }
            frameNumber = 8;
            myTM.addEventListener("allTransitionsOutDone", doneTrans);
        break;
        case "s1t5":
            switch (currentFrame){
                case 5:
                    var myTM:TransitionManager = new TransitionManager(s1text1);
                    myTM.startTransition({type:Fade, direction:Transition.OUT, duration:0.25, easing:Back.easeOut});
                break;
                case 6:
                    var myTM:TransitionManager = new TransitionManager(s1text2);
                    myTM.startTransition({type:Fade, direction:Transition.OUT, duration:0.25, easing:Back.easeOut});
                break;
                case 7:
                    var myTM:TransitionManager = new TransitionManager(s1text3);
                    myTM.startTransition({type:Fade, direction:Transition.OUT, duration:0.25, easing:Back.easeOut});
                break;
                case 8:
                    var myTM:TransitionManager = new TransitionManager(s1text4);
                    myTM.startTransition({type:Fade, direction:Transition.OUT, duration:0.25, easing:Back.easeOut});
                break;
                case 9:
                    trace("Nowhere to go!");
                break;
            }
            frameNumber = 9;
            myTM.addEventListener("allTransitionsOutDone", doneTrans);
        break;
    }
}
function doneTrans(e:Event):void{
    trace("Going frame: "+frameNumber);
    gotoAndStop(frameNumber);
}

I'm using Flash CS5 and "greensock" plugin and my error is:
TypeError: Error #1009: Cannot access a property or method of a null object reference.
        at _009_fla::MainTimeline/buttonClicked()

Answer: the problem is when you add an event listener to myTM when its not there (when clicking the menu button for the current page) so I made a quick fix by checking if myTM is instantiated (not null) and if so add the event listener, hope it fixes your problem.
replace your buttonClicked function with this one:
function buttonClicked(e:MouseEvent):void {
    //declaring new variables inside conditional cases is a bad practice
    var myTM:TransitionManager;
    switch(e.target.name){
        case "s1t1":
            switch (currentFrame){
                case 5:
                    trace("Nowhere to go!");
                break;
                case 6:
                    myTM = new TransitionManager(s1text2);
                    myTM.startTransition({type:Fade, direction:Transition.OUT, duration:0.25, easing:Back.easeOut});
                break;
                case 7:
                    myTM = new TransitionManager(s1text3);
                    myTM.startTransition({type:Fade, direction:Transition.OUT, duration:0.25, easing:Back.easeOut});
                break;
                case 8:
                    myTM = new TransitionManager(s1text4);
                    myTM.startTransition({type:Fade, direction:Transition.OUT, duration:0.25, easing:Back.easeOut});
                break;
                case 9:
                    myTM = new TransitionManager(s1text5);
                    myTM.startTransition({type:Fade, direction:Transition.OUT, duration:0.25, easing:Back.easeOut});
                break;
                default:
                    trace("Nowhere to go!");
            }
            frameNumber = 5;
            //myTM.addEventListener("allTransitionsOutDone", doneTrans)
        break;
        case "s1t2":
            switch (currentFrame){
                case 5:
                    myTM = new TransitionManager(s1text1);
                    myTM.startTransition({type:Fade, direction:Transition.OUT, duration:0.25, easing:Back.easeOut});
                break;
                case 6:
                    trace("Nowhere to go!");
                break;
                case 7:
                    myTM = new TransitionManager(s1text3);
                    myTM.startTransition({type:Fade, direction:Transition.OUT, duration:0.25, easing:Back.easeOut});
                break;
                case 8:
                    myTM = new TransitionManager(s1text4);
                    myTM.startTransition({type:Fade, direction:Transition.OUT, duration:0.25, easing:Back.easeOut});
                break;
                case 9:
                    myTM = new TransitionManager(s1text5);
                    myTM.startTransition({type:Fade, direction:Transition.OUT, duration:0.25, easing:Back.easeOut});
                break;
                default:
                    trace("Nowhere to go!");
            }
            frameNumber = 6;
            //myTM.addEventListener("allTransitionsOutDone", doneTrans);
        break;
        case "s1t3":
            switch (currentFrame){
                case 5:
                    myTM = new TransitionManager(s1text1);
                    myTM.startTransition({type:Fade, direction:Transition.OUT, duration:0.25, easing:Back.easeOut});
                break;
                case 6:
                    myTM = new TransitionManager(s1text2);
                    myTM.startTransition({type:Fade, direction:Transition.OUT, duration:0.25, easing:Back.easeOut});
                break;
                case 7:
                    trace("Nowhere to go!");
                break;
                case 8:
                    myTM = new TransitionManager(s1text4);
                    myTM.startTransition({type:Fade, direction:Transition.OUT, duration:0.25, easing:Back.easeOut});
                break;
                case 9:
                    myTM = new TransitionManager(s1text5);
                    myTM.startTransition({type:Fade, direction:Transition.OUT, duration:0.25, easing:Back.easeOut});
                break;
                default:
                    trace("Nowhere to go!");
            }
            frameNumber = 7;
            //myTM.addEventListener("allTransitionsOutDone", doneTrans);
        break;
        case "s1t4":
            switch (currentFrame){
                case 5:
                    myTM = new TransitionManager(s1text1);
                    myTM.startTransition({type:Fade, direction:Transition.OUT, duration:0.25, easing:Back.easeOut});
                break;
                case 6:
                    myTM = new TransitionManager(s1text2);
                    myTM.startTransition({type:Fade, direction:Transition.OUT, duration:0.25, easing:Back.easeOut});
                break;
                case 8:
                    trace("Nowhere to go!");
                break;
                case 7:
                    myTM = new TransitionManager(s1text3);
                    myTM.startTransition({type:Fade, direction:Transition.OUT, duration:0.25, easing:Back.easeOut});
                break;
                case 9:
                    myTM = new TransitionManager(s1text5);
                    myTM.startTransition({type:Fade, direction:Transition.OUT, duration:0.25, easing:Back.easeOut});
                break;
                default:
                    trace("Nowhere to go!");
            }
            frameNumber = 8;
            //myTM.addEventListener("allTransitionsOutDone", doneTrans);
        break;
        case "s1t5":
            switch (currentFrame){
                case 5:
                    myTM = new TransitionManager(s1text1);
                    myTM.startTransition({type:Fade, direction:Transition.OUT, duration:0.25, easing:Back.easeOut});
                break;
                case 6:
                    myTM = new TransitionManager(s1text2);
                    myTM.startTransition({type:Fade, direction:Transition.OUT, duration:0.25, easing:Back.easeOut});
                break;
                case 7:
                    myTM = new TransitionManager(s1text3);
                    myTM.startTransition({type:Fade, direction:Transition.OUT, duration:0.25, easing:Back.easeOut});
                break;
                case 8:
                    myTM = new TransitionManager(s1text4);
                    myTM.startTransition({type:Fade, direction:Transition.OUT, duration:0.25, easing:Back.easeOut});
                break;
                case 9:
                    trace("Nowhere to go!");
                break;
            }
            frameNumber = 9;
            //myTM.addEventListener("allTransitionsOutDone", doneTrans);
        break;
    }

    //if myTM is not null (not empty) add the event listener
    if (myTM)
    {
        myTM.addEventListener("allTransitionsOutDone", doneTrans);
    }
}

there's a lot of room for improvement in your code, for example it can be redone to use just one switch or many better approaches, but I don't want to heavily change your code.
Comment: Hi, Thanks. It fixed my problem. I really appreciate your help and as soon as I get enough reputation, I will vote-up your answer.. thanks again. and I'll be glad if you improve it and I learn my mistakes in programming.


jQuery: Set top position to 1/2 the difference between contained child element and parent

Question: Ok, so I have some popup bubble effects with absolutely positioned and hidden child elements called div.caption.  div.caption has a parent element named a.logo.
I want to subtract the height of div.caption from  a.logo and set.css("top",..) to be HALF of that number.
For example:
a.logo = 200px (height)
div.caption - 250px (height)
-( (250 - 200)/2 ) = -25
The result should be vertical centering of the child in relation to the parent (despite the fact that it overflows the parent.
I have the following HTML

Caption Text

Caption Text

Caption Text

and jQuery
$("div.caption").each(function() {
    var theHeight = $(this).height();
    var container = $('this').closest('a.logo').height();
    if( theHeight > container ) {
        $(this).css("top",-( (theHeight-container)/2 ) + "px");
    }
});

What's really baffling me is that $(this).closest('a.logo') is returning 40px for height(); but the DOM reports 200px for the elements height.
Somehow my targeting for the variables is off, but I need to use .this() since there are multiple instances of all of these targets and I need to set the top property individually.
Answer: Remove the quotes around this. Your code is currently looking for an element <this>, and finding the closest a.logo, which does not exist. height is set to null, which evaluates to zero in a numeric context.
var container = $(this).closest('a.logo').height();

Comment: I thought "WOW, such a stupid mistake!" but that doesn't fix it unfortunately, still returning the same 40px value which is seemingly incorrect and causing the centering effect to fail.
Comment: Actually, here is a better illustration of the problem: http://jsfiddle.net/hvJ8M/3/ ... Absurdly, I can copy this directly into my working code and it doesn't work, even though it DOES work in the JSFiddle demo...
Comment: Are you sure that you're selecting the right elements in your real code? Add `background:red` (or some sort of identifier) in your real code, to see what elements are affected. Also, which browser?
Comment: Yeah, I know that seems like it's the case but I can't find anything different or mis-targeted in my real code ... hmm
Comment: Here's the full HTML copied from the site:

We LOVE WordPress and recommend it as our CMS of choice for projects of all sizes.
Comment: and I did add `css("background","red")` successfully get red divs
Comment: @Brian Let's discuss further at this channel: http://chat.stackoverflow.com/rooms/4632/rob-w-and-brian


Unexpected Indent Error on Python SQLITE

Question: I'm working on a Thinkful challenge. Here are the instructions:

Write a script called "database.py" to print out the cities with the
  July being the warmest month. Your script must:
Connect to the database  Create the cities and weather tables (HINT:
  first pass the statement DROP TABLE IF EXISTS ; to remove
  the table before you execute the CREATE TABLE ... statement) Insert data into the two tables  Join the data together  Load into a pandas DataFrame

Here is the error
Aschs-MacBook-Air:dbs aschharwood$ python database.py
  File "database.py", line 20
    cols = [desc[0] for desc in cur.description]
    ^
IndentationError: unexpected indent

Here is the code:
import sqlite3 as lite

# Here you connect to the database. The `connect()` method returns a connection object.
con = lite.connect('get_started.db')

with con:

    cur = con.cursor()
    cur.execute("DROP TABLE IF EXISTS cities")
    cur.execute("DROP TABLE IF EXISTS weather")
    cur.execute("CREATE TABLE cities (name text, state text)")
    cur.execute("CREATE TABLE weather (city text, year integer, warm_month text, cold_month text)")
    cur.execute("INSERT INTO cities VALUES('Washington', 'DC')")
    cur.execute("INSERT INTO cities VALUES('Houston', 'TX')")
    cur.execute("INSERT INTO weather VALUES('Washington', 2013, 'July', 'January',)")
    cur.execute("INSERT INTO weather VALUES('Houston', 2013, 'July', 'January',)")
    cur.execute("SELECT * FROM cities LEFT OUTER JOIN weather ON name = city")

    rows = cur.fetchall() #grabbing all the rows
    cols = [desc[0] for desc in cur.description]
    df = pd.DataFrame(rows, columns=cols)

    print(df)

What am I doing wrong?
Your help is much appreciated!!!
Comment: The IndentationError might be due to mixing tabs and spaces. Run `python -t database.py`. The `-t` flag tells python to warn if the source file mixes tabs and spaces for indentation.
Comment: If it turns out that the IndentationError is due to mixing tabs and spaces, you could use [autope8 or reindent.py](http://stackoverflow.com/a/2625361/190597) to convert the tabs to spaces.
Comment: This is definitely the issue. Seemed to have happened when I did the copy and paste from one .py file to another. Thanks!
Answer: So it turns out that this was a copy paste issue in my text editor, Sublime Text. I copied some code from one file to another. And while it did not look like there was an indent issue, the text editor seemed to be reading it as so.


Banco de Dados para Enquete

Question: Estou fazendo um sistema de questionário e estou com dificuldades modelar a base de dados. Preciso que meu sistema seja "inteligente" a ponto de fazer perguntas diferentes de acordo com as respostas.
Por exemplo, minha primeira pergunta sempre será:
Você é um?

Homem
Mulher

Caso a resposta a pergunta ID 1 seja: Homem. Farei a pergunta ID 2:
Dos itens abaixo, por qual você mais se interessa?

Esportes
Video Games
Viagens

Ao responder a pergunta ID 2 com Esportes, farei a pergunta ID 3.
Qual esporte?

Futebol
Corrida
Luta

Agora voltando para a pergunta ID 1 em outro cenário. Caso a resposta seja Mulher. Farei a pergunta ID 2:
Dos itens abaixo, por qual você mais se interessa?

Esportes
Gastronomia
Viagens
Estética

Caso a resposta seja Viagens farei a pergunta ID 4
Qual destes destinos você gostaria de conhecer?

Dubai
China
Paris

Perceba que tenho perguntas iguais com respostas diferentes. E a combinação de uma pergunta com uma resposta deve determinar qual será a próxima pergunta, ou seja, tenho perguntas que serão exibidas apenas em determinadas situações. E uma mesma pergunta pode conter respostas diferentes dependendo da resposta à pergunta anterior.
Comment: Você tem alguma coisa que já fez? Mostra aí. Essencialmente precisa ter uma ou mais colunas que determine(m) a dependência. Esta(s) coluna(s) precisa(s) indicar qual é a questão e a resposta que precisa ter sido respondida para aquela pergunta ser feita. É possível fazer isto nas respostas também, mas acho pouco provável que seja útil modificar as respostas possíveis, é mais fácil escolher só qual pergunta é condicional. Como você está fazendo. Se tiver situações mais complexas para determinar quais perguntas serão ativadas, aí complica bem e só com mais detalhes para responder.
Answer: Alberto, apesar de duas perguntas terem exatamente o mesmo texto e do ponto de vista do usuário elas serem a mesma, a nivel de banco de dados elas não precisam ser a mesma pergunta.

Segue o script de criação das tabelas para o SQL-Server:
CREATE SCHEMA [quiz]
GO
/****** Object:  Table [quiz].[Pergunta]    Script Date: 1/13/2016 9:06:19 AM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [quiz].[Pergunta](
    [PerguntaID] [int] IDENTITY(1,1) NOT NULL,
    [Descricao] [varchar](255) NOT NULL,
 CONSTRAINT [PK_Pergunta] PRIMARY KEY CLUSTERED
(
    [PerguntaID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]

GO
SET ANSI_PADDING OFF
GO
/****** Object:  Table [quiz].[Resposta]    Script Date: 1/13/2016 9:06:19 AM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [quiz].[Resposta](
    [RespostaID] [int] NOT NULL,
    [PerguntaID] [int] NOT NULL,
    [Descricao] [varchar](255) NOT NULL,
    [PerguntaProximaID] [int] NULL,
 CONSTRAINT [PK_Resposta] PRIMARY KEY CLUSTERED
(
    [RespostaID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]

GO
SET ANSI_PADDING OFF
GO
/****** Object:  Index [IX_Resposta_PerguntaID]    Script Date: 1/13/2016 9:06:19 AM ******/
CREATE NONCLUSTERED INDEX [IX_Resposta_PerguntaID] ON [quiz].[Resposta]
(
    [PerguntaID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
GO
/****** Object:  Index [IX_Resposta_PerguntaProximaID]    Script Date: 1/13/2016 9:06:19 AM ******/
CREATE NONCLUSTERED INDEX [IX_Resposta_PerguntaProximaID] ON [quiz].[Resposta]
(
    [PerguntaProximaID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
GO
ALTER TABLE [quiz].[Resposta]  WITH CHECK ADD  CONSTRAINT [FK_Resposta_Pergunta] FOREIGN KEY([PerguntaID])
REFERENCES [quiz].[Pergunta] ([PerguntaID])
GO
ALTER TABLE [quiz].[Resposta] CHECK CONSTRAINT [FK_Resposta_Pergunta]
GO
ALTER TABLE [quiz].[Resposta]  WITH CHECK ADD  CONSTRAINT [FK_Resposta_Pergunta_Proxima] FOREIGN KEY([PerguntaProximaID])
REFERENCES [quiz].[Pergunta] ([PerguntaID])
GO
ALTER TABLE [quiz].[Resposta] CHECK CONSTRAINT [FK_Resposta_Pergunta_Proxima]
GO

Se preferir, a Tabela Pergunta pode ter uma coluna ProximaPerguntaID que servirá de valor default caso a coluna ProximaPerguntaID da tabela Resposta não for informado.

Banco de Dados para Enquete


What are the implications of sampling to attain a given distribution in one variable?

Question: Some while ago I attended a presentation of a case-control study for which enrolment was still in progress.
The lecturer, a PhD student with basic statistical education, mentioned that while in the treatment group, age was already normally distributed, the corresponding distribution in the control group was still far from normal, and therefore they were actively searching for people with the "right" age to get that nice Gaussian curve.
I have a strong feeling that proceeding in this fashion is at best problematic:  Sampling this way is neither random nor independent, and age is normally distributed neither in the general population (from which the control group presumably is recruited) nor in patients with that disease (whose incidence is, of course, age-dependent).
On the other hand, maybe it is not problematic at all, as it could be seen as simply matching cases to controls.
I'm unsure of the implications for different analyses, in particular: Would one expect that inference on a treatment effect would be affected (age is a strong predictor of course of disease)?
Comment: I'm puzzled by the whole tale. Why on earth would he need age to be remotely normal in the first place?
Comment: My guess is that the reasons are more psychological than statistical. The people conducting this study are MDs with very basic statistical expertise. I've observed several times that the normal distribution is the a priori "right distribution" for the statistically less adept.
Comment: I suppose there's some model for which he (or she) is assuming the independent variables need to be normal (which is certainly not the case for any model he's likely to want).
Answer: There is a common phenomenon among many statisticians and non-statisticians called leptokurtophobia:

The symptoms of leptokurtophobia are (1) routinely asking if your data are normally distributed and (2) transforming your data to make them appear to be less leptokurtic and more "mound shaped.

http://www.qualitydigest.com/inside/twitter-ed/do-you-have-leptokurtophobia.html#
I think this guy took it to the next level.
In some cases people assume normallity of the observations only because it simplifies their calculations in spite of clear evidence of departures from this assumption.
Besides possible misconceptions or other errors in the modelling, the immediate implications are:

They are inducing a bias by selecting people in order to obtain data where they can use the models they "know". Ideally, statistics work the other way around: collecting data with a purpose in mind $\rightarrow$ statistical modelling.
The conclusions drawn have to be changed to something like: if we sample in such a way that we obtain a normal sample, then ... Which may not be that useful.

There are many ways to modelling departures from normallity but specially non-statisticians are affraid of using them since they are typically more complicated.
Of course, there are cases where the Central Limit Theorem or some other (asymptotic) result make the assumption of normallity rather mild. However, we have to keep in mind that this is not always the case.
Comment: "*Some people assume normallity simply because it simplifies their calculations*"-- in a study where age is presumably a predictor (IV), *what calculations could it simplify*?
Comment: @Glen_b As you wisely noticed, their problem is in the modelling. For this reason I included the sentence *Besides possible misconceptions or other errors in the modelling*. I am discussing the divinisation of the normallity assumption. I am in agreement with you, then it is not necessary to answer that question :)
Comment: Ah, I gather you intended "is perceived to simplify ..." or something along those lines, then. Okay.
Comment: @Glen_b Sort of. I meant "In some cases people assume normallity of the observations only because it simplifies ..." *Pardon my French!*.


MySql displaying results in same order no matter "array-order"

Question: I am using "solr" search engine to query an index for classifieds that match a given criteria. The results are the ID:numbers of the classifieds, which I then use to find all matches in a MySql database with those ID:s.
The ID:s returned are put into an array.
As you can see below the array is imploded.
Then I use the "IN" to find all matches.
$solr_id_arr_imploded = implode("', '", $solr_id_arr);
$query = "SELECT mt.*, $sql_tbl.* FROM classified mt LEFT JOIN $sql_tbl ON
$sql_tbl.classified_id = mt.classified_id WHERE mt.ad_id IN ('$solr_id_arr_imploded')";

$sql_tbl is the category chosen by the user, in this case lets say it is "cars".
My problem is this:
I have the ID:numbers in an order (inside the array), but MySql doens't "care" about this order. MySql displays the oldest item first no matter what order the array is in.
So here is one same query displayed with two different "array-directions":
SELECT mt.*, fordon.* FROM classified mt LEFT JOIN fordon ON fordon.classified_id = mt.classified_id WHERE mt.ad_id IN ('Bmw_520i_Svensksald_784332731', 'Bmw_M3_Svensksald_755599519', 'Bmw_M3_E46_Full-utrustad_338210082')

SELECT mt.*, fordon.* FROM classified mt LEFT JOIN fordon ON fordon.classified_id = mt.classified_id WHERE mt.ad_id IN ('Bmw_M3_E46_Full-utrustad_338210082', 'Bmw_M3_Svensksald_755599519', 'Bmw_520i_Svensksald_784332731')

As you can see the ID:s are reversed in the second query above... But they are still displayed in the same order anyways. Why?
Should I use some other method of finding all MySql matches with ID:s from an array?
Ideas?
Thanks
Answer: This should do it:
SELECT mt.*, $sql_tbl.* FROM classified mt
LEFT JOIN $sql_tbl
ON $sql_tbl.classified_id = mt.classified_id
WHERE mt.ad_id IN ('$solr_id_arr_imploded')
ORDER BY FIELD(mt.ad_id,'$solr_id_arr_imploded')

See Order By Field in Sorting Rows.
Answer: MySQL will return the data in the order it "wants" (I suppose it'll be the order of the clustered index, or something like that), if you do not specify an order by clause.
If you want to change the order in which MySQL returns the results, you'll have to add an order by clause.

If that's not possible in your case, you'll have to re-order the elements from the PHP code -- for instance, instead of displaying the results from what MySQL returns, you should iterate over the list of ids returned by Solr, and display the results starting from there.
Basically, you'll first execute the MySQL query to fetch the results :
SELECT mt.*, fordon.*
FROM classified mt
    LEFT JOIN fordon ON fordon.classified_id = mt.classified_id WHERE mt.ad_id IN (
        'Bmw_520i_Svensksald_784332731', 'Bmw_M3_Svensksald_755599519',
        'Bmw_M3_E46_Full-utrustad_338210082'
    )

Then you can loop over those results, in PHP, storing them in an associative array (pseudo-code) :
$hash = array();
foreach ($db_results as $elem) {
    $hash[$elem->ad_id] = $elem;
}

$hash will contain the data, indexed by id.
And, then, you'll display the data, using what Solr returned as a starting point for the loop (pseudo-code) :
foreach ($solr_results as $id_solr) {
    echo $hash[$id_solr]->some_field . '
';
}

With this, you will :

display the results in the order returned by Solr
not do an additionnal (and possibily costly) sort on the database-side.


Apache tomcat server win8 cannot be accessed outside of local host

Question: I have installed the apache-tomcat server on my local win7. The port I specified is 9999. Additionally, I use the distributed binary version of apache tomcat. Not installing as a windows service.
I can access my service by http://localhost:9999 and http://myIPAddress:9999
But I cannot access my apache server from other computers. I searched on the internet, and found I should add a firewall inbound rule in its advanced settings.

Right click "Inbound Rules" on the left pane
Choose "New Rule"
Choose "Port"
Under "Specific ports" enter your port number (9999)
Continue with "Next" until the end of the wizard, naming the rule
when asked.

After doing this, it still doesn't work!!
I have checked with "netstat -na" to see that:
TCP    0.0.0.0:9999           0.0.0.0:0              LISTENING
Then only method I find by far is turning off my windows firewall! But this is not preferred since the potential security risk.
Some online post refers to httpd.conf file. But my apache-tomcat have no such kind of fire.
Could someone give me some hints?

EDIT:
There are three places related to port number setting in the /conf/server.xml file.
<Server port="8005" shutdown="SHUTDOWN">
<Connector port="9999" protocol="HTTP/1.1"
                   connectionTimeout="20000"
                   redirectPort="8443" />// I change the 8080 to 9999 for my own use.
<Connector port="8009" protocol="AJP/1.3" redirectPort="8443" />
Comment: This has nothing to do with your tomcat configuration.  Access is being blocked when you enable the firewall, and it's being allowed when the firewall is down.
Comment: So when you turned your firewall off, it worked?
Comment: Eh, 9999 and 8009 aren't the same...
Comment: @DanilaLadner yes. if i turned off windows firewall, it will work fine. But this is not really secure for my own computer.
Comment: @ChrisS Sorry, it is a typo. 8009 is another port listening.
Comment: So this is obviously an issue with the firewall - can you give your detailed configuration?  It's difficult to answer without getting more details.
Comment: @tdk2fe what do you mean by detailed configuration? I EDIT my post to give the port configuration part of /conf/server.xml file.
Answer: The 8080 is the tomcat port.
Should allow the Tomcat on the firewall (it is not allowed by default)...
Firewall - Allow an app or feature through Windows Firewall - Another program - browse Tomcat7.exe (i.e. c:\xampp\tomcat\bin\Tomcat7.exe)  if you enabled it as a service or Tomcat7w.exe when it is not a service...
Hope this will help.
Answer: Use the Advanced Firewall interface, make sure the profile (private, public, etc) matches what zone the interface is associated with in the Network and Sharing Center, then verify there is an enabled rule that allows the protocol and port (TCP 9999). tdk2fe is right, if it works with the firewall off, the app is configured correctly and the issue is in the firewall.
**Reading your post again, make SURE the rule you added was enabled...
Comment: What you mentioned here are all confirmed by me. I even checked the private, public, domain boxes. And the inbound rule is TCP 9999. It is enabled. This is really tough question.
Comment: The issue is definitely in the firewall since it works when that is disabled. You also have some other ports listed such as 8009 and 8443, you may need to include these in ENABLED allow firewall rules with the appropriate interface, zone, subnet(s), etc...


php pop up box after if statement?

Question: I am doing some php to make an app and i need a window to pop up when i run my php if statement. At the minute, when i run the app, my if statement works, but goes to a new page to display the info from my if statement. How would i change my echo to have a box pop up with the message instead?
Hope that makes sense.
my if statement:
<?php

$status = $_POST['status'];

if($status == "")

echo "Please enter a status.";

else {

echo "Thanks.";

}

?>

again, just to clarify, i would like my echo statements to be a pop up message box instead, i tried to use alert but that threw errors, i have looked around but cant seem to find a php pop up box.
Comment: PHP runs on the server and then delivers the content to the user. The only way the User can input something back to the server is through a GET or POST request. You will not be able to pop-up/alert from PHP and have the user insert a value then. Instead you will need to use PHP to detect the missing variable, output a HTML/Javascript popup and then have that post the value back to the PHP script.
Answer: PHP is more of a "server side" language that runs business logic. If you want a popup you will have to do it with javascript.
Perhaps something like the following:
<?php
$status = $_POST['status'];

if($status == "")

?>

<?php

else {

echo "Thanks.";

}

?>

Answer: Using PHP and javascript, you can alert something like this:
<?php

    $status = $_POST['status'];

    if($status == "")

        $msg = "Please enter a status.";

    else {

        $msg = "Thanks.";

    }

?>

php pop up box after if statement?


datagridview index change

Question: How to change the current row of a datagridview in c# by clicking on a button?
Answer: If you mean changing the selected row index, this should work:
private void button_Click(object sender, EventArgs e)
{
    grid.ClearSelection();
    // Select the third row.
    grid.Rows[2].Selected = true;
}

If you'd like to swap rows (e.g., interchange data in 1st and 3rd rows), here's an option:
int currentRowIndex = 0;
int newRowIndex = 2;

var currentRow = grid.Rows[currentRowIndex];
var rowToReplace = grid.Rows[newRowIndex];

grid.Rows.Remove(currentRow);
grid.Rows.Remove(rowToReplace);
grid.Rows.Insert(currentRowIndex, rowToReplace);
grid.Rows.Insert(newRowIndex, currentRow);

Comment: I wana change the current row. For example the current row position is 5 I want to change it to 8.
Comment: @user1235144: What do you mean? You mean moving the row with its data to a different position or just changing the selection?
Comment: Just changing the small black arrow to another record.
Comment: @user1235144: I added a snippet for swapping rows to my answer. Please see if it is what you're looking for.
Comment: I think you didn't understand my Question. I have button with it's name NEXT. And I have a grid view. I want the snippet to go to the next record when the user clicks NEXT. I want to move across the records. –
Answer: +1 Yuriy
Also if you wish to move the selection arrow and your row isn't visible then:
grid.FirstDisplayedScrollingRowIndex = grid.Rows[2].Index;
DataGgridridView1.Refresh()
grid.CurrentCell = grid.Rows[2].Cells(1) // need to ensure that this is an existing, visible cell

grid.Rows[2].Selected = True

datagridview index change


more than one build in queue for specific job in jenkins

Question: I have a job which I trigger with parameters from another job using wget. each time I give the job different parameter - which svn revision to run with.
I don't want to allow concurrent runs of the same job, but I want to allow more than one pending build in the queue for the job.
From what I have tried it didn't work, I see in the queue only one build of the job pending, no matter how many builds I trigger.
Is it possible with any plugin?
Comment: What exactly didn't work? Requests for build of the same job are queued and are not run concurrently.
Comment: I see in the queue only one build of the job pending, no matter how many builds I trigger
Comment: What URL are you passing to wget?
Comment: `http://myhost:8080/job/jnb_nbflow/buildWithParameters?jnb_revision=$SVN_REVISION`
Answer: Jenkins doesn't place a build in the queue if it already contains one with the same param values.
To trick it, you could add an additional, unused param, and set it to a random value when calling wget.
Comment: Thanks, same when running form Jenkins web UI
Answer: I needed to do the same, and discovered the Random String Parameter Plugin. This adds a random string to each build as a parameter, which is enough to make each build unique and for Jenkins to queue them independently rather than coalesce them.
Comment: Do not forget to activate the option 'This project is parameterized' with the 'Ranom String Parameter' to the job configuration


The diophantine equation $z^2=a^2+bx^2+cy^2$

Question: Is there a way to obtain (enumerate) the integer solutions $(x,y,z)$ of the following quadratic Diophantine equation
$z^2=a^2+bx^2+cy^2$
where $a$ is an integer and $b, c$ are positive integers?
I have checked the literature on Diophantine equations but could not find anything useful. Any help or suggestions would be greatly appreciated.
Comment: Did you see [Legendre's theorem](https://www.google.fr/search?sourceid=chrome-psyapi2&ion=1&espv=2&es_th=1&ie=UTF-8&q=legendre%27s%20theorem%20about%20diophantine%20equations)
Comment: Of course you can solve it.  The only cumbersome formula. And decisions are determined by Pell equations.  For example for some simple cases, you can write.  http://math.stackexchange.com/questions/351491/integral-solutions-of-hyperboloid-x2y2-z2-1/709219#709219  http://math.stackexchange.com/questions/298053/quadratic-diophantine-equations/710766#710766   http://math.stackexchange.com/questions/74931/integral-solutions-of-x2y21-z2/789972#789972
Answer: I think you can at first solve the well known equation $w^{2} + a^{2} = z^{2}$  for convenient values of a and go after to the equation $w^2 = bx^2 + cy^2$ which is solved in the book of L. J. Mordell "Diophantine Equations" (Academic Press. London and New York, 1969 page 44).
Answer: We have at least two, $(0,0,a)$ and $(0,0,-a).$
We have infinitely many solutions to
$$ b x^2 + c y^2 - z^2 = -a^2.  $$
It is possible, however, that no solutions need be primitive: under some choices of $a$ it may be that all solutions have $x,y,z$ all divisible by $a.$ An early example of this (not quite the pattern your form takes) is due to C. L. Siegel, see pages 168 and 253 in CASSELS.
Actually, an easy example is given by
$$ 3 x^2 + 3 y^2 - z^2 = -9.  $$
We see immediately that $z^2$ is divisible by $3,$ therefore $z$ is divisible by $3.$ As a result, $3x^2 + 3 y^2$ is divisible by $9,$ so that $x^2 + y^2$ is divisible by $3.$ Since Legendre symbol $(-1|3) = -1,$ we see that $x,y$ are also both divisible by $3.$
Find a solution ( the smallest one with $u,v > 0$ is best) to $u^2 - b v^2 = 1.$
We can now replace any of the  solutions we have found so far with
$$(x,y,z) \mapsto   (ux+vz,y, bvx+uz). $$
Find a solution ( the smallest one with $p,q > 0$ is best) to $p^2 - c q^2 = 1.$
We can  replace any of the  solutions we have found so far with
$$(x,y,z) \mapsto   (x,py+qz, cqy+pz). $$


get PChar argument back from Delphi DLL in my Python script

Question: Let say that I've this function in a DLL
function test_3(sInput, sOutput : PChar; sSize : int64): Integer; stdcall;
var
  sTmp : string;
  fText : TextFile;
begin
  sTmp := '+++ ' + sInput + ' +++';
  StrPLCopy(sOutput, PChar(sTmp), sSize);
  Result := 69;
  AssignFile(fText, 'test.txt');
  Rewrite(fText);
  Writeln(fText, 'in: ' + sInput);
  Writeln(fText, 'out: '  + sOutput);
  CloseFile(fText);
end;

In my Delphi program, I call it like this
…
  Input := EdtIn.Text;
  OutputSize := Input.Length + 8;
  Output := AllocMem(OutputSize);
  RC := test_3(PChar(Input), Output, OutputSize);
  EdtOut.Text := Output;
  FreeMem(Output);

and it works quite well. Now I want to call the function from a Python script.
  import ctypes as ct
  ...
  myString = "test Delphi 10.3 DLL"
  outputsize = len(myString) + 8
  …
  test_3 = lib.test_3
  test_3.restype = ct.c_int
  test_3.argtypes = [ct.c_wchar_p, ct.c_wchar_p]
  sOutput = ct.create_string_buffer(outputsize)
  print("sOutput = " + sOutput.value)

and I get an error

ctypes.ArgumentError: argument 2: : wrong type

So my question is: what is the Python equivalent of AllocMem in Delphi.
I must precise that, of course all the code is for example and in "real life" I've no access to the Delphi code in DLL.
Comment: Unicode Delphi, or ANSI Delphi? Python 2 or Python 3?
Comment: sorry, I've forgot to point out: Delphi 10.3 and Python 3.7
Comment: As you are using an Unicode Delphi version, your calculation for ``OutputSize`` (at least in the Delphi example, can't tell for Python) is wrong. AllocMem allocates memory in bytes, not in characters. So you need to double the value of ``OutputSize``, because a Unicode character is two bytes big.
Comment: "and the input and output are ANSI string". Not true. Since you are using Delphi 10.3 `PChar` is an alias for `PWideChar`, pointer to null terminated array of UTF-16 character elements. And yes, your memory allocation is broken. I would like to answer the question, but won't bring myself to do so until this is cleared up.
Comment: Try using `ct.c_char_p` as the argtype.
Comment: Is it possible to create dummy string of needed length and use it for the second argument?
Comment: Delphi 2007 and older = ANSI, Delphi 2009 and newer = Unicode!
Comment: @Jeronimo How can you say that? You can't know whether the Delphi `PChar` is 8 bit or 16 bit.
Comment: @David Heffernan Because `ctypes.create_string_buffer` creates a `ctypes.c_char_Array`, which I thought was the direct cause for the "wrong type" error.
Comment: @Jeronimo But that would be the wrong fix if `PChar` was an alias for `PWideChar` (which it is for Delphi >= 2009). We can't answer the question until the asker provides the missing information requested in my comment above.
Comment: and the input and output are ANSI string
Comment: @David I have to ask my colleague who developed the "real life" DLL. I will see him tomorrow
Comment: @David, my colleague confirms me that the input and output are Unicode and not Ansi as I originally think.
Comment: @Delphi Coder, don't worry about the size of the output; the goal of the real DLL, developed by my colleague is to translate Edifact messages to Xml and JSon, so the output is set to 100 * size of the input.
Comment: I'll have a look at this later. But rest assured that none of us care in the least about your memory allocations. You however should care about your erroneous allocations.
Answer: Here is a simple and complete example demonstrating how to do this:
Delphi library
library SO_60391682;

uses
  SysUtils;

function testStringOut(Input, Output: PChar; OutputLen: Int64): Integer; stdcall;
var
  tmp: string;
begin
  tmp := '+++ ' + Input + ' +++';
  StrPLCopy(Output, PChar(tmp), OutputLen - 1);
  // -1 because of StrPLCopy's handling of null terminator
  Result := 0;
end;

exports
  testStringOut;

begin
end.

Python program to call the Delphi library
import ctypes

lib = ctypes.WinDLL(r'SO_60391682.dll')
testStringOut = lib.testStringOut
testStringOut.restype = ctypes.c_int
testStringOut.argtypes = ctypes.c_wchar_p, ctypes.c_wchar_p, ctypes.c_int64

output = ctypes.create_unicode_buffer(256)
res = testStringOut('foo', output, len(output))
print('res={}, output={}'.format(res, output.value))

Comment: Yesssss, you save me. I've missed the "create_unicode_buffer". Thank you very much.


intense integral using DCT

Question: Is this solution correct?
Determine the following integral: $$\lim_{n \rightarrow \infty} \int_6^n(1+\frac{x}{n})^n e^{-2x} dx.$$
We will appeal to the DCT. First note that
$$\lim_{n \rightarrow \infty} (1+\frac{x}{n})^n=e^x.$$
Then we can define $f_n:= (1+\frac{x}{n})^n e^{-2x} $ and it is pretty clear to see that
$$f_n \rightarrow \chi_{[6,\infty)} e^{-x}$$
a.e., then the integrable function $g$ can be defined as $g(x)=\chi_{[0,\infty)} e^{-x}$ and we clearly have that $g(x)$ is an upper bound for the $f_n$ thus by the DCT, the given integral converges to the integral of $\chi_{[6,\infty)}e^{-x}$, that is,
$$\lim_{n \rightarrow \infty} \int_6^n(1+\frac{x}{n})^n e^{-2x} dx = \int_6^\infty e^{-x} dx$$
and the RHS here is just $e^{-6}$. Thus
$$\lim_{n \rightarrow \infty} \int_6^n(1+\frac{x}{n})^n e^{-2x} dx= e^{-6}$$
which completes the integral evaluation.
Comment: Yo should say how you get $(0 \leq )f_n(x) \leq \chi_{[0,\infty)} e^{-x}$.
Comment: Yes, everything else is fine.
Comment: ah you mean justify this step as well? got it thanks! other than that ok?
Comment: question, the $f_n$ being bounded above by $g$ does it have to do with the fact that $\chi_{[0,\infty)}(x) \ge \chi_{[6,\infty)}(x)$? for every $x$. Also, if $f_n$ non-negative because it is product of non-negative functions so by zero product property?
Answer: I suggest use MCT here rather than DCT since it's not easy to justify the function is controlled by $\exp(-x)$
For MCT, using AM-GM inequality
$$(1+\frac{x}{n})^n=(1+\frac{x}{n})^n\bullet1\leq(\frac{n(1+\frac{x}{n})+1}{n+1})^{n+1}=(1+\frac{x}{n+1})^{n+1}$$

intense integral using DCT


Apache Flink: Map function over values of a KeyedStream, without losing keyed state

Question: I have a keyed stream:
KeyedStream<String, Data> keyed =
env.addSource(...)
   .map(new Parser())
   .keyBy(i -> i.key)

I want to run a state-full process function on my stream; but the process will return a normal un-keyed stream that cause losing KeyedStream and force my to call keyBy again:
SingleOutputStreamOperator<Data> unkeyed = keyed.process(new Function)
KeyedStream<String, Data> keyedAgain = keyed.keyBy(i -> i.key)

Is there any way to call a map function over values on a KeyedStream?
How I can run a state-full function without using a low-level API like ProcessFunction that cause unwanted cost: a new sub-task at runtime, plus re-shuffeling my data?
Answer: You can use a RichMapFunction or a RichFlatmapFunction and have access to Flink's managed state mechanisms. What you'll be missing, compared to a ProcessFunction, is timers.
See the example here.
Comment: And one more question: in the case of multiple `keyBy`, is there a chance of optimization? A way to grouping multiple processes in the same slot and remove the shuffling overhead?
Comment: But `KeyedStream.map` returns `SingleOutputStreamOperator` not `KeyedStream`. Do we have to rekey the resulting stream again?
Comment: You can apply the map first, and then the keyBy.


Bacula use variable to reuse FileSet Resource

Question: I have several environments of the same application in different servers. The directory structure is very similar, so I'd like to use one single FileSet for all of them. For example:
- server1: /opt/env1/app/logs
- server1: /opt/env1/app/bin
- server1: /opt/env1/app/temp
- server1: /opt/env1/app/lib

- server2: /opt/env2/app/logs
- server2: /opt/env2/app/bin
- server2: /opt/env2/app/temp
- server2: /opt/env2/app/lib

- server2: /opt/env3/app/logs
- server2: /opt/env3/app/bin
- server2: /opt/env3/app/temp
- server2: /opt/env3/app/lib

I'd like to have something like:
FileSet {
  Name = "APP"
  Include {
    Options {
      signature = MD5
      Compression = GZIP
    }
    File = "/opt/${env}/app"
  }
  Exclude {
    File = "/opt/${env}/app/logs"
    File = "/opt/${env}/app/temp"
  }
}

Then:
Job {
  Name = "JOBENV1"
  #somehow set env variable as env1
  FileSet="APP"
  ...
}

Job {
  Name = "JOBENV2"
  #somehow set env variable as env2
  FileSet="APP"
  ...
}

Job {
  Name = "JOBENV3"
  #somehow set env variable as env3
  FileSet="APP"
  ...
}

Answer: After a few days with the solution, it seems to be working, so here it goes:
Up to the example, lets say we have the following jobs:

server1-env1-job
server2-env2-job
server2-env3-job

Then assuming the --job as a convention, the file set should look like:
FileSet {
  Name = "someapp-fileset"
  Include {
    Options {
      signature = MD5
      Compression = GZIP
    }
    File = "| bash -c \"echo %n | awk -F '-' '{print \$2}' | xargs -I ARG echo /opt/ARG\""
  }
  Exclude {
     File = "| bash -c \"echo %n | awk -F '-' '{print \$2}' | xargs -I ARG echo /opt/ARG/temp\""
     File = "| bash -c \"echo %n | awk -F '-' '{print \$2}' | xargs -I ARG echo /opt/ARG/logs\""
  }
}

For more information about the execution of commands in the file set look at the documentation
Full and incremental backups are running OK.
Answer: I don't believe you can do this - Bacula's configuration file is a configuration file, not a programming language or shell.
Your practical options are:

Use identical directory structures on each machine
This is the most practical solution from Bacula's standpoint. It requires the least additional work in the Bacula configuration file, and if your applications are "identical" it makes the most sense.
Use a fileset per machine
This is more annoying than option (1) in that you are now maintaining a bunch of nearly-identical filesets. It's most practical if you're generating your Bacula configuration with some other process that can automatically create the filesets.
Use one fileset listing all the directories
This works, but any time you add a new machine (and thus a new env# directory) you will be changing the global fileset and triggering full backups.
Use a ClientRunBeforeJob directive to put the files in a uniform location
This is a little dirty, but it works -- Have Bacula rsync the app environment to another location before it does its backup.  (If you are on a Linux system you can also use mount --bind to put the app at a uniform location without affecting anything else.)
The major downside of this approach is you double your storage requirements: you have the running production copy of the app, and the shadow copy Bacula makes in order to take its backup.
Comment: Thanks for the comments, about 1: I may have more than one environment in the same server, so it's not possible. About 4: I cannot afford to duplicate required storage (some apps have more than 500GB). I guess I'll have to choose between 2 and 3
Comment: Given the restrictions (and your comment about app size) I would go with (2) - Triggering a full backup of ALL your systems when adding a new app environment would chew up a lot of storage and probably be cost/time prohibitive.
Comment: @ghm1014 There's also the slim possibility I'm totally wrong and Bacula lets you do configuration variables now (but a quick scan of the docs says that's probably not the case) - you may want to hold off on accepting this answer in case someone comes up with a better one :)
Comment: I may have found a way, it's a little bit tricky. I could use File = "| echo /opt/%n/app" Where %n is the name of the job that can be the name of the environment, also could use awk or any other bash tool to parse the jobName to obtain the environment (of course assuming an standard for the jobname that includes the env). @voretaq7 do you think that may work?
Comment: @ghm1014 I *think* that will work (test to be sure), but I'm viscerally opposed to it because it looks scary :) Also I don't know how it will interact with the fileset-modified-so-do-a-full-backup logic, so definitely check that in a test environment - if it always runs a full that might be a Bad Thing
Comment: I will test for a few days and then update with the results, so far it seems to be working. Also incremental backups are running after the full one.
Comment: 'fileset-modified-so-do-a-full-backup' logic can be disabled btw.


Refresh automatico PHP

Question: Eai galera estou montando um sistema aqui e preciso que a pagina dê refresh automatico de 60 em 60 segundos, como poderia fazer?
Comment:
Comment: Muito obrigado brother, também funcionou perfeitamente
Answer: Coloque na página esse script:
<code><script type="text/javascript">

      Redirect();
      function Redirect()
      {
              setTimeout("location.reload(true);",60000);
      }
</script>
</code>
Em 60 segundos, ela será recarregada.
Comment: Obrigado , deu certinho hehehe Desculpe a pergunta besta, ainda sou iniciante :))
Comment: Que isso Guilherme, estamos todos aprendendo!

Refresh automatico PHP


GREP: exclude file extensions in specific directory

Question: My code takes added, modified, deleted, renamed, copied files from git status -s and compare them with the list of file paths from the file.
git status -s |
grep -E "^M|^D|^A|^R|^C" |
awk '{if ($1~/M+/ || $1~/D+/ || $1~/A+/ || $1~/R+/ || $1~/C+/) print $2}' |
grep --file=$list_of_files --fixed-strings |
grep -r --exclude="*.jar" "SVCS/bus/projects/Resources/"

Prints out git status like M foo.txt
Does some "filtering" operations
More filtering operations
Takes path to files for compare from the text file
Here I am trying to make so the last step would exclude .jar files from specific directory.

How can I do the last step? Or need to add something to the 4th step?
Comment: Since you have many, many pipes, I do think this can be probably handled in a single process. Please post a sample output of `git status -s` with the final desired output.
Comment: I'm not sure why you have the `-r` flag in the last `grep`, but I might be missing something; what about trying `| grep -vE "SVCS/bus/projects/Resources/*.jar"` as last command instead of your current `grep`?
Comment: The part until `awk` could be: `git status -s | awk '$1 ~ /M|D|A|R|C/{print $2}'` .. What is the content of `$list_of_files`?
Comment: Guys, ty, but the answer is bellow
Answer: The simple fix is to change the last line to
grep -v 'SVCS/bus/projects/Resources/.*\.jar$'

but that really is some horrible code you have there.
Keeping in mind that grep | awk and awk | grep is an antipattern, how about this refactoring?
git status -s |
grep -E "^M|^D|^A|^R|^C" |
awk '{if ($1~/M+/ || $1~/D+/ || $1~/A+/ || $1~/R+/ || $1~/C+/)

... Hang on, what's the point of that?  The grep already made sure that $1 contains one or more of those letters.  The + quantifier is completely redundant here.
print $2}'

Will break on files with whitespace in them.  This is a very common error which is aggravating because a lot of the time, the programmer knew it would break, but just figured "can't happen here".
git status -s | awk 'NR==FNR { files[$0] = 1; next }
    /^[MDARC]/ { gsub(/^[MDARC]+ /, "");
        if ($0 ~ /SVCS\/bus\/projects\/Resources\/.*\.jar$/)
            next;
        if ($0 in files) print }' "$list_of_files" -

The NR==FNR thing is a common idiom to read the first file into an array, then fall through to the next input file.  So we read $list_of_files into the keys of the associative array files; then if the file name we read from git status is present in the keys, we print it.  The condition to skip .jar files in a particular path is then a simple addition to this Awk script.
This assumes $list_of_files really is a list of actual files, as suggested by the file name.  Your code will look for a match anywhere in that file, so a partial file name would also match (for example, if the file contains path/to/ick, a file named somepath/to/icktys/mackerel would match, and thus be printed).  If that is the intended functionality, the above script will require some rather drastic modifications.
Comment: This code takes output from `git status -s` exmp: `M  Boo.txt` or ` M Far.t` and rips off path to the file or file. After, grep takes it and compares it with the path to files from the file. Now, with exceptions, thanks to you) And thank you for your explanation, I couldn't find one in the internet. And also for that little guide of yours on prettifying my code!


how to embed the result of a Ruby variable in a slim Javscript block

Question: I have a Rails app that uses slim for templating. I'd like to have:
javascript:
  window.ads.hasMap = ??? # value of show_map

like in .erb
   window.ads.hasMap = <%=show_map %>;

How would I do this?
Comment: https://stackoverflow.com/questions/5646315/how-to-embed-dynamic-ruby-code-to-javascript-section-in-slim-templates, https://stackoverflow.com/questions/17794403/ruby-inside-javascript-block-slim-template/25865643, https://github.com/slim-template/slim/issues/426 should all help
Answer: According to the docs, it looks like you want:
javascript:
  window.ads.hasMap = #{show_map}

That is, wrap your ruby variable or method in #{...}.


Create donation product with Commerce Kickstart

Question: I've installed a fresh copy of Commerce Kickstart 2 and then installed Commerce Donate.
After the installation, step 1 of the Commerce Donate readme says:

Create a donation product at Administration » Store » Products

I go /node/add/add-product and choose the type Donation. When creating the product there is a select field called product with no options.
It seems like I'm creating the display node not the actual product.
How do I create the actual product?
EDIT: Just found the same question on the Commerce Donate issue queue: Problem Creating Donation Product.
Answer: Someone replied on the Commerce Donate issue thread with a solution.
The solution is to manually go to: /admin/commerce/products/add/donation where you can then make your product.


trazendo a tag  para frente de uma div

Question: Tenho o seguinte código:

 $("[data-ripple]").hover(function(e) {

    var $self = $(this.parentNode);
    var $color = $(this).data("ripple");
 var $divServicos = document.getElementById("div-servicos");

    if($self.is(".btn-disabled")) {
      return;
    }
    if($self.closest("[data-ripple]")) {
      e.stopPropagation();
    }

    var initPos = $self.css("position"),
        offs = $self.offset(),
        x = e.pageX - offs.left,
        y = e.pageY - offs.top,
        dia = Math.min(this.offsetHeight, this.offsetWidth, 100), // start diameter
        $ripple = $('
', {class : "ripple",appendTo : $self });

    if(!initPos || initPos==="static") {
      $self.css({position:"relative"});
    }

    $('
', {
      class : "rippleWave",
      css : {
        background: $color,
        width: dia,
        height: dia,
        left: x - (dia/2),
        top: y - (dia/2),
      },
      appendTo : $ripple
    });
  $divServicos.setAttribute("style","color: rgba(255,255,255, 1); background-color: rgba(20,94,69,1.00);");
  var texto = $($self).html();
        texto = texto.substr(0, texto.indexOf('<a'));
        $(".ripple").append(texto);
  }, function(e) {
  $('div.ripple').remove();
  document.getElementById("div-servicos").setAttribute("style","color: green");
  });
.div-secao {
 width: auto;
 position: relative;
 overflow: hidden;
 margin: 0 auto;
 height: auto;
}

.box-content-informacoes{
 margin: 100px auto 5px auto;
 height: auto;
 background-color: rgba(255,255,255,1);
 text-align: center;
 font-family: "passion-one";
 color: #1A7F5F;
 font-size: 25px;
 line-height: 30px;
 transition: max-height 250ms ease;
 max-height: auto;
}

#div-servicos {
 transition: all 150ms ease;

}
#h1Servicos {
 font-size: 60px;
 font-family: 'Bebas Neue';
}

.ripple{
 position: absolute;
 top:0; left:0; bottom:0; right:0;
 overflow: hidden;
 -webkit-transform: translateZ(0); /* to contain zoomed ripple */
 transform: translateZ(0);
 border-radius: inherit; /* inherit from parent (rounded buttons etc) */
 pointer-events: none; /* allow user interaction */
    animation: ripple-shadow 0.4s forwards;
 -webkit-animation: ripple-shadow 0.4s forwards;
}
.rippleWave{
 backface-visibility: hidden;
 position: relative;
 border-radius: 50%;
 transform: scale(0.7); -webkit-transform: scale(0.7);
 background: rgba(255,255,255, 1);
 opacity: 0.6;
    animation: ripple 4s forwards;
 -webkit-animation: ripple 4s forwards;
}

@keyframes ripple-shadow {
  0%   {box-shadow: 0 0 0 rgba(0,0,0,0.0);}
  20%  {box-shadow: 0 4px 16px rgba(0,0,0,0.3);}
  100% {box-shadow: 0 0 0 rgba(0,0,0,0.0);}
}
@-webkit-keyframes ripple-shadow {
  0%   {box-shadow: 0 0 0 rgba(0,0,0,0.0);}
  20%  {box-shadow: 0 4px 16px rgba(0,0,0,0.3);}
  100% {box-shadow: 0 0 0 rgba(0,0,0,0.0);}
}
@keyframes ripple {
  to {transform: scale(999);}
}
@-webkit-keyframes ripple {
  to {-webkit-transform: scale(999);}
}
<!DOCTYPE html>

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">

Problemas com seu negócio? Podemos te ajudar!

Precisa de um rumo no seu negócio, mas ainda não sabe o caminho certo a seguir? Quer divulgar o seu empreendimento e aumentar o seu número de clientes? Ou não tem interesse em negócios, mas é louco para fazer aquele projeto da sua casa dos sonhos que nunca coube no seu bolso? Necessita de novas tecnologias que auxiliem no seu desenvolvimento profissional e pessoal? Entende a importância de projetos de engenharia pra você hoje, mas não consegue pagar? Nós temos a solução para você! Conheça melhor nossos serviços cicando aqui

O que preciso resolver é o seguinte:
Quando o evento hover acontece, uma div de classe ripple é criada com a posição absolute para que sobreponha a div nativa do código HTML. o Mesmo texto dessa div nativa é inserido dentro dessa div de classe ripple. Além disso, uma segunda div é criada de classe ripple-wave que tem como objetivo, criar essa animação de ondulação se expandindo por toda a div. O texto contigo na tag "p" dentro da div nativa, precisa aparecer sem nenhum tipo de transparência, na frente dessa div de classe ripple-wave.
Comment: Esse "Clique aqui" na imagem é o mesmo que o `aqui` do código?
Comment: é sim! é o mesmo
Comment: Veja se a resposta atende.
Comment: amigo, comentei sua resposta! Ajudou mas ainda está dando um efeito indesejado...
Answer: Altere o @keyframes para que o background da nova div fique transparente, e assim mostrando o texto abaixo:

$("[data-ripple]").hover(function(e) {
    var $self = $(this.parentNode);
    var $color = $(this).data("ripple");
 var $divServicos = document.getElementById("div-servicos");

    if($self.is(".btn-disabled")) {
      return;
    }
    if($self.closest("[data-ripple]")) {
      e.stopPropagation();
    }

    var initPos = $self.css("position"),
        offs = $self.offset(),
        x = e.pageX - offs.left,
        y = e.pageY - offs.top,
        dia = Math.min(this.offsetHeight, this.offsetWidth, 100), // start diameter
        $ripple = $('
', {class : "ripple",appendTo : $self });

    if(!initPos || initPos==="static") {
      $self.css({position:"relative"});
    }

    $('
', {
      class : "rippleWave",
      css : {
        background: $color,
        width: dia,
        height: dia,
        left: x - (dia/2),
        top: y - (dia/2),
      },
      appendTo : $ripple
    });
  $divServicos.setAttribute("style","color: rgba(255,255,255, 1); background-color: rgba(20,94,69,1);");
  var pFonte = document.getElementById("pFonte");

  }, function(e) {
  $('div.ripple').remove();
  document.getElementById("div-servicos").setAttribute("style","color: green");
  });
body{
   background: red;
}

.div-secao {
 width: auto;
 position: relative;
 overflow: hidden;
 margin: 0 auto;
 height: auto;
}

.box-content-informacoes{
 margin: 100px auto 5px auto;
 height: auto;
 background-color: rgba(255,255,255,1);
 text-align: center;
 font-family: "passion-one";
 color: #1A7F5F;
 font-size: 25px;
 line-height: 30px;
 transition: max-height 250ms ease;
 max-height: auto;
}

#div-servicos {
 transition: all 150ms ease;

}
#h1Servicos {
 font-size: 60px;
 font-family: 'Bebas Neue';
}

.ripple{
    position: absolute;
    top:0; left:0; bottom:0; right:0;
    overflow: hidden;
    -webkit-transform: translateZ(0); /* to contain zoomed ripple */
    transform: translateZ(0);
    border-radius: inherit; /* inherit from parent (rounded buttons etc) */
    pointer-events: none; /* allow user interaction */
          animation: ripple-shadow 0.4s forwards;
    -webkit-animation: ripple-shadow 0.4s forwards;
    z-index: 2;
}

.rippleWave{
    backface-visibility: hidden;
    position: absolute;
    border-radius: 50%;
    transform: scale(0.7); -webkit-transform: scale(0.7);
    background: rgba(255,255,255, 1);
    opacity: 0.7;
          animation: ripple 4s forwards;
    -webkit-animation: ripple 4s forwards;
}

@keyframes ripple-shadow {
  0%   {box-shadow: 0 0 0 rgba(0,0,0,0.0);}
  20%  {box-shadow: 0 4px 16px rgba(0,0,0,0.3);}
  100% {box-shadow: 0 0 0 rgba(0,0,0,0.0);}
}
@-webkit-keyframes ripple-shadow {
  0%   {box-shadow: 0 0 0 rgba(0,0,0,0.0);}
  20%  {box-shadow: 0 4px 16px rgba(0,0,0,0.3);}
  100% {box-shadow: 0 0 0 rgba(0,0,0,0.0);}
}
@keyframes ripple {
  50% {
     background: transparent;
     }
  100% {
     transform: scale(999);
     background: transparent;
     }
}
@-webkit-keyframes ripple {
  50% {
     background: transparent;
     }
  100% {
     transform: scale(999);
     background: transparent;
     }
}

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">

Problemas com seu negócio? Podemos te ajudar!

Precisa de um rumo no seu negócio, mas ainda não sabe o caminho certo a seguir? Quer divulgar o seu empreendimento e aumentar o seu número de clientes? Ou não tem interesse em negócios, mas é louco para fazer aquele projeto da sua casa dos sonhos que nunca coube no seu bolso? Necessita de novas tecnologias que auxiliem no seu desenvolvimento profissional e pessoal? Entende a importância de projetos de engenharia pra você hoje, mas não consegue pagar? Nós temos a solução para você! Conheça melhor nossos serviços cicando aqui

Comment: Não só resolveu como ainda meu deu ideia de fazer algumas modificações pra incluir também uma mudança na tag h1. haha. Valeu mesmo, mano! Abraço

trazendo a tag  para frente de uma div


Como chamar uma classe dentro de uma função

Question: Eu tenho a seguinte estrutura de pastas
/THEME
      /vendor
        autoload.php
        /composer
          files of composer
        /jflight
           /gacookie
              /src
              /tests
              other files
  composer.json
  composer.lock
  function.php

dentro de src, tem a classe:
Utmz.php
    <?php namespace Jflight\GACookie;

use Jflight\GACookie\ParseInterface;

class Utmz extends Cookie
{
    /**
     * Timestamp
     * @var string
     */
    public $timestamp;

    /**
     * Session count
     * @var string
     */
    public $session_count;

    /**
     * Campaign number
     * @var string
     */
    public $campaign_number;

    /**
     * Source
     * @var string
     */
    public $source;

    /**
     * Medium
     * @var string
     */
    public $medium;

    /**
     * Campaign
     * @var string
     */
    public $campaign;

    /**
     * Term
     * @var string
     */
    public $term;

    /**
     * Content
     * @var string
     */
    public $content;

    /**
     * Maps the string values in the cookie to the properties of the Utmz object
     * @var array
     */
    protected $keyMappings = array(
                        'utmcsr' => 'source',
                        'utmcmd' => 'medium',
                        'utmccn' => 'campaign',
                        'utmctr' => 'term',
                        'utmcct' => 'content'
                        );

    /**
     * Constructor
     * @param DateTimeImmutable $date
     */
    public function __construct(\DateTime $date)
    {
        $this->date = $date;
    }

    /**
     * Parse cookie string and assign properties to this
     * @param  string $cookie The string from inside the cookie
     * @return static
     */
    public function parse($cookie)
    {
        $cookieBits = explode('.', $cookie, 5);
        $this->timestamp = $this->date->createFromFormat('U', $cookieBits[1]);
        $this->session_count = (integer) $cookieBits[2];
        $this->campaign_number = (integer) $cookieBits[3];
        $array = $this->paramsToArray($cookieBits);
        $this->setExtras($array);
        return $this;
    }

    /**
     * Logic for setting the extras values from the cookie as object properties
     * @param array $array
     */
    protected function setExtras($array)
    {
        if (is_array($array))
        {
            foreach ($array as $key => $item)
            {
                if (array_key_exists($key, $this->keyMappings))
                {
                    $property = $this->keyMappings[$key];
                    $this->$property = $item;
                }
            }
        }
    }

    /**
     * Logic for splitting the extra properties from string to array
     * @param  string $cookie
     * @return array
     */
    protected function paramsToArray($cookie)
    {
        if (isset($cookie[4]))
        {

            $pairs = explode('|', $cookie[4]);

            foreach ($pairs as $pair)
            {
                $item = explode('=', $pair);

                $return[$item[0]] = $item[1];
            }

            return $return;
        }
    }
}

no arquivo function.php que esta na raiz adicionei:
require_once dirname(__FILE__).'/vendor/autoload.php';

function get_data_cookies(){

            // COMO EU CHAMO A CLASSE AQUI, QUE ESTA NO DIRETÓRIO /src/Utmz.php???

            // utmz

            $utmz->timestamp; // DateTime
            $utmz->session_count; // Integer
            $utmz->campaign_number; // Integer
            $utmz->source; // string
            $utmz->medium; // string
            $utmz->campaign; // string
            $utmz->term; // string
            $utmz->content; // string

}

Como eu chamo a classe dentro da função get_data_cookies?
----------------- ATUALIZAÇÃO ----------
require get_template_directory().'/vendor/autoload.php';

use Jflight\GACookie\GACookie;

function get_cookies(){

    $utma = GACookie::parse('utma');
    $utmz = GACookie::parse('utmz');
    var_dump( $utma );
    var_dump( $utmz );

                    //utma

             $args = $utma->time_of_first_visit; // DateTime
             $args = $utma->time_of_last_visit; // DateTime
             $args = $utma->time_of_current_visit; // DateTime
             $args = $utma->session_count; // Integer

            // utmz

             $args = $utmz->timestamp; // DateTime
             $args = $utmz->session_count; // Integer
             $args = $utmz->campaign_number; // Integer
             $args = $utmz->source; // string
             $args = $utmz->medium; // string
             $args = $utmz->campaign; // string
             $args = $utmz->term; // string
             $args = $utmz->content;  // string

}

no corpo da mensagem do formulario de contatos onde estou tentando usar esses dados inseri:
<?php get_cookies() ?>

mas isso retorna
bool(false)bool(false)

Comment: Na verdade estou aprendendo como usar eu tentei: `use Jflight\GACookie\GACookie;` deu o erro: Parse error: `syntax error, unexpected 'use' (T_USE) in.. directory theme...functions.php on line 622`
Comment: estou tentando usar esse projeto no wordpress: https://github.com/jamesflight/Google-Analytics-Cookie-Parser-PHP
Comment: editei, coloquei a classe correta que deve ser chamada
Comment: Tentou colocar essa linha com o `use` no início no arquivo?
Comment: tentei assim, desapareceu o erro mas quando tento `var_dump($utmz->source);` retorna `NULL`
Answer: A classe Utmz da biblioteca Jflight/GACookie precisa ser instanciada e precisa de uma string que representa o cookie do Google Analytics para inicializar. Não sei o contexto que está utilizando essa biblioteca, mas tente isso:
require_once dirname(__FILE__).'/vendor/autoload.php';

use \Jflight\GACookie\Utmz;

function get_data_cookies(){
  $utmz = new Utmz(new Datetime());
  $utmz->parse("GA1.2.1640324400.1505291004.utmcct=testando|utmcsr=teste");

  $utmz->timestamp; // DateTime
  $utmz->session_count; // Integer
  $utmz->campaign_number; // Integer
  $utmz->source; // string
  $utmz->medium; // string
  $utmz->campaign; // string
  $utmz->term; // string
  $utmz->content; // string
}

Contudo, leia o arquivo README.md da biblioteca que tem exemplos de uso bem claros: https://github.com/jamesflight/Google-Analytics-Cookie-Parser-PHP
Comment: muito obrigada pela ajuda, atualizei minha questão, sinceramente não entendi muito bem o que vc fez ao estanciar duas vezes ( um dentro da outra) `Utmz` e `Datetime`
Comment: Não conheço profundamente a idéia por trás dos cookies do Google Analytics, mas aqui está uma leitura que deve esclarecer: https://developers.google.com/analytics/devguides/collection/analyticsjs/cookie-usage. Comente mais sobre o que está fazendo que posso tentar ajudar mais!
Comment: Criei um formulario de contato com campos basicos para o usuario, mas dentro do corpo da mensagem estou tentando imprimir quando ocorre o clique no submit o conteudo das variaveis `$utmz` e `$utma`, que são cookies parseados do Google Analytics, o mais importante pra mim por enquanto é saber se o visitante veio da pesquisa orgânica ou paga. Esse artigo é bem esclarecedor sobre os cookies do analytics [Fazendo debug de cookies e verificação de tags do Google Analytics](http://www.seodesaia.com.br/web-analytics/fazendo-debug-de-cookies-e-verificacao-de-tags-do-google-analytics)
Comment: Mas esses dados você não consegue nos relatórios do Google Analytics?