Git pull back old feature branch, including any other feature branches but one that come in between

Question: I have git timeline like this:

master
feature-1 -> merged (to master)
feature-2 -> merged (to master)
feature-3 -> merged (to master)

All those features happen sequentially (First feature-1. Once it's completed finished, then feature-2, and so on).
Feature-2 is "conflicting" with Feature-1. Conflicting not in the sense of git conflict, rather featurewise.

Now the client decided they prefer feature-1, so we need to pull it back from the dead.
What is the safest and most efficient way to have a new branch that includes feature-1 + anything else in master (feature-3 in this case), excluding feature-2 ?
One alternative I come up with is:

git checkout feature-1
git checkout -b yeahbaby
git merge feature-3

But then you need to know all the branches (in this case it's easy, only feature-3). But in real case you have many of them.
EDITED: beside, it wouldn't work... becase feature-3 is based of master, which carries all the changes in made in feature-2 (which has been merged to master).
Comment: Not quite - I'm saying that starting from master, you'd simply do `git checkout -b yeahbaby`, `git revert -m 1 `, `git commit -m "Revert feature-2"`.  (See https://stackoverflow.com/questions/7099833/how-to-revert-a-merge-commit-thats-already-pushed-to-remote-branch)
Comment: are all features started from the same commit? maybe a visual graph will help us
Comment: No, it happens sequentially. First there is master, then feature-1 then merge, then feature-2 then merge, and so on.
Comment: I edited the original question to clarify it based on  your question.
Comment: Could you not revert the feature-2 merge?
Comment: @oliver:

I don't think so... But let me understand, so what  should do here is:

1. git checkout feature-2
2. git checkout -b yeahbaby
3. git reset --hard
4. git merge feature-3

?

But than it would the same as the other alternative; need to know all the branches from feature-3 onward.
Answer: There is no "safest way" to create a new git history that misses one feature from the original history.
The two most likely possibilities are:

Create a branch at master, and git revert <commit_id> with any commit you want to revert (ideally in reverse order). This will undo the changes made in the past as good as possible. It is relatively easy, but will become more complex the further in the past the reverted commits were
Create a branch at master, do a git rebase interactive <merge1_commit> and remove all commits that you want removed. This replays the history, and you could run tests after each rebase commit to ensure each step is valid. However this will flatten the history and you may have to repeatedly fix merge commits.

Outside git you can consider the possibility of adding a feature-toggle for the given feature, so that all customers get the same codebase, but for some customers a feature will be disabled via configuration. This would make moving forward with 2 branches somewhat easier in some cases.


Appium desktop issue on Ubuntu

Question: I've been trying to solve this issue for two weeks and cannot seem to find a solution, it only happens on Appium desktop with automationName set to UiAutomator.
I changed ownership of the /tmp folder from Root to user and set permissions to 777 but still facing the issue: I cannot change the file's permission since it's a temp folder and its name keeps changing every time I run a new appium session.
This is the error message:

An unknown server-side error occurred while processing the command. Original error: The application at '/tmp/.mount_app.Ap8xEj5P/resources/app/node_modules/appium/node_modules/appium-uiautomator2-server/apks/appium-uiautomator2-server-debug-androidTest.apk' is not writeable. Please grant write permissions to this file or to its parent folder '/tmp/.mount_app.Ap8xEj5P/resources/app/node_modules/appium/node_modules/appium-uiautomator2-server/apks' for the Appium process, so it could sign the application
Comment: Hello @EzCrash welcome to stack overflow seems that someone send you the request of approval of edit please approve if you found it needed
Comment: which appium desktop version are you using?
Comment: @SubanDhyako I'm using 1.12.0 for Linux
Answer: You could try to grant permission on /users/username/node_modules, /usr/local or /usr/bin. I ran in the same problem while trying to use UIAutomator2 on macOS and granting permissions gradually. Also, if you have the latest version of Appium, you need to switch to UIAutomator2, starting v12.1 UIAutomator is no longer supported.
Another hint: don't mix UIAutomator with UIAutomator2, check that you are trying to launch with correct capabilities
Comment: I'm using UiAutomator2, I just did what you said but still facing this issue, what else did you do to solve it ?
Answer: This bug plagued me for weeks before resolving it. The issue ended up being my Java version. I did NOT have to modify signing or read / write privileges on the file in question.
JAVA_HOME and Path environment variables were both pointing to Java 12. I needed to install jdk_1.8.0 for Java 8, and update JAVA_HOME and Path to point to Java 8. More info and possible solutions can be found on my GitHub issue that I opened with Appium devs:
https://github.com/appium/appium-desktop/issues/1080

Appium desktop issue on Ubuntu


Cassandra mutual exclusion locking (synchronization)

Question: Is there anyway to synchronise client using cassandra built in functions?
I need to perform some operations and those operations need to be synchronized with all other clients (mutual exclusion).
In RDBMS I can lock entire table or prepare special table for synchronization purposes and use SELECT ... FOR UPDATE on it.
Can I achive this with Cassandra without any third party apps? If not what's the best way to do that? Preferable languages are Java and Python.
Answer: Its not possible to lock an entire (or a subset of a) column familiy without third party libraries like Apache ZooKeeper.
I would probably start looking at Domic Williams cages before start rolling my own distributed locking mechanism
Comment: It's also pretty likely that you could avoid the need for this at all by adjusting your data model.  Perhaps that would make another good SO question?
Comment: No, I need distributed processing architecture and Cassandra as data storage. I need sync some operations to prevent same data being processed by more than one machine.
Comment: I don't need to lock column family. SELECT FOR UPDATE equivalent would be the best. I'll check ZooKeeper
Answer: If you are updating one row in a column family, it is atomic. But it won't work like select for update. You should probably revisit your data model with more denormalization in mind, so that you won't need to worry about synchronization.
Answer: Because C* provides row level atomicity why not use Lamport's Bakery Algorithm. I found an incomplete page on C* wiki too.
https://github.com/jakedouglas/cassandra_lock
Comment: I guess the wiki page you are referring to is this:  http://wiki.apache.org/cassandra/Locking
Answer: I was also looking way to make syncronization with cassandra, but as far as I know it does not provide mechanisms to implement mutexes.
However, memcached has atomic cas (check and set) operation, which can be used to implement mutex. It has also python and java clients.
So you could use memcached to implement mutexes for syncronization and does read/write data with quorum consistency level in cassandra to make sure that latest write is always returned on when reading.
Has anyone experience about implementing mutex with memcached?
Comment: This might be a bit unstable if some mutex is flushed or memcached server crash which will release lock too early. However I'm not sure how probable is that when locking is done just for few seconds at maximum. Stability depends a lot of application, how mutexes are used.


IP Address not obtained in java

Question: This code used to return my local ip address as 192.xxx.x.xxx but now it is returning 127.0.0.1 . Please help me why the same code is returning different value. Is there something that I need to watch at linux OS.
import java.util.*;
import java.lang.*;
import java.net.*;

public class GetOwnIP
{
  public static void main(String args[]) {
    try{
      InetAddress ownIP=InetAddress.getLocalHost();
      System.out.println("IP of my system is := "+ownIP.getHostAddress());
    }catch (Exception e){
      System.out.println("Exception caught ="+e.getMessage());
    }
  }
}

Answer: 127.0.0.1 is the loopback adapter - it's a perfectly correct response to the (somewhat malfomed) question "what is my IP address?"
The problem is that there are multiple correct answers to that question.
EDIT: The docs for getLocalHost say:

If there is a security manager, its
  checkConnect method is called with the
  local host name and -1 as its
  arguments to see if the operation is
  allowed. If the operation is not
  allowed, an InetAddress representing
  the loopback address is returned.

Is it possible that the change in behaviour is due to a change in permissions?
EDIT: I believe that NetworkInterface.getNetworkInterfaces is what you need to enumerate all the possibilities. Here's an example which doesn't show virtual addresses, but works for "main" interfaces:
import java.net.*;
import java.util.*;

public class Test
{
    public static void main(String[] args)
        throws Exception // Just for simplicity
    {
        for (Enumeration<NetworkInterface> ifaces =
               NetworkInterface.getNetworkInterfaces();
             ifaces.hasMoreElements(); )
        {
            NetworkInterface iface = ifaces.nextElement();
            System.out.println(iface.getName() + ":");
            for (Enumeration<InetAddress> addresses =
                   iface.getInetAddresses();
                 addresses.hasMoreElements(); )
            {
                InetAddress address = addresses.nextElement();
                System.out.println("  " + address);
            }
        }
    }
}

(I'd forgotten just how awful the Enumeration<T> type is to work with directly!)
Here are the results on my laptop right now:
lo:
  /127.0.0.1
eth0:
  /169.254.148.66
eth1:
eth2:
ppp0:
  /10.54.251.111

(I don't think that's giving away any hugely sensitive information :)
If you know which network interface you want to use, call NetworkInterface.getByName(...) and then look at the addresses for that interface (as shown in the code above).
Comment: Why is there a slash before the IP address?
Comment: In the loop above, you could also simply skip over the loopback by checking NetworkInterface#isLoopback().
Comment: @Matías It is the Java toString of an InetAddress object use address.getHostAddress() to get just the dot-separated numbers.
Answer: When you use InetAddress.getLocalHost() you are not guaranteed to get a particular interface, ie. you could receive the loopback (127) interface or a connected one.
In order to ensure you always get an external interface, you should use the java.net.NetworkInterface class. The static getByName(String) class will give you the interface with the defined name (such as "eth0"). Then you can use the getInetAddresses() function to obtain the IP addresses (could be just one) bound to that interface.
NetworkInterface ni = NetworkInterface.getByName("eth1");
ni.getInetAddresses();

Answer: Check your /etc/host file. If you put 127.0.0.1 first, it will return this as result.
The correct way to get the ip address is to use NetworkInterface.getNetworkInterfaces() and run getInetAddresses() on each of them.
Answer: You can use the NetworkInterface.getNetworkInterfaces() method to retrieve an Enumeration of all of the network interfaces for your system.
For each of the NetworkInterface instances, you can then use the getInetAddresses() method to retrieve an Enumeration of all of the InetAddress instances associated with the network interface.
Finally, you can use the getHostAddress() method on each InetAddress instance to retrieve the IP address in textual form.
Answer: This is because you have a line in /etc/hosts like
127.0.0.1 localhost
you need to have
192.xxx.xxx.xxx localhost
Though please note that this would be very bad as to solve a code issue you should not modify linux config files. Not only is it not right (and risks breaking some other network aware apps on your linux box) it will also not work anywhere else (unless the admins of those boxes are also like minded).
javadoc for InetAddress.getLocalHost(); read "....an InetAddress representing the loopback address is returned." so it appears that the implementation of getLocalHost() is incorrect
on your UNIX and WIN boxes. The loopback address is nearly allways 127.0.0.1
Found this comment
"A host may have several IP addresses and other hosts may have to use different addresses to reach it. E.g. hosts on the intranet may have to use 192.168.0.100, but external machines may have to use 184.108.40.206. If you have a socket connection to another host you can call
Socket.getLocalAddress() to find out which local address is used for the socket."

IP Address not obtained in java


Global high availability setup question

Question: I own and operate visualwebsiteoptimizer.com/. The app provides a code snippet which my customers insert in their websites to track certain metrics. Since the code snippet is external JavaScript (at the top of site code), before showing a customer website, a visitor's browser contacts our app server. In case our app server goes down, the browser will keep trying to establish the connection before it times out (typically 60 seconds). As you can imagine, we cannot afford to have our app server down in any scenario because it will negatively affect experience of not just our website visitors but our customers' website visitors too!
We are currently using DNS failover mechanism with one backup server located in a different data center (actually different continent). That is, we monitor our app server from 3 separate locations and as soon as it is detected to be down, we change A record to point to the back up server IP. This works fine for most browsers (as our TTL is 2 minutes) but IE caches the DNS for 30 minutes which might be a deal killer. See this recent post of ours visualwebsiteoptimizer.com/split-testing-blog/maximum-theoretical-downtime-for-a-website-30-minutes/
So, what kind of setup can we use to ensure an almost instant failover in case app data center suffers major outage? I read here www.tenereillo.com/GSLBPageOfShame.htm that having multiple A records is a solution but we can't afford session synchronization (yet). Another strategy that we are exploring is having two A records, one pointing to app server and second to a reverse proxy (located in a different data center) which resolves to main app server if it is up and to backup server if it is up. Do you think this strategy is reasonable?
Just to be sure of our priorities, we can afford to keep our own website or app down but we can't let customers' website slow down because of our downtime. So, in case our app servers are down we don't intend to respond with the default application response. Even a blank response will suffice, we just need that browser completes that HTTP connection (and nothing else).
Reference: I read this thread which was useful serverfault.com/questions/69870/multiple-data-centers-and-http-traffic-dns-round-robin-is-the-only-way-to-assure
Answer: Your situation is fairly similar to ours.  We want split datacentres, and network-layer type failover.
If you've got the budget to do it, then what you want, is two datacentres, multiple IP transits to each, a pair of edge routers doing BGP sessions to your transit providers, advertising your IP addresses to the global internet.
This is the only way to do true failover.  When the routers notice that the route to your servers is no-longer valid (which you can do in a number of ways), then they stop advertising that route, and traffic goes to the other site.
The problem is, that for a pair of edge routers, you're looking at a fairly high cost initially to get this set up.
Then you need to set up the networking behind all this, and you might want to consider some kind of Layer2 connectivity between your sites as a point-to-point link so that you'd have the ability to route traffic incoming to one datacentre, directly to the other in the event of partial failure of your primary site.
BGP Multihomed/Multi-location best practice and Best way to improve resilience? are questions that I asked about similar issues.
The GSLB page of shame does raise some important points, which is why, personally I'd never willingly choose a GSLB to do the job of BGP routing.
You should also look at the other points of failure in your network.  Make sure all servers have 2 NICs (connected to 2 separate switches), 2 PSUs, and that your service is comprised of multiple backend servers, as redundant pairs, or load-balanced clusters.
Basically, DNS "load balancing" via multiple A records is just "load-sharing" as the DNS server has no concept of how much load is on each server. This is cheap (free).
A GSLB service has some concept of how loaded the servers are, and their availability, and provides some greater resistance to failure, but is still plagued by the problems related to dns caching, and pegging.
This is less cheap, but slightly better.
A BGP routed network, backed by a solid infrastructure, is IMHO, the only way to truly guarantee good uptime.   You could save some money by using route servers instead of Cisco/Juniper/etc routers, but at the end of the day, you need to manage these servers very carefully indeed.
This is by no means a cheap option, or something to be undertaken lightly, but it is  a very rewarding solution, and brings you into the internet as a provider, rather than just a consumer.
Comment: I'm going to write this up as an essay on my blog tonight, I think.
The cheapest solution for the edge routers for you, would be a pair of  Dell R200s each with a couple extra NICs, and a stack of RAM (4-6GB should be sufficient), then run something like FreeBSD and Quagga, or BIRD.
Comment: Thanks, I wanted to upvote your answer but couldn't because I am new. Well, yes BGP routed network seems to be the way to go but it can be fairly hard to setup and manage for a startup (both cost and man-power resources wise). I wish there were a cheaper solution for this but probably there isn't.
Comment: Fantastic! I will be sure to check it up. Please update this thread with the link so that I don't miss it out.
Comment: +1 on the El-Cheapo router solution - We're actually running FreeBSD routers at my company with great results.  If you want something a bit more commercial (but still way cheaper than comparable Cisco gear) Juniper Networks gear (www.juniper.net) might also be a good choice.
Answer: OK, this was asked a while ago, but I'm first seeing it now.

the code snippet is external JavaScript (at the top of site code), before showing a customer website, a visitor's browser contacts our app server.

You should:

Place your Javascript file on a good, professional Content Delivery Network, i.e. purchase highly available HTTP(S) serving of the Javascript from someone who already has that expertise.
Program your Javascript so that there is a good fallback state, i.e. if your app server doesn't respond quickly then the end user sees a normal, unmodified page.

Doing anything else is irresponsible, really. I assume you already have this in place.
You should not base your service on BGP routing tricks unless you have or obtain the know-how to do so. Complex BGP routing scenarios are decidedly non-trivial to implement; don't do this yourself if you don't have the domain specific knowledge.
Your question itself is a little confused. Analysis of how to create a highly available service begins with the application data, because that's your "state". The stateless parts are easy to make highly available, the state-full parts are not. So instead of focusing on your servers and DNS, look at where your application maintains state. Start by optimizing there, and possibly asking for algorithm advice on Stack Overflow. Could you implement a notion of transactions and smart server retry in your Javascript file fx?
Answer: Actually, what you want could be upgraded to help your split testing activities as well if you combine geodns and dns failover.
Sending group A to ip 1 and group B to ip 2, even if they were on the same server would let you separate your testing groups. Group A and Group B are from different geographical regions. To be fair, the next day/week/month, you flip the groups to make sure that you allow for geographic differences. Just to be rigourous in your methodology.
The geodns/failover dns service at http://edgedirector.com can do this
disclosure: i am associated with the above link, stumbled in here researching an article on applying stupid dns tricks to split testing.

Global high availability setup question


How can I estimate a "confidence" in a score / rating

Question: I'm sure there's a more technical term for what I'm looking for, but I don't know what it is (it's not confidence intervals, I think)
I'm trying to make a system where people get ratings (from 1 to 5 stars) over time, and I want to combine all those ratings into one individual score for each person. Now, this score alone is not a very good thing, I'd like to have a second value that shows how "reliable" / "accurate" this score is.
Let's say that:

If someone gets 1 rating of "3", his score is "3", but we're not very sure of that.
If someone gets 10 ratings of "3", we're very confident he's a "3". Let's say that more than 10 ratings that are identical are not a stronger signal than 10 ratings, there's a point where we're "confident enough". Let's call this 100% confident.
If someone gets 2 x"1", and 2 x "5", the average is also a 3, but the person is all over the place, and I want to reflect this by giving this score a very low confidence value.

So, I'm pretty much looking for something that reflects variance, but also reflects how many "consistent" ratings someone has got. Or how "stable" he is at his score.
Can anyone think of either an algorithm for doing something like this, or point me in the direction of tools that you'd use for such a thing?
Thank you!
Daniel
Answer: Evan Miller's how not to sort by average rating has pretty good advice for the general problem you are trying to solve.
Comment: I was going to answer the same thing. I would fit a distribution and use the lower bound of the confidence interval for the ranking. Unfortunately, for example a t-distribution parametrized on the sample mean and variance. However, I think you need a minimum number of votes for each item.
Comment: You can have a look here http://stats.stackexchange.com/questions/37993/is-there-a-minimum-sample-size-required-for-the-t-test-to-be-valid about the minimum sample size. I would really be interested to see if there is any other distribution that we can fit with only two samples or at the limit just one.
Answer: What you are looking for is in fact exactly a measure of the variance of the ratings for each person - as you get very close to in your own wording of the question.  You might want to call this the intra-subject variance.  You could use either the original variance, or its square root, which turns it into the standard deviation and has the advantage of being directly comparable to the original scale of 1-5.
Because you can conceptualise your ratings as samples from a hypothetical infinite population of ratings for each subject, and it sounds like different subjects have different numbers of ratings, it's probably quite important to use the sample variance rather than the population variance.  This gives you an unbiased estimate of the population variance, taking into account that before estimating the variance you have first had to estimate the mean.
Comment: The person with only one 3 will have an undefined sample variance ie once a degree of freedom is spent on estimating the mean.  But your point remains a good one if comparing a person with 2 "3"s and another with 100 "3"s.  I think a good fix for that might be moving to a Bayesian paradigm.
Comment: Yes, except for the fact that a person with 1 "3", and a person with 100 "3"'s will both have a variance of 0, and the second one should score much higher.


Issue Tracker for Open Atrium 2.0

Question: I just installed Open Atrium 2.0 and noticed, as many people have, that the Issue Tracker functionality is not included. I understand why they didn't want to include it in version 2: to make way for a better solution that fits in with Drupal Core.
However, this functionality is pretty killer for what I use Open Atrium for.
So, other than https://drupal.org/project/oa_worktracker, are there other alternatives to implementing issue tracking within Open Atrium. I guess I'm unaware of a standard issue tracker for D7.
Comment: I am curious too, seems like it's needed IMO, I will post back if I find anything or testing the answer below.
Answer: I dont know whats OA2 friendly but Case Tracker, and Project Management are both D7 friendly.
From the project page of Case Tracker:

Actually, the 7.x-1.x-dev version has the content types for Project
  and Cases working without problems. The Notifications, Actions and
  View integration that needs to be tested.
The development is active and we're working toward a release. Check
  out the 7.x-1.x branch and post your patches!

From the project page for Project Management:

Project management software, allowing you to manage:
Organizations, Teams, People, Projects, Tasks, Tickets, Timetrackings,
  Notes, Invoices, and Expenses. Each of these features is managed as a
  separate module within the suite.
Comment: I think I've seen those, but I'll have to check them out again. We actually started using JIRA, and the need went away.
Answer: This answer is long after the OP presumably moved on, but for posterity...
I'm using an issue tracker on an OA2 system. I didn't set it up, but I'd be very surprised if what we used wasn't standard stuff.
OA2 in this case uses the 'Task' content type for issue tracking, which is implemented by oa_worktracker, which I can see in the filesystem at .../htdocs/profiles/openatrium/modules/apps/oa_worktracker.
http://docs.openatrium.com/node/294 also shows the Tracker as part of OpenAtrium.

Issue Tracker for Open Atrium 2.0


Getting Error when publishing in azure synapse or azure data factory

Question: I am trying to publish the synapse pipelines from master branch.
And I am getting an error and it does not point it to any details or any specific pipeline or Data flow.
Error is below:-

Error code: OK
Inner error code: BadRequest
Message: Missing parameter definition for Env
Comment: Because everything is running fine when I run the pipelines , I d not know why error when publishing. Just to add , Is it possible if I delete the .json files(Deployment and Parameter) from Worskpace_publish branch and then try publishng it again?
Answer:
BadRequest Message: Missing parameter definition for Env

is a parameter-passing error that occurs often. Default value can't be expressions. It has to be static value.
You can check if you follow the steps passing parameters:

Create parameters in the dataset:

create parameters

Change the dynamic content to reference the new dataset parameters in the dataset

change the dynamic content

Enter dynamic content referencing the original pipeline parameter in the calling pipeline

Enter dynamic content
Comment: Hi,
This is first time I am publishing from master to publish as this is a new project.
I am doing the same thing. Initially I was not setting Default Value. I have also raised this with Microsoft support team, They suggested me to put default value in all the pipelines and DFs as a static value. I already put it. But still getting this error.
Comment: Because everything is running fine when I run the pipelines , I d not know why error when publishing. Just to add , Is it possible if I delete the .json files(Deployment and Parameter) from Worskpace_publish branch and then try publishng it again?


Do not want store credit card details

Question: I am using Drupal 8 Commerce 2 Onsite payment gateway with USAepay payment gateway. I do not want to store credit card details in the database, even it should not save last 4 digit last of card number. Is there any way?
Comment: Why would you not save the last 4 digits? It has no effect on PCI compliance, all gateways allow it.
Answer: There is a reason that they have made it like that.
Take a look at this page, it describes why.

Onsite Payment Gateways always store credit card info
Payment gateways have different capabilities. Some support storing a user's card in the gateway. Others have an "offsite" flow, sending you to their site to collect card info and then returning you back to the commerce site when done.
An "Onsite" payment gateway is one that keeps the visitor on the site, collects the card numbers and posts it from the site to the gateway. In Drupal Commerce 2, the payment flow for onsite gateways is completely different than in Commerce 1, Ubercart, or many other shopping carts: it now stores the credit card in the gateway first, and creates a "Payment Method" associated with the user that contains the token from the gateway. It can then use that token for any future charges (as long as the gateway continues to honor it).

Do not want store credit card details


Trying to mock static system class with PowerMock gives VerifyError

Question: I am trying to mock JOptionPane static methods, and am stuck at a Java.lang.VerifyError.  All versions are current, since I just downloaded PowerMock for Mockito, and all their dependencies.
I cannot use the answer given for a previous question, to wrap the class and subclass the wrapper - this is all over our application.  I've invested a fair amount of time in PowerMock at this point, and I don't want to start over with fest.
Is there a way to resolve this error?  I've tried both "Mocking Static Methods" and "Mocking System Classes" in the instructions.  I can't go any farther since all I've done is @RunWith(PowerMockRunner.class) and @PrepareForTest(My.class).
I found that I could reduce this to an issue with any reference to a class that extends JPanel.  Here is a minimum test to create the issue (I've gotten the same exception with PrepareForTest on Boffo and on JPanel):
import javax.swing.JPanel;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;

@RunWith(PowerMockRunner.class)
//@PrepareForTest(JPanel.class)
@PrepareForTest(TestCase.Boffo.class)
public class TestCase {

    @SuppressWarnings("serial")
    public static class Boffo extends JPanel {}

    @Test
    public void test() throws Exception {
        new Boffo();
    }
}

Here is the exception I get when I try to run the test:
java.lang.VerifyError: (class: javax/swing/plaf/metal/MetalLookAndFeel, method: getLayoutStyle signature: ()Ljavax/swing/LayoutStyle;) Wrong return type in function
    at javax.swing.UIManager.setLookAndFeel(Unknown Source)
    at javax.swing.UIManager.initializeDefaultLAF(Unknown Source)
    at javax.swing.UIManager.initialize(Unknown Source)
    at javax.swing.UIManager.maybeInitialize(Unknown Source)
    at javax.swing.UIManager.getUI(Unknown Source)
    at javax.swing.JPanel.updateUI(Unknown Source)
    at javax.swing.JPanel.<init>(Unknown Source)
    at javax.swing.JPanel.<init>(Unknown Source)
    at javax.swing.JPanel.<init>(Unknown Source)
    at com.package.TestCase$Boffo.<init>(TestCase.java:17)
    at com.package.TestCase.test(TestCase.java:21)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
    at java.lang.reflect.Method.invoke(Unknown Source)
    at org.junit.internal.runners.TestMethod.invoke(TestMethod.java:66)
    at org.powermock.modules.junit4.internal.impl.PowerMockJUnit44RunnerDelegateImpl$PowerMockJUnit44MethodRunner.runTestMethod(PowerMockJUnit44RunnerDelegateImpl.java:312)
    at org.junit.internal.runners.MethodRoadie$2.run(MethodRoadie.java:86)
    at org.junit.internal.runners.MethodRoadie.runBeforesThenTestThenAfters(MethodRoadie.java:94)
    at org.powermock.modules.junit4.internal.impl.PowerMockJUnit44RunnerDelegateImpl$PowerMockJUnit44MethodRunner.executeTest(PowerMockJUnit44RunnerDelegateImpl.java:296)
    at org.powermock.modules.junit4.internal.impl.PowerMockJUnit44RunnerDelegateImpl$PowerMockJUnit44MethodRunner.runBeforesThenTestThenAfters(PowerMockJUnit44RunnerDelegateImpl.java:284)
    at org.junit.internal.runners.MethodRoadie.runTest(MethodRoadie.java:84)
    at org.junit.internal.runners.MethodRoadie.run(MethodRoadie.java:49)
    at org.powermock.modules.junit4.internal.impl.PowerMockJUnit44RunnerDelegateImpl.invokeTestMethod(PowerMockJUnit44RunnerDelegateImpl.java:209)
    at org.powermock.modules.junit4.internal.impl.PowerMockJUnit44RunnerDelegateImpl.runMethods(PowerMockJUnit44RunnerDelegateImpl.java:148)
    at org.powermock.modules.junit4.internal.impl.PowerMockJUnit44RunnerDelegateImpl$1.run(PowerMockJUnit44RunnerDelegateImpl.java:122)
    at org.junit.internal.runners.ClassRoadie.runUnprotected(ClassRoadie.java:34)
    at org.junit.internal.runners.ClassRoadie.runProtected(ClassRoadie.java:44)
    at org.powermock.modules.junit4.internal.impl.PowerMockJUnit44RunnerDelegateImpl.run(PowerMockJUnit44RunnerDelegateImpl.java:120)
    at org.powermock.modules.junit4.common.internal.impl.JUnit4TestSuiteChunkerImpl.run(JUnit4TestSuiteChunkerImpl.java:102)
    at org.powermock.modules.junit4.common.internal.impl.AbstractCommonPowerMockRunner.run(AbstractCommonPowerMockRunner.java:53)
    at org.powermock.modules.junit4.PowerMockRunner.run(PowerMockRunner.java:42)
    at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:46)
    at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:467)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:683)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:390)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:197)

Comment: see https://groups.google.com/forum/?fromgroups#!topic/powermock/GgUjp6_x3GQ%5B1-25%5D
Comment: I read that entire thread - what I saw was that before an answer was given, someone changed the subject to another issue.  If there is an answer in here, please point me to it.  This is one of the many places I saw the question but not an answer.
Answer: Here's a neat workaround/solution that a colleague of mine discovered today:
Just add the annotation @PowerMockIgnore("javax.swing.*") to the test class and PowerMock will defer the loading of the problematic classes to the system classloader.
edit: Just re-read the question and since you're trying to mock JOptionPane itself I'm not sure this will help, but maybe you can play around with the exclusions pattern.
Comment: import org.powermock.core.classloader.annotations.PowerMockIgnore; is the import for this.
Answer: I have no idea actually why it throws VerifyError, but you can overcome it by setting a fake LookAndFill in advance before instantiating the class.
public static class FakeLookAndFill extends BasicLookAndFeel {
    @Override
    public String getName() {
        return "FakeLookAndFill";
    }

    @Override
    public String getID() {
        return "FakeLookAndFill";
    }

    @Override
    public String getDescription() {
        return "FakeLookAndFill";
    }

    @Override
    public boolean isNativeLookAndFeel() {
        return false;
    }

    @Override
    public boolean isSupportedLookAndFeel() {
        //note it returns true
        return true;
    }
}

@Before
public void setUp() throws Exception {
    UIManager.setLookAndFeel(new FakeLookAndFill());
}


What's wrong with this problem?

Question: A regular hexagon $ABCDEF$ is given and also two points $K$ and $L$ on its sides $AB,BC$ respectively, such that $\angle KEL=15^{\circ}$. Show that EL bisects the angle $\angle KLC$.
Having made the shape using geogebra, it turns out there's something wrong. Could someone please find what's wrong and suggest what the correct problem is?
Also, if you do find the correct one, do not write a solution
Comment: Just tried it on sketchpad and I agree. EL nowhere near bisects angle KLC, no matter where K is placed on side AB (in such a way that L ends up on side BC keeping angle KCL at 15). It would be interesting if anything constant held here, as the resulting angles vary depending on where K is on AB.
Answer: AHA. By messing around on sketchpad, I found if one changes the required angle $KEL$ to be 30 degrees instead of 15, the result holds, at least using the sketchpad drawing. And the value of the two angles in which $EL$ bisects angle $KLC$ vary as the point $K$ is moved on side $AB$, keeping $L$ on side $BC$ so as to have the required angle 30 degrees.
This seems like an interesting result, and I'll likely try for a proof myself. Of course I won't put it here as per your request, which I agree with -- don't spoil the fun...
Comment: @Blue -- Too bad OP doesn't want to see that proof, as I'd like to see it. OTOH I'd still like to go for a proof myself...
Comment: If I do find the proof, I will let you know so you can share your solutions with us. :)
Comment: Okay, job done. It's quite easy actually.
Comment: @Blue how did you prove it, if I may ask?
Answer: Since @Matheo has lifted the moratorium on solutions, here's mine.

