text:
Q: Not getting proper output for RSA algorithm implemented with BigInteger I am new to programming and network security. I am trying to implement RSA algorithm for my classwork but I am not getting correct output so please help me, its not giving the same plain text while decrypting.
following is my code
import java.security.*;
import java.lang.*;
import java.math.*;

public class RSAalgo
{
    BigInteger p,q,n,d,e,ph,t;
    SecureRandom r;

    public RSAalgo()
    {
        r=new SecureRandom();
        p=new BigInteger(512,100,r);
        q=new BigInteger(512,100,r);

        System.out.println("\n RSA ALGO");
        System.out.println("\n Prime No P : "+p.intValue());
        System.out.println("\n Prime no Q : "+q.intValue());

        n=p.multiply(q);
        ph=(p.subtract(new BigInteger("1")));

        e = new BigInteger("2");

        while((ph.gcd(e).intValue()>1)||(e.compareTo(ph)!=-1))
        e=e.add(new BigInteger("1"));

        d=e.modInverse(ph);

        System.out.println("public key = "+n.intValue()+", "+e.intValue());
        System.out.println("Private key = "+n.intValue()+", "+d.intValue());

        BigInteger msg=new BigInteger("21");
        System.out.println("Message is "+msg);

        BigInteger enmsg=encrypt(msg,e,n);
        System.out.println("Encrypted message is "+enmsg.intValue());

        BigInteger demsg=decrypt(enmsg,d,n);
        System.out.println("Decrypted message is "+demsg.intValue());

    }

    BigInteger encrypt(BigInteger msg,BigInteger e, BigInteger n)
    {
        return msg.modPow(e,n);
    }

