JTextField requires me to give it focus a second time before making proper updates

Question: In my project I have a JTextField for dates to be entered in. I have an InputVerifier to ensure proper information is entered and to also do some work with it. One of the things I need is to get the DAY_OF_WEEK from the entered date. I do so with
Calendar calTest = Calendar.getInstance();
calTest.setTime(primer);
int day = calTest.get(Calendar.DAY_OF_WEEK);

I then print it to the screen, no matter what date is entered, the number shown is 4 but when I click out of the field and click back in without making changes, the proper number is printed to screen. I can't figure out why this is? Especially when the date in string form is printed correctly immediately after the field loses focus.
Below is the method where this takes place:
private void updatePrimer(String dateString) {
    Calendar calTest = Calendar.getInstance();
    calTest.setTime(primer);
    int day = calTest.get(Calendar.DAY_OF_WEEK);
    try {
        primer = simpleFormat.parse(dateString);
    } catch (ParseException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    System.out.println(day);
    shortString = shortFormat.format(primer);
    System.out.println(shortString);
    labelTrip = true;
    stringTrip = dateString;
    updateLabels(labelTrip, stringTrip);
}

Here is a small runnable program that I have been using basically as a sandbox:
EDIT This is just a "sandbox" program I have been using before implementing to my main program so that I can test basically functionality. The end result of what I need is to have a JTextField taking in a string and then format it into a date in the format MM/dd/yyyy. Using this date, a JLabel is updated with the same date but in the format of MM/dd. Additionally, the JLabel next to it will update with the date minus one day of the previous date, and then the same deal with the remaining JLabel. The changing of colors was used to help me visualize the order of operations of the program. The textarea was just thrown in for me to click something to change focus. The button just prints the date entered in the JTextField
The important thing, and what is in question here is why in updatePrimer(String dateString) the correct day of the week is only printed correctly the second time the JTextField gains focus
import java.awt.Color;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Locale;
import java.util.logging.Level;
import java.util.logging.Logger;

import javax.swing.InputVerifier;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JFormattedTextField;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextArea;
import javax.swing.SwingUtilities;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import javax.swing.text.MaskFormatter;

public class Hello implements ActionListener{
    private JFrame frame = new JFrame();
    private JPanel panel = new JPanel();
    private Date endingDate = new Date();
    private Date primer = new Date();
    private String endingString = null;
    private SimpleDateFormat simpleFormat = new SimpleDateFormat("MM/dd/yyyy");
    private SimpleDateFormat shortFormat = new SimpleDateFormat("MM/dd");
    private JFormattedTextField weekEndingData = null;

    private JLabel dateData[] = new JLabel[3];
    private JTextArea ta = new JTextArea(20, 10);
    private JButton b = new JButton("click");
    private String shortString = null;
    private boolean labelTrip = false;
    private String stringTrip = null;
    private Calendar cal = Calendar.getInstance();
    private Color blank = Color.LIGHT_GRAY;

    public Hello() {
        b.addActionListener(this);

        weekEndingData = createFormattedTextField();
        simpleFormat.setLenient(false);

        panel.add(weekEndingData);
        for (int i=0; i<3; i++){
            dateData[i] = new JLabel("12/34");
            dateData[i].setForeground(blank);
            panel.add(dateData[i]);
        }

        panel.add(ta);
        panel.add(b);

        frame.add(panel);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.pack();
        frame.setVisible(true);

    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable(){
            public void run(){
                new Hello();
            }
        });

        System.out.println("Hello, World");
    }

    private JFormattedTextField createFormattedTextField() {
        JFormattedTextField formattedField = null;
        try {
            MaskFormatter dateMask = new MaskFormatter("##/##/####");
            formattedField = new JFormattedTextField(dateMask);
        } catch (ParseException ex) {
            Logger.getLogger(Hello.class.getName()).log(Level.SEVERE, null, ex);
        }
        formattedField.setColumns(10);
        formattedField.setInputVerifier(getInputVerifier());
        return formattedField;
    }

    private InputVerifier getInputVerifier() {
        InputVerifier verifier = new InputVerifier() {

            @Override
            public boolean verify(JComponent input) {
                JFormattedTextField field = (JFormattedTextField) input;
                String text = field.getText();
                return isValidDate(text);
            }

            @Override
            public boolean shouldYieldFocus(JComponent input) {
                boolean valid = verify(input);
                if (!valid) {
                    JOptionPane.showMessageDialog(null, "Please enter a valid date in format dd/mm/yyyy");
                    weekEndingData.setText("");
                }
                return valid;
            }

        };
        return verifier;
    }

    public boolean isValidDate(String dateString) {
        if (dateString.equals("  /  /    ")){
            resetLabels();
            return true; //returns true in order to allow user to accidentally click field and still yield focus
        }
        else{
            try {
                simpleFormat.parse(dateString);
                updatePrimer(dateString);
                return true;
            } catch (ParseException ex) {
                resetLabels();
                return false;
            }

        }
    }

    private void updatePrimer(String dateString) {
        Calendar calTest = Calendar.getInstance();
        calTest.setTime(primer);
        int day = calTest.get(Calendar.DAY_OF_WEEK);
        try {
            primer = simpleFormat.parse(dateString);
        } catch (ParseException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        System.out.println(day);
        shortString = shortFormat.format(primer);
        System.out.println(shortString);
        labelTrip = true;
        stringTrip = dateString;
        updateLabels(labelTrip, stringTrip);
    }

    private void resetLabels() {
        weekEndingData.setValue(null);
        labelTrip = false;
        updateLabels(labelTrip, stringTrip);
    }

    private void updateLabels(boolean trip, String date) {
        boolean validUpdate = trip;
        if (validUpdate == false){
            for (int i = 0; i < 3; i++){
                dateData[i].setText("12/34");
                dateData[i].setForeground(blank);
            }
        }
        else if (validUpdate == true){
            try {
                cal.setTime(simpleFormat.parse(date));
            } catch (ParseException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

            int day = -1;
            for (int i = 0; i < 3; i++){
                cal.add(Calendar.DATE, day);
                dateData[i].setText(shortFormat.format(cal.getTime()));
                dateData[i].setForeground(Color.GREEN);
            }

        }
    }

    public void actionPerformed(ActionEvent e) {
        /*System.out.println("Action performed");
        System.out.println(formattedField);
        endingDate = (Date) formattedField.getValue();

        System.out.println(endingDate);
        endingString = format.format(endingDate);
        System.out.println(endingString);*/
        System.out.println(weekEndingData.getText());

    }

}

Comment: +1 did you tried by using JSpinner with SpinnerDateModel, value JFormattedTextField hard to be empty or null, this way
Comment: @mKorbel thanks for taking time to to read my question. Yes I have looked into it, unfortunately, my boss does not want a Spinner to be used. Only a textfield with a `  /  /    ` mask
Comment: So the first code block, is that where the problem is occurring?
Comment: well I "think" so. it executes and prints a day of the week but it prints the wrong one, unless it regains focus, then it prints correctly. i also think maybe the problem could be with the inputverifier yielding focus but I dont think that makes sense when everything else I want from it works perfectly
Comment: Can you try and explain what is supposed to happen and what it's actually doing. I don't think I fully understand the question. I'm playing with your program now and not sure what to be looking for
Comment: @peeskillet, sure give me a few minutes while I edit my question
Comment: @peeskillet I updated my question, hopefully it sheds more light on the matter. Essentially, if you run the program and type in a date in the JFormattedTextfield , then change focus, youll see an incorrect day of the week being printed to the console (specifically the number 4). now click on the JFormattedTextfield again, youll notice the correct day of the week printed in the console. thats what I can't figure out
Comment: If no one answers it by tomorrow, I'll have a look at it. Too lazy for debugging right now, sorry.
Comment: no worries, I appreciate your time.
Answer: After printing out my code and tracing my data through the program I discovered my problem.
In
private void updatePrimer(String dateString) {
    Calendar calTest = Calendar.getInstance();
    calTest.setTime(primer);
    int day = calTest.get(Calendar.DAY_OF_WEEK);
    try {
        primer = simpleFormat.parse(dateString);
    } catch (ParseException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    System.out.println(day);
    shortString = shortFormat.format(primer);
    System.out.println(shortString);
    labelTrip = true;
    stringTrip = dateString;
    updateLabels(labelTrip, stringTrip);
}

the lines :
calTest.setTime(primer);
int day = calTest.get(Calendar.DAY_OF_WEEK);

needed to be moved after the primer = simpleFormat.parse(dateString); try-catch block. My problem was that I was setting the time before setting the date.


How can I beat Lynels?

Question: So, Lynels are these nasty customers in The Legend of Zelda: Breath of the Wild. They're lion centaurs, usually with around 2000 or so HP. They charge right at you and hit real hard.
I've tried to fight them a few times, but they have a preference for jousting making on-foot combat a risky proposition. What strategies can I employ to battle these fiendish adversaries?
Answer: Lynels are extremely strong enemies compared to how early you'll find them in the game (for a lot of playthroughs).
If you want to know how to defeat the Lynel because you're looking for a challenge or you need to kill it I'd recommend the following things:
Have a shield equipped
You don't need to use a one handed weapon but having a shield can be extremely useful since it blocks all the damage in a risky situation. Lynels can hit extremely hard and blocking those 6-10 hearts of damage is an absolute lifesaver (especially early).
Use buff-food
The loading screen tips are absolutely right: Don't just run into a monster over and over again but try to prepare for the fight with some elixirs and buff-food. Depending on your health you can run defensive boosts but usually you should go for shock resistance, damage up and speed up.
Have lots of weapons
2000 HP is no joke. If you want to kill this thing with your melee weapons some of them will break. If you're still in the early game multiple, maybe even all your weapons will break. Keep that in mind when fighting this guy. You don't want to find yourself in a situation where your only option is using bombs.
Learn to side-hop, or backflip his attacks
ian_itor has already pointed this out in his answer but I want to mention it again since it's probably the most important thing when fighting Lynels. Dodging and counterattacking are extremely efficient. The attacks are slow and predictable. If you get the timing right you can land a lot of free hits with Flurry and it's great practice for dodging in general.
Aim for the head/use special arrows and Chuchus
If you want to use ranged make sure to aim for the head for a stagger and increased damage but also don't be afraid to use special arrows and elemental Chuchus. Freeze, shock and fire are your allies in this fight. Each element has it's own advantages and they can make the fight a lot easier when used correctly. Also be sure to not stand in a puddle and pop a lightning resistance elixir when going for a ranged method.
To kill the Lynel only two of the above mentioned points are required: A lot of weapons and good dodging. The others I've mentioned are additional help and are available from the start. I've excluded points that are unlocked since it's very possible to find a Lynel before you have access to certain advanced gadgets or powers. Obviously the fight gets easier the more you progress into the game because of better weapons, armor and powers  but if you follow these steps you'll be able to kill the Lynel with little health and a bit of patience and practice (doable with Zora weapons and about 4 hearts).
One final note:
If you simply want to complete a quest with a Lynel near the objective, I'd highly reccomend checking if you can't just sneak around it since the rewards are usually not worth the trouble they cause (at least in the early game).
Answer: You can stop a charge by using upgraded Stasis on them. It'll hold them for around 1-2 seconds, which should be just enough to fire an arrow into their face. When they come out of stasis, they'll be staggered and their charge will end.
My favourite strategy is to try and stun lock them. First, you need to hit it in the face with a powerful enough bow. Doing so will force it down on it's knee for a short while. While in this state, you can approach them and press 'A' to mount them. This allows you to get about 5 hits in depending on your stamina and how fast you can mash Y.
Answer: The strategy I have discovered allows me to run through several of the most powerful Silver Lynels in a row, without the need of a bunch of weapons.
Preparation

Complete Ancient Armour set, upgraded at least twice each. The set bonus, Ancient Proficiency, doubles the damage of Ancient weapons. If the armour is upgraded four times, it also has the highest defence in the game.
A high damage Ancient weapon, of any type. I had a 60 damage Ancient Battle Axe++.
A fair number of arrows, of any type. A good damage bow doesn't hurt, and you'll get a new one off the Lynel.
Some food or an elixir which increases attack or defence isn't a bad idea. Environmental protection is another option, if you'd rather not take constant damage if in a cold or hot area.

Combat

Run away from attacks, and keep a medium distance. Far enough that he tries to charge at you, but also not so far that he pulls out his bow. Make sure you get away from his ground stab which makes a sphere of fire around him.
Shoot arrows at his face whenever you get the chance. This will stun him. The type of arrow doesn't matter, and while bomb arrows will deal more damage at this stage, they do not make it any easier to stun.
Whenever he's stunned, run up and mount him, then attack. Weapons do not lose durability while mounted on a Lynel. Your double damage Ancient weapon will take out a hunk of his health.
Run away. It's helpful to move the camera facing forward before being kicked off the mount, to more easily keep him in view afterwards. Rinse and repeat.
Answer: One easy way is to use the lightning strike from the Gerudo Divine Beast - it deals about 500 damage per hit. Given that it'll also stun the Lynel, you can probably kill it very easily between uses.
Melee attacks are your best bet, since at range they have some pretty nasty arrows.
Comment: @twobugs you can evade the charge by side hopping or running away to the side, usually. You have to be very quick after that, though, because I think that he turns around for another charge.
Comment: @twobugs You could also take away their credit cards or take a plea deal.
Comment: Interesting - I hadn't used the lightning strike on them. Is there any other way to stop their charging? That seemed to be the big killer for me.
Comment: @twobugs stasis, freeze arrows, shock arrows, lightning blades are good choices.
Comment: @twobugs Stasis+ rune is an excellent way to stop their charging / elemental breath attack.
Answer: I defeated a Lynel like this:
First, you should have at least 8 hearts and proper defensive gear/armor, since his strikes deal heavy damage. In case you get hit, eat something immediately. Go for extra hearts, defense or damage with your meals. Fairies don't hurt either.
Never try to defeat him from distance! His aim is ludicrous and his shock arrows deal tons of damage.
Flurry is your friend. I dealt the most damage waiting for his melee attack (the one where he stands, not the one where he gallops) and backflipping in the right moment (Y + Analog Stick Down). Then you'll get the chance to do a flurry attack with Y, hitting him many times. Use a hard hitting weapon.
You have to be patient. Without spoilering, the special reward from defeating the elephant divine beast is a big help.
Good luck!
Answer: I have fought many Lynels before, the first one being during Vah Ruta's quest. I attempted to sneak around it but ended up being caught by the Lynel. I fleed from the scenario with my tail between my legs and nearly died from his nasty ark Shot, I came back again fully fitted in the Champion's Tunic mixed with the soldier's grieves and amber earrings. (They were enhanced to level 2 with the earring being level 3)I popped an electricity resistance elixir and began the fight, dodging was EXTREMELY important, as his attacks did nasty damage on my first try, so when I tried again, that's what I did, my friends were over,(Zelda fans)so when I beat it they were pretty shocked, not as shocked as me though. I was extremely afraid of Lynels at the time and constantly backed down from the quest. As a result, this was a huge success for me.
Answer: I found that if you use an ancient arrow you can kill him in one hit.  You can get one from Beetle on "customer appreciation day" whatever that is.
The sad thing is, you don't get any reward. ;-;
Comment: Ancient arrows will kill anything other than guardians and bosses (Gannon and the Blights) in one hit, but you won't get any dropped goodies since ancient arrows magically suck the enemy and everything with it into some other dimension (or something).
Answer: Listen: I killed a Silver Lynel (coliseum ruins) in 20 mins with max hearts and the master sword. This is extremely advanced in the game. I recommend killing the Lynel by skill, starting with the red ones and moving up.
My first Lynel was the Zora one (just to say, I bought all of the shock arrows in Gerudo Town and just killed him for fun) I had 3 hearts and a knight's claymore. What works is stunning him, then charging a two-handed weapon attack. It works like a charm :) Mounting doesn't always work, and if you have low stamina it doesn't give you enough of a time window to attack well. (As a side note, I wish you could actually ride a Lynel like a deer or something, with him attacking you the second you dismounted.)
No matter where you are in the game, I recommend avoiding the Lynel.
Answer: A little bit of advice from a newbie (5 hearts, 12-15 armor, great fire sword as primary weapon, 40 shield, knight bow): The Lynels that I have found have typically been around cliffs. In attempt to avoid being seen, I climbed up them, and proceeded to shoot him with an ice arrow. After freezing him, I glided over until I was directly above him, hit B to drop, and Y for a flying attack with the great flame sword. This does MASSIVE damage. Fire and ice combo after being frozen is sweet. You may or may not be able to get a few more hits in after that depending on how lucky you are... Run away and repeat. Make sure he doesn't see you because his shot is impeccable! Repeat until you are out of ice arrows. Then, move to regular arrows and use the stun/mount trick previously mentioned. High, protective ground and a ton of arrows! Worse case scenario you throw bombs at him for forever. You can also try throwing a boomerang at him, as it is the right range to not be hit by the bow, but being able to avoid the charge and fire blast. I haven't really experienced this however... Good luck!
Comment: YOU CAN'T FREEZE LYNELS!!! Elemental things don't do anything to lynels other than doing extra damage.
Comment: Also, the opposite element (fire to ice in this case) won't do anything, except for the double damage with a normal weapon to unfreeze it. It's only in your imagination.

How can I beat Lynels?


Does initializing a variable with true or false establish the direction of the content in Javascript?

Question: <code>   <script>
     var switchDirection = false;
      function doAnimation() {
        var divAdvert = document.getElementById("divAdvert");
           var currentLeft = divAdvert.offsetLeft;
            var newLocation;
           if (!switchDirection) {
               newLocation = currentLeft + 2;
               if (currentLeft >= 400) {
              switchDirection = true;
              }
          } else {
                  newLocation = currentLeft - 2;
                  if (currentLeft <= 0) {
                  switchDirection = false;
                  }
          }
             divAdvert.style.left = newLocation + "px";
       }
     setInterval(doAnimation, 10);
   </script>
</code>
I want to know why a new variable with the value of false has been declared in the beginning of the function.
Comment: …to be toggled in the function later apparently? Please tell us what parts of the function you did not understand.
Comment: var switchDirection = false; This variable keeps track of the direction in which the content is currently going. If switchDirection is false, the content is moving from left to right, which is the default. If switchDirection is true, the content is moving from right to left. // This is what the author of the program writes in the explanation of the code.I do not understand this point that how initializing the variable to false makes the direction of the content go from left to right. –
Comment: It's not the initialisation of the variable that makes the div do anything. It's the `doAnimation` function which uses the `switchDirection` state to control in which direction the content is moved in the current step.
Answer: No, nothing like this. May be developer using this variable later in page as this is global variable. He is calling function from setInterval hence its going to called repeatedly. So, he is keeping that value in some global variable as it will be lost if kept inside function.
Name is like that just to know what was the intention of variable.Its simple variable.
This line is changing the location :-
    divAdvert.style.left = newLocation + "px";
When switchDirection is false , auther is adding value:-
<code>if (!switchDirection) {
           newLocation = currentLeft + 2;
</code>
Once it is more that 400 , author changing the variable value
<code>  if (currentLeft >= 400) {
          switchDirection = true;

         }
</code>
Then he is moving it in other direction and again vice versa,
<code>     newLocation = currentLeft - 2;
              if (currentLeft <= 0) {
              switchDirection = false;
              }
</code>
Instead of giving value true false , s/he could have used values left and right or ltr and rtl but as he has only 2 values, he used true and false.
Its simple variable , you can give any name like dir or xyz it will work in same way.
And if you change all the false with true and true with false code will work same.
Comment: var switchDirection = false;
This variable keeps track of the direction in which the content is currently going. If
switchDirection is false, the content is moving from left to right, which is the
default. If switchDirection is true, the content is moving from right to left.
//
This is what the author of the program writes in the explanation of the code.I do not understand this point that how initializing the variable to false makes the direction of the content go from left to right.


Is Windows Vista worth considering when developing for Windows XP?

Question: Quite a few comments to answers in a different post, Where are the best locations to write an error log in Windows?, gave me the impression that a lot of things regarding standard folders (%APPDATA%; %TEMP%) in Windows Vista are different from Windows XP, which should of course be taken into account when developing software that will have to run under Windows  at some point.
But in my company, I do not see that happen in this decade, and maybe not in the next either. I mean, the central IT deployed SP2 only eight months ago, and any question about SP3 is met with disregard (well, if you're lucky...)
So what is your advice? Should I rewrite two modules in my current project to make them ready for Windows Vista, or should I not bother about it at all, until it is really needed?
Answer: Make them Vista-ready, if only for the fact that Windows 7 will have the same changes. Better to future-proof now when you have the chance, than later when time is critical.
Answer: Personally, I'd have a quick look at the effort level of what it would take to enable "Vista Support" in your application.
If the effort levels are acceptable based on the allotted time to make changes in your project then it's good to account for the future in any design.
You know your implementation better than anyone!
We've had some issues in-house here with shortcuts and such as they were generated in an older installation suite. It's the little things that we are currently addressing in getting our Vista Support fully up and running. I'm sure there will be some "unforeseen" obstacles you will come across as well.
Best of luck!
Answer: The big thing for supporting Windows Vista in most desktop applications is to use references like your %APPDATA% rather than hard-coding paths. That should resolve any changed folder locations. And don't do anything that requires write access in your program's install folder.
Interestingly, these rules are true for Windows XP, too. It's just that in the past it was a lot easier to get away with breaking them.
Comment: +1! I don't know why this isn't getting more upvotes. There are a number of low-impact changes -- like this -- which make your app more-or-less future proof against any Windows upgrades. Check http://blogs.msdn.com/oldnewthing/ to read the horror stories when developers break these rules ...
Comment: indeed, breaking, like having users as admin by default(and with no UAC, its bad indeed), crap like that. So you get apps that require admin priviledges.
Comment: It's a function of how many views the question receives, and an answer posted on a Friday won't get many views.
Answer: There is no need to hurry. So far it is not critical, and who knows what next the version of Windows would look like.
Comment: An MSDN subscription can get you a lot of details on upcoming versions of Microsoft software. Vista's changes weren't all of a sudden launched on all of us, just those of us without the MSDN subscription. Windows 7 isn't looking much different, and they're already starting tech previews.
Comment: And you can see what windows will looks like if you search on google. Windows 7 will be an upgrade of windows Vista.
Answer: If you planning on upgrading your software for Windows Vista, check out Windows Logo Program, Requirements for the Windows Vista Logo Program for Software (Microsoft Word document, 183 KB, file name Windows Vista Software Logo Spec 1.1.doc).
Answer: Since you can't foresee an OS upgrade in the near future, don't worry too much about it. You should, however, keep the potential for an OS upgrade in mind whenever you're changing code. If anything is OS-specific in a section of code when you make changes, tweak it so that it is either OS-independent or easy to locate and modify later to make it OS-independent (depending on how long it would take to update it).
If you get into a situation where you're just tackling lesser issues, consider specifically aiming your fixes towards areas that you know (or suspect might) have code that would need to be adjusted if your company upgraded to Vista or Windows 7.
Answer: Don't bother, Windows 7 is coming out relatively soon, you'd be best off waiting to see what changes they make to support that! Last thing you want is to spend time fixing things for Vista..... and then fixing them all over again for Windows 7.
Answer: Is your company going to upgrade to Windows Vista at all? A lot of companies are ignoring Windows Vista and are planning to upgrade to the next Windows version when it comes out in the hopes that it will suck less than Windows Vista. If this is the case, it would be a complete waste of time.  Who knows what will change in the next version of Windows. It is better to rewrite once for the new Windows than to rewrite once for Windows Vista and then again for the next Windows version.
Comment: Chances are the standard folders system won't be changing between Vista and Windows 7, likewise the other systems already changed between XP and Vista will only be updated, not replaced. Things that are similar between XP and Vista, on the other hand...
Comment: Would you be willing to bet your job on that?  I wouldn't.


Convert DataFrame to JSON with single array

Question: Let's say I have the following data....
areaId <- "abc123"
time <- format( seq.POSIXt(as.POSIXct(Sys.Date()), as.POSIXct(Sys.Date()+1), by = "5 min"),"%Y-%m-%d %H:%M:%S", tz="GMT")
value <- 10
df <- data.frame(areaId, time, value)

Giving output
$ areaId <chr> "abc123", "abc123", "abc123", "abc123", "abc123", "abc123", "abc123", "abc123", "abc123", "abc123", "abc123", "abc12…
$ time   <chr> "2022-01-30 00:00:00", "2022-01-30 00:05:00", "2022-01-30 00:10:00", "2022-01-30 00:15:00", "2022-01-30 00:20:00", "…
$ value  <dbl> 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, …

How can I convert into a JSON file that looks like this so I can POST to an API... everything I've tried so far gives me 3 individual arrays rather than 1.
{
    "nameofdata": [
        {
            "areaId": "abc123",
            "time": "2022-01-30T00:00:00Z",
            "value": 0,
        },
        {
            "areaId": "abc123",
            "time": "2022-01-30T00:05:00Z",
            "value": 0,
        },
        {
            "areaId": "abc123",
            "time": "2022-01-30T00:10:00Z",
            "value": 0,
        },
...
    ]
}

Many thanks for any assistance.
Comment: What have you tried so far?
Answer: You can do:
library(jsonlite)
toJSON(list(nameofdata = df), pretty = TRUE)

which gives:
{
  "nameofdata": [
    {
      "areaId": "abc123",
      "time": "2022-01-30 00:00:00",
      "value": 10
    },
    {
      "areaId": "abc123",
      "time": "2022-01-30 00:05:00",
      "value": 10
    },
    {
      "areaId": "abc123",
      "time": "2022-01-30 00:10:00",
      "value": 10
    }
…
  ]
}


React infinite loop

Question: I am new to React and sorry for my English.
When I pass data from Child to parent component and click on another button it doesn't render.
as you can see in my comment setState creates an infinite loop stopping the option to update the value.
I have tried different ways to solve the problem creating inside constructor variables like this.name = '' and this.selected = [], and setting on callback as this.name = name and this.selected = selected but doesn't render when I click in other options.
I've tried work with componentDidMount() and other methods of life cycle but I don't know how to solve it.
App.js (Parent component)
state = { name: '', selected: [] };

doParentControl = (name, selected) => {
   console.log('doParentControl name: ',name);
   console.log('doParentControl selected: ',selected);
   // this.setState({ name: name, selected: selected }) --> infinite loop
}

render() {
   console.log('-> render App')
   return (

Map

         <Navbar parentControl={this.doParentControl}/>
         <MapComponent name={this.state.name} selected={this.state.selected}/>

   );
}

Navbar.js (Child component)
constructor(props) {
    super(props);
    this.selected = [false, false, false];
    this.state = { name: 'tile' };
}

handleClick = (e) => {
    this.setState({name: e.target.value});
}

handleChange = (e) => {
    switch(e.target.value) {
        case 'option1': {
            this.setState({ selected: this.selected[0] = e.target.checked})
            break;
        }
        case 'option2': {
            this.setState({ selected: this.selected[1] = e.target.checked})
            break;
        }
        case 'option3': {
            this.setState({ selected: this.selected[2] = e.target.checked})
            break;
        }
        default:
            break;
    }
}

doParentControlFromChild = () => {
    this.props.parentControl(this.state.name, this.selected);
}

render() {
    console.log('render Navbar ->')
    return (

                    <button name="tile"        onClick={this.handleClick} value="tile">Tile</button>
                    <button name="tile-watercolor" onClick={this.handleClick} value="tile-watercolor">Tile WaterColor</button>
                    <button name="cartografia" onClick={this.handleClick} value="cartografia">Cartografía</button>
                    <button name="satelite"    onClick={this.handleClick} value="satelite">Satélite</button>
                    <button name="mapa"        onClick={this.handleClick} value="mapa">Mapa</button>

                <input type="checkbox" name="option1" value="option1"  onChange={this.handleChange} />Option 1
                <input type="checkbox" name="option2" value="option2"   onChange={this.handleChange} />Option 2
                <input type="checkbox" name="option3" value="option3"      onChange={this.handleChange} />Option 3

            { this.doParentControlFromChild() }

    );
}

Comment: thanks Tomasz for edit text
Answer: { this.doParentControlFromChild() } is making a function call upon render, which causes a state change, which causes a re-render, hence your loop.  Get rid of the parens and only allow a function that calls setState to be called from a user action, not simply a render call.  Something like this will do:

Comment: Thanks!!
I understand that callback from child must be inside html  item.
https://medium.com/@ruthmpardee/passing-data-between-react-components-103ad82ebd17

1 - if i put inside clearfix only render child and doesnt pass data to parent
2 - overide onClick and handleClick doesnt works
Answer: setState() let render() function re-render.
So setState() deployed at doParentControl in your parent component causes component re-rendering, and in your child component, return( ... { this.doParentControlFromChild()} ... ) just accompany with elements rendering. This cause doParentControl from your parent component be called again, so here we have the infinity-loop.
Just like earlier answer said, you need to let doParentControlFromChild be called only when it need to happen.
App.js (Father)
...
state = { name: '', selected: [] };

doParentControl = (name, selected) => {
   console.log('doParentControl name: ',name);
   console.log('doParentControl selected: ',selected);
   this.setState({ name: name, selected: selected })
}

render() {
   console.log('-> render App')
   return (

Map

         <Navbar parentControl={this.doParentControl}/>
         <MapComponent name={this.state.name} selected={this.state.selected}/>

   );
}
...

Navbar.js (Child)
...

constructor(props) {
    super(props);
    this.selected = [false, false, false];
    this.state = { name: 'tile' };
}

handleClick = (e) => {
    this.setState({name: e.target.value});
}

handleChange = (e) => {

     let index = e.target.value.match(/\d/); // fetch the idx
     this.setState({ selected: this.selected[index] = e.target.checked}, () => {
        this.doParentControlFromChild()
     })

}

doParentControlFromChild = () => {
    this.props.parentControl(this.state.name, this.selected);
}

render() {
    console.log('render Navbar ->')
    return (

                    <button name="tile"        onClick={this.handleClick} value="tile">Tile</button>
                    <button name="tile-watercolor" onClick={this.handleClick} value="tile-watercolor">Tile WaterColor</button>
                    <button name="cartografia" onClick={this.handleClick} value="cartografia">Cartografía</button>
                    <button name="satelite"    onClick={this.handleClick} value="satelite">Satélite</button>
                    <button name="mapa"        onClick={this.handleClick} value="mapa">Mapa</button>

                <input type="checkbox" name="option1" value="option1"  onChange={this.handleChange} />Option 1
                <input type="checkbox" name="option2" value="option2"   onChange={this.handleChange} />Option 2
                <input type="checkbox" name="option3" value="option3"      onChange={this.handleChange} />Option 3

    );
}

React infinite loop


execute child process in react application

Question: I wanted to know which module should I use to execute a child process from a react application.
The requirement is:
I need to have a button ,on click of which it should run npm test for the application and generate the report which I will render as per my need.
The thing at which i an stuck is to execute that npm test command on click... rest of the part is working fine if I execute the command manually.
I tried using child-process and child-process-promise modules but it does not work.

import { exec } from 'child-process-promise';

testCode = () => {
    exec("cd ../../ && npm test")
    .then((data) => console.log(data))
    .catch(err => console.log(err))
}

// it thorws an error in the import
//TypeError: Cannot read property 'split' of undefined [in index.js of child-proceess-promise module]

error message image
Comment: What code exactly did you try? What exactly did not work?
Comment: Also, what do you mean by 'execute a child process from a react application'. Are you trying to do this from *client side*? This obviously won't work. From server side it should work. `child-process-promise` is quite popular package that is workable at least.
Comment: so you have written the script in package.json and you want to run that command from the react ui is thats your question ?
Comment: yes @dileep thats what i need
Comment: @estus updated the code
Comment: It's unclear what child-proce**e**ss-promise really is. If you mean https://www.npmjs.com/package/child-process-promise then there's no `split` in index.js.
Comment: added the image for exact error that i am getting in browser
Comment: in package.json of react app.... i have a script "test": "react-scripts test --env=jsdom --coverage --verbose=false --json --outputFile=src/testReport.json" i want to execute this command on click of button
Comment: If you want to offload work from main thread, you can check out service workers instead: https://developer.mozilla.org/en-US/docs/Web/API/Service_Worker_API
Answer: It is not possible to execute a shell command / process / program from the web-browser app level.
Only a server-side app can execute a shell command like "npm test", and then pass the results to the front-end app.


How to open a new tab with new terminator process?

Question: I am trying to open a new terminator tab using Ctrl+Shift +t but it opens a new tab with the same process. The command that I run in one tab runs in another tab as well. Is there a way to start a new tab with new terminator process?
Comment: Can you give an example of a process you have in one tab that shows up in a new tap?  Can you run this test and describe what you see?  Start the command `top` in a terminal.  Then open another terminal.  Do you see the top output in the second tab?  Also what happens if you click on Tabs in the menu and click detach.  Do you see two terminals running Top?  Now what happens if you quit top in one of the terminals, does it quit in the previous terminal also?  Do you have this same behavior if you create a new terminal with `Ctl + Alt + T`?
Comment: I added a tab to an existing window using Ctl + Shift + T. When I start top in one tab, I don't see top output in another.  This hold true after detaching the tab as well. Ctl + Alt + T also starts a new process. I closed the terminator window in which I observed the "same process behavior" and when I open a new window, it works as expected (I get new processes in each new tab I open). I'm not sure why terminator was opening same processes in the window I was working earlier. I might have typed some command unknowingly which led to this behavior. Thanks for your help!
Comment: What program is running in the terminal when you hit `ctl + Alt + T`?
Answer: Ctrl+Shift+E and Ctrl+Shift+O are helpful shortcuts in terminator.
They open a new instance adjacent to the one you have, but without it being another window.
Use Ctrl+Shift+W to close it.
Comment: @VitaliiDiravka `Ctrl-Shift-T` does the trick.
Comment: Press `ctrl` while clicking on the link you want to open. :)
Comment: What about new tab (as browser tab)?


Carrierwave json column with metadata

Question: I am making file uploader that in addition to storing multiple files to s3 using fog also needs to store additional information such as file name, etc for each file.
Since number of files for one row can vary I'd like to save this data in my database table in form of json. However, carrierwave by default stores only url of the uploaded file.
Json would have structure similar to this:
{
    {
        url: ...,
        name: ...
    },
    {
        url: ...,
        name: ...
    }
}

Has anyone tried doing this and how would one go about it?
Comment: you're asking for the multiple file storage or just for the metadata (url, name)?
Comment: I need multiple file storage but each file has separate file field with few additional text fields that need to to together. So, each group containing file and text fields is one nested json in my table column.
Answer: I would implemente it either with a callback (if it gets called for each file) or a process (if callback gets called for all files at once), on the uploader:
Carrierwave Callbacks
your_uploader.rb

after :store, :save_json_info

or
process :save_json_info

def save_json_info
  info = model.json_field
  info[filename] = {
    url: ...,
    name: ...
  }
  model.update!(json_field: info)
end

(inside the uploader you actually reference the model which is being saved to as literal model)
Then you could access them by
(outside you'll substitute model for it's actual name...)
 name = model.avatar[0].file.filename

or
 name = model.avatar[0].split('/')[-1] #this is a hacky way of getting the filename, by splitting the url address and getting the last element of the split

 model.json_field[name]

(i'm not sure this is the correct way to access multiple files on carrierwave but whatever it is it should be similar)
EDITED:
And probably the best way would be to have the json field be an array as well, and then simply << { url: '...', name: '....' } on the field as you go through processing the files. Then when you loop through the files to show them you can loop with the index and get the corresponding json values for it.
So on your uploader you would have:
def save_json_info
  model.json_field << {
    url: ...,
    name: ...
  }
  model.save!
end

Then if you're looping through the images, .each_with_index for instance, you can use the index to access model.json_field[i]. Since I imagine files will be added to the array file field as they are processed, pushing them into the info_json array field in the same cycle will render the same index for both. You'll need to take care of when they're removed though.

Carrierwave json column with metadata


jQuery working in console but not in original code

Question: I have tried the following code to add href to the a tag inside a td. it is working fine while i do in console. But when I try the same in my code it is not working. Can anyone tell me the reason?

        Hai

Comment: [`$(document).ready()`](http://learn.jquery.com/using-jquery-core/document-ready/)
Comment: do you have jquery attached?
Comment: Yes I have attached jQuey 1.9.1
Answer: Use document.Ready()
$(document).ready(function() {
    $("table tbody tr td a").attr('href','http://www.google.com');
});

You need to ensure that the document is already loaded before you try to manipulate the DOM.
More info: http://api.jquery.com/ready/
Comment: So...award him the answer?
Comment: Thanks buddy..I didn't know $(document).ready() was a must..What a silly mistake..!!!!
Comment: Thanks for sharing this solution! I didn't use jQuery in a few years and I had issues with some code that wasn't running because I forgot about $(document).ready()
Answer: The element doesn't exist when your jquery is executing. You need to put your handlers inside a ready function.

$(function() {}); is the shorthand for $(document).ready(function() {});
Answer: The JS is firing before the html is created.

        Hai

Answer: put it in a ready section :

Answer: Your code executes before the DOM is ready and the element actually exists, try it this way:

The reason it works on console is because the  element already exists when you execute your code...
JSBin Demo
Answer: The order of your jQuery files in the master layout page can also influence why it does not work in actual code but works in console of the browser. jQuery files must be referenced in the following order in the master page:

For people coming here looking for a solution to what it says in title without going into specifics of this particular question, hope it helps someone.


ManyToMany Hibernate in Kotlin

Question: I am trying to build Many To Many relationship in Kotlin as the following:
@Entity
data class Gender(@field:Id var abbr: Char? = null,
                  var description: String = "") : PanacheEntityBase

@Entity
data class Interest(
    var description: String = ""): PanacheEntity()

@Entity
data class User(@field:Id var id: UUID? = null,
                @ManyToOne(fetch = FetchType.LAZY) var gender: Gender? = null,
                var birthday: Long = 0,
                @ManyToMany(fetch = FetchType.LAZY, cascade = [CascadeType.PERSIST])
                @JoinTable(
                    name = "user_interests",
                    joinColumns = [JoinColumn(name = "user_id", referencedColumnName = "id")],
                    inverseJoinColumns = [JoinColumn(name = "interest_id", referencedColumnName = "id")]
                )
                var interests: List<Interest> = listOf()) : PanacheEntityBase

and I receive error messages:
GenerationTarget encountered exception accepting command : Error executing DDL "drop table if exists User cascade" via JDBC Statement: org.hibernate.tool.schema.spi.CommandAcceptanceException: Error executing DDL "drop table if exists User cascade" via JDBC Statement

Error executing DDL "create table User (id uuid not null, birthday int8 not null, gender_abbr char(1), primary key (id))" via JDBC Statement: org.hibernate.tool.schema.spi.CommandAcceptanceException: Error executing DDL "create table User (id uuid not null, birthday int8 not null, gender_abbr char(1), primary key (id))" via JDBC Statement

Caused by: org.postgresql.util.PSQLException: ERROR: syntax error at or near "User"
  Position: 22

What am I doing wrong?
Comment: I bet "User" is a reserved keyword in SQL and i don't see any backticks or other escape mechanisms in the error.  You could try using another name for the table that isn't a reserved keyword in SQL or try to find the right configuration so that all table and column names are correctly escaped in the generated SQL.
Comment: I have changed to account and it works. Thanks a lot.
Answer: I had similar issue multiple times, it happens because user is a reserved keyword in most SQL dialects.
Easiest solution is to rename it, e.g add application prefix(e.g sw_user or SwUser in kotlin).
Another possible option can be to use doublequotes, something like
@Table(name = "\"user\"")
@Entity
data class User

This approach is a bit risky and might not work on all the databases.
There's also a list of all the reserved sql keywords

ManyToMany Hibernate in Kotlin


Undefined limit of trig function when $x$ approaches $\frac{\pi}{2}$

Question: Well, I tried making $$u = \frac{\pi}{2}-x$$ and also factoring the resulting $\cos(\frac{\pi}{2}-u)$ to the $$\cos\left(\frac{\pi}{2}\right)\cos(-u)-\sin\left(\frac{\pi}{2}\right)\sin(-u)$$ form and nothing appears to make me leave this indetermination.
How should I simplify this limit?
$$\lim_{x\to \frac{\pi}{2}} \frac{\cos(x)}{\frac{\pi}{2}-x}\;$$
PS: without using l'Hôpital's.
Comment: Had written "sen", What I meant was "sin". "Sen" is how we write sin in Portuguese, edited.
Comment: http://www.proofwiki.org/wiki/Limit_of_Sine_of_X_over_X#Geometric_Proof
Answer: Assuming that you know $\lim_{x\to 0}\frac{\sin x}{x}=1$ you can proceed as follows:
$$\lim_{x\to \pi/2}\frac{\sin (\pi/2-x)}{\pi/2-x}=1.$$
In the last equality we used the well known trig. identity $\sin{(\pi/2-x)}=\cos x.$
Comment: Wow, nice, I didn't knew this trig. identity, this really simplifies things here.


XSD : what is the difference between the namespace and the default namespace

Question: Maybe the question's title is misleading, and that is because I couldn't explain my problem in a single line sentence.
In the w3school tutorial, there is this example:
<?xml version="1.0"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"
           targetNamespace="http://www.w3schools.com"
           xmlns="http://www.w3schools.com"
           elementFormDefault="qualified">
    ...
    ...
</xs:schema>

The author has stated that: xmlns:xs="http://www.w3.org/2001/XMLSchema" means:

the elements and data types used in the schema come from the "http://www.w3.org/2001/XMLSchema" namespace. It also specifies that the elements and data types that come from the "http://www.w3.org/2001/XMLSchema" namespace should be prefixed with xs.

However, the author has also stated that targetNamespace="http://www.w3schools.com" means:

the elements defined by this schema (note, to, from, heading, body.) come from the "http://www.w3schools.com" namespace.

I have a problem understanding the previous paragraphs. The first one states that the elements come from http://www.w3.org/2001/XMLSchema namespace, though the second paragraph states that the elements come from http://www.w3schools.com namespace.
In my opinion, these two sentences conflict with each other.
Could you tell me please which one is correct? and what does each one really mean?
I appreciate your time.
Regards,
Answer: Default namespaces, qualified names and prefixes
The default namespace is the one that is not mapped to any prefix. You declare it using:
xmlns="a-string-that-is-usually-an-uri"

If you have such a declaration in an XML file, any unprefixed element will belong to that namespace. Unprefixed attributes always belong to no namespace.
You can have several namespace declarations in an XML document, but only one default namespace in each scope. You also don't need to have any default namespace. A scope consists of the element itself and its descendants. In the document below, there are two default namespaces. The ns2 namespace replaces ns1 in the element it is declared in and its descendants:
<root xmlns="ns1">
    <text>This is ns1</text>
    <child xmlns="ns2">
        <text>This is ns2</text>
    </child>
</root>

There are two <text> elements in the document above. Actually they are completely different elements since each one belongs to a different namespace. They have the same local name but their qualified names differ.
If you have a declaration for the same namespace such as:
xmlns:p="a-string-that-is-usually-an-uri"

You are mapping the namespace with a prefix p which can be used by any element in the context (considering a well-formed document, not necessarily valid). For a valid document, elements that are part of a namespace should be qualified by it, either as an unprefixed descendant (or self) of an element which declares a default namespace, or as a prefixed descendant (or self) of an element which declares a namespace mapping to that prefix. Prefixes can also be used to qualify attributes.
By using prefixes you can have all declarations at the root element, and qualified elements can mix:
<root xmlns:p="ns1" xmlns:q="ns2" xmlns="ns0">

This is ns1

    <q:child xmlns="ns2">
        <q:text>This is ns2</q:text>

This is ns1 again!

        <text>This is ns0</text>
    </q:child>
</root>

Each one of the <text> elements above are part of a different namespace.
Take some time to read this guide: Understanding XML Namespaces. It's short and if you read it carefully, you'll certainly understand how namespaces in XML work very well. If you wish, you can also read the XML Namespaces specification which is the official documentation.
Target namespaces in XSD
About the tutorial you are reading. This file:
<?xml version="1.0"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"
           targetNamespace="http://www.w3schools.com"
           xmlns="http://www.w3schools.com"
           elementFormDefault="qualified">
    ...
    ...
</xs:schema>

has two namespace declarations, and one target namespace declaration. Since it's also a schema, it contains type definitions which will belong to the target namespace. This may be confusing because the schema is a XML document which declares rules for other XML documents using XML. Treating the XSD document as a plain XML document, you have one namespace mapped to the xs prefix and another which is the default namespace. You could also have legally used different prefixes:
<abc:schema xmlns:abc="http://www.w3.org/2001/XMLSchema"
           targetNamespace="http://www.w3schools.com"
           xmlns:xyz="http://www.w3schools.com"
           elementFormDefault="qualified">
    <abc:complexType name="MyType"> ...</abc:complexType>
    <abc:element name="myElementOne" type="xyz:MyType" />
    <abc:element name="myElementTwo" type="abc:string" />
</abc:schema>

If you look carefully at the example above you might see the associations:

The schema, complexType and element elements, plus the string type all belong to the http://www.w3.org/2001/XMLSchema namespace.
There are no elements or attributes in the schema that belong to the http://www.w3schools.com namespace, since this is a schema and it's actually defining those elements.
The MyType complex type is part of the http://www.w3schools.com namespace. This is because it's being declared in the schema and the targetNamespace of the schema is http://www.w3schools.com. Since that namespace is mapped to the xyz prefix, then you need to prefix it when you refer to it That's what is happening in the type attribute of the first element, the same way the type attribute of the second element refers to the string type of the http://www.w3.org/2001/XMLSchema namespace.

You could also have written the above schema like this. It would make no difference:
<schema xmlns="http://www.w3.org/2001/XMLSchema"
           targetNamespace="http://www.w3schools.com"
           xmlns:xyz="http://www.w3schools.com"
           elementFormDefault="qualified">
    <complexType name="MyType"> ...</complexType>
    <element name="myElementOne" type="xyz:MyType" />
    <element name="myElementTwo" type="string" />
</schema>

Note now that there is a default namespace, and it's http://www.w3.org/2001/XMLSchema, so all types and elements of that namespace are unprefixed.
It's best, however, to follow conventions and map a prefix to the XSD namespace (usually xs or xsd).
About the conflicting sentences
Actually, they are not conflicting. But they are not well written (they might be, perhaps, in their original context). The first one:

the elements and data types used in the schema come from the "http://www.w3.org/2001/XMLSchema" namespace. It also specifies that the elements and data types that come from the "http://www.w3.org/2001/XMLSchema" namespace should be prefixed with xs.

Consider the XSD document as a regular XML file. In any XML file, a namespace declaration such as xmlns="ns1" in the root element is declaring that the unprefixed elements come from the ns1 default namespace. In the case described by the sentence, the author is referring to all the prefixed elements (such as element, complexType, simpleType,sequence) and types (such asstring,integer,decimal) because thexs` prefix is mapped to the XSD namespace. The author is talking about elements and types used in the XML file, not defined.
The next sentence is about targetNamespace, which is an attribute specific to the XSD specification. It declares the namespace of all the types:

targetNamespace="http://www.w3schools.com" means that the elements defined by this schema (note, to, from, heading, body.) come from the "http://www.w3schools.com" namespace.

This refers to the names you are assigning to types and elements. When you create an instance that declares that namespace, then you will be using these elements:
<note xmlns="http://www.w3schools.com">...</note>

or
<x:note xmlns:x="http://www.w3schools.com">...</x:note>

But in the XSD you are defining them. You don't even need to declare xmlns="http://www.w3schools.com" in the schema if you never refer (using attributes such as type, ref, etc.) to any other type or element you created inside it.
Comment: can I add `xmlns="xs"` and write a more compat XSD?
Answer:    default namespace serve only one purpose, it allows use of namespace qualified xml components without namespace prefix.

Just to give you one hint to solve above problems, when you define a component it's targetNamespace you should consider but when you refer a component think of default namespace(or namespace with prefix).


contents of config directory created by scaffold tool

Question: Would someone please explain why directory "config" of the application created by the scaffold tool has favicon.ico file in it. it seems to me that .ico files belong to the "static" directory. why is it there?
thanks
konstantin
Answer: We use SO for help questions. please bring these types of question to the yesod mail list.


SQLite query is not taking arguments correctly

Question: I'm trying to do an SQLite query in my Android app, but for some reason it doesn't get the arguments correctly. If I hard-code the values, the query works just fine, so I know the overall query is correct and the data is there.
...
public String[][] traerEncuestaPostventa(int idBien,
    int idEncuesta)
{

    String[][] arrayDatos = null;

    String[] arrayArgumentos = {String.valueOf(idBien), String.valueOf(idEncuesta), String.valueOf(idBien)};

    Cursor cursor = null;

    cursor = querySQL("SELECT " +
        "encuestadetalle.id_encuestadetalle," +
        "IFNULL(encuestapostventa.id_encuestapostventa, 0) as id_encuestapostventa," +
        "encuestadetalle.zona_inmueble," +
        "encuestadetalle.tarea," +
        "IFNULL(encuestaobservacion.id_encuestaobservacion, 0) as id_encuestaobservacion," +
        "IFNULL(encuestaobservacion.observacion, '') as observacion," +
        "encuestadetalle.id_encuesta," +
        "IFNULL(encuestapostventa.recepcion, 0) as recepcion" +
        " FROM encuestadetalle" +
        " LEFT JOIN (SELECT * FROM encuestapostventa WHERE id_bien = ?) AS encuestapostventa" +
        " ON encuestadetalle.id_encuestadetalle = encuestapostventa.id_encuestadetalle" +
        " LEFT JOIN encuestaobservacion" +
        " ON encuestapostventa.id_encuestapostventa = encuestaobservacion.id_encuestapostventa" +
        " WHERE encuestadetalle.id_encuesta = ?" +
        " AND (IFNULL(encuestapostventa.id_bien, 0) IN (?, 0))" +
        " ORDER BY encuestadetalle.zona_inmueble, encuestadetalle.tarea", arrayArgumentos);

    if(cursor.getCount() > 0)
    {
        int i = 0;
        arrayDatos = new String[cursor.getCount()][5];

        while(cursor.moveToNext())
        {
            //Here I handle the data;

            i = i + 1;
        }
    }

    cursor.close();
    CloseDB();
    return(arrayDatos);
}

...

public Cursor querySQL(String sql, String[] selectionArgs)
{
    Cursor oRet = null;
    // Opens the database object in "write" mode.
    db = oDB.getReadableDatabase();
    oRet = db.rawQuery(sql, selectionArgs);
    return(oRet);
}
...

Now if I replace the query like this, it works:
    cursor = querySQL("SELECT " +
        "encuestadetalle.id_encuestadetalle," +
        "IFNULL(encuestapostventa.id_encuestapostventa, 0) as id_encuestapostventa," +
        "encuestadetalle.zona_inmueble," +
        "encuestadetalle.tarea," +
        "IFNULL(encuestaobservacion.id_encuestaobservacion, 0) as id_encuestaobservacion," +
        "IFNULL(encuestaobservacion.observacion, '') as observacion," +
        "encuestadetalle.id_encuesta," +
        "IFNULL(encuestapostventa.recepcion, 0) as recepcion" +
        " FROM encuestadetalle" +
        " LEFT JOIN (SELECT * FROM encuestapostventa WHERE id_bien = 5813) AS encuestapostventa" +
        " ON encuestadetalle.id_encuestadetalle = encuestapostventa.id_encuestadetalle" +
        " LEFT JOIN encuestaobservacion" +
        " ON encuestapostventa.id_encuestapostventa = encuestaobservacion.id_encuestapostventa" +
        " WHERE encuestadetalle.id_encuesta = 3" +
        " AND (IFNULL(encuestapostventa.id_bien, 0) IN (5813, 0))" +
        " ORDER BY encuestadetalle.zona_inmueble, encuestadetalle.tarea", null);

I also tried replacing the elements in arrayArgumentos, but it didn't work, either:
    String[] arrayArgumentos = {String.valueOf(5813), String.valueOf(3), String.valueOf(5813)};

I'm guessing it has something to do with the fact that my array is a String[] and the arguments themselves are integers. How can I fix this?
Answer: Try this:
String[] arrayArgumentos = {String.valueOf(idBien)};

    Cursor cursor = null;

String sql="SELECT " +
        "encuestadetalle.id_encuestadetalle," +
        "IFNULL(encuestapostventa.id_encuestapostventa, 0) as id_encuestapostventa," +
        "encuestadetalle.zona_inmueble," +
        "encuestadetalle.tarea," +
        "IFNULL(encuestaobservacion.id_encuestaobservacion, 0) as id_encuestaobservacion," +
        "IFNULL(encuestaobservacion.observacion, '') as observacion," +
        "encuestadetalle.id_encuesta," +
        "IFNULL(encuestapostventa.recepcion, 0) as recepcion" +
        " FROM encuestadetalle" +
        " LEFT JOIN (SELECT * FROM encuestapostventa WHERE id_bien ="+String.valueOf(idBien)+ ") AS encuestapostventa" +
        " ON encuestadetalle.id_encuestadetalle = encuestapostventa.id_encuestadetalle" +
        " LEFT JOIN encuestaobservacion" +
        " ON encuestapostventa.id_encuestapostventa = encuestaobservacion.id_encuestapostventa" +
        " WHERE encuestadetalle.id_encuesta ="+String.valueOf(idEncuesta)+"" +
        " AND (IFNULL(encuestapostventa.id_bien, 0) IN (?, 0))" +
        " ORDER BY encuestadetalle.zona_inmueble, encuestadetalle.tarea"

cursor = querySQL(sql, arrayArgumentos);

Log.d("For DEBUG", "Sql String -->"+sql)

Try to put some of your arguments directly on the query.
Then print your query to check what is being sent to the database with Log statement.
The problem may be on the arguments. Also remember that when equal to a String in SQL you should use ' ' . Hope this helps.
Comment: Althought your precise suggestion didn't work, it was a good idea to replace the ?s in my query by the actual arguments. I just replaced all of them instead of leaving one for `arrayArgumentos`, and executed the query like `cursor = querySQL(sql, null);`. I can't believe I couldn't come up with this myself. So thank you!
Answer: The right format to give argument is as
rawQuery("SELECT id, name FROM people WHERE name = ? AND id = ?", new String[] {"David", "2"});

check is with hardcoded values like
...." ORDER BY encuestadetalle.zona_inmueble, encuestadetalle.tarea",  new String[] {"5813", "3","5813"});

Comment: Isn't that essentially the same that I already have? I changed it to this: `" ORDER BY encuestadetalle.zona_inmueble, encuestadetalle.tarea", new String[] {String.valueOf(idBien), String.valueOf(idEncuesta), String.valueOf(idBien)});` and it's still not working. Your answer just suggested a different way to do the same thing I'm already doing.


appleid.apple.com will not loaded on Ubuntu

Question: I have tried to open appleid.apple.com on my Ubuntu 18.10 machine and I can not get it work right. I am getting a "502 Bad Gateway" error. I thought it was something on their end but the website works fine when I open it on my phone. I have tried to use Firefox, Google Chrome and Chromium with no luck.
Edit: Apple has fixed this issue after I reported it.
Answer: It looks like Apple is filtering on User Agent. I just switched mine to Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_2) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/71.0.3578.98 Safari/537.36 and it worked fine.
Comment: NVM, I used a Firefox extension called User-Agent Switcher and it worked!
Comment: I reported this bug"(?)" to Apple. I really hope they fix this. It's really annoying since most websites don't play along nicely with User-Agent Switcher on.
Comment: How did you switch it?
Comment: Wow, this worked for me too.  Apple really sucks!!!
Answer: I had the same issue with Ubuntu and also with Mint Linux and tried out different browsers in that environments assuming the issue is only in a single environment.
The solution described above worked as well for me to install the Firefox AddOn called "UserAgentSwitcher" [https://addons.mozilla.org/de/firefox/addon/user-agent-switcher-revived/]
This gives a chance to simulates a certain environment. And It seems the Apple friends does not "like" the Linux community ;-)..
Every Linux based environment simulation lead to the 502 Bad Gateway issue - only other ones are working.
I do not have found an alternative also for other browsers so far...
Thanks for the trick.


Android navigation drawer - remove the horizontal bars separating each item

Question: I'm trying to remove or set transparent the horizontal bars separating each item in the navigation drawer menu.
Here is a screenshot from my app:

I want to remove or set same color as background color or set as transparent those horizontal grey bars.
Here's my XML code:
custom_drawer_item.xml
<.?xml version="1.0" encoding="utf-8"?>
<.RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="#edf7f2"
android:divider="@android:color/transparent">

<LinearLayout
    android:id="@+id/spinnerLayout"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:layout_marginTop="0dp"
    android:orientation="vertical"
    android:divider="@android:color/transparent" >

    <Spinner
        android:id="@+id/drawerSpinner"
        android:layout_width="fill_parent"
        android:layout_height="0dp"
        android:layout_weight="1" />
</LinearLayout>

<LinearLayout
    android:id="@+id/headerLayout"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:layout_marginTop="20dp"
    android:orientation="vertical"
    android:divider="@android:color/transparent">

    <TextView
        android:id="@+id/drawerTitle"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textColor="#96ca2d"
        android:textAppearance="?android:attr/textAppearanceSmall"
        android:divider="@android:color/transparent" />

    <View
        android:layout_width="match_parent"
        android:layout_height="2dp"
        android:layout_marginBottom="1dp"
        android:layout_marginTop="1dp"
        android:divider="@android:color/transparent">
    </View>
</LinearLayout>

<LinearLayout
    android:id="@+id/itemLayout"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:layout_alignParentLeft="true"
    android:layout_marginTop="0dp"
    android:orientation="vertical"
    android:divider="@android:color/transparent" >

    <LinearLayout
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:minHeight="50dp"
        android:divider="@android:color/transparent">

        <ImageView
            android:id="@+id/drawer_icon"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content" />

        <TextView
            android:id="@+id/drawer_itemName"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textColor="#4bb5c1"
            android:textAppearance="?android:attr/textAppearanceLarge"
        />
    </LinearLayout>

    <View
        android:layout_width="match_parent"
        android:layout_height="1dp"
        android:layout_marginBottom="0dp"
        android:layout_marginLeft="10dp"
        android:layout_marginRight="10dp"
        android:layout_marginTop="0dp"
        android:divider="@android:color/transparent">
    </View>
</LinearLayout>

<./RelativeLayout>

drawer_list_item.xml
<.TextView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@android:id/text1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center_vertical"
android:minHeight="?android:attr/listPreferredItemHeightSmall"
android:paddingLeft="16dp"
android:paddingRight="16dp"
android:textAppearance="?android:attr/textAppearanceListItemSmall"
android:textColor="#4bb5c1"
android:divider="@android:color/transparent"
/>

drawer_layout.xml
<.?xml version="1.0" encoding="utf-8"?>
<.RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="60dp"
android:background="?android:attr/activatedBackgroundIndicator"
android:divider="@android:color/transparent">

<ImageView
    android:id="@+id/button"
    android:layout_width="190dp"
    android:layout_height="40dp"
    android:layout_alignParentLeft="true"
    android:layout_centerVertical="true"
    android:contentDescription="descri imagem"
    android:paddingBottom="10dp"
    android:paddingLeft="10dp"
    android:paddingRight="10dp"
    android:paddingTop="10dp" />

<./RelativeLayout>

PS; Don't mind the . (dot) in the xml code, it's there just to enforce SO to show those lines otherwise for some reason those lines wouldn't be shown in my question.
Thanks!
Answer: in your layout of activity that contains navigation drawer in the listview put these lines
android:divider="@android:color/transparent"
android:dividerHeight="0dp"

Answer: try to customize your items' background by setting a custom drawable:
1/ create a little file in your res/drawable : white_empty_background.xml
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="rectangle" >
    <solid android:color="@android:color/white" />

</shape>

2/ in your item's layout set this drawable as background.
Answer: remove
<View
    android:layout_width="match_parent"
    android:layout_height="1dp"
    android:layout_marginBottom="0dp"
    android:layout_marginLeft="10dp"
    android:layout_marginRight="10dp"
    android:layout_marginTop="0dp"
    android:divider="@android:color/transparent">
</View>

from your xml
and then try it, must work
Comment: I removed that view but the horizontal bars are still present
Comment: try it after removing this
        android:divider="@android:color/transparent"  from your linearlayouts


Proper order of valves in heating pump systems?

Question: I believe I have a basic understanding of the usage of each component. That being said, I lack knowledge of the proper installation order, especially regarding non-return valves (among others).
I have a splitter-type heat pump unit Daikin Altehrma that is a bit weak for my system so the manufacturer recommends the usage of additional components for a correct operation:

anuloid (hydraulic balancer of dynamic pressures)
magnetic filter (because the internal is weak)
secondary pump (because the internal is weak)
and expansion tanks (for cold and hot water)

Here is a diagram I made of how things I imagine should be connected, but I have doubts if it makes sense:

I'm looking to know if the positions of non-return valves, air vents, filters and pressure by-pass valve are correct. I even tried to ask ChatGPT, but unfortunately, I was able to force the order upon AI even in a malicious way so I guess I will need a piece of advice from an actual living human being.
Cold, hot, and re-circulation outlets are 3/4" while outlets for underfloor heating are 1". The pressure by-pass valve was supplied with the unit and "in and out" are both 3/4" so I assume this should be installed either on a hot or cold outlet (?) - no idea.
Comment: You do not need expansion tank in the cold line, only in hot
Comment: You do not need air vents in cold lines only in hot
Comment: @Ruskes air vents on both cold lines are an inseparable part (feature) of the filter itself
Answer: I am not clear as to why you need 2 expansion tanks in the first place, but even if you did use both, it doesn't make sense, to me, where the one on the cold water line is located and why you don't have it in the same position as the one on the hot water line. Having a non-return valve placed in between the tank and the cold water side expansion tank renders the expansion tank useless.
I only install expansion tanks on the cold water line side but I know others install them on the hot water side.
Pressure bypass valves are generally placed at the outlet of a pump to recirculate some of the liquid back into the reservoir it is pumping out of so I am not understanding your intended use of it in your cold water inlet line to your tank?
Comment: `why you don't have it in the same position as the one on the hot water line` - not sure what you mean by this. from your proposed answer I understood this: https://i.stack.imgur.com/0Y1V4.png is that correct?
Comment: The expansion tank on the cold water side has to be the closest item to the tank like it is on the hot water side.


How do I get YouTube channel identifier from a channel link? - PHP

Question: I'm trying to get a YouTube channel's username or ID from their channel link. Some channels have unique usernames and some channels have random IDs. Is there a method to retrieve this ID in a string format from a given link to their channel using PHP?
Answer: The Channel resource (https://developers.google.com/youtube/v3/docs/channels) has a id property that YouTube uses to uniquely identify the channel.
You can use the Channel's list method (https://developers.google.com/youtube/v3/docs/channels/list) which will search for Channels based on a search criteria you provide. One possible search criteria is a username parameter. Once you get the channel that corresponds to that username, you can get the id property from that channel.


Java's charsets / character encoding

Question: I have a file in Spanish so it's full of characters like:
 á é í ó ú ñ Ñ Á É Í Ó Ú

I have to read the file, so I do this:
fr = new FileReader(ficheroEntrada);
BufferedReader rEntrada = new BufferedReader(fr);

String linea = rEntrada.readLine();
if (linea == null) {
logger.error("ERROR: Empty file.");
return null;
}
String delimitador = "[;]";
String[] tokens = null;

List<String> token = new ArrayList<String>();
while ((linea = rEntrada.readLine()) != null) {
    // Some parsing specific to my file.
    tokens = linea.split(delimitador);
    token.add(tokens[0]);
    token.add(tokens[1]);
}
logger.info("List of tokens: " + token);
return token;

When I read the list of tokens, all the special characters are gone and have been replaced by this kind of characters:
Ó = Ó
Ñ = Ñ

And so on...
What's happening? I had never had problems with the charsets (I'm assuming is a charset issue). Is it because of this computer? What can I do?
Any extra advice will be appreciated, I'm learning! Thank you!
Comment: Use `InputStreamReader` and specify the appropriate encoding. `FileReader` will assume "default" encoding, so it won't decode the characters properly.
Answer: You need to specify related character encoding.
BufferedReader rEntrada  = new BufferedReader(
    new InputStreamReader(new FileInputStream(fr), "UTF-8"));

Answer:
What's happening?

The answers recommending reading and writing using UTF-8 encoding should fix your problem.  My answer is more about what happened and how to diagnose similar problems in the future.
The first place to start is the UTF-8 character table at http://www.utf8-chartable.de. There is a drop down on the page which lets you browse different portions of Unicode.  One of your problem characters is Ó.  Checking the chart reveals that if your file was encoded in UTF-8, then the character is U+00D3 LATIN CAPITAL LETTER O WITH ACUTE and the UTF-8 sequence is two bytes, hex  c3 93
Now let's check the ISO-8859-1 character set at http://en.wikipedia.org/wiki/ISO/IEC_8859-1, since this is also a popular character set.  However this is one of those single-byte character sets.  Every valid character is represented by a single byte, unlike UTF-8 where a character may be represented by 1, 2 or 3 bytes.
Note that the character at C3 looks like à but there is no character at 93.  So your default encoding is probably not ISO-8859-1.
Next lets check Windows 1252 at http://en.wikipedia.org/wiki/Windows-1252.  This is almost the same as ISO-8859-1 but fills in some of the blank spaces with useful characters.  And there we have a match.  The sequence C3 93 in Windows 1252 is exactly the character string Ó
What all this tells me is that your file is UTF-8 encoded however your Java environment is configured with Windows 1252 as it's default encoding.  If you modify your code to explicitly specify the character set ("UTF-8") instead of using the default your code will be less likely to fail on different environments.
Keep in mind though - this could have just as easily happened the other way.  If you have a file of primarily Spanish text, it could just as easily been an ISO-8859-1 or Windows 1252 encoded file.  In which case your code running on your machine would have worked just fine and switching it to read "UTF-8" encoding would have created a different set of garbled characters.
This is part of the reason you are getting conflicting advice.  Different people have encountered different mismatches based on their platform and so have discovered different fixes.
When in doubt, I read the file in emacs and switch to hexl-mode so I can see the exact binary data in the file.  I'm sure there are better and more modern ways to do this.
A final thought - it might be worth reading The Absolute Minimum Every Software Developer Absolutely, Positively Must Know About Unicode and Character Sets (No Excuses!
Comment: +1. Good information on background. I would suggest mark as Wiki.
Answer: You have  the default encoding wrong. You probably need to read UTF8 or latin1. See this snippet for setting the encoding on streams. See also Java, default encoding
public class Program {

    public static void main(String... args)  {

        if (args.length != 2) {
            return ;
        }

        try {
            Reader reader = new InputStreamReader(
                        new FileInputStream(args[0]),"UTF-8");
            BufferedReader fin = new BufferedReader(reader);
            Writer writer = new OutputStreamWriter(
                       new FileOutputStream(args[1]), "UTF-8");
            BufferedWriter fout = new BufferedWriter(writer);
            String s;
            while ((s=fin.readLine())!=null) {
                fout.write(s);
                fout.newLine();
            }

            //Remember to call close.
            //calling close on a BufferedReader/BufferedWriter
            // will automatically call close on its underlying stream
            fin.close();
            fout.close();

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

    }
}

Answer: In my experience, the text file should be read and written based on Western encoding: ISO-8859-1.
BufferedReader rEntrada  = new BufferedReader(
    new InputStreamReader(new FileInputStream(fr), "ISO-8859-1"));
Comment: i have áéíóú characters on my doc and this encodings worked for me. UTF-8 did not. Thanks.
Answer: The other answers provide you a right direction. Just wanted to add that Guava with its Files.newReader(File,Charset) helper method makes creating such a BufferedReader a lot readable (pardon the pun):
BufferedReader rEntrada = Files.newReader(new File(ficheroEntrada), Charsets.UTF_8);

Java's charsets / character encoding


Python tika parser error - Failed to receive startup confirmation from startServer

Question: I am trying to use Tika in python to parse PDF files. I am using python 2.7 and a Mac. I cannot get it to work. I have installed it, then:
from tika import parser
raw = parser.from_file('...file')

I get this error (edited for brevity):
Retrieving http://search.maven.org/remotecontent ... to /var/folders/... [MainThread  ] [INFO ]  Retrieving http:// ... [MainThread  ] [WARNI]  Failed to see startup log message; retrying...
...
2019-04-08 14:53:05,910 [MainThread  ] [ERROR]  Tika startup log message not received after 3 tries.
2019-04-08 14:53:05,916 [MainThread  ] [ERROR]  Failed to receive startup confirmation from startServer.

My question is very similar to that here Use tika with python, runtimeerror: unable to start tika server. The top answer, though, doesn't work for me. I have installed Java 8, but it still doesn't work. What should I do?
Comment: If you grab the Tika App runnable jar manually, and try to run that directly (eg `java -jar apache-tika-1.20.jar`), does that work fine?
Comment: I might be doing things wrong. I went to https://tika.apache.org/download.html and downloaded tika-server-1.20.jar. I then ran `java - jar 'filepath to tika-server-1.20.jar'`. I got this error: Exception in thread "main" java.lang.UnsupportedClassVersionError: org/apache/tika/server/TikaServerCli : Unsupported major.minor version 52.0. I did the same thing and got a similar error with `tika-app`1.20.jar` (Exception in thread "main" java.lang.UnsupportedClassVersionError: org/apache/tika/cli/TikaCLI : Unsupported major.minor version 52.0).
Comment: That means your version of Java is too old. Upgrade! Apache Tika needs Java 8+
Comment: I thought I had upgraded (I did so yesterday). When I go to Java Control Panel, it is Version 8 Update 201 (build 1.8.0_201-b09). But when I go to Terminal and do `java -version`, it says `java version "1.6.0_65"`. What to do?
Comment: Uninstall the old version of Java 6? Helping you with Java on Windows isn't really a Tika problem though, so you really need a new questions!
Comment: Thanks! I did so (and installed the Java JDK), and everything works now.
Answer: Not sure you still have problem with this - or for anyone else coming here. Even though you installed Java 8 (from Oracle or so), the terminal still see the old java that comes with OSX.
You need to tell the terminal to use the new Java you have just installed. Put this into your .bash_profile
export JAVA_HOME="/Library/Internet Plug-Ins/JavaAppletPlugin.plugin/Contents/Home/"
else, check System Preference > Java > Java > View > Path
you can see the path for Java, copy everything up to Home/ and paste it to
export JAVA_HOME=""
Restart your terminal and tike should work now
Comment: how do i do this for terminal on windows


Check if string contains at least two alpha chars

Question: I need to check if a string has at least two alpha characters, like a1763r or ab1244
I was thinking I would use something like:
myString = "a123B";
myString.Any(char.IsDigit).Count();

but I'm using .net 2.0 so this method Any() does not exists.
Is there something equivalent?
Comment: Try programming. For example, you might write a loop that checks each character.
Comment: You could use a regular expression...
Comment: But why would he ever.
Answer: Don't know about alpha or what not, but you can count how many characters are digits without Linq like so:
string str = "a123B";
int digits = 0;
foreach (char c in str)
    if (char.IsDigit(c))
        digits++;
print(digits); // 3

Answer: You can create a simple helper function that loops over your string, taking in a minimum threshold to meet.  It returns boolean to match the type of output behavior from .Any()
public bool ContainsMinAlphaCharacters(string input, int threshold)
{
    var count = 0;
    foreach (var character in input)
    {
        if (char.IsDigit(character)) count++;
        if (count >= threshold)
        {
            return true;
        }
    }

    return false;
}

Answer: Use regexpressions
two letters: Regex.IsMatch(myString, "[A-Za-z].*?[A-Za-z]");
two digits: Regex.IsMatch(myString, "\d.*?\d");
Answer: Not really. You will have to loop through the string and check if each character is a digit to get the count.


What group name should I use to make a custom block show up in the Creative Inventory in the same category as gem/metal blocks?

Question: Using a resource and behavior pack, I made an Echo Block which is craftable from 9 Echo Shards, and so I want it to appear in the same part of the Creative Mode inventory menu as the other blocks which are made from 9 of a special material (e.g. metals or gems). Ideally, I'd like it to appear right after the Block of Raw Gold, but anywhere in that general vicinity is fine. Right now, I tried setting the category and group (inside echo_block.json in the "blocks" folder within the behavior pack) as follows:
{
    "format_version": "1.20.20",
    "minecraft:block": {
        "description": {
            "identifier": "addtns:echo_block",
            "menu_category": {
                "category": "construction",
                "group": "itemGroup.name.copper"
            }
        },
        "components": {
            "minecraft:light_emission": 7,
            "minecraft:destructible_by_mining": {
                 "seconds_to_destroy": 5
            }
        }
    }
}

(I tried using itemGroup.name.copper because looking at this list of group names, that was the most likely looking candidate out of the given options.)
Result: The custom block shows up as the very last thing in the menu - not anywhere near the copper blocks or the other metal & gem blocks. It is correctly tagged with the category name "Construction," though.
Here is a screenshot:

So, it looks like the line "group": "itemGroup.name.copper" is not doing anything at all. Why is this, and how can I fix it? There seems to be a similar question here, but it is a year old and has no answers.
Everything else about the block (texture, animation, mining and the crafting recipe) works as intended, just not the menu positioning.
Answer: UPDATE:
Before, I had been looking at the Search tab (with all possible blocks and items) instead of a more specific tab within the Creative Inventory. When viewing the "Construction" tab, the custom block does actually show up in the expandable group under the copper block.
Screenshot of "Construction" tab:

However, it still seems strange that in the Search tab, the block is placed in the last slot and not next to the copper blocks. It doesn't seem likely that there is a way to "fix" this, though, and it is a minor issue.
Comment: Thanks - I had *considered* posting this as an answer instead of an edit, but wasn't sure it really constituted a solution.  Since the item group **is** working within the relevant page, it doesn't seem likely that there is an actual fix for the "All" tab, so I accepted your answer.


Scrollbars show up when animating container with textviews (How can i disable it?)

Question: Im using a simple ValueAnimator to animate a LinearLayout's height UP or DOWN.
As I add a new child I use a onPreDrawListener to set the height to what it was prior to the child being added, and then I simply animate the height to the new height.
The animation works good. Problem is, since the TextView isnt fully visible at the start it shows a small scrollbar next to it until its content can be seen on screen.
My question is, how can I totally disable this scrollbar?
Ive tried setting the scrollbars value in xml to none with no change, Ive also tried changing the default fade delay of the scrollbar but it doesnt seem to affect it at all.
Hope theres someone out there who knows a solution. Thanks in advance!
Answer: Solved it by creating the TextView through XML and adding these two lines.
android:scrollbarThumbVertical="@android:color/transparent"
android:scrollbarTrackVertical="@android:color/transparent"


Semicontinuity problem

Question: If $A \subset \mathbb{R}^n$, is that claim true?
$$\chi_A \text{ is LSC} \Longleftrightarrow A\text{ is open}$$
And then how can I prove it?
($\chi_A$ is characteristic function : if $x \in A$ than $\chi_A =1$ otherwise zero.)
Comment: Oh, it's clear to understand it. Thanks a lot
Answer: True. In fact
\begin{equation}
\chi_{A} \mbox{is LSC} \  \Leftrightarrow \ \forall \  t \in \mathbb{R} \  \{x : \chi_A (x) \le t\}\ \mbox{is closed.}
\end{equation}
 But
$$
\{x : \chi_A (x) \le t\} = \left\{
\begin{array}{rcl}
\mathbb{R^{n}} &if& t \ge 1\\
A^{c} &if& 0 \le t <1\\
\emptyset &if& 1 < t.\\
\end{array}
\right.
$$
$\Leftrightarrow A$ is open.
Answer: If by LSC you mean lower semicontinuity and by charcteristic function you mean $\chi_A(x) = \infty$ when $x \notin A$, in the convention of convex analysis, then, this does not hold. The set would be closed iff its characteristic function is LSC.
In general, the following properties are equivalent for an extended real-valued function:

$f$ is LSC on $\mathbb{R}^n$,
the epigraph of $f$ is closed in $\mathbb{R}^n \times \mathbb{R}$,
the sublevel sets $\text{lev}_{\le \alpha} f := \{ x \in \mathbb{R}^n: f(x) \le \alpha\}$ are all closed in $\mathbb{R}^n$.

If by $\chi_A$ you mean $\chi_A(x) = 0$ if $x \notin A$. Then, it holds. The sublevel sets of $\chi_A$ are $\mathbb{R}^n$, $\mathbb{R}^n \setminus A$ and the empty set. For a nonempty set $A$, all of these are closed iff $A$ is open. Hence, the claim is true.
Comment: Sorry for my original post which was wrong.
Comment: What are $ \underline{\chi_{A}}, \overline{\chi_{A}}?$
Comment: @Marcos, not sure what those are, you should ask japee.

Semicontinuity problem


How to auto adjust the bar with respect to the plotBand option in xrange highcharts?

Question: I have applied the plotBand option for the xrange chart where the first row is small than the second on , but when resizing the window the data series are not aligned with the plotBand area.
Currently I'm modifying the y and height of the series by using css, is there any way to make it dynamic to fit into the plotBand area during window resizing.
Jsfiddle: http://jsfiddle.net/karnan796/t1Ldnc69/13/

also the green bar not aligned to the plotBand area
Answer: You need to adjust the plotBands to the groupPadding value:
Highcharts.chart('container', {
    ...,
    yAxis: {
        plotBands: [{
            from: -0.3,
            to: 0.3,
            color: '#00401f'
        }, {
            from: 0.7,
            to: 1.3,
            color: '#2f4776'
        }],
        ...
    },
    series: [{
        pointPadding: 0,
        groupPadding: 0.2,
        ...
    }]
});

Live demo: http://jsfiddle.net/BlackLabel/orpvc50t/
API Reference:
https://api.highcharts.com/highcharts/series.xrange.groupPadding
https://api.highcharts.com/highcharts/series.xrange.pointPadding


React-slick not working on first render

Question: I tried react-slick with dynamic children but it don't work as it should be, the height on first render was coming as some 176px but If I try to resize the browser then it works and the height changes to 514px. I thought may be I force my component to render one more time but it didn't work. I tried to replicate the issue but getting some other issue there.
Take a look at the fiddle
 var Item = React.createClass({
 render: function() {
 return (

 kitten pic

)
 }
 });

var ReactSlickDemo = React.createClass({
render: function() {
var settings = {
  dots: false,
  vertical: true,
  autoplay: true,
  autoplaySpeed: 6000,
  arrows: false,
  slidesToShow: 1,
  slidesToScroll: 1,
  touchMove: false,
  swipeToSlide: false,
  swipe: false
}
return (

  < Slider {...settings
  } >
  < Item / >
  < Item / >
  < Item / >
  < /Slider>

 );
 }
});

 ReactDOM.render( < ReactSlickDemo / > ,
 document.getElementById('container')
  );

Comment: You'll have to force a re-render on resize and then update state in that function.
Comment: @Pavan don't you think my page will flicker by doing that?  Is there any other way to achieve may be some work around on the first render itself. :(
Comment: I can't run your fiddle.
Comment: https://jsfiddle.net/sourabhgarg/sbdm4b4o/ try
Answer: You have added react component <Item> in <Slider> component. So, you need to wrap <Item> inside
 and that should work.

      < Item / >
      < Item / >
      < Item / >

Please find details on below link:
https://github.com/akiran/react-slick/issues/328
Answer: Please add the parent div css:-
.container {   display: inline-block; }

Answer: in my case this worked:
<Slider className={'image-carousel'}>

and set style like this:
.image-carousel {
   display: flex !important;
   flex-direction: row !important;
   align-items: center !important;
 }

React-slick not working on first render


Command grep failing in ansible when grep item not present

Question: Here the following piece of code is waiting  for the kubernetest pod to be disappeared  after launch.
pod do disappeared but the script fails  with the error.
I want to wait till pod disappeared and the continue with rest of the task.
<code>- name: Check ms pod has disappeared
  sudo: yes
  run_once: true
  when: ansible_hostname !=  "inception-{{ vms_subdomain }}"
  shell: "kubectl get pod --namespace=vms | grep {{ item.key }}"
  register: command_res
  with_dict: "{{ microservices }}"
  until: "command_res.rc == 1"
  retries: 10
  delay: 20

TASK [sp-sif : Check ms resouce has disappeared] *******************************
Tuesday 07 February 2017  15:26:52 +0000 (0:00:02.051)       0:03:23.889 ******
FAILED - RETRYING: TASK: sp-sif : Check ms resouce has disappeared (5 retries left).
FAILED - RETRYING: TASK: sp-sif : Check ms resouce has disappeared (4 retries left).
FAILED - RETRYING: TASK: sp-sif : Check ms resouce has disappeared (3 retries left).

failed: [kubernetes-master-vik202vmsservices-1] (item={'key': u'iwan', 'value': {u'streams': u'ncs-alarms'}}) => {"attempts": 4, "changed": true, "cmd": "kubectl get pod --namespace=vms | grep iwanms", "del
ta": "0:00:00.048855", "end": "2017-02-07 15:28:26.707882", "failed": true, "item": {"key": "iwan", "value": {"streams": "ncs-alarmsf"}}, "rc": 1, "start": "2017-02-07 15:28:26.659027", "stderr": "", "stdout
": "", "stdout_lines": [], "warnings": []}
</code>
Comment: This task is not optimal. Try to do it without loop, e.g. add `-o json` to `kubectl` and parse stdout as json to search for all keys at once.
Answer: I think you should work with a failed_when instruction, example:
<code>- name: Check ms pod has disappeared
  sudo: yes
  run_once: true
  #when: ansible_hostname !=  "inception-{{ vms_subdomain }}"
  shell: "cat /tmp/runbmct2.sh|grep raulhugo"
  register: command_res
  #with_dict: "{{ microservices }}"
  until: "command_res.rc == 1"
  failed_when: "'NOT' in command_res.stdout"
  retries: 10
  delay: 20
- name: Check the output
  debug: var=command_res
</code>
As you see in the example I added to your task failed_when: "'NOT' in command_res.stdout"  if you at this and run you playbook again it wont fail.
When you use this kind of command grep you should especify where it will fails.


How do you set a variable global in codeigniter

Question: Note: Ive already set mine to extend to a base controller extending the ci controller for all my controller, the problem is how do i pass and declare a variable and pass it on the template?
Comment: nevermind it seems i can set it in the constructor
Comment: You can follow the this link `https://www.formget.com/codeigniter-global-variable/`
Answer: You can pass the data to view file from controller as below :
Home.php Controller file
<?php
class Home extends CI_Controller {

    public function index()
    {
        $data['title'] = "Title";
        $data['heading'] = "Heading";

        $this->load->view('home', $data);
    }
}

home.php view file

          <title> <?php echo $title; ?> </title>

<?php echo $heading; ?>

Answer: You can use 2 difftent methods view data from the controller.
Method 1 :
Controller file : Home.php
<?php
class Home extends CI_Controller {

    public function index()
    {
        $this->data['title'] = "Title";
        $this->data['heading'] = "Heading";

        $this->load->view('home', $this->data);
    }

}

Method 2 :
Controller file : Home.php
<?php
class Home extends CI_Controller {

    public function index()
    {
        $data['title'] = "Title";
        $data['heading'] = "Heading";

        $this->load->view('home', $data);
    }

}

Note : View file same here. no changes
view file : home.php
enter code here

          <title> <?php echo $title; ?> </title>

<?php echo $heading; ?>