text:
Q: Loop through a list and create a geoJSON dynamically in Java I'm using simpleJSON in Java and I want to create a geojson. I would like to loop through a list that for each element of the list that has longtitude coords an Array would be created for the longtitude and latitude coords. The format of the geojson should be as follows:
{"type": "FeatureCollection",
"crs": {
    "type": "name",
    "properties": {
            "name": "ESPG:4326"
            }
    },
    "features":[

    {
        "type":"Feature",
        "geometry":{
                "type":"Point",
                "coordinates":[55,55]
                },
        "properties":{
                "desc":"something"}
                }
    ]
},{
        "type":"Feature",
        "geometry":{
                "type":"Point",
                "coordinates":[49,32]
                },
        "properties":{
                "desc":"something"}
                }
    ]
}

My problem is that when I'm looping through the list and use the .put for a JSONArray object every time that it changes the previous values instead of just adding the new ones so I end up with something that looks like this:
{"type": "FeatureCollection",
"crs": {
    "type": "name",
    "properties": {
            "name": "ESPG:4326"
            }
    },
    "features":[

    {
        "type":"Feature",
        "geometry":{
                "type":"Point",
                "coordinates":[55,55]
                },
        "properties":{
                "desc":"something"}
                }
    ]
},{
        "type":"Feature",
        "geometry":{
                "type":"Point",
                "coordinates":[55,55]
                },
        "properties":{
                "desc":"something"}
                }
    ]
}

Here is the code that I'm using:
public String toJson(ArrayList<String> array){
  JSONObject featureCollection = new JSONObject();
  featureCollection.put("type", "FeatureCollection");
  JSONObject properties = new JSONObject();
  properties.put("name", "ESPG:4326");
  JSONObject crs = new JSONObject();
  crs.put("type", "name");
  crs.put("properties", properties);
  featureCollection.put("crs", crs);

  JSONArray features = new JSONArray();
  JSONObject feature = new JSONObject();
  feature.put("type", "Feature");
  JSONObject geometry = new JSONObject();

  JSONAray JSONArrayCoord = new JSONArray();
  for(int i=0; i<array.length; i++){
    eachElement = array[i];
    if(eachElement.getLongtitude()!=null){
      JSONArrayCoord.add(0, eachElement.getLongtitude());
      JSONArrayCoord.add(1, eachElement.getLatitude());
      geometry.put("type", "Point");
      geometry.put("coordinates", JSONArrayCoord);
      feature.put("geometry", geometry);

      features.add(feature);
      featureCollection.put("features", features);
    }
  }
  return featureCollection.toString();
}

Any ideas?Thanks!!

A: The problem was I was initializing a JSONObject called feature, JSONArrayCoord and geometry outside of the loop. Here is the corrected code for the for loop:
for(int i=0; i<array.length; i++){
    eachElement = array[i];
    if(eachElement.getLongtitude()!=null){
      JSONObject geometry = new JSONObject();
      JSONArray JSONArrayCoord = new JSONArray();
      JSONObject newFeature = new JSONObject();

      JSONArrayCoord.add(0, eachElement.getLongtitude());
      JSONArrayCoord.add(1, eachElement.getLatitude());

      geometry.put("type", "Point");
      geometry.put("coordinates", JSONArrayCoord);
      feature.put("geometry", geometry);
      features.add(newFeature);
      featureCollection.put("features", features);
    }
  }


text:
Q: can wily monitor grails application? Our enterprise uses  CA Wily Introscope for production live environment. We want to develop an application using GRAILS, but I could not find any documentation on web/stackoverflow regarding this. Has anyone has done this? Is this possible? Else we may have to go back to doing in java.

A: Yes. It can be done quite easily. We do that in our enterprise, Grails is after all java under the hood running on the JVM and Wily has no issues dealing with that.

redpajama_set_name: RedPajamaStackExchange


text:
Q: uncaught reference error while using setter method in Javascript let person = {
  _name: 'Lu Xun',
  _age: 137,

  set age(ageIn) {
    if (typeof ageIn === 'number') {
      this._age = ageIn;
    }
    else {
      console.log('Invalid input');
      return 'Invalid input';
    }
  }

};
console.log(person.set age('bdhh'));

//  While executing the code is is giving error as uncaught reference
   error

A: You're invoking the setter the wrong way.
person.age = 15; // this is how you call your setter

See your updated code in jsFiddle: https://jsfiddle.net/t3uzpobn/4/

A: The way you call the setter is not correct:

let person = {
  _name: 'Lu Xun',
  _age: 137,

  set age(ageIn) {
    if (typeof ageIn === 'number') {
      this._age = ageIn;
    }
    else {
      console.log('Invalid input');
      return 'Invalid input';
    }
  }

};
console.log(person.age = 'bdhh');
console.log(person.age = 13);

A: Your calling method is not correct
let person = {
  _name: 'Lu Xun',
  _age: 137,

  set age(ageIn) {
    if (typeof ageIn === 'number') {
      this._age = ageIn;
    }
    else {
      console.log('Invalid input');
      return 'Invalid input';
    }
  }

};
console.log(person.age = 'bdhh');


text:
Q: Register-WMIEvent Applications And Services Logs (Wail2Ban) I have asked a related question windows-server-wail2ban
I am trying to use Wail2Ban with Windows Server 2012. As stated in the question above the log does not seem to take the IP and thereforeWail2Ban is unable to ban hosts without this information. With a few changes I could then log the IP but could not access shared folder.
A commenter gave me the following link Event 4625 no Source, so it seems there is a secondary log file for failed RDP authentication and this event does have the IP. Therefore I can remove the change made and instead use this log whilst keeping access to shared folders.
The next issue I am having is that apparently it is not possible to use Register-WMIEvent with Application and Service Logs. I have howevre, found some posts that show a workaround for this.Accessing Extended Logs.
I have followed the above and added the relevant key for Microsoft-Windows-RemoteDesktopServices-RdpCoreTS/Operational, now when using Get-EventLog -list I see Microsoft-Windows-RemoteDesktopServices-RdpCoreTS/Operational included in the ouput which was not the case before making the registry change.
I have not really touched Windows/Powershell before I am more php, but I can grasp some concepts of the code. Looking at the wail2ban powershell code I see
$SinkName = "LoginAttempt"
$query = "SELECT * FROM __instanceCreationEvent WHERE TargetInstance ISA 'Win32_NTLogEvent' AND TargetInstance.EventCode= <> 4625"

I then see
Register-WMIEvent -Query $query -sourceidentifier $SinkName
do {
    $new_event = wait-event -sourceidentifier $SinkName

I am able to see the output in the powershell windows but I never see it find event 140 from the application and security logs.
Can anyone advise how I could utilise these logs with the current code or at least minimal modification. I have a feeling if I knew the TargetInstance and -sourceidentifier I may be able to crack this.

A: It seems my issue most likely was I needed a reboot after the registry changes.
The vast majority of my question contains the steps necessary to get this working, however I have answered this question on my related question windows-server-wail2ban:

I now have this working with a few alterations.
I have changed the NTLM settings back to default, this is not
  necessary to do unless you have followed other articles and changed
  these settings.
A commenter pointed me in the direction of Event ID 4625 Without
  Source IP. It seems in the extended logs the IP is logged, just
  not in event 4625.
I followed the following article Accessing Extended Logs and
  added the registry key for
  Microsoft-Windows-RemoteDesktopServices-RdpCoreTS/Operational
I then changed one line in the wail2ban.ps1 file to allow these logs
  to be used
$EventTypes = "Application,Security,System,Microsoft-Windows-RemoteDesktopServices-RdpCoreTS/Operational"

Event logs we allow to be processed
I also had to change the wail2ban_config to add the log file also and
  reference the event type id
# Wail2ban Configuration
[Events]
#[Security]
#4625=RDP Logins
#[Application]
#18456=MSSQL Logins
[Microsoft-Windows-RemoteDesktopServices-RdpCoreTS/Operational]
140=RDP Logins
[Whitelist]
# Add your whitelist here, in the format `IP = Comment`
# Supports plain IPs , e.g. `12.34.56.78  = My Machine`
# Also, ranges, e.g. `11.22.33.0/24 = My Company Range`

Adding the
  [Microsoft-Windows-RemoteDesktopServices-RdpCoreTS/Operational]
  section being the important thing here.
Once I had rebooted so the registry changes could take effect wail2ban
  started to work as expected.
I found wbemtest (put in run) to be useful here as you are able to
  query the logs and check to see if
  Microsoft-Windows-RemoteDesktopServices-RdpCoreTS/Operational is
  part of Win32_NTLogEvent
Whilst I do now have this working, I will be looking at the solution
  proposed by @moteus as this looks like an interesting solution, that
  would be easily moved and installed.


text:
Q: What test do I use for two variables that are ordinal and seem to have a non monotonic relationship? I'm trying to find the right test for association for two likert scale, ordinal variables from a questionnaire I did:

*

*"How often do you recycle" - (1) Almost Daily, (2)2-3 times a week, (3)Once a week, (4) Less than once a week, (5)I don't recycle

*"Recycling can conserve the environment" - Ranges from (1)Strongly agree to (5)Strongly disagree, with (3)Neutral in the middle and a (6)I don't know option.
After graphing the data from my two variables together, it seems to that they don't have a monotonic relationship. From what I've searched, Kendall's tau c might suit my situation but I'm not sure if its a good idea since they don't have a monotonic relationship.
Edit: I'm aware that this seems like a duplicate from another similar question found here, but as I said in the below comments, Glen_b, who answered the question in the other post, mentioned that when one is looking for some general measure of non-monotonic association, you can look at nominal-nominal (such as Cramer's V), and nominal-ordinal association and he gave a reference to an article about that. But I want to know how does looking at nominal-nominal or nominal-ordinal association help me since I'm trying to do ordinal-ordinal association testing?


text:
Q: How do I check if a char is a vowel? This Java code is giving me trouble:
    String word = <Uses an input>
    int y = 3;
    char z;
    do {
        z = word.charAt(y);
         if (z!='a' || z!='e' || z!='i' || z!='o' || z!='u')) {
            for (int i = 0; i==y; i++) {
                wordT  = wordT + word.charAt(i);
                } break;
         }
    } while(true);

I want to check if the third letter of word is a non-vowel, and if it is I want it to return the non-vowel and any characters preceding it. If it is a vowel, it checks the next letter in the string, if it's also a vowel then it checks the next one until it finds a non-vowel.
Example:

word = Jaemeas then wordT must = Jaem

Example 2:

word=Jaeoimus then wordT must =Jaeoim

The problem is with my if statement, I can't figure out how to make it check all the vowels in that one line.

A: Clean method to check for vowels:
public static boolean isVowel(char c) {
  return "AEIOUaeiou".indexOf(c) != -1;
}

A: Your condition is flawed. Think about the simpler version
z != 'a' || z != 'e'

If z is 'a' then the second half will be true since z is not 'e' (i.e. the whole condition is true), and if z is 'e' then the first half will be true since z is not 'a' (again, whole condition true). Of course, if z is neither 'a' nor 'e' then both parts will be true. In other words, your condition will never be false!
You likely want &&s there instead:
z != 'a' && z != 'e' && ...