    BigInteger decrypt(BigInteger msg,BigInteger d, BigInteger n)
    {
        return msg.modPow(d,n);
    }

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

input: 21
encrypted msg and decrypted msg are random everytime

A: Your phi is calculated incorrectly. It must be phi = (p - 1)x(q - 1), but it actually is phi = (p - 1). You forgot to multiply an additional term. Or in other words:
ph = p.subtract(BigInteger.ONE).multiply(q.subtract(BigInteger.ONE));

See the Wikipedia article on RSA.

Other considerations:
Unpadded (textbook) RSA is insecure. You need to implement secure padding such as OAEP.
RSA itself can only encrypt something that is numerically smaller than the modulus. If your plaintext is larger (don't forget the padding), then you need hybrid encryption.

A: I feel the accepted answer is somewhat misleading at this point in time, so I thought I would simply edit your code to incorporate the comments of @Artom B. Please compare the code below to your code and the code posted by @Krzysztof Cichocki to see where your mistakes are. I also used BigInteger.ONE instead of new BigInteger("1") but that is mostly a cosmetic change.
import java.math.BigInteger;
import java.security.SecureRandom;

public class RSAalgo {
    BigInteger p, q, n, d, e, ph, t;
    SecureRandom r;

    public RSAalgo() {
        r = new SecureRandom();
        p = new BigInteger(512, 100, r);
        q = new BigInteger(512, 100, r);

        System.out.println("\n RSA ALGO");
        System.out.println("\n Prime No P : " + p);
        System.out.println("\n Prime no Q : " + q);

        n = p.multiply(q);
        ph = (p.subtract(BigInteger.ONE)).multiply(q.subtract(BigInteger.ONE));

        e = new BigInteger("2");

        while ((ph.gcd(e).intValue() > 1) || (e.compareTo(ph) != -1))
            e = e.add(BigInteger.ONE);

        d = e.modInverse(ph);

        System.out.println("public key = " + n + ", " + e);
        System.out.println("Private key = " + n + ", " + d);

        BigInteger msg = new BigInteger("21");
        System.out.println("Message is " + msg);

        BigInteger enmsg = encrypt(msg, e, n);
        System.out.println("Encrypted message is " + enmsg);

        BigInteger demsg = decrypt(enmsg, d, n);
        System.out.println("Decrypted message is " + demsg);

    }

    BigInteger encrypt(BigInteger msg, BigInteger e, BigInteger n) {
        return msg.modPow(e, n);
    }

    BigInteger decrypt(BigInteger msg, BigInteger d, BigInteger n) {
        return msg.modPow(d, n);
    }

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

Here is the output from one run of this program:
 RSA ALGO

 Prime No P : 7385887478481685426993214602368774899822361657609273024676297215761456907576361503385555975157308399849328828600179690472123592317381855278505714472809701

 Prime no Q : 9697854674813414062564435136414673948111723349180632387293117086433856431627811334553449685531026027836405752904433352501524789604919970659422354853067003
public key = 71627263410839472181079411740104072578551746566830443612142954116975018729181714598122158332496727078551292122128676328582232680698169145364025223095271546289887132569293490463703371501767853891145781471271218830484185948403241381862567321829707888222282401077404230822288043321027073755612191149650621396103, 7
Private key = 71627263410839472181079411740104072578551746566830443612142954116975018729181714598122158332496727078551292122128676328582232680698169145364025223095271546289887132569293490463703371501767853891145781471271218830484185948403241381862567321829707888222282401077404230822288043321027073755612191149650621396103, 10232466201548496025868487391443438939793106652404349087448993445282145532740244942588879761785246725507327446018382332654604668671167020766289317585038789886592139896313428700864804674045572279580110668766543837295697679012843168241389911832006742841122102191831818029892152810377878779112321888797327931343
Message is 21
Encrypted message is 1801088541
Decrypted message is 21

If you look carefully at the encrypted message 1801088541 perhaps you can deduce the flaw that Artom alluded to when he stated "Unpadded (textbook) RSA is insecure". You need to implement secure padding such as OAEP."

A: This works for me, it is very old code written by me but it works, you need to implement the pojo classes, but those only hold the numbers and are trivial to implement. Compare the results from each step with this, it should help you to debug your code.
public class RSAService {
    private Key PublicKey, PrivateKey;

        public Primes newPrimes(int n) {
            Random r= new Random();
            Primes p = new Primes();
            p.p= BigInteger.probablePrime(n, r);
            p.q= BigInteger.probablePrime(n, r);
            p.e= BigInteger.probablePrime(n, r);
            return p;
        }

    public BigInteger extEuklides(BigInteger nwd_a, BigInteger nwd_b) {

                   BigInteger a, b;
           BigInteger r, q;
           BigInteger x, x1, x2;
           BigInteger y, y1, y2;
           BigInteger nwd;

               // a must be greater than b
           if (nwd_b.compareTo(nwd_a)>0)
           {
              nwd = nwd_b;
              nwd_b = nwd_a;
              nwd_a = nwd;
           }

           //initialize a and b
           a = nwd_a;
           b = nwd_b;

           //initialize r and nwd
           q = a.divide(b);
           r = a.subtract(q.multiply(b));
           nwd = b;

           //initialize x and y
           x2 = BigInteger.ONE;
           x1 = BigInteger.ZERO;
           y2 = BigInteger.ZERO;
           y1 = BigInteger.ONE;
           x  = BigInteger.ONE;
           y  = y2.subtract(q.subtract(BigInteger.ONE).multiply(y1));

           while (r.compareTo(BigInteger.ZERO)!= 0)
           {

              a = b;
              b = r;

              x = x2.subtract(q.multiply(x1));
              x2 = x1;
              x1 = x;

              y = y2.subtract(q.multiply(y1));
              y2 = y1;
              y1 = y;

              nwd = r;
              q = a.divide(b);
              r = a.subtract(q.multiply(b));
           }

           if (nwd.compareTo(BigInteger.ONE) == 0)
            // System.out.println(nwd_b+" * "+y+" mod "+nwd_a+" = 1");
                   {return y;}
                   return null;
    }

        public void newKeys(int size) {
            BigInteger fn;
            BigInteger n,d;
            Primes prim;
            do {
                 prim=newPrimes(size);
                 n= prim.p.multiply(prim.q);
                 fn= prim.p.subtract(BigInteger.ONE).multiply(prim.q.subtract(BigInteger.ONE));
            } while ((d=extEuklides(fn, prim.e))==null);
            PublicKey.mod=n;
            PublicKey.pow=d;
            PrivateKey.mod=n;
            PrivateKey.pow=prim.e;
        }

        public static void main(String[] args) {
            newKeys(512);
            // use the public and private key to encode decode by modpow

        }
}

class Key:
import java.math.BigInteger;

public class Key {
    BigInteger mod,pow;
}

class Primes:
import java.io.Serializable;
import java.math.BigInteger;

public class Primes implements Serializable {
    BigInteger p,q,e;
}


text:
Q: Disk failing on Dell Mini, are there diagnostic tools? my dell mini 10v running Ubuntu 10.10 runs ok for hours, but then will suddenly slow down drastically. Switching to a console shows lots of error messages, which also get into /var/log/syslog. These errors happen every couple of seconds. I'm figuring that the disk is failing, but is there anyway to be sure, and can laptop disks be replaced easily?
Mar 20 11:08:12 dell-mini kernel: [ 2476.378774] ata1.00: status: { DRDY ERR }
Mar 20 11:08:12 dell-mini kernel: [ 2476.378785] ata1.00: error: { UNC }
Mar 20 11:08:12 dell-mini kernel: [ 2476.449841] ata1.00: configured for UDMA/133
Mar 20 11:08:12 dell-mini kernel: [ 2476.449887] ata1: EH complete
Mar 20 11:08:14 dell-mini kernel: [ 2478.777754] ata1.00: exception Emask 0x0 SAct 0x0 SErr 0x0 action 0x0
Mar 20 11:08:14 dell-mini kernel: [ 2478.777976] ata1.00: BMDMA stat 0x24
Mar 20 11:08:14 dell-mini kernel: [ 2478.778059] ata1.00: failed command: READ DMA
Mar 20 11:08:14 dell-mini kernel: [ 2478.778162] ata1.00: cmd c8/00:08:43:3b:97/00:00:00:00:00/e0 tag 0 dma 4096 in
Mar 20 11:08:14 dell-mini kernel: [ 2478.778166]          res 51/40:00:47:3b:97/00:00:00:00:00/00 Emask 0x9 (media error)

A: If you go to "System" > "Administration" > "Disk Utility", you should see a list of your hard drives.
Click on the drive in question, and you can check the drive for errors, or view the SMART data and have the drive run some of it's own tests.
It doesn't look like the Mini 10v drives are too buried in the computer - they are directly beneath the keyboard, and are pretty easy to access.
Luckily, someone appears to have posted a great hard drive swap video on YouTube for your model that you can use as a guide.

A: You could also use the tool smartmon to run a extended test.
http://www.techrepublic.com/blog/opensource/using-smartctl-to-get-smart-status-information-on-your-hard-drives/1389

redpajama_set_name: RedPajamaStackExchange


text:
Q: How do you prove that there are infinitely many primes of the form $5 + 6n$? There should be infinitely many primes of the form $5+6n$. How do you prove it? The same should be true for $7+6n$.

A: Primes of the form $6n+5$ is particularly easy:
Suppose that there are finitely many primes of the form $6n+5$, namely
$p_1,\cdots, p_n$.
Consider
$p^*=6p_1\cdots p_n -1$.
Note that any odd prime other than 3, is of the form $6n+1$ or $6n+5$.
Thus, prime divisors of $p^*$ are either of the form $6n+1$ or $6n+5$.
The prime divisors of $p^*$ should have at least one prime divisor of the form $6n+5$.
This is a contradiction.
For primes of the form $6n+1$, use the following:
"Existence of $x$ in $x^2-x+1\equiv 0\textrm{ mod }p$ $\Longleftrightarrow$ $p$ is of the form $6n+1$."
Suppose there are only finitely many $6n+1$ primes, namely $p_1,\cdots, p_n$,
Then consider $p^*=(p_1\cdots p_n)^2-(p_1\cdots p_n) + 1$.
Prime divisor of $p^*$ should be of the form $6n+1$ according to the above equivalence.
This is a contradiction.

A: If we cross out from sequence of positive integers all numbers divisible by 2 and all numbers divisible by 3, then all remaining numbers will be in one of two forms:
$S1(n)=6n+5=5,11,17,...$ or $S2(n)=6n+7=7,13,19,....n= 0,1,2,3,...$ So all prime numbers also will be in one of these two forms and ratio 0f number of primes in the sequence $S1(n)$ to number of primes in the sequence $S2(n)$ tends to be $1$.


text:
Q: Is storing aws cognito JWT key in frontend javascript insecure? I was reviewing a website's javascript files to find an endpoint i wanted,during this i found a line like this.

DASHBOARD_API_Token=eyJraWQiOiJVS2paTnB3SWdBK292QzB3RWdxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx

When i decoded the Above JWT i found entities like kid, username, useremail, iss = http://cognito-idp.us-east-1.amazonaws.com/{pool-id}
I have read few amazon resources which tell that its possible to fetch aws credentials using the above token. Given that i only have the jwt token what is possible and is it that i have to contact the website to revoke the current token?

A: Well, AWS Cognito is quite an interesting beast when it comes to its JWT tokens and what you can do with them.
Firstly, when you authenticate the user against Cognito User Pool, you get 3 different tokens: AccessToken, IdToken, and RefreshToken. Both AccessToken and IdToken are valid for exactly 1 hour (and you can't change it). This is why you get RefreshToken, which you can use to get new pair of AccessToken and IdToken by calling, for example, InitiateAuth. RefreshToken is by default valid for 30 days, but you can change it in the settings of your Cognito User Pool.
AccessToken
This is the most powerful token that is given by Cognito. If you possess a valid AccessToken, you can call several quite sensitive Cognito APIs.
One very surprising example is that you can call DeleteUser API by providing AccessToken and it will completely remove your account from Cognito User Pool. The "nicest" thing here is that app developer can't stop you from doing it if you've got a valid AccessToken. AWS devs are saying that "its by design". That was one of the strongest reasons why we decided not to pass Cognito Access Token onto the application frontend.
Speaking of the payload of AccessToken, the only potentially sensitive claim is the client_id, which contains the Cognito Client Id, which was used to authenticate the user. If this client does not have a client secret (which should probably be considered a security flaw in the first place), then the client_id can be used to call quite wide range of Cognito APIs. However, Cognito considers client_id to be public information. All other claims are considered public, you can see the full list of claims here.
IdToken
Contains the information about the player. It may contain some personal information about the player depending on what standard claims and custom attributes were configured in your Cognito User Pool, however it is also possible to suppress or override those claims using Pre Token Generation Lambda Trigger. Using this trigger allows one to hide or mask player attributes, which are considered sensitive and should not appear in IdToken.
As far as I'm aware, you cannot user IdToken to call Cognito APIs.
RefreshToken
Can only be used to request new AccessToken and IdToken, cannot be used to call Cognito APIs. In our particular use case we had to avoid passing RefreshToken to the app frontend, since it can be used to get AccessToken against public Cognito API (meaning that we cannot stop the user from doing that).
Using Cognito tokens to get AWS credentials
This is only possible if Cognito User Pool has been explicitly integrated with Cognito Identity Pool (which assumes that app developers knew what they were doing). When you exchange your Cognito JWT tokens, you get temporary AWS credentials with permissions bounded to a specific IAM role configured in Cognito Identity Pool. It is completely legitimate flow and intended behaviour. Moreover, if Cognito Identity Pool is configured to allow unauthenticated access, you can even get temporary AWS credentials without having Cognito JWT tokens (but those will be tied to another, presumably, more restrictive IAM role).
Using Cognito tokens with API Gateway
AWS API Gateway resources can be integrated with Cognito User Pools. Depending on how the integration is done, you can use either an AccessToken or IdToken from the integrated Cognito User Pool.
Revoking the tokens
You can revoke all tokens issued for your account in Cognito User Pool by calling GlobalSignOut API and providing a valid AccessToken. As this API is public, you don't need to contact the website if you possess a valid AccessToken.


text:
Q: When does a torsor of the generic fiber extend? Let $(S,\eta,s)=\mathrm{Spec}(R)$ be the spectrum of a DVR.
Let $f\colon P\to S$ be an abelian scheme. Taking restriction gives an injection from the group of $P$-torsors to the group of $P_\eta$-torsors: $$\rho\colon\mathrm{H}^1(S,P)\to\mathrm{H}^1(\eta,P_\eta).$$
How can we discribe the cokernel of $\rho$?
[Here is my attempt: Let $j\colon \eta\to S$ be the open immersion. We have an isomorphism $$P\to j_*j^*P=j_*P_\eta.$$ Here we identify the $S$-scheme $P$ with its sheaf of etale sections. This is an isomorphism: note that $P$ is proper, so rational sections in $P$ extends. We have the spectral sequence $$\mathrm{H}^p(S,R^qj_*P_\eta)\Rightarrow\mathrm{H}^{p+q}(\eta,P_\eta).$$The low degree terms reads:
$$0\to\mathrm{H}^1(S,P)\to\mathrm{H}^1(\eta, P_\eta)\to \mathrm{H}^0(S,R^1j_*P_\eta)\to \mathrm{H}^2(S,P)\to\mathrm{H}^2(\eta, P_\eta)$$
The sheaf $R^1j_*P_\eta$ is supported on $s$, I am not sure how to interpret $\mathrm{H}^0(S,R^1j_*P_\eta)$? ]

A: Here's a suggestion (not a full answer): take a geometric point $\bar{s} \rightarrow s$ above $s$. Then the stalk $\left(R^1 j_* P_{\eta}\right)_{\bar{s}}$ is computed as the Galois cohomology $H^1(K^{sh},P_{\eta})$ where $K^{sh}$ is the fraction field of the strict henselization of $R$. This follows from the discussion here, and the fact that the local ring $\mathcal{O}_{S,s}$ is isomorphic to $R$.
The absolute Galois group of $K^{sh}$ is isomorphic to the inertia subgroup of the absolute Galois group of $K$, and since $P_{\eta} \rightarrow \eta$ extends to a smooth scheme over $S$, general base change theorems tell you that this implies that inertia acts trivially. This allows you to describe the group $H^0(S,R^1j_*P_{\eta})$ more explicitly.


text:
Q: Necessary and sufficient condition for existence of a partial order I'm trying to find a necessary and sufficient condition for the existence of a partial order such that an arbitrary relation on a set X is a subset of the partial order.
So far all I have is that since a partial order is reflexive, transitive, and symmetric, the partial order must only have elements related to themselves in order for any relation to be a subset of it, since the relation in question may be symmetric. Any help would be appreciated.

A:
$R$ is a subset of a partial order if and only if for all lists $x_1,x_2,\dots,x_n$ of  elements in $R$, we have
  $$
x_1\def\R{\,R\,}\R x_2\R x_3\R\dots \R x_n\R x_1\implies x_1=x_2=\dots=x_n
$$

In graph theory terms, $R$ must be acyclic. This is a generalization of $R$ being anti-symmetric, which says that $x_1\R x_2\R x_1\implies x_1=x_2$.
If $R$ is a subset of a partial order $\le$, then $x_1\def\R{\,R\,}\R x_2\R x_3\R\dots \R x_n\R x_1$ would imply $x_1\le x_2\le \dots\le x_n\le x_1$, which combined with transitivity and anti-symmetry implies all $x_i$ are equal.
Conversely, if that condition holds, then let $\le$ be the transitive closure of $R$, where $x\le y$ if there is a chain $x\R z_1\R z_2 \R\dots\R z_k \R y$. Then $\le$ is easily shown to be transitive (connect the chains), and the given condition allows you to show anti-symmetry.

A: Assume R is a relation for S.
A necessary condition for R to be a subset of an order for S is:
there does not exist distinct x,y with xRy and yRx.
A sufficient condition for R to be a subset of an order for S is;
there does not exist distinct x,y with xTy and yTx,
where T is the reflexive and transitive closure of R.


text:
Q: Kotlin onClick Button is not working in Android Studio I'm just making my first steps with Android Studio and Kotlin. Unfortunately I despair of a simple application here.
I would like a certain function to be addressed by an onClick event of a button and then to give a toast.
But in my current setup this seems not to work. I will post the code for it. So once my MainActivity.kt and activity_main.xml
class MainActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

    }

    fun startDashboard(view: View) {
        Toast.makeText(this@MainActivity, "called startDasboard",Toast.LENGTH_SHORT).show()
    }
}

   <?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:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <androidx.constraintlayout.widget.Guideline
        android:id="@+id/guideline5"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="vertical"
        app:layout_constraintGuide_percent="0.1" />

    <androidx.constraintlayout.widget.Guideline
        android:id="@+id/guideline6"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="vertical"
        app:layout_constraintGuide_percent="0.9" />

    <Button
        android:id="@+id/startButton"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginBottom="30dp"
        android:onClick="startDashboard"
        android:text="@string/startButtonText"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="@+id/guideline" />

    <androidx.constraintlayout.widget.Guideline
        android:id="@+id/guideline"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        app:layout_constraintGuide_begin="625dp" />

</androidx.constraintlayout.widget.ConstraintLayout>

A: The code looks fine in my perspective. However, since you said that it doesn't show the toast, try this in the meantime.
In your MainActivity.kt
// below the setContentView()

val button: Button = findViewById(R.id.startButton)

button.setOnClickListener{ view ->
    startDashboard(view)
}


text:
Q: Share data from Layout to RenderBody I'm trying to share data from my main _Layout to the views rendered by RenderBody.
I tried to use a ViewBag initialized in "Shared/_Layout" but it doesn't work. However, I noticed that this ViewBag can be used in partials but not in the views displayed by @RenderBody.
Example _Layout:
PageData["XX"] = "myValue";
ViewContext.Controller.ViewBag.XX= "myValue";
Page.XX= "myValue";
ViewBag.XX= "myValue";
ViewContext.ViewData["XX"] = "myValue";

<body>
    @Html.Partial("_MyPartial") // Everything has the correct value in the partial

    <main class="content">
        @RenderBody() // Everything is null in that view
    </main>
</body>

I tried with ViewBag.Property, ViewData["Property"], Page.Property and PageData["Property"] but they are all null in the view rendered by RenderBody.
It seems that because the Layout is the last element compiled.
I don't want to use any code. Everything needs to be in the view, do something pretty similar to my example above. It must be in the layout because the value I want to share is defined by the user through the CMS. It means that this layout is used by static page but also views rendered by controller.
My question is: How I can give/share data from the _Layout to my views rendered by RenderBody()?

A: try this in your Layout :
@ViewContext.Controller.ViewBag.Test= "test";

A:
How I can give/share data to my views rendered by RenderBody()?

Controllers are responsible for preparing the data (model, ViewBag, TempData, etc) and handing it over to Views.
You could also look into filters for preparing the data.

You need to populate your ViewBag in your Controller:
public class HomeController
{
    public ActionResult Index()
    {
        // populate your ViewBag
        ViewBag.myValue = "some text";
    }
}

And then in your View/PartialView you can use it like this:
MyPartialView.cshtml
<label>@ViewBag.myValue</label>

A: Yes you can used viewBag in your partials view. When call viewBag in razor file(.cshtml)
you must be return a partial view for display.

A: ViewBag and ViewData is view-specific, so they're emptied whenever you hit a different View/Action. Try checking this link http://rachelappel.com/when-to-use-viewbag-viewdata-or-tempdata-in-asp.net-mvc-3-applications for more info.
Try using TempData for that effect - http://www.tutorialsteacher.com/mvc/tempdata-in-asp.net-mvc


text:
Q: Generate a Report On Publication List Can we generate a report on Publication list i.e. how many Persons subscribe or unsubscribe from that particular list in a specific time period ?

A: I understood that you would like to know if there is any standard report that can be generated for the publication list.
I would like to inform you that, at present, we do not have a standard report on the publication list at SFMC.
The reason there is no Reporting available for Publication Lists is that they are not actually "Lists", as they do not hold Attribute data as the Lists do, just subscriber identifying information such as Email Address, Subscriber Key is used in the account, and Status. Normal Reports for Lists will not work on a Publication List.
To get data about the information in a Publication list would involve using a Query of the Data View PublicationSubscriber, see our documentation here -
https://help.salesforce.com/articleView?id=mc_as_data_view_publicationsubscriber.htm&type=5
Thanks.


text:
Q: r - remove first row of condition per subject in dataframe I have a long format dataframe with multiple subjects and multiple conditions for each subject.
I want to remove the first row of each condition (except the first one) for all subjects.
My dataframe looks like this:
> df <- data.frame(subj = c(rep(1,4),rep(2,4), rep(3,4)), cond = (rep(c("A", "A", "B", "B"),times=3)), value = round(runif(12, min = 0, max = 10)))
> df
subj cond value
1    A     1
1    A     5
1    B     3
1    B    10
2    A     6
2    A     5
2    B     2
2    B     0
3    A     5
3    A     8
3    B     5
3    B     2

I have found the duplicated() function but it only removes the first row of each condition for the first subject:
df <- df[duplicated(df$cond),]
subj cond value
 1    A     5
 1    B    10
 2    A     6
 2    A     5
 2    B     2
 2    B     0
 3    A     5
 3    A     8
 3    B     5
 3    B     2

Is there a way to "reset" the finding of a duplicate whenever a new subject begins?
And how can I stop it from excluding the first row of the first condition?
Thank you all so much!

A: You could subset with the duplicated interaction of the two variables:
> df
   subj cond value
1     1    A     5
2     1    A     7
3     1    B     4
4     1    B     8
5     2    A     5
6     2    A     2
7     2    B     8
8     2    B     5
9     3    A     8
10    3    A     1
11    3    B     1
12    3    B     5

df1 <- df[!duplicated(interaction(df$subj, df$cond)),]

> df1
   subj cond value
1     1    A     5
3     1    B     4
5     2    A     5
7     2    B     8
9     3    A     8
11    3    B     1

Edit:
I've read your question again and it seems you want to remove the first row, not the last. In this case, use
df1 <- df[!duplicated(interaction(df$subj, df$cond), fromLast = TRUE),]

> df1
   subj cond value
2     1    A     4
4     1    B     9
6     2    A     9
8     2    B     7
10    3    A     1
12    3    B     2

A: Alternative (but does depend on actual df):
df <- data.frame(subj = c(rep(1,4),rep(2,4), rep(3,4)),
                 cond = (rep(c("A", "A", "B", "B"),times=3)),
                 value = round(runif(12, min = 0, max = 10)))
df

dummy <- as.character(df$cond) # factor to character
mask <- c(FALSE, dummy[-1] == dummy[-length(dummy)])
df[mask,]


text:
Q: No accessor to set property private final java.util.Map org.springframework.boot.configurationprocessor.json.JSONObject.nameValuePairs I'm trying to use Mongo DB for one of Java application using Spring boot. I have created model for my document and then using Mongo Repository and then trying to use JSONObject as one of the property in my document. While inserting a document into the collection works fine but while trying to access it I'm getting the exception. Below is my code please let me know if I'm making any mistake. Thanks in advance.
@Document(collection="AppSetting")
public class AppSetting {

    @Id
    private ObjectId id;
    private String name;
    private JSONObject value;

    /**
     * @return the name
     */
    public String getName() {
        return name;
    }
    /**
     * @param name the name to set
     */
    public void setName(String name) {
        this.name = name;
    }

    /**
     * @return the value
     */
    public JSONObject getValue() {
        return value;
    }
    /**
     * @param value the value to set
     */
    public void setValue(JSONObject value) {
        this.value = value;
    }
}

Repository:
public interface AppSettingRepository extends MongoRepository<AppSetting, ObjectId>{
    AppSetting findByName(String name);
}

Finally the service where I'm performing the operation is goes here:
@RestController
@RequestMapping("/apidoc/appsetting")
public class AppSettingController {

    @Autowired
    AppSettingRepository appRepo;

    @RequestMapping(method = RequestMethod.POST, value = "/updateConnector/{appname}")
    public ResponseEntity<String> updateAvailableConnector(@PathVariable("appname") final String appName,
            @RequestBody final Map<String, String> connectors
    ) {

        if( connectors == null || appName == null) {
            return null;
        }

        AppSetting setting = appRepo.findByName(appName);

        if(setting == null) {
            setting = new AppSetting();
            setting.setName(appName);
        }

        if(setting.getValue() == null)
            setting.setValue(new JSONObject());

        // Update Existing Connectors
        for( String key : connectors.keySet()) {
            try {
                setting.getValue().put(key, connectors.get(key));
            } catch (JSONException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }

        appRepo.save(setting);
        return null;
    }
}

StackTrace:
java.lang.UnsupportedOperationException: No accessor to set property private final java.util.Map org.springframework.boot.configurationprocessor.json.JSONObject.nameValuePairs!
    at org.springframework.boot.configurationprocessor.json.JSONObject_Accessor_ao0wv9.setProperty(Unknown Source) ~[spring-boot-configuration-processor-2.1.9.RELEASE.jar:2.1.9.RELEASE]
    at org.springframework.data.mapping.model.ConvertingPropertyAccessor.setProperty(ConvertingPropertyAccessor.java:61) ~[spring-data-commons-2.1.11.RELEASE.jar:2.1.11.RELEASE]
    at org.springframework.data.mongodb.core.convert.MappingMongoConverter.readProperties(MappingMongoConverter.java:380) ~[spring-data-mongodb-2.1.11.RELEASE.jar:2.1.11.RELEASE]
    at org.springframework.data.mongodb.core.convert.MappingMongoConverter.populateProperties(MappingMongoConverter.java:297) ~[spring-data-mongodb-2.1.11.RELEASE.jar:2.1.11.RELEASE]
    at org.springframework.data.mongodb.core.convert.MappingMongoConverter.read(MappingMongoConverter.java:277) ~[spring-data-mongodb-2.1.11.RELEASE.jar:2.1.11.RELEASE]
    at org.springframework.data.mongodb.core.convert.MappingMongoConverter.read(MappingMongoConverter.java:247) ~[spring-data-mongodb-2.1.11.RELEASE.jar:2.1.11.RELEASE]
    at org.springframework.data.mongodb.core.convert.MappingMongoConverter.readValue(MappingMongoConverter.java:1493) ~[spring-data-mongodb-2.1.11.RELEASE.jar:2.1.11.RELEASE]
    at org.springframework.data.mongodb.core.convert.MappingMongoConverter$MongoDbPropertyValueProvider.getPropertyValue(MappingMongoConverter.java:1391) ~[spring-data-mongodb-2.1.11.RELEASE.jar:2.1.11.RELEASE]
    at org.springframework.data.mongodb.core.convert.MappingMongoConverter.readProperties(MappingMongoConverter.java:380) ~[spring-data-mongodb-2.1.11.RELEASE.jar:2.1.11.RELEASE]
    at org.springframework.data.mongodb.core.convert.MappingMongoConverter.populateProperties(MappingMongoConverter.java:297) ~[spring-data-mongodb-2.1.11.RELEASE.jar:2.1.11.RELEASE]
    at org.springframework.data.mongodb.core.convert.MappingMongoConverter.read(MappingMongoConverter.java:277) ~[spring-data-mongodb-2.1.11.RELEASE.jar:2.1.11.RELEASE]
    at org.springframework.data.mongodb.core.convert.MappingMongoConverter.read(MappingMongoConverter.java:247) ~[spring-data-mongodb-2.1.11.RELEASE.jar:2.1.11.RELEASE]
    at org.springframework.data.mongodb.core.convert.MappingMongoConverter.read(MappingMongoConverter.java:196) ~[spring-data-mongodb-2.1.11.RELEASE.jar:2.1.11.RELEASE]
    at org.springframework.data.mongodb.core.convert.MappingMongoConverter.read(MappingMongoConverter.java:192) ~[spring-data-mongodb-2.1.11.RELEASE.jar:2.1.11.RELEASE]
    at org.springframework.data.mongodb.core.convert.MappingMongoConverter.read(MappingMongoConverter.java:80) ~[spring-data-mongodb-2.1.11.RELEASE.jar:2.1.11.RELEASE]
    at org.springframework.data.mongodb.core.MongoTemplate$ProjectingReadCallback.doWith(MongoTemplate.java:3081) ~[spring-data-mongodb-2.1.11.RELEASE.jar:2.1.11.RELEASE]
    at org.springframework.data.mongodb.core.MongoTemplate.executeFindMultiInternal(MongoTemplate.java:2687) ~[spring-data-mongodb-2.1.11.RELEASE.jar:2.1.11.RELEASE]
    at org.springframework.data.mongodb.core.MongoTemplate.doFind(MongoTemplate.java:2441) ~[spring-data-mongodb-2.1.11.RELEASE.jar:2.1.11.RELEASE]
    at org.springframework.data.mongodb.core.ExecutableFindOperationSupport$ExecutableFindSupport.doFind(ExecutableFindOperationSupport.java:214) ~[spring-data-mongodb-2.1.11.RELEASE.jar:2.1.11.RELEASE]
    at org.springframework.data.mongodb.core.ExecutableFindOperationSupport$ExecutableFindSupport.oneValue(ExecutableFindOperationSupport.java:126) ~[spring-data-mongodb-2.1.11.RELEASE.jar:2.1.11.RELEASE]
    at org.springframework.data.mongodb.repository.query.AbstractMongoQuery.lambda$getExecution$4(AbstractMongoQuery.java:126) ~[spring-data-mongodb-2.1.11.RELEASE.jar:2.1.11.RELEASE]
    at org.springframework.data.mongodb.repository.query.AbstractMongoQuery.execute(AbstractMongoQuery.java:99) ~[spring-data-mongodb-2.1.11.RELEASE.jar:2.1.11.RELEASE]
    at org.springframework.data.repository.core.support.RepositoryFactorySupport$QueryExecutorMethodInterceptor.doInvoke(RepositoryFactorySupport.java:605) ~[spring-data-commons-2.1.11.RELEASE.jar:2.1.11.RELEASE]
    at org.springframework.data.repository.core.support.RepositoryFactorySupport$QueryExecutorMethodInterceptor.lambda$invoke$3(RepositoryFactorySupport.java:595) ~[spring-data-commons-2.1.11.RELEASE.jar:2.1.11.RELEASE]
    at org.springframework.data.repository.core.support.RepositoryFactorySupport$QueryExecutorMethodInterceptor.invoke(RepositoryFactorySupport.java:595) ~[spring-data-commons-2.1.11.RELEASE.jar:2.1.11.RELEASE]
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186) ~[spring-aop-5.1.10.RELEASE.jar:5.1.10.RELEASE]
    at org.springframework.data.projection.DefaultMethodInvokingMethodInterceptor.invoke(DefaultMethodInvokingMethodInterceptor.java:59) ~[spring-data-commons-2.1.11.RELEASE.jar:2.1.11.RELEASE]
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186) ~[spring-aop-5.1.10.RELEASE.jar:5.1.10.RELEASE]
    at org.springframework.aop.interceptor.ExposeInvocationInterceptor.invoke(ExposeInvocationInterceptor.java:93) ~[spring-aop-5.1.10.RELEASE.jar:5.1.10.RELEASE]
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186) ~[spring-aop-5.1.10.RELEASE.jar:5.1.10.RELEASE]
    at org.springframework.data.repository.core.support.SurroundingTransactionDetectorMethodInterceptor.invoke(SurroundingTransactionDetectorMethodInterceptor.java:61) ~[spring-data-commons-2.1.11.RELEASE.jar:2.1.11.RELEASE]
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186) ~[spring-aop-5.1.10.RELEASE.jar:5.1.10.RELEASE]
    at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:212) ~[spring-aop-5.1.10.RELEASE.jar:5.1.10.RELEASE]
    at com.sun.proxy.$Proxy67.findByName(Unknown Source) ~[na:na]
    at com.adobe.apidoccreator.api.AppSettingController.updateAvailableConnector(AppSettingController.java:36) ~[classes/:na]
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:1.8.0_201]
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[na:1.8.0_201]
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:1.8.0_201]
    at java.lang.reflect.Method.invoke(Method.java:498) ~[na:1.8.0_201]
    at org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:190) ~[spring-web-5.1.10.RELEASE.jar:5.1.10.RELEASE]
    at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:138) ~[spring-web-5.1.10.RELEASE.jar:5.1.10.RELEASE]
    at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:105) ~[spring-webmvc-5.1.10.RELEASE.jar:5.1.10.RELEASE]
    at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:893) ~[spring-webmvc-5.1.10.RELEASE.jar:5.1.10.RELEASE]
    at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:798) ~[spring-webmvc-5.1.10.RELEASE.jar:5.1.10.RELEASE]
    at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:87) ~[spring-webmvc-5.1.10.RELEASE.jar:5.1.10.RELEASE]
    at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:1040) ~[spring-webmvc-5.1.10.RELEASE.jar:5.1.10.RELEASE]
    at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:943) ~[spring-webmvc-5.1.10.RELEASE.jar:5.1.10.RELEASE]
    at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:1006) ~[spring-webmvc-5.1.10.RELEASE.jar:5.1.10.RELEASE]
    at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:909) ~[spring-webmvc-5.1.10.RELEASE.jar:5.1.10.RELEASE]
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:660) ~[tomcat-embed-core-9.0.26.jar:9.0.26]
    at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:883) ~[spring-webmvc-5.1.10.RELEASE.jar:5.1.10.RELEASE]
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:741) ~[tomcat-embed-core-9.0.26.jar:9.0.26]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:231) ~[tomcat-embed-core-9.0.26.jar:9.0.26]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-9.0.26.jar:9.0.26]
    at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53) ~[tomcat-embed-websocket-9.0.26.jar:9.0.26]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) ~[tomcat-embed-core-9.0.26.jar:9.0.26]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-9.0.26.jar:9.0.26]
    at org.springframework.web.filter.RequestContextFilter.doFilterInternal(RequestContextFilter.java:100) ~[spring-web-5.1.10.RELEASE.jar:5.1.10.RELEASE]
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119) ~[spring-web-5.1.10.RELEASE.jar:5.1.10.RELEASE]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) ~[tomcat-embed-core-9.0.26.jar:9.0.26]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-9.0.26.jar:9.0.26]
    at org.springframework.web.filter.FormContentFilter.doFilterInternal(FormContentFilter.java:93) ~[spring-web-5.1.10.RELEASE.jar:5.1.10.RELEASE]
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119) ~[spring-web-5.1.10.RELEASE.jar:5.1.10.RELEASE]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) ~[tomcat-embed-core-9.0.26.jar:9.0.26]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-9.0.26.jar:9.0.26]
    at org.springframework.web.filter.HiddenHttpMethodFilter.doFilterInternal(HiddenHttpMethodFilter.java:94) ~[spring-web-5.1.10.RELEASE.jar:5.1.10.RELEASE]
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119) ~[spring-web-5.1.10.RELEASE.jar:5.1.10.RELEASE]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) ~[tomcat-embed-core-9.0.26.jar:9.0.26]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-9.0.26.jar:9.0.26]
    at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:201) ~[spring-web-5.1.10.RELEASE.jar:5.1.10.RELEASE]
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119) ~[spring-web-5.1.10.RELEASE.jar:5.1.10.RELEASE]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) ~[tomcat-embed-core-9.0.26.jar:9.0.26]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-9.0.26.jar:9.0.26]
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:202) ~[tomcat-embed-core-9.0.26.jar:9.0.26]
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:96) [tomcat-embed-core-9.0.26.jar:9.0.26]
    at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:526) [tomcat-embed-core-9.0.26.jar:9.0.26]
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:139) [tomcat-embed-core-9.0.26.jar:9.0.26]
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:92) [tomcat-embed-core-9.0.26.jar:9.0.26]
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:74) [tomcat-embed-core-9.0.26.jar:9.0.26]
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:343) [tomcat-embed-core-9.0.26.jar:9.0.26]
    at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:408) [tomcat-embed-core-9.0.26.jar:9.0.26]
    at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:66) [tomcat-embed-core-9.0.26.jar:9.0.26]
    at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:860) [tomcat-embed-core-9.0.26.jar:9.0.26]
    at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1589) [tomcat-embed-core-9.0.26.jar:9.0.26]
    at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49) [tomcat-embed-core-9.0.26.jar:9.0.26]
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149) [na:1.8.0_201]
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624) [na:1.8.0_201]
    at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61) [tomcat-embed-core-9.0.26.jar:9.0.26]
    at java.lang.Thread.run(Thread.java:748) [na:1.8.0_201]