Reflect $A$ and $C$ across $\overline{EK}$ and $\overline{EL}$, respectively, to get $A^\prime$ and $C^\prime$, both of which are on the circle with center $E$ through $A$ and $C$.

Since $|\angle AEC| = 60^\circ$ and $|\angle KEL| = 30^\circ$, we have that
$$|\angle A^\prime EK| + |\angle C^\prime EL| = |\angle AEK| + |\angle CEL| = 60^\circ - 30^\circ = |\angle KEL|$$
so that $A^\prime$ and $C^\prime$ must coincide.
By reflection, $\overline{EK}$ and $\overline{EL}$ are respective bisectors of $\angle AKA^\prime$ and $\angle BLB^\prime$.

To see that this in fact solves the problem, observe that $\overline{KL}$ contains $A^\prime=C^\prime$: angles $\angle EAB$ and $\angle ECB$ are right, whereupon their reflections, $\angle EA^\prime K$ and $\angle EC^\prime L$, are also right, so that points $K$, $L$, and $A^\prime = C^\prime$ are collinear. $\square$

Note that there's nothing special about the hexagon here. The same phenomenon appears whenever $A$, $B$, $C$ are three consecutive vertices of any regular $2n$-gon, with $E$ the vertex opposite $B$, provided $|\angle KEL| = 90^\circ/n$.