Or perhaps:
"aeiou".indexOf(z) < 0

A: How about an approach using regular expressions?  If you use the proper pattern you can get the results from the Matcher object using groups.  In the code sample below the call to m.group(1) should return you the string you're looking for as long as there's a pattern match.
String wordT = null;
Pattern patternOne = Pattern.compile("^([\\w]{2}[AEIOUaeiou]*[^AEIOUaeiou]{1}).*");
Matcher m = patternOne.matcher("Jaemeas");
if (m.matches()) {
    wordT = m.group(1);
}

Just a little different approach that accomplishes the same goal.

A: Actually there are much more efficient ways to check it but since you've asked what is the problem with yours, I can tell that the problem is you have to change those OR operators with AND operators. With your if statement, it will always be true.

A: So in event anyone ever comes across this and wants a easy compare method that can be used in many scenarios.
Doesn't matter if it is UPPERCASE or lowercase. A-Z and a-z.
bool vowel = ((1 << letter) & 2130466) != 0;
This is the easiest way I could think of. I tested this in C++ and on a 64bit PC so results may differ but basically there's only 32 bits available in a "32 bit integer" as such bit 64 and bit 32 get removed and you are left with a value from 1 - 26 when performing the "<< letter".
If you don't understand how bits work sorry i'm not going go super in depth but the technique of
1 << N is the same thing as 2^N power or creating a power of two.
So when we do 1 << N & X we checking if X contains the power of two that creates our vowel is located in this value 2130466. If the result doesn't equal 0 then it was successfully a vowel.
This situation can apply to anything you use bits for and even values larger then 32 for an index will work in this case so long as the range of values is 0 to 31. So like the letters as mentioned before might be 65-90 or 97-122 but since but we keep remove 32 until we are left with a remainder ranging from 1-26. The remainder isn't how it actually works, but it gives you an idea of the process.
Something to keep in mind if you have no guarantee on the incoming letters it to check if the letter is below 'A' or above 'u'. As the results will always be false anyways.
For example teh following will return a false vowel positive. "!" exclamation point is value 33 and it will provide the same bit value as 'A' or 'a' would.

A: For starters, you are checking if the letter is "not a" OR "not e" OR "not i" etc.
Lets say that the letter is i. Then the letter is not a, so that returns "True". Then the entire statement is True because i != a. I think what you are looking for is to AND the statements together, not OR them.
Once you do this, you need to look at how to increment y and check this again. If the first time you get a vowel, you want to see if the next character is a vowel too, or not. This only checks the character at location y=3.

A:  String word="Jaemeas";
 String wordT="";
        int y=3;
        char z;
        do{
            z=word.charAt(y);
             if(z!='a'&&z!='e'&&z!='i'&&z!='o'&&z!='u'&&y<word.length()){
                for(int i = 0; i<=y;i++){
                    wordT=wordT+word.charAt(i);
                    }
            break;
            }
           else{
                 y++;
             }

        }while(true);

here is my answer.

A: I have declared a char[] constant for the VOWELS, then implemented a method that checks whether a char is a vowel or not (returning a boolean value). In my main method, I am declaring a string and converting it to an array of chars, so that I can pass the index of the char array as the parameter of my isVowel method:
public class FindVowelsInString {

        static final char[] VOWELS = {'a', 'e', 'i', 'o', 'u'};

        public static void main(String[] args) {

            String str = "hello";
            char[] array = str.toCharArray();

            //Check with a consonant
            boolean vowelChecker = FindVowelsInString.isVowel(array[0]);
            System.out.println("Is this a character a vowel?" + vowelChecker);

            //Check with a vowel
            boolean vowelChecker2 = FindVowelsInString.isVowel(array[1]);
            System.out.println("Is this a character a vowel?" + vowelChecker2);

        }

        private static boolean isVowel(char vowel) {
            boolean isVowel = false;
            for (int i = 0; i < FindVowelsInString.getVowel().length; i++) {
                if (FindVowelsInString.getVowel()[i] == vowel) {
                    isVowel = true;
                }
            }
            return isVowel;
        }

        public static char[] getVowel() {
            return FindVowelsInString.VOWELS;
        }
    }


text:
Q: Exibir uma imagem com Java Swing JLabel Estou tentando exibir uma imagem num app utilizando Swing Java.
Eu pego alguns frames de um vídeo e os exibo como imagem
    private void updateView(){
    Image tempCurrent = imageProcessor.toBufferedImage(currentImage);
    currentImageView.setIcon(new ImageIcon(tempCurrent));

    //JOptionPane.showMessageDialog(null, "um alo");

}

não sou programador Java, mas preciso dar manutenção nesse código.
O procedimento "currentImageView.setIcon" deveria exibir uma imagem no JPanel, mas simplesmente não faz nada.
A variavel currentImaveView é o JLabel video.
A parte engraçada é que se eu executo o "JOptionPane", ah imagem aparece.
Alguém pode me ajudar?

A: Utiliza este código se queres por uma imagem dentro do jlabel:
// Import ImageIcon
ImageIcon iconLogo = new ImageIcon("Images/YourCompanyLogo.png");

"nome da variable da jlabel".setIcon(iconLogo);


text:
Q: Beginner Java OOP I am developing a simple Dog class to create dog objects and display the results.
Dog
_________

int - size
String - breed;
String - name;

__________

Dog(int, String, String)
bark()
bark(int)
toString(): String
print()

I have made the class successfully using getters and setters but my problem is the toString and print methods. I understand the toString method should return a string with the dog details but don't know how to print them.
I could in theory print it like this:
Dog a = new Dog ();
String details = a.toString();
System.out.println(details);

But this isn't how it's specified in the UML spec.
Should the toString method call the print method itself?
and if so, how?
Dog class:
class Dog{
    private int size;
    private String breed;
    private String name;

    //Create getter and setter methods:
    public void setName (String name){
        this.name = name;
    }

    public void setSize (int size){
        this.size = size;
    }

    public void setBreed (String breed){
        this.breed = breed;
    }

    public int getSize () {
        return this.size;
    }

    public String getBreed () {
        return this.breed;
    }

    public String getName () {
        return this.name;
    }

    public void bark () {
        System.out.println("Ruff! Ruff!");
    }

    public void bark (int amtOfBarks){
        for (int i = 0; i < amtOfBarks; i++){
        System.out.print("Ruff! Ruff! ");
        }
    }

     public String toString () {
        return "Name: "+this.name+"\nBreed: "+this.breed+"\nSize: "+this.size;
    }

}

Main Method:
class TestDog {
    public static void main (String [] args){

        Dog rex = new Dog();
        rex.setName("Rex");
        rex.setBreed("poodle");
        rex.setSize(1);

        rex.toString();

        rex.bark(3);
    }
}

A: From your Class structure diagram, the print() method should call System.out.println(this);.
Note : The toString() will be called implicitly. in System.out.println

A: Agree with klemenp.
write your toString() method as follows:
@override
public String toString () {
        return "Name: "+this.name+"\nBreed: "+this.breed+"\nSize: "+this.size;
    }

and it will be implicitly called when you print the Object:
Edit to your code :
class TestDog {
    public static void main (String [] args){

        Dog rex = new Dog();
        rex.setName("Rex");
        rex.setBreed("poodle");
        rex.setSize(1);

        //rex.toString();

System.out.println(rex);

        rex.bark(3);
    }
}

A: in class Dog
public String toString(){
    return "details of dog";
}

so you can:
a = new Dog();

....
    System.out.println(a);

A: from the doc of toString

Returns a string representation of the object. In general, the toString method returns a string that "textually represents" this object. The result should be a concise but informative representation that is easy for a person to read. It is recommended that all subclasses override this method.

so to show your own details you have to override this method. a casual example is given here
public String toString(){
    String s = /// add your detials
    return s;
}

now from the code where you are using dog instance print dog.toString()

A: Creating a dog in this case is :
Dog a = new Dog (120, "breedname", "name");
In order to print the details you need getters,
in a create a get function like

getBreed(){
      return breed; }

in dog, then to print you use:
System.out.println(a.getBreed());

A: in Class Dog write toString() as follows :
@Override
public String toString() {
    return "String describing the details about Dog class";
}

Here @Override annotation is required, because every class has Default toString() method inherited from Object class....

A: The toString() method should not call the print() method. It should be the other way around.
Override toString() and call it from the print() method.
@Override
public String toString()
{
    return "details";
}

public void print()
{
    System.out.println(this.toString()); // same as System.out.println(this);
}

A: To represent your object as String you have to override toString() method.
It is usually done as below (Eclipse as an example can generate it for you, using fields you will tell)
class Dog {

    private int size;
    private String breed;
    private String name;

    //constructors, methods, getters and setters

    @Override
    public String toString() {
        return "Dog [size=" + size + ", breed=" + breed + ", name=" + name
            + "]";
    }

}

Then you may use your instance object directly in System.out.println() and you will get String representation. You do NOT need to do as you said String details = a.toString(); and only then use it.
    Dog dogInstance = new Dog(21, "Dog Breed", "Dog Name");
    System.out.println(dogInstance);

As a result will be:
Dog [size=21, breed=Dog Breed, name=Dog Name]


text:
Q: php.ini.default cp php.ini config have some error in Mac OSX I have a problem about PHP configuration in Mac OSX.
The things is :
If I input the command :
cp php.ini.default php.ini

the php file can not be compiled.but the web server is working.
If I delete "php.ihi" and keep "php.ini.default" file .the php file can be complied.
And the "extension_dir" isn't work .
This is problem just like the question
Enable php on mac snow leopard [closed]
But the following link have not resolve the question.
Any-guys can resolve it?
thank you very much .

A: aha .I have got the answer .
following the command :
vi /etc/php.ini
short_open_tag=off  ==> short_open_tag=on
sudo apachectl restart

now .everything is ok.


text:
Q: Android : Print html document from WebView I'v read that the WebView in Android is a simple browser based on webkit and I was thinking that calling window.print() from my html document will be handled by this "mini-browser".
But no.
After reading many things on that subject, it seems that it's only possible to call a print function from the android app, and not from the html document, and this parti is poorly documented.
Has anyone experienced this before ?
Thanks.

A: Thanks, @martync! Reposting my comment as an answer, as it has turned out to actually answer the question.
The documentation explicitly says "You cannot use JavaScript in a HTML document to trigger printing", and provides an example of how to use the Java API. Chrome for Android (at least Beta) supports window.print().


text:
Q: Finding approximation of root AS for newton approximation of the reciprocal of the square root of 5. Does the function f(x)=1/x - 5^1/2 apply for newton method

A: No, because if you know $5^{1/2}$ to use in $f(x)$, then clearly you know
$\dfrac{1}{5^{1/2}}$.
The usual Newton's method for finding the reciprocal of the square root of $a$ uses $f(x)=\dfrac{1}{x^2}-a$, which has the advantage that the Newton iteration does not need a division:
$$
x_{n+1} = \frac{x_{n}(3-ax_n^2)}{2}
$$


text:
Q: how to run a docker image using its container name rather than image name, which is always creating a new container? as iam new to docker , i cannot find all the commands and docker run -i ubuntu  always creating a new instance of ubuntu rather than opening the previously created container.
I was expecting to run the container i created before .