A: I had the same issue when using Lombok. Once I removed Lombok and created Getters &  Setters as well as Constructors it worked.


text:
Q: Link in 100% width table results in 90% width table This is REALLY wierd.
This below code should result in a 100% width e-mail, with a lime colored top. But because the TD contains a link, the whole table is now 90% (or so) - but only in iPhone e-mail. Remove the link and the email is correct... What's going on?
https://s3.amazonaws.com/resultcaptures/C1C356D4-EAC0-4A50-B278-04155E256E51.png
I've boiled my email down to this:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<title>Email</title>

This is a link

Nothing is wrong with it... right? ...or am I blind?

A: This MacRumors thread provides a solution to the issue: http://forums.macrumors.com/showthread.php?t=1158457

Try to put align="center" and style="text-align:center" onto the first table and then put style="text-align:left" onto the second one if necessary.

If you wrap your content in a parent table with center alignment, this oddly seems to eliminate the right margin on the iPhone mail reader.

A: There is for sure a problem with iOS. The problem is that the e-mail gets scaled down to fit the width of the e-mail client, but when the mail is narrower than the e-mail client this accours - but only with e-mails with anchors in.
Set the with of the table to 320px to get rid of it, but say goodbye to elastic layout.

A: Ok, I found a working solution:
Just set:
table {
    width: 99%; /* 99.99% doesn't seem to work */
    margin: 0 auto;
}

