View of multiple tables. Need to remove "doubles" defined by 1 table

Question: Ok, so this is what i'm stuck with.

Full size
SELECT     dbo.InstellingGegevens.INST_SUBTYPE, dbo.InstellingGegevens.INST_BRON, dbo.InstellingGegevens.INST_INSTELLINGSNUMMER,
                      dbo.InstellingGegevens.INST_NAAM, dbo.InstellingGegevens.INST_KORTENAAM, dbo.InstellingGegevens.INST_VESTIGINGSNAAM,
                      dbo.InstellingGegevens.INST_ROEPNAAM, dbo.InstellingGegevens.INST_STATUUT, dbo.InstellingGegevens.ONDERWIJSNIVEAU_REF,
                      dbo.InstellingGegevens.ONDERWIJSSOORT_REF, dbo.InstellingGegevens.DATUM_TOT, dbo.InstellingGegevens.DATUM_VAN,
                      dbo.InstellingGegevens.VERBOND_REF, dbo.InstellingGegevens.VSKO_LID, dbo.InstellingGegevens.NET_REF, dbo.Instellingen.Inst_ID, dbo.Instellingen.INST_TYPE,
                      dbo.Instellingen.INST_REF, dbo.Instellingen.INST_LOC_REF, dbo.Instellingen.INST_LOCNR, dbo.Instellingen.Opt_KalStandaard, dbo.InstellingTelecom.INST_TEL,
                      dbo.InstellingTelecom.INST_FAX, dbo.InstellingTelecom.INST_EMAIL, dbo.InstellingTelecom.INST_WEB, dbo.InstellingAdressen.SOORT,
                      dbo.InstellingAdressen.STRAAT, dbo.InstellingAdressen.POSTCODE, dbo.InstellingAdressen.GEMEENTE, dbo.InstellingAdressen.GEM_REF,
                      dbo.InstellingAdressen.FUSIEGEM_REF, dbo.InstellingAdressen.FUSIEGEM, dbo.InstellingAdressen.ALFA_G, dbo.InstellingAdressen.PROVINCIE,
                      dbo.InstellingAdressen.BISDOM, dbo.InstellingAdressen.ARRONDISSEMENT, dbo.InstellingAdressen.GEWEST, dbo.InstellingLogin.Inst_Gebruikersnaam,
                      dbo.InstellingLogin.Inst_Concode, dbo.InstellingLogin.Inst_DirCode, dbo.InstellingLogin.DOSSNR, dbo.InstellingLogin.Instelling_ID,
                      dbo.InstellingContPersDirecteurs.AANSPREKING, dbo.InstellingContPersDirecteurs.CONTACTPERSOON, dbo.InstellingContPersDirecteurs.FUNCTIE
FROM         dbo.InstellingGegevens RIGHT OUTER JOIN
                      dbo.Instellingen ON dbo.InstellingGegevens.INST_TYPE = dbo.Instellingen.INST_TYPE AND dbo.InstellingGegevens.INST_REF = dbo.Instellingen.INST_REF AND
                      dbo.InstellingGegevens.INST_LOC_REF = dbo.Instellingen.INST_LOC_REF AND
                      dbo.InstellingGegevens.INST_LOCNR = dbo.Instellingen.INST_LOCNR LEFT OUTER JOIN
                      dbo.InstellingTelecom ON dbo.InstellingGegevens.INST_TYPE = dbo.InstellingTelecom.INST_TYPE AND
                      dbo.InstellingGegevens.INST_REF = dbo.InstellingTelecom.INST_REF AND
                      dbo.InstellingGegevens.INST_LOC_REF = dbo.InstellingTelecom.INST_LOC_REF LEFT OUTER JOIN
                      dbo.InstellingAdressen ON dbo.InstellingGegevens.INST_TYPE = dbo.InstellingAdressen.INST_TYPE AND
                      dbo.InstellingGegevens.INST_REF = dbo.InstellingAdressen.INST_REF AND
                      dbo.InstellingGegevens.INST_LOC_REF = dbo.InstellingAdressen.INST_LOC_REF LEFT OUTER JOIN
                      dbo.InstellingLogin ON dbo.InstellingLogin.Inst_InstellingIKONType = dbo.Instellingen.INST_TYPE AND
                      dbo.InstellingLogin.Inst_InstellingIKON_REF = dbo.Instellingen.INST_REF AND dbo.InstellingLogin.Inst_Loc_REF = dbo.Instellingen.INST_LOC_REF AND
                      dbo.InstellingLogin.Inst_Loc_Nr = dbo.Instellingen.INST_LOCNR LEFT OUTER JOIN
                      dbo.InstellingContPersDirecteurs ON dbo.InstellingGegevens.INST_TYPE = dbo.InstellingContPersDirecteurs.INST_TYPE AND
                      dbo.InstellingGegevens.INST_REF = dbo.InstellingContPersDirecteurs.INST_REF AND
                      dbo.InstellingGegevens.INST_LOC_REF = dbo.InstellingContPersDirecteurs.INST_LOC_REF
WHERE     (NOT (dbo.InstellingLogin.Inst_InstellingIKON_REF IS NULL))

So here is the problem:
the 'should be' PK is a 1 varchar 3 int's key. for every key there is supposed to be 1 row in each of the tables which you can see in the image. the 'parent' of those keys is the table Instellingen. This table is generated with a distinct select of InstellingenLogin
the real problem is that there are about 10 doubles in InstellingenLogin (of about 5k records) and because of this, some rows return double in the view, with only the columns of InstellingLogin different.
what i want is that if there are 2 or more rows in InstellingLogin with the same key, that only 1 will show (the first one,... doenst matter which one, just 1 will do).
in short that means that for every record in Instellingen i want 1 record in this view.
is there any way to do that?
Comment: I'm a bit confused, can you show some of the duplicate data you are trying to eliminate?
Comment: a dupe row would have the same value as the other row, only the values from the `InstellingLogin` table are different.
Answer: You need to wrap InstellingenLogin in some kind of aggregate to remove the duplicates and then join to the result - you can do this with a subquery.  You could do a GROUP BY with MIN() or MAX() to pick a value or you could do ROW_NUMBER() OVER (ORDER BY some_criteria PARTIION BY your_key) and pick the first row.
Also, I recommend using aliases on your tables - makes it far more readable
WITH UniqueLogins AS (
    -- How to pick Inst_Gebruikersnaam, Inst_Concode, Inst_DirCode, DOSSNR, Instelling_ID, InstellingIKONType, Inst_Loc_REF, Inst_Loc_Nr, Inst_InstellingIKON_REF
    SELECT key columns, MIN(non key column), MIN(non key column), MIN(non key column)
    FROM dbo.InstellingLogin
    GROUP BY key columns
)
SELECT     G.INST_SUBTYPE, G.INST_BRON, G.INST_INSTELLINGSNUMMER,
                  G.INST_NAAM, G.INST_KORTENAAM, G.INST_VESTIGINGSNAAM,
                  G.INST_ROEPNAAM, G.INST_STATUUT, G.ONDERWIJSNIVEAU_REF,
                  G.ONDERWIJSSOORT_REF, G.DATUM_TOT, G.DATUM_VAN,
                  G.VERBOND_REF, G.VSKO_LID, G.NET_REF, I.Inst_ID, I.INST_TYPE,
                  I.INST_REF, I.INST_LOC_REF, I.INST_LOCNR, I.Opt_KalStandaard, T.INST_TEL,
                  T.INST_FAX, T.INST_EMAIL, T.INST_WEB, A.SOORT,
                  A.STRAAT, A.POSTCODE, A.GEMEENTE, A.GEM_REF,
                  A.FUSIEGEM_REF, A.FUSIEGEM, A.ALFA_G, A.PROVINCIE,
                  A.BISDOM, A.ARRONDISSEMENT, A.GEWEST, UniqueLogins.Inst_Gebruikersnaam,
                  UniqueLogins.Inst_Concode, UniqueLogins.Inst_DirCode, UniqueLogins.DOSSNR, UniqueLogins.Instelling_ID,
                  CPD.AANSPREKING, CPD.CONTACTPERSOON, CPD.FUNCTIE
FROM         dbo.InstellingGegevens AS G RIGHT OUTER JOIN
                  dbo.Instellingen AS I ON G.INST_TYPE = I.INST_TYPE AND G.INST_REF = I.INST_REF AND
                  G.INST_LOC_REF = I.INST_LOC_REF AND
                  G.INST_LOCNR = I.INST_LOCNR LEFT OUTER JOIN
                  dbo.InstellingTelecom AS T ON G.INST_TYPE = T.INST_TYPE AND
                  G.INST_REF = T.INST_REF AND
                  G.INST_LOC_REF = T.INST_LOC_REF LEFT OUTER JOIN
                  dbo.InstellingAdressen AS A ON G.INST_TYPE = A.INST_TYPE AND
                  G.INST_REF = A.INST_REF AND
                  G.INST_LOC_REF = A.INST_LOC_REF LEFT OUTER JOIN
                  UniqueLogins ON UniqueLogins.Inst_InstellingIKONType = I.INST_TYPE AND
                  UniqueLogins.Inst_InstellingIKON_REF = I.INST_REF AND UniqueLogins.Inst_Loc_REF = I.INST_LOC_REF AND
                  UniqueLogins.Inst_Loc_Nr = I.INST_LOCNR LEFT OUTER JOIN
                  dbo.InstellingContPersDirecteurs AS CPD ON G.INST_TYPE = CPD.INST_TYPE AND
                  G.INST_REF = CPD.INST_REF AND
                  G.INST_LOC_REF = CPD.INST_LOC_REF
WHERE     (NOT (UniqueLogins.Inst_InstellingIKON_REF IS NULL))

Comment: can you explain this more? i know a fair bit of SQL but it aint clear to me how to do what you are suggesting :)
Answer: I'm a bit confused but I think the answer below should illustrate how to acheive what you need:
SELECT * FROM Instellingen as i
CROSS APPLY
(
    SELECT TOP (1) * FROM InstellingLogin as il
    WHERE i.INST_LOC_REF = il.Inst_Loc_REF
    and i.INST_LOCNR=il.Inst_Loc_Nr
    and i.INST_REF=il.Inst_InstellingIKON_REF
    and i.INST_TYPE=il.Inst_InstellingIKONType
    order by il.Datum_tot
) la

This will basically join on Instellingen and InstellingenLogin but only on the first record found
Comment: the idea sounds good but unfortunately something is wrong in the syntax for MS SQL
Comment: ok, i got this to work on a stand-alone merge. now to put it all together
Comment: this works, but when i run some queries on this view it takes about 2 minutes to return 5k rows! without the cross join it takes about 1s
Answer: You can use DENSE_RANK to Arbitrarily select a row. Basically create a CTE that ranks the instellinglogin and then only select the one with a Rank of 1. The tricky bit is that you have a left join to instellinglogin so you'll need to do the inner join inside the left join like so. Also I kept the Join condition as the the columns to partition. This may not be correct.
LEFT OUTER JOIN (dbo.instellinglogin
                            INNER JOIN unique_login
                              ON dbo.instellinglogin.inst_instellingikontype =
                                      unique_login .inst_instellingikontype
                                 AND dbo.instellinglogin.inst_instellingikon_ref =
                                     unique_login.inst_instellingikon_ref
                                 AND dbo.instellinglogin.inst_loc_ref =
                                     unique_login.inst_loc_ref
                                 AND dbo.instellinglogin.inst_loc_nr =
                                     unique_login.inst_loc_nr
                                 AND unique_login.therank = 1 )
             ON dbo.instellinglogin.inst_instellingikontype =
                dbo.instellingen.inst_type
                AND dbo.instellinglogin.inst_instellingikon_ref =
                    dbo.instellingen.inst_ref
                AND dbo.instellinglogin.inst_loc_ref = dbo.instellingen.inst_loc_ref
                AND dbo.instellinglogin.inst_loc_nr = dbo.instellingen.inst_locnr