What's wrong with this problem?


javax.el.PropertyNotFoundException: Property 'selectedUser' not found on type bg.fmi.master.thesis.beans.ProfileBean

Question: Do you have any idea why my app throws me this exception:
WARNING: /myProfile.xhtml @71,27 target="#{profileBean.selectedUser}": Property 'selectedUser' not found on type bg.fmi.master.thesis.beans.ProfileBean
javax.el.PropertyNotFoundException: /myProfile.xhtml @71,27 target="#{profileBean.selectedUser}": Property 'selectedUser' not found on type bg.fmi.master.thesis.beans.ProfileBean
---
Caused by: javax.el.PropertyNotFoundException: Property 'selectedUser' not found on type bg.fmi.master.thesis.beans.ProfileBean

When i have this property in my bean:
@ManagedBean(name = "profileBean")
public class ProfileBean implements Serializable {
    private TUser selectedUser = new TUser();

    public TUser getSelectedUser() {
        return selectedUser;
    }

    public void setSelectedUser(TUser selectedUser) {
        this.selectedUser = selectedUser;
    }

The .xhtml code is this:

        ....

           <f:setPropertyActionListener target="#{profileBean.selectedUser}" value="#{user}" />

Thanks in advance!
Comment: Code looks okay. You're most likely not running the code you think you're running. That said, your environment seems to support EL 2.2. Why not just `action="#{profileBean.editUser(user)}"` instead of this listener mess?
Comment: It throws again exception: Caused by: javax.el.MethodNotFoundException: /myProfile.xhtml @73,53 action="#{profileBean.editUser(user)}": Method not found: firstname.lastname@example.com(bg.fmi.master.thesis.model.TUser). I edited my method too.In one of your post on similar question, was written that f:attribute may be used and I manage to make it working with this code  but it is still unclear for me why it does not work in the other ways describe above.
Comment: You're most likely not running the code you think you're running.
Comment: How can i understand what exactly i am running?
Comment: Do you have other errors in the log except for this?
Comment: No, it is just this.
Answer: I have made a simple project based on your sample code.
<h:form>

