How can I identify new & improved PEX plumbing materials with less fracturing & chlorine/chlorimene degredation issues?

Question: Just bought 14 year old 3,200 sq ft,(3-Bed,3-Bath) house & may have to work on the PEX plumbing issues. I have read a lot about class action law suits, relating to (PEX-A Pipe fracturing, especially right behind the plastic rings) & (PEX-B dezinktification failures with brass connections causing lots of water disasters over the last 20 yrs.
My problems is I can't seem to locate information about the systems that have the newest (PEX A&B plastic tbg recipes) &  better (metal/plastic) fittings technology, that should be produced to replace all the older PEX tbg & fitting issues.
There is a vast amount of failures on many message boards, with home owners telling their war stories battling water damage in ceilings, walls, floors & basements costing thousands of dollars, with leaks through their houses.
Question: How would you find out Where you can get the PEX materials that have less issues with (chlorine / chloramine ammonia) & dezinktification ) problems. There are way too many bad message board stories of PEX systems failing over the last 20 yrs, when originally the systems we suppose to be manufactured with expectations of lasting 25 to 50 years.
Comment: Almost every house is plumbed with pex these days. Most failures are due to improper installation.
Comment: It sounds like you've done a lot of research. I'd suggest it would be worthwhile contacting the manufacturers and ask them about the specifics of the products they are _currently_ producing. If the specs they provide on current products meet _your_ standards of acceptability (based on your knowledge through research), then go with it! It doesn't really matter who makes it, right?
Comment: "Yes, Uponor AquaPEX piping and ProPEX fittings are covered by a 25-year transferable limited warranty. For complete details, visit our warranties page."
Comment: Brand recommendations are offtopic here, I'm afraid.
Comment: FreeMan, yes your suggestion would probably be the best & only way to proceed. I just figured by calling their online support, I might possibly get a biased reply. Thank you for you help.
Comment: Food for thought: For years now, water companies have been swapping their water meters out with new ones, containing check valves, creating closed systems, and raising water pressure in the mains to satisfy demands. I wonder how many of the homeowners affected have installed pressure reducers and expansion tanks? Uponor pex is rated: 180F at 100psi, 73F at 160psi, & 120F at 130psi (1/2 to 2" white pipe only). My water heater is set at 125F and water main = 120psi) so if I didn't have a pressure reducer installed & I had white Uponor pex (only) I could easily exceed the rating!! I wonder????
Comment: https://www.uponor.com/en-us/customer-support/faq#:~:text=Is%20the%20Uponor
Comment: Looks like they stand behind their product but if the installation exceeds the rating then like any other company they are not liable. So the house must not have too high of pressure, the water heater must have an expansion tank, and it doesn't seem the best idea to use their white pex on the hot water line incase those 2 failed, to insure that would not be the case. Fittings are often not installed correctly so those leaks are on the installer.
Comment: FYI I understand the chlorine issue.
Comment: There are now stainless steel fittings
Comment: Are you maybe confusing pex with polybutylene pipe?
Answer: It sounds like you've done a lot of research.
I'd suggest it would be worthwhile contacting the manufacturers and ask them about the specifics of the products they are currently producing. If the specs they provide on current products meet your standards of acceptability (based on your knowledge through research), then go with it!
While you might get a biased "we just want to sell stuff" answer if you ask something like "have you fixed the problems I've seen reported about ____", you're likely to get specifics if you ask "does your pipe have this and that in it?" Those questions should get you yes/no answers and you can then base your decision on those yes/no answers. If you feel you're being fed a line of "we just wanna sell pipe", well, that's a pretty good indication that this is a manufacturer you can't trust, and you should move on to the next one.
It doesn't really matter who makes the pipe, right? You just care that they've resolved the issues you've found.
Comment: FreeMan, yes, I get your point. Ask questions with specific directives, like  1; improvement with Chlorine tubing issues) & 2; Dezinktification improvement to stop corrosion in the brass fitting.  Thank you so much for your help ! ! !
Comment: Took the tour, gutter done FreeMan.
Comment: Glad that helped, @OilyTex. Having taken the [tour], please use the proper way of saying thanks. I'm not looking for the magic interwebz points, it just helps others to know that there's a solution here.
Comment: Thanks, sir! Again, don't really care about magic internet points, I've already redeemed some for all the unicorns & rainbows I could want, this just keeps the wheels greased and the system working. Hope you find the info you're after!


How do I change the form of Deoxys in Pokémon X and Y?

Question: How can I change the form of Deoxys in Pokémon X and Y? In previous games there are meteorites that, upon touching, cause its form to change. Is there something similar to this in Pokémon X and Y?
Answer: From serebii: http://www.serebii.net/xy/bankunlocks.shtml

In the Fossil Lab in Ambrette Town, in the north-west part of the lab
  you will find various Meteorites. Four of these meteorites will allow
  you to change Deoxys' form between its four forms: Normal, Attack,
  Defense and Speed Formes.
Comment: Once I test it out, I will accept accordingly.
Comment: Each one is not assigned to a form, they all cause him to cycle to the next one.


Chrome doesn't refresh static JS file when running local development with Google App Engine Flask dev_appserver.py

Question: Chrome loads the javascript file, but when I update the file, the update doesn't appear in Chrome. I've tried this in Firefox and I can see that the javascript file has updated when I refresh the page, but not in Chrome.
I'm using Flask and the javascript files are in the static folder. My directory looks like:
app
-env
-lib
-static
--css
--img
--js <-- there is where my js file is
-templates
--partials
-app.yaml
-main.py
-requirements.txt

My app.yaml file is:
runtime: python27
api_version: 1
threadsafe: yes
# Handlers define how to route requests to your application.
handlers:
# This handler tells app engine how to route requests to a WSGI application.
# The script value is in the format <path.to.module>.<wsgi_application>
# where <wsgi_application> is a WSGI application object.
- url: .*  # This regex directs all routes to main.app
  script: main.app

Comment: Did you try disabling cache in chrome dev tools (Ctrl + Shift + i)?  Network tab at the top the checkbox for disabling cache.  The dev tools window has to be open for any of the options to work.
Comment: whoa, yes, thank you @Derek, that totally worked! You should answer this as an official answer!
Answer: Ctrl + Shift + i    Network Tab > Disable cache.
Note: Dev tools has to be open for options to work.
Answer: You may keep you code under flask under yourapp/static/js as mentioned in
http://exploreflask.com/en/latest/static.html
use versions in javascript when you modify it.


How does invisibility work in Skyrim?

Question: So there I am, with nothing but my dagger and 4 enduring invisibility potions, all I need to do is sneak in, and out of the Thalmor Embassy. Easy, right? Or so I think. After I cause a distraction and grab my dagger and potions from the chest, I open the first door after having gulped a invisibility potion, and Charge past them real quick, and BOOM firebolts and lightning bolts fly at me, and I get smacked into a wall, my butt thouroughly kicked. What happened?! Does an invisibility potion NOT make you invisible? They turned on me faster than a hound on a bunny the moment I opened the door....
Answer: I open the first door after having gulped a invisibility potion. That is where your issue lies.
You drank your potion before opening the door, which counts as an action that ends the invisibility effect. You want to drink your invisibility potions after you open the door to sneak past the Thalmor.

Invisibility will end if the caster:

Activates an item (including: using levers and buttons, opening doors and containers, grabbing and stealing items).

Uses a magical effect other than invisibility (including spells, potions, and scrolls).

Interacts with a character (including attack, pickpocket, and dialogue).

Though you can't be seen while invisible, you can still be detected if you make too much noise or do anything that would attract attention.

Although you cannot be seen when you are invisible, you can still be heard, meaning enemies may still detect you. You are more likely to be detected if you:

move too close to an enemy.