Here's the complete SQL Below
WITH unique_login
     AS (SELECT instellinglogin.inst_instellingikontype,
                instellinglogin.inst_instellingikon_ref,
                instellinglogin.inst_loc_ref,
                instellinglogin.inst_loc_nr,
                Dense_rank() OVER (ORDER BY
                instellinglogin.inst_instellingikontype,
                instellinglogin.inst_instellingikon_ref,
                instellinglogin.inst_loc_ref,
                instellinglogin.inst_loc_nr) AS therank)
SELECT dbo.instellinggegevens.inst_subtype,
       dbo.instellinggegevens.inst_bron,
       dbo.instellinggegevens.inst_instellingsnummer,
       dbo.instellinggegevens.inst_naam,
       dbo.instellinggegevens.inst_kortenaam,
       dbo.instellinggegevens.inst_vestigingsnaam,
       dbo.instellinggegevens.inst_roepnaam,
       dbo.instellinggegevens.inst_statuut,
       dbo.instellinggegevens.onderwijsniveau_ref,
       dbo.instellinggegevens.onderwijssoort_ref,
       dbo.instellinggegevens.datum_tot,
       dbo.instellinggegevens.datum_van,
       dbo.instellinggegevens.verbond_ref,
       dbo.instellinggegevens.vsko_lid,
       dbo.instellinggegevens.net_ref,
       dbo.instellingen.inst_id,
       dbo.instellingen.inst_type,
       dbo.instellingen.inst_ref,
       dbo.instellingen.inst_loc_ref,
       dbo.instellingen.inst_locnr,
       dbo.instellingen.opt_kalstandaard,
       dbo.instellingtelecom.inst_tel,
       dbo.instellingtelecom.inst_fax,
       dbo.instellingtelecom.inst_email,
       dbo.instellingtelecom.inst_web,
       dbo.instellingadressen.soort,
       dbo.instellingadressen.straat,
       dbo.instellingadressen.postcode,
       dbo.instellingadressen.gemeente,
       dbo.instellingadressen.gem_ref,
       dbo.instellingadressen.fusiegem_ref,
       dbo.instellingadressen.fusiegem,
       dbo.instellingadressen.alfa_g,
       dbo.instellingadressen.provincie,
       dbo.instellingadressen.bisdom,
       dbo.instellingadressen.arrondissement,
       dbo.instellingadressen.gewest,
       dbo.instellinglogin.inst_gebruikersnaam,
       dbo.instellinglogin.inst_concode,
       dbo.instellinglogin.inst_dircode,
       dbo.instellinglogin.dossnr,
       dbo.instellinglogin.instelling_id,
       dbo.instellingcontpersdirecteurs.aanspreking,
       dbo.instellingcontpersdirecteurs.contactpersoon,
       dbo.instellingcontpersdirecteurs.functie
FROM   dbo.instellinggegevens
       RIGHT OUTER JOIN dbo.instellingen
         ON dbo.instellinggegevens.inst_type = dbo.instellingen.inst_type
            AND dbo.instellinggegevens.inst_ref = dbo.instellingen.inst_ref
            AND dbo.instellinggegevens.inst_loc_ref =
                dbo.instellingen.inst_loc_ref
            AND dbo.instellinggegevens.inst_locnr = dbo.instellingen.inst_locnr
       LEFT OUTER JOIN dbo.instellingtelecom
         ON dbo.instellinggegevens.inst_type = dbo.instellingtelecom.inst_type
            AND dbo.instellinggegevens.inst_ref = dbo.instellingtelecom.inst_ref
            AND dbo.instellinggegevens.inst_loc_ref =
                dbo.instellingtelecom.inst_loc_ref
       LEFT OUTER JOIN dbo.instellingadressen
         ON dbo.instellinggegevens.inst_type = dbo.instellingadressen.inst_type
            AND dbo.instellinggegevens.inst_ref =
                dbo.instellingadressen.inst_ref
            AND dbo.instellinggegevens.inst_loc_ref =
                dbo.instellingadressen.inst_loc_ref
       LEFT OUTER JOIN (dbo.instellinglogin
                        INNER JOIN unique_login
                          ON dbo.instellinglogin.inst_instellingikontype =
                                  unique_login .inst_instellingikontype
                             AND dbo.instellinglogin.inst_instellingikon_ref =
                                 unique_login.inst_instellingikon_ref
                             AND dbo.instellinglogin.inst_loc_ref =
                                 unique_login.inst_loc_ref
                             AND dbo.instellinglogin.inst_loc_nr =
                                 unique_login.inst_loc_nr
                             AND unique_login.therank = 1 )
         ON dbo.instellinglogin.inst_instellingikontype =
            dbo.instellingen.inst_type
            AND dbo.instellinglogin.inst_instellingikon_ref =
                dbo.instellingen.inst_ref
            AND dbo.instellinglogin.inst_loc_ref = dbo.instellingen.inst_loc_ref
            AND dbo.instellinglogin.inst_loc_nr = dbo.instellingen.inst_locnr
       LEFT OUTER JOIN dbo.instellingcontpersdirecteurs
         ON dbo.instellinggegevens.inst_type =
            dbo.instellingcontpersdirecteurs.inst_type
            AND dbo.instellinggegevens.inst_ref =
                dbo.instellingcontpersdirecteurs.inst_ref
            AND dbo.instellinggegevens.inst_loc_ref =
                dbo.instellingcontpersdirecteurs.inst_loc_ref
WHERE  ( NOT ( dbo.instellinglogin.inst_instellingikon_ref IS NULL ) )

Comment: i tried this but i get the error: The multi-part identifier instellinglogin.inst_instellingikontype could not be found. this repeated 2 times for all of the 'keys'
Answer: Or you could substitute the IntellingLogin table in the query with a derived table such as:
(SELECT RN = row_number() over
(partition by INST_LOC_REF,
INST_LOCNR, INST_REF, INST_TYPE order
by Datum_tot) , *  From
InstellingLogin) A

and add in the join condition: A.RN = 1
Comment: although the cross apply is likely to have better performance since it does an index seek on the InstellingLogin table and not an index scan as the others...
Comment: i tested it. it works as fast if not a bit faster than the cross apply.


How to use the Photobucket REST API?

Question: Has anyone successfully used the Photobucket REST API? According to the pathetic docs, it requires OAuth authorization, which would require a consumer key and secret, but registering an app gives you but a single developer key, which I have no idea what to do with.
Answer: If you go into photobucket and go to your application and view the details, you will see there is a developer key and what they call a 'private' key. I would assume this is the secret you are looking for. If you manage to make a successful call to the photobucket API, I would appreciate if you could provide the URL you used (anonymize anything private like the signature, of course)

How to use the Photobucket REST API?


Move repository files under different folder

Question: I've created some time ago a repository with many files in it but without any structure like folder 'root' and folder 'tags' and so on. Now I would like to create folder 'root' and put my current work in there, and than create  a branch called tagv23 in folder 'tags'. I've created in TortoiseSVN in repo-browser folders root and tags. How to move my all other folders and files to folder 'root' that it will work?
Answer: Just move the files using drag and drop, when browsing the repository.
Comment: It's too simple to be obvious
Comment: +1 if you mean browsing folders in Repo-browser.. 'cause this works for me!
Answer: You're essentially going to branch your existing files and folders. It's always a copy operation, so copy your existing files and folders to the 'root' folder and then delete the originals. Now you can branch from 'root' to 'tagv23'.


Where do i start when applying finish to a table?

Question: So I'm spraying a bojo table with polyurethane. Sounds easy right!! Where should I start? Legs first so I don't have to lay the table on the topside if I where to do the top first? Does that make sense??
Thanks for your input and help guys
Comment: Hi there and welcome! This is a searchable Q&A site so it's generally most helpful to make sure your title is in the form of a question. That really helps others find things of interest to them (maybe they have the same question, or maybe they're an expert and can answer!) It would be best if you edited your question to have a more meaningful title. You're more likely to get help and also you're helping others
Comment: This would be a better question for the Woodworking stack.
Answer: If you screw eye hooks in the bottom of the legs, you can suspend it and spray the whole thing.
If you can't suspend it, put the feet on painting pyramids and you can spray the whole thing.
If the above options don't work, do the feet and legs first and let it FULLY dry before flipping it to poly the rest.
Answer: Polyurethane doesn't look very nice if you just do one coat. It's better to do multiple. If you do that you'll have to flip it anyway.
If you really want one coat and do flip, I'd say do it upside down first, then top last. First this will keep the coat of the top from being damaged while you do the bottom. Second, if the PU drips down sides it will look better if the drips are downwards not upwards. Of course wipe any droplets you can see before they dry.
If you don't want to flip at all, then just do it upright. You might not get much on the bottoms of the feet, which may or may not matter to you. You will also have less PU on the legs because it will flow down, and it may bulge at the bottom of the legs. It's easier to get an even PU coat if you can keep the surface horizontal while drying it. But the tabletop is the most important and at least that should get a pretty good coat this way.


Close all other windows and keep current infobox google maps

Question: Excuse my English, I speak Spanish,
My question is how could I just click one infobox and close the others, and if you select a different one it would open that and close the others.
This means that when you click on one it's the only one open

Answer: After your marker creation add the follow
// add a click listener to the marker
google.maps.event.addListener(marker, 'click', function() {
    // reference clicked marker
    var curMarker =  this;
    // loop through all markers
    $.each(markers, function(index, marker) {
        // if marker is not the clicked marker, close the marker
        if(marker !== curMarker) {
            marker.infobox.close();
        }
    });
  });

I created a fiddle example here http://jsfiddle.net/pimlinders/rjmg8/4/


$\gamma: \left[ -\frac{\pi}{2}, \frac{\pi}{2} \right] \to \mathbb C$, $\gamma (t) = 2e^{it}$. Calculate: $\int_{\gamma} \frac{z}{z^2 + 1} dz$.

Question:
Let $\gamma: \left[  -\frac{\pi}{2}, \frac{\pi}{2} \right] \to \mathbb C$ be given by $\gamma (t) = 2e^{it}$. Calculate
$$\int_{\gamma} \frac{z}{z^2 + 1} dz$$
by finding area $U$ containing $\gamma^* = \gamma \left( \left[   -\frac{\pi}{2}, \frac{\pi}{2} \right] \right) $ and an antiderivative $F$ of function $f(z) = \frac{z}{z^2 + 1}$ on area $U$. Use the equality: $\int_{\gamma} f(z) dz = F(\gamma(\frac{\pi}{2})) - F(\gamma(-\frac{\pi}{2})).$