       <f:setPropertyActionListener target="#{profileBean.selectedUser}" value="#{user}" />

</h:form>

There was no such error as described. Your problem comes from other place. Remove unnecessary bits and try to isolate the problem. You could change the name of the property and see if the error reflects the new name. Make sure you don't have another bean with the same name.


Can't install the debian9 package inside the Docker image

Question: I've run Debian 9 in as the Docker image. Next I've tried to install the vim package, but it's got error
apt update && apt install -y vim && apt install -y ps
...
Err:4 http://security.debian.org/debian-security stretch/updates Release
  404  Not Found [IP: 22.214.171.124 80]
Err:5 http://deb.debian.org/debian stretch Release
  404  Not Found
Err:6 http://deb.debian.org/debian stretch-updates Release
  404  Not Found
Reading package lists... Done

After that I googled an info and changed the /etc/atp/sources.list file to
deb http://security.debian.org/debian-security stable-security/updates main
deb http://ftp.debian.org/debian stable main contrib non-free

and apt can execute the command update without issues. But I still couldn't install any package.
I found the address for archive distrs (https://archive.debian.org/debian-archive/debian/dists/stretch/). Obviously I ought to use the deb https://archive.debian.org/debian-archive repos, but can't fetch how to specify them properly.
The image debian:12 works fine. Should I copy the repos from it?
Comment: Of course you can, by using the archive repos. But it's highly discouraged because it's insecure. It's also off topic for this site.
Comment: No, you should not mix different OS versions, this only creates further problems. Debian 9 is EOL. There are archive mirrors you can use, but you should upgrade your applications to work with more modern versions.
Comment: @GeraldSchneider, so I can't run Debian 9 in my work totally? Without repos it's useless.
Answer: You may need to change the repo URL for the archive one, using something like :
deb http://archive.debian.org/debian/ stretch main contrib


How to parse url in spark sql(Scala)

Question: I am using following function to parse url but it throws error,
val b = Seq(("http://spark.apache.org/path?query=1"),("https://people.apache.org/~pwendell/spark-nightly/spark-master-docs/latest/api/sql/#negative")).toDF("url_col")
        .withColumn("host",parse_url($"url_col","HOST"))
        .withColumn("query",parse_url($"url_col","QUERY"))
        .show(false)

Error:
<console>:285: error: not found: value parse_url
               .withColumn("host",parse_url($"url_col","HOST"))
                                  ^
<console>:286: error: not found: value parse_url
               .withColumn("query",parse_url($"url_col","QUERY"))
                                   ^

Kindly Guide how to parse url into its different parts.
Comment: parse_url is your custom function?
Answer: parse_url is available as only sql and not as api . refer to parse_url
so you should be using it as a sql query and not as a function call through api
You should register the dataframe and use query as below
val b = Seq(("http://spark.apache.org/path?query=1"),("https://people.apache.org/~pwendell/spark-nightly/spark-master-docs/latest/api/sql/#negative")).toDF("url_col")

b.createOrReplaceTempView("temp")
spark.sql("SELECT url_col, parse_url(`url_col`, 'HOST') as HOST, parse_url(`url_col`,'QUERY') as QUERY from temp").show(false)

which should give you output as
+--------------------------------------------------------------------------------------------+-----------------+-------+
|url_col                                                                                |HOST             |QUERY  |
+--------------------------------------------------------------------------------------------+-----------------+-------+
|http://spark.apache.org/path?query=1                                                        |spark.apache.org |query=1|
|https://people.apache.org/~pwendell/spark-nightly/spark-master-docs/latest/api/sql/#negative|people.apache.org|null   |
+--------------------------------------------------------------------------------------------+-----------------+-------+

I hope the answer is helpful
Answer: Answer by @Ramesh is correct, but you also might want some hacky way to use this function without SQL queries :)
Hack is in the fact, that "callUDF" function calls not only UDFs, but any available function.
So you can write:
import org.apache.spark.sql._
import org.apache.spark.sql.functions._

b.withColumn("host", callUDF("parse_url", $"url_col", lit("HOST"))).
 withColumn("query", callUDF("parse_url", $"url_col", lit("QUERY"))).
 show(false)

Edit: after this Pull Request is merged, you can just use parse_url like a normal function. PR made after this question :)
Answer: As mentioned before, when you register a UDF you don't get a Java function, rather you introduce it to Spark, so you must call it in the "Spark-way".
I want to suggest another method I find convenient, especially when there are several columns you want to add, by using selectExpr
val b = Seq(("http://spark.apache.org/path?query=1"),("https://people.apache.org/~pwendell/spark-nightly/spark-master-docs/latest/api/sql/#negative")).toDF("url_col")
val c = b.selectExpr("*", "parse_url(url_col, 'HOST') as host", "parse_url(url_col, 'QUERY') as query")
c.show(false)

Answer: I created a library called bebe that exposes the parse_url functionality via the Scala API.
Suppose you have the following DataFrame:
+------------------------------------+---------------+
|some_string                         |part_to_extract|
+------------------------------------+---------------+
|http://spark.apache.org/path?query=1|HOST           |
|http://spark.apache.org/path?query=1|QUERY          |
|null                                |null           |
+------------------------------------+---------------+

Calculate the different parts of the URL:
df.withColumn("actual", bebe_parse_url(col("some_string"), col("part_to_extract")))

+------------------------------------+---------------+----------------+
|some_string                         |part_to_extract|actual          |
+------------------------------------+---------------+----------------+
|http://spark.apache.org/path?query=1|HOST           |spark.apache.org|
|http://spark.apache.org/path?query=1|QUERY          |query=1         |
|null                                |null           |null            |
+------------------------------------+---------------+----------------+

How to parse url in spark sql(Scala)


C# Jquery Ajax Post Multiple Data Parameters