text:
Q: How to prevent Deadlock exception in SELECT FOR UPDATE after the update? I have an account table with 1 row.
I have 2 threads which do the next:
1st thread:
begin transaction;
select * from account where balance=0 for update;
UPDATE account SET balance = 10 WHERE balance=0;
// waiting here for several seconds
commit transaction;

2nd thread:
begin transaction;
select * from account where balance=0 for update;
commit transaction;

The flow is the next:
1) 1st thread starts and proceeds up to the waiting here for several seconds line.
2) 2nd thread starts and is blocked (logically because the 1st thread has not released pessimistic locks yet).
3) 1st thread successfully commits a transaction.
4) 2nd thread gets an error: ERROR 1213 (40001): Deadlock found when trying to get lock; try restarting transaction
Why Deadlock exception is getting in such scenario, if there is no deadlocks? I tried this scenario with all 4 transaction isolation levels and with all isolation levels the same error is acquired.

A: The problem was my mistake. So the above code actually should work.
My problem was that I used lock in share mode in the first thread and in the second I used for update. I thought that they are the same, but actually they are not. When I changed the first thread to use for update also, they started to work correctly.
Thanks to Shadow who gave a tip to use innodb status monitor to check deadlock transactions information (SHOW ENGINE INNODB STATUS;).


text:
Q: create thumbnail with codeigniter fixed size ; How do I create thumbnail form original size (any size) to 50 x 50 (fixed size) link text
when add images to lightbox all images in any size will resize to 50 x 50 dimention how to implement that with codeigniter image class ;
imagine I have image with 600x320 dimensions when i re size it with maintain_ratio "on" it's gave me 50x27 dimensions when i re size it to 50x50 . anyway if I turn maintain_ration "off" it's resized nicely to 50x50 but output is deformed

A: I'm not exactly sure what you are asking. Do you want to resize an image to 50x50 or do you want to create a lightbox effect. To resize simply follow the instructions in the user guide. They're very straightforward: http://codeigniter.com/user_guide/libraries/image_lib.html
If you want to create a lightbox then you will need to use JavaScript not codeigniter. There are loads out there to choose from for different js frameworks if you don't want to build your own.
Hope that helps.


text:
Q: проанализировать строку необходимо ввести N строк и в каждой из них найти и выписать (в структуру?) : число,слово между символами (например [] ), и одно из двух ключевых слов(например рядовой/сержант (enum?)). Какой наилучший способ реализовать данную задачу?

A: Если у вас строка всегда строго такого формата как бы описали, то можно сделать так:
#include <iostream>
#include <string>
#include <limits>

enum Rank{
    Soldier,
    Sergeant,
    Unknown
};

struct Data{
    int i;
    std::string s;
    Rank r;
};

std::istream& operator>>(std::istream &is, Rank &rank){
    static const std::string soldier("рядовой");
    static const std::string sergeant("сержант");

    std::string s;
    is >> s;

    if(s == soldier){
        rank = Rank::Soldier;
    }else if(s == sergeant){
        rank = Rank::Sergeant;
    }
    else{
        rank = Rank::Unknown;
    }

    return is;
}

std::istream& operator>>(std::istream &is, Data &data){
    is >> data.i;

    is.ignore(std::numeric_limits<std::streamsize>::max(), '[');
    std::getline(is, data.s, ']');

    is >> data.r;

    return is;
}

Использовать потом это можно так:
Data d;
stream >> d;

где stream любой поток ввода. Хоть из файла, хоть из строки, хоть с клавиатуры. Вот пример со строкой:
#include <sstream>

int main(){
    std::string input("42 [привет]  рядовой");
    std::stringstream stream(input);

    Data d;

    stream >> d;
    std::cout << d.i << std::endl; //42
    std::cout << d.s << std::endl; //привет
    std::cout << d.r << std::endl; //0 -> Rank::Soldier
}

Полный пример


text:
Q: How can I prevent TeamCity Cloud Agents (running on Amzon EC2) from leaving defunct volume snapshots when they terminate? I've recently set up TeamCity to use agents running on Amazon EC2. I've been using it for a week or so and noticed my bill was racking up quite quickly. When I looked in my dashboard I had 30 or so snapshots, which I presume I'm being charged for.
TeamCity starts agents on demand and stops them when they've been idle for about an hour. At that point, the instance is deleted. I would expect the corresponding snapshot to be deleted too, but that doesn't seem to be happening, they are piling up like zombies!
When setting this up I followed Roy Osherove's guide and I tried to follow to the letter, but I'm sure I must have missed something. Does anyone know where I went wrong?

A: you can create a special teamcity-agent image, when add esb volume, check the "Delete on Termination" checkbox.


text:
Q: Lightning, why do you need to wait for the flash to reach you? Why would a person about to be struck by lightning have to "wait" for the actual flash to reach them before getting hit?
As the electric field exists regardless of whether or not the charge in the atmosphere is moving and thus once a high enough potential is reached it should ionize the cells in your body regardless of whether or not the "flash" has reached you yet.
Was my initial assumption that you have to wait before the flash reaches you before you feel it wrong? As I have never actually seen someone get hit.
Another question: Why doesn't the flash appear at all points at the same time? The electric field exists everywhere so why doesn't it ionize the atoms at the same time (or at least the speed of light) when there is a high enough PD between the clouds and ground?  Is it because the electric field is stronger at the top then the bottom so ionizes it first at the top?