Now I can find the antiderivative. It is just $\frac{\ln(z^2 + 1)}{2}$. The problem is that $\gamma (t) = 2e^{it}$ is a ring around $0$ and there is no way to cover that area with logarithm. So I need to somehow merge more than one area to get my $U$. I don't know how to do that.
Comment: No such thing exists, as it is a closed ring. There is such a thing as patching together open sets to define continuous logarithms, but it's impossible to do on a ring
Answer: I'll give you some hints to solve this problem.
First note that by "symmetry of path and function $f$" (this expression needs to become a bit more rigor by you!) then can be concluded that $$∮_{\gamma_1} f(z)dz = \frac{1}{2}∮_{\gamma_2} f(z)dz$$
where $$\gamma_1= 2e^{it} : t\in [\frac{-\pi}{2},\frac{\pi}{2}]$$
$$\gamma_2= 2e^{it} : t\in [\frac{-\pi}{2},\frac{3\pi}{2}]$$
and finally following lemma from Stein's book "Complex Analysis" will help you to finish the job:

Corollary2.3:Suppose that f is holomorphic in an open set containing a toy >contour γ and its interior, except for poles at the points $z_1,...,z_N$ inside γ. Then
$$∮_{\gamma} f(z)dz = 2\pi i\sum res_{z_k}f$$
where the right hand side is residue of $f$ at $z_k$ and $z_k$ is a pole for f and
$$res_{z_k}f = \lim_{z \to z_k} (z-z_k)f(z)$$
Answer: If we look at $f(z) = \frac z{z^2+1}$, we can easily observe it has singularities at $z = \pm i$. So, it is holomorphic on open subsets of $\mathbb C$ that don't contain these points.
As you observe, the obvious candidate for antiderivative $z\mapsto\frac 12 \log(z^2+1)$ is problematic since $z\mapsto z^2+1$ will map semicircle $\gamma^*$ onto a circle around $0$. But we can use a bit of trickery and write
$$\frac12 \log(z^2+1) = \frac12 \log(z^2(1+1/z^2)) = \frac 12\log(1+1/z^2) + \log z.$$
Direct calculation shows that $$\frac d{dz}\left( \frac 12\log(1+1/z^2) + \log z \right) = \frac z{z^2+1},$$ but we avoid the problem from before since $z\mapsto 1+1/z^2$ maps semicircle $\gamma^*$ onto the circle centred at $1$, but with radius $1/4$ instead of $4$. So, we can use
$$F(z) = \frac 12\log(1+1/z^2) + \log z$$ to evaluate your integral to be $\pi i$.
To find appropriate open $U$, note that for $\log(1+1/z^2)$ we simply need $|z|>1$ and for $\log z$ exclude appropriate ray, such as the negative real axis.

Alternatively, by using substitution $w = z^2 + 1$, we can see that your integral is $\frac 12 \int_\Gamma \frac{dw}w$ where $\Gamma$ is a circle around $0$, which is well known to evaluate to $\frac 12 \cdot 2\pi i$.


Dedekind-MacNeille Completion

Question: Let $\mathbb{N}$ be the set of natural numbers.
a) Describe the Dedekind-MacNeille completion of the poset of finite subsets of $\mathbb{N}$.
b) Describe the Dedekind-MacNeille completion of the poset of cofinite subsets of $\mathbb{N}$.
c) Describe the Dedekind-MacNeille completion of the poset of finite and cofinite subsets of $\mathbb{N}$.
Here is my efforts to do with part a.
Call $P$ is the poset of finite subsets of $\mathbb{N}$.
Suppose $A$ is an element in the power set of $P$. Then $A^{u}$, which is the set of all upper bound of $A$. Then we have $A^u$ is the set of elements of the form $A \cup B$ where $B$ is an element in the power set of $P$. And then take $\left(A^u\right)^l = A^{ul}$, which is the set of all lower bounds of $A^u$, we have $A^{ul}$ contains the $\emptyset$ and all subsets of $A$.
Then by the definition of Dedekind-MacNeille, I conclude $A = \left\{\emptyset\right\}$ and $A = \left\{\emptyset, \left\{n\right\}\right\}$, where $n$ is a natural number.
Do I messed up something? And I still stuck with b and c. So any hint is appreciated. Thanks.
Comment: Obviously you messed up something. You picked $A$ an element of the powerset of $P$. Then you conclude that $A=\{\varnothing\}$ or $\{\varnothing,\{n\}\}$. This can't be right. Apparently, you got the right value for $A^u$, but from then on, nothing seems right. Remember that the Dedekind—MacNeille completion of a poset is the "least" complete lattice into which you can embed the poset. You know that, don't you? (You could be bound to use the definition.)
Answer: I think the best way to tackle this problem is to use the following result, which you can find, for example, in Davey and Priestley, Introduction to Lattices and Order.

7.41 Theorem.
  Let $P$ be a poset and let $\varphi:P\to\mathbf{DM}(P)$ be the order-embedding of $P$ into its Dedekind—MacNeille completion given by $\varphi(x) = \,\downarrow\!x$.
   (i) $\varphi(P)$ is both join-dense and meet-dense in $\mathbf{DM}(P)$.
  (ii) Let $\mathbf L$ be a complete lattice and assume that $P$ is a subset of $L$ which is both join-dense and meet-dense in $L$. Then $\mathbf L \cong \mathbf{DM}(P)$ via an order-isomorphism which agrees with $\varphi$ on $P$.

Now, let us see how we could use this result to answer (a) and (c).
(Notice that (b) is similar to (a), so I'll leave it to you.)
If $P$ is the poset of finite subsets of $\mathbb N$, then I claim that $P\cup\{\mathbb N\}$ is its Dedekind—MacNeille completion.
Let us use (ii) from the Theorem to show it.
To start with, you can easily show that $P\cup\{\mathbb N\}$, with the $\subseteq$ order relation, is a complete lattice.
Now, given an element of $P\cup\{\mathbb N\}$, we show that it is the join and the meet of some subset of $P$.
For the element $\mathbb N$, we have that $\mathbb N = \bigwedge \varnothing = \bigvee \{\{n\}:n \in \mathbb N\}$, so we're done; any other element $A$ belongs to $P$, so we just say $A = \bigwedge\{A\}=\bigvee\{A\}$.
In the case of (c), that is, $P$ is the poset of finite and co-finite subsets of $\mathbb N$, I claim that the Dedekind—MacNeille completion of the finite and co-finite subsets of $\mathbb N$ is the powerset of $\mathbb N$.
Indeed, any full powerset lattice is a complete lattice.
Now take $A \subseteq \mathbb N$.
Then
$$A = \bigcup \{ \{a\} : a \in A \} = \bigcap \{ \mathbb N \setminus \{b\} : b \notin A \}.$$
Since $\{a\}$ is a finite subset of $\mathbb N$, for each $a \in A$ and $\mathbb N \setminus \{b\}$ is a co-finite one, for each $b \notin A$, we get that $P$ is both join-dense and meet-dense in the powerset of $\mathbb N$.

Dedekind-MacNeille Completion


why my textbox doesnot return any proper value in jquery?

Question: I have created this controller for for getting existing value by searching id. this is my controller for searching data by id. this code is running well but result is not acceptable. i am new in jquery that's why i am explaining this very helpfully..
   public string Search(string id=null)
            {
                string[] ci = new string[9];
                //return "Artistry";

                string cn = null;
                cn = Request.QueryString["id"];
                if (cn != null)
                {
                    ClientInfo c = db.SingleOrDefault<ClientInfo>("where CId='" + cn + "'");
                    if (c != null)
                    {
                       // ci[0] = c.CId.ToString();
                        ci[1] = c.CName;
                        ci[2] = c.CCName;
                        ci[3] = c.PhoneNo.ToString();
                        ci[4] = c.Fax;
                        ci[5] = c.Email;
                        ci[6] = c.Address;
                        ci[7] = c.PostalCode.ToString();
                        ci[8] = c.Country;
                        return ci[5];
                    }
                    else
                        return null;
                }
                else
                    return null;
                 //*/
            }

My view page script for showing my data..

And finally my sql server database for showing data in views are..
SELECT TOP 1000 [CId]
      ,[CName]
      ,[CCName]
      ,[PhoneNo]
      ,[Fax]
      ,[Email]
      ,[Address]
      ,[PostalCode]
      ,[Country]
  FROM [test].[dbo].[ClientInfo]

Comment: Is the control with the ID #CId the textbox you are talking about that is not returning a value??? so that the line that reads 'var url = "/Clients/Search/" + v;' results in 'v' being undefined or something? Just need a bit more clarification of where in your code the issue is, the query seems irrelevant, but maybe it is not?? Cheerz.
Comment: did the alert showed at least?
Answer: I think you should return json type data like so:
public JsonResult Search(string id=null)
    {
         // view code

             return Json(new {info=ci[5]});
    }

And client code:
$.get(url, function (data, status) {

                alert("Test : " + data.info + " Status :" + status);
            });


Is there a non-trivial function satisfying $\int_0^1 (f(x)+x)^a \, dx=0$ for $a$ a positive real (or integer)?

Question: Here is the functional equation:
$$\int_0^1 (f(x)+x)^a \, dx=0$$
Is there a function $f(x)$ that satisfies it for any $a>0$ and $f(x)\not\equiv-x$?
What about the case where $a$ is an integer?
Comment: It depends on the conditions you have on the regularity of $f$. When a=2 or any other even integer, the function $(f(x) + x)^2$ is non-negative. If $f$ is continuous, this can only happen if $f(x) + x = 0$. In general,  we must have $f(x) + x = 0$ almost everywhere (like in Almeida's example).
Comment: When you say "any $a > 0$" do you mean "all $a > 0$"?  If $a$ is an even integer, your equation says $f(x) + x = 0$ for almost every $x$ (with respect to Lebesgue measure).
Comment: Why not define $g(x)=f(x)+x $ and ask about $g(x)^a$? It looks like you just chose an abstruse form of this.
Comment: @LucasKaufmann we can assume $f(x)$ to be non-real.
Answer: Let $S$ be an finite set such that $S \subset [0,1]$, and $M$ an subset with the same ammount of elements of $S$, such that $M \subset \mathbb{R}$.
Now let $\begin{cases} f(x) = -x \text{ if } x\notin S \\
f(x) = g(x) \text{ otherwise}
\end{cases}$
Where $g(x)$ is some abritary function $g:S \to M$
Then the integral in question can be computed by splitting it into an finite sum of other integrals, in which $f(x)$ behaves exactly as $f(x)=-x$.
Now, It's fully possible this trickery I did is forbidden by the $f(x) \not\equiv -x$, i don't actually know how restrcitve that notation is. Please do let me know


Collectionview inside tableview cell not increasing height of collectionView

Question: I have UICollecitonView inside UITableViewCell, Everyting is working good, My tableview is loading properly and my collectionview too. But in my requirement, I don't want collection view to scroll, instead it should increase its height.
When I am increasing height of tableview cell, the collection view inside tableviewcell is not increasing. Although I am increasing height constraint of collectionview programmatically. I tried calling layoutIfNeeded and setNeedsUpdateConstraint on collectionView, and on tableview cell and also on viewcontroller's view. But collectionview's height is not increasing.
Can anyone tell me how to achieve it?
Comment: You need to call `reloadRowsAtIndexPaths` while increasing height of tableview cell.
Comment: It will be better if you share some code.
Answer: You have to try delegate for collection view
-(CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath
{
   return CGSizeMake(80, 180);
}


Inline vs Normal Function in C++

Question: I have just finished inline functions chapter in Bruce Eckel's : thinking in C++. Well there's an exercise which asks you to create two exact functions one being inline and the other not. Then use clock() and count the time passed for each one. I have worked on similar problems and I don't think there's anything complex with it. Therefore I came up with :
#include <iostream>
#include <ctime>
using namespace std;

inline int infun(int x) {
    x = 3;
    x = 5;
    cout << "";
    return x;

}

int fun(int x) {
    x = 3;
    x = 5;
    cout << "";
    return x;

}

int main() {

    clock_t startIn = clock();
    for (int i = 0; i < 10000000; i++) {
        infun(i);

    }
    clock_t finishIn = clock();

    clock_t start = clock();
    for (int i = 0; i < 10000000; i++) {
        fun(i);

    }
    clock_t finish = clock();

    clock_t startIn2 = clock();
    for (int i = 0; i < 10000000; i++) {
        infun(i);

    }
    clock_t finishIn2 = clock();

    cout << "Inline: " << (finishIn - startIn) << endl << "Regular Function: "
            << (finish - start) << endl<< "Second Inline: " << finishIn2 - startIn2 << endl;
    return 0;
}

Output
Inline: 195842
Regular Function: 166564
Second Inline: 162917

So I have 3 functions. 2 exactly similar inlines and one non-inline (for testing purposes I came up with this case).
a) Why the first inline takes all that time (the same happens for any function executed first)
b) Why if the repetitions are decreased (lets say 1000) the normal function is faster than the others.
My test cases are satisfied even with simpler functions like :
inline int infun(int x) {
    return x;
}

I've also checked the assembly output to ensure that the inlines are truly inlines or that g++ does not promote the non-inline to inline. Thank you for your time, any feedback is appreciated.
Comment: What compiler options did you use?  Measuring an un-optimized build is not going to give you the correct information.
Comment: `inline` is simply a recommendation, the compiler makes its own determination on whether to actually inline the code. From there cache effects might give different timing on the exact same code. Also there's a lot of granularity in the standard `clock`, you might see a huge difference that isn't real.
Comment: Thanks for your input, I have used the auto generated build options of Eclipse and I've just tested g++ with no options. Same results. The author has not referred yet to any special building options. To add, the notion of the book's exercises so far is more or less some playful experience with the theory (not really special problems). The result had to be solid as the theory and in the case there was a conflict the author would probably ask why.
Comment: Modern compilers can figure out automatically which functions will benefit from inlining, and they're likely to ignore the keyword.
Comment: @Barmar: Modern compilers better not ignore that keyword, or else your program may fail to compile from duplicate definitions. However they might not consider it in the optimizer.
Comment: @celtschk I meant they ignore it when deciding whether to inline. They still do the other stuff it requires.
Comment: @fllprbt - If you use g++ without options, the timing is not interesting. Unless you ask the compiler to optimize the code and make it fast, it might  not even consider inlining the inline functions. It's like Usain Bolt walking instead of running.
Answer: paraphrasing from cppreference.com:

An inline function is a function with the following properties:
1) There may be more than one definition of an inline function in the program as long as each definition appears in a different translation unit. For example, an inline function may be defined in a header file that is #include'd in multiple source files.
2) The definition of an inline function must be present in the translation unit where it is accessed (not necessarily before the point of access).
3) An inline function with external linkage (e.g. not declared static) has the following additional properties:
1) It must be declared inline in every translation unit.
  2) It has the same address in every translation unit.