Question: In my c# mvc4 application I have three objects I wish to pass to an ActionResult using an AJAX post with Jquery.  The objects are two strings and a form collection.  Ive had no problems passing only the form collection, but cant seem to get the syntax correct for passing all three.  Here is what Ive tried:
 $(document).ready(function () {
        $('#ChangeName').click(function (e) {
            var tdata = $('#form1').serialize();
            var origname = $('#NameDiv').find('input[name="myName"]').first().val();
            var newname = $('#NameDiv').find('input[name="updatedName"]').first().val();
            $.ajax({
                type: "POST",
                data: {tdata + origname + newname},
                url: "Home/ChangeName",
                success: function (result) { success(result); }
            });
        });

Ive also tried commas after each variable name in the data: section with and without the brackets.  How can I pass all three?  When its been successful both string values have populated correctly when debugging but the values dont appear in the ActionResult and show null instead.
Ive also tried placing this below data:  contentType: "application/x-www-form-urlencoded",
Here is the beginning of my ActionResult as well:
 public ActionResult ChangeName(string Name, string updatedName, FormCollection mCollection)

Comment: `{}` you are constructing an object, an object has `key: value` pairs, you are concatenating strings within the object without assigning any `key:value` pairs. `data : { tdata : tdata, origname : origname, newname : newname}`, or simply `data : "tdata="+tdata+"&origname="+origname+"&newname="+newname;`
Comment: @Ohgodwhy I just tried both of your suggestions and once again when debugging the values populate in Firebug but as soon as the code hits the ActionResult both of the string values are shown as null
Answer: Can you try:
$(document).ready(function () {
        $('#ChangeName').click(function (e) {
            var tdata = $('#form1').serialize();
            var origname = $('#NameDiv').find('input[name="myName"]').first().val();
            var newname = $('#NameDiv').find('input[name="updatedName"]').first().val();
            $.ajax({
                type: "POST",
                data: {
                    mCollection: tdata,
                    Name: origname,
                    updatedName: newname
                },
                url: "Home/ChangeName",
                success: function (result) { success(result); }
            });
        });

Comment: However, this is breaking my intended functionality by adding origname and newname to the FormCollection.  Is there a way to send all three of these without them being included in the FormCollection object?
Answer: I think the problem is how you are putting the origname  and newname in the ajax request.
Try this:
var origname = $('#NameDiv').find('input[name="myName"]').first().val();
var newname = $('#NameDiv').find('input[name="updatedName"]').first().val();
$.ajax({
     url: 'Home/ChangeName',
     type: "POST",
     data: $("#form1").serialize() + "&origname =" + origname + "&newname =" + newname,
     success: function (result) { success(result); }
});

Comment: I have tried your suggestion as well and Im getting the same results.  Both string values being null when the code reaches the ActionResult.
Comment: In that case make sure you are reading the origname  and newname  value by jQuery properly. It may be possible that the selector u r using to get these values returns to value. It works for me very well.
Comment: Im not sure that I understand you, but as I mentioned above when debugging in Firebug origname and newname both show the correct values.  Its only when I reach the ActionResult to which they are passed that the values disappear and the parameters are null.  I believe my problem may be not knowing what content type to assign or that it isnt set up correctly to pass multiple object types like a Form Collection and strings together in the same POST.


What is the relationship between confidence intervals that are build with bootstrapping vs t-distributions?

Question: I've seen a few resources online that construct confidence intervals (CI) in different ways.

One is through bootstrapping which essentially samples with replacement from a group of measurements and takes the mean of each of these samples. A 95% CI would then be the range that includes 95% of these sample means.

Another is by taking a sample mean and adding a t-statistic multiplied by the sample standard error:

$$\bar{x} \pm t*\frac{s}{\sqrt{n}}$$
How are these related? (Are they identical?) How are these different?
Comment: In general, they are not identical.  The confidence interval constructed using the standard error of the mean assumes that the sampling distribution of the mean is normal (hence the use of the standard error).  However, if the population distribution is long tailed, this assumption is dubious.  Hence, bootstrapping can be used (which basically approximates the sampling distribution of the statistic).
Answer: If you know that data are sampled from a normal distribution, but with unknown mean and variance,
you can use the displayed formula in the second
part of your question to get an exact 95% CI. That is, over the long run such CI's will 'cover' (include) the population mean $\mu$ 95% of the time.
Roughly speaking, to the extent that data are not
normal such CIs (especially ones based on small
samples) will not be accurate.
The R procedure t.test makes 95% CIs, using your formula. A normal sample of size $n = 20$ from
a distribution with mean $\mu = 50$ and the resulting 95% CI $(45.522, 51.140)$ are shown below:
set.seed(2022)
y = rnorm(20, 50, 6)
summary(y);  sd(y)
   Min. 1st Qu.  Median    Mean 3rd Qu.    Max.
  32.60   44.25   49.20   48.33   52.38   56.12
[1] 6.00178   # sample SD
t.test(y)$conf.int
[1] 45.52181 51.13965
attr(,"conf.level")
[1] 0.95

If you know the distribution type of a non-normal population, you may be able to find an exact 95% CI
using statistical theory. For example, if data are
exponential, then you can 'pivot' the relationship
$$\frac{\bar X}{\mu} \sim
\mathsf{Gamma}(\mathrm{shape}=n,\, \mathrm{rate}=n)$$
to get an exact 95% CI of the form
$(\bar X/U,\, \bar X/L),$ where $L, U$ cut probabilities $0.025$ from the lower and upper tails, respectively, for the gamma distribution given above.
For example, consider the following data and 95% CI
$(7.02,\, 17.04).$
set.seed(1234)
x = rexp(20, 1/10)  # population mean 10.
summary(x)
    Min.  1st Qu.   Median     Mean  3rd Qu.     Max.
 0.06582  2.35724  8.31061 10.40792 17.44730 30.52458
mean(x)/qgamma(c(.975,.025), 20, 20)
[1]  7.015584 17.039088

If you had mistakenly assumed that sample x was sampled from a normal population, you would get
a somewhat inaccurate "95% CI" $(6.18, 14.63).$ from your formula.
t.test(x)$conf.int
[1]  6.184321 14.631515
attr(,"conf.level")
[1] 0.95

If you did not know the distribution families
from which samples x and y were drawn, then
you might use nonparametric bootstrap CIs for
the population means.
There are many styles of bootstraps. Unfortunately,
the quantile method you describe in your question
does not always give the best results.
I will use a slight modification of it based on
distances between re-sample means and the means of the original samples.
The sample size $n = 20$ is barely adequate for
bootstrapping. But let's see what CIs we get for
the population means of normal sample y and
exponential sample y, respectively.
First, the normal sample for which the t CI is
$(45.522, 51.140)$ The 95% nonparametric bootstrap CI is $(45.903, 50.878),$ which is not the same,
but also not far off.
set.seed(216);  a = mean(y)
d = replicate(2000, mean(sample(y,20,rep=T))-a)
UL = quantile(d, c(.975,.025))
a - UL
  97.5%    2.5%
45.9033 50.8783

Second, for the exponential sample 'x'
the exact 95% CI is $(7.02, 17.04)$ and
the 95% bootstrap CI is $(6.67, 14.15),$
which is not bad for such a small sample from a skewed distribution.
set.seed(217);  a = mean(x)
d = replicate(2000, mean(sample(x,20,rep=T))-a)
UL = quantile(d, c(.975,.025))
a - UL
97.5%      2.5%
6.670051 14.148429

Note: The exact 95% CIs above for the exponential mean are not symmetrical
about $\bar X.$ Instead, they are 'probability symmetric' because they
cut probability $0.025$ from each tail
of the relevant gamma distribution.
Equally valid 95% CIs might split the tail probabilities, totaling 0.05, as 0.02:0.03 or as 0.03:0.02. Thus, it one usually speaks of a 95% CI
instead of the 95% CI for a particular parameter. Three equally valid exact 95% CIs for the exponential mean $\mu = 1/\lambda$ above might be as follows:
set.seed(1234)
x = rexp(20, 1/10)
mean(x)/qgamma(c(.97,.02), 20, 20)
[1]  7.125314 17.464727

mean(x)/qgamma(c(.98,.03), 20, 20)
[1]  6.88854 16.69026

mean(x)/qgamma(c(.975,.025), 20, 20)
[1]  7.015584 17.039088


How are the age restrictions followed by ICC for under 19 cricket tournaments?

Question: I have some doubts under this topic,

Can a player aged 19 play under 19 international cricket match?
(Since 19 is not under 19)
Consider a player having birthday during the series/tournament. How
the age will be calculated for him?
Comment: Nice question. I too had doubt why players like Samson, Vijay Zol who are over 19 can play under 19 WC.
Answer:
Can a player aged 19 play under 19 international cricket match? (Since 19 is not under 19)

The age of the player is not determined during the world cup. It is determined on 1st of September before the world cup. E.g. For ICC U19 World Cup 2014 the age of the players was determined based on 1st September 2013. That means any player must be under 19 on 1st Sept. 2013 to be qualified. You can see some players like Vijay Zol, Sanju Samson were over 19 during U19 WC 2014. But they were under 19 on 1st Sept. 2013.
Also to note, maximum age of 19 is applicable for players of Full Member countries only. For players from Associate and Affiliate Member countries the maximum age is 20 (probably due to limited number of cricketers).
Source: Age Determination Policy for ICC Under 19 Cricket World Cup PDF

Consider a player having birthday during the series/tournament. How the age will be calculated for him?

To clear the doubt players must be under 19/20 at midnight (in the country of birth). E.g. at changeover from the 31st August to the 1st September.


Função para printar diretório em uma Label Python

Question: Criei uma função que abre um arquivo com o Tkinter + filedialog, até ai tudo certo.
Porém preciso printar o diretório do arquivo selecionado em uma Label.
Segue função:
from tkinter import *
from tkinter import filedialog
import pandas as pd

def browse_button2():
    df2 = pd.read_csv(filedialog.askopenfile()) #aqui o botão seleciona o arquivo
    lb2["text"] = filedialog.askopenfilename() #aqui estou tentando definir que o label receba em sua propriedade "text" como valor a caminho do arquivo selecionado, Exemplo "C:\documentos\texte.csv"
    return df2

lb2 = Label(root, font=( 'arial', 10), bd=1, width=43, height=1, relief=RIDGE, borderwidth=1)
lb2.grid(row=2, column=0)
lb2.configure(background='#FFFFFF')
lb2.place(x=48, y=136)

Answer: Para inserir um texto no Label use o método config e passe o diretório obtido como argumento para o parâmetro text. O objeto Label funciona também como um dicionário, logo você também pode definir a chave text do objeto com o diretório: Exemplo:
label.config(text=path)
label["text"] = path

O seu programa está abrindo duas vezes a caixa de diálogo porque você está chamando askopenfile() na primeira linha da função e depois você está chamando askopenfilename() na terceira linha.
Talvez o que você queira é usar o diretório do arquivo selecionado no filedialog.askopenfile() para inserir no Label. Para isso, basta usar o atributo name para pegar o diretório do arquivo:
def browse_button2():
    file = filedialog.askopenfile() # Recebo o arquivo selecionado
    df2 = pd.read_csv(file)
    lb2["text"] = file.name # Estou passando o diretório do arquivo selecionado
    return df2

Comment: para printar o diretório usei o seguinte   lb2["text"] = filedialog.askopenfilename()                  ele da certo ele printa o diretório do arquivo, porem ele abre 2x a caixa de dialogo para selecionar um arquivo
Comment: entendi,  vou tentar explicar de uma forma melhor. para abrir o arquivo estou utilizando o askopenfile(), que me abre uma janela para escolher o arquivo. eu não estou discrevendo no código um caminho fixo para escolher o arquivo. quando portanto quando utilizo o comando da forma que vc me mandou ele printa o camino da função "Path" e nao do caminho do arquvo que selecionei
Comment: Acho que entendi o que você quer então, vou editar a resposta. Por favor veja se é isso mesmo.
Comment: Muito bom, é isso mesmo, muito obrigad, sou novo com programação, isso é bem basico mas pra quem ta comesando as vezes enrroca em coisas bobas


Integral Expression Without $dx$, $dy$, $d\tau$, etc.

Question: My textbook gives the following proof of the single-variable version of Taylor's theorem:

As promised, we begin with the Fundamental Theorem of Calculus, written in the form
$$f(x_0 + h) = f(x_0) + \int_{x_0}^{x_0 + h} f'(\tau) \ d \tau$$
Next, we write $d \tau = - d(x_0 + h - \tau)$ and integrate parts to give
$$f(x_0 + h) = f(x_0) = f'(x_0) h + \int_{x_0}^{x_0 + h} f''(\tau)(x_0 + h - \tau) \ d \tau,$$
which is the first-order Taylor formula. Integrating by parts again, we get
$$\int_{x_0}^{x_0 + h} f''(\tau)(x_0 + h - \tau) \ d\tau = - \dfrac{1}{2} \int_{x_0}^{x_0 + h} f''(\tau) d(x_0 + h - \tau)^2$$
$$= \dfrac{1}{2} f''(x_0) h^2 + \dfrac{1}{2} \int_{x_0}^{x_0 + h} f'''(\tau)(x_0 + h - \tau)^2 \ d \tau,$$
which, when substituted into the preceding formula, gives the second-order Taylor formula:
$$f(x_0 + h) = f(x_0) + f'(x_0) h + \dfrac{1}{2}f''(x_0) h^2 + \dfrac{1}{2} \int_{x_0}^{x_0 + h} f'''(\tau)(x_0 + h - \tau)^2 \ \ d\tau$$

I'm confused by the expression
$$- \dfrac{1}{2} \int_{x_0}^{x_0 + h} f''(\tau) d(x_0 + h - \tau)^2$$
Can someone explain what this means when the integral is without a $dx$, $dy$, $d\tau$, etc.? Is such a thing even a valid integral expression? And if there is no $d\tau$, then how are we supposed to know what we integrate the integrand with respect to?
I would greatly appreciate it if someone could please take the time to explain this.
Answer: I think you can safely ignore it, but what it means is:
$$
\int_{x_0}^{x_0 + h} f''(\tau)(x_0 + h - \tau)d\tau = -\frac{1}{2}\int_{x_0}^{x_0 + h}f''(\tau)\frac{d}{d\tau}(x_0 + h - \tau)^2\; d\tau.
$$
Given that (I hate this:) "the $d\tau$'s cancel", they have written the right-hand side above without either $d\tau$.
Comment: Ahh, ok, that makes sense. Thanks for the clarification!


How To Get Google Event Messages From Pub/Sub service in terminal?

Question: Is there a command to get the Message body as shown in the Google Cloud Platform Console Subscriptions (relating to event triggers from Nest Doorbell Device) in the terminal?
If not, how can I make an API request to the Pub/Sub service and receive the same JSON Payload shown in the GCP Console?
Thanks
Answer: You can use the gcloud CLI to view subscription messages. Just do not ack the message so that it will continue to be delivered to subscribers.
Note: I do not work with the Nest doorbell, so I cannot comment on their interface. The following is specific to the Pub/Sub service.
gcloud pubsub subscriptions pull
You can do the same thing with the REST API or one of the SDKs.
REST API: Method: projects.subscriptions.pull
SDK: Receiving messages using Pull
Comment: For the REST API I am getting a permission denied error, I have added the API key to the URL, I think I need to add OAuth credentials to the POST request but I am unsure on how to do it?
Comment: @john - API keys are not supported, you must use an access token. Create a new question - to answer requires details from you and the steps are too big to put in comments. As a tip, this command will generate the token you need: https://cloud.google.com/sdk/gcloud/reference/auth/application-default/print-access-token Add an HTTP header **Authorization: Bearer TOKEN** to your REST API request.
Comment: @john - Also read this link that discusses IAM Pub/Sub authorization: https://cloud.google.com/pubsub/docs/access-control
Comment: i have posted a new question: https://stackoverflow.com/questions/70961353/proper-way-of-authorizing-google-pub-sub-rest-api-post-request


Tratar retorno na classe em C#

Question: Tenho uma classe Mesa:
public class Mesa
{
   public int Cdmesa { get; set; }
   public int Flsituacao { get; set; }
   public string Status { get; set; }
}

Gostaria de retornar o Status com as seguintes condições:

Se Flsituacao = 1 retornar Status "LIVRE"
Se Flsituacao = 2 retornar Status "OCUPADO"

É possível fazer isso diretamente na classe?
Comment: Eu falei partes relevantes. Eu dei uma resposta, mas só com isso não sei se está certa. Ou pode dar mais detalhes. Note que eu fiz o que parece ser o que quer, mas não é certo, não sei o que deve fazer com o `set`. Veja se acha que precisa mudar algo na resposta.
Comment: Pode colocar outras partes relevantes da classe? Posso responder assim, mas será na "sorte".
Comment: A classe é bem grande e eu não consigo copiar pois esta em outro pc sem internet. O que mais seria relevante?
Answer: você pode definir um get;set; personalizado.
public class Mesa
{
    public int Cdmesa { get; set; }
    public int Flsituacao { get; set; }
    public string Status
    {
        get
        {
            switch (this.Flsituacao)
            {
                case 1: return "LIVRE";
                case 2: return "OCUPADO";
                default: return "SITUACAO NÃO ENCONTRADA"
            }
        }
        set
        {
            switch (value)
            {
                case "LIVRE": this.Flsituacao = 1; break;
                case "OCUPADO": this.Flsituacao = 2; break;
            }
        }
    }
}

mas neste caso, o mais racional é usar um enumerador.
public enum MesaSituacao : int
{
    [Display(Name = "LIVRE")]
    Livre = 1,
    [Display(Name = "OCUPADO")]
    Ocupado = 2,
    [Display(Name = "RESERVADO")]
    Reservado = 3,
}

public class Mesa
{
    public int Cdmesa { get; set; }
    public MesaSituacao Flsituacao { get; set; }
}

Answer: Depende do que você chama de diretamente na classe. Se for isso mesmo não tem como. Mas pode fazer na propriedade.
public class Mesa {
    public int Cdmesa { get; set; }
    public int Flsituacao { get; set; }
    public string Status {
        get {
            if (Flsituacao == 1) return "LIVRE";
            if (Flsituacao ==  2) return "OCUPADO";
            return "RESERVADO";
        }
    }
}

Coloquei no GitHub para referência futura.
Não vou chutar o que o set deve fazer já que a pergunta não diz o que é. Se tiver que mandar o texto e ele ter que setar o Flsituacao não vejo vantagem em ter os dois a não ser pensando para o futuro.
Comment: Realmente não tinha necessidade de implementar o SET e acabei tirando. As duas respostas estão certas. Valeu
Comment: @leopiazzoli imagino que ambas ajudam, mas como elas são diferentes só uma te atendeu melhor e foi o que você resolveu fazer, pode escolher qualquer uma das duas.
Comment: Ah, vi agora que já escolheu a outra.
Comment: Usei a resposta que tem SWITCH pra caso venha a adicionar mais situações no futuro. Mas também o SET era desnecessário. :)
Comment: @leopiazzoli Eu pensei em fazer, mas nesse caso da exatamente na mesma, a não ser pelo fato de ter um valor *default*, eu não o fiz porque na sua pergunta não consta isso, não consta o que deve fazer se vier um valor errado, se nunca pode vir um valor errado (que é o que eu considerei, pelo menso é o certo a fazer), ou seja, fui na lógica mais correta para o caso, de acordo com o descrito.

Tratar retorno na classe em C#


SFTP Can't upload module despite using owner's credentials

Question: I'm new to both Linux and Drupal, but I can see that the owner and group assigned to the drupal modules directory is one of my SU accounts on the server. When I log on to SFTP I use that same credential.
I tried to upload a module using Aptana studio and it tells me it can't create folders.
Do you feel that there's additional ownership info needed on the server side? Would my folder rights not be applicable when connecting via SFTP?
Answer: Using ssh you can log in to the system to check about directory permissions using the same credentials you use with sftp.
try..
ssh user@host

to login and then use a number of commands to check permissions
ls -l                      //Lists files with permissions for user, group and other
chmod 755 dir/file         //Change file/directory permission
chown user:group dir/file  //Change the user/group ownership of file(s)

scp command can also upload file from local (*nix) machine to server.
scp path/to/local/file user@host:/path/on/server

Comment: Shoaib, thank you. I had already done the chown but not the chmod so I went up a folder and did a chmod on the drupal modules directory. It does not seem to have affected the ability to remote mkdir from within the sftp client I am currently using however, I will look into it further and comment on this thread when completed.


CSS Grid Dropdown Menu

Question: When clicking on the hamburger icon, I want the dropdown menu to overlay the content below the header. At the moment, the problem is that the dropdown menu is pushing the content down instead of overlaying it. I tried fiddling with z-index and positioning but nothing seems to work.
HTML Code

        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>Document</title>
        <link href="https://fonts.googleapis.com/css2?family=Montserrat:wght@700&family=Rubik:wght@700&display=swap" rel="stylesheet">
        <link rel="stylesheet" type="text/css" href="../css/main.css">

Home

Programs

Tournaments

Recreation

About

Contact

CSS Code
:root {
    --primary-color: #000A41;
    --secondary-color: #c62828;
}

html {
    box-sizing: border-box;
}

*, *::before, *::after {
    box-sizing: inherit;
}

body {
    margin: 0;
    padding: 0;
    font-family: 'Montserrat', sans-serif;
}

header {
    background-color: var(--primary-color);
    color: #fff;
    display: grid;
    grid-template-columns: 1fr 1fr 1fr 1fr 1fr;
    grid-template-rows: 25% 25%;
}

/******************/
/* Navigation bar */
/******************/

nav {
    grid-column: 1 / 6;
    grid-row: 2 / 3;
}

nav ul {
    list-style: none;
    margin: 0;
    padding: 0;
    overflow: hidden;
    transition: height 400ms ease;
}

nav ul:not(.active) {
    display: none;
}

nav li {
    text-align: center;
    padding: 25px 10px 25px 10px;
    border-top: 2px solid #fff;
    z-index: 10;
}

nav li:hover {
    background-color: var(--secondary-color);
}

nav a {
    text-decoration: none;
    text-transform: uppercase;
    color: #fff;
}

.nav-toggle {
    grid-column: 5 / 6;
    place-self: center;
    position: relative;
    cursor: pointer;
    width: 50px;
    height: 50px;
}

.nav-toggle.active .nav-icon {
    background-color: rgba(0, 0, 0, 0);
}

.nav-toggle.active .nav-icon::before {
    top: 0;
    transform: rotate(45deg);
}

.nav-toggle.active .nav-icon::after {
    top: 0;
    transform: rotate(135deg);
}

.nav-icon {
    position: absolute;
    width: 40px;
    height: 6px;
    left: 50%;
    margin-left: -20px;
    top: 50%;
    margin-top: -3px;
    background-color: #fff;
}

.nav-icon:before,
.nav-icon:after {
    content: '';
    position: absolute;
    width: 40px;
    height: 6px;
    background-color: #fff;
    transition: 400ms;
}

.nav-icon:before {
    top: -12px;
}

.nav-icon:after {
    top: 12px;
}

.nav-logo {
    grid-column: 1 / 2;
    place-self: center;
    width: 50px;
    margin: 0.5em;
}

/******************/
/*    Home Page   */
/******************/

.home {
    display: grid;
    /* grid-template-rows: 1fr 1fr; */
    grid-template-columns: 1fr 1fr 1fr 1fr 1fr;
    grid-template-rows: 25% 25%;
    background-color: var(--primary-color);
}

.home-logo {
    grid-column: 2 / 5;
    place-self: center;
    width: 217px;
}

JS Code
var ready = (callback) => {
    if (document.readyState != 'loading') {
        callback()
    } else {
        document.addEventListener('DOMContentLoaded', callback)
    }
}

ready(() => {
    const nav_menu = document.getElementById('nav-menu')
    const nav_icon = document.getElementById('nav-toggle')

    nav_icon.addEventListener('click', (e) => {
        e.preventDefault()
        nav_collapse()
    })

    function nav_collapse() {
        // set exit icon
        nav_icon.classList.toggle('active')

        if (!nav_menu.classList.contains('active')) {
            // display menu
            nav_menu.classList.add('active')
            nav_menu.style.height = 'auto'

            // get computed height of menu
            let height = nav_menu.clientHeight + 'px'

            // set height of menu to 0 to trigger the slide down animation
            nav_menu.style.height = '0px'

            // set 100ms delay for slide down effect
            setTimeout(() => {
                nav_menu.style.height = height
            }, 100);
        } else {
            // set height of menu to 0 to trigger the slide up animation
            nav_menu.style.height = '0px'

            // collapse menu when animation finishes
            nav_menu.addEventListener('transitionend', () => {
                nav_menu.classList.remove('active')
            }, {once: true})
        }
    }
})

Comment: Can you please tell me. Do you want this section part under the navigation or not?
Answer: In this section part in displayed under the navigation and now content is not coming upon the nav  part. Can you check and tell me how you want to diplayed it and where?

var ready = (callback) => {
    if (document.readyState != 'loading') {
        callback()
    } else {
        document.addEventListener('DOMContentLoaded', callback)
    }
}

ready(() => {
    const nav_menu = document.getElementById('nav-menu')
    const nav_icon = document.getElementById('nav-toggle')

    nav_icon.addEventListener('click', (e) => {
        e.preventDefault()
        nav_collapse()
    })

    function nav_collapse() {
        // set exit icon
        nav_icon.classList.toggle('active')

        if (!nav_menu.classList.contains('active')) {
            // display menu
            nav_menu.classList.add('active')
            nav_menu.style.height = 'auto'

            // get computed height of menu
            let height = nav_menu.clientHeight + 'px'

            // set height of menu to 0 to trigger the slide down animation
            nav_menu.style.height = '0px'

            // set 100ms delay for slide down effect
            setTimeout(() => {
                nav_menu.style.height = height
            }, 100);
        } else {
            // set height of menu to 0 to trigger the slide up animation
            nav_menu.style.height = '0px'

            // collapse menu when animation finishes
            nav_menu.addEventListener('transitionend', () => {
                nav_menu.classList.remove('active')
            }, {once: true})
        }
    }
})
     :root {
    --primary-color: #000A41;
    --secondary-color: #c62828;
}

html {
    box-sizing: border-box;
}

*, *::before, *::after {
    box-sizing: inherit;
}

body {
    margin: 0;
    padding: 0;
    font-family: 'Montserrat', sans-serif;
}

header {
    background-color: var(--primary-color);
    color: #fff;
    display: grid;
}

/******************/
/* Navigation bar */
/******************/

nav {
    grid-column: 1 / 6;
    grid-row: 2 / 3;
}

nav ul {
    list-style: none;
    margin: 0;
    padding: 0;
    overflow: hidden;
    transition: height 400ms ease;
}

nav ul:not(.active) {
    display: none;
}

nav li {
    text-align: center;
    padding: 25px 10px 25px 10px;
    border-top: 2px solid #fff;
    z-index: 10;
}

nav li:hover {
    background-color: var(--secondary-color);
}

nav a {
    text-decoration: none;
    text-transform: uppercase;
    color: #fff;
}

.nav-toggle {
    grid-column: 5 / 6;
    place-self: center;
    position: relative;
    cursor: pointer;
    width: 50px;
    height: 50px;
}

.nav-toggle.active .nav-icon {
    background-color: rgba(0, 0, 0, 0);
}

.nav-toggle.active .nav-icon::before {
    top: 0;
    transform: rotate(45deg);
}

.nav-toggle.active .nav-icon::after {
    top: 0;
    transform: rotate(135deg);
}

.nav-icon {
    position: absolute;
    width: 40px;
    height: 6px;
    left: 50%;
    margin-top: 25px;
    background-color: #fff;
}

.nav-icon:before,
.nav-icon:after {
    content: '';
    position: absolute;
    width: 40px;
    height: 6px;
    background-color: #fff;
    transition: 400ms;
}

.nav-icon:before {
    top: -12px;
}

.nav-icon:after {
    top: 12px;
}

.nav-logo {
    grid-column: 1 / 2;
    place-self: center;
    width: 50px;
    margin-top: 25px;
}

/******************/
/*    Home Page   */
/******************/

.home-logo {
    grid-column: 2 / 5;
    place-self: center;
    width: 217px;
}

        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>Document</title>
        <link href="https://fonts.googleapis.com/css2?family=Montserrat:wght@700&family=Rubik:wght@700&display=swap" rel="stylesheet">
        <link rel="stylesheet" type="text/css" href="../css/main.css">

RVA

Home

Programs

Tournaments

Recreation

About

Contact

Comment: I want the nav dropdown to overlay over the logo. When I ran the snippet, it simply pushed the logo down instead of stacking over it. Let me know if I'm not being clear, please.
Comment: ok if it is logo which is going down then what was that which is in the right side volleyball acedemy. you want this to put or it was a mistake? I can remove that image if it is not being used or i use only logo in place of this academy pic or text.
Comment: "  the right side volleyball acedemy" sorry left side image
Comment: The logo does not come down it stays fixed in the navbar. Only the menu comes down. You can use text if that makes it easier.
Comment: Check this, i use text in place of image.

CSS Grid Dropdown Menu


Storing jQuery variables in Rails cookies

Question: I'm having a bit of trouble trying to post jQuery variables to a Rails cookie.
I want to store two jQuery variables when any user visits the page.
I've got a bit of Ajax making the post, thus:
/$.post('/where', {var1: one, var2: two});

I'm just not wholly sure how to set up the '/where' part.
Any help would be great!
Cheers.
Answer: Instead of posting directly to a Rails cookie, you should post to the "/where" url, which calls a controller action. In the action, you can set the cookies.
For example,
in your routes, declare:
post "/where", :to => "whatever#where"

in your controller:
class WhateverController < ApplicationController

  def where

    session[:var1] = params[:var1]
    session[:var2] = params[:var2]

    ...
    render :nothing => true //if you don't want to render anything
  end

 end

If that's not what you're looking for, can you elaborate more in your question?


Como funcionam decoradores em Python?

Question: O @Elizeu Santos perguntou no grupo de Python em português do facebook o seguinte:

"Fala galera, to estudando python e uma coisa que não estou entendendo
  são os decorators. Dei de cara com eles fazendo o tuto de flask, podem
  me esclarecer?"

(O facebook não é legal para responder perguntas que incluam português e código misturado nos comentários - aqui é muito melhor formatado pra isso - então trouxe a pergunta pra cá, para colar a resposta que eu escrevi pra ele)
Answer: Uma função em Python é um objeto como qualquer outro - quando fazemos def func(): ..., o nome func fica associado ao corpo da função que é definido depois do comando def.
Um decorator é uma função (ou outro objeto chamável) que recebe uma função como parâmetro e retorna uma função. Essa nova função que é retornada pelo decorator é que fica associada ao nome da função original.
Ou seja, suponha um decorator deco, se for usado com a sintaxe de
@ faz exatamente o mesmo que isso aqui:
def func():
   # faz coisas
func = deco(func)

Esse trecho de código é o mesmo que:
@deco
def func():
   #faz coisas

Nos dois casos, depois desse trecho de código, o nome func fica associado ao objeto que foi retornado pela chamada a função deco. Em geral esse objeto é uma função que chama a função func original, mas faz alguma coisa antes ou depois de chamá-la.
Por exemplo, um decorador que simplesmente registra quantas vezes as funções que ele decora foram chamadas, numa variável global contador pode ser declarado assim:
contador = 0

def contar_acessos(funcao_decorada):
    # não sabemos quantos parâmetros existirão na chamada
    # da função funcao_decorada, então recebemos *args e **kw
    def nova_func(*args, **kw):
         global contador
         contador += 1
         # e chamamos a função original, com os parâmetros recebidos:
         return funcao_decorada(*args, **kw)
    # retornamos a função "nova_func" - que só faz
    # incrementar o contador e  retornar o valor da chamada à função original
    return nova_func

# agora vamos usar o decorador:
@contar_acessos
def soma(a, b):
    return a + b

E quando colamos esse código no interpretador interativo e chamamos soma algumas vezes, temos:
>>> contador
0
>>> soma(2,2)
4
>>> soma(3,2)
5
>>> soma("a", "b")
'ab'
>>> contador
3

Então, nesse caso simples, tudo o que é feito é aumentar o valor da variável contador antes de chamar a mesma função que foi decorada (e que dentro da função nova_funcao está com o nome de funcao_decorada já que ela é passada como parâmetro para a função de fora, a contar_acessos).
Mas você pode sofisticar a coisa - pode-se criar uma função que guarde o valor de retorno da função decorada num dicionário, por exemplo, daí você faz um cache simples (memoize). Pode-se simplesmente registrar a função decorada numa lista de "funções que fazem algo", e retornar ela mesma, sem criar uma nova função decoradora. Acredito que é isso que o Flask faz - anota a sua função decorada como uma função que responde a um endereço na URL.
Comment: Gostei da iniciativa. Por mais que eu saiba o que são os decorators em Python, eu sempre tenho que treinar e reler, para não ficar confuso

Como funcionam decoradores em Python?


the Zariski topology on $\mathbb{A}^{n}_K$ is discrete iff $K$ is finite field.

Question:
Suppose that $K$ is a finite field, then the Zariski topology on $\mathbb{A}^{n}_K$ is discrete. Show that it is never true if $K$ is an infinite field.

Suppose that $K$ is a finite field, then consider any singleton set $T=\{(a_1,a_2 \dots a_n)\}$ of $\mathbb{A}^{n}_K$. Then I claim that $T$ is a closed subset.
To see that consider the set of polynomials $$T=\{x_i-a_i : i=1,2,3 \dots n \} $$. Then $V(S)=T$ which proves that $T$ is a closed subset. Further since our set over which the topology is being defined is a finite set, it has the discrete topology.
Now I am unable to do the subproblem which asks us to show that this is never the case when $K$ is an infinite field. How should I show that? I thought that showing a particular set is not of the form of $V(S)$ would work, because the sets of the form $V(I)$ satisfy the closed set definition of a topology, but I am unable to find a set and prove the desired result. I am considering the set of the form $S=\{a,a,a \dots a : a\in K\}$ but I am stuck.
Will the following work?
Consider $S=\{a,a,a \dots a : a\in K\}$ is a closed set, then $S=\{a,a,a \dots a : a\in K\}=V(I)$, then $I=\{f(x_1,x_2 \dots x_n) : f(a,a, \dots a )=0 \text{ for all } a \in K \}$. Choose any element $f(x_1,x_2 \dots x_n ) \in I$, then $f(a,a \dots a)=0 \Rightarrow x-a | f(x_1,a \dots a) $ for all $a \in K$. Since the cardinality of the field being considered here is infinite and any polynomial here is finite degree, implies $f(x)=0 \Rightarrow \! \Leftarrow$. The division algorithm works because we are working in a field and any field is an euclidean domain.
Answer: Here's an outline of a solution: reduce to the case of $\Bbb A^1$. Now classify the closed subsets of $\Bbb A^1_k$ (hint: use the coordinate algebra; see the related questions in the sidebar if you're stuck on this bit). Think about what would need to happen for that topology to be the discrete topology.
A bigger hint:

 When is the cofinite topology the discrete topology? Look at the intersection of any two open subsets.

It's important to note that this situation is unique to the situation of "classical varieties" - the scheme $\Bbb A^1_k$ is irreducible for any field $k$, exactly as one would expect.


Does it mean $|N_H|=|H|$?

Question: Let $G$ be a finite group and $H$ be a proper subgroup of $G$. Let $N_H:=\{g\in G: gHg^{-1}=H\}$ be the normalizer of $H$. I try to show that the index of $H$ in $G$ is greater than the index of $N_H$ in $G$, that is
$$
[G:N_H]\le [G:H]
$$
My proof is to use the Lagrange's theorem,
$$
|G|=|H|[G:H]=|N_H|[G:N_H]
$$
and note that $H\subset N_H$, so by $|H|\le N_H$, we complete the proof.
However, I saw a statement in the lecture note

For a subgroup $H$ of $G$, we have
$$
|gHg^{-1}|=|H|
$$

Does it mean $|N_H|=|H|$?
Comment: No. The elements of $N_H$ are the $g$s that make $gHg^{-1} = H$, not the elements of $gHg^{-1}$.
Comment: Please don't forget to accept an answer.
Answer: Consider the symmetric group $G=S_3$ and let $H=A_3$ be the subgroup of even permutation then,
$|G:H|=\frac{|G|}{|H|}=\frac{3!}{3}=2$ so $H$ is normal subgroup in $G$ .
And using the following property :
$H$ is normal subgroup in $G$ if and only if $N_H=G$ .
we deduce that $N_{A_{3}}=S_3$ now you see that the order of $H$ is 3 and the order of $N_H$ is 6 which means $|N_H|\neq|H|$
Answer: No.
The smallest counterexample is $H=\{e\}$ in $G=\Bbb Z_2$, since then $H\lhd G$, meaning
$$\boxed{N_{\Bbb Z_2}(\{e\})=\Bbb Z_2}$$
but $|\{e\}|<|\Bbb Z_2|.$

One of the smallest nontrivial counterexamples is $H=\Bbb Z_2$ in $G=\Bbb Z_4$, since then $H\lhd G$ (as $G$ is abelian), meaning
$$\boxed{N_{\Bbb Z_4}(\Bbb Z_2)=\Bbb Z_4}$$
but $|\Bbb Z_2|<|\Bbb Z_4|.$

I have used the more common notation of $N_G(H):=N_H.$
Comment: Is $|gHg^{-1}|=|N_H|$? Can you some examples?
Comment: No, since $|H|=|gHg^{-1}|$. Conjugation in a group is a bijection, @Hermi.

Does it mean $|N_H|=|H|$?


Create an Ellipse in javavfx where the scaling is from the top left (like a Rectangle) rather than center

Question: I have a javafx program that generates a canvas where a user can draw an Ellipse. I am using the press down, drag and release technique for the mouse.
However I want to be able to scale the shape in size from the top left corner of the shape (much like a Rectangle is scaled) rather than its center. Is there any suggestions to how I could achieve this?
@Override
public void start(Stage ellipseStage) {

    //Create ellipse
    ellipsePane = new Pane();
    ellipsePane.setMinSize(600,600);

    ellipsePane.setOnMousePressed(e -> {
        if (e.getButton() == MouseButton.PRIMARY) {
            ellipse = new Ellipse();
            ellipse.setCenterX(e.getX());
            ellipse.setCenterY(e.getY());
            ellipse.setStroke(Color.ORANGE);
            ellipse.setFill(Color.BLACK);
            ellipsePane.getChildren().add(ellipse);
        }
        //if we double click
        if (e.getClickCount() == 2) {
            ellipse = null;
        }
    });

    //When the mouse is dragged the ellipse expands
    ellipsePane.setOnMouseDragged(e -> {
        if (ellipse != null) {
            ellipse.setRadiusX(e.getX() - ellipse.getCenterX());
            ellipse.setRadiusY(e.getY() - ellipse.getCenterY());
        }
    });

    Scene scene = new Scene(ellipsePane);
    ellipseStage.setScene(scene);
    ellipseStage.show();
}

public static void main(String[] args) {
    launch(args);
}}

Comment: You're setting the radius based on the position of the click, relative to the center. What if you used `getLayoutX()` or `getCenterX() - getRadiusX()/2` to get the edge position?
Answer: One option is to keep track of the location of the original mouse press, then set the center X/Y properties of the Ellipse to always be the midpoint between the origin and where the mouse is currently (i.e. where it's dragged). The radii would be half the distance between the origin and the current location as well. Here's an example:
import javafx.application.Application;
import javafx.geometry.Point2D;
import javafx.scene.Scene;
import javafx.scene.input.MouseEvent;
import javafx.scene.layout.Pane;
import javafx.scene.shape.Ellipse;
import javafx.stage.Stage;

public class Main extends Application {

    private Pane pane;
    private Point2D origin;
    private Ellipse ellipse;

    @Override
    public void start(Stage primaryStage) {
        pane = new Pane();
        pane.setOnMousePressed(this::handleMousePressed);
        pane.setOnMouseDragged(this::handleMouseDragged);
        pane.setOnMouseReleased(this::handleMouseReleased);

        primaryStage.setScene(new Scene(pane, 600.0, 400.0));
        primaryStage.show();
    }

    private void handleMousePressed(MouseEvent event) {
        event.consume();

        origin = new Point2D(event.getX(), event.getY());
        ellipse = new Ellipse(event.getX(), event.getY(), 0.0, 0.0);
        pane.getChildren().add(ellipse);
    }

    private void handleMouseDragged(MouseEvent event) {
        event.consume();

        ellipse.setCenterX((origin.getX() + event.getX()) / 2.0);
        ellipse.setCenterY((origin.getY() + event.getY()) / 2.0);
        ellipse.setRadiusX(Math.abs(event.getX() - origin.getX()) / 2.0);
        ellipse.setRadiusY(Math.abs(event.getY() - origin.getY()) / 2.0);
    }

    private void handleMouseReleased(MouseEvent event) {
        event.consume();

        ellipse = null;
        origin = null;
    }

}

Comment: Thank you. This looks promising and also seems like a cleaner way to arrange my code.
Answer: So I presume what you mean is that when you drag the ellipse, the edge position changes but you want the edge position to stay the same and the center to move.
ellipsePane.setOnMouseDragged(e -> {
    if (ellipse != null) {

        double x0 = ellipse.getCenterX() - ellipse.getRadiusX();
        double y0 = ellipse.getCenterY() - ellipse.getRadiusY();

        //the new radii
        double rxp = e.getX() - x0;
        double ryp = e.getY() - y0;

        //the new center positions. to keep the origin the same.
        double cx = x0 + rxp;
        double cy = y0 + ryp;

        ellipse.setRadiusX(rxp);
        ellipse.setRadiusY(ryp);
        ellipse.setCenterX(cx);
        ellipse.setCenterY(cy);

    }
});


Force parsing a from parent-type to child-type?

Question: I have a class that have many other classes extends it. So now I use GenericPool to recycle items for better performance. But the problem is, I can't cast child class, for example:
StarDustSprite sprStarDust = (StarDustSprite) splStarDust[rndGenerator.nextInt(Parent.andStarDustR.length)].obtainPoolItem();

(StarDustSprite extends a class named Sprite, and the obtainPoolItem() function return a Sprite object).
So can I force parse it? Or I have to make 10 GenericPool class if I have 10 child-classes?
Thank you.
Comment: Beware - recycling objects "for better performance" can lead to *worse* performance!
Comment: Could you explain why? Everytime I create a Sprite, I have to create a Texture and a TextureRegion, as well as init the Sprite (I mean the class that extends Sprite).
Answer:
So can I force parse it?

No, you can't cast like that, for the same reason as you can't cast for example an Object into a String.

Or I have to make 10 GenericPool class if I have 10 child-classes?

I guess so. But I wouldn't solve it like this in the first place.
If you really want to reuse objects, I suggest you just lazily initialize a list of objects, which you can later reuse.
Comment: Thank you for your answer. But I can't initialize that list, because I don't know exactly how many I would need. But there're a lot of child class, so I hope there's a better solution!
Comment: That's why you would do it lazily, i.e., "on-demand". Look up lazy initialization.
Comment: OK, thank you, look like copy GenericPool class is simplier, because I only have to change the class type name. Problem solved!


Why does $\ln(2+\tan\theta) - \frac{1}{2}\ln(1+\tan^2\theta) =\ln (\frac{2 + \tan\theta}{\sec\theta})$?

Question: How is it that
$$\ln(2+\tan\theta) - \frac{1}{2}\ln\left(1+\tan^2\theta\right) = \ln \left(\frac{2 + \tan\theta}{\sec\theta}\right)$$
Comment: A necessary condition to have your homework done by others is to copy it correctly. A sufficient condition is to include honest attempts of solving it yourself. Unfortunately, not a necessary condition neither a sufficient one has been displayed here, so I move to down vote.
Comment: Please indicate your approach.
Comment: Sorry I have modified the question. It should be correct now.
Comment: @uniquesolution interesting comment :)
Comment: Thanks I got it.  My main problem was getting rid of the $-\frac{1}{2}$.  After doing that I was easily able to apply the log rule and solve this question. Thanks
Answer: $$\ln(2+\tan\theta) - \frac{1}{2}\ln\left(1+\tan^2\theta\right) = \ln \left(\frac{2 + \tan\theta}{\sec\theta}\right)$$
$$\ln(2+\tan\theta) - \ln\left(\sec \theta\right ) = \ln \left(\frac{2 + \tan\theta}{\sec\theta}\right)$$
Answer: Hint: $$1+\tan^2\theta=\sec^2\theta$$ and
$$\ln x- \frac{1}{2}\ln y=\ln x-\ln y^{\frac{1}{2}}=\ln\frac{x}{y^\frac{1}{2}}.$$
I think you can finish from here.
Answer: $\begin{align}\ln(1+\tan\theta) - \frac{1}{2}\ln(1+\tan^2\theta) = & \ln \left(\frac{2 + \tan\theta}{\sec\theta}\right)\\=
&\ln\left(\frac{(1+\tan\theta)}{\sqrt{1+\tan^2\theta}}\right)\\=
&\ln\left(\frac{(1+\tan\theta)}{\sqrt{\sec^2\theta}}\right)\\=
&\ln \left(\frac{1 + \tan\theta}{\lvert\sec\theta\rvert}\right)
\end{align}$
Answer: Hint:
Forget $\sec \theta$ (it's just $\dfrac1{\cos\theta}$) and remember $1+\tan^2\theta=\dfrac1{\cos^2\theta}.$