A: You don't have to wait for the flash to get hit.  However, the flash occurs so astonishingly close to getting hit that no biological system is going to be able to distinguish them.
The flash is an effect caused by the flow of electrons, heating the air.  If there are no electrons flowing, there's nothing heating the air, but also no electrical "hit."  Technically the electrons are flowing through you before the flash occurs, but for all intents and purposes, it's instant.  Technically it takes the lightning a few millionths of a second to heat up the air to 50,000F, so if you have a system that is operating in the millions of samples per seconds range, you could detect the lag between the flow of electricity and the generation of heat.  At any slower speed, the flash is an indication that the current has begun flowing very fast in that particular region of space.
As for why it doesn't appear at the same time, that's a fundamental reality of electricity.  While we sometimes think about electrical circuits as just wires, voltage sources, and resistors, there are also inductive and capacitive elements.  When working with really fast signals like a lightning flash, these play a part.  It's possible to transfer a large amount of charge from one section of the air to another without a path to ground, because the capacitance of the air lets it store a charge.  For a simplified handling of this, one could look at transmission lines, which are similar but don't have the complication of dealing with ionizing gases (or at least you really hope your transmission line doesn't have ionizing gases.  It's typically a bad day for you when that happens!).  These can be looked at to understand how electricity which "travels at the speed of light" can result in slower propagation of the effects that we are observing.
Of course, once a path to ground is "found," the resulting circuit lights up into a lightning flash extremely quickly.  It's not instantaneous, but dang is it fast.  Only the exploratory phase is slow, as we see in some of my favorite lightning videos.  Here's one which shows a bunch of branching feelers, which precede the strike, and here's one which shows a nice leader, which actually forms the lightning strike.
Also, potentially of interest is the Marx generator, which is a high voltage generator built on similar concepts of ionizing gasses.  This naturally has the advantage of being implemented with bulk components (resistors and capacitors) so that you can see what the structure looks like, and it also strikes twice in the same place (especially if that "same place" is Mehdi "Electroboom" Sadaghdar's fingers)!

A: The previous answer is not quite correct.
The real reason is that there doesn't exist a strong field until the lightning flash gets there.
The field in the clouds is strong and the field on the ground are weak. A pathfinding group of charges called a "leader" branches its way towards areas of lower/higher potential (depending on the charge - incidentally leaders are normally negative).
They go into areas that may be high field or low field, but what creates the giant strike is connection to a conductor (i.e. the ground). This is why intracloud lightning has less dramatic flashes (not called strikes unless it hits the ground).
These leaders obviously bring regions of locally very high field with them, so the high field does not exist until this part of the lightning reaches you.


text:
Q: Post Query not working I have made a widget in my functions.php, like this:
class Categories_Widget extends WP_Widget
{
  function __construct() {
        parent::__construct(
            'categories_widget', // Base ID
          ('Categoriën tonen'), // Name
            array( 'description' => ( 'Toon categoriën' ), ) // Args
        );
    }
  function widget($args, $instance)
  {
    extract($args, EXTR_SKIP);

    echo $before_widget;
    //echo "
This is my new widget!
";
    include 'inc/categories.php';
    echo $after_widget;
  }
}
add_action( 'widgets_init', create_function('', 'return register_widget("Categories_Widget");') );

Which fully works. In this widget, I include the categories.php file, which looks like this:
<?php

    $categories = get_categories();

    foreach ( $categories as $category ) {
      ?>
      <div class="categories-block category-<?php echo $category->name ?>">

<?php echo $category->name ?>

        <?php
        $catId = $category->term_id;
        global $post;
        $args = array( 'category' => $catId );
        $posts = get_posts( $args );
        foreach ( $posts as $post ) {
          setup_postdata($post);
          ?>

<a href="<?php the_permalink() ?>"><?php the_title() ?>

          <?php
        }
        wp_reset_postdata();
        ?>

      <?php
    }

For some reason, it shows the category name, but not the query I want to create.

A: For the type of your $catId, you must use the cat parameter.
You can check here the differents parameters allowed.

cat (int) - use category id.
category_name (string) - use category slug.
category__and (array) - use category id.
category__in (array) - use category id.
category__not_in (array) - use category id.


text:
Q: System Verilog, order of execution? In system Verilog if I have:
module my_module (
        input logic clk,
        input logic rst,
        output logic A,
        output logic B
    ;(
    logic A = 1'b0;
    logic B = 1'b0;

Then A and B will be connected to 0 at the same time.
But what about a situation where I have something like this:
module my_module (
    input logic clk,
    input logic rst,
    output logic A,
    output logic B
;(
logic and_out, or_out;
always_ff @(posedge clk, posedge rst) begin
    if (rst == 1'b1) begin
        A <= 1'b0;
        B <= 1'b1;
    end
    else begin
        A <= or_out;
        B <= and_out;
    end
end
always_comb begin
    and_out = A & B;
    or_out = A | B;
end
endmodule

How will be the order between always_ff and always_comb? will they get excuted at same time?

A: In your first example, A and `B are static variables that get initialized before the existence of simulation time, and never assigned again. They are essentially  the same as a constant.
In your second example, all always blocks execute as concurrent processes starting at time 0. But a simulator actually puts all always and initial blocks in a queue to begin execution at time 0 in an unspecified order. Also note that an always_comb is equivalent to
always begin
 and_out = A & B;
 or_out = A | B;
 @(A or B);
end

This guarantees the block gets executed at least one at time 0, so in case somehow A and B get updated first, the outputs will get updated.


text:
Q: Simplify function with condition not working I try to simplify the function Q below:
Q[x_] := Sign[x] /; x > 1
Simplify[Q[x], Assumptions -> x > 1]
(*return Q[x]*)

But it doesn't work. However, if I write something like this:
Q[x_] := Piecewise[{{Sign[x], x > 1}}]
Simplify[Q[x], Assumptions -> x > 1]
(*return 1*)

It works well. Why is this curious difference? I have searched the documentation but found no help. And is there a third way to write the function Q? I found the double curly braces rather ugly.

A: Before feeding a function to "Simplify" it will be evaluated. Now, consider:
Clear[Q];
Q[x_] := Sign[x] /; x > 1
Q[x]
(*Q[x]*)

Clear[Q]
Q[x_] := Piecewise[{{Sign[x], x > 1}}]
Q[x]

As you see, the difference is that in the first stage of evaluation Q[x] is not replaced in the first case and replace in the second case.
If you ensure that Q[x] is always replaced it will do what you want. This can be achieved by using "Set" instead of "SetDelayed":
Clear[Q]
Q[x_] = Sign[x] /; x > 1;
Q[x]
Simplify[Q[x], Assumptions -> x > 1]


text:
Q: Store datapoints persistently before writing to database I have a Django app that receives sensor data. This data is then processed and written to influxDB using the influxdb-client-python library. I would like to write the data in an asynchronous manner and thus return a response to the producer of the data before it is actually written to the database.
However, once I send this response I can no longer afford to lose this data. Since I can never be sure that the server will in fact be able to write the data to influxDB, I was thinking about first writing it to a file and returning a response after this is successful (similar to a WAL). This introduces new problems like making sure the WAL is actually written to a file and most importantly, making sure it is thread-safe since the server may be handling multiple requests concurrently.
Is there any better way of doing this, maybe built-in in Django?

A: That sounds like a queue, background tasks, etc.  You are right, it just displaces the issue, but queues are highly reliable as well.
The standard libs for doing this with Django and/or Rest Framework are:

*

*Celery - Full featured, mature, pluggable queue backends

*Django RQ - Simpler, uses only redis

Celery is probably the right starting point here, since it lets you use a "real" queue backend, but Django RQ+redis will also work if there isn't a ton of load.
Without knowing anything more about your app or architecture, its hard to say more.  There are a lot of queuing systems (Rabbit, ZeroMQ, AWS SQS, Google's, etc).  You can also look into building the queue+processor using, for example, AWS SQS and AWS Lambda Functions (or google versions).


text:
Q: Eclipse plugin for python to give different indentation levels different colors What I'm looking for is an eclipse extension to work with PyDev to make different levels of indentation have different colored indentations before it. For example, reference the code block below
1     for line in list:
2         function.dothing()
3         if condition:
4             do something

The plugin I'm looking for, if it exists, would color the spaces between 1 and for one color (say, red), and then the spaces between the numbers and text on lines 2/3 a different color (say, green), and the spaces between 4 and do yet another color (say, blue). Does anything like this exist, if yes, what's it called?
(Bad) graphical representation:

A: I don't think there's such an option right now. Currently the closer you can get is EditBox: https://github.com/Nodeclipse/EditBox
Not sure, but it may be something that could be added as an option to EditBox if you're up to changing its code...


text:
Q: -SearchQuery not deleting all items According to my powershell code shown, it should delete all items between 90 days ago and yesterday. For example if I ran this now the date range would be 1/29/2014 - 4/28/2014.
$x = ((get-date).addDays(-90)).ToShortDateString()
$y = ((get-date).addDays(-1)).ToShortDateString()
$xy = "$($x)..$($y)"

Search-Mailbox bunnyb2 -SearchQuery "Received:$xy" -DeleteContent -Force

This is deleting most of the mail it is supposed to. However the mailbox still retains all deleted email up until ((get-date).addDays(-1)) at 7pm. The last 5 hours of email that should be deleted are not.
At first I thought it could be a time conversion issue however the machine I am running the command on is in Central Time USA, and the mailbox server is also  Central Time USA.

Also, please do not tell me to do "Search-Mailbox whismj-SearchQuery "Received:<$y" -DeleteContent -Force". This is a whole other can of worms for me. While the code execute absolutely nothing is returned or deleted. However when I take off the < all email that was received yesterday is deleted.

A: I realize this is an older post, but maybe this will help someone searching.
In order to hit the whole date range, you need to provide multiple options to the -SearchQuery parameter (which is expecting a full AQS query). I've never had luck using the syntax you're using, even though it's listed in the documentation; adding the explicit time seems work when using two Received blocks instead of trying to combine them.
To get all mail in January 2015, try using the following:
-SearchQuery "Received: > $('01/01/2015 00:00:00') AND Received: < $('01/31/2015 23:59:59')


text:
Q: Android why does this NOT throw wrong thread exception? I was under the impression that views can only be manipulated from the main thread... however, why does this NOT crash:
public class MainActivity extends Activity {
    TextView tv;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        tv = new TextView(this);
        tv.setText("original text");
        setContentView(tv);

        new Thread(new Runnable() {
            @Override
            public void run() {
                tv.setText("trollollolol i should die here but i won't.");
            }
        }).start();
    }
}

i ran on device & emulator, both work just fine and i see the text change. what's going on?
i also checked thread IDs and the background thread is DEFINITELY not the main thread (threadID = 1)

A: Android doesn't actually stop you from updating the UI from outside the main thread. It's just more of a ticking time bomb. If the main UI thread isn't updating the UI at the time, then your thread can do it.
At least that was my understanding. I don't 100% know for sure, but I've been able to (accidentally) update the UI from outside the main UI thread before. Sometimes it would work and sometimes it wouldn't. But as a good practice i would use a Async task.


text:
Q: Why can't a malicious site obtain a CSRF token via GET before attacking? If I understand correctly, in a CSRF attack a malicious website A tells my browser to send a request to site B. My browser will automatically include my B cookies in that request. Although A cannot see those cookies, if I'm already authenticated in B the request will look legit, and whatever action was asked will be successfully performed. To avoid this, every time that I visit a page of B containing a form, I receive a CSRF token. This token is associated to my session, so if I make a POST to B I MUST include such token; otherwise B rejects my request. The benefit of this scheme is that A will not have access to that token.
I have two questions:

*

*Is the above description correct?

*If so, why can't site A first tell my browser to send a GET to B, obtain the CSRF token from the response, and then use the token to send now a POST to B? Notice that the token will be valid and associated to my session, as the GET also contains all my B cookies.

Thanks!

A: Your description is correct.
If site A tells your browser to go to B and get the token, that's fine, but as it is a cross-domain request, A will not have access to the token in Javascript (this is a browser feature). So when A tells your browser to go back to B and actually do something, it still cannot include the token in the request.
That is, unless B set the token as a cookie. Evidently, that would be flawed, because the token cookie would also be sent, thus negating any protection. So the token in this case must be sent as either a form value or a request header (or something else that is not sent automatically like a cookie).
This also means that if B is vulnerable to cross-site scripting, it is also vulnerable to CSRF, because the token can then be stolen, but CSRF is the smaller problem then. :)

A: Correct.
Site A can't get site B's csrf token because of the browser's CORS strategy.
And we need to validate the request's referer(It can be forged).
https://en.wikipedia.org/wiki/HTTP_referer
It is also a good practice to validate the crsf token in url(AKA query string).
FYI,Laravel, a popular web framework, uses a hidden CSRF token field in the form to prevent csrf attack.


text:
Q: Can't get first person controls works I'm starting with Three.js, and I'm trying to set up a simple first person controls in my scene, which is containing a single sphere. I just see a black screen. There are no errors.
Without FirstPersonControls, I can see the sphere.
What am I doing wrong ?
<!DOCTYPE html>

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

A: FirstPersonControls is designed to work with full-width canvases, so you need to set
var RENDER_WIDTH = window.innerWidth, RENDER_HEIGHT = window.innerHeight;

Also remove you style settings.
Finally, to make it easier to "find" your sphere, set controls.lookVertical = false -- just for now.
From that point, you'll just have to experiment.


text:
Q: 'Anchor' component to the right of a row of components in GridBagLayout I want to display a list of components graphically across the screen in a row. I'm currently attempting to do this with the Grid Bag Layout manager. Additonally, the button to create a new component is just another component and is also included in the row. However, I want the button to always be the right most component. I've illustrated what I mean in the mock-ups below.
The example above is before a component was added, and the example below is after.

The only solution I can see is to manually remove and re-add the Creation button every time a component is added, but I'd like to find a more elegant way of fixing this than that.

A: I solved this by removing the component before I added a new one, and then just adding it again after the new component was added.


text:
Q: SQL mariaDB trigger on column update I have a 1st table having columns as id, name and status and 2nd table columns as id and status.
Whenever there is any update on 1st table, status column for a specific id column , i want to update the 2nd table's column status value as 1st table status value.
1st table id column = 2nd table id column

A: This is how you would create this trigger:
CREATE TRIGGER update_status
    AFTER UPDATE
    ON table1
    FOR EACH ROW
BEGIN
    UPDATE table2
    SET status = NEW.status
    WHERE id = NEW.id;
END

This is for the UPDATE only. You probably have to create another trigger which inserts new rows from table1 in table2:
CREATE TRIGGER insert_status
    AFTER INSERT
    ON table1
    FOR EACH ROW
BEGIN
    INSERT INTO table2 (id, status)
    VALUES (NEW.id, NEW.status);
END


text:
Q: Raise an error inside a generator if no data has been yielded I want to raise an error inside a generator if no yield has happened.
Below is a very simplified example of my issue:
def test1():
  for i in range(1, 28):
    if i % 5 == 0:
      yield str(i)
  raise CustomEXception

def test2(x):
  for i in range(1, 38):
    if i % x == 0:
      yield str(i)
  raise CustomEXception

a = test1()
b = test2()

The test1 and test2 in reality are looping through data, search for matches, manipulate the data and yield. If no data is yielded, an error is raised.
for w,q in itertools.products(a, b):
   try:
     print(w + q)
     # do some more operation with w, q
   except CustomException:
     # do some more checking

The results from the generators are used to create a Cartesian product.
The problem is that this doesn't work, the exception is raised, with nothing yielded before.

A: Also you must make sure your functions are only going to raise an exception if there have been no yields
def test2(x):
    fail = True
    for i in range(1,38):
        if i % x == 0:
            fail = False
            yield str(i)
    if fail:
        raise ValueError

This way, if there are one or more yields then no exceptions are raised and product will produce its own generator.

A: Since your exception is raised by the product call which exhausts the iterators, you have to structure it differently:
try:
    for w, q in itertools.products(a, b):
        print(w + q)
        # do some more operation with w, q
except CustomException:
    # do some more checking

Notice that now, products(a,b) is within the try-block. The loop body itself only ever processes w,q after it is handed the execution flow from the generator upon a successful yield.


text:
Q: Can't load images in Pygame using Pydroid 3 app. The error says unsupported file format for both jpg and png. But pygame.image.get_extended() = True import sys
import pygame
pygame.init()
screen = pygame.display.set_mode((0,0))
red = (255,0,0)
blue = (0,0,255)
img = pygame.image.load("car.png")

while True:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            pygame.quit()
            sys.exit()

    screen.blit(img,(0,0))
    screen.fill(red)
    pygame.display.flip()

"""
Examples on the app use png images, when I run pygame.image.get_extened() is says True so I should be able to use files other than BMP right?


text:
Q: Handling cookies in HTTP request in Jmeter I have a Jmeter load project the requires retrieving 2 values of cookies and resend them in the other requests.
Here is my project test plan:
-Test Plan
-Thread Group
-Login request
-Payment page
-Payment history page
-HTTP Cookie Manager
-HTTP Header Manager
-View Results Tree

Cookie Data:
JSESSIONID=0000SZb55xyLAaqLlDzumq_PpIw:-1; XSRF-TOKEN=a684e233-648e-4219-ae21-25fb362e232d
The cookie data is received successfully from the login request by cookie manager and sent in the second request (Payment page) but in the third request (Payment history page) only JSESSIONID is sent and I don't know why the second cookie is not sent in the third request.

A: Most probably you are not getting this cookie in Set-Cookie response header for second request therefore it doesn't get picked up by the cookie manager. If your application expects the cookie in 3rd request it might be your application issue.
As a workaround you can store the cookie value into a JMeter Variable for later re-use.

*

*Add the next line to user.properties file (lives in the "bin" folder of your JMeter installation
    CookieManager.save.cookies=true

*Restart JMeter to pick the property up

*That's it, now you should be able to refer cookie value as ${COOKIE_XSRF-TOKEN} where required, for example add another HTTP Cookie Manager as a child of the 3rd request (according to Scoping Rules "local" cookie manager will override the "global" one) and define XSRF_TOKEN and other cookies if needed there)

See Using the HTTP Cookie Manager in JMeter article for more information on handling cookies in JMeter tests.


text:
Q: Missing Channel Offset in Sequence 0 Source Room:X Target Room:Y in altium I just followed this Page for a simple project but I get

Missing Channel Offset in Sequence 0 Source Room:X Target Room:Y in Altium

error. I have set/checked all the components channel offsets, but everything seems correct.
Here is my projet:
enter link description here
I will be thankful if you could help me.


text:
Q: preg_match не работает с русскими буквами Почему данный код не выводит 1 ?
$message = "Андрей";

if(preg_match('/^[а-яА-ЯёЁa-zA-Z]+$/', $message)){

    echo "1";
}

A: Если вам надо разбирать строку в UTF-8, необходимо использовать модификатор u

u (PCRE_UTF8) Этот модификатор включает дополнительную
  функциональность PCRE, которая не совместима с Perl: шаблон и целевая
  строка обрабатываются как UTF-8 строки. Недопустимая целевая строка
  приводит к тому, что функции preg_* ничего не находят, а неправильный
  шаблон приводит к ошибке уровня E_WARNING. Пятый и шестой октеты UTF-8
  последовательности рассматриваются недопустимыми с PHP 5.3.4 (согласно
  PCRE 7.3 2007-08-28); ранее они считались допустимыми.

То есть в вашем случае:
preg_match('/^[а-яА-Яa-zA-ZёЁ]+$/u', $message)

A: У меня в таком варианте заработала:
$message = "Андрей";

 if(preg_match('/^[а-яА-Яa-zA-ZёЁ]+$/u', $message)){
      echo "1";
}


text:
Q: Inverse Trigonometry Question (Stuck in Algebraic Simplification) The original question:

If x and y are of same sign, then find the value of $$\cfrac{x^3}{2} \csc^2 \left(\cfrac{1}{2}\tan^{-1} \cfrac{x}{y}\right) + \cfrac{y^3}{2} \sec^2 \left(\cfrac{1}{2}\tan^{-1} \cfrac{y}{x} \right) $$

This is my attempt to the question:
$$\cfrac{x^3}{2\sin^2 \left(\cfrac{1}{2}\tan^{-1} \cfrac{x}{y}\right)} + \cfrac{y^3}{2\cos^2 \left(\cfrac{1}{2}\tan^{-1} \cfrac{y}{x} \right)} $$
$$
=\cfrac{x^3}{1-\cos(\tan^{-1} (x/y))} + \cfrac{y^3}{1+\cos(\tan^{-1}(y/x))} $$
$$
=\cfrac{x^3}{1 - \cfrac{|y|}{\sqrt{x^2+y^2}}} + \cfrac{y^3}{1+\cfrac{|x|}{\sqrt{x^2+y^2}}} $$
I'm not sure how to simplify this further. I've been trying to simplify this further for a long time but couldn't get any desirable answer.
Options are:
(A) $(x-y)(x^2+y^2)$
(B) $(x+y)(x^2-y^2)$
(C) $(x+y)(x^2+y^2)$
Also, any other better/alternate way to approach the question is welcomed.

A: i will take $x,y$ to have the same sign. using double angle formula, we have  $$\tan^{-1}(y/x) = 2t, \tan^{-1}(x/y) = \pi/2 - 2t, r = \sqrt{x^2 + y^2}.$$ then
$$\begin{align} \cfrac{x^3}{2} \csc^2 \left(\cfrac{1}{2}\tan^{-1} \cfrac{x}{y}\right) + \cfrac{y^3}{2} \sec^2 \left(\cfrac{1}{2}\tan^{-1} \cfrac{y}{x} \right) &= \frac{x^3}{2\sin^2(\pi/4 - t)} + \frac{y^3}{2\cos^2 t}\\
&=\frac{x^3}{1 - \cos (\pi/2 - 2t)} + \frac{y^3}{1 + \cos 2t }\\
&=\frac{x^3}{1 - \sin 2t} + \frac{y^3}{1 + \cos 2t }\\
&=\frac{x^3}{1 - \frac y r} + \frac{y^3}{1 + \frac xr }\\
&= \frac{r\left(x^3(r+x)+y^3(r-y)\right)}{(r-y)(r+x)}\\
&=\frac{r\left( r(x^3+y^3)+(x^4 - y^4)\right)}{(r-y)(r+x)} \\
&=\frac{r(x+y)\left( r(x^2-xy+y^2)+(x - y)(x^2+y^2)\right)}{(r-y)(r+x)}\\
&=\frac{r^2(x+y)\left( r^2-xy +r(x - y)\right)}{(r-y)(r+x)}\\
&=r^2(x+y)=(x^2+y^2)(x+y) \end{align}$$


text:
Q: Erro de Locale / ORA-01843: not a valid month / JVM language Estou rodando uma aplicação que é um microserviço feito em Spring Boot.
Ao executar um código local, ele consegue obter os dados do banco. É a geração de um relatório que busca dados no banco oracle que está setado as configurações como pt/BR em geral.
SELECT * FROM NLS_SESSION_PARAMETERS;

Resultado:
NLS_LANGUAGE    BRAZILIAN PORTUGUESE
NLS_TERRITORY   BRAZIL
NLS_CURRENCY    R$
NLS_ISO_CURRENCY    BRAZIL
NLS_NUMERIC_CHARACTERS  ,.
NLS_CALENDAR    GREGORIAN
NLS_DATE_FORMAT DD/MM/RR
NLS_DATE_LANGUAGE   BRAZILIAN PORTUGUESE
NLS_SORT    WEST_EUROPEAN
NLS_TIME_FORMAT HH24:MI:SSXFF
NLS_TIMESTAMP_FORMAT    DD/MM/RR HH24:MI:SSXFF

Eu faço o deploy no jenkins após commit. E a aplicação é colocada no kubernetes.
Ele gera o erro Caused by: java.sql.SQLDataException: ORA-01843: not a valid month
Ao ler o locale default, do código no servidor, eu percebi que ele está com default Locale default: en_US
Eu já tentei mudar o locale de algumas maneiras.
Uma delas foi no application.yml:
spring.mvc.locale: pt_BR

Já tentei setar programaticamente após a aplicação subir:
    @EventListener(ApplicationReadyEvent.class)
    public void doSomethingAfterStartup() {
        Locale.setDefault(new Locale("pt", "BR"));
        System.out.println("LocaleConfig | Locale Setted");
        System.out.println(Locale.getDefault());
    }

E de fato, quando leio o locale no início do método do controller que recebe a requisição, ele já está setado como pt/BR.
2021-10-25 12:54:08.913  INFO 1 --- [or-http-epoll-3] b.c.u.a.v1.controller.MonthlyController  : MonthlyController / Locale for generate excel: pt_BR

Mesmo assim continua apresentando o mesmo erro:
2021-10-25 12:54:10.130  WARN 1 --- [or-http-epoll-3] o.h.engine.jdbc.spi.SqlExceptionHelper   : SQL Error: 1843, SQLState: 22008
2021-10-25 12:54:10.131 ERROR 1 --- [or-http-epoll-3] o.h.engine.jdbc.spi.SqlExceptionHelper   : ORA-01843: not a valid month

A: O problema foi resolvido adicionando os parâmetros da JVM no pipeline do servidor.
-Duser.country=BR -Duser.language=pt
De outras maneiras, conforme acima, não conseguia resolver.


text:
Q: Shall. I use a preposition here? which one is correct?

We had a very small marriage ceremony where only close relatives and friends were invited.

Or

We had a very small marriage ceremony where only close relatives and friends were invited to.

A: The first sentence reads okay to me; I would not use the second sentence.
But I would suggest this rewording:
We had a very small marriage ceremony to which only close relatives and friends were invited.
Or better yet, to avoid switching to the passive voice:
We had a very small marriage ceremony to which we invited only close relatives and friends.


text:
Q: How to dynamically add array values into string? I have array with db col names.
$db_cols = ['name', 'age', 'gender'];

I need to add POST values into db query from array $db_cols dynamically. Result must be something like this.
$db->query('INSERT INTO tbl (id, '.implode(', ', $db_cols).', order) VALUES (?, '.str_repeat('?, ', count($db_cols)).' ?)', [$_POST['id'],$_POST['name'], $_POST['age'], $_POST['gender'], $order]);

But I need modify this part of the code above $_POST['name'], $_POST['age'], $_POST['gender']
Query result:
INSERT INTO tbl (id, name, age, gender, order) VALUES (?, ?, ?, ?, ?),[1, 'Joe', '35', 'male', 1]

Thank you for help.


text:
Q: Xcode 7 with Swift 2 - AppCrashing today I downloaded the new Xcode Version and update my App to Swift 2 code.
But now my App is crashing on start the App on my iPad.
The error looks like this:
**dyld`dyld_fatal_error:
->  0x120099088 <+0>: brk    #0x3**

This is my only information.
Informations:
I use my iPad with iOS9 and my Deployment is iOS9 too.
I use belowed shown libaries:
  pod 'Alamofire', '~> 2.0'
  pod 'ActionSheetPicker-3.0', '~> 1.5.1'
  pod 'ActionSheetPicker-3.0', '~> 1.5.1'
  pod 'AFDateHelper', '~> 3.1.0'
  pod 'SwiftHUEColorPicker', '~> 0.1.5'
  pod 'UIColor_Hex_Swift', '~> 1.1'
  pod 'MBProgressHUD', '~> 0.9.1'

Furthermore I use this libaries for my own Framework which is implemented in my App too.
 pod 'SwiftyJSON', '~> 2.2'
 pod 'SwiftSerializer', '~> 0.1'

I hope you can help me.
Best regards,
Seb

A: Try to Product > Clean your project.
Or press Cmd + Q and relaunch Xcode.


text:
Q: How to change passive present continuous tense to its infinitive form? "The meal is being cooked" to "I heard the sound of the meal being cooked"? Eg: The meal is being cooked.
if we say
1- I heard the sound of the meal being cooked, then people may interpret as "I heard the sound of the meal that is cooked" and we lost its continuous meaning
2- I heard the sound of the meal being being cooked, the sentence is weird.
How to change passive present continuous tense to its infinitive form?

A: I think your understanding of point #1 is actually incorrect.  The sentence:

I heard the sound of the meal being cooked.

would be interpreted by most people to mean "I heard a sound" and "the sound was produced by the activity the meal being cooked".  (I heard somebody cooking it)
If instead, you actually wanted to say that you heard the sound of the meal itself, not the sounds of cooking (the meal is currently being cooked, but that's a side-issue), then you would need to say something like:

I heard the sound of the meal which is being cooked.

(Though I'm not really sure what sounds a meal would make by itself)
You are correct that your sentence #2 is weird.  In fact, it is actually just wrong (not grammatically correct, and makes no sense).


text:
Q: MySQL JOIN Abuse? How bad can it get? I've been reading a lot about Relational Databases using many JOIN statements on every SELECT. However, I've been wondering if there's any performance problem on the long run when abusing this method.
For example, lets say we have a users table. I would usually add the "most used" data, instead of doing any extra JOINs. When I say the "most used" data, for instance, would be the username, display picture and location.
This data would always be needed when displaying any user interaction on the website, example: on every comments table JOIN for articles. Instead of doing a JOIN on the users & users_profiles tables to get the 'location' and 'display', just use the information on users table.
That's my approach, however I do know that there are a lot of excellent and experienced programmers that can give me a word of advice about this matter.
My questions are:
Should I try to be conservative with the JOINs? or should I use them more? Why?
Are there any performance problems on the long run when using JOIN a lot?
Note: I must clarify, that I'm not trying to avoid JOINS at all. I use them only when needed. On this example would be comment/article authors, extra profile information that only displays on user profiles pages... etc.

A: My advice on data modeling is:

*

*You should favour optional (nullable) columns over 1:1 joins generally speaking. There are still instances where 1:1 makes sense, usually revolving around subtyping. People tend to be more squeamish when it comes to nullable columns than they do about joins oddly;

*Don't make a model too indirect unless really justified (more on this below);

*Favour joins over aggregation. This can vary so it needs to be tested. See Oracle vs MySQL vs SQL Server: Aggregation vs Joins for an example of this;

*Joins are better than N+1 selects. An N+1 select is, for example, selecting an order from a database table and then issuing a separate query to get all the line items for that order;

*The scalability of joins is usually only an issue when you're doing mass selects. If you select a single row and then join that to a few things rarely is this a problem (but sometimes it is);

*Foreign keys should always be indexed unless you're dealing with a trivially small table;

More in Database Development Mistakes Made by AppDevelopers.
Now as for directness of a model, let me give you an example. Let's say you're designing a system for authentication and authorization of users. An overengineered solution might look something like this:

*

*Alias (id, username, user_id);

*User (id, ...);

*Email (id, user_id, email address);

*Login (id, user_id, ...)

*Login Roles (id, login_id, role_id);

*Role (id, name);

*Role Privilege (id, role_id, privilege_id);

*Privilege (id, name).

So you need 6 joins to get from the username entered to the actual privileges. Sure there might be an actual requirement for this but more often than not this kind of system is put in because of the hand-wringing by some developer thinking they might someday need it even though every user only has one alias, user to login is 1:1 and so on. A simpler solution is:

*

*User (id, username, email address, user type)

and, well, that's it. Perhaps if you need a complex role system but it's also quite possible that you don't and if you do it's reasonably easy to slot in (user type becomes a foreign key into a user types or roles table) or it's generally straightforward to map the old to the new.
This is thing about complexity: it's easy to add and hard to remove. Usually it's a constant vigil against unintended complexity, which is bad enough without going and making it worse by adding unnecessary complexity.

A: Some bright person once said:

Normalize until it hurts, denormalize until it works!

It all depends on the type of joins, and the join conditions, but there are nothing wrong with them. Joins ON table1.PK = table2.FK are very efficient.

A: If the data is 1 <-> 1, and you will not have many null fields, dont over normalize. You can still specify the fields required ("most used data") in the select statements.

A: Fear not joining.  The relational model is strong and you should employ it.  Someone always discussed N+1, but also consider--in your context--joining against users often for security purposes too as the query can additionally mandate user existence, status, session correctness, and field expectation.
Many large sites go so far as to have session table and http request table for every request, always joined against each other for the page queries.  Benefit is that parameters are always matched to sessions, sessions to proper users, user status always checked, &c &c but moreso that it allows for some interesting scale-out benefits.
Long story, do it wisely, but don't skimp on joining.

A: As others have said - joins aren't a thing to avoid at all.  In fact, in most models it is rare not to have a few joins in every single query that the application runs.
Even in the biggest queries they aren't usually a performance problems - and often fix performance problems that would occur if you have redundant and repeating data all over the place.
However, be aware that under the cover the database just joins two tables at a time.  So, joins necessitate multiple steps by the database that are invisible to the developer.  When it does these joins it has to make a few decisions about how to go about it:

*

*walk through all the values on the left table, then match them one at a time to the values on the right?

*Do just the opposite?

*Sort the keys from both tables and walk through them at the same time?

*Build hashes of keys on both sides?

*Apply filtering criteria before or after a given join?

*etc

So, if your joins are complex ultimately the efficiency will be driven by the sophistication of your optimizer/planner and the currency and detail of your statistics.  MySQL isn't a strong contender here - so I'd generally keep my model and sql a little simpler than if I was using something else.  But a few joins per query should almost always be fine.


text:
Q: How to extract a perticular data from xml whole output data in C++ I have a C++ function which prints whole xml output data on console. This data has many elements. I want to print particular element on the console.
My function looks like below:
 void SampleEventListner::OnBarcodeEvent(short int eventType, std::string & pscandata){
    cout << pscandata << endl;
}

This above code is printing output like the attached photo. Out of many elements i need to print only datalabel. How can we do this?. Thank you.

A: Yoy may do it with open source tinyxml2 library.

A: I like to use pugixml; small lightweight and fast.
#include <iostream>
#include "pugixml.hpp"

std::string XML = "<outArgs>\
  <scannerID>1</scannerID>\
  <arg-xml>\
    <scandata>\
      <modelnumber>DS9308-SR00004ZZWW</modelnumber>\
      <serialnumber>19361523701373 </serialnumber>\
      <datalabel>0x68 0x74 0x68 0x74 0x68 0x74 0x68 0x74 0x68 0x74 0x68 0x74 0x68 0x74</datalabel>\
      <rawdata>0x00 0x01 0x00 0x01 0x00 0x01 0x00 0x01 0x00 0x01 0x00 0x01 0x00 0x01</rawdata>\
    </scandata>\
  </arg-xml>\
</outArgs>";

void PrintTag(std::string &pscandata)
{
  pugi::xml_document DOM = pugi::xml_document();
  pugi::xml_parse_result result = DOM.load_string(pscandata.c_str(), pugi::parse_default);
  if (result)
    std::cout << DOM.select_node("//datalabel").node().first_child().value() << "\n";
  else
    std::cout << "Error parsing XML. Offset:" << result.offset;
}

int main(int argc, char *argv[])
{
  PrintTag(XML);
}


text:
Q: Configure TP-LINK router to broadcast my network IP address I have a TP-Link model:TL-WR1043ND which I want to use in my network of 172.23.5... but when ever I connect it broadcast 192.168.1.1 network to all client that connect as the result, they can't access the map drive of the server. I want to set it up so that it will broadcast the ip of my network I am using DHCP

A: the manual is availabe here: http://tp-link.com/Resources/document/TL-WR1043ND_V1_User_Guide.pdf
and the section on configuring DHCP starts on page 55. see figure 4.7.1 for the screen you would use to set your dhcp pool start and end addresses.


text:
Q: Hit Test behavior I have the following code
public partial class MainWindow : Window
{
    public MainWindow() {
        InitializeComponent();
    }

    List<UIElement> ucs = new List<UIElement>();

    private void Window_PreviewMouseLeftButtonDown(object sender,
        MouseButtonEventArgs e)
    {
        ucs.Clear();

        Point p = e.GetPosition((UIElement)sender);

        VisualTreeHelper.HitTest(this, null,
            new HitTestResultCallback(MyHitTestCallback),
            new PointHitTestParameters(p));

        Console.WriteLine("ucs.Count = {0}", ucs.Count);

        foreach (var item in ucs)
        {
            Console.WriteLine("item: {0}", item.ToString());
        }
    }

    HitTestResultBehavior MyHitTestCallback(HitTestResult result)
    {
        ucs.Add(result.VisualHit as UIElement);
        return HitTestResultBehavior.Continue;
    }
}

this is my window
<Window>
    <Grid>
        <my:UserControl1 HorizontalAlignment="Left" Margin="82,88,0,0" x:Name="userControl11" VerticalAlignment="Top" />
        <my:UserControl1 HorizontalAlignment="Left" Margin="168,166,0,0" x:Name="userControl12" VerticalAlignment="Top" />
        <my:UserControl1 HorizontalAlignment="Left" Margin="231,130,0,0" x:Name="userControl13" VerticalAlignment="Top" />
    </Grid>
</Window>

this is my UC
<UserControl>
    <Grid>
        <Label Content="Label" Height="44" HorizontalAlignment="Left" Name="label1" VerticalAlignment="Top" FontSize="20" FontWeight="Bold" Width="78" Background="#FF4B9FC4" BorderBrush="#FF020A0D" BorderThickness="1" />
    </Grid>
</UserControl>

this is the output when I click ON A USER CONTROL, then on a intersection of 2 UserControls:
ucs.Count = 2
item: System.Windows.Controls.Border
item: System.Windows.Controls.Border
ucs.Count = 3
item: System.Windows.Controls.Border
item: System.Windows.Controls.Border
item: System.Windows.Controls.Border

Why this? Where is the UserControl under the mouse instance?
PS:
Now, when I have on the Label the BorderThickness = 0
ucs.Count = 3
item: System.Windows.Controls.TextBlock
item: System.Windows.Controls.Border
item: System.Windows.Controls.Border
ucs.Count = 3
item: System.Windows.Controls.TextBlock
item: System.Windows.Controls.Border
item: System.Windows.Controls.Border

A: The UserControl1 is invisible. Its contents are visible, but your UserControl1 instance itself does not have any visuals of its own. (And it never will. A user control's job is really just to contain other things.)
Hit testing only reports elements that make a direct contribution to the visual tree. And since hit testing considers each element in isolation, this means that elements that are acting purely as containers don't show up. (And a related fact is that hit testing only considers the pixels that actually got painted. So if you have a Border where you've set the BorderBrush and a non-zero BorderThickness but you have no Background, the hit test will only consider the border outline to be a hit - points inside of the border will not be considered to hit the border because it's not painting anything in its interior.
If you need to do hit testing of a "this thing, or anything inside this thing" style, then either either

*

*use mouse enter/leave events - those bubble, and so they will get raised even on invisible container elements

*use IsMouseOver or

*use the hit test function you're using, passing the user control as the first argument, and treat any hit as an indication that the hit test point is inside the user control

The third one is more complex, but if you need to hit test points other than the one currently under the mouse, you'd need to use it.


text:
Q: Exchange two nodes in LinkedList I encountered a simple "problem": Exchange two nodes in a LinkedList (.NET 2) How can I do it in a "optimal" way. Thanks!
Dim label1 As New Label()
Dim label2 As New Label()
'... some code
Dim testList As New LinkedList(Of Label)
'... some code
Dim node1 As LinkedListNode(Of Label) = testList.Find(label1)
Dim node2 As LinkedListNode(Of Label) = testList.Find(label2)

If ??? Then
  ' exchange two nodes
End If

is the
node1.Value = label2
node2.Value = label1

sufficient?

A: How about:
testList.AddAfter(node1, node2.Value)
testList.AddAfter(node2, node1.Value)
testList.Remove(node1)
testList.Remove(node2)

This is four O(1) operations, and will work whether the nodes are at the start or end of the list. The only problem is that if node1 == node2 it will add two new nodes, remove the existing one, and then throw an exception as it tries to remove it again. Obviously this isn't a problem if your algorithm makes sure they're different to start with...
EDIT: Doh. The MSDN docs misled me into thinking that Value is read-only. (It says: "Gets the value contained in the node" - rather than "Gets or sets [...]." Actually it's writable, so you could do:
Label tmp = node1.Value
node1.Value = node2.Value
node2.Value = tmp

On the other hand, anything that already has a reference to the nodes will see the change, which may not be what you want. Of course, anything that already has a reference to the nodes will end up seeing nodes which are no longer part of the list using my first approach...

A: I don't know the implementation, but if your nodes have simply one value (in addition to the next and previous links), you can just swap the values.


text:
Q: Fixed serialization field order I need a basic sign of a form submissión. I serialize the fields and get sha1 of json string. The problem is th serializer, sort the fields randomly. Can I set a fixed fields order?
Thx

A: I suppose you´re speaking about front-end.
I´m talking hearsay but dictionary order attributes randomly as well. So Why don´t you order them by javascript or others? When you receive the Json, you can order the values and then paint them. Kind of (selection sort):
var data = json.split(";");
var i,j,k
for (var i = -1; i < data.length(); i++){
    for (j = k = i; k < data.length(); k++ ) {
      if (data[j] > data[k]) j = k;
    }
    [arr[j], arr[i]] = [arr[i], arr[j]];
 }
 return data;
}

You can use another sorting algorythm if you want.
https://h3manth.com/javascript-sorting/


text:
Q: apache cxf maven plugin wsdl wildcard configurations In a maven project structure, I have several wsdls/schemas organised inside separate folders under resources folder. I have to configure apache cxf maven plugin in pom.xml to generate classes from all the wsdls. How can i configure a relative path with wildcard for this? I used the following but was not successful.
<wsdlOption>
 <wsdl>${basedir}/src/main/resources/wsdl/**/*.wsdl</wsdl>
</wsdlOption>

Please let me know how i can configure such a relative path.

A: From CXF doc, you should be able to do it like this:
<configuration>
    <sourceRoot>${project.build.directory}/generated/cxf</sourceRoot>
    <wsdlRoot>${project.basedir}/src/main/resources/wsdl</wsdlRoot>
    <includes>
        <include>*.wsdl</include>
    </includes>
</configuration>


text:
Q: How can I control the slash in Url Action in ASP.NET MVC I'm on working an Asp.net MVC project that I have use an URL like that:
Terms and Conditions

Which I want it go to: /Privacy/Index#Legal
But it auto added the slash which make the URL not good: /Privacy/Index#/Legal
What I'm wrong? Sorry I'm a new Asp.net MVC developer. Thanks
UPDATED:
I found the problem that my project used AngularJS, the solution that config the $locationPrivider will solve the problem:
$locationProvider.html5Mode({
    enabled: true,
    requireBase: false,
    rewriteLinks: false
});

Thanks for all your support.

A: You can configure whether or not to use trailing slash in urls throug AppendTrailingSlash property of RouteCollection object.
In order to remove it from all URLs in your application you should modify RegisterRoutes method
public class RouteConfig
 {
        public static void RegisterRoutes(RouteCollection routes)
        {
            ///add this line
            routes.AppendTrailingSlash = false;
        }
 }

Once you set this up @Url.Action("Index","Privacy") will be generated without  trailing slash


text:
Q: Hide Keyboard then push done in UITextView I'm trying to make so that the keyboard hides then i push done on a UITextView. I no have to do it on an UITextField. But because i need multiline text i need an UITextView. I have done it for UITextField this way this.txtDefault.ShouldReturn += (textField) => { textField.ResignFirstResponder(); return true; }; But it seemed that the UITextView doesn't have an ShouldReturn method. Have can i do it.
Best Regard Morten Starck

A: Can you use a UITextField for your purposes instead?
Apple's docs on UITextView say there isn't a selector for ShouldReturn at all, hence MonoTouch isn't going to be able to make it work either.
Here is another SO question on the subject, but these guys are using Obj-C.  They suggest using ShouldChangeTextInRange, but that would be ugly.  Using UITextField would be easier if you can make it work for your case.


text:
Q: can't find the solution?? it is showing cannot resolve R

It is showing cannot resovle R.
how i can solve this problem?????
if you need xml file to solve problem ,ask me in comment
Please help
 ..................................................................................................................................................................................................................................................................................................................
Here's the java code:
package com.example.android.justjava;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.TextView;

import java.text.NumberFormat;

/**
 * This app displays an order form to order coffee.
 */
public class MainActivity extends AppCompatActivity {
    int  quantity = 0;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }

    /**
     * This method is called when the order button is clicked.
     */
    public void submitOrder(View view) {
        int price= quantity*16;
       String priceMessage="total:" + (quantity*16) ;
              priceMessage=priceMessage +"\nThank You!";
             displayMessage(priceMessage);

    }

    /**
     * This method displays the given text on the screen.
     */
    private void displayMessage(String message) {
        TextView priceTextView = (TextView) findViewById(R.id.price_text_view);
        priceTextView.setText(message);
    }

    public void increase(View view) {
        quantity = quantity + 1;

displayPrice(quantity*16);
        display(quantity);
    }

    public void decrease(View view) {

            quantity = quantity - 1;
        displayPrice(quantity*16);
        display(quantity);
    }
    /**
     * This method displays the given quantity value on the screen.
     */
    private void display(int number) {
        TextView quantityTextView = (TextView) findViewById(R.id.quantity_text_view);
        quantityTextView.setText("" + number);
    }

    /**
     * This method displays the given price on the screen.
     */
    private void displayPrice(int number) {
        TextView priceTextView = (TextView) findViewById(R.id.price_text_view);
        priceTextView.setText(NumberFormat.getCurrencyInstance().format(number);
    }

here's the xml file:::
................................................................................................................................................................................................................................................
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:background="@drawable/w"
        android:orientation="vertical"
        >

        <TextView
            android:id="@+id/txt1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="center"
            android:layout_marginTop="20dp"

            android:text="Welcome to Ordering Menu"
            android:textColor="@android:color/white"
            android:textSize="25sp"
            app:fontFamily="@font/crafty_girls" />

        <LinearLayout
            android:layout_width="wrap_content"
            android:layout_marginTop="20dp"
            android:layout_height="wrap_content"
            android:orientation="horizontal">

            <ImageView
                android:layout_width="100dp"
                android:layout_height="100dp"
                android:layout_marginLeft="20dp"
                android:src="@drawable/cappo"/>
            <Button
                android:id="@+id/btn2"
                android:layout_width="48dp"
                android:layout_height="48dp"
                android:textSize="30sp"
                android:layout_marginLeft="50dp"
                android:layout_marginTop="20dp"
                android:onClick="increase"
                android:text="+"
                android:textColor="@android:color/black"
                android:background="@android:color/white" />

            <TextView

                android:id="@+id/quantity_text_view"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginLeft="10dp"
                android:layout_marginTop="20dp"
                android:text="0"
                android:textSize="20sp"

                android:textColor="@android:color/white" />

            <Button
                android:id="@+id/btn3"
                android:layout_width="50dp"
                android:textColor="@android:color/black"
                android:background="@android:color/white"
                android:layout_height="50dp"
                android:textBold="true"
                android:layout_marginLeft="10dp"
                 android:layout_marginTop="20dp"
                android:onClick="decrease"
                android:textSize="30sp"
                android:text="-" />

        </LinearLayout>

        <TextView

            android:id="@+id/kk"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginLeft="170dp"
            android:text="Price" />

        <TextView
            android:id="@+id/price_text_view"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginLeft="20dp"
            android:layout_marginTop="10dp"
            android:text="$0"
            android:textColor="#000000" />

        <Button
            android:id="@+id/btn1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginLeft="10dp"
            android:layout_marginTop="15dp"
            android:onClick="submitOrder"
            android:text="ORDER" />

    </LinearLayout>

</android.support.constraint.ConstraintLayout>

A: This may not be the case for you but worth a shot, sometimes Android studio is glitchy and needs to be closed/ reopened. Also you could try, Build > Clean Project.

A: Try from android studio menu File -> Invalidate Caches and Restart -> Invalidate and Restart

A:
i'm new in this type of developing ,so can i know where can i find this import list

So i can suggest you to check few things.

*

*Make sure you have installed your targeted build tools. Eg: API 28

*Check the package name in your AndroidManifest.xml file. You may have deleted the package name from the manifest file mistakenly.

*If none of the above in your case, try to import com.example.android.justjava.R


text:
Q: Is it possible to display vega/vega-lite bar based on period time column? I was wonder if it is possible to create a vega/vega-lite visualization , based on time periodic columns.
For example , assume that i would like to display a graph of athletics results in a bar/other visualization.
rio-2016-athletics
I have tried to make some changes to simple bar chart bellow.
I have edited only the "amount" column in order to display time-period results:
 "data": [
    {
      "name": "table",
      "values": [
        {"category": "1", "amount": 1:42.15},
        {"category": "2", "amount": 1:42.61},
        {"category": "3", "amount": 1:42.93},
        {"category": "4", "amount": 1:43.41}
      ]
    }
  ]

I got the following error message:
[Error] Unexpected token : in JSON at position 208 and line 12
Can one advise how to display time periodic column IN THE FORMAT THAT I AM LOOKING FOR (mm:ss.ms)
The original code was:
{
  "$schema": "https://vega.github.io/schema/vega/v5.json",
  "width": 400,
  "height": 200,
  "padding": 5,

  "data": [
    {
      "name": "table",
      "values": [
        {"category": "1", "amount": 42.15},
        {"category": "2", "amount": 42.61},
        {"category": "3", "amount": 42.93},
        {"category": "4", "amount": 43.41}
      ]
    }
  ],

  "signals": [
    {
      "name": "tooltip",
      "value": {},
      "on": [
        {"events": "rect:mouseover", "update": "datum"},
        {"events": "rect:mouseout",  "update": "{}"}
      ]
    }
  ],

  "scales": [
    {
      "name": "xscale",
      "type": "band",
      "domain": {"data": "table", "field": "category"},
      "range": "width",
      "padding": 0.05,
      "round": true
    },
    {
      "name": "yscale",
      "domain": {"data": "table", "field": "amount"},
      "nice": true,
      "range": "height"
    }
  ],

  "axes": [
    { "orient": "bottom", "scale": "xscale" },
    { "orient": "left", "scale": "yscale" }
  ],

  "marks": [
    {
      "type": "rect",
      "from": {"data":"table"},
      "encode": {
        "enter": {
          "x": {"scale": "xscale", "field": "category"},
          "width": {"scale": "xscale", "band": 1},
          "y": {"scale": "yscale", "field": "amount"},
          "y2": {"scale": "yscale", "value": 0}
        },
        "update": {
          "fill": {"value": "steelblue"}
        },
        "hover": {
          "fill": {"value": "red"}
        }
      }
    },
    {
      "type": "text",
      "encode": {
        "enter": {
          "align": {"value": "center"},
          "baseline": {"value": "bottom"},
          "fill": {"value": "#333"}
        },
        "update": {
          "x": {"scale": "xscale", "signal": "tooltip.category", "band": 0.5},
          "y": {"scale": "yscale", "signal": "tooltip.amount", "offset": -2},
          "text": {"signal": "tooltip.amount"},
          "fillOpacity": [
            {"test": "datum === tooltip", "value": 0},
            {"value": 1}
          ]
        }
      }
    }
  ]
}

A: Your first issue is that you have created invalid JSON: your timestamps need to be quoted. That is, replace 1:42.15 with "1:42.15".
As for parsing the dates, this is easiest to do in Vega-Lite. You can use the Data Format value to control how your date strings are interpreted. For example (online editor):
{
  "data": {
      "values": [
        {"category": "1", "amount": "1:42.15"},
        {"category": "2", "amount": "1:42.61"},
        {"category": "3", "amount": "1:42.93"},
        {"category": "4", "amount": "1:43.41"}
      ],
      "format": {"parse": {"amount": "date:'%M:%S.%L'"}}
  },
  "mark": "point",
  "encoding": {
    "x": {"field": "category", "type": "ordinal"},
    "y": {"field": "amount", "timeUnit": "minutessecondsmilliseconds", "type": "temporal"}
  }
}

If you're interested in how this translates to Vega, you can click the "Compiled Vega" tab in the above editor link.


text:
Q: Angular 10 Swagger Codegen: Generic type ModuleWithProviders requires 1 type argument(s) I am generating https://editor.swagger.io/ Codegen proxies.
It is giving the following error in Angular 10. How can this be fixed?

Generic type 'ModuleWithProviders' requires 1 type argument(s).

export class ApiModule {
    public static forRoot(configurationFactory: () => Configuration): ModuleWithProviders {
        return {
            ngModule: ApiModule,
            providers: [ { provide: Configuration, useFactory: configurationFactory } ]
        };
    }

    constructor( @Optional() @SkipSelf() parentModule: ApiModule,
                 @Optional() http: HttpClient) {
        if (parentModule) {
            throw new Error('ApiModule is already loaded. Import in your base AppModule only.');
        }
        if (!http) {
            throw new Error('You need to import the HttpClientModule in your AppModule! \n' +
            'See also https://github.com/angular/angular/issues/20575');
        }
    }
}

A: this error tells you that, the ModuleWithProviders class has 1 generic paramter. so you sould use it like ModuleWithProviders<T> where T is a type.
EDIT:
The class is defined like this:
interface ModuleWithProviders<T> {
  ngModule: Type<T>
  providers?: Provider[]
}

.
export class ApiModule {
  public static forRoot(configurationFactory: () => Configuration) : ModuleWithProviders<ApiModule> {
    return {
        ngModule: ApiModule,
        providers: [ { provide: Configuration, useFactory: configurationFactory } ]
    };
}

See Resource:
https://angular.io/guide/migration-module-with-providers

A: io.swagger.swagger-codegen fully supports Angular 10 since version 2.4.17. In detail you can se the fix which was provided in this pull request.
As djf mentioned use the parameter --additional-properties ngVersion=10 when calling generate to tell io.swagger.swagger-codegen to use Angular 10.

A: We stumbled over the same issue. Luckily you can provide custom *.mustache templates to the swagger-codegen-cli using the -t switch (see the swagger doc).
Our adapted api.module.mustache looks like this:
import { NgModule, ModuleWithProviders, SkipSelf, Optional } from '@angular/core';
import { Configuration } from './configuration';
{{#useHttpClient}}import { HttpClient } from '@angular/common/http';{{/useHttpClient}}
{{^useHttpClient}}import { Http } from '@angular/http';{{/useHttpClient}}

{{#apiInfo}}
{{#apis}}
import { {{classname}} } from './{{importPath}}';
{{/apis}}
{{/apiInfo}}

@NgModule({
  imports:      [],
  declarations: [],
  exports:      [],
  providers: [
    {{#apiInfo}}{{#apis}}{{classname}}{{#hasMore}},
    {{/hasMore}}{{/apis}}{{/apiInfo}} ]
})
export class ApiModule {
    public static forRoot(configurationFactory: () => Configuration): ModuleWithProviders<ApiModule> {
        return {
            ngModule: ApiModule,
            providers: [ { provide: Configuration, useFactory: configurationFactory } ]
        };
    }

    constructor( @Optional() @SkipSelf() parentModule: ApiModule,
                 @Optional() http: {{#useHttpClient}}HttpClient{{/useHttpClient}}{{^useHttpClient}}Http{{/useHttpClient}}) {
        if (parentModule) {
            throw new Error('ApiModule is already loaded. Import in your base AppModule only.');
        }
        if (!http) {
            throw new Error('You need to import the {{#useHttpClient}}HttpClientModule{{/useHttpClient}}{{^useHttpClient}}HttpModule{{/useHttpClient}} in your AppModule! \n' +
            'See also https://github.com/angular/angular/issues/20575');
        }
    }
}

The only change needed is to replace ModuleWithProviders by ModuleWithProviders<ApiModule>.
Afterwards the generated api.module.ts will work with Angular 10.


text:
Q: Twig - Mimic PHP for loop functionality in twig with iterations of +5 (or anything other than +1) How can I mimic this PHP functionality in twig? I need to increment a number by 5 for each iteration of a for loop. The PHP code below works as expected:
for($x=5; $x<=20; $x+=5)
{
    echo $x,'<br>';
}

which outputs:
5 ,10 ,15 ,20 ,

However this code in twig does not work as expected.
{% for y in range(0, 20) %}
{{ y + 5 }} ,
{% endfor %}

Which outputs:
5 , 6 , 7 , 8 , 9 , 10 , 11 , 12 , 13 , 14 , 15 , 16 , 17 , 18 , 19 , 20 , 21 , 22 , 23 , 24 , 25

I have also tried setting the new value of y for each iteration however that does not work either...
{% for y in range(0, 20) %}
{{ y + 5 }} ,
{% set y = y + 5 %}
{% endfor %}

A: Try this
{% for y in range(5, 20, 5) %}
{{ y }} ,
{% endfor %}


text:
Q: Producer is publishing into Kafka but cannot read from Spark structured streaming I am using Kafka to publish Tweets and it runs correctly as I am able to see the echo with the following command
bin/kafka-console-consumer.sh --bootstrap-server xxx.xxx.xx.xxx:9092 --topic trump --from-beginning

But when I try to consume with Structured streaming using the following code
if __name__ == "__main__":

    spark = SparkSession.builder.appName("TwitterSentimentAnalysis").getOrCreate()

    source_df = spark \
        .readStream \
        .format("kafka") \
        .option("kafka.bootstrap.servers", "xxx.xxx.xx.xxx:9092") \
        .option("subscribe", "tweets") \
        .option("startingOffsets", "latest") \
        .load()

    query = source_df \
        .writeStream \
        .outputMode("append") \
        .format("console") \
        .start()

Then I got an output but it does not show the Tweet under the value column. Instead I have a weird chain of alphanumeric as below. I checked without truncate the column value and I got the same but longer pattern.
+----+--------------------+------+---------+------+--------------------+-------------+
| key|               value| topic|partition|offset|           timestamp|timestampType|
+----+--------------------+------+---------+------+--------------------+-------------+
|null|[52 54 20 40 70 7...|tweets|        0| 45724|2021-03-17 12:57:...|            0|
|null|[23 52 57 52 49 2...|tweets|        0| 45725|2021-03-17 12:57:...|            0|
|null|[52 54 20 40 54 7...|tweets|        0| 45726|2021-03-17 12:57:...|            0|
|null|[52 54 20 40 44 6...|tweets|        0| 45727|2021-03-17 12:57:...|            0|
|null|[40 42 42 43 50 6...|tweets|        0| 45728|2021-03-17 12:57:...|            0|
|null|[40 4C 6F 72 64 5...|tweets|        0| 45729|2021-03-17 12:57:...|            0|
|null|[41 6E 6E 6F 75 6...|tweets|        0| 45730|2021-03-17 12:57:...|            0|
|null|[42 69 74 63 6F 6...|tweets|        0| 45731|2021-03-17 12:57:...|            0|
|null|[40 65 72 69 6B 7...|tweets|        0| 45732|2021-03-17 12:57:...|            0|
|null|[74 68 65 20 6D 6...|tweets|        0| 45733|2021-03-17 12:57:...|            0|
|null|[52 54 20 40 6D 6...|tweets|        0| 45734|2021-03-17 12:57:...|            0|
|null|[52 54 20 40 6D 6...|tweets|        0| 45735|2021-03-17 12:57:...|            0|
|null|[40 42 54 43 54 4...|tweets|        0| 45736|2021-03-17 12:57:...|            0|
|null|[52 54 20 40 49 6...|tweets|        0| 45737|2021-03-17 12:57:...|            0|
|null|[52 54 20 40 63 6...|tweets|        0| 45738|2021-03-17 12:57:...|            0|
|null|[42 75 20 6F 6C 6...|tweets|        0| 45739|2021-03-17 12:57:...|            0|
|null|[40 5F 43 72 79 7...|tweets|        0| 45740|2021-03-17 12:57:...|            0|
|null|[40 57 69 6E 66 6...|tweets|        0| 45741|2021-03-17 12:57:...|            0|
|null|[4D 79 20 72 65 6...|tweets|        0| 45742|2021-03-17 12:57:...|            0|
|null|[52 54 20 40 6F 6...|tweets|        0| 45743|2021-03-17 12:57:...|            0|
+----+--------------------+------+---------+------+--------------------+-------------+
only showing top 20 rows

Any help to learn the situation would be appreciated.

A: By default, the data (columns key and value) stored in Kafka is serialized as a String.
Looking at the Structured Streaming + Kafka Integration Guide you will see that the type of two columns key and value is binary:

Also, in the Guide it is mentioned how to deal with this. You need to cast the columns into String Type as shown below:
source_df.selectExpr("CAST(key AS STRING)", "CAST(value AS STRING)") \
        .writeStream \
        .outputMode("append") \
        .format("console") \
        .start()