swing a weapon (even if you don't hit someone with it).

run into a mobile object or walk on a trap.

make noise, including casting the spell without using the Quiet Casting perk.

If you want to get your best experience of invisibility, you can use it in conjunction with Muffle (an apprentice level illusion spell and armor enchantment)

Because the Dragonborn's footfall can be heard by enemies while invisible, Muffle is useful when combined with it. Using both spells while sneaking makes the Dragonborn almost impossible to detect by others, unless the Dragonborn bumps into them or performs an action

How does invisibility work in Skyrim?


A finite set of coplanar points is such that none lies within the triangle formed by any other three. Are the points vertices of a convex polygon?

Question:
A finite set of points in a plane have a certain property:

If we consider any 3 points in the set, and the triangle generated by these points, then NONE of the other points in the set is in the interior of this triangle.

Does it follow that we can form a convex polygon having all points as vertices?
Comment: Welcome to MSE. Your question is phrased as an isolated problem, without any further information or context. This does not match [many users' quality standards](http://goo.gl/mLWc8), so it may attract downvotes, or closed. To prevent that, please [edit] the question. [This](http://goo.gl/PlJyVQ) will help you recognise and resolve the issues. Concretely: please provide context, and include your work and thoughts on the problem. These changes can help in formulating more appropriate answers.
Comment: What it you take three points on a line?
Answer: The answer is No because of "degenerate cases": Take three points forming an equilateral triangle and a fourth point in the interior of one of the edges.
If you exclude such things, using a more careful formulation of the problem, the answer is Yes, because of Carathéodory's theorem. This theorem says that any point in the convex hull of a given set $S\subset{\mathbb R}^2$ is in the convex hull of three points of $S$.
Let $M$ be the set of given points. The convex hull of this set is a convex polygon $P$ with vertex set $S\subset M$, and is then also the convex hull of $S$. When $S$ is not all of $M$ then there is a $p\in M$ which lies in the interior of $P$. This point $p$ would then lie in a triangle formed by points of $S\subset M$, but your clause has  forbidden that.
Comment: @user3733558: I'd say the "interior of a triangle" is the actual interior, containing no boundary points.
Comment: A point of clarification, Professor: isn't the "interior of a triangle" defined as the set of all points in the convex hull of the triangle's vertices? If so, it seems to me that the OP's problem statement (which, I'll grant you, isn't sharply clear) would actually exclude such cases as the one you're offering as a counter-example. I'm sorry, I'm probably missing something obvious, but I have to ask.
Comment: I suspect OP's definition matches [this one](https://mathworld.wolfram.com/TriangleInterior.html). But I thought exactly as you do at first as well. Clearly, the OP should improve the problem statement and clarify that point. Thanks for your time, Professor.
Comment: An even more basic reason why the answer is "no": the set could be empty.
Answer: No.
Consider a five-sided polygon: a square with an extra vertex on one side, slightly inwards.  This is a concave polygon, but fulfills the stated criteria: pick any three vertices, and the triangle formed contains none of the other vertices.
Link to illustration
Comment: I don't think your counter-example works. Take top-left, top-right and bottom-left. You haven't drawn that triangle, and it contains one of the vertices (top-middle).
Comment: @user3733558: D'oh! You're right.  Thanks!


Finishing YoutubeStandAlonePlayer after completing video in Android?

Question: How to detect when the youtube video ends in YoutubeStandAlonePlayer using google api for Youtube player, I have to finish the player and write instructions after that once the video completes?
<code>Intent intent = YouTubeStandalonePlayer.createVideoIntent(
          mActivity , DEVELOPER_KEY, VIDEO_ID, startTimeMillis, autoplay, lightboxMode);
startActivity(intent);
</code>
Answer: This is currently not possible because YouTubeStandalonePlayer is the activity related to YouTube app which is another app where we doesn't have any control over other apps activity.
As said in documentation of YouTube Player Api,

The second option is to use the YouTubeStandalonePlayer which will start video playback in a separate activity. This is simpler to use, however it gives you less flexibility and control over video playback. The StandalonePlayer supports two modes, either fullscreen or lightbox. In lightbox mode, the activity launching the player is still visible behind the player, slightly dimmed.

Link:- docs


Cascade delete from self-referential many-to-many relationship

Question: I have a SQLite database with the following tables:
fits_table = Table("fits", saveddata_meta,
                         Column("ID", Integer, primary_key = True),
                         Column("ownerID", ForeignKey("users.ID"), nullable = True, index = True),
                         Column("shipID", Integer, nullable = False, index = True),
                         Column("name", String, nullable = False),
                         Column("timestamp", Integer, nullable = False),
                         Column("characterID", ForeignKey("characters.ID"), nullable = True),
                         Column("damagePatternID", ForeignKey("damagePatterns.ID"), nullable=True),
                         Column("booster", Boolean, nullable = False, index = True, default = 0))

projectedFits_table = Table("projectedFits", saveddata_meta,
                            Column("sourceID", ForeignKey("fits.ID"), primary_key = True),
                            Column("victimID", ForeignKey("fits.ID"), primary_key = True),
                            Column("amount", Integer))
mapper(Fit, fits_table,
       properties = {
                     "_Fit__projectedFits" : relation(Fit,
                                                      primaryjoin = projectedFits_table.c.victimID == fits_table.c.ID,
                                                      secondaryjoin = fits_table.c.ID == projectedFits_table.c.sourceID,
                                                      secondary = projectedFits_table,
                                                      collection_class = HandledProjectedFitList)
                     })

It's basically a relationship table that links a Fit to another Fit.
I've been trying to figure out the proper way to cascade a delete, but I cannot get it to work. I would like if a Fit is deleted, then it also deletes any rows in the relationship table where the fit ID is in either the source or victim column.
EDIT: I forgot to add what cascade flags I tried.
cascade='all, delete, delete-orphan', single_parent=True, - did not work. In face, manually deleting the relationship row also deleted the parent (whatever matched the sourceID)
cascade='delete', single_parent=True, - did not have the issue the above setting had, but still did not delete the relationship record when the Fit was deleted
cascade='all, delete', single_parent=True, - same as above
EDIT 2:
I kept fiddling with it, and without adding a cascade attribute, it kinda works. Let me explain:
If I have Fit B linked to Fit A (A is parent in this case), then delete Fit B, it does not delete the relationship. However, if I delete fit A, it does delete the relationship.
I am assuming that I have just been thinking about this completely wrong. When I have a fit instance, it gathers the relationships it has, and deletes any when that fit is deleted. However, when I delete fit B, it technically doesn't have any fits that are linked to it as children. So it never delete them.
I guess a workaround would be to assign the fits that B is a child of to a dummy attribute so that it gets deleted as well. Or do some sort of post processing in the middle layer of the application. Will post back with results, though I still welcome any thoughts. =)
Comment: What [cascade settings](http://docs.sqlalchemy.org/en/rel_0_9/orm/session.html#unitofwork-cascades) did you try?
Comment: Whoops, thanks for letting me know. My attempts have bee added
Answer: I figured it out. As stated in an edit to the OP, I simply had to create a new relation with the criteria swapped. This way both relationships are loaded and deleted when the fit is deleted:
mapper(Fit, fits_table,
   properties = {
                 "_Fit__projectedFits" : relation(Fit,
                                                  primaryjoin = projectedFits_table.c.victimID == fits_table.c.ID,
                                                  secondaryjoin = fits_table.c.ID == projectedFits_table.c.sourceID,
                                                  secondary = projectedFits_table,
                                                  collection_class = HandledProjectedFitList),

                 "_Fit__projectedOnto" : relation(Fit,
                                                  primaryjoin = fits_table.c.ID == projectedFits_table.c.sourceID,
                                                  secondaryjoin = fits_table.c.ID == projectedFits_table.c.victimID == fits_table.c.ID,
                                                  secondary = projectedFits_table,
                                                  collection_class = HandledProjectedFitList)


Converting Hex To Ascii Memory Access

Question: So I have a memory block that is fill with hex values, and I want to read in those hex values as Ascii. Unfortunately, I can't seem to figure out how to do this.
char* charstring = malloc(sizeof(uint16_t));
uint8_t test = 0x65;
sprintf(charstring, "%x ", test);
fprintf(Output, "%s", charstring);
free(charstring);

This just gives me a ton of "65", not the "e" I was expecting.
I know it's a simple question, but I've literally clicked every link on the front page of google and can't figure out my problem!
Comment: `char* charstring = malloc(sizeof(uint16_t));` <-- What on earth is this? Where is your string terminator?
Comment: @squeamishossifrage I saw on a few of the google pages that people were passing pointers to sprintf to hold the converted hex value, so I made my own.
Answer: You get 65 because you are using %x as the format specifier, change it to %c for the character value.
Note that you don't have enough space for charstring for the null terminator. Fix it.
Comment: GAHH, i read on one if the sites that it was x. Thank you, that fixed everything!

Converting Hex To Ascii Memory Access


Continued issue with kex_exchange_identification: Connection closed by remote host

Question: I've recently set up an ubuntu server on an old Dell Optiplex. I can remote in via ssh when on the same network. However, when I try to ssh in from a different network using the public IP, I get the following error:
kex_exchange_identification: Connection closed by remote host
I have searched this error on this forum as well as many others and have tried many different ways to fix this error, but nothing has worked so far. I have port forwarded to the server's static IP, I've allowed OpenSSH and opened port 22 on my server through UFW, and I've set up a VPN that connects my computer to my network. None of these have worked so far.
What am I doing wrong? If anyone has any other ideas that I could try, or anything that I should quadruple check that would be fantastic. Thanks so much.
Answer: I run into a similar case with a small computer I have in my desk. What I did to debug the issue was to run sshd -t, which runs the sshd daemon in debug mode. This command reported that the permissions of my keys were invalid. All I had to do then was to go in the folder where the keys are stored and issue chmod 0600 <your_ssh_keys>. Maybe the action you run generated things with the wrong permissions too
Answer: Sorry for having to submit an answer as I can't yet comment as I don't have enough reputation.
It seems like we need to do a little more debugging to answer this question properly but you mention UFW so I am wondering if this is actually misconfigured.
There's also a possibility that your /etc/hosts.allow and /etc/hosts.deny configs are misconfigured.
Additionally, are you using Password auth or Public Key auth? The reason I ask this is that even if you're using password auth the ssh client will still send your host-id keys during the connection phase, which the ssh server may consider as an authentication failure (in certain configurations) and means you won't get to the point where you enter your password. This can be fixed by using the following:
ssh -o PubkeyAuthentication=No -o PreferredAuthentications=Password <username>@<your server IP>

If you can submit the output from:
UFW with:
sudo ufw status

Double check the entries in your /etc/hosts.* files.
Also submit the output debug output when trying to authenticate by adding the -v flag, e.g:
ssh -v -i <ssh_privkey> <username>@<your server IP>

Hopefully we can get to the bottom of this one.


C# - How do I find the database key of a Listbox item?

Question: I am writing an application where the surname and first name of an employee is shown in a (sorted) listbox - for a selected business unit (hard coded in example below) using an sql statement.  The index of the employee (Access) database is the employee number.
When the item is selected from the listbox I can't find a way to determine the employee number that enables me to read the database to obtain attributes about the employee on a new form.   I think the trick maybe using keyvaluepair but need some guidance on how this is coded.  A sample of the code is below and thanks in anticipation of your help.
using System;
using System.Collections.Generic;
using System.Windows.Forms;
using System.Data.OleDb;

namespace WindowsFormsApp1
{
    public partial class Form1 : Form
    {
        private OleDbConnection connection = new OleDbConnection();
        public Form1()
        {
            InitializeComponent();
            connection.ConnectionString = @"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\Mark\Documents\Employee.accdb;Persist Security Info=False;";
            listBox1_Load();
            }

    void listBox1_Load()
        {
            try
            {
            // Open database and select the data to be shown in the List Box - hard-coded example here
            connection.Open();
            OleDbCommand command = new OleDbCommand();
            command.Connection = connection;
            string query = "select ID, FirstName, Surname from Employee where BusinessUnit = 'Finance'";
            command.CommandText = query;

            OleDbDataReader reader = command.ExecuteReader();

            // Read records returned by the query and populate the list box with the employee name
            while (reader.Read())
            {
                listBox1.Items.Add(reader["Surname"] + ", " + reader["FirstName"]);
            }
            connection.Close();
            }
            catch (Exception ex)
            {
                MessageBox.Show("Error " + ex);
            }
        }

        private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
        {

        }
    }
}

Answer: I would store the data from the DB in a Dictionary, let's say
Dictionary<int,String[]>

where the key is ID and the array is composed of Name and Surname.
Then you populate the listBox with the Dictionary data.
Answer: Not an appropriate answer but an idea:
Maybe you could try something like converting the result into an array or dictionary
listBox1.DataSource = <Array or Dictionary>;
listBox1.DisplayMember = "NameOfColumnToBeDisplayed";
listBox1.ValueMember = "NameOfColumnToUseValueFrom";

And the Display != Value (e.g. value would be your employee id)
Comment: The data displayed will be more that one column in the format  "Surname, First Name" so I'm not sure whether DisplayMember allows that.   I tried previously using an array, but because the list is sorted in the listbox automatically the items will not match.
Comment: He could just concatenate both columns as a string. It really depends on his purpose and how to successfully retrieve a collection that he can easily manipulate. It's been a while since I last touched C# but I remember doing something very similar. Still, it's only a thought.
Answer: not sure if you can add a hidden field into the listbox. however if you store the query you received into a variable which is retained (maybe a datatable as opposed to using a datareader), then when a user clicks to select an option from the listbox you can use that to find the associated record in the query using the index of the listbox selected item.
however you must ensure that the query does the sorting of the results and not the listbox.
Mike
Comment: Thanks Mike - your last point is something I hadn't considered and should make my life a lot easier.
Comment: No Problem, you might even be better off binding the datasource of the listbox and to a datatable and setting the valuemember and displaymember properties on the listbox.


How to cap a 3/8" water feed

Question: What materials are required to cap off a 3/8" water feed at the valve?
I had a dishwasher.  Its feed line connected to the water service under my kitchen sink right at the hot water shut off valve.  I've removed that hose and would like to continue to use the kitchen sink.   What do I need in order to cap off opening?
I have a compression fitting cap that fits on the threads, but this, by itself, does not make a water tight seal.
Comment: How about a few picture so we can see what you see.
Comment: If you have a Y or T splitter on the hot water supply, you can remove that and hook the sink directly to the valve.
Answer: I recently dealt with a similar problem -- I installed a water accessory and was faced with a 3/8" compression male outlet and nothing needing to be connected to it. A cap was easy to find at the plumbing supply but it didn't seal well. Wrapping the male thread with teflon tape plus pipe dope slowed the leak to a very slow drip, but the fact is the threads on a compression joint just aren't intended to form a seal.
In this case I got away with sealing it by placing a thick o-ring in the bottom of the cap. It sealed the cap to the male fitting nicely.
I was concerned the o-ring might wrinkle or buckle in some way during assembly, allowing the leak to continue. Had that happened I also considered carefully placing a brass or acetyl/delrin ferrule (without any tubing) into the male fitting, then place the o-ring around that, and finally install the cap. Maybe the ferrule would seal between the fitting and the cap, but if it didn't, it could provide some structure to help keep the o-ring in place.
Comment: I had the same problem, I was able to find a flat rubber washer in the big box store and it sealed fine.

How to cap a 3/8” water feed


Multi-schema select statement doesn't work in PL/SQL procedure?

Question: I'm trying to create a procedure to run multiple PL/SQL statements, but I haven't gotten very far. The select statement works fine if I run it out of a procedure, but if I try to execute it inside one -- it can't find the shttran table. I'm guessing it might be a schema issue, but I have no idea how-to correct. Ideas?
CREATE OR REPLACE PROCEDURE REGREPORTUSER.findUnsent
IS
BEGIN
   INSERT INTO regreportuser.maltran (maltran.maltran_key,
                                      maltran.maltran_sent)
      SELECT shttran.shttran_id || shttran.shttran_seq_no AS maltran_key,
             'No' AS maltran_sent
        FROM saturn.shttran -- This is the table it can't find
       WHERE     TO_DATE (shttran.shttran_activity_date) > SYSDATE - 14
             AND shttran.shttran_user = 'WWW2_USER'
             AND shttran.shttran_id || shttran.shttran_seq_no NOT IN
                    (SELECT maltran.maltran_key FROM regreportuser.maltran);
END findUnsent;

Answer: Most likely, the problem is that the user that owns the stored procedure, REGREPORTUSER has access to the table saturn.shttran via a role rather than as a direct grant.  A definer's rights stored procedure cannot use privileges that are granted to a definer via a role.  It can only use privileges granted directly.
You can verify that this is, in fact, the problem by disabling roles in your SQL*Plus session.  If you run the command
SQL> set role none;

and then try to execute the SQL statement, you should get the same error.  In order to fix the problem, you need to give the grant directly
GRANT SELECT ON saturn.shttran
   TO REGREPORTUSER


Blocked User Functionality

Question: We have an iOS app that lets user post and share content. An admin can block certain users. Once a user is blocked the content they have posted will not be visible to anyone else. Additionally, we are considering not letting such users post any new content as long as they are blocked. I can think of following two ways of implementing the UX when a blocked user tries to post new content:

User posts content and then receives an alert saying that their request could not be completed because there was a problem with their account and they should contact the administrator to resolve this issue.
The UI elements that let user post content are disabled and overlaid with text that says that there is a problem withe their account and they should contact the administrator to resolve this issue.

I can't decide between the two. What is your opinion?
Comment: @septerr, my point was that, if there's no reason to let blocked users create posts, then your answer's obvious.
Comment: Is there a reason to let the blocked user create posts? Will they be saved and posted when the user is unblocked?
Comment: Hadn't thought of that yet. Good point!
Comment: I think it depends on why you are blocking them.  Are they blocked for being "trolls"?  Consider letting them continue to post without informing them that other users can't see their posts - they will continue to provide further evidence of their true behavior.  If it was a one-time mistake, your admin could quietly unblock them.  If it's a consistent pattern, leave them blocked, and you'll have evidence to provide to authorities if their behavior remains abusive.
Answer: My recommendation would be to go for the second option of disabling the option of even posting content and informing him that there is a problem with his account as that informs the user that there is a restriction on his account which must be resolved before he can continue to post content
Paypal does this with an message which says that they have limited access to the users account until he performs specific steps as shown below

That said, make it very easy for the user to contact the administrator (like the example above) so that the user knows exactly what his next step should be.
The problem with the first approach is that if you allow the user to post content and refuse him at the last minute, you are going to frustrate him as he might have spent a lot of time writing down the content and to be denied at the last minute would be frustrating.Also as Ken rightly pointed out, unless you have a mechanism to save the posts for the blocked user until unblocking, how can the user ensure that his content has been saved for publishing once his account is restored.

Blocked User Functionality


Is it ever "legal" to steal from a slain enemy's home?

Question: A few times, I've had to vanquish an enemy in their home.

 Most recently, Nepos the Nose.

However, even after they're defeated, all of the possessions in their house are still marked as "Steal" instead of "Take".  Are there still negative consequences for taking things from the houses of a slain enemy?
Answer: No, it is still not legal even if the owner is dead.  Taking those items will still mark them as stolen in your inventory.  However, since there are no witnesses left, you will probably be able to get away with it.  On top of that, you are probably unlikely to be the target of some payback by the now dead owner.
Having said that, the only place you can sell those stolen goods is still through a fence (which requires joining the thieves guild).  And the items will still be taken away if you are ever arrested on some other charge.
Comment: You can also fence things through the Fence perk. (Speechcraft level 90)
Comment: Unlikely? Don't know if being dead affects the chance, but I've had payback exacted by a dead man before.
Comment: @MatthewScharley I think that the general consensus is the payback was initiated before they died. Don't have a reference right now.
Comment: I find it interesting that pickpocketing from NPCs is stealing while they're alive, but "legal" when they're dead - and yet death does not remove the illegal status of taking items from their homes.


How to Set zoom using google map

Question: Need to set the zoom to get all location visible when i have more than one location on map . I am using google map api v3.
The code I am using is below
function initialize() {
    var myLatlng = new google.maps.LatLng(20.798362600000000000, -156.331925299999970000);

    var mapOptions = {
        zoom: 10,
        center: myLatlng,
        mapTypeId: google.maps.MapTypeId.ROADMAP
    };

    map = new google.maps.Map(document.getElementById('map-canvas'),mapOptions);

    addMarker(21.29539299, -157.8258667,'2525 South King Street,Honolulu HI 96826','Down to Earth','wholesale','restaurant');
    addMarker(20.87521935, -156.68008423,'658 Front St, lahaina HI 96761','Veg Out','wholesale','restaurant');
    addMarker(20.73747253, -156.45561218,'1847 S Kihei Rd,kihei HI 96753','Rodeo Kihei','wholesale','retailer');
    addMarker(20.9165287, -156.38095093,'127 Hana Hwy,Paia HI 96779','Test User','wholesale','retailer');
    addMarker(21.29226112, -157.82328796,'2525 South King Street,Honolulu HI 96826','Some User','wholesale','both');
    addMarker(20.91534615, -156.38002014,'49 Baldwin Ave.,Paia HI 96779','Mana Foods 2','wholesale','retailer');
    addMarker(20.88739586, -156.4566803,'340 Hana Hwy,, HI,Kahului HI 96732','Alive and Well 2','wholesale','restaurant');

    //addMarker(, ,'','','delivery');
}

google.maps.event.addDomListener(window, 'load', initialize);

Answer: Change the
  zoom: 10

to a lower number - lower number equals less zoom.
Try: zoom: 5
Example of zoom level 10 :
JSFiddle of Zoom 10
And now zoom level 5:
JSFiddle of Zoom 5
Comment: Sorry, it should be lower the number. Answer edited to reflect that

How to Set zoom using google map


Omit XML Declaration in DataSet.WriteXMLSchema

Question: i need to serialize a dataset in c# to xml for sending the data to a webservice. I cannot change the webservice so my code has to be changed to fit the requirements of the webservice.
I use dataset.WriteXmlSchema(stream) to write the schema and add dataset.WriteXml(stream) to add the data itself.
The result now looks like following:
<?xml version='1.0'?>
<xs:schema id='DocumentElement' xmlns='' xmlns:xs='http://www.w3.org/2001/XMLSchema' ...

Is there a chance to get rid of the <?xml version='1.0'?> declaration?
I need to encapsulate the XML result of the dataset into other xml data and the xml declation breaks the data i need to send. I didn't want to start with fuzzy string handling and i thought there must be something more straight forward.
Thanks
MadMaxapp
Answer: There seems no way to omit the xml declaration. I've implemented some code to remove the first line of the xml. Not nice but it works.


How $\gcd (s,t)=1$ implies $\gcd(s-t,s+t) =1$?

Question: Let $s$ and $t$ be two relatively prime odd numbers. We want to know the $d=\gcd(s-t,s+t).$ Let $d=2^lm$ thus $s-t=2^lmk_1$ and $s+t=2^lmk_2$ for $k_1$ and $k_2$ odd numbers and $\gcd(k_1, k_2)=1.$ Summing and subtracting both sides of two equality-es and diving by $2$ results in $s=2^lm \frac{(k_1+k_2)}{2}$ and  $t=2^lm \frac{(k_2-k_1)}{2}$ in which $\frac{(k_2 \pm k_1)}{2}$ are integers as both $k_1$ and $k_2$ are odd numbers and because $s$ and $t$ are relatively prime implies $l=0$ which is not possible since both $s-t$ and $s+t$ are even so must $l \ge 1$ !! Contradiction?
A rewritten version of this same question, for the author's benefit:
Let $s$ and $t$ be two distinct relatively prime odd numbers.
We want to compute $d=\gcd(s-t,s+t).$ Note that $s-t$ and $s+t$ are both nonzero because $s$ and $t$ are distinct.
Let $d=2^\ell m$, where $m$ is odd.  Then since $s-t$ and $s+t$ are both multiples of $d$, we have
\begin{align}
s-t&=2^\ell mk_1 \text{and}\\
s+t&=2^\ell mk_2
\end{align}
where $k_1$ and $k_2$ are both odd. Furthermore, $\gcd(k_1, k_2)=1,$ for if it were some other number $u > 1$, then $ud$ would divide both $s+t$ and $s-t$, contradicting the fact that $d$ is their greatest common divisor.
Finally, since both $s-t$ and $s+t$ are even and nonzero, we must have $\ell \ge 1$, which we'll use shortly.
Summing and subtracting both sides of these two equalities and dividing by $2$ gives
\begin{align}
s&=2^\ell m \frac{(k_1+k_2)}{2} \text{ and}\\
t& =2^\ell m \frac{(k_2-k_1)}{2}
\end{align}
Note that because $k_1$ and $k_2$ are both odd, their sum and difference are both even, hence
$\frac{(k_2 \pm k_1)}{2}$ are both integers.
Now $s$ and $t$ are relatively prime (given), so $\ell$ must be zero (otherwise $2^\ell$ would divide both, and the gcd could not be $1$).
On the other hand, we showed above that $\ell \ge 1$. That's a contradiction.
=====
Now there's definitely something screwy in the "proof" above, because Jyrki's example shows that the gcd is actually $2$. But you'll have a lot easier time finding the error now that the "proof" is actually written clearly and coherently.
Comment: $s=5,t=3\implies s+t=8, s-t=2$ and $\gcd(s+t,s-t)=?$
Comment: If $s$ and $t$ are two relatively prime odd numbers, then $\gcd(s+t,s-t)=2$.
Comment: Suggestion: It seems English may not be your first language. To help clarify your writing, try (a) using shorter sentences, and (b) introducing paragraph breaks. For instance, your first "thus" should start a new sentence. Also, try to put hypotheses first rather than last (so $\gcd(k_1, k_2) = 1$ should be right at the front of that sentence rather than at the end). Your third sentence is really about 3 or 4 sentences, and reading it leaves me breathless and confused, even though I know this material quite well. Does this matter? Maybe. Often writing clearly leads to improved understanding.
Comment: @Batominovski, Of course but I am asking about the contradiction. Please read whole OP not just the title.
Comment: @JohnHughes, of course it matters. Thanks a lot for your suggestion. :)
Answer: $k_1$ and $k_2$ don't have to be odd numbers, only one of them has to be. If $s$ and $t$ are both odd, $s+t$ and $s-t$ are both even, so you know that $d$ is also even.
Comment: It could be that $s-t=4\cdot\text{odd}$ but $s+t=2\cdot\text{odd}$.  In fact, one of $s+t$ and $s-t$ is $2$ modulo $4$, and the other is divisible by $4$.
Comment: I factored all 2's so that k_1 and k_2 be odds
Comment: Exactly, take $s=5$ and $t=1$ for example
Comment: I've edited your question to add a reformatted "proof"  that is (I believe) much more readable.


Change Animation Speed Series of Images

Question: I have a series of images, I want them to repeat. However, I want the first half to play in, for example 2 seconds, then the second half to play in 5 seconds.
It is quite easy to play a series of images, using the following
<code>   - (void) completeCycles:(int) cycles inhalePercentage:(int) inhalePercent exhalePercentage:(int) exhalePercent totalCycleTime:(int) time
   {
    NSMutableArray *textures = [NSMutableArray array];

    for (int i = 0; i < kNumberBreathingImages; i++) {
        NSString *textureName = [NSString stringWithFormat:@"breath%d.png", i];

        for (int i = 0; i < inhalePercent; i++) {
            [textures addObject:[UIImage imageNamed:textureName]];
        }
    }

    for (int i = kNumberBreathingImages - 1; i > 0; i--) {
        NSString *textureName = [NSString stringWithFormat:@"breath%d.png", i];
        for (int i = 0; i < exhalePercent; i++) {
            [textures addObject:[UIImage imageNamed:textureName]];
        }
    }

    self.animationImageView.animationImages = textures;
    self.animationImageView.animationDuration = time;
    self.animationImageView.animationRepeatCount = cycles;
    [self.animationImageView startAnimating];
    }
</code>
However, I want the first half of the animation to take x time and the second half to take y time.
I don't think the above will allow me to do this, just wondering what a better approach would be.
Pretty sure will need to use
<code>UIView animateWithDuration:animations: completion:
</code>
Thanks for any assistance.
This code creates this effect,
Comment: Just use a video clip (i.e. youtube), make it full screen, then take screen shot of the frames you want (pause video and scrub etc)
Comment: You can work by changing the number of frames, this would require to repeat some images on the base of the total images number. The best would be use keyframe animation.
Comment: @Andrea I've looked into this a little (Keyframe Ani) but couldn't find a decent example.
Comment: A bit off-topic, but where can one get / download sequences of the images like that online? Thanks in advance.
Answer: The animation system on UIImageView is very limited. I would suggest that you make your own implementation with say 2 image view.
You would than change the image in one imageview and the fade in and out using UIView animateWithDuration
I have written a method for you. Please note: I have not tested it.
It assumes you have your frames in a array called 'frames' and have two UIIMageView placed on top of each other called 'imgv1' and 'imgv2'
<code>-(void)performAnimationOfFrameAtIndex:(NSNumber*)indexNum
{
int index = [indexNum intValue];
if(index >= frames.count)
{
    return;
}
UIImage *img = [frames objectAtIndex:index];

UIImageView *imgIn;
UIImageView *imgOut;
if(index % 2 == 0)
{
    imgIn = imgv1;
    imgOut = imgv2;
}
else
{
    imgIn = imgv2;
    imgOut = imgv1;
}
imgIn.image = img;
[self.view sendSubviewToBack:imgIn];

[UIView animateWithDuration:0.1 animations:^
{
    imgIn.alpha = 1;
    imgOut.alpha = 0;
} completion:^(BOOL finished)
{
    [self performSelectorOnMainThread:@selector(performAnimationOfFrameAtIndex:) withObject:[NSNumber numberWithInt:index+1] waitUntilDone:NO];
}];

}
</code>
Thanks for the idea,
I changed your code above to get the desired effect I wanted, now it works perfect. The alpha was causing a "strobe" effect even when the duration is 0 seconds.
Here is my final code
Enjoy the 100 :-)
<code>- (void) performAnimationOfFrameAtIndex:(NSNumber*)indexNum
{
    int index = indexNum.intValue;
    if (index >= self.frames.count) return;

    UIImage *img = self.frames[index];

    UIImageView *imgIn;
    UIImageView *imgOut;

    float speed = (index <= self.frames.count / 2) ? 0.1 : 1; // first half : second half speed.

    if (index % 2 == 0) {
        imgIn = self.animationImageViewOne;
        imgOut = self.animationImageViewTwo;
    }
    else {
        imgIn = self.animationImageViewTwo;
        imgOut = self.animationImageViewOne;
    }

    imgIn.image = img;

    [self.view sendSubviewToBack:imgIn];
    [self performSelector:@selector(performAnimationOfFrameAtIndex:) withObject:[NSNumber numberWithInt:index+1]  afterDelay:speed];
}
</code>
Comment: Thanks for attempt, it swaps images - but this causes a "flash" like effect when they swap. But the main problem is i need, I want the first half to play in, for example 2 seconds, then the second half to play in 5 seconds.
Answer:
I don't think the above will allow me to do this, just wondering what a better approach would be.

Actually, it will. You just need to repeat the images as you form the sequence. For the images in the first group, repeat each one twice before going on to the next one. For the images in the second group, repeat each one five times before going on to the next one. Now set the time for the total animation to 7 seconds. Since there are about the same number of images in each group originally, you can readily see that this means the first group will take about 2 seconds and the second group will take about 5 seconds.
Comment: Yeah, this could work but I need exact duration flexibility, as first half could be 1,2,3,5 seconds and the second half could be 6,7,8,20 etc. So need total control of the duration.
Comment: The main problem with this its instead of 6 or 10 or whatever # images, i can have 100's - so its a waste of memory / and has a slow load time.

Change Animation Speed Series of Images


Pandas: adding a column to a dataframe from dictionary, when keys are the indices of the dataframe

Question: I know this question is similar to a lot of other questions, but I don't see an answer to this specific situation. Suppose I have a dataframe with unique index values, and I want to add a column with a dictionary where the keys are the index values. What is the easiest way to do this?
The best way that I've come up with is the following:
df = pd.DataFrame(index=['Aaron','Benjamin','Clinton','Daniel'])
dic = {'Aaron':25,'Benjamin':40,'Clinton':55,'Daniel':1}

df['nums']=dic
df['nums'].replace(dic)

I know that, if I want to add a column from a dictionary and the keys are another column, I can use the .map command. Is there a way to use this when the keys are the index values? I can't seem to make this work.
Answer: Use a list comprehension;
df['nums'] = [dic.get(i) for i in df.index]
df

          nums
Aaron       25
Benjamin    40
Clinton     55
Daniel       1

Answer: Adding get when using map
df['num']=df.index.map(dic.get)
df
Out[1035]:
          num
Aaron      25
Benjamin   40
Clinton    55
Daniel      1

Answer: In [28]: df['new'] = pd.Series(dic)

In [29]: df
Out[29]:
          new
Aaron      25
Benjamin   40
Clinton    55
Daniel      1

Comment: I think this is close to what I want, I should have specified that I may already have existing columns, in which case I should simply do df['new'] = pd.Series(dic), correct?
Comment: Thanks! I don't know enough yet to know which is the best answer, all of these were helpful


How to design an application - passing application option values to custom functions

Question: I'm building a C# Windows Forms application that will load music files from given directory, do some operations with these and save them.
I have a custom class with music specific methods (functions). I have created it's instance in main form class to call these methods with given arguments. The methods not only need data to work with (i.e. filepath) but sometimes they also need to load some values from application options (i.e. which music file extensions the application should load from given directory). What's the best approach to load those options?
Should I just create an instance of options class in the main form class and pass the whole instance to every function(method) I call? Or should I store the options class instance in my custom music class?
Main Class:
public partial class mainForm : Form
{
    private MusicFunctions mf = new MusicFunctions();
    public mainForm()
    {...}

    private void openToolStripMenuItem_Click(object sender, EventArgs e)
    {
      ...
      mf.loadMusicFiles(path, true);
      // btw what's the best approach to load data into form objects (i.e. DataGridView)? Should I pass those as arguments to my functions or create a new object in my custom function and return it as a function return value?
    }

    private void optionsChangeButton_Click(object sender, EventArgs e)
    {
        // I would have to create functions inside musicFunction class to be able to change options
        int a = 10;
        mf.ChangeOptions(a);
        ...
    }

}

MusicFunctions Class
public class MusicFunctions
{
    private MyOptions options;
    public class MusicFunctions()
    {
        options = new Options();
    }

    public void loadMusicFiles(string filepath, bool includeSubfolders = false)
    {
      foreach (string ext in options.Extensions)
      {
           ....
      }
    }
}

Comment: Neither. You might want to get acquainted with the MVP pattern.
Answer: It depends on the scope of those options. If those options are read only once and have to do with the program, the class instance should be held by the application (or you could store the options in a .config file and use the Framework classes to read them in that case). If the options have to do with a music, the instance of the class representing that song should hold it.
Also check the suggestion of @EliAlgranti in the comments in your question.


Javascript to make a text field have capital first letter and rest lower case

Question: I am using a form software that has limited editing capabilities, however allows to add java script. Normally I would like to use PHP for something like this, but in this case i will have to use Javascript, which I have very little experience with.
Essentially on my landing page, I have a form in which people can submit.
First Name
Last Name
Email
etc.
the problem is - I mail merge the submissions, and when people enter their name as BOB SMITH or bob smith and not Bob Smith, it makes it look unprofessional when I send them this email. So I would like to add a javascript to this landing page that when the form submits, it converts the strings in the first_name text field and the last_name text field to have the first letter capitalized, and the rest lower case. Another problem is I do not think I can edit the form properties, so if at all possible this javascript would essentially go at the top of the page, and hopefully I dont have to edit the text field properties to activate it...any help would be greatly appreciated.
Thanks
Comment: name = name[0].toUpperCase() + name.substr(1).toLowerCase();
Comment: Doesn't it look unprofessional when you send mail to Mccoy and O'brien? In any case, if someone wants to write their name in all caps they're unlikely to be bothered when someone else does it too.
Comment: Also, you can modify what the user has typed after the submit-button has been pressed with a onSubmitHandler. `document.getElementById('theForm').onsubmit = function() {
    var firstName = document.getElementById('firstName');
    firstName.value = firstName.value[0].toUpperCase() + firstName.value.substr(1).toLowerCase();
  };`
Comment: Juhana, the unprofessional thing is when someone can't write his Own Name ProPerly :)  But this solution decreases the problem by 95%.
Comment: See [*Convert first letter to uppercase on input box*](http://stackoverflow.com/questions/14688141/convert-first-letter-to-uppercase-on-input-box).
Answer: If you have multiple names / words, this will get them all...
function getProperCase(sText) {
  return sText.replace(
    /([^\W_]+[^\s-]*) */g,
    function(s){
      return s.charAt(0).toUpperCase() + s.substr(1).toLowerCase();
    }
  );
}

Answer: Here is a Javascript Gist for building human-readable names I recently created that does just what you need plus a little extra.
I wont try to explain and instead, here are some examples:
//dan macdonald -> Dan MacDonald [call true]
//dAN mCdOnAlD  -> Dan McDonald [call true]
//paz y MIño    -> Paz y Miño [call true]
//BEN d'hosier  -> Ben D'Hosier
//sara ma'afala -> Sara Ma'afala

Include in your page like so:

Or access the raw file at https://gist.githubusercontent.com/isaacdozier/5ae92c1da9622c77df4c9a70a9f9a849/raw/a81c877e77a3c0c3a795ac40bbf6721950cb2e05/read-names.js
Call the fuction like this:
capsFullName('john SMITH')

which outputs 'John Smith'
OR THIS
capsFullName('sara y gonzalez', true)

which outputs 'Sara y Gonzalez'
note: capsFullName('sara y gonzalez') outputs 'Sara Y Gonzalez'
Answer: You could use the function below:
function capitalizeFirstLetter(str) {
    return str.charAt(0).toUpperCase() + str.slice(1).toLowerCase();
}

It receives a parameter, and returns the first letter uppercased + the rest of your string lowercased.
Answer: I think it's almost like Will P said, but:
function ucFirst(s) {
    return s.substr(0,1).toUpperCase() + s.substr(1).toLowerCase();
}

function camelCase(s) {
    var a=s.split(" ");
    for(var i in a) a[i]=ucFirst(a[i]);
    return a.join(" ");
}

...because you need the last name Cameled too.
(And now you can bind this to the change event.  Or wherever you see fit.)
According to Will, the final version would look like:
$(function () {
    $("input").on("change", function () {
        $(this).val(camelCase($(this).val()));
    });
});

Hope I didn't mess up the brackets :)
Comment: Yup, your solution was perfect for that case.  That's why I upvoted it.


ExecuteFunction not invoking the function

Question: I have created a Microsoft Office Add-in React (TypeScript) Project using yo office.
I have changed my manifest.xml to include
<Control xsi:type="Button" id="Contoso.GrabSelectionButton">

  <Supertip>
    <Title resid="Contoso.GrabSelectionButton.Label" />
    <Description resid="Contoso.GrabSelectionButton.Tooltip" />
  </Supertip>
  <Icon>
    <bt:Image size="16" resid="Contoso.tpicon_16x16" />
    <bt:Image size="32" resid="Contoso.tpicon_32x32" />
    <bt:Image size="80" resid="Contoso.tpicon_80x80" />
  </Icon>

  <Action xsi:type="ExecuteFunction">
    <FunctionName>grabSelection</FunctionName>
  </Action>
</Control>

The <FunctionFile resid="Contoso.DesktopFunctionFile.Url" /> is set correctly - I did not change it from the template default.
I added the method in function-file.ts like this
(() => {
  Office.initialize = () => { console.log("this gets logged..."); };

  function grabSelection(event){
    console.log("grabSelection invoked! - this does not get logged");

    event.completed();
  }

})();

and I have also tried like this
   (() => {
      Office.initialize = () => { console.log("this gets logged..."); };
    })();

export function grabSelection(event){
  console.log("grabSelection invoked! - this does not get logged");
  event.completed();
}

I can see it compiled and included at runtime but the function does not get invoked...
why is the function not being invoked? Is it a problem with webpack not exporting the function correctly?
Comment: turns out others have stumbled across this issue: https://github.com/OfficeDev/generator-office/issues/424
Answer: I managed to fix this by attaching my function to the global namespace like this:
(() => {
  Office.initialize = () => {
    console.log("function file loaded...!");
   };
  })();

function grabSelection(event: any): void {
    console.log("i got invoked!!!");
    event.completed();
}

const _global = (window /* browser */ || global /* node */) as any;
_global.grabSelection= grabSelection;


TypeError: 'Vector' object is not iterable

Question: I was trying to compute the intersection point of two lines, but constantly get "TypeError: 'Vector' object is not iterable"
I've tried to search for the answer but failed. How should I fix this, pls?
here's the code:
from decimal import Decimal, getcontext

from vector import Vector

getcontext().prec = 30

class Line(object):

    NO_NONZERO_ELTS_FOUND_MSG = 'No nonzero elements found'

    def __init__(self, normal_vector=None, constant_term=None):
        self.dimension = 2

        if not normal_vector:
            all_zeros = ['0']*self.dimension
            normal_vector = Vector(all_zeros)
        self.normal_vector = normal_vector

        if not constant_term:
            constant_term = Decimal('0')
        self.constant_term = Decimal(constant_term)

        self.set_basepoint()

    def __eq__(self, ell):
        if self.normal_vector.is_zero():
            if not ell.normal_vector.is_zero():
                return False
            else:
                diff = self.constant_term - ell.constant_term
                return MyDecimal(diff).is_near_zero()
        elif ell.normal_vector.is_zero():
            return False

        if not self.is_parallel_to(ell):
            return False

        x0 = self.basepoint
        y0 = ell.basepoint
        basepoint_difference = x0.minus(y0)

        n = self.normal_vector
        return basepoint_difference.is_orthogonal_to(n)

    def is_parallel_to(self, ell):
        n1 = self.normal_vector
        n2 = ell.normal_vector
        return n1.is_parallel_to(n2)

    def set_basepoint(self):
        try:
            n = self.normal_vector
            c = self.constant_term
            basepoint_coords = ['0']*self.dimension

            initial_index = Line.first_nonzero_index(n)
            initial_coefficient = n[initial_index]

            basepoint_coords[initial_index] = c/initial_coefficient
            self.basepoint = Vector(basepoint_coords)

        except Exception as e:
            if str(e) == Line.NO_NONZERO_ELTS_FOUND_MSG:
                self.basepoint = None
            else:
                raise e

    def intersection_with(self, ell):
        try:
            A, B = self.normal_vector.coordinates
            C, D = ell.normal_vector.coordinates
            k1 = self.constant_term
            k2 = ell.constant_term

            x_numerator = D*k1 - B*k2
            y_numerator = -C*k1 + A*k2
            one_over_denom = Decimal('1')/(A*D - B*C)

            return Vector([x_numerator, y_numerator]).times_scalar(one_over_denom)

        except ZeroDivisionError:
            if self == ell:
                return self
            else:
                return None

    def __str__(self):

        num_decimal_places = 3

        def write_coefficient(coefficient, is_initial_term=False):
            coefficient = round(coefficient, num_decimal_places)
            if coefficient % 1 == 0:
                coefficient = int(coefficient)

            output = ''

            if coefficient < 0:
                output += '-'
            if coefficient > 0 and not is_initial_term:
                output += '+'

            if not is_initial_term:
                output += ' '

            if abs(coefficient) != 1:
                output += '{}'.format(abs(coefficient))

            return output

        n = self.normal_vector

        try:
            initial_index = Line.first_nonzero_index(n)
            terms = [write_coefficient(n[i], is_initial_term=(i==initial_index)) + 'x_{}'.format(i+1)
                     for i in range(self.dimension) if round(n[i], num_decimal_places) != 0]
            output = ' '.join(terms)

        except Exception as e:
            if str(e) == self.NO_NONZERO_ELTS_FOUND_MSG:
                output = '0'
            else:
                raise e

        constant = round(self.constant_term, num_decimal_places)
        if constant % 1 == 0:
            constant = int(constant)
        output += ' = {}'.format(constant)

        return output

    @staticmethod
    def first_nonzero_index(iterable):
        for k, item in enumerate(iterable):
            if not MyDecimal(item).is_near_zero():
                return k
        raise Exception(Line.NO_NONZERO_ELTS_FOUND_MSG)

class MyDecimal(Decimal):
    def is_near_zero(self, eps=1e-10):
        return abs(self) < eps

ell1 = Line(normal_vector = Vector(['4.046', '2.836']), constant_term = '1.21')
ell2 = Line(normal_vector = Vector(['10.115', '7.09']), constant_term = '3.025')
print 'intersection 1:', ell1.intersection_with(ell2)

ell1 = Line(normal_vector = Vector(['7.204', '3.182']), constant_term = '8.68')
ell2 = Line(normal_vector = Vector(['8.172', '4.114']), constant_term = '9.883')
print 'intersection 2:', ell1.intersection_with(ell2)

ell1 = Line(normal_vector = Vector(['1.182', '5.562']), constant_term ='6.744')
ell2 = Line(normal_vector = Vector(['1.773', '8.343']), constant_term = '9.525')
print 'intersection 3:', ell1.intersection_with(ell2)

=============================================================
here's the error message:
Traceback (most recent call last):
  File "/Users/Tristan/Desktop/line.py", line 146, in <module>
    ell1 = Line(normal_vector = Vector(['4.046', '2.836']), constant_term = '1.21')
  File "/Users/Tristan/Desktop/line.py", line 24, in __init__
    self.set_basepoint()
  File "/Users/Tristan/Desktop/line.py", line 67, in set_basepoint
    raise e
TypeError: 'Vector' object is not iterable
[Finished in 0.0s with exit code 1]
[shell_cmd: python -u "/Users/Tristan/Desktop/line.py"]
[dir: /Users/Tristan/Desktop]
[path: /usr/bin:/bin:/usr/sbin:/sbin]

=============================================================
and here's the code in vector.py:
from math import sqrt, acos, pi
from decimal import Decimal, getcontext

getcontext().prec = 30

class Vector(object):

    CANNOT_NORMALIZE_ZERO_VECTOR_MSG = 'cannot nomalize the zero vector.'
    CANNOT_COMPUTE_ANGLE_WITH_ZERO_VECTOR_MSG = 'Cannot compute an angle\
                                             with the zero vector.'
    NO_UNIQUE_PARALLEL_COMPONENT_MSG = 'there is no unique parallel\
                                     commponent.'
    NO_UNIQUE_ORTHOGONAL_COMPONENT_MSG = 'there is no unique orthogonal\
                                     commponent.'

    def __init__(self, coordinates):
        try:
            if not coordinates:
                raise ValueError
            self.coordinates = tuple([Decimal(x) for x in coordinates])
            self.dimension = len(self.coordinates)

        except ValueError:
            raise ValueError('The coordinates must be nonempty')

        except TypeError:
            raise TypeError('The coordinates must be an iterable')

    def __str__(self):
        return 'Vector: {}'.format(self.coordinates)

    def __eq__(self, v):
        return self.coordinates == v.coordinates

    def plus(self, v):
        new_coordinates = [x + y for x,y in zip(self.coordinates, v.coordinates)]
        return Vector(new_coordinates)

    def minus(self, v):
        new_coordinates = [x - y for x,y in zip(self.coordinates, v.coordinates)]
        return Vector(new_coordinates)

    def times_scalar(self, c):
        new_coordinates =[Decimal(c)*x for x in self.coordinates]
        return Vector(new_coordinates)

    def magnitude(self):
        coordinates_squared = [x**2 for x in self.coordinates]
        return Decimal(sum(coordinates_squared)).sqrt()

    def normalized(self):
        try:
            magnitude = self.magnitude()
            return self.times_scalar(Decimal('1.0')/Decimal(magnitude))
        except ZeroDivisionError:
            raise Exception(self.CANNOT_NORMALIZE_ZERO_VECTOR_MSG)

    def dot(self, v):
        return sum([x*y for x, y in zip(self.coordinates, v.coordinates)])

    def angle_with(self, v, in_degrees = False):
        try:
            u1 = self.normalized()
            u2 = v.normalized()
            angle_in_radians = Decimal(acos(u1.dot(u2)))

            if in_degrees:
                degrees_per_radian = Decimal('180.0')/Decimal(pi)
                return angle_in_radians * degrees_per_radian
            else:
                return angle_in_radians

        except Exception as e:
            if str(e) == self.CANNOT_NORMALIZE_ZERO_VECTOR_MSG:
                raise Exception(self.CANNOT_COMPUTE_ANGLE_WITH_ZERO_VECTOR_MSG)
            else:
                raise e

    def is_orthogonal_to(self, v, tolerance = 1e-10):
        return abs(self.dot(v)) < tolerance

    def is_parallel_to(self, v):
        return (self.is_zero()
                or v.is_zero() or
                self.angle_with(v) == 0 or
                self.angle_with(v) == pi)

    def is_zero(self, tolerance = 1e-10):
        return self.magnitude() < tolerance

    def projection(self, v):
        try:
            unit_v = v.normalized()
            return (unit_v).times_scalar(self.dot(unit_v))
        except Exception as e:
            if str(e) == self.CANNOT_NORMALIZE_ZERO_VECTOR_MSG:
                raise Exception(self.NO_UNIQUE_PARALLEL_COMPONENT_MSG)
            else:
                raise e

    def orthogonal(self, v):
        try:
            return self.minus(self.projection(v))
        except Exception as e:
            if str(e) == self.NO_UNIQUE_PARALLEL_COMPONENT_MSG:
                raise Exception(self.NO_UNIQUE_ORTHOGONAL_COMPONENT_MSG)
            else:
                raise e

    def decompose(self, v):
        return str(self.projection(v)) + '+' + str(self.orthogonal(v))

    def cross_products(self, v):
        try:
            x_1, y_1, z_1 = self.coordinates
            x_2, y_2, z_2 = v.coordinates
            new_coordinates = [y_1*z_2 - y_2*z_1,
                -(x_1*z_2 - x_2*z_1), x_1*y_2 - x_2*y_1]
            return Vector(new_coordinates)

        except ValueError as e:
            msg = str(e)
            if msg == 'need more than 2 values to unpack':
                self_embedded_in_R3 = Vector(self.coordinates + ('0',))
                v_embedded_in_R3 = Vector(v.coordinates + ('0',))
                return self_embedded_in_R3.cross_products(v_embedded_in_R3)
            elif (msg == 'too many values to unpack' or
                msg == 'need more than 1 value to unpack'):
                raise Exception('only defined in two 3-dimensions')
            else:
                raise e

    def area_of_parallelogram(self, v):
        return (self.cross_products(v)).magnitude()

    def area_of_triangle(self, v):
        return self.area_of_parallelogram(v)/Decimal('2.0')

Comment: Welcome to StackOverflow. Could you try to minimize the required code yourself (see [mcve]) and [edit] your question? Currently that's just a huge code dump.
Comment: thanks, I will stick to that rule from now on.
Answer: The error is coming from the following line in set_basepoint function:
TypeError: 'Vector' object is not iterable
> test.py(136)first_nonzero_index()
    135     def first_nonzero_index(iterable):
--> 136         for k, item in enumerate(iterable):
    137             if not MyDecimal(item).is_near_zero():

ipdb> up
> test.py(57)set_basepoint()
     56
---> 57         initial_index = Line.first_nonzero_index(n)
     58         initial_coefficient = n[initial_index]

Meaning the line raising exception is initial_index = Line.first_nonzero_index(n).
The line with the error was hidden because of the overly broad try/except block in set_basepoint, which I commented out to get to the above.
I am not sure what was wanted there, perhaps Line.first_nonzero_index(n.coordinates) instead which does not break.
The code in first_nonzero_index is doing for k, item in enumerate(iterable): and iterable was a Vector which is not an iterable, hence the error.
In general, keep try/except blocks as small as possible so as not to hide the code that actually raised the exception.
Also checking str(e) equality in exception handling is bad practice, that will break if the string representation of the exception changes. Use isinstance on the exception class instead.
Comment: Thank you danny, but after this modification, there rises another error, it reads "TypeError: 'Vector' object does not support indexing".
Comment: Well said.  I was just typing up my own version of this, but you've now said everything I was planning to say.
Comment: @Eric, a [Minimal, Complete and Verifiable example](http://stackoverflow.com/help/mcve) will need to be shown when asking questions. 'Does not support' indexing is the error raised when doing things like `n[1]` on an object that.. does not support indexing, much like the previous iteration error. From that, and the above guidelines on error handling, it should be easy to understand where that error is coming from.
Comment: @danny Problem solved, thanks!  BTW this is my first question on stackoverflow.  I will enhance my way of asking question according to the rules from now on.
Comment: No problem, glad it is resolved and welcome to Stack Overflow. Also please accept an answer if it solved the question, or editing your question with a solution you have found.
Answer:     def set_basepoint(self):
    try:
        n = self.normal_vector
        # print(n)  # Vector: (Decimal('4.046'), Decimal('2.836'))
        c = self.constant_term
        basepoint_coords = ['0']*self.dimension

        initial_index = Line.first_nonzero_index(n.coordinates)
        # print(initial_index)  # 0

        initial_coefficient = n.coordinates[initial_index]
        # print(initial_coefficient)  # 4.046
        basepoint_coords[initial_index] = c/initial_coefficient
        self.basepoint = Vector(basepoint_coords)

    except Exception as e:
        if str(e) == Line.NO_NONZERO_ELTS_FOUND_MSG:
            self.basepoint = None
        else:
            raise e

solve this bug,we should first learn Vector class seriously.
Answer: Vector type is not iterable because of
 def __str__(self):
        return 'Vector: {}'.format(self.coordinates)

the str method actually stores a string not a tuple.
the fix be using Line.first_nonzero_index(n.coordinates) instead of Line.first_nonzero_index(n.coordinates) in all the instances of calling  first_nonzero_index() and initial_coefficient = n.coordinates[initial_index] instead of initial_coefficient = n[initial_index]. also, there is another bug
in Line class
in the str method :
try:
    initial_index = Line.first_nonzero_index(n.coordinates)
   terms = [write_coefficient(n[i], is_initial_term=(i==initial_index))+'x_{}'.format(i+1)
       for i in range(self.dimension) if round(n.coordinates[i], num_decimal_places) != 0]
            output = ' '.join(terms)

vector class is also not indexable do replace each n witn n.coordinates


Read props from parent component in a list of dynamic components

Question: I have a problem to read the passed data via props in Vue.js from parent to child. I have a list of components
components: [
        {
          name: "Cart Overview",
          component: "CartOverview",
          props: this.shopperCart
        },
        {
          name: "Bank Account Overview",
          component: "BankAccountOverview",
          props: {}
        },
        { name: "Verification", component: "Verification", props: {} },
        {
          name: "Completion Message",
          component: "CompletionMessage",
          props: {}
        }
      ]

The variable "shopperCart" is set by a request from a backend.
Template of the parent component

  <component
    :is="checkoutComponents[currentStep].component"
    v-bind="checkoutComponents[currentStep].props"
  ></component>

The user can navigate through the components with a next step button who sets the variable currentStep.
Example of one child component
<template>

Cart Oerview

    {{ shopperCart }}

</template>

The components lie on a modal. The log output only shows up displaying undefined when I refresh the page, where I can open the modal.
Can someone please help me?
Best regards,
A. Mehlen
Answer: I found myself a solution. I changed in the parent component the v-bind with :data

  <component
    :is="checkoutComponents[currentStep].component"
    :data="checkoutComponents[currentStep].props"
  ></component>

and in the child component the name of the prop
<template>

Cart Oerview

    {{ data }}

</template>

Now it works :-)


The groups with symmetric subgroups lattice

Question: Let $G$ be a group and $\frak L (G)$ be set of all subgroups of $G$. Clearly, $\frak L (G)$ is a lattice.
If we know that $\frak L (G)$ is symmetric then what can be said about the group $G$ ?
Any reference and observation would be appriciated.
Example: Elemantary abelian $p$ groups, the groups that all Sylow subgroups of prime orders are such examples.
Comment: The lattices that you call 'symmetric' are usually called 'self-dual'. All finite abelian groups have self-dual subgroup lattices.
Comment: Does "symmetric" mean [one of these things](http://en.wikipedia.org/wiki/Modular_lattice#Modular_pairs_and_related_notions)?
Comment: @anon: Raughly speaking, Hasse Diagram of the lattice is same from Top to botton or botton to top.
Comment: @anon: Precisesly, If we put another order "$\leq *$" by   $H\leq * K$ if $K\leq H$ then the new lattice is isomorphic to the previous one.
Comment: @anon: I hope it is clear now ?
Answer: This is covered in Chapter 8 of Schmidt's book "Subgroup lattices of groups"; everything in this answer is there, but I summarize it here for convenience.
Say a group $G$ has a dual $\hat{G}$ if their subgroup lattices are anti-isomorphic. Your question is about when $G$ is dual to itself.
Baer (1939) proved that every group w/ dual is torsion, i.e. all its elements have finite order.
For locally finite groups (which means every finitely generated subgroup is finite), there is a complete classification of groups with duals. (This is Theorem 8.2.2 in Schmidt, due to Suzuki and Zacher):
If $G$ is a locally finite group, and $\delta$ is a lattice anti-isomorphism to $L(\hat{G})$, then:

$G = \prod_{\lambda} G_{\lambda}$ where the $G_{\lambda}$ are coprime to one another
$\hat{G} = \prod_{\lambda} \delta(\hat{G}_\lambda)$, where $\hat{G}_\lambda := \langle G_{\mu} : \mu \neq \lambda \rangle$ and the $\delta(\hat{G}_\lambda)$ are coprime to one another
For every $\lambda$, there exists (not nec. distinct) primes $p,q$ such that one of the following holds:

$G_\lambda$ is a cyclic $p$-group, $\delta(\hat{G}_\lambda)$ is a cyclic $q$-group, or
$G_\lambda$ and $\delta(\hat{G}_\lambda)$ are both either elementary abelian of order $p^n$ or a semi-direct product of an elementary abelian group of order $p^{n-1}$ by a group of order $q$, or
$G_\lambda$ and $\delta(\hat{G}_\lambda)$ are finite non-Hamiltonian $p$-groups with modular subgroup lattices

Maybe from these more can be said when $G$ is self-dual ($G = \hat{G}$)...


call objective c method from cpp method

Question: I have a cpp class like that..
class MyContactListener : public b2ContactListener
{
    int countContact;
    ///this is an objective c class...
    HelloWorld *hel;

        public:
    void EndContact(b2Contact* contact)
    {
            ///initialize objective c object
        hel=[[HelloWorld alloc] autorelease];
            ///call objective c method.........
        [hel beginContact];

    }

 };

inside cpp class i call a objective c method.the objective c method looks like..
-(void )beginContact
{
    shakeCounter++;
    [_label setString:[NSString stringWithFormat:@"%d",shakeCounter]];

}

The objective c method get called....and also the variable shakeCounter increased.....but
_label string is not updated...._label is initialized properly and work properly if i called
the objective c method from objective c class using self....
Can anyone help???
Comment: Please `NSLog(@"%@", _label);` after `shakeCounter++;` and show the output.
Comment: This question is related to [Unable to call an Objective C method from a C function](http://stackoverflow.com/questions/304885/unable-to-call-an-objective-c-method-from-a-c-function).
Comment: yes....i saw this and i got null....
Answer: Use a Delegate in the Contact listener to call the methods on the objective-c class:
class MyContactListener : public b2ContactListener
{
    public:
    MyDelegateClass *delegate;

    void BeginContact(b2Contact* contact) {
        [delegate beginContact:contact];
    }

    void EndContact(b2Contact* contact) {
        [delegate endContact:contact];
    }

    void PreSolve(b2Contact* contact, const b2Manifold* oldManifold) {
        [delegate preSolve:contact manifold:oldManifold];
    }

    void PostSolve(b2Contact* contact, const b2ContactImpulse* impulse)  {
        [delegate postSolve:contact impulse:impulse];
    }
};

Declare a Protocol for the Delegate:
#import "Box2D.h"

@protocol B2ContactListener <NSObject>

-(void) beginContact:(b2Contact*) contact;
-(void) endContact:(b2Contact*) contact;
-(void) preSolve:(b2Contact*) contact manifold:(const b2Manifold*) oldManifold;
-(void) postSolve:(b2Contact*) contact impulse:(const b2ContactImpulse*) impulse;

@end

Declare the interface that implements the protocol:
@interface MyDelegateClass: CCLayer <B2ContactListener> {
  //interface code here.
}
@end

@implementation MyDelegateClass

-(void) beginContact:(b2Contact*) contact {
    //implement your code here
}
-(void) endContact:(b2Contact*) contact {
    //implement your code here
}
-(void) preSolve:(b2Contact*) contact manifold:(const b2Manifold*) oldManifold{
    //implement your code here
}
-(void) postSolve:(b2Contact*) contact impulse:(const b2ContactImpulse*) impulse{
    //implement your code here
}
@end

Construct the delegate and the assign it in your code. Set it in your world object:
MyContactListener *listener = new MyContactListener();
listener->delegate = self;
world_->SetContactListener(listener);

Now your objective-c class will receive the events.
Answer: oww....i solved it....
just put this in top of project
#define PTM_RATIO 32
#import "HelloWorldScene.h"

id refToSelf;

and initialize this in onload or something like that...
self = [super init];
refToSelf = self;

Now call the objective c method using this....
    [refToSelf beginContact];

it will work...........
Comment: Actually, no you haven't solved the problem.  The fact that it appears to work just shows you are doing something fundamentally wrong.
Comment: I'm receiving runtime memory leaked warnings with ARC enabled using above code. http://stackoverflow.com/questions/11840943/runtime-memory-leaked-warnings-when-executing-objective-c-code-within-c-code-wit
Answer: I'm not sure if it is the source of your problem, but this line:
hel=[[HelloWorld alloc] autorelease];

Should be:
hel=[[[HelloWorld alloc] init] autorelease];

Answer: Your code is totally confused.  I assume that you want to create the Objective-C object inside endContact and persist it until some later point.  At the moment you are creating a new object each time but you are not initialising it at all.  Your code is never going to work.
The C++ method should probably look something like:
void EndContact(b2Contact* contact)
{
    // release old object and initialize a new one
    [hel release];
    hel = [[HelloWorld alloc] init];
        ///call objective c method.........
    [hel beginContact];

}

or
void EndContact(b2Contact* contact)
{
    HelloWorld* hel  = [[HelloWorld alloc] init];
    [hel beginContact];
    [hel release];
}

Depending on how long you want your hel object to last for.
I don't know why _label is not being updated.  You'll need to show us your code for initialising it to answer that.
Answer: Few things:
Is _label an NSString, or an NSMutableString? An NSString won't respond to setString, because it is fixed at creation.
This:

self = [super init];
refToSelf = self;

Is odd, to say the least. You're basically saying self = self here. You never need to call init on your self.
I'd strongly recommend having a look at Apple's excellent intro here: The Objective C Language

call objective c method from cpp method


Weird behaviour of SwiftUI Picker View when the other view getting new value from AVCaptureDevice API

Question: I'm new to SwiftUI and Combine. What I trying to build is a manual camera app, and there's only 4 UI component:

CaptureButton for making a shot from the camera
FocusPicker for controlling manually camera focus exposure
OffsetView for displaying a level of exposure
CameraPreviewRepresentable for integrating UIKit camera into SwiftUI view

Also added Privacy requests into.Info.plist file from a user to allow camera feature and saving to Apple Photo App

For updating data and passing it to the UI, I'm using CameraViewModel, currentCameraSubject and currentCamera Publisher to showing new values from AVCaptureDevice and setting it to CameraViewModel.
And I'm noticing a really interesting behavior/bug of FocusPicker when I start interacting with it and piking a new focus it constantly get back to started position and when OffsetView is getting a new value each time.
But interesting enough for example when OffsetView has the same value then FocusPicker is doing normal. And I do not know why this is happening. Please help, it's really frustrating to fix for me.
By the way, it will only work on a real device only.
Here's all the code:
import SwiftUI

//@main
//struct StackOverflowCamApp: App {
//    var cameraViewModel = CameraViewModel(focusLensPosition: 0)
//    let cameraController: CustomCameraController = CustomCameraController()
//
//    var body: some Scene {
//        WindowGroup {
//            ContentView(cameraViewModel: cameraViewModel, cameraController: cameraController)
//        }
//    }
//}

struct ContentView: View {

    @State private var didTapCapture = false
    @ObservedObject var cameraViewModel: CameraViewModel
    let cameraController: CustomCameraController

    var body: some View {

        VStack {
            ZStack {
                CameraPreviewRepresentable(didTapCapture: $didTapCapture, cameraViewModel: cameraViewModel, cameraController: cameraController)
                    .frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .center)

                VStack {
                    FocusPicker(selectedFocus: $cameraViewModel.focusChoice)

                    Text(String(format: "%.2f", cameraViewModel.focusLensPosition))
                        .foregroundColor(.red)
                        .font(.largeTitle)
                }
                .frame(maxWidth: .infinity, alignment: .leading)
            }
            .edgesIgnoringSafeArea(.all)

            Spacer()

            OffsetView(levelValue: cameraViewModel.exposureTargetOffset, height: 100)
                .frame(maxWidth: .infinity, alignment: .leading)

            CaptureButton(didTapCapture: $didTapCapture)
                .frame(width: 100, height: 100, alignment: .center)
                .padding(.bottom, 20)
        }
    }
}

struct CaptureButton: View {
    @Binding var didTapCapture : Bool

    var body: some View {
        Button {
            didTapCapture.toggle()

        } label: {
            Image(systemName: "photo")
                .font(.largeTitle)
                .padding(30)
                .background(Color.red)
                .foregroundColor(.white)
                .clipShape(Circle())
                .overlay(
                    Circle()
                        .stroke(Color.red)
                )
        }
    }
}

struct OffsetView: View {

    var levelValue: Float
    let height: CGFloat

    var body: some View {

        ZStack {
            Rectangle()
                .foregroundColor(.red)
                .frame(maxWidth: height / 2, maxHeight: height, alignment: .trailing)

            Rectangle()
                .foregroundColor(.orange)
                .frame(maxWidth: height / 2, maxHeight: height / 20, alignment: .trailing)
                .offset(x: 0, y: min(CGFloat(-levelValue) * height / 2, height / 2))
        }
    }
}

struct FocusPicker: View {

    @Binding var selectedFocus: FocusChoice

    var body: some View {

        Picker(selection: $selectedFocus, label: Text("")) {
            ForEach(0..<FocusChoice.allCases.count) {
                Text("\(FocusChoice.allCases[$0].caption)")
                    .foregroundColor(.white)
                    .font(.subheadline)
                    .fontWeight(.medium)
                    .tag(FocusChoice.allCases[$0])
            }
            .animation(.none)
            .background(Color.clear)
            .pickerStyle(WheelPickerStyle())
        }
        .frame(width: 60, height: 200)
        .border(Color.gray, width: 5)
        .clipped()
    }
}

import SwiftUI
import Combine
import AVFoundation

struct CameraPreviewRepresentable: UIViewControllerRepresentable {

    @Environment(\.presentationMode) var presentationMode
    @Binding var didTapCapture: Bool
    @ObservedObject var cameraViewModel: CameraViewModel

    let cameraController: CustomCameraController

    func makeUIViewController(context: Context) -> CustomCameraController {
        cameraController.delegate = context.coordinator

        return cameraController
    }

    func updateUIViewController(_ cameraViewController: CustomCameraController, context: Context) {

        if didTapCapture {
            cameraViewController.didTapRecord()
        }

        // checking if new value is differnt from the previous value
        if cameraViewModel.focusChoice.rawValue != cameraViewController.manualFocusValue {
            cameraViewController.manualFocusValue = cameraViewModel.focusChoice.rawValue
        }
    }

    func makeCoordinator() -> Coordinator {
        Coordinator(self, cameraViewModel: cameraViewModel)
    }

    class Coordinator: NSObject, UINavigationControllerDelegate, AVCapturePhotoCaptureDelegate {
        let parent: CameraPreviewRepresentable
        var cameraViewModel: CameraViewModel

        var tokens = Set<AnyCancellable>()

        init(_ parent: CameraPreviewRepresentable, cameraViewModel: CameraViewModel) {
            self.parent = parent
            self.cameraViewModel = cameraViewModel
            super.init()

            // for showing focus lens position
            self.parent.cameraController.currentCamera
                    .filter { $0 != nil }
                    .flatMap { $0!.publisher(for: \.lensPosition) }
                    .assign(to: \.focusLensPosition, on: cameraViewModel)
                    .store(in: &tokens)

            // for showing exposure offset
            self.parent.cameraController.currentCamera
                .filter { $0 != nil }
                .flatMap { $0!.publisher(for: \.exposureTargetOffset) }
                .assign(to: \.exposureTargetOffset, on: cameraViewModel)
                .store(in: &tokens)
        }

        func photoOutput(_ output: AVCapturePhotoOutput, didFinishProcessingPhoto photo: AVCapturePhoto, error: Error?) {

            parent.didTapCapture = false

            if let imageData = photo.fileDataRepresentation(), let image = UIImage(data: imageData) {
                UIImageWriteToSavedPhotosAlbum(image, nil, nil, nil)
            }

            parent.presentationMode.wrappedValue.dismiss()
        }
    }
}

import Combine
import AVFoundation

class CameraViewModel: ObservableObject {
    @Published var focusLensPosition: Float = 0
    @Published var exposureTargetOffset: Float = 0

    @Published var focusChoice: FocusChoice = .infinity

    private var tokens = Set<AnyCancellable>()

    init(focusLensPosition: Float) {
        self.focusLensPosition = focusLensPosition
    }
}

enum FocusChoice: Float, CaseIterable {
    case infinity = 1
    case ft_30 = 0.95
    case ft_15 = 0.9
    case ft_10 = 0.85
    case ft_7 = 0.8
    case ft_5 = 0.5
    case ft_4 = 0.7
    case ft_3_5 = 0.65
    case ft_3 = 0.6
    case auto = 0
}

extension FocusChoice {
    var caption: String {
        switch self {
        case .infinity: return "∞ft"
        case .ft_30: return "30"
        case .ft_15: return "15"
        case .ft_10: return "10"
        case .ft_7: return "7"
        case .ft_5: return "5"
        case .ft_4: return "4"
        case .ft_3_5: return "3.5"
        case .ft_3: return "3"
        case .auto: return "Auto"
        }
    }
}

import UIKit
import Combine
import AVFoundation

class CustomCameraController: UIViewController {

    var image: UIImage?

    var captureSession = AVCaptureSession()
    var backCamera: AVCaptureDevice?
    var frontCamera: AVCaptureDevice?
    lazy var currentCamera: AnyPublisher<AVCaptureDevice?, Never> = currentCameraSubject.eraseToAnyPublisher()
    var photoOutput: AVCapturePhotoOutput?
    var cameraPreviewLayer: AVCaptureVideoPreviewLayer?
    private var currentCameraSubject = CurrentValueSubject<AVCaptureDevice?, Never>(nil)

    var manualFocusValue: Float = 1 {
        didSet {
            guard manualFocusValue != 0 else {
                setAutoLensPosition()
                return
            }
            setFocusLensPosition(manualValue: manualFocusValue)
        }
    }

    //DELEGATE
    var delegate: AVCapturePhotoCaptureDelegate?

    func setFocusLensPosition(manualValue: Float) {
        do {
            try currentCameraSubject.value!.lockForConfiguration()
            currentCameraSubject.value!.focusMode = .locked
            currentCameraSubject.value!.setFocusModeLocked(lensPosition: manualValue, completionHandler: nil)
            currentCameraSubject.value!.unlockForConfiguration()
        } catch let error {
            print(error.localizedDescription)
        }
    }

    func setAutoLensPosition() {
        do {
            try currentCameraSubject.value!.lockForConfiguration()
            currentCameraSubject.value!.focusMode = .continuousAutoFocus
            currentCameraSubject.value!.unlockForConfiguration()
        } catch let error {
            print(error.localizedDescription)
        }
    }

    func didTapRecord() {

        let settings = AVCapturePhotoSettings()
        photoOutput?.capturePhoto(with: settings, delegate: delegate!)
    }

    override func viewDidLoad() {
        super.viewDidLoad()
        setup()
    }

    func setup() {

        setupCaptureSession()
        setupDevice()
        setupInputOutput()
        setupPreviewLayer()
        startRunningCaptureSession()
    }

    func setupCaptureSession() {
        captureSession.sessionPreset = .photo
    }

    func setupDevice() {
        let deviceDiscoverySession =
            AVCaptureDevice.DiscoverySession(deviceTypes: [.builtInWideAngleCamera],
                                                                      mediaType: .video,
                                                                      position: .unspecified)
        for device in deviceDiscoverySession.devices {

            switch device.position {
            case .front:
                self.frontCamera = device
            case .back:
                self.backCamera = device
            default:
                break
            }
        }

        self.currentCameraSubject.send(self.backCamera)
    }

    func setupInputOutput() {
        do {
          let captureDeviceInput = try AVCaptureDeviceInput(device: currentCameraSubject.value!)
          captureSession.addInput(captureDeviceInput)
          photoOutput = AVCapturePhotoOutput()
          captureSession.addOutput(photoOutput!)
        } catch {
          print(error)
        }

      }

    func setupPreviewLayer() {

        self.cameraPreviewLayer = AVCaptureVideoPreviewLayer(session: captureSession)
        self.cameraPreviewLayer?.videoGravity = AVLayerVideoGravity.resizeAspectFill

        let deviceOrientation = UIDevice.current.orientation
        cameraPreviewLayer?.connection?.videoOrientation = AVCaptureVideoOrientation(rawValue: deviceOrientation.rawValue)!

        self.cameraPreviewLayer?.frame = self.view.frame
        self.view.layer.insertSublayer(cameraPreviewLayer!, at: 0)
    }

    func startRunningCaptureSession() {
        captureSession.startRunning()
    }
}

Answer: Your ContentView gets updated all the time from the Published values. To Fix that we first remove the declaration as ObservedObject from the ViewModel inside the ContentView and declare it like that:
let cameraViewModel: CameraViewModel

Now we will get some errors. For FocusView just use ProxyBinding.
FocusPicker(selectedFocus: Binding<FocusChoice>(
    get: {
        cameraViewModel.focusChoice
    },
    set: {
        cameraViewModel.focusChoice = $0
    }
))

For the updated text, just create another View. Here! we use ObservedObject.
struct TextView: View {
    @ObservedObject var cameraViewModel: CameraViewModel

    var body: some View {
        Text(String(format: "%.2f", cameraViewModel.focusLensPosition))
            .foregroundColor(.red)
            .font(.largeTitle)
    }
}

Same for the OffsetView. Add ObservedObject there
struct OffsetView: View {
    @ObservedObject var viewModel : CameraViewModel

    let height: CGFloat

    var body: some View {

        ZStack {
            Rectangle()
                .foregroundColor(.red)
                .frame(maxWidth: height / 2, maxHeight: height, alignment: .trailing)

            Rectangle()
                .foregroundColor(.orange)
                .frame(maxWidth: height / 2, maxHeight: height / 20, alignment: .trailing)
                .offset(x: 0, y: min(CGFloat(-viewModel.exposureTargetOffset) * height / 2, height / 2))
        }
    }
}

The ContentView will then look like that:
struct ContentView: View {

    @State private var didTapCapture = false
    let cameraViewModel: CameraViewModel
    let cameraController: CustomCameraController

    var body: some View {

        VStack {
            ZStack {
                CameraPreviewRepresentable(didTapCapture: $didTapCapture, cameraViewModel: cameraViewModel, cameraController: cameraController)
                    .frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .center)

                VStack {
                    FocusPicker(selectedFocus: Binding<FocusChoice>(
                        get: {
                            cameraViewModel.focusChoice
                        },
                        set: {
                            cameraViewModel.focusChoice = $0
                        }
                    ))

                    TextView(cameraViewModel: cameraViewModel)
                }
                .frame(maxWidth: .infinity, alignment: .leading)
            }
            .edgesIgnoringSafeArea(.all)

            Spacer()

            OffsetView(viewModel: cameraViewModel, height: 100)

                .frame(maxWidth: .infinity, alignment: .leading)

            CaptureButton(didTapCapture: $didTapCapture)
                .frame(width: 100, height: 100, alignment: .center)
                .padding(.bottom, 20)
        }
    }
}

Hence, we do not have any ObservedObject anymore in the ContentView and our Picker just works fine.


RegEx to exclude a space between country code and phone number itself?

Question: My goal is to create two groups from a full phone number(which is given in a string):
First group: +xyz (any three numbers with a plus sign)
Second group: following 7 or 8 digits
So, my regex is:
((\D?[0-9]{3})(\D?\s?[0-9]{7,8}))
The problem I encountered was that if I have, for example +358 55667788, whitespace after a country code is still included in the second group. Is there any way how to fix this?
String I have looks like this. "+347 56887364  +37256887364
+33359835647"
Comment: what is the info you want to extract from `"+347 56887364 +37256887364 +33359835647"` ?
Comment: I'm sure you are aware, but nevertheless: some country codes can actually be 1-digit, 2-digit (for example Russia +7, India +91 etc.), and even more complicated than that
Comment: +xyz and following 7 or 8 eight numbers, the phone number itself
Comment: Yeah, I know, but currently I have to deal only with those that contain three numbers
Comment: Your assumption of three digits for the country code is false.  As it has been commented, some country codes are 1 and 2 digits, but also 4 digits (for small countries that somehow share prefix with a bigger country)
Answer: You could use this regex pattern:
\+\d{3}[ ]?\d{7,8}\b

Sample script using re.findall:
inp = "Here are some nums: +347 56887364 +37256887364 +33359835647"
nums = re.findall(r'\+\d{3}[ ]?\d{7,8}\b', inp)
print(nums)  # ['+347 56887364', '+37256887364', '+33359835647']