How to Efficiently Retrieve the Oldest Transaction Signature for a Solana Address with Billions of Transactions

Question: I'm working on a project where I need to retrieve the oldest transaction signature for a given Solana address. However, I'm facing a challenge when dealing with addresses that have billions of transactions. My current code, which fetches signatures in batches, doesn't work efficiently for such addresses and could easily hit the rate limit.
Here's my current code:
import asyncio
from solana.rpc.async_api import AsyncClient
from typing import Optional
from solders.pubkey import Pubkey

SOLANA_RPC_URL = "https://api.mainnet-beta.solana.com/"  # Example RPC URL, adjust as necessary

async def get_oldest_transaction_signature(address: str) -> Optional[str]:
    async with AsyncClient(SOLANA_RPC_URL) as client:
        # Start with None to get the most recent signatures first
        before = None
        oldest_signature = None

        address = Pubkey.from_string(address)

        while True:
            # Fetch a batch of signatures
            signatures_response = await client.get_signatures_for_address(
                address, before=before, limit=1000
            )
            signatures = signatures_response.value
            if not signatures:
                break  # No more signatures found
            # Update the oldest signature
            oldest_signature = signatures[-1].signature
            # Set the 'before' parameter to the oldest signature in the current batch
            before = oldest_signature
    if oldest_signature:
        return str(oldest_signature)
    else:
        return None

# Usage example
async def main():
    address = "BXbmrFeRNUn13V5YYHnXe2Ws55H48hJuB7LyKqEyXLTh"  # Replace with the actual address
    oldest_signature = await get_oldest_transaction_signature(address)
    print(f"Oldest Transaction Signature: {oldest_signature}")

if __name__ == "__main__":
    asyncio.run(main())

The issue with this code is that it starts from the most recent signatures and keeps fetching batches of signatures until it reaches the oldest one. For addresses with billions of transactions, this approach is not feasible due to the large number of requests required and the potential of hitting the rate limit.
Is there any way to efficiently filter and retrieve only the first (oldest) transaction signature for a given address? I want my function to return the very oldest transaction signature without having to iterate through all the transactions.
NOTE that the given address is just a sample and does not contain billions of transactions but I am still getting rate limits because there are lots of transactions.
If we can just filter or sort it in descending order (oldest to latest).
Is there any function like that?
Any suggestions or alternative approaches would be greatly appreciated. Thank you in advance for your help!
Answer: You're unfortunately doing things the right way.
Using the normal Solana RPC, you'll need to iterate through calls to getSignaturesForAddress using the before parameter, there's no other simple way. As long as you respect the rate limiting and back off when the server tells you, you'll be fine.
Other RPC providers might have additional indexing solutions, so be sure to do some research.
Alternatively, you could search through all of the blocks that have ever been produced using getBlock and sifting through all transactions for the target address, but that will likely take even longer.


As a citizen, we have the right to a speedy and fair trial by jury of our PEERS. How does a group of one's peers present their attendance to a judge?