Notice that not once has optimisation, performance or actual inlining of machine code been mentioned or even hinted at.
inline simply says to the compiler: "this function may be defined more than once, but I promise that each definition is identical"
Comment: @fllprbt I'll expand upon my comment. I had a quick look at the book you mention. It was written almost 20 years ago. Back then, there were a great many c programmers who thought they knew c++ (but didn't). It's also fair to say that the c++ standard was not as mature as it is today. The confusion is understandable. However, if Mr Eckel is still teaching, he ought to up his game and/or revise his book. It is misleading people.
Comment: Thanks for your comment. The book though raises the efficiency issue so many times even making suggestions when to use inline for efficiency. That is the very essence of this exercise as well, finding out which one is faster.
Comment: @fllprbt the meaning of `inline` has changed in C++, so simply put: the compiler will not "inline" a function just because you marked it to do so. The only purpose of `inline` in C++ is to tell the compiler a function definition is identical across translation units.
Comment: @RichardHodges The book was suggested by my dissertation's supervisor who relates for sure to an older period. Just recently I found out that it was not that good but this last issue puts me really into thinking of changing. Thank you for the feedback.

Inline vs Normal Function in C++


VBA to paste data to specific cell based on column and row criteria

Question: I am trying to have a button that will snapshot a number to another sheet. The copy/paste code works as it should however I need it to paste accordingly to the proper user and week.
This is what I have so far:
Sub CopyScore()

Worksheets("Scorecard").Range("AD13").Copy
Worksheets("Yearly").Range("B2").PasteSpecial xlPasteValues

End Sub

Obviously, this just paste to B2
How can I make this where in the Yearly sheet it needs to look for a specific name in column A and also a specific number in Row A?
Just to make more sense... It will be looking at a name on the Scorecard (D2) sheet then matching that to a name in column A. It will also be looking at the week #(V2) on the Scorecard sheet and matching that to the column in Yearly.
If this was able to be written for another sheet on the same workbook and another code for a workbook that is not open that would be amazing...
So this works great!
Sub demo()
Dim ySht As Worksheet, ce As Range
Dim c As Range, oWBook As Workbook
With ThisWorkbook.Worksheets("Scorecard")
    If .Range("AD13") <> "" Then
        Set oWBook = Workbooks.Open("d:\temp\my.xlsx") ' updated as needed
        Set ySht = oWBook.Worksheets("Yearly")
        ' Search name
        Set c = ySht.Columns(1).Find(.Cells(2, "D"))
        If Not c Is Nothing And .Range("V2") > 0 Then
            Set ce = ySht.Cells(c.Row, 1).Offset(0, .Range("V2"))
            ce.Value = .Range("AD13")
            ce.AddComment
            ce.Comment.Text .Range("B29").Value
        End If
        oWBook.Save
        oWBook.Close
    End If
End With

End Sub
However, if B29 is blank I get an error since there is no text for the comment.
Also is there a way to make it so that if the "Yearly" worksheet cell is not blank it will not send the score? This would eliminate changing the score after it has been submitted.
Comment: What's the location of ` the column in Yearly.'?
Comment: Column "A" is the location.
Comment: Please share the screenshots of your worksheets. Also, share some examples of what needs to be copied where and the logic behind it. It looks like a simple lookup that could be handled using a formula using `INDEX/MATCH` (in older versions) or `XLOOKUP` (in Microsoft 365). If you already have a formula you have tried, please share it.
Comment: Here is the file. https://file.io/8SMYNkzqozdh The issue is that once you select a different associate all information changes based on their name. I would like this to be a button so I can snap shot their score to the yearly sheet.
Answer: Please try
Sub demo()  ' [Stop updating]
    Dim ySht As Worksheet
    Dim c As Range, ce As Range
    Set ySht = ThisWorkbook.Worksheets("Yearly")
    With Worksheets("Scorecard")
        If .Range("AD13") <> "" Then
            ' Search name
            Set c = ySht.Columns(1).Find(.Cells(2, "D"))
            If Not c Is Nothing And .Range("V2") > 0 Then
                Set ce = ySht.Cells(c.Row, 1).Offset(0, .Range("V2"))
                ce.Value = .Range("AD13")
                ce.AddComment
                ce.Comment.Text .Range("B29").Value
            End If
        End If
    End With
End Sub

Question: If I wanted to do this to a workbook that is closed. e.g. The "scorecard" workbook would be open and then it would send the number to a workbook that is closed.
Answer: The main code logic is same. The only different is the code to open/close the target workbook.

Sub demo()
    Dim ySht As Worksheet, ce As Range
    Dim c As Range, oWBook As Workbook
    With ThisWorkbook.Worksheets("Scorecard")
        If .Range("AD13") <> "" Then
            Set oWBook = Workbooks.Open("d:\temp\my.xlsx") ' updated as needed
            Set ySht = oWBook.Worksheets("Yearly")
            ' Search name
            Set c = ySht.Columns(1).Find(.Cells(2, "D"))
            If Not c Is Nothing And .Range("V2") > 0 Then
                Set ce = ySht.Cells(c.Row, 1).Offset(0, .Range("V2"))
                ' "Yearly" worksheet cell is blank
                If Len(ce.Value) = 0 Then
                    ce.Value = .Range("AD13")
                    ' Comment cell is not blank
                    If Len(.Range("B29").Value) > 0 Then
                        ce.AddComment
                        ce.Comment.Text .Range("B29").Value
                    End If
                End If
            End If
            oWBook.Save
            oWBook.Close
        End If
    End With
End Sub

Comment: If I wanted to do this to a workbook that is closed.. how different would the code have to be?
Comment: Are both sheets in a closed workbook?
Comment: The "scorecard" workbook would be open and then it would send the number to a workbook that is closed.
Comment: Several lines are needed to get it done. I have updated the code.
Comment: Amazing... You are great. I cannot thank you enough.
Comment: Taller_ExcelHome, If i wanted to also add the the notes section as a comment to the cell how can i do this? I have it where it is creating the comment but it will not copy the contents of the cell...

            Set c = ySht.Columns(1).Find(.Cells(2, "D"))
            If Not c Is Nothing And .Range("V2") > 0 Then
                ySht.Cells(c.Row, 1).Offset(0, .Range("V2")).AddComment ("B29")
Comment: Hmmm this gives me a runtime error of 1004.

ySht.Cells(c.Row, 1).Offset(0, .Range("V2")).AddComment ySht.Range("B29")
Comment: Error 1004 for the line with .Comment.Text .Range("B29").Value
Comment: Works! Amazing... I need your brain... Thank you again... If i need anymore help would you be ok with me commenting here again?
Comment: Yes, it is a minor change on it. Otherwise a new post would be helpful for SO users.
Comment: Ok... found an issue. If the "Notes" section is blank i get an error. anyway to fix this? Also is there a way to "Block" a score being overwritten if it has already been submitted? Sorry...
Comment: What does ` "Notes" section is blank` mean? Please give the detail about overwritten issue on OP.
Comment: Added to the OP.
Comment: If B29 is blank, do you want to add a blank comment or skip adding comment?
Comment: Skip adding a comment.


XMLSerializer fails to deserialize a xml document

Question: I am a newbie to C#. I have a java REST service which returns a xml response and I am trying to deserialize the xml document using C# XmlSerializer. A sample xml document response is pasted below.
<?xml version="1.0" encoding="UTF-8"
 standalone="yes" ?>  <ns2:Document
 xmlns:ns2="http://hxps.honeywell.com/model/impl"
 xmlns:ns3="http://hxps.honeywell.com/datatypes/impl"
 type="PS">
 <docId>SamplePSDocument1</docId>
 <fields
 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 xmlns:ns5="http://jaxb.dev.java.net/array"
 xsi:type="ns5:anyTypeArray">   <item
 xsi:type="ns3:scalarFieldImpl"
 key="Name">
      <value xmlns:xs="http://www.w3.org/2001/XMLSchema"
 xsi:type="xs:string">HXPS A4</value>
 </item>   <item
 xsi:type="ns3:scalarFieldImpl"
 key="Creation Date">
       <value xmlns:xs="http://www.w3.org/2001/XMLSchema"
 xsi:type="xs:string">20 April
 2007</value>    </item> </fields>
 <id>fb92f871-1f3d-4fa4-ba24-5ae3af0a493f</id>
 <revision>1-c75f688e212fb5341ebdbd22a3867c14</revision>

 - <version>   <majorVersionNumber>1</majorVersionNumber>
 <minorVerisonNumber>5</minorVerisonNumber>
 </version> </ns2:document>