To get rid of the very small minimal gap, just set the background-color the same as your table.
Fixed for now!
I had the same issue: Link


text:
Q: Problems adding a new element to the DOM? Trying to add a new element to the DOM but I get all sorts of errors depending on what I try to do.
http://jsfiddle.net/pRVAd/

Welcome

A: The script is in the  and your code runs immediately (it is not a delayed function call). The  does not exist when you try to run it.
Move the script to just before  or move it into a function and call it onload.
getElementsByTag is not a method on the document object. You probably mean getElementsByTagName but that returns a NodeList, not an HTMLElementNode. This is like an array. You need to pull the first item off it, or better:
Use document.body

A: Here is what you want:

Welcome

and here is JSFiddle Demo

A: Try with this new Fiddle: http://jsfiddle.net/pRVAd/1/

    <input type="button" value="Do The Thing" onclick="doTheThing()">

Welcome

The correct sintax is: document.getElementsByTagName("TagName")[index]

A:

Welcome

window.onload and how to use it correctly.
document.body


text:
Q: Is it possible to do a swap on return in c++, instead of return by value? Suppose I'm coding a string class in C++ (I know I can use the library). The string length is variable and the storage space is dynamically allocated in the constructor and freed in the destructor. When the main function calls c=a+b (a,b,c are strings), the operator+ member function creates a temporary object that stores the concatenated string a+b, returns it to the main function, and then the operator= member function is called to free the string originally stored in c and copy data from the temporary string a+b to c, and finally the temporary a+b is destructed.
I'm wondering if there's a way to make this happen: instead of having the operator= copy data from a+b to c, I want it to swap the data pointers of a+b and c, so that when a+b is destructed, it destructs the original data in c (which is what we want), while c now takes the result of a+b without needing to copy.
I know coding a 2-parameter member function setToStrcat and calling c.setToStrcat(a,b) can do this. For example, the function can be coded as:
    void String::setToStrcat(const String& a,const String& b){
      String tmp(a.len+b.len); int i,j;
      for(i=0;i<a.len;i++) tmp[i]=a[i];
      for(j=0;j<b.len;i++,j++) tmp[i]=b[j];
      tmp[i]='\0'; this->swap(tmp);
    }

    void String::swap(String& a){
      int n=len; len=a.len; a.len=n;
      char *s=str; str=a.str; a.str=s;
    }

I omitted the definitions of my constructor (which allocates len+1 char-type spaces) and operator[] (which returns a reference of the ith character). The swap function swaps the data pointers and length variables between *this and tmp, so that when tmp is destructed after the swap, it is actually the data originally stored in *this (the String c in the main function) that is destructed. What *this now has in its possession (c.str) is the concatenated string a+b.
I would like to know if there is a way to optimize the performance of c=a+b to the same level. I tried c.swap(a+b) and changed the return type of a+b to String&, but I receive warning (reference to a local variable) and GDB shows that the temporary gets destructed before the swap happens, while I want the other way.
I think my question is general. In C++ programming, we often need a temporary object to store the result of a function, but when we assign it to another object in the main function, can we not copy the data but use a (much faster) swap of pointers instead? What is a neat way of making this happen?

A: In C++11, you can do this by writing a move constructor. Rvalue references were added to the language to solve this exact problem.
class String {
  ...
  String(String&& s) : str(nullptr) {
    this->swap(s);
  }
  String& operator=(String&& s) {
    this->swap(s);
  }
  ...
  String operator+(String const& other) {
    // (your implementation of concatenation here)
  }
  ...
}

Then code like this will not trigger an extra copy constructor or a memory allocation, it will just move the allocated memory from the temporary (the thing returned from operator+) to the new object c.
String c = a + b;


text:
Q: Java library for showing network graphically I want to depict a network graphically (one IP connecting to different IPs) , where i can show one node connecting to two or more nodes.Something like this.Suggest me some library in JAVA which can help me in doing this.