Question: A defendant has the right to be tried by his peers. A group of the defendant's peers want to attend the trial as these peers. How do we confront the judge with our rights to be those peers? Peers are not court appointed jury.
Comment: You do not have that right. It is not up to you to determine who is and who is not a peer. In fact, if you are too close to one of the sides you would be recused as you would not be expected to be impartial. And it is not the juror's "right"; it is the defendant's right so it would be defended by the defendant's lawyer, if needed.
Comment: Does this answer your question? [Legal Definition of Peers, as in Jury of your Peers](https://law.stackexchange.com/questions/5351/legal-definition-of-peers-as-in-jury-of-your-peers)
Comment: @SJuan76 Your comments should be placed as an answer, as they are clearly an attempt at one.
Comment: @SJuan76 Thank you for the comments. They're a helpful way to provide information that other users can turn into an answer when you don't have the time or inclination to work one up yourself.
Comment: The linked question is clearly related, but in my view is not a duplicate. It focuses on the legal definition of "peer". Thus focuses on process, and rights.
Answer:
A defendant has the right to be tried by his peers.

In the U.S., this is an incorrect belief. A defendant does not has the right to be tried by his peers in the U.S.
The "jury of his peers" language is a legacy of English law in the days when aristocrats were entitled to a jury of aristocrats rather than commoners, while commoners were entitled to a jury of commoners.
The sole legacy of that in U.S. law is in court-martials in which officers are entitled to have their cases heard by a panel of fellow officers, rather than by a panel of active duty military personnel generally.
Outside of court-martials in the U.S., the "jury of his peers" concept was eliminated not later than the time when the current U.S. constitution was adopted (in 1789) which eliminated hereditary titles of nobility, or when 6th Amendment to the Bill of Rights was adopted (as applicable in federal criminal cases) which was adopted in 1791.
Instead, the Courts have interpreted the 6th Amendment right to trial by jury, which has now been applied to state and local governments as well, to require that the jury be drawn from a fair cross-section of the community (regardless of what an individual jury actually ends up as) and to have people who are conflicted or biased removed from the jury.
Answer: From your user name, I guess you are in the US. So the relevant text would be the 6th Amendment,

In all criminal prosecutions, the accused shall enjoy the right to a speedy and public trial, by an impartial jury [...]

There are exceptions to the trial being public, either at the request of the defendant or at the request of the prosecution/government. Also, being public does not mean that all prospective attendants may watch, just that some visitors and press are allowed in, up to capacity.
The legal system tries to assure an impartial jury by not picking them from the visitors. The way to be picked varies from state to state, it starts with voter records, driving licenses, etc. and then a random pick, followed by attempts to exclude those with a connection to the case.
Comment: "There are exceptions to the trial being public, either at the request of the defendant or at the request of the prosecution/government." This said, the press and public have standing to challenge the closing of a trial even if the prosecution and defense agree otherwise (and the public often prevails in these cases).
Answer: The relevant provision in the US federal constitution is the Sixth Amendment,  which reads:

In all criminal prosecutions, the accused shall enjoy the right to a speedy and public trial, by an impartial jury of the State and district wherein the crime shall have been committed, which district shall have been previously ascertained by law.

Note that this says nothing about peers. It requires the jury to be "impartial",  and to come from the same area where the crime occurred.
The phrase "Jury of his peers" derives from the English Magna Carta (Great Charter), specifically from Chapter 39 of the 1215 version. A translation into modern English of this posted by the British Library reads:

(39) No free man shall be seized or imprisoned, or stripped of his rights or possessions, or outlawed or exiled, or deprived of his standing in any way, nor will we proceed with force against him, or send others to do so, except by the lawful judgment of his equals or by the law of the land.

This demand was made of King John by the Barons, who objected to being judged  by those of inferior social status. Originally it applied primarily to judges, not juries. But it was not enforced as intended. The clause "or by the law of the land" was soon taken to man that as long as a judge ruled according to established law, the judge could be of common birth. (see *Magna Carta by J. C. Holt, ISBn 978-1107471573; Se also The Law of the Land by Charles Rembar) Later chapter 39 led to the right of British Peers of the Realm to be tried only by the House of lords, a right that persisted in the UK until well into the 20th century. But there has never been that sort of right in the US since it became a nation.
Some older state constitutions do preserve the words "jury of peers". For example The Virginia Constution provides (in Art. I, § 8) that:

In criminal prosecutions a man has a right to demand the cause and nature of his/her accusation, to be confronted with the accusers and witnesses, and to call for evidence in his favor, and s/he must enjoy the right to a speedy and public trial, by an impartial jury of his/her vicinage, without whose unanimous consent s/he cannot be found guilty. S/he shall not be deprived of life or liberty, except by the law of the land or the judgment of his peers, nor be compelled in any criminal proceeding to give evidence against himself, nor be put twice in jeopardy for the same offense.

But this, and similar provisions elsewhere, have been held to mean a jury of citizens, not specially selected to include or exclude any race, profession, or other special group. Indeed any such selection would render the trial invalid under the Sixth Amendment, and the Due Process clause of the Fifth or Fourteenth.
There is no process by which a group may present itself to a judge as the "peers" and ask to be seated as the jury in a particular case, nor by which the defendant may present a group as his or her "peers". A defendant may object to a particular person believed to be biased or otherwise ineligible, and may object to a selection process s/he thinks unfair or biased. But a defendant may not demand and obtain a jury that more closely resembles himself or herself than a widely representative cross-section of the community.
Law.com says of the jury guarantee:

...This has been interpreted by courts to mean that the available jurors include a broad spectrum of the population, particularly of race, national origin and gender. Jury selection may include no process which excludes those of a particular race or intentionally narrows the spectrum of possible jurors. It does not mean that women are to be tried by women, Asians by Asians, or African Americans by African Americans.

The LII page says of the Sixth Amendment provision:

This right can be found in the Sixth Amendment of the U.S. Constitution where it states, "the accused shall enjoy the right to a speedy and public trial, by an impartial jury." See Impartial Jury. The purpose of this provision is to ensure that a jury's verdict is not tainted by biases that jurors may harbor before being presented with the evidence of the particular case. Readily recognized biases include gender, race, sexual orientation, nationality, etc. To exclude potentially biased jurors, either party to the suit may use a peremptory challenge during the jury selection process.


How to use Raster Translate in QGIS to convert to PNG with color?

Question: I am trying to use the QGIS Raster Translate to convert a geotiff of my slope to PNG. I was able to create a PNG image with transparency. However the resulting image was white/black and did not adopt my symbology. How can I possibly input maybe an additional command to adopt my symbology? The raster is single band.
Answer: Add your raster to a new QGIS project.  Symbolize your layer with psuedo-color as you see fit.  From the Project menu choose Import/Export.  From Import/Export choose Export Map to Image.  Ensure that you have checked the Append georeference information checked.  Pick the image size, scale, and resolution as appropriate.  Save as a PNG.  The output location will include the PNG and the PGW.
Answer: Converting a single band raster to a three band raster is not going to change the fact that you only have one band of data. This operation is not going to 'add color' to the raster.  It sounds like you have a symbology problem.  See this tutorial on different strategies for symbolizing raster data in QGIS.
Comment: I know how to add a Symbology. What I am asking is how to convert the raster with psuedo-color to PNG with the color involved since the process does not adopt the color.


How do I migrate my Blogger blog to WordPress without losing my present search engine rank?

Question: I presently own a Blogger blog which is already ranking on Google for some keywords. I want to migrate to WordPress because of low SEO quality of Blogger but I have some few concerns about the best way to go about it since I'm already ranking on Google.
Wouldn't that mean I'm going to be starting all over again? If I post the same post which I already posted to Blogger, wouldn't the new ones be ignored as duplicate?
Answer: it depends on how your site is setup. If you have your own domain on Blogger (i.e. www.myblog.example), the ranking should not change if you move to another provider. But if you have a blogger address, yes the ranking will drop because the adresse of the site will change.
Also, please note that the SEO is not made by Blogger (you cannot say "low SEO quality of Blogger..."). 95% of your SEO is coming from the quality of your content.
Answer: Although it's not easy, it is possible to completely move your blog to from blogger to Wordpress.
Wordpress even supports this in a way:
Once you install WP, go to Dashboard>Tools>Import>Blogger (see screenshot). This will import all your posts from blogger.
For further info on how to do this, please refer to this article, which covers the topic in depth.


Parsing resources

Question: Does anyone know any resources (books/websites/whatever) related to parsing. I'm not so much interested in specific technologies such as yacc, XML or regular expressions, but something more general about best practices, stream vs. pull, error reporting and recovery, gotchas to look out for etc.
Answer: There a nice book on parsing techniques Parsing Techniques, a Practical Guige. You should be able to find some interesting bits. There is complete chapter on error handling.
Answer: This may not be exactly what you meant, but a very good, and slightly relevant, book;
Data Crunching: Solve Everyday Problems using Java, Python, and More

Parsing resources


Can I tell who is accessing archive.org archived documents from my site from my server logs?

Question: I currently host a website with a collection of some of my projects, where a few of them are currently undergoing a patent review process. I don't want these documents to be public (though they were in the past), so I've deleted the documents on my website. However, they are still available on the Wayback Machine's archive.org. The Wayback Machine has informed me that they do not store who has accessed certain URLs, but they can remove my page from the archive if I request it.  Is there a way that I, through my own server logs, can see that these old, since-deleted documents are being accessed? My backend collects access logs, for the record.
Answer: No.
The wayback machine stores its own copy of the page, so browsers dont interact with your server when viewing the archived version (thats the point of it.. if your site changes or goes away there is still a record)


Max request per sec/hour for a VF page webform

Question: We have a VF page as a webform and hosted as a Salesforce site.Because there are lot of requests hitting it,is it possible for us to get an estimate of how many requests can it handle per sec/hour?Is there a way to perform a load testing for this VF page.Can we use Event monitoring to find out max requests it can handle at once?
Any immediate response is appreciated.
Answer: Performance testing is not allowed without advanced notice.

Sometimes changes and customizations to your Salesforce implementation impact performance. Before going into production, it is wise to run sandbox performance tests, please read Methods of Locating and Testing for Performance Issues. Salesforce is a multi-tenant environment. If you decide to test, you will need to schedule this with Support so Salesforce can monitor activity levels.

...

Performance tests must be submitted for approval at least two weeks in advance of the testing date(s), requests without a two week notice may be denied. To submit the request, navigate to the Help portal and select Network and Performance > Notify Salesforce of an upcoming activity > Schedule a Performance Test

Note that the basic limits are determined by the Site.com limits. If you need more than this amount of power, you can negotiate for additional power (bandwidth, CPU time, etc). Contact your account executive for more information. That said, you can estimate how much data and CPU your page uses, divide it in to the Site.com limits, and you'll have an estimate to how many requests you can handle.


Isekai manga about a hero that has been given a phoenix

Question: The manga I've been looking for is an isekai manga about the MC who has been isekai'd and has been given a phoenix as a pet/mount by a small goddess, approximately the size of a chicken.
Comment: I think it was given to the MC by a goddess in the size of a chicken. @Valorum
Comment: This is incredibly terse, can you not remember anything else about the manga? When did you read it? Why was he given the phoenix? By whom? Can you remember any plot elements at all? What any of the characters look like? If you remember anything else please [edit] your question to include those details. At the moment this is highly likely to be closed as "Needs detail/clarity" as I imagine there are several mangas where something like this happens so it will only be random guesses to try and find it. Remember the more detail you add the more likely it is someone will find this for you.
Comment: The New Gate (TSUKI GA MICHIBIKU ISEKAI DOUCHUU)?
Comment: @Solacia - If my answer below is correct, please mark it as [accepted](https://scifi.stackexchange.com/help/accepted-answer) by clicking on the check mark beneath the voting buttons. It will reward me with some [reputation](https://scifi.stackexchange.com/help/whats-reputation), and helps with the administration of the site. Also, please consider [upvoting](https://scifi.stackexchange.com/help/privileges/vote-up) the answer as well, if you haven't already. Thanks.
Answer: Could it be Reborn as a Phoenix: A Normal Bird Can't Beat a Dragon, Right?...?

The story begins with a boy hospitalised in modern day Japan, but soon shifts to a medieval setting where the same boy encounters a small flaming bird, which becomes his pet/companion.


Is micelle formation in a soap solution a chemical reaction?

Question: I know that soap molecules have a hydrophilic end and a hydrophobic end which attract to water and oil respectively. However, does a chemical reaction take place?
Answer: Chemical 'reactions' are normally defined by changes in 'bonding'.  Related to soap micelles, for the micelle to exist and have integrity enough to be characterized from a situation where they did not previously exist, some 'bonding' must come into being.  That bonding is normally described as 'London Forces' or 'Vander Waals Bonds' or 'Hydrogen bonding' or 'electrostatic' interactions.  Since equivalent concentrations produce equivalent results, the micelle formation is also reproducible.  In the purest sense this does imply that soap micelle formation is a chemical reaction.
The question is more philosophical than anything.


How to let line numbers count from 1 in org subtree?

Question: When I narrow an org mode header into a subtree(using command org-narrow-to-subtree) in vanilla Emacs, the line number counts from 1 in the subtree, but when I create a subtree in Doom Emacs, the line number counts from the original line number(e.g. if the header is on the 8000th line in the original file, the header in the subtree still starts from 8000, instead of 1). How can I make it count from 1 in the subtree?
Comment: What line numbering mode are you using?  display-line-numbers-mode (available since emacs 26) is both faster than older line-number modes (it's implemented in C not elisp I believe) and for me has the behaviour you say you want (i.e. when narrowed it counts from 1).
Comment: @CroadLangshan Thanks, but I believe I'm using `display-line-numbers-mode` because I've checked the value of `display-line-numbers-mode`, which is `t`. I also tried disabling the mode by running the `display-line-numbers-mode` command, the line numbers disappeared. Rerun the command redisplayed line numbers. So I think I'm using this mode to show line numbers.
Comment: What emacs version are you using?  I'm using 27.1, and the docs for variable `display-line-numbers` say "If the value is t, display the absolute number of each line of a buffer
shown in a window.  Absolute line numbers count from the beginning of
the current narrowing, or from buffer beginning.".  You might also poke around in variables starting with `display-line` (something like ivy or helm together with `C-h v` is helpful for that, or `M-x customize-group  display-line-numbers` )
Answer: Put this in an appropriate place in your emacs configuration (not sure what file that is for doom):
(custom-set-variables
   '(display-line-numbers-widen nil))

I think you could use setq-default instead if you like, but I hear there are some subtleties that make custom-set-variables a better choice for customize-able variables -- it's OK to use custom-set-variables in your ordinary emacs config however you like -- just don't edit by hand the special customize call that is commented with ;; custom-set-variables was added by Custom. unless you know what you're doing.
Alternatively, you can use M-x customize-variable <RET> display-line-numbers-widen <RET>.
Comment: Ah it automatically becomes buffer-local when set, so probably you'd have to use `setq-default` if you want to set a global default value across buffers (though since this is C-implemented, maybe it's even more special than that?  Haven't tested). Corrected my answer
Comment: Thanks, it worked! And as you said, only `customize-variable` worked. `setq` didn't work. Maybe `customize-variable` has higher priority.


What are ether pros and cons of a single high megapixel phone camera vs dual rear camera phone when photographing kids?

Question: I'm not too bothered about the actual phone but need to upgrade and am wondering what is better to photograph small children. My kids move alot and blurry pictures just seem to be the most commom picture. I want to capture the best images I can but am completely confused about the differences in the dual rear cameras and high mega pixel one. Which will have faster autofocus, and which will give better results overall.
Answer: Your existing camera may not be the issue here, and the two options you are looking at may not solve your problems. It seems you are seeing motion blur. This is related to shutter speed (the longer the shutter is open and/or the faster a child is moving, the more motion blur you will see). Try taking photographs in brighter light, ideally a sunny day. If you are using a completely automatic camera (which most phone camera apps are) it will most likely go to a faster shutter speed and you will not see motion blur. This is something quite old cameras will do just as well as modern ones. If you have a camera app with basic settings options, try choosing sports mode to get the same result.


Parent major Scale / A major to E flat...?

Question: The Basis for my query was that, Mode Scales' can be interpreted in either 'Series and/or 'Parallel... It turns out That, 'C (over )Aeolian, starts in the 6th degree, therefore counting backwards from C, is, Bb, Ab, G, F, Eb.  The chords over the steady C bass note are the vi, IV & V in the key of Eb major, which are Cm, Ab & Bb. Used as a Mode Drone backing to compliment the Aeolian C:.
Comment: Can you walk us through how you reached the answer of Ef major?
Comment: Keeping the w,w,s,w,w,w,s, formula for the Major Scale in mind, to calculate the PMS ( Parent Major Scale of a Key ), you count backwards from C: to, Aeolian,  C to, Bb, to, Ab, to, Gb to, F, to, Eb ! or, as in degrees A is six degrees of C / so , six degrees backwards is Eb.Why this is, I do not know. This is the way it is explained per Guitar Instructors via the WEB
Comment: Incidentally, modes are not exclusive to guitar, ( OP tag); they work for all instruments.
Answer: Usually when people talk about 'parent major scales' they are referring to the relationship between modes and keys. For example, D-dorian is all natural notes starting with D, or in other words a key signature of no flats or sharps. The major scale with no flats or sharps is C-major making C major the parent major scale of D dorian.
With that in mind, it doesn't make sense to ask what the parent major scale of a major scale is. The major scale that shares a key signature with A major is, well, A major. There is a mode - the Ionian mode - that is identical the major scale, so you might ask what the parent major scale of A Ionian is, and that would be A major.
It's nor clear how you ended up with E-flat.
Answer: The parent major of A IS A! I think what you're getting at is to, say, take a phrygian mode of E, for example, and calculate what the key sig., or major scale notes, it possesses.In this example, phrygian starts on the 3rd note of its parent scale, thus that will be C major. All the notes in E phrygian are those found in C.
It may be less complicated to consider the formula a different way."I don't play like my aunty Lou" works for me. No, I'm not ga-ga! It's a mnemonic for Ionian, Dorian, Phrygian, Lydian, Mixolydian, Aeolian, Locrian.
Let's go back to E Phrygian.Using the above list, it's the third on it. Always going back to Ionian, that will give us C major (E>D>C). It will work for all the modes of majors, or come to think, all modes.
Your problem, I think, stems from not knowing the notes which make up key signatures. I say this, as you mixed up a key with 3# and one with 3b. Any mode of a particular key MUST have the same notes as its parent, obviously, otherwise they can't belong together.


Science fiction book or series with a character called a Vail or Vale, a tracker who hunts the main character through space

Question: Looking for a book, or series of books, that had a character called a Vail or Vale that was basically a tracker and would kill the people tracked. When the person tracked was killed, the Vail started to assume their characteristics and started to realize that what they were doing was wrong.  Tracked the main character through space.
Comment: Hi, welcome to the site. In roughly which year did you read this, and when do you think it might've been published? Also, do you recall anything about the cover/s?
Comment: You could improve this question by going through the checklists [here](https://scifi.meta.stackexchange.com/questions/9335/how-to-ask-a-good-story-id-question) and editing in any relevant info you can think to add.
Answer: In the Rings of the Master series by Jack Chalker the main characters have a nemesis called a Val (named after the flying dutchman IIRC) that pursues them. It is an agent of the all powerful computer created to save the human race (only a slight spoiler, please excuse me). This sounds like the story you are recalling
Comment: The Vals were named after Jean Valjean from Les Miserables. A point is made that they were named after the pursued character because they were imprinted with the fugitive's memories so that they could better track/capture them
Comment: Thanks @AlanT. It's been a while since I read them. Might dig them out and refresh my memories.


What were Spirit and Opportunities wheels made out of?

Question: I'm doing a report on the mars rovers and am wondering what material did NASA use to construct spirit and opportunity's wheels. Was it aluminium? Rubber? Titanium? Magnesium? I don't know. Can't find any information on the topic so hoping you guys have some good idea of what they're made of.
Comment: I believe this answers your question: https://space.stackexchange.com/a/13232/32284. In short the wheels were made out of 10'' aluminium.
Comment: First guess would be aluminium, Rubber/plastic has problems in the temperature range of flight and Mars, Titanium is problematic to fabricate with unless you really need it's properties. Magnesium can catch fire and otherwise be chemically exciting which is not good on a wheel rolling across an unknown surface.
Comment: @GremlinWranger There are some kind of polyimides usefull for space applications, Solimide foam was used. Not an ordinary cheap plastic with low temperature resistance.
Answer: Aluminum and foam according to this page that describes the wheels as manufactured from a single Aluminum block with foam inserts into the spiral suspension system spokes. The black surface of the wheel itself is just an anodized coating.
Interestingly the wheels are described as being by design less effective in sand than they could have been by having curved rather than square cleats, to avoid getting snagging while crossing the airbags.
Given both rovers ended up getting bogged in sand possibly another data point in the decision to land later rovers under power rather than by airbag, since it avoids needing to compromise the wheel design this way.
Comment: The foam is made from [polyimide](https://en.wikipedia.org/wiki/Polyimide_foam) a polymer used for space aplications. It resists high temperatures and is relatively low outgassing. Kapton is a well known polyimide used to cover the Apollo Lunar Module.


How do I add cells together on OS X numbers app

Question: What format should the cell be? This can not be added and only gives a exclamation mark - "the formula contains a syntax error.
OS X and numbers v3.5.3
Comment: There are iOS versions of numbers and OS X versions of numbers. We can help if you edit these details into the post. The cell needs to contain an actual number and the steps to check and change that vary. Or you could use a function to convert strings to numbers, again that depends on the version.
Comment: Your screenshot shows adding two numbers, not cells.  What do you really need?  How to sum numbers or sum cells?
Answer: The error at the bottom of your screenshot is from a previous entry. The Result bar does not update as you type—it updates when the cell contents changes. There's nothing wrong with that formula. Press Enter to enter the formula into the cell.

As for adding cells: whilst in formula edit mode, click the cell to insert its reference into the current cursor location, and use the standard syntax (something+something).
Answer: gagarside's answer is the correct answer.
To take this a step further, you could use the SUM function.
To sum values hard coded (like in your original post):

To sum values in cells (more dynamic as one can change single values easily):


Patterns in Generalized Continued Fractions

Question: According to the Wikipedia page on generalized continued fractions, $\pi$ can be given several GCF representations which have very regular structures; for example, one has the partial denominators as (1, 2, 2, 2, ...) and the partial numerators as (4, 12, 32, 52, 72, ...).  My question is, can every real number be represented as a GCF that exhibits some sort of "structure"?  I put that word in quotes because I'm not really sure how to define it concretely; ideally, the sequence of either partial numerators or partial denominators should be expressable using a predictable, explicit formula.  Are there any theorems establishing results like this, or are there some numbers that have no GCF representation that is indistinguishable from random noise?  If some numbers need to be expressed in other forms for a pattern to emerge, like Engel expansions, I'd be interested in knowing about that too.
Answer: I think under any reasonable definition there will be only countably many explicit formulas or patterns. So in fact most reals can't be expressed this way. (See also the concept of "computable number.")
Answer: It depends on what you mean by "generalized continued fraction". Greg Martin has a nice paper where the role of reciprocal is replaced by other things; he shows that all nice things happen, and do so simultaneously.
I don't agree with the negative countable/uncountable explanations (although I agree with the conclusion) given in other answers. For example, let $A(x)=(\{\lfloor n x \rfloor: n\in {\mathbb Z}\})$, and consider the simple continued fractions $y=[0;a_1,a_2,...]$ where $a_i=1$ if $i=A(x)$, and $a_i=2$ otherwise. Distinct $x$ yield distinct $y$, so we get uncountably many reals this way, all of whose simple continued fractions have "structure".
Comment: I wouldn't call this "structure" unless x had certain nice Diophantine properties.
Comment: If you came across a number, computed its cf, and found that it happened to have this form, you'd say "holy moly!" To me, that's structure.
Answer: I assume you're restricting the numerators and denominators to be integers, else there's the trivial generalized continued fraction (x;0,0,0,...) for any x.
I'm going to interpret "formula" broadly, as the sequence generated by an algorithm. Again one has to make an integer restriction, because there's a simple algorithm to generate the standard continued fraction for any x. I think the right way to state the restriction is that within the algorithms generating the sequences of numberators and denominators all numerical constants should be integers. But with that restriction, the answer to your question is no: there are uncountably many real numbers and only countably many algorithms that can be used to generate generalized continued fractions.
Answer: It's true that certain types of real numbers can be expressed as patterned generalized continued fractions, as indicated by the "Examples" section of the cited article. However, not all reals can be so expressed. For example, according to Wikipedia, the Euler–Mascheroni constant (aka "gamma" or γ) "has not been proved algebraic or transcendental. In fact, it is not even known whether γ is irrational," but finding a generalized continued fraction for γ would answer the latter question.
Comment: How would finding a generalized continued fraction determine whether $\gamma$ is irrational? $2=1+3/(2+3/(2+3/(2+...$.
Comment: I'm well aware of the theory of simple continued fractions. Your statement that finding a GENERALIZED continued fraction for $\gamma$ would settle the rationality of $\gamma$ appears wrong.
Comment: I still see no universal test for rationality.
Comment: For rationality, if the SIMPLE (!) continued fraction for an expression terminates after a finite number of terms, the expression is rational; otherwise, it is not. Your above example shows that rational numbers can have nonterminating GENERALIZED CFs, but that's because there can be infinitely many of those for a given number, as opposed to only one SIMPLE CF (two if the final term b(k) > 1 is re-expressed as [..., b(k)-1, 1], but this is trivial). I try to choose my CFs to combine speed with relative simplicity.
Comment: If you look more closely in the "Examples" section, you'll see that your GCF for "2" is a special case of the GCF for the square root of (x^2+y), where in your case x=1 and y=3. It's certainly possible for nth roots be rational, but they generally have a simpler form than transcental functions and numbers. I expect that should a pattern be found, it will be cyclic, but the numbers themselves will not repeat, similar to the nth root examples in the same article, but requiring several terms before the repeating pattern becames apparent.


Diode-connected PMOS

Question: Im currently a year 1 electrical engineering student. May I ask, for a diode-connected PMOS (gate connected to drain), why is |Vsd| = |Vgd| ?
Comment: Are asking why you take the absolute value or why they are equal to each other? Please explain what you don't understand the equation that you have provided? **_ALSO_** please quote where you saw this equation because it is likely that the location where you got this equation will also provide you some information about the equation.
Comment: The equation is not correct. If the gate and drain are shorted together, then \$V_{gd}\$ is zero. But \$V_{gs}\$ will be approximately equal to \$V_{th}\$ (if there's non-zero current through the channel).
Answer:
The relation you have asked for in the question is wrong.
In the diode connected PMOS, fig.B, Gate and Drain are shorted.
Hence \$V_G = V_D\$.
And therefore \$V_{GD} = 0 \$ and \$V_{GS} = V_{DS}\$.
M2 will always be in saturation as \$ V_{DS} > V_{GS} - V_{Th} \$ always.

Diode-connected PMOS


What is the business term to use when describing take a business to smaller markets

Question: Like a business used to operate in big cities/markets, now the mgmt team made a decision - avoid the saturation and competition - to take the business to smaller places where there are new opportunities and less competition. Is there a business jargon for this?
Answer: It is market diversification:

Corporate strategy:

Practice under which a firm enters a market different from its core business. Reasons for diversification include (1) reducing risk of relying on only one or few income sources, (2) avoiding cyclical or seasonal fluctuations by producing goods or services with different demand cycles, (3) achieving a higher growth rate, and (4) countering a competitor by invading the competitor's core industry or market.

(www.businessdictionary.com)
Comment: yea am aware of the diversify narrative just looking for a lingo that is specific to this going down to smaller markets/lower-tiered cities behavior.
Comment: @BenJIANG - not sure there is a specific definition, what I usually hear is : big companies are going to *tap smaller markets*.


Feature Engineering on transactional dataset clustering

Question: I have a data set with transactions details from different business (roughly 1 thousand business entities). Each row is a transaction. The structure of the dataset is as follows:

client_id
Sex
Age
transaction_ammount
business_entity

123
M
88
4829
storeA

123
M
88
1049
storeB

255
F
25
1122
storeH

My goal is to cluster the clients depending on their consuming habits, age and sex.
I am having a hard time on deciding on the best features to feed this dataset into a clustering algorithm (probably K-means as a starter).
Some of the things I am planning to do are:

One hot encoding on: sex
Make each store be a column and each row value be the amount of transactions a certain user did pay to that store (for example, if user1 made two transactions to storeB, there will be a 2 in the user1 row on the storeB column).

One of the main things I am struggling with right now is how to sum the transactions data per user. I would need to run an aggregated operation on them, but don't know which one would be better. Some of the ones I have in my mind:

Average transaction amount per user
Min transaction amount per user
Max transaction amount per user
The above 3 but for each store per user (which would mean that, if I have 1000 stores, I would have to add 3000 thousand columns). This makes sense since each store have a wide range of product prices and running an operation among all the transactions of a user will be misleading.

What feature engineering technique would you recommend me? Is there any additional data wrangling I should do?
Answer: Depending on your processing limitations I'd be tempted to do the following, for each client a single row consisting of:

Age
Sex (one hot encoded)
Per store:

Purchase Count
Total Purchase Value
Average Purchase Value
Min Purchase Value
Max Purchase Value

Additionally if you have the transaction dates I'd try to include things like:

Days since first purchase
Avg. days between purchases

Hopefully that helps you a bit, good luck!


Authenticated vs Unauthenticated network scans

Question:
What are the differences between authenticated and unauthenticated network scans?
Do they show the same results?
In which scenario should both be used?
Comment: So your question does not make any sense now... I never heard of "authenticated network scan", so could you please ellaborate?
Comment: What are you trying to scan?
Answer: I assume you are talking about web applications. If not, edit your question as my answer will not make much sense.

What are the differences between authenticated and unauthenticated scans?

Authenticated scan is when you have a valid account on the application. Unauthenticated is when you do not have any.

Do they show the same results?

No, they show different results. Unauthenticated scan will show every resource that anyone on the internet can access, without having an account. Authenticated will show only resources accessible to valid users.

In which scenario should both be used?

If the application don't have account controls, a simple unauthenticated scan is the only option, as you cannot use an account if no accounts are available.
If there are accounts involved, use both. Why?
If you have credentials, login on your account and scan everything you can. Map every resource, every available backend, everything. Log out, and try to access the protected resources with the unauthenticated session. If you can access secured resources without an account, you found an authentication bypass vulnerability.
Comment: And a variety of  privilege escalation is when not only anonymous/authenticated access but also multiple levels of authentication are supported; a regular user should not get more privileged (admin) levels of access or access to content belonging to a different authenticated user.
Comment: I just edited the post. I meant about network scans. Sorry for the confusion.
Answer:
What are the differences between authenticated and unauthenticated network scans?

As noted above - it depends whether the scanner is given a valid account or not.

Do they show the same results?

For infrastructure scans, they should but rarely do. Authenticated scans can use the (usually) admin access they are given to check patch status and version numbers more accurately (in theory) than the direct tests might be able to do. This, of course, depends on the information they are accessing (for Windows systems, usually in the Registry) to be correct. Which it usually is but it is the edge cases where it isn't that are interesting.

In which scenario should both be used?

As ThoriumBR noted, if you are doing web app testing, you need to use authenticated scanning and should, in fact, scan with different privileged accounts. If you are doing infrastructure testing, you would usually use both methods if you are testing from an internal IP (or remotely but with a test scanner inside the target network.) And compare the results from the two different scan types (or from the different privilege levels with a web app scan.)
Answer: The question is at least weird formulated.
Network scan implies scanning for network devices which generally does not require anything but network access/valid network address. You just use a general network scanning tool that can be standard ICMP or something else based (if ICMP is blocked) and that's it. Nothing else is necessary.
If you want to deep scan devices like PCs, then yes, there is a big difference between being authenticated and unauthenticated. The result will clearly be different as a general scan for device information will go as deep as you have access.
So with no authentication you will get basic results and with an authentication like domain-level you will get very detailed information about domain-member devices.
As for scenarios, it depends on your objective. To determine the PCs in a network  segment clearly you don't need to authenticate, but if you want detailed info like registry content or detailed system information you need to authenticate on these devices.


Animated part showing up rotated in game, but fine in blender 2.79

Question: Right first of all I know you're probably thinking it's the games fault... But it's 100% not.
I know this because in call of duty 4 other weapon models are set up the exact same and they work fine. With that out of the way I'll tell you what's wrong.
So I'm using "Blender CoD" add-on for blender which allows me to import/export models in an xmodel_export format which the game uses to convert the model to a usable weapon.
So I have an armature and vertex meshes set up using the same bone structure from a working model I'm adapting as the gun I'm creating (LW3 Tundra from call of duty black ops cold war) is an evolved version of the L96 from various games, in this case battlefield 3.
I'd run into a couple issues at first as I've never really used blender before and I'd probably spend 20 hours learning by myself how to use it.
Issue 1 - solved) The scope wasn't repositioning correctly in blender
so I pressed "Ctrl + a" and set the rest position or something or other.
I solved that and then got the next issue.
Issue 2 - solved) The weapon bolt (cocking device) wasn't in the right place and was to the left.
I solved that by doing the same as I did to the scope.
Issue 3 - unsolved) So after I'd done that I'd set the "rest pose?" Using the same Ctrl + a method. But this time the bolt was still rotated upwards in game, but not blender.
Which I found was weird because I solved every other problem by realizing that something was wrong in blender. I had no problems with the rotation in previous testing, but now it's not going away.
I think one of the reasons this is is because I'd set the rotation with the set to rest pose method. And maybe because the part is animated, it screwed up?
I tried rotating bones, putting them on different parts of the model but no use. Any help would be helpful.
Method I used to fix the scope, except I did it on the meshes, although it seemed to work.
My Rig Changes Position in Edit/Object Mode?
"
I had this same problem too! I tried all of these answers but none helped, I finally figured it out. All you have to do is go into pose mode and select each bone individually(you might be able to select all but I didn't try) and press "Ctrl+A" and apply location, rotation, and scale. If this doesn't help for you I am very sorry. It worked for me.
"
Answer: Simple fix, just adjust the part to the incorrect position and apply as rest pose using Ctrl +  A in Pose Mode


Why doesn't BGP come up when no hold-time is defined?

Question: Why doesn't BGP come up when no hold-time is defined?
if defined, the BGP protocol comes up without any problem.
Comment: We need more details in order to answer your question.  Please provide the equipment model, OS version, and relevant configuration,
Comment: I respectfully don't agree with  you @Ron Trunk , in my opinion this should be enough to answer this theoretical question. I don't get why a default wouldn't hold-time wouldn't be enough if none is defined between two devices.
Comment: It may be how the particular vendor(s) implemented the protocol.
Answer: Check your log file for an Unacceptable Hold Time open error subcode from the peer.  A BGP speaker isn't required to support the default hold time.  The specification is a bit poorly-structured in this regard, but see RFC 4271 § 6.2.


Failed to load resource: the server responded with a status of 502 (Bad Gateway)

Question: How can you solve a 502 error?
I believe whats causing the 502 error is a nested loop that contains heavy calculations. It would take up to 2 minutes for it to finish that block of code on my local server. However on a public server I just get this
502 Bad Gateway
nginx/1.10.3 (Ubuntu)
for j in x:
    if j == 1:
        index_for_multi_array = 0
    else:
        index_for_multi_array = 1

    q = con[j-1] # index 0 and 7
    q = q * 1e-6
    m = mass[j-1]
    for i in range(1,int(bands[j-1])+1):
        #read parameters
        vc         = float(_1_wnum[index_for_multi_array][i-1])
        S0         = float(_1_int[index_for_multi_array][i-1] )
        gamma_air  = float(_1_abroad[index_for_multi_array][i-1])
        gamma_self = float(_1_sbroad[index_for_multi_array][i-1])
        n          = float(_1_abcoef[index_for_multi_array][i-1] )
        #resonance shape
        alpha_1  = float( (1.0- q) * gamma_air  + q * gamma_self ) * (P/P0) * ((T/T0) ** n)
        fv       = (alpha_1 / math.pi) * np.power((np.true_divide(v,vc)),2) * np.add((np.true_divide(1, np.power(v-vc,2) + alpha_1**2)) , np.true_divide(1,np.power((v+vc),2)+alpha_1**2))
        gv       = np.true_divide(v,vc) * pre_calculation / np.tanh(h*c*vc / (2*k*T)) * fv
        S        = S0  #line intensity
        sigmav   = gv * S0
        qq       = q * P/R/T*NA
        kv       = P/P0*T0/T*qq*sigmav
        kvt[index_for_multi_array,:] = kvt[index_for_multi_array,:] + kv

the max number of iterations of the inner loop is 209,000
the number of iterations of the outer loop is 8
My site is made with django. I am also using numpy (i installed it on the public server), js, html, and css.
Also the home page works fine. On a click of a button I get redirected to another page. That page takes a while to load because there are a lot of calculations being made in views.py, but midway it crashes with the 502 error.
Any ideas for where to start looking to solve this error?
Comment: as @rchurch4 said , I'd move your code which has large calculations to be returned as an api and called via ajax. Also , If you're using web servers (nginx) please try by increasing [uwsgi-timeout](https://stackoverflow.com/questions/16141610/nginx-timeouts-when-uwsgi-takes-long-to-process-request).
Answer: Update: If your code isn't returning fast enough, I would suggest returning the blank page with no calculations returned, and have the page make an ajax call to the heavy calculations so that it can load asynchronously.  Once the calculations are done, the page will load their results: http://api.jquery.com/jquery.ajax/
So what you'd do is move the heavy calculations to a view that returns your results in some format like JSON (https://docs.djangoproject.com/en/2.1/ref/request-response/#django.http.JsonResponse), and set up Javascript on the original page to call that view, wait for the JSON to be returned, and render the JSON into whatever format you wanted on the page once it is returned.
Another option is to string up Celery: http://docs.celeryproject.org/en/latest/
OLD: Try changing proxy_pass to your server IP instead of 127.0.0.1:8000 in /etc/nginx/sites-available/myproject.  Also make sure that in your settings.py, your server's IP is in ALLOWED_HOSTS.
Bad gateways are not usually the result of coding problems.  They usually are configuration problems.
Comment: Okay, so I'm pretty sure that it's a configuration issue, but since I can't see your code, I can't be sure.  Try commenting out the heavy calculations and returning hard code instead of doing the computations. If you still get the 502, then it is certainly your configuration.
Comment: If your heavy calculations code is loading data from elsewhere on the server, are you sure that your static root and media root are properly configured?
Comment: Everything worked when I commented out the heavy calculations so the problem is there. I will edit my question to include the code that is causing this error. Do you know why this happening ?
Comment: I opened csv files and stored values in a numpy matrix at the beginning of the function. Which works fine.
Comment: If you were able to open the CSV files without the 502, then try the asynchronous call like I described in the updated answer. Celery could also be for you.
Answer: Use the nginx configuration directives proxy_read_timeout and proxy_send_timeout to make nginx not terminate the proxy connection prematurely and return an error.
Comment: I have been playing around with the nginx configs but its still crashing. I checked the nginx error log and this is what I got: upstream prematurely closed connection while reading response header from upstream.
Comment: I went to /etc/nginx/sites-available/django and this is the current setup   location / {
            proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
            proxy_set_header Host $host;
            proxy_redirect off;
            proxy_buffering off;
            proxy_read_timeout 900s;
            proxy_send_timeout 900s;
            proxy_pass http://184.108.40.206/;
    }
Comment: `upstream prematurely closed connection` means your worker host terminated the connection. Do you run e.g. uwsgi? That might have a timeout to restrict http requests as well.
Comment: I am not sure, how can I figure that out? Also after I make changes to /etc/nginx/sites-available/django do I have to run a command or something to recompile that file?
Comment: Do you own and run the worker host `220.127.116.11` ? Can you check what's running on that host? Also, if you try to hit a worker endpoint with e.g. curl - does it complete successfully ?
Comment: I am not sure how to check all that. But I think I figured out the problem. The site basically  crashes after 30 seconds of it loading which is the default time out of gunicorn. From what I read online, I have to change the timeout duration in gunicorn.config. I couldnt find that file though. Would you happen to know where it can be located?
Comment: Try changing http://docs.gunicorn.org/en/stable/settings.html#timeout - it defaults to 30 seconds so that's probably it.
Answer: Solved with going to python2.7 directory /usr/lib/python2.7/dist-packages/gunicorn and opening the config file and finding the timeout function and changing the default timeout from 30 to 60 .
The running the command service gunicorn restart
This should fix the timout problem


Is it possible to permute a binary vector obliviously?

Question: Lets say A has a binary vector of length n, B has a permutation matrix of size n. Is there a way for B to permute A's vector so that A only learns about the result of permutation and B does not learn about the original vector?
Comment: Just as a random observation, if A can make $\log_2 n$ queries with $n$-bit vectors against the same permutation matrix, then they can trivially recover the entire permutation. So if this is possible at all, the number of queries must be strictly limited.
Comment: Correct me if I'm wrong but surely if B knows the permutation p and the output he can invert p and use it to get the original vector again.
Comment: B doesn't know the output of the permutation, at the beginning A knows v, B knows P, and at the end A should know Pv while B still only knows P
Comment: If B knows the result, he knows the hamming weight, so some (usually small) information leakage is unavoidable
Answer: Using an encryption scheme that is rerandomizable (such as ElGamal for example), A can just send n ciphertexts encrypting her values, then B shuffles those ciphertexts and rerandomize them. B never learns anything and the rerandomization destroys information about the original ciphertexts so that A cannot trace back the permutation.
Comment: It's a binary vector, which implies the entries are all 0 and 1. With basic ElGamal you can't encrypt 0s. This [question/answer](https://crypto.stackexchange.com/questions/20907/how-to-use-elgamal-to-encrypt-zero) provides a small modification that facilitates encryptions of 0.


Risky Connection Blocked by McAfee

Question: McAfee has been blocking a connection from a certain IP address (I found the IP Adress to be from Hong Kong). Should I be concerned? McAfee says the program is "SYSTEM". Also if I should be concerned what could I do about it?
Comment: Welcome to Security.SE! Do you have any more information about this connection? Do you know if a program on your computer is trying to connect to the IP address of if the connection is coming from Hong Kong?
Comment: Note sure, that was all the information McAfee provided in a small pop-up window in the bottom of my screen.
Comment: You can sometimes find more information by looking in McAfee's logs stored on the computer. I don't know the exact location, but you could try in `C:\Program Files` or in `%APPDATA%`. The internal logs are usually not intended for non technical users (and sometimes not intended for humans at all), so it may be difficult to understand.
Comment: If the warnings appear even after reboot, then you probably are infected with a level 3 userland skiddy RAT. If the warnings do not persist after reboot, then someone may be exploiting you repeatedly using metasploit or any shell handler program and escalating to SYSTEM. In both cases you should be able to track down the originating process and kill it.
Answer: If the connection is originating from your computer, you should investigate why
Determining which process is attempting the connection
There are several tools in the [Sysinternals Suite] that can help you understand what program is making the connection. The TCPView program may show you the attempted connection, but as I understand it, it is basically just a GUI on netstat, so you might miss the connection.
The process monitor (ProcMon) tool will capture many different kinds of events concerning network connections, the file system and the registry (and much more). This page has details about how to use ProcMon to trace network connections to the responsible process.
Additionally, you can use the new sysmon tool. This page has some details on how to setup and use sysmon.
Once you determine the process that is sending the connection, you can use Process Explorer to submit the program to Virus Total. Virus Total will scan the sample across a few dozen AV products. A non-finding of a malicious signature doesn't necessarily mean it is benign, but its a good start. Launch procexp.exe as Administrator, locate the process via it's PID and right click to select "Check VirusTotal".
Determining what the process is trying to send
Using a program like wireshark, you may be able to determine what the program is trying to send. If McAfee is blocking the connection then, then nothing may be sent because connection is blocked. However, if you can determine what DNS entry is being used (if one is being used at all), then you can edit your hosts file to your local host. You can then set up a temporary webserver, (I like using python's python -m SimpleHTTPServer 80) to allow the connection to be established.
Follow Traditional Malware Investigatory Practices
If you can't track down the network connection, follow traditional approaches to determining if your computer is infected with malware. This post has many areas to investigate. Further, you can use tools like volatility to investigate your computers memory. Volatility can be especially helpful if a rootkit has been utilized to hide processes.

Risky Connection Blocked by McAfee


How to set up a Tor hidden service?

Question: Seeing that I find the technical side of it extremely interesting, I want to try to set up a Tor hidden service. For this I am following the Torproject instructions. I installed Tor, have it running, installed a LAMP server, and then edited the /etc/tor/torrc file with the following lines:
HiddenServiceDir /home/hubbtwea/hidden_service/
HiddenServicePort 80 127.0.0.1:80

Restarting tor (with sudo /etc/init.d/tor_restart) should then create the folder /home/hubbtwea/hidden_service/ with two files in it. Restarting goes fine:
 * Stopping tor daemon...               [ OK ]
 * Starting tor daemon...               [ OK ]

but afterwards, there is no folder created in my home dir. I then try to restart Tor again (with the same command) and then it says the following:
 * Stopping tor daemon...               [fail]
 * Starting tor daemon...               [ OK ]

It seems to be able to start, but not to stop (I wouldn't know why), and there is still no hidden_service folder created in my home folder.
Does anybody know what I could be doing wrong here?
Comment: Ah! Good tip! In there it said that permission was denied for creating the folder hidden_service. So I manually created it, chmodded it to 777 and chowned it to debian-tor. The last one did it. Thanks for the tip! (and I know, I'll chmod the dir to something more reasonable again).
Comment: What do the logs say?  (/var/log/tor/log)
Comment: Ah, no excuse me. Now it stops perfectly as well. Thanks! I just wrote an answer to my own question as well, but unfortunately I can only answer my own question after 8 hours (because I have less than 10 reputation). I'll do so tomorrow. Oh, and if the info on the tor prject would be a wiki I would have added this to that page as well.
Comment: Great, maybe you can write a nice answer for your own question?
Comment: Unfortunately I can't upvote comments yet, but otherwise I would have! If you just suggest it as an answer I'll gladly accept it.. :)
Comment: @weasel-PeterPalfrader - Oh, and one more question: do you know why it (still) fails to stop, even though starting is successful?
Comment: Still?  Previously it failed to stop because it wasn't running - the permission error made it shut down.  If it still fails to stop then something else is wrong.
Answer: Tor checks the ownership of several files and directories at startup. One of those directories is the HiddenServiceDir. This should belong to the user who started the Tor process. Otherwise you will get the warning:
Oct 06 12:34:56.000 [warn] /foo/bar is not owned by this user (johndoe, 1011)
    but by root (0). Perhaps you are running Tor as the wrong user?

It seems you are using Debian or some similar distribution. They use the system user debian-tor to run the Tor process. So you should make sure that the hidden service directory is owned by this user.
Apart from that I would not recommend to put the hidden service data inside your home directory. This data is often accidentally deleted, put into some cloud or misused otherwise. So you risk to give those data out of your hand. Debian puts  it by default into /var/lib/tor. This is often better than the home directory and also conform to the Filesystem Hierarchy Standard.
Answer: I just solved what I believe may be your problem as well.
Try leaving the 'HiddenServiceDir' alone or back to it's normal value which I believe is
HiddenServiceDir /var/lib/tor/hidden_service/

Restart Yor with these
sudo service tor stop
sudo service tor start

You won't have access to /var/lib/tor so to access the .onion address from /var/lib/tor/hidden_service/ you could use
sudo cat /var/lib/tor/hidden_service/hostname

Answer: Check in the logs (/var/log/tor/log) if your LAMP and/or Tor has access to create a folder for your hidden service. You can create it manually (that is the best in that case) and then chmod it to 777 an chown to debian-tor. That should solve all your problems !
(answer written based on comments)
Comment: -1 for any answer that suggests chmoding anything to 777.  And what has this to do with Apache, MySQL or PHP?
Comment: weasel, anyway, tor will chmod backward this 777 to 700.

How to set up a Tor hidden service?


How do I convert a grilling recipe to an oven/ broiling recipe?

Question: I found a recipe in a magazine that was for grilled pork butt. I live in New York City with no access to a grill. I Googled how to convert from grilling to oven/ broiling. I wound up with a very tasty burned butt.
Comment: What did you try? How did you change the recipe?
Comment: To tell you the truth it was so long ago I don't remember, it was the cooking time only I believe
Comment: I'd hate to be the person who tasted your burned butt.
Comment: Lol I am a member of Cooks Illustrated and I asked them how to convert the Rx. I was told to listen to their Radio show. I don't own a radio I have every other electrical "do-dad"but no radio so they said they would write it in the next edition of the magazine.  I have been waiting and waiting , it fan ally came and I snatched it from my husbands hand .......... No conversion. BIG SURPRISE☹
Answer: Since you mentioned a butt in your question, I'll start there. The way to get close to the crispy sear and smokey flavor you get from grilling is, surprisingly, to cook the butt at a very low temp (~200-225 F) until the internal temp. gets to about 135 F.
Before putting the roast in the oven, you want to massage a generous amount of olive oil all over the meat and season it to suit your tastes.
When the internal temp gets to ~135 F (count on 3-6 hours depending on the weight), remove the roast from the oven and tent foil over it. Heat your oven to its hottest temp (~500 F). When the oven is fully heated, uncover the butt and put it back in the oven until the internal temp reaches between 145 F (about medium) to 165 F (well done).
This method will give your meat a nice crunchy sear on the outside, while leaving it juicy and flavorful inside. The high temp at the end will also create some smoke and add to that grilled flavor.


Notepad++ stopped color-coding my source code... How to fix?

Question: For no apparent reason, it just stopped. No more color-coding. Is there a mystery setting I accidentally turned off?
Comment: It stopped completely, for every file? Or just for a certain file? Did it previously work with that file (under its current name)?
Answer: I had the same problem and discovered it was because I had enabled global foreground color under Global Styles.
Answer: Try out the following:

Select a language manually from the "Languages" menu.
In Settings/Preferences, check the File Associatons.
In worst case, reinstall.
Comment: This advise only true if you tried the accepted answer without success.
Answer: In the Language menu select your corresponding language. For example H and then html
Comment: That fixed it for me! The global settings wasn't the issue. Thanks Todd
Answer: The solution for me was to go into the Style Configurator, select the 'Global Styles' from the Language selection box and uncheck the 'Enable global foreground colour' option. I am not sure why that was checked, but all of the code coloring worked after unchecking it. Thanks Richard!
Answer: Have a look in Settings -> Style Configurator. Maybe your styles got messed up somehow. You could try changing the selected style to see if it makes a difference.
I think the saved styles are stored in the "themes" directory under your Notepad++ installation directory, so you could also check that the files have not become corrupted in some way.
Answer: I had the same problem (I Googled "notepad++ file coloring quit" to find this discussion.) In my case the coloring quit mid file in a single file. I finally realized that adjacent string literals with one of them a macro was fooling Notepad++.
My code that broke it read:
    Write_Supplemental_Configuration(privateData->new_config, FTP_ROOT_DIR"/lists.csv");
and the fix was to add a space after the macro:
    Write_Supplemental_Configuration(privateData->new_config, FTP_ROOT_DIR "/lists.csv");
I tried replacing the macro FTP_ROOT_DIR with "foo" and the problem went away.
So in my case it was a macro that fooled the Notepad++ coloring.
Comment: This has happened to me quite often while editing extremely large files or when scrolling rapidly through files.  It seems that the highlighting doesn't keep up at times.
Answer: watch out for the single quote that you copy from the web. if you get one of those "upper commas" instead of the tic mark it will confuse the code and kill the coloring (in SQL).  just delete and replace.
Answer: Make sure that when you save the file it's saved as an .html instead of a .txt. This make a difference because the .html allows you to see the different colour codes whereas .txt doesn't.
Answer:
Check, if you have saved the documents as .HTML and not as .txt
in the menu, choose Settings>Style configurator...
and in the list in the left pan select html, check if the colors for different tags are being shown in the color blocks. if yes, chosse a font and then save and exit.
Check only after you save the document in .html, whether it is working or not.
Comment: This answer is very similar to some of the older answers. When answering an old question you need to add significant extra information, just writing the same as an existing answer is not helpful. Such answers are likely to be poorly received.
Answer: The language setting solved the issue for (all) 3 Javascript files (.js) which suffered from it, which previously were all recognized correctly as Javascript. For some reason it forgot they were Javascript files apparently!?
Answer: First type any thing and Save the file in any format you are working with (i-e; .cpp if c++, .js if JavaScript....etc)
And make sure global foreground color is disabled.
And it should work fine.
Answer: File > Save As > Format Type = Structured Query Language > Name the file with '*.sql'. THIS SHOULD BRING ALL THE COLOR CODES.....to differentiate your code and make it look pretty. J
Answer: If you want to display text in SQL format, then in menu select Language => S => SQL
Comment: Welcome to SO, this does not provide an answer to the question
Answer: I just had the same thing happen to me. The only way I could fix it was to rename the file (I just added one character). Then open it with notepad++. The code was colored again. Then renamed the file back to the original name and it is still colored.
I have since found that if I close Notepad++ without closing the file first this happens. Try closing the file first then close Notepad++ then reopen the file.
This bug seems to be fixed as of version 7.8.6
Answer: Got to Setting -> Style Configuration and remove the global style checkbox
Comment: The instructions are correct, but your picture shows something different: it shows Settings -> Preferences instead of Settings -> Style Configurator.
Answer: If the coloring only stopped working for one file, you should check the extension name of your file.  You might have accidentally saved the file as .txt
Answer: A couple years late here, but I'm pretty sure you're opening ".txt" files that contain your source code. Because the file doesn't have the language's extension, Notepad++ can't determine how to color-code it. You'll have to select the language under the "Language" tab.


DFSR File Filters on Server 2008 R2

Question: I've got a serverfarm which utilizes DFSR for file and folder replication.  I'm familiar with File and Folder Filters on the replicated folders for the group.  I'm curious if these can be set per server?  I basically need to exclude robots.txt to and from 1 server but I need it to replicate through the rest of the members.
Answer: No this is not possible. The files in the RF are replicated to all members.

DFSR File Filters on Server 2008 R2


Stolen coins and hacked wallets

Question: How do I track down the owner of an address that stole my wallet. I have the address need to follow up. My coins show up in their wallet.
Answer: You almost certainly can not.
Only if you're lucky and the thief is not very smart - he could be in the same country, and use a local exchange to get fiat currency. Then, maybe, the police could help (they have enough power to ask an exchange to reveal the account owner).
But this someone could just go to any exchange, replace stolen coins to any crypto (few times) transfer those into any other wallet - and you lose track of it forever.
Sorry to bring you bad news. I hope you didn't lose much.
Answer: I've used Etherscan to see the account:
https://etherscan.io/address/0x7C887feBc897C5D1bc67fE80BFd5B3fc05F8440f
Then I added the said account to Tenderly.co (wallet monitor):

My plan is to monitor the wallet with some service, get notification of movement to an exchange and warn the exchange, but most probably everything has been emptied and moved so fast that it will be gone
Answer: This is great tool for following stolen assets. It also supports multiple netwroks.
https://metasleuth.io/

Stolen coins and hacked wallets


Does moving a grappled opponent while mounted reduce your mount's speed?

Question: When you move a grappled opponent, your speed is halved.
However, while mounted, your mount is moving you.
Is your mount's speed halved when you move a grappled opponent ?
Answer: It would reduce only the grappling character's speed, as the other answers explain it, but when taking it strictly RAW you can only use the grappling creatures movement to move the grappled creature: (emphasis mine)

Moving a Grappled Creature. When you move, you can drag or carry the grappled creature with you, but your speed is halved, unless the creature is two or more sizes smaller than you.

Basically, your steeds movement would end the grappled condition, because it would remove the grappled creature out of the grapplers reach.

The condition also ends if an effect removes the grappled creature from the reach of the grappler or grappling effect, such as when a creature is hurled away by the thunderwave spell.
Comment: This might require a separate question : can you maintain a grapple while on a moving mount ?
Comment: See my answer..but this all hinges on can you mount a mount and grapple.  Though, I think your condition ending event example is more for something else causing movement, not you...but good point though
Comment: Asked the question [here](https://rpg.stackexchange.com/questions/110778/can-you-maintain-a-grapple-while-on-a-moving-mount).
Answer: The mount's speed is unaffected, unless the weight of the rider and the grappled creature together exceed its carrying capacity (which is unlikely).  The main effect is that since mounting and dismounting use half the rider's movement, and the rider's movement is halved when moving a grappled creature, then if the rider wishes to mount or dismount the steed while maintaining the grapple, that will consume his entire movement.
Answer: No
If a character is moving a grappled opponent, that character's speed is halved.
Even while mounted though the speed of the character and mount are independent.
Assuming a controlled mount, it just means that the character can direct the mount to act using the mount's actions/speed.

It moves as you direct it, and it has only three action options: Dash, Disengage, and Dodge. A controlled mount can move and act even on the turn that you mount it.

And seeing that mounting a steed while grappling (although very difficult to imagine and probably harder to execute in game) does not in any way mean the steed is now grappling the opponent instead.
Thus, the mount's steed would remain unchanged.
Answer: Actually this begs the question of, "Can you maintain a grapple and mount your mount?".   Nowhere in RAW, does it say that is possible...but, if I were a DM, I might rule this as possible -- maybe subject to a skill/ability check.
E.g. Something like: Roll to see if you can maintain the grapple this round (If "yes", then continue with the action sequence; if "no", the grapple is lost as per normal rules) and then Roll to see if you can mount your mount (If "yes", then you're mounted; if "no", then you can't mount this round.)
Or, maybe reverse the checks, depending on whether you might want to penalize a PC for failing to mount. (I.e. Because you failed to mount, you suffer a penalty to maintaining your grapple attempt)
Now, if we assume that that basic question is, "Yes", then I would probably say the mount would slowed to half speed -- so, that you could maintain the grapple.
While, the other answers seem to think that this wouldn't be the case (slowing your mount), and the movement that's slowed is yours,  I would humbly beg to disagree.  I would think that the total movement being used should be slowed down -- whether that's yours (unmounted) or the mounts (mounted) -- plus, if any encumbrance limitations apply, add these too.  The "in game" rational being, this speed loss is to allow you to maintain the grapple.


Accessing files on Linux container from host sans root

Question: I have a container from systemd-nspawn. The folder for the container /var/lib/machines/our-runner is owned by vu-our-runner-0:vg-our-runner-0. I am trying to serve files within it from the hosts apache2 instance, however, I cannot do usermod -aG vg-our-runner-0 www-data, as it says that vg-our-runner-0 does not exist, despite ls -ld saying otherwise. How would I give apache access to this short of running it as root (as root has access to the folders within the container)? The host is Debian, the container is Arch.
Answer:
it says that vg-our-runner-0 does not exist, despite ls -ld saying otherwise

Well, those aren't the same thing. It is true that the group doesn't "exist" in /etc/group where usermod looks – it's a virtual group defined by systemd-machined. It is also true that the group "exists" when the getgrnam() or getgrid() functions are called by ls – because they collect information from more places than just /etc/group.
The /etc/passwd and /etc/group files are not only source of passwd & group information on Linux. When a program like ls -l tries to look up a group name or GID, multiple nsswitch modules can supply this information. (They're all listed in /etc/nsswitch.conf, and the 'libnss_files' module is what actually reads /etc/group.)
In particular, ls -l also asks the 'libnss_mymachines' module which is installed by systemd and provides information on the fly about currently running containers. It's also why the group suddenly stops being recognized when the container is stopped. (It's also why all vu-/vg- names stop being recognized whenever systemd-machined exits on idle...)
Fortunately, nsswitch has a special case for groups where it supports merging membership results from several modules; if you manually add this group to /etc/group, making sure to preserve its GID, then you will be able to add members to it.
So you could look up the GID using ls -ldn (e.g. 1164378112 in this case) and add a new line to /etc/group like this:
echo "vg-our-runner-0:x:1164378112:www-data" >> /etc/group

Now tools like id www-data or groups www-data (which collect group memberships through nsswitch) will report the new GID. It doesn't matter to the kernel where the group was defined – a GID is a GID.
Comment: You're not allowed to descend into the /var/lib/machines directory because you don't have the `x` permission on it. At this point, deeper permissions aren't even checked yet.
Comment: ThanksI I've been able to add my own account and www-data to the group with your answer, however, I still cannot access its directory. Running `namei -l /var/lib/machines/our-runner/` results [in the following.](https://gist.github.com/Orangian/f33e8efcdce71c9d379920052c08fb9d) So it seems like even though I am part of the vg-our-runner-0 group, I still strangely do not have access.
Comment: It also seems like both vu-our-runner-0 and vg-our-runner-0 have the same id of 73007104. Trying su vu-our-runner-0 as root also gives me an authentication error strangely enough.
Comment: Whoops! Thanks for your help! I'm kinda new to unix, so I don't have a clue what most attributes do. Resolved.


how to handle photography permission in a conference?

Question: I am a photographer. We have around 30 people who do not allow us to take a photo of them during an institute for 4 weeks. Around 600 will attend and apparently it is not easy to follow the permission.How can I handle this situation?
Please help me.
Thanks for your advice in advance.
Comment: Color code their name tags?
Comment: they don't want their photos taken or not published ?
Comment: @EricShain Please post an expanded version of that comment as an answer!
Comment: I think Eric's suggestion is really good.
Answer: I'd have expected the organizers to have permission to photograph and video from all the attendees, typically done as part of the terms and conditions of agreeing to attend.
I'd suggest contacting the organizers and finding out what arrangements and terms and conditions are in place.  You should probably ask them to seek cooperation from the attendees.
If it's a minority that refuse to cooperate, I'd use the suggestion by @eric-shain and color code the name tags (of those who object).  I wouldn't be surprised if they'd object to be color coded as well, but at least ask the organizers. :-)
It's unusual to have people at conferences refuse to be photographed (or videoed).  This is especially pointless now that everyone and his mother has a phone that can do video and still and those people rarely ask permission to do so (or use the material later).
Answer: Ask them to take a photo of them with their name to be able to remove the photos after the conference is done.
Have a release paper explaining what and how you will do it.
You will have a list of private photos of people that you know you can remove (or blur out) from your global photo pool.
Answer: Carry with you a supply of cheap self-stick neon-colored dots (3/4 to 1" diameter, typically sold at office supply stores or hardware stores to price items at garage sales). If someone doesn't want their photo taken at the conference, give them a neon dot to stick on their name tag or near their face (on their chest or shoulder) so you can blur them out.


Is amrita or legend of samudra manthan mentioned in Vedic scriptures?

Question: The legend of samudra manthan and amrita is mentioned in itihasa, puranas but the legend of samudra manthan mentioned in verses of vedas, Upanishads or brahmanas or is the drink of immortality amrita atleast mentioned in these Vedic scriptures that is vedas, Upanishads or brahmanas?
Answer: I could not find refernces of samudra manthan in vedas but I found refernces of amrita-

for,wealthy waters,ye control all treasures:ye bring auspicious intellect and amrta ye are the queens of independent riches sarasvati give full life to the singer!(Rig veda book 10 hymn 30 verse 12).
Now,ye sapient ones,make ye the axes sharp wherewith ye fashion bowls to hold the amrta.Knowing the secret places make ye ready that whereby the gods have gotten immortality(Rig Veda book 10 hymn 53 verse 10)


One community or More than One Commmunity

Question: We want to create a partner community to allow the partner to access and view cases and reports. However, the boarder expects that when the partner user access the community, he will see the logo of his company instead of our. We have a lot of partners, is this possible through visualforce? Or should we create one community for each partner? Or better to create a website intetgrated with salesforce to allow partner to access and see the reports related to cases and the cases recordo to view/edit?
Comment: I'm not an expert on communities but it should be possible with one community. When you reference "partners" in your question I think, in salesforce speak, you mean accounts. And yes when you create the community I believe a user is created as a contact within an account. So when that user logs in they have access to only related information... I maybe wrong so let's hope someone else replied...I would recommend trying it out in a developer org if you don't have a license or a sandbox if you do.
Comment: @n34_panda  , thank you for your reply. Yes, with sharing rules, I can make accessible only the records that user is the owner or bases in some criteria. However, I would like to know if it's possible to create visualforce pages in the partner community, once the stakeholder expects that when the partner access the partner community, he will see the logo of his company, not only of our company. Do you knkow if I can use visualforce page in the partner community?
Answer: From the Help:

Maximum Number of Communities Limit
You can have up to 100 communities in your Salesforce org. Active, inactive, and preview communities, including Force.com sites, count against this limit.
To see this limit in your org, from Setup enter Communities in the Quick Find box, then select All Communities. The Maximum number of communities field displays 100.

In essence, you only want to have one community, not one for each of your "partners".
From your description, it doesn't sound to me as though you need a "Partner Community" since you only want to view cases and reports. There are many other less expensive licenses that can do what you want. See Communities User Licenses for a comparison.
As for branding, if your users are all registered users, you can do what you've described using a solution which serves content that's dependent on the user.accountId property. This can be done via a variety of means the most common of which would be custom CSS but could also be formula based as well using a "Content Management Solution" as with normal web site design (beyond the scope of this forum).
Comment: is possible to edit cases through the css page for instance? I agree with you and I also through about a website (portal) instead of a community.
Comment: I'm not certain I follow your question. You could customize the CSS that applies to the Cases page and have that display custom content that's in the context of the current user. I hope that answers your question. I don't believe you'd be able to access Cases other than to submit one through a website. Look into Salesforce Sites for more on what you could do if you wanted to go that direction.


Is "swap" the right word for moving files?

Question: I want to describe moving a list of files to another department. What word would be appropriate to use here? Currently I'm using "swap". Please let me know if that's suitable and suggest alternatives.
Comment: It depends on the situation. How are you moving the files? digitally? physically?
Comment: digitally. A file with list of accounts to be moved from one department to another .
Comment: What do you mean by "department" if you're talking digitally?
Answer: Thanks for the clarification.
Moving things digital may use the word like - transferring, proceeding from here to there or simply as we all know - moving! Among these, I'd use transfer as the system itself might say transfer complete!
Swap won't fit here. It means exchange and I don't think that's the case here (or at least in the scenario you mentioned).

swap (v) - to give something to somebody and receive something in exchange
Comment: Thanks for your answer . could i use "shift" here ?
Comment: @sankrish you can but then I prefer 'transfer' that has no ambiguity. That's the jargon we use when we transfer files from one place to another, don't we? In fact, the system itself says **transfer complete.**
Comment: But i guess i should stress the accounts inside the file.So its not similar to file transfer alone
Comment: I think it won't affect much. We are giving the name to the *process* and not the location! Whether it's within the setup or outside, if the files are moving from one place to another place, I'd prefer *transfer* and then further clarify from where to where. *shift* is also the word but with more ambiguity.


Projecting 3D Points to 2D Points

Question: I know this is a common question and there are oodles of resources on the web and several questions here handling this area but I can't find exactly what I need.  So, with apologies in advance, here goes:
I have a 3D point that needs to be converted to a 2D point
I have available:
Point location (Px,Py,Pz)
Camera location (Cx,Cy,Cz)
Camera orientation (I can control this but I don't know how to represent it)
I was trying to follow the wikipedia guide on this - http://en.wikipedia.org/wiki/3D_projection#Perspective_projection
My questions are:
How should I be representing the camera orientation?
How do I calculate the values of Ex,Ey,Ez from the wikipedia guide, the "viewer's position relative to the display surface"
Is there anything else I should know?
Answer: Old tutorials are great, mostly from the days before T&L and shaders, even before hardware rendering. Start with an understanding of them, i.e. /technical/math-and-physics/3d-matrix-math-demystified-r695">http://www.gamedev.net/page/resources//technical/math-and-physics/3d-matrix-math-demystified-r695 . Then go on to application for a camera: http://www.codeguru.com/cpp/misc/misc/graphics/article.php/c10123/Deriving-Projection-Matrices.htm
Basically, you translate and then rotate the entire 'universe' around the camera. So you have your point: you define a translation (movement) for the camera, then a rotation matrix. You apply them to any 'world content,' i.e. your point. You can then "cheat" and simply divide the x and y values by z to project to the 2d plane, but you should really do calculations that correct for field-of-view properly.
Comment: That first link seems to be broken, getting a 404
Comment: It won't work in answer body. http://www.gamedev.net/page/resources/_/technical/math-and-physics/3d-matrix-math-demystified-r695
Answer: If you compile Opencv with Java bindings you can do this easily using the the [Calib3d module](http://docs.opencv.org/java/2.4.4/org/opencv/calib3d/Calib3d.html#projectPoints(org.opencv.core.MatOfPoint3f, org.opencv.core.Mat, org.opencv.core.Mat, org.opencv.core.Mat, org.opencv.core.MatOfDouble, org.opencv.core.MatOfPoint2f))

Projecting 3D Points to 2D Points


Would a submarine float in the atmosphere of Jupiter?

Question: Would a submarine float in the atmosphere of Jupiter, or would it get crushed?
Comment: Even more interesting, the "Operating depth" which is typically limited by the pressure at which the submarine will be crushed, may or may not be the same as the depth at which it would float, which is governed by the density of the surrounding gas. In the ocean the water density is roughly constant, and pressure increases with depth. On Jupiter, at least where the atmosphere is gaseous, both pressure and density vary with depth. Hat I more time, I'd love to work out an answer to this question. Maybe later. +1
Comment: I think the question is, "*Where* in the atmosphere of Jupiter would a submarine's operating depth be?"
Comment: It would be nice if you could update the question according to suggestions in comments; use "edit" link.
Comment: Jupiters atmosphere is predominantly H2 and He, isn't it? Is a temperature profile known?
Answer: As the comments above indicate, factors like density, pressure and temperature are important for a Jupiter submariner. Of course nobody yet has the exact details of Jupiter's interior structure, but there's a diagram in this LASP page[WebCite archived version] that indicates the following:                                                                       At the intersection of Jupiter's liquid hydrogen/metallic hydrogen layer, the density is about $1\text{ g}/\text{cm}^3$, which would permit the submarine to float. However, the temperature there is $\sim5000\text{ K}$, and the pressure is $\sim2 \times 10^6\text{ bar}$, so it can't be done with normal equipment.
Answer: Short answer: It would get crushed.
Long answer: See today's "What If" on http://what-if.xkcd.com/138/
Comment: Welcome to Physics! This post could be better if you summarized Randall's argument moreso than the "it would get crushed" you've given. This is otherwise a link-only answer that [are generally not well-received here](http://meta.stackexchange.com/a/8259/230312).
Comment: Wow, my question has reached Randall!


IID sequence and stopping time

Question: Let $X_0=0, X_1, X_2,\dots, X_N$ be i.i.d. random variables, with Gaussian distribution $\cal N (0,1)$.
For $k=0,\dots, N, S_k=\sum_{i=1}^k X_i$ and $\tau=\min\{k:S_k^2\geq N-k\}$. So $\tau$ is
a stopping time, while $\tau-1$ may not be one. My question is:
$E[X_{\tau}]=0?\ E[X_{\tau}^2]=?$ Thanks for any hints, discussion and help.
Answer: Intuitively, in the joint pdf given any event where $X_\tau > 0$, there is a symmetric situation with $X_\tau < 0$ by flipping the sign of all the $X_i$ .
By symmetry of the pdf, Integrating gets you zero.
I'm sure there's a optional stopping theorem lurking somewhere though I guess you are trying already--- http://en.m.wikipedia.org/wiki/Optional_stopping_theorem
Candidate martingales are $S_k$ and $S_k^2-k $ .

IID sequence and stopping time