It works fine when I deserialize this xml document into Document object. My document class is pasted below
[System.SerializableAttribute()]
[System.Xml.Serialization.XmlTypeAttribute(Namespace = "http://hxps.honeywell.com/model/impl", TypeName = "PSDocument")]
[System.Xml.Serialization.SoapTypeAttribute(Namespace = "http://hxps.honeywell.com/model/impl", TypeName = "PSDocument")]
[System.Xml.Serialization.XmlRootAttribute(Namespace = "http://hxps.honeywell.com/model/impl", ElementName = "Document")]

public partial class PSDocument
{

    private Com.Honeywell.Hxps.Sdk.Model.DocumentType _type;
    private string _description;
    private string _displayName;
    private string _docId;
    private Com.Honeywell.Hxps.Sdk.Model.Impl.VersionImpl _version;
    private object _fields;
    private string _revision;
    private string _id;
    ///
    ///  (no documentation provided)
    ///
    [System.Xml.Serialization.XmlAttributeAttribute(AttributeName = "type")]
    [System.Xml.Serialization.SoapAttributeAttribute(AttributeName = "type")]
    public Com.Honeywell.Hxps.Sdk.Model.DocumentType Type
    {
        get
        {
            return this._type;
        }
        set
        {
            this._type = value;
        }
    }

    ///
    ///  Property for the XML serializer indicating whether the "Type" property should be included in the output.
    ///
    [System.Xml.Serialization.XmlIgnoreAttribute]
    [System.Xml.Serialization.SoapIgnoreAttribute]
    [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)]
    public bool TypeSpecified
    {
        get
        {
            return this._type != Com.Honeywell.Hxps.Sdk.Model.DocumentType.NULL;
        }
        set
        {
            if (!value)
            {
                this._type = Com.Honeywell.Hxps.Sdk.Model.DocumentType.NULL;
            }
        }
    }
    ///
    ///  (no documentation provided)
    ///
    [System.Xml.Serialization.XmlElementAttribute(ElementName = "description", Namespace = "")]
    [System.Xml.Serialization.SoapElementAttribute(ElementName = "description")]
    public string Description
    {
        get
        {
            return this._description;
        }
        set
        {
            this._description = value;
        }
    }
    ///
    ///  (no documentation provided)
    ///
    [System.Xml.Serialization.XmlElementAttribute(ElementName = "displayName", Namespace = "")]
    [System.Xml.Serialization.SoapElementAttribute(ElementName = "displayName")]
    public string DisplayName
    {
        get
        {
            return this._displayName;
        }
        set
        {
            this._displayName = value;
        }
    }
    ///
    ///  (no documentation provided)
    ///
    [System.Xml.Serialization.XmlElementAttribute(ElementName = "docId", Namespace = "")]
    [System.Xml.Serialization.SoapElementAttribute(ElementName = "docId")]
    public string DocId
    {
        get
        {
            return this._docId;
        }
        set
        {
            this._docId = value;
        }
    }
    ///
    ///  (no documentation provided)
    ///
    [System.Xml.Serialization.XmlElementAttribute(ElementName = "version", Namespace = "")]
    [System.Xml.Serialization.SoapElementAttribute(ElementName = "version")]
    public Com.Honeywell.Hxps.Sdk.Model.Impl.VersionImpl Version
    {
        get
        {
            return this._version;
        }
        set
        {
            this._version = value;
        }
    }
    ///
    ///  (no documentation provided)
    ///
    [System.Xml.Serialization.XmlElementAttribute(ElementName = "fields", Namespace = "")]
    [System.Xml.Serialization.SoapElementAttribute(ElementName = "fields")]
    public object Fields
    {
        get
        {
            return this._fields;
        }
        set
        {
            this._fields = value;
        }
    }
    ///
    ///  (no documentation provided)
    ///
    [System.Xml.Serialization.XmlElementAttribute(ElementName = "revision", Namespace = "")]
    [System.Xml.Serialization.SoapElementAttribute(ElementName = "revision")]
    public string Revision
    {
        get
        {
            return this._revision;
        }
        set
        {
            this._revision = value;
        }
    }
    ///
    ///  (no documentation provided)
    ///
    [System.Xml.Serialization.XmlElementAttribute(ElementName = "id", Namespace = "")]
    [System.Xml.Serialization.SoapElementAttribute(ElementName = "id")]
    public string Id
    {
        get
        {
            return this._id;
        }
        set
        {
            this._id = value;
        }
    }
}
}

In my main program, I get an array of xmlNodes when I try
Array fields = (Array)doc.Fields;

In the server side java REST service implementation, fields is actually a arraylist which will contain instances of three implementations of an interface. (List may contain ScalarFieldImpl or ArrayFieldImpl which are custom business objects).
I want to deserialize this xml fields into ScalarFieldImpl or ArrayFieldImpl using XmlSerializer. I want to know whether it is possible? If so, how do I do that?
Comment: I could not get my xml viewable in my problem text. Can someone tell me how do I fix that?
Comment: I've changed it to use code formatting, but I haven't attempted to re-layout in case I change any meaning
Answer: As far as I know this isn't possible with the ootb xml (de-)serializer, I think you'll have to write your own XmlSerializer. Or try to use LINQ to XML.
Comment: Damn I wasn't awake yesterday, look at this link http://msdn.microsoft.com/en-us/library/system.xml.serialization.xmlarrayitemattribute.aspx
Answer: I got this working. I did few changes in my PSDocument class.
private object _fields;  -> private ArrayList _fields;
Also I changed get/set method and added new metadata
[System.Xml.Serialization.XmlArray(ElementName = "fields", Namespace = "")]
[System.Xml.Serialization.XmlArrayItem(ElementName="item")]
public ArrayList Fields
{
     get
     {
                return this._fields;
     }
     set
     {
                this._fields = value;
     }
}
Previously I had the following lines in my PSDocument class
[System.Xml.Serialization.XmlElementAttribute(ElementName = "fields", Namespace = "")]
    [System.Xml.Serialization.SoapElementAttribute(ElementName = "fields")]
    public object Fields
    {
        get
        {
            return this._fields;
        }
        set
        {
            this._fields = value;
        }
    }
So while deserializing fields in PSDocument, I get an arraylist with items as elements.
Hope this helps someone.


How to fix Gray screen with androidx.constraintLayout text in android studio

Question: I am learning android development
I have this problem with my design view of my android studio that shows gray background with androidx.constraintLayout.constraintLayout text in the middle
xml design view snapshot

Now i tried solutions stated in Why is my design screen gray and only says "androidx.constraintlayout.ConstraintLayout" in Android Studio?
I added dependencies { implementation "androidx.constraintlayout:constraintlayout:2.0.0-beta4" } in build.gradle and android:id="@+id/constraintLayout" in my xml file
I also tried:
rebuilding the project, invalidating cache and the solution provided in the issue tab which is:
    The following classes could not be instantiated:
    - androidx.constraintlayout.widget.ConstraintLayout
(Open Class, Show Exception, Clear Cache)
     Tip: Use View.isInEditMode() in your custom views to skip code or show sample data when shown in the IDE.
If this is an unexpected error you can also try to build the project, then manually refresh the layout.

but found no luck
here is my gradle.build app dependency:
dependencies {
implementation fileTree(dir: 'libs', include: ['*.jar'])
implementation "androidx.constraintlayout:constraintlayout:2.0.0-beta4"
implementation 'androidx.constraintlayout:constraintlayout:1.1.3'
implementation 'androidx.appcompat:appcompat:1.3.1'
implementation 'androidx.constraintlayout:constraintlayout:2.1.1'
testImplementation 'junit:junit:4.12'
androidTestImplementation 'androidx.test.ext:junit:1.1.3'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.4.0'

}
here is my xml file:
    <?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/constraintLayout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Hello World!"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintLeft_toLeftOf="parent"
    app:layout_constraintRight_toRightOf="parent"
    app:layout_constraintTop_toTopOf="parent" />

</androidx.constraintlayout.widget.ConstraintLayout>

here is my gradle.properties
    org.gradle.jvmargs=-Xmx1024m
# When configured, Gradle will run in incubating parallel mode.
# This option should only be used with decoupled projects. More details, visit
# http://www.gradle.org/docs/current/userguide/multi_project_builds.html#sec:decoupled_projects
# org.gradle.parallel=true
# AndroidX package structure to make it clearer which packages are bundled with the
# Android operating system, and which are packaged with your app's APK
# https://developer.android.com/topic/libraries/support-library/androidx-rn
android.useAndroidX=true
# Automatically convert third-party libraries to use AndroidX
android.enableJetifier=true

ANDROID STUDIO version = 3.6.3 running 32 bit
SDK version = 26.1.1
Comment: Why are you not using the latest Android studio ?? And why is SDK version not the latest ??
Comment: Because my machine is 32 bit
Answer: I had the same problem
But I fix it by delete
implementation 'androidx.constraintlayout:constraintlayout:2.1.1'

and use
implementation 'androidx.constraintlayout:constraintlayout:1.1.3'

only
I don't know what caused that problem, but I hope that will help you.


Date shell command in hive script

Question: I would like to run date command in hive script. It being a shell command, I tried using a preceding '!'. Tried the following:
hive (default)> !date --date="6 months ago";
date: extra operand `ago"'
Try `date --help' for more information.
Command failed with exit code = 1

Comment: Yeah. The hive parser does not honor the quotes when parsing the command, so it tries to execute `date` with 3 args i.e. `--date="6` then `months` then `ago"`. You have no workaround. Blank space cannot be escaped.
Answer: As mentioned by @samson in comment hive does not parse the command --date="6 months ago";. You can use below workaround.
select add_months(current_date(),-6);

Date shell command in hive script


Send files from Ubuntu to iPhone idevicepair says "no device found"

Question: How to get idevicepair to see my iPhone?
I'm trying find some way of sending files to the phone from laptop without using Internet.
Following the instructions at https://wiki.archlinux.org/title/IOS for installing libimobiledevice:

systemctl status usbmuxd.service Yes it shows running since my last boot days ago
idevicepair pair: no device found

tail syslog shows a lot of errors on plugging in the phone but
lsusb lists the phone
Following instructions at https://opensource.com/article/21/8/libimobiledevice-iphone-linux:

ifuse --help to confirm libimobiledevice is installed: help displayed successfully
mkdir ~/iPhone ok
ifuse ~/iPhone: "No device found"
ifuse ~/iPhone --root "No device found"

No relevant topics here in stackoverflow and indeed this lib does not get much attention elsewhere. Another person on reddit same issue but no replies to his question.
Ubuntu 18.04 with extended service (Pro)
iPhone 16.5.1
Any suggestions?
Answer: A suggestion (really a work-around):
I successfully move files back and forth from my iPhone 8, iOS 16.7.2 over my home WiFi network, with the app "File Manager Pro" by zuhanden, using lftp on my Linux laptop. I had to download lftp. I don't know if this can also be done on any other of the file manager apps available.

open File Manager, then, on Home page, select "Add connection" (blue highlight on my Iphone). Select WiFi Connect, then "Enable". The local IP will be displayed.
Open Terminal. cd to directory file(s) reside. Then, "lftp". Then "put -O http://[ip address for File Manager connection] [filename]". That's upper case letter O.

lftp also includes a "get" command.
Good luck!


How do I create a dictionary from a csv using python