A: Maybe jgraph could be used?
http://www.jgraph.com/jgraph.html
Or NetBeans Visual Library?
http://platform.netbeans.org/graph/

A: Take a look at the JUNG library .

is a library that provides a common and extendible language for the
  modeling, analysis, and visualization of data that can be represented
  as a graph or network.

A: There is now a library that combines JUNG and NetBeans Visual Library so you can use JUNG's layouts against real components.


text:
Q: Entity Framework "Migrations Configuration" and autofac I am trying to inject dependencies into the Entity Framework Configurations class and I cannot seem to get it to work. The configurations class looks like this-
public class Configuration : DbMigrationsConfiguration<ApplicationContext>
{
    private readonly IApplicationUserManager _applicationUserManager;
    public Configuration(IApplicationUserManager userManager)
    {
        AutomaticMigrationsEnabled = true;
        AutomaticMigrationDataLossAllowed = true;
        _applicationUserManager = userManager;
    }
    protected override void Seed(ApplicationContext context) {
      //seed data here
    }
}

And I am registering with Autofac like this-
  builder.Register(c => new Configuration(c.Resolve<ApplicationUserManager>()));

This will not work because running "Update-database" complains that "No migrations configuration type was found in the assembly". So obviously it doesn't like the parameter-less constructor. So I tried using property injection like this-
 public class Configuration : DbMigrationsConfiguration<ApplicationContext>
{
    public IApplicationUserManager ApplicationUserManager {get;set;}
    public Configuration()
    {
        AutomaticMigrationsEnabled = true;
        AutomaticMigrationDataLossAllowed = true;

    }
    protected override void Seed(ApplicationContext context) {
      //seed data here
    }
}

and registering it with Autofac like this -
builder.Register(c => new Configuration { ApplicationUserManager = c.Resolve<ApplicationUserManager>() });

However, this doesn't work either, the ApplicationUserManager property is always null. Is it possible to inject properties into the Configuration class?

A: First of all, it looks really strange that you wanna use some dependency in migration configuration class. So I advice you to think about aproach in general.
Explanation:
Your configuration is correct, but when you use dependency injection you should keep in mind 2 things:

*

*you should register your dependency in dependency container.

*you should create component that contains dependency using your dependency container, so this container will inject all dependencies during creation of an object.

So you registered your dependency, but the problem is that instance of configuration class is creating not through dependency container. If you will create instance through dependency container e.g.
DependencyResolver.Current.GetService<Configuration>();

your injection will work. In your situation it is not acceptable, because configuration is creating by EF.
Possible solution:
You can try to resolve instance manually in your configuration class.
public class Configuration : DbMigrationsConfiguration<ApplicationContext>
{
    public Configuration(IApplicationUserManager userManager)
    {
        AutomaticMigrationsEnabled = true;
        AutomaticMigrationDataLossAllowed = true;
    }
    protected override void Seed(ApplicationContext context) {
       var applicationUserManager = DependencyResolver.Current.GetService<IApplicationUserManager>();
    }
}

Conclusion: think about your aproach first and if you really need to do this use proposed workaround.

A: I think that you can even use your User/Role/Claim Classes without using Dependency injection and simply creating objects in the Configuration class. This works for me, with Identity Framework.
    UserClaimService userClaimService = new UserClaimService(new EfRepository<UserClaim>(context));
    UserRoleService userRoleService = new UserRoleService(new EfRepository<UserRole>(context));
    UserLoginService userLoginService = new UserLoginService(new EfRepository<UserLogin>(context));
    RoleService roleService = new RoleService(new EfRepository<Role>(context));

    ApplicationUserService applicationUserService = new ApplicationUserService(
            new EfRepository<ApplicationUser>(context),
            userRoleService,
            roleService);

    UserManager<ApplicationUser, int> userManager = new UserManager<ApplicationUser, int>(new UserStore(applicationUserService, userClaimService, userRoleService, userLoginService, roleService));


text:
Q: Setting keyboard layout for a particular device using xkbcomp I'm using xkbcomp to swap the Alt and Win keys on an Apple keyboard of mine.
This works:
xkbcomp -w0 -I"$DIR" "$DIR/keymap/mykbd" $DISPLAY

...but it changes the layout for all keyboards, and this will not do because I am frequently changing between a standing and sitting position (and swapping keyboards).
I have taken the trouble of specifying a device. The xkbcomp help text says: -i <deviceid>  Specifies device ID (not name) to compile for
xkbcomp -w0 -I"$DIR" -i 16 "$DIR/keymap/mykbd" $DISPLAY

...but this seems to produce no effect!
I drew the id 16 from xinput list | grep Magic\ Keyboard. I've also tried /dev/input/event18 as an id, taken from xinput list-props 16 | grep 'Device Node', but this produces no better effect.
Update:
Suprisingly, when I provide the id of Virtual core keyboard instead of Magic Keyboard, I do get an effect: the new mapping gets applied to my Magic Keyboard, and if I proceed to type on my integrated laptop keyboard, the keymap then reverts to the original configuration.
I can't explain this. Does anyone have any insight?

A: You may wish to employ the technique described here.
Alternatively, create a separate .xkb file for each device (could use method described here for each one) and place shortcuts for each on the desktop. Persistence wouldn't be as important since the expectation is that the key layout (device) would be selected manually.


text:
Q: problem in understanding the setRunning (boolean run) method   public class GameLoopThread extends Thread
   {
    static final long FPS = 10;
    private GameView view;
    private boolean running = false;
    public GameLoopThread(GameView view)
     {
         this.view = view;
     }
   public void setRunning(boolean run)
   {
         running = run;
   }
   @Override
   public void run()
   {
         long ticksPS = 1000 / FPS;
         long startTime;
         long sleepTime;
         while (running)
         {
                Canvas c = null;
                startTime = System.currentTimeMillis();
                try
                {
                       c = view.getHolder().lockCanvas();
                       synchronized (view.getHolder())
                       {
                              view.onDraw(c);
                       }
                }
                finally
                {
                       if (c != null)
                       {
                              view.getHolder().unlockCanvasAndPost(c);
                       }
                }
                sleepTime = ticksPS-(System.currentTimeMillis() - startTime);
                try
                {
                       if (sleepTime > 0)
                              sleep(sleepTime);
                       else
                              sleep(10);
                }
                 catch (Exception e){

               }
            }
       }
  }

my confusion is that
  i have initialize-->private boolean running = false;
   after that i assigned-->
public void setRunning(boolean run)
   {
         running = run;
   }

so what "running" realy holds, what is the vale of "run"?sombody plz explain setRunning(boolean run) method.

A: run will hold whatever you pass as the argument to the setRunning() method. It will be either true or false.
From the looks of the code, it appears to control re-drawing the Canvas. As long as running is true (by means of calling setRunning(true) on the Thread), it will re-draw the Canvas every 100 ms (or 10 frames per second).
EDIT
You should declarerunning using the volatile modifier in order for proper synchronization to occur. If you do not include the modifier, and you call setRunning() from another thread, the "expected" result is not guaranteed.
See here.


text:
Q: Google Maps InfoWindow [showing error] Please look at my code. Where is the problem?
When i call this function coordinates now work normally( lines not working) and info windows also not working.
So when delete function binfowindow everything is working but infowindow show only last data..
Updated!  Not a result!
 function getline() {

       var mpenc = new google.maps.InfoWindow();
downloadUrl("line.php", function(doc) {

        var g = google.maps;

        var xmlDoc = xmlParse(doc);

        bounds = new google.maps.LatLngBounds();
        var markers = xmlDoc.documentElement.getElementsByTagName("marker");
      // ========= Now process the polylines ===========
      var lines = xmlDoc.documentElement.getElementsByTagName("line");

      // read each line
      for (var a = 0; a < lines.length; a++) {
        // get any line attributes
       var colour = lines[a].getAttribute("colour");
        var width  = parseFloat(lines[a].getAttribute("width"));
        var diameter = lines[a].getAttribute("diameter");
        var project = lines[a].getAttribute("projectid");
        var contract = lines[a].getAttribute("contract");
        var comp = lines[a].getAttribute("complated");
        var id = lines[a].getAttribute("id_line");
        var html = "men ?" + id + " I: ";
        // read each point on that line
        var points = lines[a].getElementsByTagName("point");
        var pts = [];
        var length = 0;
        var point = null;
        for (var i = 0; i < points.length; i++) {
           pts[i] = new g.LatLng(parseFloat(points[i].getAttribute("lng")),
                                parseFloat(points[i].getAttribute("lat")));
           if (i > 0) {
             length += pts[i-1].distanceFrom(pts[i]);
             if (isNaN(length)) { alert("["+i+"] length="+length+" segment="+pts[i-1].distanceFrom(pts[i])) };
           }
           bounds.extend(pts[i]);
           point = pts[parseInt(i/2)];
        }
        // length *= 0.000621371192; // miles/meter

  if (comp < 1) {
 colorr = '#FA0505' }

 if (comp > 0 && comp < 25 ) {
 colorr = '#FFA640' }

 if (comp > 24 && comp < 50) {
 colorr = '#FFFD91' }

 if (comp > 49 && comp < 75) {
 colorr = '#E8E400' }

 if (comp > 74 && comp < 100) {
 colorr = '#BFFFAD' }

 if (comp == 100) {
 colorr = '#0F8500' }

        var poly = new g.Polyline({
                          map:map,
                          path:pts,
                          strokeColor:colorr,
                          strokeWeight:width,
                          clickable: true
                          });

google.maps.event.addListener(poly,'mouseover', function() {

        this.setOptions({strokeColor: '#690469' });
           this.setOptions({strokeOpacity: 1.0 });
           this.setOptions({strokeWeight: 4 });

  });

     google.maps.event.addListener(poly,'mouseout', function() {

        this.setOptions({strokeColor: colorr });
           this.setOptions({strokeOpacity: 1.0 });
           this.setOptions({strokeWeight: 4 });
  });

    var funcs = [];

function createfunc(i) {
    return function() {

  google.maps.event.addListener(poly,'click', function(event) {
    mpenc.setContent(html +i);
    mpenc.setPosition(event.latLng);
    mpenc.open(map);
  });

    };
}

for (var i = 0; i < lines.length; i++) {
    funcs[i] = createfunc(i);
}

for (var j = 0; j < lines.length; j++) {
    funcs[j]();                        // and now let's run each one to see
}

      }
      map.fitBounds(bounds);

    });

}


text:
Q: aws secrets manger and multiple accounts I have a secret in one account that I want to share in another account.  In the other account we have a lambda function that will need this secret.  I followed this and it works great.
AWS share secrets between accounts
Now we want to see if instead of granting access to every user that invokes this lambda is there a way to grant access to a group or a role in the other account access to the secret.  I tried using the role that invokes the function but I got denied in the response for the lambda.  Then next I tried a group in the other account but it wouldn't let me save it. I just kept telling the principal was not correct.  Thanks.
So here is what I used for policies.
Policy on the Customer Managed Key
{
        "Sid": "Permissions for external users",
        "Effect": "Allow",
        "Principal": {
            "AWS": "arn:aws:iam::external-acct:role/Cross-Account-KMS-Role"
        },
        "Action": [
            "kms:Decrypt",
            "kms:DescribeKey"
        ],
        "Resource": "*",
        "Condition": {
            "StringEquals": {
                "kms:ViaService": "secretsmanager.us-east-1.amazonaws.com"
            },
            "StringLike": {
                "kms:EncryptionContext:SecretARN": "arn:aws:secretsmanager:us-east-1:central-acct:secret:my-secret"
            }
        }
    }

