Is it possible to create anti-muons in a particle accelerator?

Question: I love particle and nuclear physics and I'm starting to search some things about it even. So, my doubt is: is it possible to create antimuons (positive charged muons) in a particle accelerator, but without colliding two beams? I mean, only colliding a beam against objects or with the help of machines like Cherenkov detectors or Muon filters.
Answer: Yes.  In fact, the first process you generally learn about in quantum field theory is the annhilation of an electron/positron pair to produce a muon/antimuon pair.
Comment: You don't even have to get that exotic. NuSea (AKA fermilab experiment 866) used Drell-Yan muon/antimuon pairs from (among other cases) a proton beam on a stationary hydrogen target.
Comment: @JoãoTeixeira You can do Jerry's version in fixed target kinematics with a positron beam and ordinary matter.
Comment: @Jerry Schirmer, wouldn't that involve colliding an electron with a positron?
Comment: @dmckee I don't know if you can also help me with this issue: which device/machine or process should I use to measure the levels of muonium formed?
Answer:
is it possible to create antimuons (positive charged muons) in a particle accelerator, but without colliding two beams? I mean, only colliding a beam against objects

Yes, these are the fixed target experiments, various beams interacting with nuclei in the targets.
In this bubble chamber picture the target is the protons in the nucleus of the hydrogen atoms:

This picture comes from an experiment at CERN in which a beam of 8.2 GeV/c K- particles is fired into the 2 metre hydrogen-filled bubble chamber.
The main interaction produces 4 charged particles and a neutral particle that decays a little way downstream into two charged charged particles (with a characteristc `vee' shape).
This event is rich in the number of different particles that can be identified from a `reading' of the tracks: electron, positron, pi+, pi-, K0, , K-, mu +, mu-; for details.
In addition, one can infer the existence of various neutrinos in the decay of the pi+ (muon neutrino) and the mu+ (electron neutrino and antimuon neutrino).

The muons, + and - come from decays.

or with the help of machines like Cherenkov detectors or Muon filters.

There is some confusion here, detectors detect particles, they do not produce them. In the picture above the detector is the camera taking the picture, plus the volume of hydrogen where the particles leave a track. The production happens at the vertices. In particular the muon producing  vertices is where the green tracks begin, the decay of the Kaon and pion.
The site may interest you.


What is meant by "Country of residence" in Australian Visa Application form?

Question: I'm filling in an online application form for an Australian visa, and there is a step "Contact details" which asks for a "Country of residence", specifically "Usual country of residence" (see the screenshot below). There is a <code>?</code> hint and it is not informative—here is the full text of that hint:

From the option list, select your usual country of residence.
In a later step, you will be asked to provide your full residential
  address in this country.

MY QUESTION:
What is really meant by "Country of residence" here? Is it the country of my citizenship or the country I currently reside in? Now I'm not in my country of citizenship. I reside in another country with an extended tourist visa. I have resided in that country for six months now and plan to go to Australia from that country. So what should I state: the country I'm residing in now or the country of my citizenship?
Comment: You answered this yourself: "..or the country I currently reside" the question is about residence. ...reside..., ...residence...
Comment: I think you're overthinking it. They will later ask you for a residential address in that country. Where can you get mail reliably?
Comment: @MarkMayo, sure I did. The full text of that "?" hint I copy/pasted in my question: *From the option list, select your usual country of residence. In a later step, you will be asked to provide your full residential address in this country.*
Comment: The simple fact that there is discussion about the form negates any 'sense' it may make to any proportion of humanity ...
Comment: There are clearly two possibilities, and the opinions (no matter how cogent and clearly expressed) of strangers on the Internet are unimportant compared to that of the Australian government. Contact them and ask.
Comment: @MarkMayo, agree, I've updated the qustion.
Answer: Note the word 'usual'.  If you're on a tourist visa in another country for just 6 months, that's not really where you NORMALLY reside.  You're considered a visitor in that country, not a resident.
In this case it's likely to be your country of citizenship, if that's where you usually live when you're not travelling on this tourist visa.
Comment: @Blackbird57 because if you're like me, I've got a South African and New Zealand citizenship, and live in Australia.  So they have to specify, to make sure.
Comment: If you do not *usually* reside in your country of citizenship, then the answer should be the country in which you usually reside.
Comment: some people may technically no longer be a resident anywhere, for example if you have chosen to become a nomad and travel the world, and have been doing so for many months.  Your last country of residence, your last permanent country before you started your travel, might be the most relevant.  In practice, they are looking for an address for which they can contact you
Comment: That's the thing that I *usually* do not live in my country of citizenship
Comment: That's confusing though, why not just say country of citizenship ? If later pages don't refer to citizenship I suppose usual residence then would mean country of citizenship
Comment: @Green but in the country where you have you tourist visa, you are a still a tourist, not a resident. Residency is usually where you pay taxes, for example, or where you work.
Comment: @Blackbird57 because of agreements like the Schengen Agreement, where citizens from each participating country have leave to legal reside/work indefinitely in any other participating country. Furthermore, there are people who are citizens of no country [stateless] and there are people who are citizens of many countries [multi-nationality], to further complicate you world view.
Comment: I have the legal right to reside in many countries. That doesn't mean I reside there. And citizens of no country reside where they reside. They ask for "residence", so you respond where you reside. Not where you are citizen, but where you have the right to reside, but where you reside.
Answer: Your residence
What address would you give someone who intends to send you critical correspondence at some indefinite point in the future? Where do you have your mail shipped? Where do you receive your bills? What address does your most recently opened bank account have on it? What address do you put on your tax forms? What address is nearest the school you would send your kids to (if you had any)? Etc.
That is your current residence. This is not always the same as your citizenship.
An example
Residence: I live in Japan. My kids go to school there, I have a permanent residential address, have a residency visa, etc.
Visitor: I visit other countries for work for several months at a time. Sometimes I rent an apartment, sometimes I'm staying with people I know (at their residence), but I might leave at any time and am usually either on a work visa or tourist visa.
Citizen: I am an American citizen. I was born in Texas and my passport says so.
Where you live, where you are, and what place claims to own you.
You can be in-between
For a few years I didn't really have a residence. I hopped around a lot and didn't have a single city or even country I could call "home". If someone had, in an official capacity, asked me where I lived I would have still replied "Texas". Even though that wasn't true in the sense that I hadn't been there for a few years, it was more true than claiming some place I had only been staying for a few weeks or months and knew I wouldn't be in much longer (especially on a tourist visa).
It is useful to note that many official bureaucracies (and their documents) are particularly unfriendly to people who don't fit the "born, schooled, worked, died -- all in the same 10 miles" mould. This bureaucratic detail can significantly hinder your efforts to get even the simplest things done in life, despite being a completely made-up problem. For that reason it is usually much less painful to use your place of birth or your family's residence (if you have a family or parents) as a sort of administrative anchor rather than try to explain the details of your situation.
Comment: disagree with the part: "What address would you give someone who intends to send you a letter sometime next year?" as this would imply the OP should list Australia, which is where the OP intends to be
Comment: @EdmundYeung99 The point is *uncertainty*. I'll change it to express that more deliberately, since it apparently wasn't clear that planning to have someone address a letter a year hence to a place one hasn't yet aquired a visa to is the height of wishful thinking.
Comment: ah yep, I misread that first paragraph, but I see your point now
Comment: +1 As an Australian citizen also residing in Japan (on a non-permanent resident visa), for all Australia matters (filling in the incoming Immigration form etc.) I am a resident of Japan regardless of citizenship.
Answer: The question boils down to:

Do you have permanent residency in another country; rather than than
  the one which issued your passport?

For example, I live and work in Kuwait. I am not a Kuwaiti citizen, but a permanent resident.
So for that application, I would put Kuwait as the country of my residency, even though its not the country of my nationality.
Comment: And to extend to the OPs scenario - if you were to visit a third country on a tourist visa, you would still put Kuwait as the country of your residency.
Comment: For the Australian Visa (and Immigration Declarations) there is no requirement to be a permanent resident of any country in order to fill in that answer. I am an Australian citizen, however I reside (without permanent residency) in Japan. I write Japan as the answer to the question, Where is you country of residence? as I live and work in Japan. In Australia the stipulation also exists in tax law. If you have working rights in Australia (Working Holiday, Student and Working Visa's to name a few) you are considered a resident of Australia for tax purposes regardless of time lived in Australia.
Comment: Permanent Residency is not required. I equate the Usual country of residence to being the country in which you are ordinarily resident. https://en.wikipedia.org/wiki/Ordinarily_resident_status
Comment: If you are ordinarily a resident, you have either permanent residency or a citizenship - otherwise, you are just a temporary visitor.
Comment: The last comment is incorrect.  It is possible to reside for a long time or even indefinitely in some countries without having permanent residence or citizenship there.
Answer: The form asks for an address in your country of residence. Figure out which address makes sense. The country that is in is your country of residence. I think that should be the crux of the question.
If you don't have an idea of which address or addresses to use for that part of the form then maybe you need an immigration attorney to interpret the question for you confidentially. Sometimes a situation is completely legal but hard to explain, and that's what those attorneys are for.
Answer: Country of residence means exactly that, where you're living right now. I've come across forms with this phrasing, usually they ask you about citizenship in a separate question later
Also note the little question mark next to the question, that can give you a hint as to how they define country of residence
Comment: It does say 'USUAL' country of residence, so it might not be that clear cut...
Comment: Also countries where you're on a tourist visa don't generally consider you to be living there, you're visiting.
Comment: disagree, not where you are "living", but where you are "residing".  Where you happen to be while filling out the form is irrelevant.  As Mark pointed out, you may be a tourist or otherwise.
Comment: @EdmundYeung99 a tourist doesn't live in a country, they're passing through
Comment: I copy/paste the full hint in my question. It is not informative.
Comment: @Blackbird57 the word "living" can be argued to mean a lot of things, hence why the word "reside" is used
Comment: Even "reside" can be argued. "Residence", however, is slightly clearer. That small difference implies a place where you *permanently* reside, i.e., where you file your taxes. I "reside" in other countries for months on end for work reasons, but I do not call any of them my "place of residence". I think the "usual" term comes into play here in case you, for example, own houses in multiple countries - Which one do you "usually" stay in? Again, this should match whatever you report on your taxes.
Answer: This was a subject of discussion in the EU. The consensus seems to be, for the majority of cases, that this is the place where you pay your taxes (except if you have formally requested residency)
This is not always the case, though: in cases where you wonder whether you should switch to another country's driving license, you should use the one of the country your car is usually parked in.. This has apparently changed in 2013.
I found out this when doing some research in the past, form memory it was on the EU web site, deeply hidden. This does not cover the exotic cases, thought (when someone lives in multiple countries throughout the year and does not have the usual clear cut for taxes (which is 1/2 year + 1 day))
Answer: In this case since you are to be invited for an interview at the closest destination to you, the country of residence is where you live right now.
Comment: Er, pretty sure that's covered by the NEXT question - where they ask the applicant's closest office.  You could be on holiday for the next month in Europe, so the closest office might be in Paris, for example.
Answer: Your country of residence is where you spend over 50% of the time when you are not being a tourist.
Excluding all the time you are travelling on a tourist visa, where will you spend 50% or more of your year?  This may be in the country of your citizenship, but could be where you have a work visa, or permanent resident's visa.
Comment: No such country has to exist though.
For example lets say I was an international consultant, who was in hight demand. My home base might be say the UK, but one year, I might spend 3 month in France, 3 Months in Australia, 3 Months in the USA, and with the remainder spent in between job at my home in (say) the UK. The next year I might go to different countries, or the same. Who knows.
But I don't spend 50% of my time in any country. But the answer the form wants is probably the UK, being the only country I am certain to be at at somepoint on a regular basis.


Benefits of testing at a wireframe prototype stage rather than design stage?

Question: Trying to convince internally that testing at an interactive prototype stage will be more effective at ridding usability issues than at a design stage. What are the benefits of testing early other than the fact it is more cost-effective?
Comment: Perhaps re-form your question so that it's actually a question. A request for ideas is probably better suited for a forum, and is likely to get flagged here. Your question looks interesting though, so perhaps ask: "What are the main benefits of testing early...." etc. Your title was good, but I just think your question should be re-formed.
Answer: Testing at wireframe stage can bring huge rewards and I would encourage it with any project.
The biggest and perhaps most obvious benefit being that it will quickly identify any key issues in your design, together with lesser issues that need only minimal adjustment. If not anything else, you could always think of it as a critical cost saving exercise (That's how I'd pitch it), if you get it right first time - even if it takes that little while longer - then you eradicate the need to spend hundreds of man hours / £'s on having a design built. Tested, then rebuilt and so on.
I also find that testing via wireframes allows for the exploration of multiple experiences, and indeed helps to identify and evolve those that prove to be a good fit. I can understand clients being a little apprehensive about letting a small group of users test an un-built, ghastly looking prototype, but there are people out there that are used to doing just that and will provide you with that oh so important feedback.
Answer: Approaching the best solution for an issue often is an iterative process. So, prototyping and testing at an early stage helps you in this process.
You often can prototype two or three alternative version and do a quick testing with colleagues, your mum or somebody from the street to find out which variant works best - and not which looks best.

Test the usability not the design and perception of what you developed.
  Evaluate your solution quickly without involving a designer - I guess efficiency would be the main argument.

Of course, design influences the perception of a page, a functionaliy etc. But it seldom really changes quality of the pure functionality.
Answer: Interaction is not the only aspect of usability testing. Visual design and motion design lead to discoverability, and findability as well as assisting with information hirerarchy and learnability. As a result the answer is:
YES, but..
Yes in that testing before any visual design happens is extremely beneficial and can represent a large cost savings, however, the visual and motion design can make or break the design in the ways mentioned above, so you need to test when these are in place as well. Banner blindness is a classic example of a way something might work fine in a wireframe but would fail later.
Comment: That's not exactly what the OP asked 2.5 years ago.
Comment: Hmmm... How does this answer "Benefits of testing at a wireframe prototype stage rather than design stage?". Your answer discuss the importance of testing i design phase which is an answer, but not to this question. Could you edit your answer and try to add statements closer to the question? Thank you!


Azure storage metrics data

Question: I am trying to implement azure storage metrics code in my role but i am checking if there is easy way to get azure storage metric data about my files usage. my code is stable and i do not want to change code again.
Answer: Actually if you already have Windows Azure role running, then you don't need to make any changes to your code and you still can get Windows Azure Blob storage Metrics data.
I have written a blog about it last time as Collecting Windows Azure Storage REST API level metrics data without a single line of programming, just by using tools
Please try above and see if this works for you.
Answer: Storage analytics is disabled by default, so any operations against your storage up til now has not been logged for analysis.
You may choose to enable analytics at any time, for both logging (detailed access information for every single object) and metrics (hourly rollups). Further, you may choose which specific storage service to track (blobs, tables, queues) and which operations to track (read, write, delete). Once analytics are enabled, you may access the resulting analytics data from any app (as long as you have the storage account name + key).
Persistent Systems just published a blog post on enabling storage analytics for Java apps. The same principles may be applied to a .net app (and the sdk's are very similar).
Additionally, Full Scale 180 published a sample app encapsulating storage analytics (based on REST API, as it was written before SDK v1.6 came out).

Azure storage metrics data


Spark View Engine very slow code editing in Visual Studio 2008

Question: How to increase editor responsiveness when typing code for Spark View Engine?
Spark plugin for VS08 takes lot of CPU resources as it checks the syntax of all Spark files on each key stroke: does anyone have an idea how to optimize this?
Answer: Unfortunately I haven't found a workaround; I also noticed that it tends to eat memory and slow down VS after a while. So I open .spark files as HTML code - this gives good syntax highlighting and tags completion for HTML; I can live without Spark intellisense.


Is XFCE dead or still under development?

Question: The XFCE website seems to be alive, and distros like Xubuntu still use it. But XFCE hasn't been updated since 2015. Is the project dead?
Comment: Do not mix up the news update on the website with actual changes in the projects. Check https://www.xfce.org/projects and you'll see many updates from this November.
Comment: I'm voting to close this question as off-topic because the answer to this Question could change over time and contains a matter of opinion ("should we stop using it?")
Comment: The roadmap https://github.com/lxqt/lxqt/wiki/Roadmap for LXQT hasn't updated since June '16, at the same time the current LXQT version 0.90 was released. So, LXQT isn't that much fresher than XFCE.
Answer: There hasn't been a full release of Xfce for a while, but the project is still alive. The git repositories are very active, and a number of projects inside Xfce have had releases since Xfce 4.12: Thunar, the file manager, in October 2018, Ristretto, the picture viewer, in August 2018, etc.
Comment: Basically, the current development push is trying to get everything to work properly with GTK+ 3.  I expect there'll be a full release (as opposed to the current piecemeal releases) once that happens.


How can I reclaim a barony from a Holy Order?

Question: I just need to take control of one barony to restore the Roman Empire, but that barony is hands of a Holy Order, I've tried excommunicating them, and also tried to create a claim, but my counselor never creates a claim in the barony itself, any ideas?
Comment: I think you should have a de jure claim on it. Not sure if Holy Order mechanics screw that up.
Answer: If you don't have a claim on the title, and you can't usurp it, you might be able to invite a claimant to your court.
To do that, click on the coat of arms for that title to go to the title screen. One of the buttons on will say "Claimants", and this will reveal a new window with a list of everybody who has a claim on that title. Anybody in that list who has a green thumbs up next to their portrait, is willing to join your court if you click on them.

If there are no one willing, you may try to persuade one of those with a red thumbs down to win them over – however, there is no guarantee for success. Figure out why they won't join you.
Either way, if you are successful, the new claimant will join your court in approximately fourteeen days. You will then be able to press his/her claim.
If the title is lower than your own (as it is in your case), the claimant will become your vassal after the war. If the title is equal to yours or higher, the claimant will become independent.
Answer: ... Except there are no claimants to Holy Order baronies, as they appear overnight from the event and have Open Elective succession...
However, as Affine previously said, you CAN press de jure county claims... but for Holy Orders, ONLY if you yourself own the county.

Hope this helps anyone who had the same problem I did.
Comment: Yes actually this happened to me twice, the second time it didn't had any claimants, if you expel the order all of its dominions go back to you, and voilà!


Can I develop bw film with a c41 developer?

Question: I have a c41 kit with all the needed chemicals to develop color negative film. Can I use the developer from this kit for black and white film?
I am aware that I will need a stop bath and a fixer, but can i use the developer i already own?
Comment: Color developer is more expensive than BW developer.  Since you already need to obtain more than half the chemicals to complete BW development properly, what's the point of doing half C41, half BW?  Why not just get the right chemicals?
Answer: The answer is YES:
The C-41 color developer is a typical (non-staining) black & white developer. Its job is to differentiate between exposed and non-exposed silver salts present on the film. The developer then goes to work on the exposed silver salts. They are reduced to their two component parts which are silver and an halogen (Iodine – chlorine – bromine). The halogen portion is dissolved by the waters of the developers. The silver portion is precipitated as an opaque tuft of metallic silver. The result is a negative image of the original vista.
The C-41 color developer also contains a color developer. Its job is to couple with incomplete dyes imbedded in the color film during manufacture. This action completes the dyes. Should this happen, the dyes blossom and become cyan, magenta or yellow dye globules, based on which emulsion layer they are in. Since a black & white film is void of these incomplete dyes, no such action will occur. The result will be a black & white negative.
In the C-41 process, the film emerges from the developer with three dye images, and three silver images. The silver is opaque and thus veils the dyes. The C-41 process contains silver bleach. Its job is to convert the silver image back to a silver salt.
Next the C-41 process fixes the film using a typical fix bath. IF the C-41 solutions are of an abridged type, the bleach and the fix step are combined making a bleach-fix or blix. The color film emerges, whereas the silver images are removed, and the resulting color images are a color negative.
Bottom line: You can use the C-41 developer to process black & white film. You would do better if you used a solution that is optimized to develop black & white film. You should follow the developing step by a stop-bath or water rinse.  Next you fix the film using a typical black & white fix bath. The finished film should then be washed in running water to purge it of the processing chemicals.
If the black & white film is treated with the bleach-fix blix, all your images will be destroyed.
Answer: You probably could, with some experimentation.  However, C41 chemicals are a lot fussier and a lot more expensive than black-and-white chemistry.
For only a few dollars (or your equivalent currency), you could buy proper chemicals for black-and-white work, and have well-tested, useful information as to the proper parameters (dilution, development time and temperature) that you should use.
You actually don't need stop bath (it is recommended but not required).  A 60-second running-water rinse between developer and fixer is also acceptable.  You can also dilute ordinary table vinegar to serve as a stop bath, since it contains acetic acid, the most commonly used chemical in stop bath.
Answer: Just developed a roll of Lomography Orca BW in 110 that I thought was Tiger color negative. Developed it in standard C41 chems and blix at 102F, pulled the film out after the processing was done, and VOILA! There are images. I thought, "how come the negs are not brown, but instead, grey?" Then realized that the negs say ORCA BW. I was thoroughly surprised that there were images. Now I can say, that although I will develop BW with proper processing, I know that it can be done. I'll post images here as soon as I scan them.


Metallic Gradient Foil vector effect?

Question: I'm attempting to create a gradient foil effect, however I can't seem to find any direction as to how to make this as a vector. I've seen other examples like the one below, but the ones I've made look way to harsh and not modern at all. Are there any techniques I can use to replicate this effect?
Comment: Gradient filled rectangles ? Look at Illustrators Metal Gradients in the Swatch Libraries and see how they were constructed ? (Swatch Libraries> Gradients> Metals)
Answer: They appear to be basic gradient fills. Nothing overly complex.

To "color tint" the rectangles, one method would be to add an additional fill via the Appearance Panel and then lower it's opacity or change the blend mode, or both...

Metallic Gradient Foil vector effect?


How to convert Text file to ByteArray and send it via API using NIFI

Question: I have a text file. I have to convert it to byteArray and send it through REST API. How to achieve this?
I tried many ways to convert the file to byteArray, last one is ExecuteScript with below code:
import base64
import codecs

with codecs.open('/path/to/input/file.txt', 'r', encoding='utf-8') as file:
file_content = file.read()
file_bytes = file_content.encode('utf-8')
encoded_bytes = base64.b64encode(file_bytes)
encoded_string = encoded_bytes.decode('utf-8')

flowFile = session.putAttribute(flowFile, 'fileContent', encoded_string)
session.transfer(flowFile, REL_SUCCESS)

but still get error:

utf-8' codec can't decode byte 0xff in position 0: unexpected code byte in


Is design now a subset of refactoring?

Question: Looking at the cool new principles of software development:

Agile
You Ain't Gonna Need It
Less As A Competitive Advantage
Behaviour-Driven Development
The Evils Of Premature Optimization

The New Way seems to be to dive in and write what you need to achieve the first iteration of scope objectives, and refactor as necessary to have elegant solutions. Your codebase grows incrementally, and never has a big planning/hierarchical design stage. That, to me, suggests that software design (worthy though it is) has been subsumed into refactoring, because that's where the elegant code comes from, not the incremental additions to functionality.
Am I wrong?
Comment: Did you mean "You Ain't Gonna Need It" to link somewhere else than "Agile Unified Process"?
Answer: Well the trouble with refactoring is that you need to know good design before you jump head first in. BDD/TDD are supposed to make the design emerge but without other factors, such as Domain knowledge and technical competence you will end up in trouble.
Answer: I'd say that doing it the way you describe is a recipe for disaster, I would still recommend to do the overall design up front. Of course during the project you will need to change the design, it is never set in stone, flexibility is a must! (That's where the refactoring has to come in). I would also recommend to do the more detailed design for a module just before you start coding it.
But a solid general design is worth its weight in gold: It gives all developers a common base from which to start, a common idea or perhaps vision, of the goal.
Without that everybody will do as he/she thinks best, with the result that everybody does things in a different way. And suddenly you have to refactor a lot, just to align everybody to what has emerged as the apps architecture. The resulting code is ... not very elegant.
Answer: Wrong?  Partially.
"Your codebase grows incrementally, and never has a big planning/hierarchical design stage."
Correct.
"That, to me, suggests that software design (worthy though it is) has been subsumed into refactoring..."
Not quite correct.
There's a huge gulf between Big Design Up Front (BDUF) and a more Agile design approach.
BDUF dictates that all design is completed before any coding.  This is still popular (just read an RFP yesterday which absolutely required all design be reviewed by the customer before any coding could begin.  Sigh.)
Agile suggests that perhaps all design isn't a helpful goal.  You need to do enough design that TDD will work.  You can't, for example, start TDD until you have a working infrastructure that allows someone to write tests and incrementally evolve a solution knowing that there won't be a weird production deployment problem to solve.
Design is still king.  Agile Design is better than monolithic design.
A consequence of Agile Design is YAGNI, DRY and Less-is-More.  These don't replace design, they're a consequence of how you prioritize and do design.
BDD and TDD are ways to structure your time so you have focus on what people need, what they do and what really matters.  TDD, in particular, focuses on testable behaviors of the software.  Not zero-value nuance, but actual behavior.
Premature optimization is interesting, but unrelated.  Even Agile teams can run down a low-value rat-hole pursuing a nuance or optimization that doesn't add any value.  Premature optimization is a habit of overthinking (== "hand wringing") a technology choice without facts about actual performance.
Agile is supposed to help you focus on the big picture: What actual people will actually do with the actual software and avoid technology rat-holes.
It doesn't replace engineering.  It refocuses it.
Answer: Depends what you're designing.  If it's a complex algorithm thats going to be the next video compression standard, you can iteratate and refactor 'till the cows come home and it isn't going to get any faster.  The perfomance comes from design.
Similarly, if you are writing a very large application, that will grow through regular releases, you need to put in place an architecture that will support growth, and this will be by design.  You can go down a long road by jumping head first into code just to discover a dead end.

Am I wrong?

IMHO, pretty much.
Edit: The reason I make many design decisions early in the process rather than mid flow is this can often be the cheapest time to do so.  For example, if we start writing an application using platform dependent technology early on, it may be a very expensive decision to reverse.  If we take time to consider the platforms we want to support before starting to code, it is much cheaper.  We can't and won't get everything right first time, but this does not relieve us of the duty of exploring all important design choices up front.  Every tried refactoring a MS MDI program to MVC?  I have, and wouldn't recommend it ;)
Comment: Isn't design a part of refactoring? Just larger scale?
Comment: You'd have to define what you mean by refactoring.  My understanding of refactoring is iteratively improving code quality without affecting its functionality.  Iteratively improving design to improve functionality before starting to code is something very different, often much cheaper and quicker.
Answer: There's nothing in the agile manifesto, which says that you're not allowed to think before you act. Of course you can be agile and still design up front. Architecture is best designed, so before you start coding/refactoring, you should have some ideas as to how your application should be constructed.
The point is you don't have to complete each and every step before moving on. Do as much design as you need to get started.
When you have code, you can refactor as needed, but changing the fundamental architecture through refactoring becomes hard if you start from a simple dummy application every time.
Answer: Reminds me of the following quote:

The goal is clean code that works. [...] First we'll solve the "that works" part of the problem. Then we'll solve the "clean code" part. This is the opposite of architecture-driven development, where you solve "clean code" first, then scramble around trying to integrate into the design the things you learn as you solve the "that works" problem. (Kent Beck, "TDD by Example")
Answer: The nature of design is changing, I'd say the new way is to think before coding, but just about what will be implemented in the next iteration. See "Is design dead".
Design for today, code for tomorrow.
Answer: New?  No.  I was reading about agile ten years ago.  And agile is just the crystalization of ideas that have been around for longer than that.  It's hardly new, it just hasn't diffused everywhere yet.
As for your view of design, I think there's still a place for an overarching idea and some up front design.  It's the waterfall notion that you can't make a move before requirements and design are 100% complete that has been discredited everywhere but in the large firms that still cling to it.
Answer: Let's see if we can get a definition. I'm going to suggest that there may be a book we could reference. How about the one by Martin Fowler?
"Refactoring: Improving the Design of Existing Code"
Now let's take as an example the TDD mantra:
until done do

Red (we wrote a test and it failed because there was nothing that could pass it)
Green (we designed and wrote some code and the test now succeeds)
Refactor (we need to integrate the design we did with everything else)

end
I know the Agile books tend to just say "write enough code to pass the test", but there's design implicit in that statement. By necessity. Choosing a variable name is a design decision. Not a big one, but a decision nonetheless. naming a function or method is a slightly bigger one, and so on up the food chain.
There's nothing in Agile that can ensure you always make good design decisions. Nothing in waterfall or any other process either. Agile does assert that you can't figure it all out upfront and tries - with some success in my experience - to give you a set of tools to help you make better decisions throughout the whole exercise.

Is design now a subset of refactoring?


How to make an enchantment with more than standard allowed max level?

Question: I've seen a lot of lets plays and vanilla servers where players used swords with, for example, Sharpness X (but max allowed level is V). Or, also, I saw modded severs where you can donate and buy Nano Sabre from Industrial Craft with Sharpness XVII. How can I get such enchantment with in game methods? Is there some mod to do that? I tried Enchantmets Plus and More Enchantments mods but there is no such ability. I want be able to combine two Sharpness V (or any other enchantment, not only sharpness) books in anvil and get Sharpness VI book instead of Sharpness V again.
Comment: Possible duplicate of [Combine sharpness 10 book with a sword in a anvil](https://gaming.stackexchange.com/questions/375996/combine-sharpness-10-book-with-a-sword-in-a-anvil)
Comment: You've probably meant "Nano Sabre" :-) "Sable" means "соболь".
Comment: Closing an older question as a duplicate of a newer question because the newer question's answers actually contain commands that let you use anvils to do this, and this question only has "this isn't possible" and "use a mod".
Comment: @OrcJMR, yes, of course, sabre too =)
Answer: You can use commands to create items with any enchantments:
/give @p iron_sword 1 0 {ench:[{id:16,lvl:10}]}

There is no other way in vanilla. Someone else might know a mod that does that, though.
Comment: @DmytroTsiniavskyi It doesn't need to be "cheaty" -- you can go to your Anvil Of Supremeness (aka Pit o' Lava), toss in your pair of `Sharpness V` books, and then `/give` yourself a `Sharpness VI` book. I do this all the time for recipes and such that I feel should exist, but don't -- and the end result is no different than a mod.
Comment: Thanks, I thought about that, but I need something not such obviously cheaty and without using command blocks... Mod, I guess.
Comment: Ok, lets hope someone else answers what you need. Nevertheless, I'll leave my answer for reference, it might be useful for someone.
Comment: how do i enchant MULTIPLE enchants more than lvl 5?
Answer: The mod you are looking for is called  SuperEnchants.
SuperEnchants mod allows you to enchant tools that have high levels. Note that you will need 30 levels and a enchanting table with maxed out levels. The higher the level you use to enchant, the luckier you will get. Enchanting something next to lvl 10 will lead to NEAR impossible..
Enchantments that their limits have been increased or changed:
Sharpness Levels up to 10 [X]
Fire Aspect Levels up to 10 [X]
Looting Levels up to 5 [V]
Knockback Levels up to 5 [V]

Efficiency Levels up to 10 [X]
Unbreaking Levels up to 10 [X]
Fortune Levels up to 5 [V]

Protection Levels up to 10 [X]
Projectile Protection Levels up to 10 [X]
Blast Protection Levels up to 10 [X]
Feather Falling Levels up to 10 [X]
Thorns Levels up to 5 [V]

Power Levels up to 10 [X]
Punch Levels up to 5 [V]

Answer: If you are looking for a no cheating aspect, then the mod Orespawn adds many new dimensions with various boss battles and new ores that can get you the type of enchants you are talking about. For example, once you beat the King you get King armour. This gives you, among others, Protection 10. If you want to not only get these enchantments but also want to add a certain amount of adventure and challenge to getting this rather end-game items then I would defiantly recommend it. If you want to read more, you can find the Orespawn website has tons of Information that you may find useful.
Answer: You can install TMI (TooManyItems). You can enchant whatever you want like silk touch X in a sword. I've install it on my Minecraft 1.7.2 and you can get spawners that you couldn't get like random fireworks spawner and charged creeper, xp orb and saddled pig. You can experiment with potions, favorite items (enchanted or not), Enchanted books, set time to sunrise, noon, sunset, and midnight. You can set creative, survival, and adventure immediately, rain on-off and delete mode if you like to delete in one click.


How can I represent a tile-based map and related properties on disk?

Question: I'm trying to load a tile-based map in my game. I've been watching SDL tutorials for a while now but they never covered how to represent the map in a file? How can I represent a tile map on-disk in a way that also lets me store information about collision and other properties?
Comment: Is there a specific way you're representing tile maps on the disk that you're having trouble with? Or are you unsure of how to represent tile maps on the disk?
Comment: @JoshPetrie I am unsure of how to represent tile maps on the disk and how to detect collision on the tile maps.
Comment: It's probably worth asking the collision question separately. Since we don't permit questions asking for tutorials I changed your question to ask specifically about representing the map in a way that would let you still store collision info, which you could ask about in a new post.
Comment: I would suggest you look into the specifications of the [Tiled TMX map format](http://doc.mapeditor.org/). Maybe you'll get inspired :)
Answer: There are several well-used methods.
One of the simplest, to implement and to work with, is to use some sort of text grid, used in a lot of roguelikes. Here's an example from puzzlescript:
=======
LEGEND
=======

. = Background
# = Wall
P = Player
* = Crate
@ = Crate and Target
O = Target

=======
LEVELS
=======

#########
#.......#
#.....@.#
#.P.*.O.#
#.......#
#.......#
#########

Each tile is represented as a single character in a plain text file. One advantage is that you can edit levels using a text editor. You can also use lots of different characters to represent different tile types, so there's some amount of flexibility.
Sometimes you have lots of tile types/properties and not enough ASCII characters to represent them, so another approach is to use tile IDs. That is, each tile is represented by an ID number, and the entire map is a 2D array of these numbers, followed by tile definitions. So you might have:
1,1,1,2,256,190,...
3,5,7,3,0,0,0,...

1 = Wall
2 = Floor
3 = Grass
256 = Excalibur
...

This is how Tiled does it; the actual file could be XML, JSON, or anything that can represent 2D arrays.
Sometimes you could have gigantic maps; imagine a tile-based space game where most of the space is empty but the map is massive. Representing it as a 2D array would be impractical - a 1 million squared map would take one trillion elements to represent. Here you may want to go with something like a sparse matrix storage, i.e. you only store where interesting tiles are, and not the whole map. There are also certain procedural generation techniques you can use to cut down on storage requirements.
Comment: Multiple layers
Comment: How would you handle stacked elements? E.g. a tree over a grass tile.
Comment: Puzzlescript does it by assigning each object to a layer. The example shows `@=create and target`. Very powerful technique.
Answer: Loading the tile map has many different possibilities. Probably the most common is an XML file, but I personally dislike XML files because they are way bigger than they need to be. What I do 95% of the time for this, is have a text file that does a diagram of it. Here is an excerpt from a tile map in one of my own games.
~begin
~enemy_rate 50
#
#
#
#       ###
####
#
#
#
#
#
########
#
#
#
#       ^
################
~end

They are extremely easy to read with the human eye, extremely fast to load because they are just .txt files, and quite versatile. As you can see, ~begin, means that it is the beginning of a tile map, ~enemy_rate is a parameter I use to specify things about that map, and ~end means that it is the end. I can have as many of those I want in a file, since they have beginnings and endings in the file.
However, since this is ASCII, you are limited to a total of ~93 different possible drawn ASCII characters. For most cases, 93 different tiles is more than enough, and you could make modifiers, but something to consider.
As for checking for collisions, I have a really basic version in C++ that does this exact job, but it's not perfect. This is what it looks like:
bool GameRoom::checkCollision(double x, double y, GameObject * object)
{
    return (getCollGrid((x + object->hitBoxX1) / wallWidth, (y + object->hitBoxY1) / wallHeight) != 0 ||
        getCollGrid((x + object->hitBoxX2) / wallWidth, (y + object->hitBoxY1) / wallHeight) != 0 ||
        getCollGrid((x + object->hitBoxX1) / wallWidth, (y + object->hitBoxY2) / wallHeight) != 0 ||
        getCollGrid((x + object->hitBoxX2) / wallWidth, (y + object->hitBoxY2) / wallHeight) != 0);
}

In this example getCollGrid(x, y) returns the value at (x, y) position; and checks that it isn't 0. I use that in an example game, so it does work.
Answer: What you are trying to do is storing a grid of numbers into an array, there is unlikely to be one, best solution. We've used Paolo's example for some projects.
For others we've used something as simple as a bitmap where eacht pixel's color meant a different tile-type. The tile-type determined the properties of the tile. This made the map easy to observe and edit with basic image editors. You could decide to store aditional information in different color channels or in an accompanying file.
Answer: TL;DR MsgPack
Long one
I developed a game and asset management library in ActionScript using msgpack. Msgpack -as its slogan says- is like json but... smaller. msgpack is available on a lot of languages, like C and C++. This is the repository.
There is a counterpart here: although the people recommending me this format was the Python group, I never heard about it before, so I don't know how maintained is right now, but it never failed me.
Another alternatives with their caveats:

XML: Usually good and human readable, but pretty heavy for your porpose.
JSON: Better than XML, readable almost like XML, but still heavy.
Plain array or custom format: The best it can be depending on how good are you coding the serializer and deserializer for it.

I think you will have several layers here (tiled map games have several layers for floor, decals, objects to pick, objects to collide against, ceilings, extra effects like clouds... you choose). My suggestion is to think the format carefully, and pack the objects using msgpack as a bidimensional array [x,y] or small arrays [layer]. This means, somewhere you will have something like this:
uint width = 100;
uint height = 100;
uint FLOOR = 0;
uint DECALS = 1;
uint PICKABLE = 2;
uint COLLIDERS = 3; //players and other colliding objects would be here
uint CEILING = 4;
uint EXTRA = 5;
uint[,,] map = new uint[width, height, 6];

map[0,0,3] = (numerical id for your player);

//YOUR NEXT TASK IS TO SERIALIZE AND SAVE THIS MAP VARIABLE INTO A FILE.


Student Visa inquiry - Canada

Question: My wife is a Bangaladeshi who has a Bangaladesh passport whereas I am from Sri Lanka and I have a Sri Lankan passport .We are newly married and we reside in Colombo. My wife is considering applying for a student visa in Canada and I will join her as a dependent. Will there be any issues in applying since we have two different nationalities?
Answer: Having different nationalities are not a problem in itself, as long as you are legally married according to the local law and the relationship is not excluded by Canadian immigration law (spouses/partners under 18 or virtual marriages) and she is legally residing in Sri Lanka.
Both of you will need to follow the rules for applicants from Sri Lanka, and some documents may need to be authenticated or notarized depending on the instructions from the visa office.
Other considerations apply whether you have different nationalities or not, e.g. financial ability to support both of you in Canada, genuineness of the marriage. Newly married transnational couples may have a harder time to prove a genuine marriage, but this will not usually be a problem unless you just married a month ago without having met physically with her before.

Student Visa inquiry - Canada


Find files with group permissions more restrictive than owner permissions

Question: This is an actual work-related problem.  Users could previously "su - userx" and was able to execute a script with user:owner permissions as userx:groupz 760 or 540, or modify a file that's userx:groupz 740 or 640.  Now, that user may no longer su to userx and must perform tasks as a member of groupz.  The group permissions need to be changed, but the problem files must be found first.  They can be found when they fail, or hopefully you could help me find them proactively.  Any file or directory whose owner:group is userx:groupz and whose group permissions are more restrictive than the owner permissions might be a problem and must be looked at in the context of "business logic".  Is there a way to find all such files and directories?  An answer to this could uncover many potential problems that would otherwise only surface when an operation that used to work now fails.
Answer: If you have GNU find available, you can use something like this:
find /somedir -user userx -group groupz \( -perm /u+w,g-w -o -perm /u+r,g-r -o -perm /u+x,g- \) -ls

Comment: jordanm,  that looks great.  I see the +- patterns.  Based on that, did you accidentally leave of the x in -perm /u+x,g- expression (i.e. u+x,g-x)?
Comment: That turned out to not be what I was looking for, but it led me in the write direction to find the solution which is as follows:
Comment: ... as follows (showing only part of line): \( -perm -u=r -a ! -perm -g=r \) -o \( -perm -u=w -a ! -perm -g=w \) -o \( -perm -u=x -a ! -perm -g=x \)
Answer: Look for files that belong to the desired user and group, and such that, for one of the three file access rights, the user has this right but not the group.
find / -user userx -group groupz \( -perm -u+r ! -perm -g+r -o \
                                    -perm -g+w ! -perm -g+w -o \
                                    -perm -g+x ! -perm -g+x \) -print

Note that this can return any file type, including symbolic links for which permissions and ownership don't matter on many unix variants. To exclude symbolic links, add ! -type l.
If you want to act on the files, use -exec.
If all you want to do is align group permissions on user permissions, you can run chmod g=u liberally.
find / -user userx -group groupz ! -type l -exec chmod g=u {} +

Comment: Thanks for the ! -type l and -exec suggestions.  The 1st one solves a separate problem I was having yesterday!  I use the -exec extensively but mostly with grep to search for files containing something.
Comment: Does ! -follow work the same as ! -type l arguments?
Comment: @TonyV No, `-follow` is global. (More precisely, it applies to any test that comes after it on the command line) It doesn't mean "follow this symbolic link", it means "if you encounter a symbolic link, use its target". It isn't a boolean test, so `! -follow` doesn't make sense.
Answer: Here is the final solution that I tested and it worked.  In order to avoid searching on mounted remote file systems, I needed -mount, and to avoid following symbolic links I needed ! -follow.  I wanted the output to show the permissions so I could easily verify they satisfied my criteria so I used -ls.  A surprise was that "order of the arguments" was very important.  Until I found an order that worked, the command would return some results that were incorrect.
find  -user userx -group groupz -mount \
(
    ( -perm -u=r  -a  ! -perm -g=r ) -o  \
    ( -perm -u=w  -a  ! -perm -g=w ) -o  \
    ( -perm -u=x  -a  ! -perm -g=x )     \
) -ls  ! -follow
Comment: The posted text wasn't exactly what I typed.  Every left paren, (, and every right paren, ), must be preficed with a backslash, \.
Comment: @Gilles - Hmmm.  Thinking back to my toy problem test setup I only used -follow and also left -follow off.  That makes sense.  To not follow the link, just leave it off instead of negating it.  Maybe the negate symbol made it do the same thing but regardless I think you'd suggest I leave off the "! -follow" and it would work.  I agree.  I used the above to solve my problem, but I'll try it again "in 2016" with my toy setup.  Thanks!


Need help with wiring a combination two way switch

Question: I'm trying to swap out an existing two way combo switch with a new. When I pulled it out, the right side terminals had three wires. Two black and a red. On the left side there was one black. My new outlet only has space for two wires on the right and left. How do I wire properly? Thanks, new here
Comment: Where are you on this planet, for that matter?
Comment: Three "hot" wires and 1 "load" is incorrect for that switch. The source data is wrong or misinterpreted.  Your question about red wires may explain all this: you are expecting hot wires to be color-coded *by function*.  Doesn't work that way.  Hots are any color other than white/gray (neutral) or green/bare (ground).  If you want them color coded,  you can retape them colors after you identify them; I do exactly that.
Comment: Photos added in original post. The combo switch goes to a pantry and the garage light. When I wired the new outlet without the red, the garage light didn't work, so clearly goes to garage. and now that I notice it, the garage light also has switch out by the side door in garage. So perhaps that's my problem, I need a three way combo switch since that light is controlled from two switches.
Comment: Can you post photos of the situation with the old switch, as well as the make and model of the new switch? Also, where are you on this planet?
Comment: Yes I'll get a photo when I get a chance. But it was in the order, top down, black, black, red.
Comment: Screw positions don't mean anything at all on switches. What matters is the terminal function, and every model puts the terminals in different places.
Comment: Save the box because the diagram is usually printed inside.
Comment: Also it's a Leviton 15A 120 combo 2 switch, model no 5224.
Comment: There is a diagram as Normal but they only show two wires on each side. So why three "hot" wires and only one load?
Comment: Your may have an extra hot wire that actually goes to another switch or receptacle or fixture someplace else. That is especially likely if it has a matching white in a bundle of white neutrals. **Pictures!**
Comment: Just a general thought, can you connect a red wire with a black since the red is considered hot?
Comment: @ThreePhaseEel In the US at least, I would guess, since there's a wire nut in the box.
Comment: @TylerH -- yeah, the OP's wiring is pretty archetypically North American (some of the verbiage in their original post had me tripped up for a bit)
Answer: You need to return the switch you got and get a single-pole/3-way combination switch instead of a single-pole/single-pole
Your existing combination switch has a normal single pole switch on the top and a 3-way (two location) switch on the bottom, while it sounds like your new switch consists of two single pole switches, which won't help you with your garage light very much.  So, as you are suspecting, you'll need to take it back and get the correct thing; fortunately, it shouldn't be that much harder to find.
As to how this was wired
The good news is that we can identify the functions of the old wires from here.  Clearly, since the black wire on the left is shared between both halves of the old switch, it must be the always-hot feed in.  From the terminal screws on the right,  the top one is connected to the black switched-hot for the light controlled by the top (single-pole) switch, while the bottom two screws connect to the black and red wires that serve as the travellers to the garage light.
You'll need to remember what these wires do, though, since the positions of the screws on the new switch isn't going to help you any, only the fact that the common screws on said replacement will be a different color.  Also note that NEC 404.9(B) permits snap switches to be grounded by their screws, so don't worry about running a grounding pigtail to your switch.
Comment: Thank you very much, that's helpful. Once I realized there was another switch in the garage today I figured it was a three way (recently bought the house so still discovering).
Comment: @Diyhomenoah -- we thank people around here by upvoting and/or accepting their answers :)
Comment: No clue how to do that, would be happy to. Just joined
Comment: @Diyhomenoah -- there is a score, up/down arrows, and a grey checkmark on the left side of questions & answers here (the checkmark accepts answers, the up/down arrows do what you'd expect to the score)


Authentication pattern .Net

Question: I am planning to create a component that will be able to check user's credentials (username and password) and, if they are valid, return associated profiles.
I don't want to use the providers that already exist in the .Net framework (I am trying to exercise my development skills ).
Is there any pattern I can use? Or standards?
Comment: Generally speaking, using the provided components is advised because user authentication requires secure handling of credentials, which is wrought with hazard!

To give you a better answer, give us a bit more detail: are you planning on storing creds yourself, or are you authenticating against AD?
Answer: The providers that .Net supply are all derrived from System.Web.Security.MembershipProvider.
The best pattern you could follow is to write your own class that derives from Membership provider. That way you can write your own Authentication mechanism without having to worry about the security plumbing involved with checking authentication for every request.
Answer: The membership providers are really nice, and you can definitely exercise your dev skills even if you use them.  But you'd be developing something other than a user auth/profile service!.
If you truly want to roll it yourself, you need a store for the username and password hash.  When users register, have them type in the password and then hash it.  Store the username and password hash in whatever store you choose.  Then, when a user logs in, you hash the pw they provide and check it against the stored hash.
For the simplest cases you could just use an XML file with a list of elements, one element per user, and you can use XmlSerialization to slurp it in and save it.
<code><UserDB>
  <user>
    <name>Obsidian</name>
    <pwhash>8731876r4hndmhduihd</pwhash>
    <dateadded>2009-03-25-18:34:44</dateadded>
 </user>
</UserDB>
</code>
But you could also use a database, or AD/AM, some other store.

Authentication pattern .Net


Assign operator in Java

Question: I have 2 ArrayLists in Java:
mProductList = new ArrayList<ProductSample>();
mProductList2 = new ArrayList<ProductSample>();

mProductList = productSampleList;

mProductList2 = productSampleList;

mProductList2 .remove(3);

The productSampleList has size 5.
Why after this segment code is executed. mProductList has size 4?
Does we have any way to avoid this? I want the mProductList have size 5 as the same as  productSampleList.
        Thanks!
Answer: Try this:
mProductList2 = new ArrayList<ProductSample>(productSampleList);

As it is currently, productSampleList, mProductList and mProductList2 all point to the same object, so changes to one will be reflected on the others. My solution was to simply create a copy of the list that can be modified independently of the original, but remember: productSampleList and mProductList are still pointing to the same object.
Comment: @VanDang no you didn't, in the line `mProductList2 = productSampleList;` you reassigned `mProductList2` to a different list. You have to grasp the concept of object references in Java.
Comment: I got it! Thank you very much for your help! I'm new in Java, so this mistake is unavoidable. Thanks again.
Answer: All 3 productSampleList, mProductList and mProductList2 are references to the same ArrayList object, therefore calling the .remove() method on any one of them removes the element from the underlying single ArrayList object.
If you want to maintain separate ArrayList reference for each of your variables, you would need to create 3 different ArrayLists
Answer: When you are using list, (or arraylist) the size() method returns the number of elements in the list. lists are not like arrays, where the size is fixed. If you want a fixed size, use arrays.
Have a look at http://docs.oracle.com/javase/7/docs/api/java/util/List.html to learn more about lists.
Here is a good distinction between arrays and arraylists.
Answer: You can try this:-
    public class ArrayListTest {

    public static void main(String str[]){
        ArrayList productSampleList=new ArrayList();
        ArrayList mProductList=null;
        ArrayList mProductList2=null;

        productSampleList.add("Hi");
        productSampleList.add("Hi");
        productSampleList.add("Hi");
        productSampleList.add("Hi");
        productSampleList.add("Hi");

        System.out.println("Main productSampleList size..."+productSampleList.size());
        mProductList=new ArrayList(productSampleList);
        mProductList2=new ArrayList(productSampleList);
        System.out.println("mProductList size..."+mProductList.size());
        System.out.println("mProductList2 size..."+mProductList2.size());
        mProductList2.remove(1);
        System.out.println("mProductList size..."+mProductList.size());
        System.out.println("mProductList2 size..."+mProductList2.size());

    }
}

Output:-
Main productSampleList size...5

mProductList size...5

mProductList2 size...5

mProductList size...5

mProductList2 size...4

Assign operator in Java


Streaming music from raspotify to bluetooth audio speaker

Question: I'm trying to create a raspberry pi which streams spotify music to a bluetooth speaker. I have a raspberry pi zero w with the latest version of raspbian stretch lite. I have my bluetooth connection and my raspotify set up. The only thing i can't figure out is how to redirect the output of raspotify to the bluetooth speaker. Is there a way to tell the pi to redirect all the audio to a bluetooth speaker?
Answer: You will want to pair your bluetooth speaker to the raspberry pi. I dont know if this is possible for all bluetooth speakers; from a quick google it does look possible.
Next you will want to find what hardware device that the bluetooth speaker is set to, so that we can tell raspotify to use this device.
Do this by running
aplay -l

and you'll get something that looks like
**** List of PLAYBACK Hardware Devices ****
card 0: ALSA [bcm2835 ALSA], device 0: bcm2835 ALSA [bcm2835 ALSA]
  Subdevices: 7/8
  Subdevice #0: subdevice #0
  Subdevice #1: subdevice #1
  Subdevice #2: subdevice #2
  Subdevice #3: subdevice #3
  Subdevice #4: subdevice #4
  Subdevice #5: subdevice #5
  Subdevice #6: subdevice #6
  Subdevice #7: subdevice #7
card 0: ALSA [bcm2835 ALSA], device 1: bcm2835 ALSA [bcm2835 IEC958/HDMI]
  Subdevices: 1/1
  Subdevice #0: subdevice #0

Then you will take whatever number device is the bluetooth speaker, and put that in the raspotify settings file
sudo nano /etc/default/raspotify

then adding the below line to your settings with correct hw number - ('hw:0,1' which I believe means card 0, device 1. obviously put the x,x that is the same as your bluetooth speaker)
OPTIONS="--device hw:0,1"

save this file and restart your raspotify service
sudo systemctl restart raspotify

If you're lucky everything should work, if not then even the raspotify file tells you ymmv for changing the hw device and you may need to figure out an alternate plan to use this speaker.
Good luck, hopefully this helps


Reasons for CTRL+PrtScr+R+E+I+S+U+B

Question: If Linux stops responding one might be forced to make an unclean shutdown and in this case one might unknowingly just turn off the power. I read that you should try and make a soft reset with ctrl+prntSc + R +E +I + S+ U+ B with Linux if possible, because a suddently turning off the power might corrupt the file system. What are the details of this and is it true to say that Linux is less resilient that MS-Windows in this case?
Comment: Those are usually [Alt+SysRq](https://unix.stackexchange.com/a/16555/70524)...
Comment: Possible duplicate of [What happens if I do an improper shutdown of Lubuntu 13.10?](https://unix.stackexchange.com/questions/106836/what-happens-if-i-do-an-improper-shutdown-of-lubuntu-13-10)
Comment: Yes, there's a reason for the backronym to be `Reboot Even If System's Utterly Borken` and not something based on "BUSIER". :p   https://en.wikipedia.org/wiki/Reisub#Uses
Comment: i do not know what your experience with Linux file systems is, but over the past 25 years I powercycled 1000s of machines with no FS corruption whatsoever. YMMV.
Comment: Filesystems may actually be corrupt but have mechanisms to automatically recover from such corruption (e.g. journaling).
Comment: Also see sourcejedi's answer to an exact duplicate of this question three weeks later: https://unix.stackexchange.com/a/442967/170373
Answer: I don't think Ctrl+PrtScr will do much, what you need is SysRq (usually on the same physical key as PrtScr, accessed by holding Alt when pressing that key, for that reason it's a little unclear to be if the "magic" combinations are actually SysRq+<letter> or Alt+SysRq+<letter>).
The B function will boot the system, so your combination is a waste of time, only the B will ever be done, and just booting is about as bad as powercycling.
What can (sometimes) be gained by SysRq+R,E,I,S,U,B (to me + indicates that you need to press all the keys at once, and pressing eight keys at once is hard and not what you want to do - and note that "BUSIER" is actually the classic combination completely backwards), is a nicer shutdown where as much data as possible is written to the disk(s) nicely, so a fsck is not needed on the next boot, and the risk of data loss is minimised.
There's a lot of information, including a complete list of SysRq-combinations and some mnemonics on the wikipedia page for Magic SysRq.
Comment: U.S.E. in it's wisdom declared a REISUB question by same author as a duplicate as this one. I have acted accordingly to provide an answer on the canonical question. Comment to let you know the original question has now been modified, so the comment in this question about BUSIER applies to an earlier version only.
Answer:
What are the details of this and is it true to say that Linux is less resilient that MS-Windows in this case?

It might have been useful to make the comparison at one point. That comparison probably explains why these SysRQ commands are quite so well known.  However it does not apply in comparing recent Linux and Windows versions.
The details are largely explained if you understand the meaning of "journalling filesystem".  Example reference.
As per this reference, the most popular Linux filesystem series gained journalling filesystem support somewhat later than Microsoft's.
Additionally, the popular understanding is that Linux filesystems would still have been able to recover just fine using fsck, the problem is that fsck takes so long on larger disks, so journalling is more of an optimization.
Given just how long this can take on modern large disks, it is hard to quibble about journalling being more "resilient" :-).  In principle, it's possible the sync also has some use, regardless of journalling filesystems.  It lets you trigger an immediate writeback which includes any unsynced file contents.  (You must then watch the disk LEDs or noise to guess when writeback has finished).  This avoids e.g. having to wait for dirty_writeback_centisecs on ext filesystems.  Some people have even configured their systems to use "laptop mode" where lazy writeback is delayed indefinitely to save power.
There is an additional detail. Journalling filesystems on Linux tend to assume they are not run with barriers disabled. The performance effect of barriers has been mitigated such that Linux distributions have stopped disabling barriers by default. (Alternatively, disabling barriers could be "safe" in some circumstances and on some hardware, but this does not apply to normal PC hardware as of 2018.  Redhat have stopped recommending disabling barriers even on such hardware). Example reference.
quotes (some formatting - useful links - have been lost):
Journalling filesystem

Updating file systems to reflect changes to files and directories usually requires many separate write operations. This makes it possible for an interruption (like a power failure or system crash) between writes to leave data structures in an invalid intermediate state.[1]
For example, deleting a file on a Unix file system involves three steps:[5]

Removing its directory entry.
Releasing the inode to the pool of free inodes.
Returning any blocks used to the pool of free disk blocks.

If a crash occurs after step 1 and before step 2, there will be an orphaned inode and hence a storage leak. On the other hand, if only step 2 is performed first before the crash, the not-yet-deleted file will be marked free and possibly be overwritten by something else.
Detecting and recovering from such inconsistencies normally requires a complete walk of its data structures, for example by a tool such as fsck (the file system checker).[2] This must typically be done before the file system is next mounted for read-write access. If the file system is large and if there is relatively little I/O bandwidth, this can take a long time and result in longer downtimes if it blocks the rest of the system from coming back online.
To prevent this, a journaled file system allocates a special area—the journal—in which it records the changes it will make ahead of time. After a crash, recovery simply involves reading the journal from the file system and replaying changes from this journal until the file system is consistent again. The changes are thus said to be atomic (not divisible) in that they either succeed (succeeded originally or are replayed completely during recovery), or are not replayed at all (are skipped because they had not yet been completely written to the journal before the crash occurred).

barriers

To mitigate the risk of data corruption during power loss, some storage devices use battery-backed write caches. Generally, high-end arrays and some hardware controllers use battery-backed write caches. However, because the cache's volatility is not visible to the kernel, Red Hat Enterprise Linux 6 enables write barriers by default on all supported journaling file systems.
For devices with non-volatile, battery-backed write caches and those with write-caching disabled, you can safely disable write barriers at mount time using the -o nobarrier option for mount. However, some devices do not support write barriers; such devices will log an error message to /var/log/messages (refer to Table 22.1, "Write barrier error messages per file system").
[...]
Note
The use of nobarrier is no longer recommended in Red Hat Enterprise Linux 6 as the negative performance impact of write barriers is negligible (approximately 3%). The benefits of write barriers typically outweigh the performance benefits of disabling them. Additionally, the nobarrier option should never be used on storage configured on virtual machines.

Reasons for CTRL+PrtScr+R+E+I+S+U+B


Downloading additional voices from command-line

Question: I am using a MacOS X server (to which I only have command-line access) to convert text to speech which is saved to sound files (using PyObjC). I would like to install some of the optional OS X voices (for example com.apple.speech.synthesis.voice.tom.premium) but I need to be able to do this through the command-line rather than via the System Preferences. Does anyone know a way to do this?
Comment: I need to do this as part of a Travis (http://travis-ci.org) job, and therefore this ideally all has to be done via the command-line.
Comment: Why can't you use Sys Prefs?
Answer: You can predownload the voice files to your App/Python package (or however you are distributing your app), and then write a script to move or copy the voice files to this folder:
/System/Library/Speech/Voices/

So:

Download the voice files on your development machine
Wrap them inside an assets folder or something like this
Part of your Travis script can be to move the files first in the Voices folder on the mac
And after that, you run your tests/other scripts


Does the motion tracker follow a point if it changes colour throughout the video?

Question: Does the motion tracker follow a point if it changes colour throughout the video?
Like an colour changing led dangling from a pendulum or a firework mid-flight?
Answer: Ideally you want to track objects that do not shift in shape, color or brightness. There is some room however to do some adaptable tracking.
In the tracking settings use:
Pattern Match:
Previous frame.
Enable:
Prepass
and
Normalize.
If the changes are slow, those settings might help you to track an object that changes color or intensity. Note that if the changes are too drastic from frame to frame, you will need to track until the frame where the automatic tracking stops (or fails to be accurate), then manually re-position the tracker and continue the automatic process until it fails again and so on.

Blatant quote from the manual

Pattern Match
Pattern Match controls which patterns get tracked; to be more precise, the pattern from which frame is getting tracked. Here is an example which should make things clearer.
The tracker algorithm receives two images inside the search area and the position of a point to be tracked in the first image. The tracker tries to find the position of that point from the first image in the second image.
Now, this is how tracking of the sequence happens. The second image is always from a frame at which the position of marker is not known (next tracking frame). But a different first image (instead of the one that immediately precedes the second image in the footage) can be sent to the tracker.
Keyframe
An image created from a frame on which the track was keyframed. This configuration prevents sliding from the original position (because the position which best corresponds to the original pattern is returned by the tracker), but it can lead to small jumps and can lead to failures when the feature point is deformed due to camera motion (perspective transformation, for example).
Previous Frame
Keyframes for tracks are creating every frames, and tracking between keyframed image and next image is used. In this configuration the pattern is tracking between two neighboring frames. It allows dealing with cases of large transformations of the feature point but can lead to sliding from the original position, so it should be controlled.
Prepass
Enables a two pass tracking, where the first pass is a brute force tracking of location only, and the second pass will use tracking of the full motion model refining the first pass.
Normalize
Means patterns will be normalized by their average intensity while tracking, to make them invariant to illumination changes. An example where this is useful is a scene where a marker moves in the shadow of an object.


Software to download audio playing on a website

Question: The following link: https://www.audiobookcup.com/bigger-leaner-stronger-audiobook/
has audio that can be played on the website. Is there any tool that can be used to download this?
Comment: "Audiobook Cup is a free audio book listening platform. You can listen to thousands of audiobooks online for free on this site, or you can download audiobooks offline by paying $ 4.99." - I'm not sure whether we help in finding tools for illegal activities.
Comment: I am glad that I saw your comment before posting an answer :-)  Thanks, Thomas
Answer: In general if a webpage does not prevent this, you can download media with browser extensions, such as flashgot for firefox or bulk media downloader for chrome.
Understandably Audiobook Cup does not allow you to do this.


Sending array to node is taken as object using formData

Question: I am performing an update where, in addition to other data, I need to send Node an array that includes the information of one or more images, but only their path and ID, not the image itself.
I am performing an update where, in addition to other data, I need to send Node an array that includes the information of one or more images to be deleted, but I only pass its path as well as ID, not the image itself since the images are in Cloudinary.
I use formData because among these data I send the new images in case new ones are required, but I receive all the data except for the images to be deleted, since instead of receiving an array I only receive [Object Object] and I cannot work with it. This is my code:

    const putProduct = async (productToUpdate, filesToDelete) => {

        console.log(filesToDelete) // Array

        const formData = new FormData()
        const imageArr = Array.from(productToUpdate.pictures)

        imageArr.forEach(image => {
          formData.append('pictures', image)
        })

        formData.append('filesToDelete', filesToDelete)
        formData.append('barCode', productToUpdate.barCode)

        try {
            const dataOnLs = localStorage.getItem('cmtjs')
            const config = {
                headers: {
                    "Content-Type": "multipart/form-data",
                    apiKey: dataOnLs
                }
            }

            const { data } = await axiosClient.put(`/products/${productToUpdate.id}`, formData, config )

I receive in Node and go through the console req.body.filesToDelete but it always indicates [Object Object]
let updateProduct = async ( req, res = response ) => {

    const filesToDelete = req.body.filesToDelete;
    console.log(filesToDelete); // [object Object]
    return

Comment: What request body middleware have you registered? To support `multipart/form-data`, you need something like [Multer](https://github.com/expressjs/multer)
Comment: Yes, exactly I use Multer
Answer: FormData requires objects to be strings. Here's the replacements:
Frontend
Replace:
formData.append('filesToDelete', filesToDelete)

With:
formData.append('filesToDelete', JSON.stringify(filesToDelete))

Backend
Replace:
const filesToDelete = req.body.filesToDelete

With:
const filesToDelete = JSON.parse(req.body.filesToDelete)

Answer: You should treat the filesToDelete array the same way you treat productToUpdate.pictures.
If you want filesToDelete to appear as an array in req.body.filesToDelete, use this...
filesToDelete.forEach((f) => {
  formData.append("filesToDelete", f);
});

Multer automatically handles repeated fields as an array. You can optionally add [] to the field name for clarity in your code...
formData.append("filesToDelete[]", f);

but the result will be the same.

On the client-side, you can remove the content-type header. Your browser will handle this automatically for you.


Python Encoding issue

Question: Why am I getting this issue? and how do I resolve it?
UnicodeDecodeError: 'utf8' codec can't decode byte 0x92 in position 24: unexpected code byte

Thank you
Comment: Please give more information and post some code.
Comment: See: http://groups.google.com/group/pylons-discuss/browse_thread/thread/ec18b194bd260244?pli=1
Comment: Can you explain what you are trying to do?
Comment: More information indeed, especially if it's Python 3.x or 2.x
Answer: Somewhere, perhaps subtly, you are asking Python to turn a stream of bytes into a "string" of characters.
Don't think of a string as "bytes".  A string is a list of numbers, each number having an agreed meaning in Unicode.  (#65 = Latin Capital A.  #19968 = Chinese Character "One"/"First") .
There are many methods of encoding a list of Unicode entities into a stream of bytes.  Python is assuming your stream of bytes is the result of a particular such method, called "UTF-8".
However, your stream of bytes has data that does not correspond to that method. Thus the error is raised.
You need to figure out the encoding of the stream of bytes, and tell Python that encoding.
It's important to know if you're using Python 2 or 3, and the code leading up to this exception to see where your bytes came from and what the appropriate way to deal with them is.
If it's from reading a file, you can explicity deal with the bytes read.  But you must be sure of the file encoding.
If it's from a string that is part of your source code, then Python is assuming the "wrong thing" about your source files... perhaps $LC_ALL or $LANG needs to be set.  This is a good time to firmly understand the concept of encoding, and how text editors choose an encoding to write, and what is standard for your language and operating system.
Answer: In addition to what Joe said, chardet is a useful tool to detect encoding of the source data.
Answer: Somewhere you have a plain string encoded as "Windows-1252" (or "cp1252") containing a "RIGHT SINGLE QUOTATION MARK" (') instead of an APOSTROPHE ('). This could come from a file you read, or even in a Python source file of yours; you could be running Python 2.x and have a # -*- coding: utf8 -*- line somewhere near the script's beginning, or you could be running Python 3.x.
You don't give enough data; however, somewhere you have a cp1252-encoded string, which you try (explicitly or implicitly) to decode to unicode as utf-8. This won't work.
Give us more info, and we'll try again to help you.
Joe Koberg's answer reminded me of an older answer of mine, which some people have found helpful: Python UnicodeDecodeError - Am I misunderstanding encode?

Python Encoding issue


JOIN Performance: Composite key versus BigInt Primary Key

Question: We have a table that is going to be say 100 million to a billion rows (Table name: Archive)
This table will be referenced from another table, Users.
We have 2 options for the primary key on the Archive table:
option 1:  dataID (bigint)
option 2: userID  + datetime (4 byte version).
Schema:
Users
- userID (int)
Archive
- userID
- datetime
OR
Archive
- dataID (big int)
Which one would be faster?
We are shying away from using Option#1 because bigint is 8 bytes and with 100 million rows that will add up to allot of storage.
Update
Ok sorry I forgot to mention, userID and datetime have to be regardless, so that was the reason for not adding another column, dataID, to the table.
Comment: minor correction: the phrase should be "add up to a lot of storage".  Allot has a completely different meaning.
Answer: Some thoughts, but there is probably not a clear cut solution:

If you have a billion rows, why not use int which goes from -2.1 billion to +2.1 billion?
Userid, int, 4 bytes + smalldatetime, 4 bytes = 8 bytes, same as bigint
If you are thinking of userid + smalldatetime then surely this is useful anyway.
If so, adding a surrogate "archiveID" column will increase space anyway
Do you require filtering/sorting by userid + smalldatetime?
Make sure your model is correct, worry about JOINs later...
Comment: As an alternative to the first bullet, how about an unsigned int, which goes from 0 to 4.2 billion?
Comment: SQL Server does not have unsigned int :-)
Answer: Concern: Using UserID/[small]datetime carries with it a high risk of not being unique.
Here is some real schema. Is this what you're talking about?
<code>-- Users (regardless of Archive choice)
CREATE TABLE dbo.Users (
    userID      int           NOT NULL  IDENTITY,
    <other columns>
    CONSTRAINT <name> PRIMARY KEY CLUSTERED (userID)
)

-- Archive option 1
CREATE TABLE dbo.Archive (
    dataID      bigint        NOT NULL  IDENTITY,
    userID      int           NOT NULL,
    [datetime]  smalldatetime NOT NULL,
    <other columns>
    CONSTRAINT <name> PRIMARY KEY CLUSTERED (dataID)
)

-- Archive option 2
CREATE TABLE dbo.Archive (
    userID      int           NOT NULL,
    [datetime]  smalldatetime NOT NULL,
    <other columns>
    CONSTRAINT <name> PRIMARY KEY CLUSTERED (userID, [datetime] DESC)
)
CREATE NONCLUSTERED INDEX <name> ON dbo.Archive (
    userID,
    [datetime] DESC
)
</code>
If this were my decision, I would definitely got with option 1. Disk is cheap.
If you go with Option 2, it's likely that you will have to add some other column to your PK to make it unique, then your design starts degrading.
Comment: Plus I would never use a datetime in a PK unless there was trigger that it could never be updated atfter the initial insert. That's just an accident waiting to happen.
Answer: What's with option 3: Making dataID a 4 byte int?
Also, if I understand it right, the archive table will be referenced from the users table, so it wouldn't even make much sense to have the userID in the archive table.
Answer: I recommend that you setup a simulation to validate this in your environment, but my guess would be that the single bigint would be faster in general; however when you query the table what are you going to be querying on?
If I was building an arhive, I might lean to having an autoincrement identity field, and then using a partioning scheme to partion based on DateTime and perhaps userid but that would depend on the circumstance.


Deriving order statistics with respect to sample size

Question: I am considering a sample of n iid random variables, distributed according to a law F. I am interested in deriving the CDF of the i-th order statistics, $F_i(t)=\sum_{k=i}^n \binom{n}{k}F(t)^k(1-F(t))^{n-k}$, with respect to the sample size, n. Still, I do not know how to deal with deriving a sum with respect to the number of its addends and how to derive the binomial coefficient with respect to n. Suggestions?
Comment: Derivation of binomial coefficient is not an easy task. If you are interested in finding the derivative by yourself consider taking the derivative of the very last formula at the end of this page: https://en.wikipedia.org/wiki/Binomial_coefficient
Answer: We can first use that the derivative operator is linear and derive the term of the sum:
$
\begin{align}
 \frac{\partial F_i(t,n)}{\partial n} & =  \sum \limits_{k=i}^n \frac{\partial \binom{n}{k}F(t)^k(1-F(t))^{n-k} }{\partial n}\\
 & = \sum \limits_{k=i}^n \binom{n}{k}F(t)^kln(1-F(t))(1-F(t))^{n-k} + \frac{\partial \binom{n}{k}}{\partial n} F(t)^k(1-F(t))^{n-k} \tag1
\end{align}
$
On the other hand, in order to derive the binomial coefficient we can re write it:
$
\begin{align}
   n \choose k & =\frac {n!}{k!\,(n-k)!} \\
 & =  \frac {\Gamma (n+1)}{\Gamma (k+1)\,\Gamma (n-k+1)} \\
 & = \exp(\ln \Gamma (n+1)-\ln \Gamma (k+1)-\ln \Gamma (n-k+1)) \tag2
\end{align}
$
Let $\psi$ be the Digamma function defined like this:
$$\psi (x)={\frac {d}{dx}}\ln {\big (}\Gamma (x){\big )}={\frac {\Gamma '(x)}{\Gamma (x)}} \tag3$$
Then,
$$\frac{\partial \binom{n}{k}}{\partial n} =  \binom{n}{k}(\psi(n+1)-\psi(-k+n+1)) \tag4$$


Tables names in a supertype/subtype schema

Question: I have 3 types of users in my app. The users share some common attributes, but they also have quite a bit of stuff that pertains uniquely to each user type. I have a person table that contains limited information about each user. I then have 3 tables for each user type: admin, reader, approver.
Now, the design I have gone with thus far has been something like this:
General Tables (don't pertain to users)
e.g.,
country
city
Tables That Pertain to all Users
e.g.,
person_contact
person_contact_category
Tables That Pertain to User Type
e.g.,
approver_approve_for
reader_can_view
Now, based on this information, I am wondering a few things:

Global tables do not get a prefix. Is it considered bad practice to prefix the tables that pertain to a subset with the subset name (e.g., admin_)? I figured it makes it easy to look at the DB design and see exactly what subtype each table pertains to, but the next question is what made me ask this question at all.
The table person_contacts_categories_map is a junction table between the many categories a person can have, and the many contacts in those categories. OK, typically I name my junction tables something like contact_category. Unfortunately, there are more things that get categories in this app than just contacts, thus I am saying this table relates to all persons (e.g., person_) and relates to contacts (contact_). I was thinking then that the junction table should be named person_contact_person_contact_category, but that is just horrible.

So, given what I've laid out, does anyone know a better approach to this problem, or is what I am doing fine?
Comment: Looks clean to me.
Answer: Instead of changing the names of individual tables, I would recommend using schema names to denote the different types of users.
For instance:

Admin.Users
Reader.Users
Approver.Users

Using Schemas in this way allows a more flexible method for controlling access since you can assign rights by schema instead of at the individual table level.
Answer: I would reverse the naming convention for dealing with subset types.  So a table of users, then another table of users_admin, users_reader, users_approver.
I've used this in the past for parent-child tables.  It makes them easy to locate and determine who is the parent and who is the child when looking at a list of table names.


If gravitational waves exist are they technically just another form of light/electromagnetic wave?

Question: I would imagine a gravitational wave would have very similar characteristics to electromagnetic wave, what kind of differences are there?
Comment: A little bit of research would shows you that they are very different entities. Also, a source emitting gravitational waves does not have to have electric charge, which would seem to disprove your hypothesis. Stick a bunch of neutrinos together in a certain asymmetric configuration and you can create gravitational waves.
Comment: http://www.tapir.caltech.edu/~teviet/Waves/differences.html
Comment: See also this article https://arxiv.org/ftp/arxiv/papers/1101/1101.2247.pdf
Answer:
If gravitational waves exist are they technically just another form of
  light/electromagnetic wave?

No.
Electromagnetic waves are (classically) disturbances in the electromagnetic field that propagate with speed $c$.
Gravitational waves are disturbances in the geometry of spacetime that propagate with speed $c$.

I would imagine a gravitational wave would have very similar
  characteristics to electromagnetic wave

Electromagnetism is (classically) linear.  However, the gravitational field equations are non-linear (which are approximately linear in the 'small-signal' approximation).
While there is dipole electromagnetic radiation, the lowest order gravitational radiation is quadrupole.  This is related to the fact that the gravitational field is a rank 2 tensor field as opposed to a vector field.
So, other than the fact that they are waves and propagate at $c$, they aren't similar at all.  In a comment, Hassan has provided a relevant link for further reading.
Answer: gravitational waves and electromagnetic waves might be the same thing if mass and charge were the same thing (as far as i understand reality they are not the same thing).
imagine that we are standing some distance from each other and facing each other and you're holding a negative charge and i am holding a positive charge.  they attract each other but we are restricting motion so that they cannot move toward each other along the line connecting them.  but they can move in the left/right dimension and the up/down dimension.
so i move my charge up and your charge follows it up.  i move my charge to my right and your charge follows it (to your left).  then i wave my charge back and forth (actually left-and-right) a couple times per second and your charge follows that waving motion.  that is literally an EM wave and i am a transmitting antenna and you are a receiving antenna.  if i moved my charge back-and-forth a million times per second, you could tune that in with an AM radio.  if i move it back-and-forth 100 million times per second, you could tune it in with an FM radio.  if i move it 500 trillion times per second, you would see it as a blur of orange color.
that's what EM waves are.  if i perturb the position of my charge, the position of your charge is perturbed.  if a third-party observer who is equidistant from both you and me was watching, he/she would see the perturbation of your charge occur at a time that is $\frac{L}{c}$ later where $L$ is the distance between us.
now imagine you and i are big as gods and we're holding planets (that are attracted to each other due to gravity) and we do the same thing: i perturb the position of my planet and your planet responds with a similar perturbation.  again, for the third-party observer who is equidistant from both you and me, the observer would see the perturbation of your mass occur at a time that is $\frac{L}{c}$ later than my perturbation where $L$ is the distance between us.
you get EM waves by waving a charge around (and the other folks holding a charge have their charges perturbed) and you get gravitational waves by waving large masses (a planet or a star) around and the other masses (that are attracted to it) are perturbed in their positions.  $c$ is not just the "speed of light" or the speed of EM, but is the speed of any "instantaneous" interaction.
that speed is really only an expression of the units we use to express it.  as long as $c$ is real, positive, and finite, it doesn't matter what value it is.  if all dimensionless fundamental constants remained the same, everything else in physical reality would scale so that, for us mortals, $c$ would continue to be measured as around 299792458 meters per second (assuming the meter definition preceding 1960, now it is defined so that $c$ is that value).
Comment: One small addition for the sake of clarity: While AM (amplitude modulation) and FM (frequency modulation) radio are in the frequency range that you specified, technically you'd have to modulate the frequency (i.e. the speed with which you're waving) or the amplitude (the distance you wave to the left/right) to be able to tune into it with a radio.
Comment: no @chopper, that is incorrect (and being an electrical engineer, i feel that i have sufficient chops and credentials to say so).  in both cases you can *"tune it in"* and in both cases you would hear silence (as opposed to the band noise you would hear in an empty channel) because both signals are **unmodulated**.  i.e., you **can** tune in unmodulated AM and FM signals (and you will hear a nice silence rather than the hiss between stations and the reason you may not hear hiss with a modern receiver is because of muting/gate function in the receiver, not because the hiss isn't there).


How can I get exact user plus the user's exact posts in laravel from jwt token laravel

Question: I'm trying to get a list of a single user plus his/her post in another table, while passing the user jwt token in the header.
public function getAuthenticatedUser()
{
    try {

        if (! $user = JWTAuth::parseToken()->authenticate()) {
            return response()->json(['user_not_found'], 404);
        }

    } catch (Tymon\JWTAuth\Exceptions\TokenExpiredException $e) {

        return response()->json(['token_expired'], $e->getStatusCode());

    } catch (Tymon\JWTAuth\Exceptions\TokenInvalidException $e) {

        return response()->json(['token_invalid'], $e->getStatusCode());

    } catch (Tymon\JWTAuth\Exceptions\JWTException $e) {

        return response()->json(['token_absent'], $e->getStatusCode());

    }

    // the token is valid and we have found the user via the sub claim

    $user = auth()->user();
    $userid = User::where('id', $user->id);
    $return = UserResource::collection($userid);
    return response()->json($return);

}

While doing it this way I get
BadMethodCallException: Call to undefined method Illuminate\Database\Eloquent\Builder::mapInto() in file C:\xampp\htdocs\doc\vendor\laravel\framework\src\Illuminate\Support\Traits\ForwardsCalls.php on line 50

#0 C:\xampp\htdocs\doc\vendor\laravel\framework\src\Illuminate\Support\Traits\ForwardsCalls.php(36): Illuminate\Database\Eloquent\Builder::throwBadMethodCallException('mapInto')

But if I do it this way;
$user = auth()->user();
$userid = User::find($user);
$return = UserResource::collection($userid);
return response()->json($return);

I get a response, but I get two users returned, instead of the exact user with the jwt token
When I return just auth()->user() I get the exact user of the jwt but without the post resource.
How can I get exact user plus the user's exact posts
Comment: Try `User::where('id', $user->id)->first();`
Comment: BadMethodCallException: Call to undefined method App\User::mapInto() in file
 C:\xampp\htdocs\doc\vendor\laravel\framework\src\Illuminate\Support\Traits\ForwardsCalls.php on line 50

This is the response
Answer: I see a problem in the following snippet.
User::where('id', $user->id);

where is a syntactic sugar for calling where on a query builder, it therefor returns a query builder, to retrieve the user this way.
User::where('id', $user->id)->first();

Secondly a helper is made for this exact case called find(), you can call statically on model classes.
$user = User::find($user->id);

EDIT
$return = UserResource::collection($userid);

Expects a Collection, therefor change it to a single resource.
$return = new UserResource($userid);

Comment: BadMethodCallException: Call to undefined method App\User::mapInto() in file

 C:\xampp\htdocs\doc\vendor\laravel\framework\src\Illuminate\Support\Traits\Forwa
   rdsCalls.php on line 50