Question: I have a csv file of the format:

spelling, pronunciation, syllables, tag
head, H-EH-D, 1, NSING
bottle, B-O-T-UH-L, 2, NSING
fall, F-AW-L, 1, VBASE

I would like to convert it into a dictionary of the form:
'head' : ['H-EH-D', '1', 'NSING']
Comment: Does https://stackoverflow.com/questions/6740918/creating-a-dictionary-from-a-csv-file help?
Comment: You can't have a dictionary entry that looks like that. I suggest either:- 'head': 'H-EH-D, 1, NSING' or 'head': ['H-EH-D', '1', 'NSING']
Comment: @DarkKnight edited as per your suggestion and to alfinkel24 thank you but it doesn't seem to have exactly what I'm looking for.
Comment: Please edit your question to show the code you've tried and we can help you further
Comment: I've tried a few things such as using the csv.DictReader module  and creating a none-type object in dictionary format but they're all separate implementations. I wanted a fresh implementation, if that makes sense as none of them quite does what I want.
Answer: (using csv library, thank for the suggestion @Serge Ballesta)
This solution may work for you :
import csv
result = {}
# open file
with open("file.csv", "r") as csv_file:
    parsed_csv = csv.reader(csv_file) # parse data with csv library
    next(parsed_csv) # skip first line
    # store line in dictionnary
    for line in parsed_csv:
        result[line[0]] = line[1:]
print(result)

This code will print :

{"head": ["H-EH-D", "1", "NSING"], "bottle": ["B-O-T-UH-L", "2", "NSING"], "fall": ["F-AW-L", "1", "VBASE"]}

for your example.
Comment: Sigh..., why do you split the line *by hand* instead of using the `csv` module from the standard library?
Answer: I had created test.csv file with only two inputs as followed:
head,H-EH-D,1,NSING
bottle,B-O-T-UH-L,2,NSING

My code:
import csv

my_dict = {}
with open('test.csv', mode='r') as infile:
    reader = csv.reader(infile)
    for row in reader:
        key, value = row[0], row[1:]
        # my_dict={rows[0]:rows[1:] for rows in reader}
        my_dict[key] = value

print(my_dict)

The output of the above code looks like:
{'head': ['H-EH-D', '1', 'NSING'], 'bottle': ['B-O-T-UH-L', '2', 'NSING']}


Create Sharepoint List which has gantt view - programmatically

Question: I am new to Sharepoint therefore don't know much - any help would be highly appreciated.
Basically I want to programatically (in the same project):

Create a List and make it a Gantt View
Add add appropriate columns (that would generate the Gantt chart) to the list
And finally I would like to add values/data to the columns created via this code

If there is a sample code or any tutorial...please
Any help would be much appreciated please
Thank you so much
Answer: Try this:
<code>using (SPSite site = new SPSite("http://yoursite/"))
{
    using (SPWeb web = site.OpenWeb())
    {
        Guid id = web.Lists.Add("listname", "descr", // 1
                                 SPListTemplateType.GanttTasks);

        SPList list = web.Lists[id]; // 2
        list.Fields.Add("display name", SPFieldType.Text, false);
        list.Update();

        // You should use "InternalName" to update your field values
        foreach (SPField field in list.Fields)
        {
            Console.WriteLine("{0}\t{1}", field.InternalName, field.Title);
        }

        SPListItem item = list.Items.Add(); // 3
        item["display name"] = "my value";
        item["PercentComplete"] = 1; // 100%
        item["StartDate"] = DateTime.Now;
        item["DueDate"] = new DateTime(2009, 12, 31);
        item.Update();

        Guid itemId = item.UniqueId;
        SPListItem itemUpdate = web.Lists["listname"].Items[itemId];
        itemUpdate["PercentComplete"] = .45; // 45%
        itemUpdate.Update();
    }
}
</code>
HTH
Comment: Thank you very much for your reply...Will this show the list automatically as a gant chart?

Thank you so much!
Comment: I meant linking the gantt properties such as startdate, enddate ,etc...please?
Comment: Sorry to be a pain but when i add the other properties it does not work

i want to add the startdate, end date and other details as shown below

                    list.Update();        SPListItem item = list.Items.Add(); // 3

                    item["Title"] = "TaskTest";
                    item["Task Status"] = "In Progress";
                    item["% Complete"] = 59;
                    item["Start Date"] = "10/10/2009";
                    item["Due Date"] = "25/10/102009";
                    item.Update();
Comment: superb! this works perfect - last one more favour please...i really appreciate...                     item["Start Date"] = 10/10/2009;      is not working for me.....how can i add the date do i have to use speech marks plsss??

thank you so much....god bless!
Comment: WORKS AMAZINGLY GREAT! THANK YOU SO MUCH!!! YOU'VE BEEN VERY HELPFUL

THANK YOU!!!
Comment: One last question....once the list has been created and i have added one record...if i want to add more records will i use Getlist instead of the Add? And also if i want to update the same values again? e.g you've set the % to 100 and for e.g. i wish to change it to 45? please

thank you!
Comment: i've created the new question as requested - can you please help?

http://stackoverflow.com/questions/1578361/update-sharepoint-list-item


How to put space between switch button and its text in android?

Question: I have the following element:
<Switch
    android:text="Data about client?"
    android:id="@+id/connected" />

But on designer the switch button and its text "Data about client?" are very glued together. I tried putting space between ? and " like that :
android:text="Data about client?    "

But I don't like that type of solution very much
Answer: I had the same issue, but for me the accepted answer of Sravan Sriram did not solve the problem.

What worked for me was the tag
    android:switchPadding = "10dp"

Minimum space between the switch and caption text. docs
Comment: `app:switchPadding="10dp"` worked for me for `SwitchCompat`
Answer: Sure, kindly use this
android:switchPadding="5dp"

Answer: If you are using androidx.appcompat.widget.SwitchCompat then use                 app:switchPadding="8dp". This is work for me
Comment: And that's true for `com.google.android.material.switchmaterial.SwitchMaterial`
Answer:
Use tag "android:thumbTextPadding"
Comment: This is not the correct answer. [This](https://stackoverflow.com/a/49184365/4334743) is actually correct.


Ruby using helpers in single script

Question: I am wanting to use the pluralize text helper in a ruby script I am writing, but can't find anywhere on how to include Rails helpers in a single ruby script. I know you need to include the helper module and require the helpers, but like I said I am not 100% sure on how to get it to work.
Comment: Rails is a framework and so has a necessary amount of coupling. In RoR 3 they tried to minimize this but your best bet is to grab that module, try to use it, and see what it asks for when running. The easiest way of course would just be to include the whole framework and only use the bits you need.
Answer:
<code>
require 'action_view'
include ActionView::Helpers::TextHelper
puts pluralize(2, 'person')
</code>

(Requires gem actionpack installed, tested with ruby 1.9.1, actionpack 3.0.3)
Answer: Or you can use the inflector in ActiveSupport, assuming you have the activesupport gem installed:
<code>$ irb
>> require 'active_support/inflector'
=> true
>> "person".pluralize
=> "people"
</code>

Ruby using helpers in single script


installation java error

Question: when i trying to install java in my ubuntu 14.04 os from
apt-get install openjdk-7-jdk

error shows
Errors were encountered while processing:
 libqt4-sql-sqlite:amd64
E: Sub-process /usr/bin/dpkg returned an error code (1)

how to resolved it
Answer: Did you try to install this package before libqt4-sql-sqlite?
It looks like you tried to install it before and it wasn't installed correctly.
This doesn't mean that java was not installed try executing java --version on your machine it must work.
To delete this problem try running sudo apt-get autoremove this must remove unconfigured and broken packages from your system.
Comment: E: dpkg was interrupted, you must manually run 'dpkg --configure -a' to correct the problem.
when i try apt-get autoremove
Comment: Did you try if java is working?
Comment: It appears that `libqt4-sql-sqlite` is installed but not configured try to configure it with `dpkg --configure -a`.

installation java error


Is it kosher to memory map a file a second time but with a larger size?

Question: In my application, one file on disk is created and memory mapped with an initial size. If I apply a second memory mapping to the file, with a larger size, the file expands to the new size. Windows lets me do this without error but I don't know if it's actually kosher. Are there any problems with a second memory mapping with a larger size?
Comment: No, I don't think a Rabbi will approve.
Comment: @MarkRansom, says the (language) agnostic. ;)
Comment: You question is if there is a problem with having same memory mapped twice in a single process or are you worried about something more?
Comment: The question is if it's okay to have a second mapping with a larger size than the first one. I'll clarify the question.
Answer: The CreateFileMapping documentation has this to say:

After a file mapping object is created, the size of the file must not exceed the size of the file mapping object; if it does, not all of the file contents are available for sharing.

This would appear to imply (since no other downsides or prohibitions are mentioned) that the only side effect of mapping a file a second time with a larger size is that the first mapping won't be able to see the whole thing (obviously).


Should I share unit control in Starcrarft 2 2v2?

Question: Some time ago I played a lot of Warcraft 3 2v2. I was even quite decent.
Back then most players shared their units, as micro was way more important. People hated it  when their hero died because they could not retreat with allied units blocking the way.
So it was accepted that everybody shared their units after the obligatory "gl hf".
I am currently low diamond 2v2 and up until now no one shared their units with me or offered it.
Is there a reason for this? Should I start sharing my units?
Comment: What is the 2v2 tag? It has no description.
Comment: It refers to battles between two teams of two players each. At present, the scope of the tag is actually limited to Starcraft 2, probably because it's the only RTS people get that serious about at the moment.
Comment: This question is truly conditional. There is no right or wrong answer. It depends on your opponent, yourself, and any strategies that occur. It is all preference. You don't know what your teammate will do with the control and there is no way to know unless it is a premade team. It is not a norm however to simply give control from the start of the match. I'm assuming this is for random 2v2s.
Comment: @Nick122 I disagree that this is truly conditional. Of course situation and user preference is a part of it, but there are strategic and tactical reasons to consider, as enumerated below.
Comment: Though it is really conditional, answer will be very useful and interesting to lot of people
Answer: Shared control really depends on the situation. First, a few things to remember:

Shared control does not have to be permanent for the game
Shared control does not have to be mutual

A few scenarios where sharing control in a random team would be beneficial would be;

Early rushes, such as combined or mixed zealot, zergling or marine rush. There is a huge benefit in making these combined rush armies act as a single army instead of scattered control. This also allows the off player to focus more on economy and tech instead of micromanagement.
Terran walls, and only during the early game.

However, shared control is much more beneficial when you have a trusted partner that you play with often and have a good line of communication with. Shared control in these scenarios allow you to act as a redundant set of eyes for each others armies. For example, units or armies that stray out of position can be saved by a command instead of mad pinging and yelling.
Shared control with an ally also allows better use of spell casters or micro management of certain blocks of units (e.g. one guy harass with all available air while the other distracts with all available ground at the front door). There are many different scenarios which this can be useful, not restricting strategy to the owner of the unit but instead the type of unit.
If there is no line of communication (usually in random teams), then sharing control is usually a bad idea. You can not predict that your strategy will align sufficiently with theirs to prevent unit control conflicts.
Answer: I would only share control with players you trust, i.e. premade teams. Chances are, your ally has horrendous unit control and move commands your army into the opponents siege tanks.
There is no rule for sharing control at the moment. Noone does it, noone asks for it except sometimes for terrans in shared bases that share control so allies can lower supply depots.
Answer: As a Terran player I almost always share my units, unless they are another Terran player and help me build the wall. A couple reasons why i share units is either they are rushing and im working on a transition incase the rush (which have a pretty high failure rate) fails. I do this so that my ally can move my units with his/hers and I usually dont screen over until they are nearing the base. The other reason i usually let my allies take control is because of my wall, I find it very annoying to have to stop what im doing to lower my wall (although sometimes i macro it and just hit a couple hotkeys instead), so this allows them to do it instead of me.
I would say the only time I for sure dont is if it is obvious that my ally is a bit rusty/new to the game.
Answer: Some people prefer not to have shared control, because it can make it harder to micro. If your armies are fighting together and you try to select some Colossus over here, you might accidentally select your allies' medivacs.
It can also result in inefficient casting - if we're both trying to forefield a choke, we could end up with a super weird, inefficient pattern that wastes energy.