Now on the secret itself we set this policy up.
{
"Version" : "2012-10-17",
"Statement" : [ {
"Effect" : "Allow",
"Principal" : {
  "AWS" : "arn:aws:iam::external-acct:role/Cross-Account-KMS-Role"
},
"Action" : "secretsmanager:GetSecretValue",
"Resource" : "*",
"Condition" : {
  "ForAnyValue:StringEquals" : {
    "secretsmanager:VersionStage" : "AWSCURRENT"
  }
}}

Then on the external account we created this policy
{
"Version": "2012-10-17",
"Statement": [
    {
        "Effect": "Allow",
        "Action": "secretsmanager:GetSecretValue",
        "Resource": "arn:aws:secretsmanager:us-east-1:central-acct:secret:my-secret"
    },
    {
        "Effect": "Allow",
        "Action": "kms:Decrypt",
        "Resource": "arn:aws:kms:us-east-1:central-acct:key/customer-key-1"
    }
]

}
then we atached the policy to the Role above.  Now when i did this for my own account instead of the role I can use aws cli and pull the secret.   Now of course i wasn't using the role but my account.

A: Ok, So I figured it out.  It seems that the resource policy on the CMK was wrong.  I had used one like this
arn:aws:kms:us-east-1:my_acct:key/my_policy

When I needed one like this.
arn:aws:kms:us-east-1:my_acct:key/my_policy_id


text:
Q: VB 2010 PrintDocument stacks printed text I have run into another problem with my current project. I have a form that I need to print. Doing some searching online I found a few examples and implemented it into my code. It prints but prints all my text boxes and labels stacked on top of one another. How can I get this to print my textboxes and labels formatted as I have them in the form?
Here is my code:
 Private Sub PrintToolStripMenuItem1_Click_1(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles PrintToolStripMenuItem1.Click

        PrintDocument1.PrinterSettings.Copies = 2
        PrintDocument1.Print()

    End Sub

 Private Sub PrintDocument1_PrintPage(ByVal sender As System.Object, ByVal e As System.Drawing.Printing.PrintPageEventArgs) Handles PrintDocument1.PrintPage

        e.Graphics.DrawString(TextBox1.Text, TextBox1.Font, Brushes.Blue, 100, 100)
        e.Graphics.DrawString(Label1.Text, Label1.Font, Brushes.Blue, 100, 100)
        e.Graphics.DrawString(Label2.Text, Label2.Font, Brushes.Blue, 100, 100)
        e.Graphics.DrawString(datebox.Text, datebox.Font, Brushes.Blue, 100, 100)
        e.Graphics.DrawString(Label3.Text, Label3.Font, Brushes.Blue, 100, 100)
        e.Graphics.DrawString(locationbox.Text, locationbox.Font, Brushes.Blue, 100, 100)
        e.Graphics.DrawString(Label4.Text, Label4.Font, Brushes.Blue, 100, 100)
        e.Graphics.DrawString(groupbox.Text, groupbox.Font, Brushes.Blue, 100, 100)
        e.Graphics.DrawString(Label5.Text, Label5.Font, Brushes.Blue, 100, 100)
        e.Graphics.DrawString(passbox.Text, passbox.Font, Brushes.Blue, 100, 100)
        e.Graphics.DrawString(Label7.Text, Label7.Font, Brushes.Blue, 100, 100)
        e.Graphics.DrawString(TextBox6.Text, TextBox6.Font, Brushes.Blue, 100, 100)
        e.Graphics.DrawString(apbox.Text, apbox.Font, Brushes.Blue, 100, 100)
        e.Graphics.DrawString(Label8.Text, Label8.Font, Brushes.Blue, 100, 100)
        e.Graphics.DrawString(TextBox7.Text, TextBox7.Font, Brushes.Blue, 100, 100)

    End Sub

Im still new to vb 2010 so any help is appreciated, Thanks!

A: Just realized my mistake. I'm as blind as a bat, as it was in my face the entire time.
Just in case anyone else ever needs to figure this out.
e.Graphics.DrawString(TextBox1.Text, TextBox1.Font, Brushes.Blue, X-coordinate, Y-coordinate)


text:
Q: Greenplum Delete statement not working We have a scenario in that, We need to compare staging table with Destination table.Finally, want to delete the record at destination table
We tried
DELETE  FROM DestTable
FROM    DestTable d
        LEFT JOIN StagingTable s ON d.ID = s.ID
WHERE   s.id IS NULL

Please advice on it. How do I create delete statement in this scenario?
Any help on it would be much appreciated?

A: This isn't supported in HAWQ.  HAWQ only supports INSERT and TRUNCATE.
In Greenplum, be careful executing a lot of DELETE statements.  You will want to run a VACUUM command either before or after running the DELETE.  You will probably be better off using TRUNCATE and INSERT just like in HAWQ.
DELETE FROM DestTable d
USING StagingTable s
WHERE d.ID = s.ID;


text:
Q: Quartz.NET Scheduler, initalization in each scheduler.Start() I have several Robot Jobs that extends to abstract RobotJob class, sharing log files, configurations, pause/continue options etc... I'm trying adopt Quartz.NET to schedule these jobs. I'm also trying to make it work with least amount of code/structure modification. However, I have two intertwined problems:
1) I need a parameterless constructor in MyRobotJob since scheduler.Start() constructs a new MyRobotJob object, but I don't want a parameterless constructor.
2) Since scheduler.Start() creates a new MyRobotJob, there is an infinite loop stemming from the calls of the constructors. I know that this design is problematic, and I wonder how can I modify it so there will only be single MyRobotJob object that will run according to the schedule.
What I tried: I defined an abstract method that returns IJob in RobotJob. I implemented it in MyRobotJob which returned another class MyRobotRunner, implementing IJob. But if I do it like that in a separate class, I cannot make use of my logging methods in RobotJob. A simplified version of the code is like this:
public abstract class RobotJob
{
    public string Cron { get; set; }
    public string LogFile { get; set; }
    public JobStatus Status { get; set; }
    // Properties, helpers...

    protected RobotJob(string name, string cron, string logFile = null)
    {
        this.Name = name;
        this.LogFile = logFile;
        this.Cron = cron;
        InitQuartzScheduler();
    }

    private void InitQuartzScheduler()
    {
        scheduler = StdSchedulerFactory.GetDefaultScheduler();

        IJobDetail job = JobBuilder.Create(this.GetType())
            .WithIdentity(this.GetType().Name, "AJob")
            .Build();

        trigger = TriggerBuilder.Create()
            .WithIdentity(this.GetType().Name, "ATrigger")
            .StartNow()
            .WithCronSchedule(Cron)
            .Build();

        scheduler.ScheduleJob(job, trigger);

        scheduler.Start(); // At this part, infinite loop starts
    }
}

[DisallowConcurrentExecution]
public class MyRobotJob : RobotJob, IJob
{
    // I need a parameterless constructor here, to construct
    public MyRobotJob()
        : base("x", "cron", "logFile")

    public MyRobotJob(string name, string cron, string logFile = null)
        : base(name, cron, logFile)
    {

    }
    public override void Execute(IJobExecutionContext context)
    {
        // DoStuff();
    }
}

A: You don't need to call scheduler.Start() every time you add your job.  Make a method on a scheduler wrapper which will add your jobs and also will start your scheduler only once.
public class Scheduler : IScheduler
{
private readonly Quartz.IScheduler quartzScheduler;

public Scheduler()
{
  ISchedulerFactory schedulerFactory = new StdSchedulerFactory();
  quartzScheduler = schedulerFactory.GetScheduler();
  quartzScheduler.Start();
}

public void Stop()
{
  quartzScheduler.Shutdown(false);
}

public void ScheduleRoboJob()
{
  // your code here
  quartzScheduler.ScheduleJob(job, trigger);
}


text:
Q: Tor by SSH / http proxy Is there a program that i can use to access my socks5(Tor) ,by simulating a servor SSH or http(s) proxy.
Because torsocks doesn't work with some web browsers.
The connection should look like this:
local host <--> https proxy / SSH <--> tor <--> internet

A: sudo -s
apt-get install privoxy
echo "forward-socks5 / localhost:9050 ." >>/etc/privoxy/config
systemctl restart privoxy

https://wiki.archlinux.org/index.php/ELinks#Tor_usage


text:
Q: About Juju charms I need td-agent charms with bionic series. Only trusty series is available in charmstore.
Please guide me how to get that charm with bionic series otherwise please inform me how series conversion happens in charm...
Thanks in advance...

A: According to this website, td-Agent or Fluentd is also available for Ubuntu Bionic Beaver.
You can download the suitable version for Ubuntu 18.04 via this link.
Choose the version you want, and click on it to download it.
Once the download is finished, go to the download folder (let's assume it is Downloads) by running on the terminal cd ~/Downloads then run sudo dpkg -i <the name of the td-agent package> (for example sudo dpkg -i td-agent_3.5.1-0_amd64.deb).
For additional details and other methods of installation, check this link


text:
Q: GLES20 parse obj file and vertex, texture indices I'm new in OpenGL-ES 2.0 and try to parse .obj file and draw on Android.
And I've succeed draw a simple cube with parsed data from .obj file
the 'v' (vertex coords)
and the first values of 'f' line (v index)

but the next step, I need to draw 'Texture' with .obj data, I found there is 'Texture Index' and I've no idea how can I use this 'Texture Index' with my codes
GLES20.glVertexAttribPointer(mPositionHandle, 3, GLES20.GL_FLOAT, false, VSTRIDE, vertexCoords);
GLES20.glEnableVertexAttribArray(mPositionHandle);

GLES20.glVertexAttribPointer(maTextureHandle, 2, GLES20.GL_FLOAT, false, TSTRIDE, textureCoords);
GLES20.glEnableVertexAttribArray(maTextureHandle);

...

GLES20.glDrawElements(GLES20.GL_TRIANGLES, indexLength, GLES20.GL_UNSIGNED_SHORT, vertexIndices);

I think, only 'Vertex indices' parameter can use on glDrawElements API.
How can I use glDrawElements with 'Vertex Indices' and 'Texture Indices'?

A: You can´t use texture indices with GLES20.glDrawElements.
GLES20.glDrawElements can't draw elements with multiple textures, it will allways use the "current texture"
You set the Current texture binding a previosusly created texture.
GLES20.glBindTexture(GLES20.GL_TEXTURE_2D, textureID); //Next call of glDrawElements will use this texture
It's a good idea to order vertices by the texture id and execute one GLES20.glDrawElements call for each texture id


text: Q: Interstellar Debris Do radio astronomers not have solid data on just how dense and widely distributed solid interstellar debris is? I cannot seem to find any direct answer on this subject from any source. I am interested in this as it could be quite an obstacle for interstellar travel without good sensors.


text:
Q: Multiple variable length lists inside ScrollView Disclaimer: I'm mostly a backend developer, but I was called to an emergency with an android app, so the nuances of the framework are unknown to me.
Said that, I have the following requirement:
Show in a single long screen (vertically scrollable) the information coming from backend. This particular screen has two different sets of lists with the following layout

*

*main element 1

*main element 2

*...

References

*

*Reference 1

*Reference 2

*...

(For clarification, main elements are links to further details of each, while references are plain text)
On previous cases I have used something like this (with only a single list)
 <ScrollView
    ...
   >
      <RecyclerView
        ...
       />
  </ScrollView>

using the adapter to show the elements.
(If this is a suboptimal approach, I'm open to suggestions)
But using two RecyclerViews causes weird behavior (like having two scrollable sections on screen), and on further investigation, it's advised to not use RecyclerView inside ScrollView at all, but I haven't found any alternative either.
Any help or pointer will be appreciated

A: Android Geek provided the right answer on his comment. I'm just adding this to mark the question as solved.

Try to add NestedScrollView instead of ScrollView and add android:nestedScrollingEnabled="false" in both recyclerviews


text:
Q: Rails 2.3.14 localization for yes/no I have YAML like so, in /config/locales/defaults/en.yml:
en:
  no_results_found: None Found
  yes: Yes
  no: No
  approve: Approve

And get these results in rails console:
>> helper.t(:no_results_found)
=> "None Found"
>> helper.t(:yes)
=> "en, yes"
>> helper.t(:no)
=> "en, no"
>> helper.t(:approve)
=> "Approve"

I've tried renaming yes/no to yes_text, and no_text, and get weirder results:
>> helper.t(:yes_text)
=> true
>> helper.t(:no_text)
=> false

How can I output (in English) yes or no? Keep in mind I define in yaml so I can provide versions in other languages.

A: Use:
en:
  'yes': Yes
  'no': No

A: en:
 no_results_found: "None Found"
 result_yes: "Yes"
 result_no: "No"
 approve: "Approve"

Add some prefix with yes: or no: translation variable as it is default in i18n.


text:
Q: In excel, how do you multiply and sum alternating cells in a row? For now I am just using
=(A1*C1)+(B1*D4)+(E1*G1)+(F1*H1)+...
but this is a long row of cells. they just alternate and I was hoping there was a simpler way.
Thanks

A: Assuming the last cell in the range is H1:
=SUMPRODUCT(A1:F1,C1:H1,N(ISODD(EVEN(COLUMN(A1:F1)-MIN(COLUMN(A1:F1))+1)/2)))
Or, for Office 365:
=SUMPRODUCT(A1:F1,C1:H1,N(ISODD(EVEN(SEQUENCE(,COLUMNS(A1:F1)))/2)))
Note the deliberately offset ranges (A1:F1 and C1:H1).


text:
Q: Can't Install font awesome library on React JS I copied this command
npm i --save @fortawesome/fontawesome-svg-core
npm install --save @fortawesome/free-solid-svg-icons
npm install --save @fortawesome/react-fontawesome

And the error for these three commands is:

npm WARN config global --global, --local are deprecated. Use
--location=global instead. npm ERR! code E401 npm ERR! Incorrect or
missing password. npm ERR! If you were trying to login, change your
password, create an npm ERR! authentication token or enable two-factor
authentication then npm ERR! that means you likely typed your password
in incorrectly. npm ERR! Please try again, or recover your password
at: npm ERR!     https://www.npmjs.com/forgot npm ERR! npm ERR! If you
were doing some other operation then your saved credentials are npm
ERR! probably out of date. To correct this please try logging in again
with: npm ERR!     npm login
npm ERR! A complete log of this run can be found in: npm ERR!
C:\Users\user\AppData\Local\npm-cache_logs\2022-08-06T09_30_05_325Z-debug-0.log

What kind of solution that I need here? While I already follow the guide from official website https://fontawesome.com/v5/docs/web/use-with/react


text:
Q: Sharing a TLB entry between two logical CPUs (Intel) I wondered if it is possible if two threads belonging to the same program with the same PCID can share the TLB entry when they are scheduled to run on the same physical CPU?
I already looked into the SDM (https://www.intel.com/content/www/us/en/developer/articles/technical/intel-sdm.html); page 3115 (TLB and HT) does not mention any sharing mechanism. But another part of the document states that before accessing the TLB entry, the PCID value is checked, and if it is equal, the value is used. However, there is also a bit for the current thread set next to the PCID identifier.
My question: is the PCID value used with priority over the CPU-thread bit or is it necessary that both values match?

A: From my observations, it is not possible (at least for the dTLB), even though it would bring performance benefits.
How I came to that conclusion
As suggested by Peter, I wrote a small program that consists of two worker threads that access the same heap region over and over again.
Compile with -O0 to prevent optimization.
#define _GNU_SOURCE
#include <stdio.h>
#include <pthread.h>
#include <stdlib.h>
#include <inttypes.h>
#include <err.h>
#include <sched.h>
#include <sys/mman.h>

#define PAGE_SIZE 4096

int repetitions = 1ll << 20;
uint64_t ptrsize = 1ll<<18;
uint64_t main_cpu, co_cpu ;

void pin_task_to(int pid, int cpu)
{
    cpu_set_t cset;
    CPU_ZERO(&cset);
    CPU_SET(cpu, &cset);
    if (sched_setaffinity(pid, sizeof(cpu_set_t), &cset))
        err(1, "affinity");
}
void pin_to(int cpu) { pin_task_to(0, cpu); }

void *foo(void *p)
{
    pin_to(main_cpu);

    int value;
    uint8_t *ptr = (uint8_t *)p;
    printf("Running on CPU: %d\n", sched_getcpu());
    for (size_t j = 0; j < repetitions; j++)
    {
        for (size_t i = 0; i < ptrsize; i += PAGE_SIZE)
        {
            value += ptr[i];
        }
    }
    volatile int dummy = value;
    pthread_exit(NULL);
}

void *boo(void *p)
{
    pin_to(co_cpu);

    int value;
    uint8_t *ptr = (uint8_t *)p;
    printf("Running on CPU: %d\n", sched_getcpu());
    for (size_t j = 0; j < repetitions; j++)
    {
        for (size_t i = 0; i < ptrsize; i+=PAGE_SIZE)
        {
            value += ptr[i];
        }
    }
    volatile int dummy = value;
    pthread_exit(NULL);
}

int main(int argc, char **argv)
{
    if (argc < 3){
        exit(-1);
    }
    main_cpu = strtoul(argv[1], NULL, 16);
    co_cpu = strtoul(argv[2], NULL, 16);
    pthread_t id[2];
    void *mptr = malloc(ptrsize);

    pthread_create(&id[0], NULL, foo, mptr);
    pthread_create(&id[1], NULL, boo, mptr);

    pthread_join(id[0], NULL);
    pthread_join(id[1], NULL);
}

I decided to sum up all the values in the memory region (obviously, the value will overflow) to prevent the CPU from doing microarchitectural optimization.
[The other Idea was to simply dereference the memory region byte by byte and load the value in RAX]
We go over the memory region repetitions times to reduce the noise within one run induced by the slightly different startup time of the threads and other processes and interrupts on the system.
Results
My machine has four physical and eight logical cores. Logical core x and x+4 are located on the same physical one (lstopo).
CPU: Intel Core i5 8250u
Running on the same logical core
Since the kernel uses PCIDs to identify TLB entries, a context switch to the other thread should not invalidate the TLBs.
> $ perf stat -e dtlb_load_misses.stlb_hit,dtlb_load_misses.miss_causes_a_walk,cycles,task-clock ./main 1 1
Running on CPU: 1
Running on CPU: 1

 Performance counter stats for './main 1 1':

        12,621,724      dtlb_load_misses.stlb_hit:u #   49.035 M/sec
             1,152      dtlb_load_misses.miss_causes_a_walk:u #    4.475 K/sec
       834,363,092      cycles:u                  #    3.241 GHz
            257.40 msec task-clock:u              #    0.997 CPUs utilized

       0.258177969 seconds time elapsed

       0.258253000 seconds user
       0.000000000 seconds sys

Running on two different physical cores
No TLB sharing or interference whatsoever.
> $ perf stat -e dtlb_load_misses.stlb_hit,dtlb_load_misses.miss_causes_a_walk,cycles,task-clock ./main 1 2
Running on CPU: 1
Running on CPU: 2

 Performance counter stats for './main 1 2':

        11,740,758      dtlb_load_misses.stlb_hit:u #   45.962 M/sec
             1,647      dtlb_load_misses.miss_causes_a_walk:u #    6.448 K/sec
       834,021,644      cycles:u                  #    3.265 GHz
            255.44 msec task-clock:u              #    1.991 CPUs utilized

       0.128304564 seconds time elapsed

       0.255768000 seconds user
       0.000000000 seconds sys

Running on the same physical core
If TLB sharing is possible, I would expect to have here the lowest sTLB hits and a low number of dTLB page walks. But instead, we have the highest number in both cases.
> $ perf stat -e dtlb_load_misses.stlb_hit,dtlb_load_misses.miss_causes_a_walk,cycles,task-clock ./main 1 5
Running on CPU: 1
Running on CPU: 5

 Performance counter stats for './main 1 5':

       140,040,429      dtlb_load_misses.stlb_hit:u #  291.368 M/sec
           198,827      dtlb_load_misses.miss_causes_a_walk:u #  413.680 K/sec
     1,596,298,827      cycles:u                  #    3.321 GHz
            480.63 msec task-clock:u              #    1.990 CPUs utilized

       0.241509701 seconds time elapsed

       0.480996000 seconds user
       0.000000000 seconds sys

Conclusion
As you can see, we have the most sTLB hits and dTLB page walks when running on the same physical core. Thus, I would follow from it that there is no sharing mechanism for the same PCID on the same physical core. Running the process on the same logical core and two different physical cores results in roughly the same amount of misses/hits to the sTLB. This further supports the thesis that there is sharing on the same logical core but not on the physical one.
Update
As suggested by Peter also use a linked-list approach to prevent THP and prefetching. The modified data is shown below.
Compile with -O0 to prevent optimization
#define _GNU_SOURCE
#include <stdio.h>
#include <pthread.h>
#include <stdlib.h>
#include <inttypes.h>
#include <err.h>
#include <sched.h>
#include <time.h>
#include <sys/mman.h>

#define PAGE_SIZE 4096

const int repetitions = 1ll << 20;
const uint64_t ptrsize = 1ll<< 5;
uint64_t main_cpu, co_cpu ;

void pin_task_to(int pid, int cpu)
{
    cpu_set_t cset;
    CPU_ZERO(&cset);
    CPU_SET(cpu, &cset);
    if (sched_setaffinity(pid, sizeof(cpu_set_t), &cset))
        err(1, "affinity");
}
void pin_to(int cpu) { pin_task_to(0, cpu); }

void *foo(void *p)
{
    pin_to(main_cpu);

    uint64_t *value;
    uint64_t *ptr = (uint64_t *)p;
    printf("Running on CPU: %d\n", sched_getcpu());
    for (size_t j = 0; j < repetitions; j++)
    {
        value = ptr;
        for (size_t i = 0; i < ptrsize; i++)
        {
            value = (uint64_t *)*value;
        }
    }
    volatile uint64_t *dummy = value;
    pthread_exit(NULL);
}

void *boo(void *p)
{
    pin_to(co_cpu);

    uint64_t *value;
    uint64_t *ptr = (uint64_t *)p;
    printf("Running on CPU: %d\n", sched_getcpu());
    for (size_t j = 0; j < repetitions; j++)
    {
        value = ptr;
        for (size_t i = 0; i < ptrsize; i++)
        {
            value = (uint64_t *)*value;
        }
    }
    volatile uint64_t *dummy = value;
    pthread_exit(NULL);
}

int main(int argc, char **argv)
{
    if (argc < 3){
        exit(-1);
    }
    srand(time(NULL));

    uint64_t *head,*tail,*tmp_ptr;
    int r;
    head = mmap(NULL,PAGE_SIZE,PROT_READ|PROT_WRITE,MAP_PRIVATE | MAP_ANONYMOUS,0,0);
    tail = head;
    for (size_t i = 0; i < ptrsize; i++)
    {
        r = (rand() & 0xF) +1;
        // try to use differents offset to the next page to prevent microarch prefetching
        tmp_ptr = mmap(tail-r*PAGE_SIZE, PAGE_SIZE, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS, 0, 0);
        *tail = (uint64_t)tmp_ptr;
        tail = tmp_ptr;
    }

    printf("%Lx, %lx\n", head, *head);
    main_cpu = strtoul(argv[1], NULL, 16);
    co_cpu = strtoul(argv[2], NULL, 16);
    pthread_t id[2];

    pthread_create(&id[0], NULL, foo, head);
    pthread_create(&id[1], NULL, boo, head);

    pthread_join(id[0], NULL);
    pthread_join(id[1], NULL);
}

Same Logical Core
> $ perf stat -e dtlb_load_misses.stlb_hit,dtlb_load_misses.miss_causes_a_walk,cycles,task-clock ./main 1 1
7feac4d90000, 7feac4d5b000
Running on CPU: 1
Running on CPU: 1

 Performance counter stats for './main 1 1':

             3,696      dtlb_load_misses.stlb_hit:u #   11.679 K/sec
               743      dtlb_load_misses.miss_causes_a_walk:u #    2.348 K/sec
       762,856,367      cycles:u                  #    2.410 GHz
            316.48 msec task-clock:u              #    0.998 CPUs utilized

       0.317105072 seconds time elapsed

       0.316859000 seconds user
       0.000000000 seconds sys

Different Physical Cores
> $ perf stat -e dtlb_load_misses.stlb_hit,dtlb_load_misses.miss_causes_a_walk,cycles,task-clock ./main 1 2
7f59bb395000, 7f59bb34d000
Running on CPU: 1
Running on CPU: 2

 Performance counter stats for './main 1 2':

            15,144      dtlb_load_misses.stlb_hit:u #   49.480 K/sec
               756      dtlb_load_misses.miss_causes_a_walk:u #    2.470 K/sec
       770,800,780      cycles:u                  #    2.518 GHz
            306.06 msec task-clock:u              #    1.982 CPUs utilized

       0.154410840 seconds time elapsed

       0.306345000 seconds user
       0.000000000 seconds sys

Same Physical Core / Different Logical Cores
> $ perf stat -e dtlb_load_misses.stlb_hit,dtlb_load_misses.miss_causes_a_walk,cycles,task-clock ./main 1 5
7f7d69e8b000, 7f7d69e56000
Running on CPU: 5
Running on CPU: 1

 Performance counter stats for './main 1 5':

         9,237,992      dtlb_load_misses.stlb_hit:u #   20.554 M/sec
               789      dtlb_load_misses.miss_causes_a_walk:u #    1.755 K/sec
     1,007,185,858      cycles:u                  #    2.241 GHz
            449.45 msec task-clock:u              #    1.989 CPUs utilized

       0.225947522 seconds time elapsed

       0.449813000 seconds user
       0.000000000 seconds sys


text:
Q: Why does using Cytoscape I can`t align text correcnly I am vizualizing my db with cytoscape.js, but I can't align the parent nodes text correctly (by object). It seems like the "parent" selector does not exist. All other selectors are working correctly for me.
Here is the important part of my js file:
var cy = window.cy = cytoscape({
  container: document.getElementById('cy'),
  style: [{
      selector: 'node',
      css: {
        'content': 'data(label)',
        'text-valign': 'center',
        'text-halign': 'center',
        'font-style': 'oblique',
        'font-size': 10,
        'shape': 'round-rectangle',
      }
    },
    {
      selector: 'parent',
      css: {
        'text-valign': 'top',
        'text-halign': 'center',
        'font-style': 'normal',
        'font-size': 15,
      }
    },
    {
      selector: 'edge',
      css: {
        'curve-style': 'unbundled-bezier',
        'control-point-distances': [-20, 10],
        'target-arrow-shape': 'triangle'
      }
    }
  ],

  elements: myElements,

  layout: {
    name: 'preset',
    padding: 5
  }
});

A: You are using the parent selector wrong, you can read up on these selectors in the docs:
var cy = window.cy = cytoscape({
  container: document.getElementById('cy'),
  style: [{
      selector: 'node',
      css: {
        'content': 'data(label)',
        'text-valign': 'center',
        'text-halign': 'center',
        'font-style': 'oblique',
        'font-size': 10,
        'shape': 'round-rectangle',
      }
    },
    {
      selector: ':parent',
      css: {
        'text-valign': 'top',
        'text-halign': 'center',
        'font-style': 'normal',
        'font-size': 15,
      }
    },
    {
      selector: 'edge',
      css: {
        'curve-style': 'unbundled-bezier',
        'control-point-distances': [-20, 10],
        'target-arrow-shape': 'triangle'
      }
    }
  ],

  elements: myElements,

  layout: {
    name: 'preset',
    padding: 5
  }
});


text:
Q: Loading sql text file into variable and submitting insert/update query via pymysql produces warnings - safe to ignore? I have some stored procedures that are stored in a .sql file.  I want to use pymysql to add these to the DB.  So, I am loading the file into a variable, like this:
    with open(filepath, 'r') as file:
        sql = file.read()

Then I am using pymysql to submit that, like this:
    connection = pymysql.connect(...)

    with connection.cursor() as cursor:
        cursor.execute(sql)

    connection.close()

This seems to work great, but I get warnings that concern me.  They look like this:
/usr/lib/python3/dist-packages/pymysql/cursors.py:322: Warning: (139, 'Row size too large (> 8126). Changing some columns to TEXT or BLOB may help. In current row format, BLOB prefix of 0 bytes is stored inline.')
self._do_get_result()
/usr/lib/python3/dist-packages/pymysql/cursors.py:322: Warning: (1246, "Converting column '' from VARCHAR to TEXT")
self._do_get_result()

My question is:  are these safe to ignore?
Update:
I figured out the first warning (the one about Row size too large):  The sql text file that generated that warning was a View creation, not an SP creation, and the amount of fields in the view did exceed the row size, so mystery solved there.  I'm still trying to figure out what exactly is causing that second warning.
Update 2:
I figured out the second warning.  The sql text file that generated that one was an SP creation, and there was a variable declared in there as DECLARE v_sql VARCHAR(32000).  I changed that to VARCHAR(2000) and the warning went away.  So, it looks like having variables greater than a certain size will generate that warning.

A: For the first warning I posted, the issue was: The sql text file that generated that warning was a View creation, not an SP creation, and the amount of fields in the view did exceed the row size
For the second warning I posted, the issue was:  The sql text file that generated that one was an SP creation, and there was a variable declared in there as DECLARE v_sql VARCHAR(32000). I changed that to VARCHAR(2000) and the warning went away. So, it looks like having variables greater than a certain size will generate that warning.


text:
Q: Why is script calculating Ellipsoidal area instead of cartesian area? I have this two shapefiles (https://drive.google.com/file/d/1a83sh-V46uaoUFwPXEtoZnD_XUBGG9X9/view?usp=sharing). The original one is in 4326 reference system.
The second one is the result of qgis reproject processing.
I wish calculate the area (square meters) in each feature. This is my script:
# -*- Encoding: UTF-8 without BOM -*-

import ogr
from qgis.core import (
    QgsApplication,
    QgsCoordinateReferenceSystem
)

### CHANGE
dissolved_path = '/etc/zagros/20220223_Silvia_Jaqueline_RASTER/LITORAL_PR_CITYS_RASTER_EXT/ANTONINA/2000/0003_ANTONINA_PR_2000_DISSOLVED.shp'
reprojected_path = '/etc/zagros/20220223_Silvia_Jaqueline_RASTER/LITORAL_PR_CITYS_RASTER_EXT/ANTONINA/2000/0004_ANTONINA_PR_2000_REPROJECTED.shp'

import os
#  Initiating QGIS
os.environ["QT_QPA_PLATFORM"] = "offscreen"

qgs = QgsApplication([], False)
qgs.setPrefixPath("/usr", True)
qgs.initQgis()

import sys
sys.path.append('/usr/share/qgis/python/plugins')
sys.path.append('/usr/share/qgis/python/plugins/processing')

from processing.core import Processing

#  Initiate processing lib
process_obj = Processing.Processing()
process_obj.initialize()

standardAREAfield = "area"

utmzone = 22
epgs = 31982
# Parameters for qgis scripting
algorit = "native:reprojectlayer"
parameters = {'INPUT': dissolved_path,
              'TARGET_CRS': QgsCoordinateReferenceSystem.fromEpsgId(epgs),
              'OPERATION': f'+proj=pipeline +step +proj=unitconvert +xy_in=deg +xy_out=rad +step +proj=utm +zone={utmzone} +south +ellps=GRS80',
              'OUTPUT': reprojected_path
              }

# Execute processing alg
Processing.processing.run(algOrName=algorit, parameters=parameters)

# Build driver
driver = ogr.GetDriverByName("ESRI Shapefile")

# Open shapefile reprojected
datasource_reproject = driver.Open(reprojected_path, 1)

# Build layer from reproject dalyer
lyr_reprojected = datasource_reproject.GetLayer()

# Insert area field on attribute table
idfield = ogr.FieldDefn(standardAREAfield, ogr.OFTReal)

# Set field width
idfield.SetWidth(20)

# Set field precision
idfield.SetPrecision(2)

# Create the field on the layer
lyr_reprojected.CreateField(idfield)

for features in lyr_reprojected:
    # Feature Geometry object
    geom = features.GetGeometryRef()

    # Calculate area from geometry
    area = geom.Area()

    # Set area field with area value
    features.SetField(standardAREAfield, area)

    # Setting the features of this layer (final step, saving what i just wrote)
    lyr_reprojected.SetFeature(features)

    features.Destroy()

datasource_reproject.Destroy()
lyr_reprojected = None

The matter is the feature number 6 is a perfect square of 30 x 30 meters, so the area should be 900.00 m2... But this script is saving the value of 809.90.
What am I missing?

A: I believe I found that feature from your files. The reprojected geometry from 0004_ANTONINA_PR_2000_REPROJECTED.shp is not square and the sides are not 30 m. The geometry as WKT is
POLYGON ((
        733451.619710086 7187073.450727058,
        733478.7364326176 7187072.979020646,
        733478.2170076868 7187043.121013427,
        733451.1003455913 7187043.592723457,
        733451.619710086 7187073.450727058
    ))

The cartesian lengths of the sides are about 29.8 m (N-S) and 27.2 m (W-E). The area 809.89 square meters is calculated correctly by cartesian coordinates.
It seems that reprojection of data does not happen like you supposed. The original EPSG:4326 geometry is
POLYGON ((
        -48.679076425737996 -25.41495635525268,
        -48.67880693115276 -25.41495635525268,
        -48.67880693115276 -25.415225849837917,
        -48.679076425737996 -25.415225849837917,
        -48.679076425737996 -25.41495635525268
    ))

Did you these coordinates as basis when you wrote that the sides are exactly 30 meters? How did you calculate that?


text:
Q: Redirect the people from website join the telegram group Is it possible to create a PHP script which allows us to redirect the people from website form to join telegram group?
Example, we have a simple form on the website with username and email. when user will fill the form the user will redirect from website to join the telegram group.
Does somebody know how to?
Thank You!

A: This should do the trick
header('Location: <telegram url>');