Remove some of trailing zeros from decimal

Question: I have column decimal(10,5) — VALUE, and column int — PICTURE.
So, I need to round VALUE to PICTURE digits after decimal point.
For example:

if VALUE = 10.50000 and PICTURE = 2, I want to get 10.50;
if VALUE = 0.15371 and PICTURE = 3, I want to get 0.154

If I use just Round() or Cast(Round(...) as nvarchar), then I have trailing zeros. If I Cast() to float, then I loose zeros.
Is there any solution?
Comment: This is something for your presentation layer, not the RDBMS. A Column can only have 1 data type, and that data type can't have varying scales, precisions and lengths. For a `decimal` column, if that column is defined as a `decimal(10,5)` it will **always** have 5 decimal places, even if none are needed. If you want a vary *display* value, get your display layer to handle that.
Comment: @Larnu, You are right. I should deal with this on presentation layer. But always want an easy solution, like get everything in one select.
Answer: You can use the str() function with trim():
select trim(str(value, 20, picture))

str() converts a number to a string with the specified length and precision.  Sadly, it produces a fixed length string, left padded with spaces.  The trim() removes the spaces.


Drawing custom UITableCells with the correct data

Question: I've got a UITableView with custom tablecells. First I had a version which implemented a separate NIB file to create the custom cell view, but this makes scrolling awfully slow. The official answer is to do your own drawing, so I implemented a drawing variant (ABTableViewCell).
Everything is working now, except for the drawing of the cells that are out of the view. The first 8 cells are drawn correctly - they get the correct title, image, etc. - but everything outside of that has a random repetition of already drawn cells. Only when the cell is clicked/touched the labels and images of the cell are updated with the correct data.
My RootViewController implements UITableViewDataSource and CustomCell is initialised there.
I've verified that all the data is passed correctly to the CustomCell, so it must have something to do with the drawing. I think I've tracked it down to the fact that the drawContentView method is only called for the cells which are in view and not for the ones that scroll into view.
How would I trigger the drawContentView again to update the cells which come into view? Is that something I would have to do from my RootViewController, using something else than: (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath?
CustomCell.h:
#import "ABTableViewCell.h"

@interface CustomCell : ABTableViewCell {
  NSString * cellSubText;
  NSString * cellText;
  NSString * cellImage;
  NSString * cellIcon;
  NSString * cellId;
}

@property (nonatomic, copy) NSString *cellSubText;
@property (nonatomic, copy) NSString *cellText;
@property (nonatomic, copy) NSString *cellImage;
@property (nonatomic, copy) NSString *cellIcon;
@property (nonatomic, copy) NSString *cellId;

@end

CustomCell.m:
#import "CustomCell.h"

@implementation CustomCell

@synthesize cellSubText, cellText, cellImage, cellIcon, cellId;

static UIFont *celSubFont = nil;
static UIFont *cellFont = nil;

+ (void)initialize {
    if(self == [CustomCell class]) {
        cellSubFont = [[UIFont systemFontOfSize:13] retain];
        cellFont = [[UIFont boldSystemFontOfSize:17] retain];
    }
}

- (void)setFirstText:(NSString *)s {
    [cellSubText release];
    cellSubText = [s copy];
    [self setNeedsDisplay];
}

- (void)setLastText:(NSString *)s {
    [cellText release];
    cellText = [s copy];
    [self setNeedsDisplay];
}

- (void)drawContentView:(CGRect)r {
    CGContextRef context = UIGraphicsGetCurrentContext();

    UIColor *backgroundColour = [UIColor whiteColor];
    UIColor *categoryColour = [UIColor grayColor];
    UIColor *titleColour = [UIColor blackColor];
  if(self.highlighted || self.selected) {
    backgroundColour = [UIColor clearColor];
        categoryColour = [UIColor whiteColor];
    titleColour = [UIColor whiteColor];
    }

    [backgroundColour set];
    CGContextFillRect(context, r);

    CGPoint pCategory;
    pCategory.x = 60;
    pCategory.y = 3;

    [categoryColour set];
  [cellSubText drawAtPoint:pCategory forWidth:235 withFont:categoryFont minFontSize:13 actualFontSize:NULL lineBreakMode:UILineBreakModeTailTruncation baselineAdjustment:UIBaselineAdjustmentNone];

  CGPoint pTitle;
    pTitle.x = 60;
    pTitle.y = 17;

  [titleColour set];
  [cellText drawAtPoint:pTitle forWidth:235 withFont:titleFont minFontSize:17 actualFontSize:NULL lineBreakMode:UILineBreakModeTailTruncation baselineAdjustment:UIBaselineAdjustmentNone];

  //Display the image
  CGPoint pImage;
    pImage.x = 5;
    pImage.y = 5;

  NSData *imageData = [[NSData dataWithContentsOfURL:[NSURL URLWithString:cellImage]] retain];
  UIImage *image = [UIImage imageWithData:imageData];
  [image drawAtPoint:pImage];
}

- (void)dealloc {
  [cellSubText release];
  [cellText release];
  [cellIcon release];
  [cellImage release];
  [super dealloc];
}
@end

RootViewController.m
#import "CustomCell.h"
#import "MyAppDelegate.h"
#import "RootViewController.h"
#import "DetailViewController.h"

@implementation RootViewController
@synthesize tableDataArray;

- (void)viewDidLoad {
  [super viewDidLoad];
}

//Override the default initWithNibName method
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil tableDataSource:(NSArray*)tableData {
  if (self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil]) {
    // Custom initialization
    tableDataArray = [tableData retain];
  }
  return self;
}

-(void)viewWillAppear:(BOOL)animated {
  appDelegate = (MyAppDelegate *)[[UIApplication sharedApplication] delegate];
  [super viewWillAppear:animated];
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
  return [self.tableDataArray count];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *CustomCellIdentifier = @"CustomCellIdentifier";

    CustomCell *cell = (CustomCell *)[tableView dequeueReusableCellWithIdentifier:CustomCellIdentifier];
    if(cell == nil) {
        cell = [[[CustomCell alloc] initWithFrame:CGRectZero reuseIdentifier:CustomCellIdentifier] retain];
    }
  cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
  NSUInteger row = [indexPath row];
  NSDictionary *rowData = [self.tableDataArray objectAtIndex:row];
    cell.cellSubText = [rowData objectForKey:@"Date"];
    cell.cellText = [rowData objectForKey:@"Name"];
  cell.cellImage = [rowData objectForKey:@"Image"];
  cell.cellId = [rowData objectForKey:@"Id"];

    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
  NSString *selectedCell = [tableDataArray objectAtIndex:indexPath.row];

  DetailViewController *detailViewController = [[DetailViewController alloc] initWithNibName:@"DetailView" bundle:[NSBundle mainBundle]];
  detailViewController.selectedCell = selectedCell;
  [self.navigationController pushViewController:detailViewController animated:YES];
  [detailViewController release];
  detailViewController = nil;
}

- (void)dealloc {
    [super dealloc];
}

@end

Comment: Can you put your code for the TableViewController especially the cellForRowAtIndexPath and the way you're using the dequeueReusableCellWithIdentifier ? From your description, this sounds like if you're reusing an existing cell but don't apply the correct values to it.
Comment: I've updated the post with the TableViewController code.
Comment: I did some testing today and I think your comment describes the situation quite accurately. How would you suggest I use dequeueReusableCellWithIdentifier?
Answer: - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *CustomCellIdentifier = @"CustomCellIdentifier";

    CustomCell *cell = (CustomCell *)[tableView dequeueReusableCellWithIdentifier:CustomCellIdentifier];
    if(cell == nil) {
        cell = [[[CustomCell alloc] initWithFrame:CGRectZero reuseIdentifier:CustomCellIdentifier] retain];
    }

static NSString *CustomCellIdentifier = @"CustomCellIdentifier";
The above bolded code is making such behavior for you.
In iphone, tableview reuses already created cells. which are not visible.
Ex: First 8 cells will be created separately. And when you scroll down, first few rows will   get hide. Now the hidden cells are going to be reused by the cells which are going to show now. This is why you are getting this behavior:) Try to give unique identifier if your table view contents are less.
or
If your cell is a subclass of UITableViewCell, you can override
- (void)prepareForReuse
which gets called just before the cell is returned from
- (UITableViewCell *)dequeueReusableCellWithIdentifier:(NSString *)identifier
Comment: The cell is indeed a subclass of UITableViewCell so prepareForReuse gets called each time a cell is drawn. But it's getting the wrong data from RootViewController. My guess is that the static declaration of the CustomCellIdentifier is indeed to blame. The problem is I have quite a lot cells to display, so a unique identifier might not be the solution (I'm not sure how slow it would be). Would there be another way to achieve this?
Answer: Perhaps the table view is reusing your cells and giving you random results by reusing the currently setup cells; have you looked into - (void)prepareForReuse on the UITableViewCell class?
Answer: -(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    int myButtonTag = 1000+(10*indexPath.section)+indexPath.row;
    NSString *kCellID = [NSString stringWithFormat:@"cellId_%i",myButtonTag];

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:kCellID];
    if (cell == nil)
    {
       //[[cell viewWithTag:myButtonTag] removeFromSuperview];
       cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:kCellID];
    }

    cell.accessoryType = UITableViewCellAccessoryNone;
}

In order to remove data from your cell while scrolling fast in a UITableView (especially in an ARC controlled environment), do remember to set a Unique CellIdentifier in your cellId string, which dequeues the older cell. This way it exempts it from populating the repeated cells. Hope you find it appropriate and to your liking. Cheers!


Lp space Example

Question: How are spaces connected $L_{\infty}(E)$ and $L_{p}(E)$, $|E| = \infty$?
$$f \in L_\infty, \text{ but } f\notin L_1 \quad f = \frac{1}{x} \quad  E = [1, \infty)$$
What can we say about reverse insertion? I think there is a suitable example
Answer: Neither containment holds for Lebesgue measure if $|E| = \infty$. Your example shows that $L^{\infty}(E) \not\subset L^1(E)$. For a counterexample in the reverse direction, let $E = (0,\infty)$ and define
$$f(x) = \begin{cases} \frac{1}{\sqrt{x}} & \text{ if }0 < x < 1 \\ 0 & \text{ otherwise} \end{cases}$$
Then $f \in L^1(E)$ but $f \not\in L^{\infty}(E)$.

Lp space Example


How to specify the TLS ciphers when connecting to HTTPs servers in clojure

Question: When I am using `slurp' to get the HTML page from "https://clojuredocs.org/clojure.core/slurp", I always get the Exception like:
SSLHandshakeException Received fatal alert: handshake_failure  sun.security.ssl.Alerts.getSSLException (Alerts.java:192)

But there is no problem when I use the 'wget' download the same page.  After doing a comparison of the pcaps, I find the problem might be caused by the cipher suites chosen by the client. When I am using 'slurp', there is 22 cipher suites selected, while the wget selects 66 cipher suites (I can't list all the cipher suites here).
So my question: is there a way to configure the default cipher suites of the JVM to make slurp work with "https://clojuredocs.org"?
Comment: You might want to look at https://stackoverflow.com/questions/34136168/force-jvm-to-use-certain-cipher-for-https-connections
Answer: You probably want to solve this on the JVM level.  For example on my machine it just works:
(subs (slurp "https://clojuredocs.org") 0 10)
"<!DOCTYPE "

I tried this both with IBM Java:
java version "1.8.0_161"
Java(TM) SE Runtime Environment (build 22.214.171.124 - pxa6480sr5fp11-20180326_01(SR5 FP11))
IBM J9 VM (build 2.9, JRE 1.8.0 Linux amd64-64 Compressed References 20180309_380776 (JIT enabled, AOT enabled)

and Oracle Java:
java version "1.8.0_171"
Java(TM) SE Runtime Environment (build 1.8.0_171-b11)
Java HotSpot(TM) 64-Bit Server VM (build 25.171-b11, mixed mode)

Sounds to me like you need a recent Java version and everything will be fine. Which version are you using?


Store default translation if key is missing

Question: I am trying to store a default translation if a translation is missing in Rails.
After much struggle I came up with this:
backend = I18n.backend
if not backend.exists?(locale, key)
  backend.store_translations(locale, {key => locale.to_s + "-" + key.to_s})
end

The problem is, it stores the default values but it does not find them. Any idea what is wrong here?
Comment: What code are you running to find the values after they are stored?
Comment: I am using a key-value backend and use Redis with it. The `KeyValue` backend is trying to find the values. I just use `t` to translate strings.
Answer: After so much headache, I found the problem:
It is because the dots in my keys are converted to their unicode character when stored, so, they are not found. For example actions.save is converted to actions\u0001save.
I don't know why this happens.


XML UTF-8 encoding checking

Question: I have an XML structure like this, some Student item contains invalid UTF-8 byte sequenceswhich may cause XML parsing fail for the whole XML document.
What I want to do is, filter out Student item which contains UTF-8 byte sequences, and keep the valid byte sequences ones. Any advice or samples about how to do this in .Net (C# preferred)?
BTW: invalid byte sequences I mean => http://en.wikipedia.org/wiki/UTF-8#Invalid_byte_sequences
<code><?xml version="1.0" encoding="utf-8"?>
<AllStudents>
  <Student>
    Mike
  </Student>
  <Student>
    (Invalid name here)
  </Student>
</AllStudents>
</code>
thanks in advance,
George
Answer: I don't know C#, so I'm afraid I can't give you code to do this, but the basic idea is to read the whole file as a utf-8 text file, using a DecoderFallback to replace invalid sequences with either question mark characters or the unicode chacter 0xFFFD.  Then write the file back out as a utf-8 text file, and parse that.
Basically, you separate out the operation of "wiping out bad utf-8 sequences" from the operation of "parsing the xml file".
You should probably even be able to skip writing the file back out again before running the XML parser to read in the fixed data; there should be some way to write the file to an in-memory byte stream and parse that byte stream as XML.  (Again, sorry for not knowing C#)
Answer: That's pretty hard to do. You won't get an XML parser to parse a document with invalid characters in it, so I think you're reduced to a couple of options:

Figure out why the encoding is wrong - a common problem is labeling the document as UTF-8 (or having no encoding declaration) when the document is actually written in Latin-1.
Take out the bad sections by hand.
Try and find a tag soup parser for .NET that will continue parsing after the error.
Reject the invalid XML document.
Comment: Any ways to use regular expression to do such kinds of check?
Comment: BTW: tag soup is for Java, not .Net?
Answer: Very close from XML encoding issue.
Comment: That question is dealing with how to check the whole XML document is valid, but this question is about how to filter out invalid ones. Any ideas for this question?

XML UTF-8 encoding checking


Total Possible Amperage of Sub-Breaker Box

Question: I've been trying to find more information on how cheaters work but could never come to a definite decision on how many total amps they might pull.

Basically my question comes down to this:

In the image above, the sub unit is supplied with a max of 125 Amps. Does the two pole 20 Amp "cheater" supply a maximum of 20 Amps or 40 Amps?

a) If it supplies a maximum of 40 amps, then wouldn't that mean the total possible Amperage that it could try to pull would be 130 Amps, and thus could try to overdraw power, and would pop the main breaker?
b) If it supplies a maximum of 20 amps, could I safely swap out one of the 15 amp breakers for a 20 amp breaker, provided the cables used are 12 Gauge?
Answer: 40 Amps.  I've never heard those called "cheater" before - I think space saving is the term I've heard.
The total amps of all breakers in a panel often exceed the overall rating of the main breaker in the panel.  The reality is that not all circuits are pulling anywhere close to 100% of their rating 100% of the time.  Yes you can trip the main breaker.
The electrical service 125 Amps in your case is sized based on various factors.  It isn't sized based on the breakers (though the breakers would be associated with the applicances/devices used to size the service).  Here is an example online calculator that can help size the service.
http://www.douglashelmer.com/calculators/electrical/residential-service/index.htm
Comment: Cheaters was the original trade name as they were listed as non current limiting , they had no rejection feature so the buss locations could be overloaded tandem large breakers on both sides could do it. You can still find them on line today (non current limiting) stickers on the side.
Comment: @Max -- you'll have to go through the *entire* circuit and make sure that the wiring's 12AWG
Comment: So, would it generally be safe to replace one of the 15 amp ones with a 20 amp breaker? (again as long as the cable is 12 gauge, which it is)
Answer: Ok first we don't add values up like that but a cheater, tandem or double stuff is rated for the amperage on the handle so yes that cheater can draw up to 40 amps without tripping on that one leg 20 at each breaker.
What if you put a 60 amp breaker in that panel that and a 40 and 4 20's , it is possible it would be just fine we add up the loads on the circuits and in some cases may not count one, for example the 60 for an electric heater and a 40 for a AC unit you would only count the 60 the 40 not running the same time as the 60, this is all part of load calculations your 15 amp breaker will rarely have 12 amps on them when they do have that or 15 it is usually for short periods of time. These are additional safety's built into code and the diversity of the loads makes a difference SO is your box overloaded? Not even close you really could have much larger breakers as my examples tried to show you are probably drawing just about 1/2 the rated current of this sub and your limiting factor is the breaker feeding it if you have a 125 amp breaker feeding this sub it will protect the panel.
You have a circuit that is all 12 gauge wiring and would like to bump the breaker from a 15 to a 20 go ahead , at some point if you start tripping your main you have gone two far but I rarely see that with all small breakers and a few tandems  .
As long as your panel is rated for tandems it is fine the buss can handle the load. If they are true cheaters (non current limiting) devices you may overload that buss location but I doubt it with a 15 full size on the other side.
Comment: You will be fine I would do it on this panel with out measuring as long as the circuit wire is 12 awg.
Comment: @fresh codemonger , a non CTL breaker is for replacement only these were popular in the early days of circuit breakers back when we had the crazy 20 or 24 limit prior to the CTL rejection feature that's why they were called cheaters . I mis spoke or typed the name is non circuit limiting so the bus that was designed for 20 breakers but a 150 amp panel could actually handle 30 circuits but code limited the breakers so this was the cheat getting full use. This is how I remember it but may be wrong. when the panel has a listing like 12/20 or 30/40 the first # is the spaces 2nd circuits post CTL.
Comment: Thanks, I meant to mention in the question, that the main thing I wanted to solve is if it would generally be safe to upgrade the 15 amp to a 20 amp circuit, but incorrectly assumed it wouldn't be smart to potentially overdraw the circuit with the amperage in the first place.
Comment: What do you mean by overload that buss location?  If the cheater breakers do not limit current - that seems crazy - then you could draw more current then the wire connecting to those breakers is able to handle with out tripping the breakers and the wire could start to melt and start a fire?  I am assuming cheaters can't be code approved.


Model names from ViewModel in Razor

Question: I have the following ViewModel:
public class ProfileViewModel
{
    public BandProfileModel BandProfile { get; set; }
    public MusicanProfileModel MusicianProfile { get; set; }
    public RegularProfileModel RegularProfile { get; set; }
}

I'm using this ViewModel In my View to Post a form:
 @using (Ajax.BeginForm("RegisterBand", "NewProfile", new AjaxOptions() { HttpMethod = "Post",
            InsertionMode = InsertionMode.Replace
        }))
        {
            @Html.AntiForgeryToken()
            @Html.ValidationSummary(true, "", new { @class = "text-danger" })

                        Bandname

                        @Html.EditorFor(x => x.BandProfile.Name, new { htmlAttributes = new { @class = "form-control" } })
                        @Html.ValidationMessageFor(x => x.BandProfile.Name, "", new { @class = "text-danger" })

Here Is my RegisterBand model:
  public ActionResult RegisterBand(BandProfileModel model)
        {

            if (ModelState.IsValid == false)
            {
                return Json(JsonRequestBehavior.AllowGet);
            }

            return View("Index");
        }

The problem I have is that the name-attribute of Input fields are BandProfile.Name, BandProfile.Genre, instead of just Genre and Name.
How can I solve this problem?
Comment: In addition to the accepted answer, you can also use `public ActionResult RegisterBand([Bind(Ptefix = "BandProfile")] BandProfileModel model)` which effectively strips the prefix when binding
Answer: You could just change your RegisterBand ActionResult to accept a ProfileViewModel.
public ActionResult RegisterBand(ProfileViewModel model)
{
    if (ModelState.IsValid == false)
    {
        return Json(JsonRequestBehavior.AllowGet);
    }

    return View("Index");
}

Your HttpPost needs to accept an instance of the same object that you pass into the form, otherwise it won't know what names to bind to.
Answer: if you want to change the name and id of control you can do it like this
 @Html.EditorFor(x => x.BandProfile.Name, new { htmlAttributes = new { @class = "form-control", @id="Genre",@Name="Genre"  } })

Model names from ViewModel in Razor


Correct password cannot be authenticated to run Synaptic Package Manager GUI

Question: I cannot access my synaptic package manager(in GUI) due to authentication error. Even though I enter the correct user password, it always say that "Your authentication attempt was unsuccessful. Please try again."
I also configured the sudoers file and add/edit my user priveleges:
maximus ALL=(ALL:ALL) ALL

below the root priveleges.
Is there any other way to access or any other configurations to access it in GUI?
Comment: How did you edit the `sudoers`-file when you cannot `sudo`?
Comment: i go to boot setup then go to advance settings and i use recovery mode then i use root shell. there, i use visudo.
Answer: I solved it!.. I change the one that launches the synaptic by replacing
Exec = synaptic-pkexec
in usr/share/applications/synaptic.desktop
pkexec is the one that manages authentication when you open synaptic(that is the flaw) which it doesn't authenticate you even though your root password is correct. I replace it to
gksu synaptic %u

then, save it.(You must have a gconf-editor and gksu installed.)
After that, I press alt+ F2 then I type there "gconf-editor" and then I go to apps>gksu and then mark the sudo-mode.
If pkexec gives you trouble launching synaptic in GUI, better try to change its launcher to gksu. That will do.