text:
## Mission Objectives

The SOC-i mission will carry an advanced guidance, navigation and control (GNC) payload capable of reorienting the spacecraft while satisfying multiple pointing constraints. SOC-i will also carry an Earth imaging camera, enabling it to take pictures of specified ground locations.

The mission will operate in space for 6 months, and will be supported by a UW ground station being developed in the Aerospace Engineering Research Building. It is a stated goal of the mission to be completely open-source, maintain code on our team's GitHub page .

The experimental GNC system is capable of reorienting the spacecraft while guaranteeing hard pointing constraints and minimizing the change in angular momentum stored in a set of three reaction wheels. In the figure below, the green cone represents a navigation sensor's field of view, while the red cone represents the camera's field of view. Reorientation maneuvers must be executed such that (i) the sun vector $\boldmath{s}_{\mathcal{B}}$ remains inside the green cone, (ii) the sun vector simultaneously remains outside the red cone and (iii) actuator and slew-rate limits are not violated. The satellite must compute these solutions on-board without any pre-loaded solutions or ground intervention.

The payload leverages previous work done at the UW in this area. In particular, we adapt methods from (Kim et al, 2010) and (Lee and Mesbahi, 2013) to formulate the problem. Solutions are obtained in real-time using the ECOS solver running on the main flight computer. Our implementation is an on-going process, but will use elements of optimal control theory or Successive Convexification .

### Software

See the open source GNC code based in Matlab/Simulink.


text:
# Chemistry question. Which of the following statements are true?

## $C {a}^{+} \left(g\right)$ + ${e}^{-}$ $\to C a$(g) i.) The energy change for this process is the negative of the first ionization energy of the $C {a}^{+}$ ion. ii). The energy change for this process is the negative of the first ionization energy of the Ca atom. iii). The energy change for this process is the negative of the electron affinity of the Ca atom.

##### 1 Answer
Nov 19, 2017

The third answer is true.

#### Explanation:

The first two statements reference the ionization energy, which is the energy required to REMOVE an electron.

On the other hand, electron affinity is the energy either released/absorbed when an atom GAINS an electron.

We can see from the chemical equation that an electron is being added, thus it is the electron affinity.

format: plain


text:
# Running Maven Tests in Jenkins

A few notes on executing Maven + TestNG tests in Jenkins.

### Running tests

Use the following Maven commands in Jenkins when executing tests.

In pom.xml, the test suite file should be specified, such as testng.xml. To run a custom TestNG test suite file, use the following command:

To run a specific TestNG class, use the following command:

Note that the symbol # must be used between class name and method name. In other words, -Dtest=TestCircle.test_area will not work.

### Configuring tests

Sometimes, your tests need to access resources outside of standard Eclipse/Maven project folders. For the tests to pass both locally and on Jenkins, the full path to the current workspace may be required to resolve the file path to those resources in tests. Jenkins set a number of environment variables, including the variable WORKSPACE as the absolute path of the workspace.

For local environment, we need to set environment variable WORKSPACE to simulate Jenkins environment. In the tests, we need to retrieve this environment variable, as follows in Java:

Besides workspace’s absolute path, we might also need to configure some constants in tests from a configuration file. When initializing constants from properties files in Maven, remember:

• Use this.class.getResourceAsStream() method.
• By Maven convention, properties file should be in src/main/resources folder.
• Default property values could be used when reading properties file.

Note that the location of the properties file in the example above is src/main/resources/config.properties.


text:
# Paxos on Steroids and a Crash Course in TLA+

@rystsov recently posted an interesting article in which he describes a peculiar generalization of Single-Decree Paxos that could, in some situations, replace Multi-Paxos. I was skeptical: this looked really useful; why wasn’t everyone aware of it already?

I still don’t know the answer to that question, but I’ve since failed at constructing a counter-example, and find that the algorithm looks “correct” (more on what that means later).

That’s exciting! Today, embark with me on what will hopefully become a series of posts on what (at least here) will be called Compare-And-Swap Paxos (CAS-Paxos), and how to explore its properties through formal specification.

A reasonable first step is a tutorial-style formal description of the algorithm in TLA+, which among other things is also a model checker which allows you to specify the algorithm and explore concrete histories it permits.

This then, is the plan for today:

## Review: Linearizability

We are talking about registers today (i.e. an abstract system that, no matter the implementation, exposes and operates on a single value), so for the purpose of making everything hands-on, imagine your system to be a distributed key-value store with only a single active key (perhaps CockroachDB or one using the algorithm described later), and that you have multiple clients running compare-and-swaps on that key.

Linearizability of that system (i.e. all the clients writing to that key) holds if no matter how things interleave, for each operation in any possible history, you can find an instant at which it (and only it) applied atomically, and that instant is between the moment in time at which the respective command was initiated (i.e. a request dispatched by a client) and acknowledged (i.e. a response received by the client).

For example, if the register is initially foo, and at

• time=10: I dispatch CAS(bar, baz)
• time=15: You dispatch CAS(foo, bar)
• time=20: I receive OK from the system
• time=30: You receive OK from the system

then that history is linearizable: my CAS succeeded, so your operation must have applied to the system before mine; otherwise the register wouldn’t have had the value bar I’d assumed I’d seen. And that is well possible because you initiated your CAS before the system told me mine had applied, and so we can arrange them atomically in a history for the system:

• time=10: I dispatch CAS(bar, baz)
• time=15: You dispatch CAS(foo, bar)
• time=16: Server executes your CAS(foo, bar)
• time=17: Server executes my CAS(bar, baz)
• time=20: I receive OK from the system
• time=30: You receive OK from the system

Kyle Kingsbury (aphyr) does a much better job describing this, so you should go there unless you’re already comfortable with the concept.

## Review: Single-Decree Paxos

Single-Decree Paxos is a consensus algorithm that lets a number of so-called acceptors agree on a single value (out of many that may be offered to them) and preserve that value for eternity, unless a quorum of acceptors holding on to a copy of the value perish, never to be seen again.

To clients, the abstraction provided is a linearizable register that can be written exactly once and, once written, exposes the same value forever.

There are good resources for learning about Paxos here (slides with examples!) and here (words only), so we only review it briefly. You absolutely want to make sure that you understand simple Paxos well before you continue.

Paxos is organized around ballot (or proposal) numbers, and the goal is generally to get successful responses from a majority of the acceptors. Clients (“proposers”) which want to propose a (or learn the, if any) value pick a unique proposal number (in practice, one that they think might actually succeed) and try to take it first through a PREPARE phase and, if a majority of acceptors indicates success, an ACCEPT phase.

At the end of a successful PREPARE phase, the proposer has learned from a majority of the acceptors

• that they promise to not service any smaller ballots than the proposer’s, and
• whether there is already a value (not necessarily committed) which must be picked up or whether the proposer gets to choose one.

If any values are returned from PREPARE, the proposer must use the value corresponding to the highest ballot (and there are never two values for any ballot).

The proposer can then proceed to the ACCEPT phase, in which it tries to store the chosen value on all acceptors (but needs only a quorum); an acceptor will refuse values for a ballot that it has promised not to service any more.

Unsuccessful proposals are usually caused by network issues, the proposer crashing half-way through, or (most interestingly) multiple proposals overlapping concurrently. But, no matter the interleaving, after the first successful ACCEPT phase, the value is set in stone (barring failure of a majority of acceptors) and all successful proposals will result in the same value - a register backed by Single Decree Paxos is linearizable.

## Verbal Description of CAS-Paxos

CAS-Paxos is derived from Single Decree Paxos with just one small but impactful change: After the PREPARE phase, the proposer is allowed to pick a new value (perhaps taking into account the value, if any, learned from the PREPARE phase).

For the purposes of this discussion, we’ll settle on that all proposers want to run compare-and-swaps: if the value they learn is the one they expect, they go ahead and try to get a new value accepted. To simply read the value, you run an instance of Single-Decree Paxos instead.

It’s not clear at this point of the posting, but the resulting algorithm actually seems to make basic sense (as in, it provides guarantees which are useful), though we’ll discover a few caveats. And, though we won’t even get close to proving it today (and I haven’t proved it), the semantics of the register, once suitably defined, should be linearizable!

For now, the bird-eye view: whereas before we were stuck with a write-once register, now we seem to have something on our hands that can change value as often as we’d like, and perhaps could serve as the building block of a key-value store.

Let’s discuss the concrete behavior of the algorithm later and do some TLA+ first.

## Specifying CAS-Paxos in TLA+

Don’t care about writing the spec? Jump straight into the analysis.

Don’t try to copy-paste from these examples; they’ve been formatted to fit the screen. Instead, to follow along, head on over to the caspaxos-tla repo; the initial commits on the master branch track this post.

A TLA specification starts with a list of module imports. We’ll deal with integers and will want to talk about the cardinality of sets, so we import

EXTENDS Integers, FiniteSets

From what I can tell, in practice you use whichever operators you find on the internet and when it fails, realize that there is something you needed to import, which you then add.

### Constants, Basic Definitions, and Assertions

When you specify a model, you leave certain parts configurable so that you can invoke the model checker with various settings.

For CAS-Paxos, we have a set of possible values the register can take, a set of oblique acceptors for which we really only care about how many they are, and a mutator which maps a ballot number and a value to a new value.

CONSTANT Values, Acceptors, Mutator(_, _)

Throughout this whole exercise, keep in mind that the state space which needs to be explored by the model checker exponentially spirals out of control. For example, you certainly can’t hope to check all possible histories when the register can hold 100 different values (in fact, 10 is probably out of reach already); I’m using 4 throughout this example simply because that finishes in 15 seconds on my machine. Note also that we don’t restrict the ballot numbers just yet; that’s achieved later, by overriding the definition of the natural numbers while checking the model.

Mutator is a good approximation of how compare-and-swap’ping proposers would choose the new values (Single-Decree Paxos corresponds to Mutator(ballot, foundValue) = foundValue), abstracting away nondeterminism by using the ballot number to decide on the new value. You could let the model checker generate “real” CAS operations as well, but let’s agree that this is interesting enough, and that it’s easy enough to extend this later.

Now, we define the set of all quorums. The crucial property that we need is that any two quorums intersect nontrivially, and the ASSUME command lets the model checker verify that it holds in the concrete instances we run it for.

Since we’re lazy, we use the set of all majorities of acceptors as the set of quorums. This is what you usually see in practice because it maximizes the number of acceptors you can afford to lose.

Quorums == {
S \in SUBSET(Acceptors) :
Cardinality(S) > Cardinality(Acceptors \ S) }

ASSUME QuorumAssumption == /\ \A Q \in Quorums : Q \subseteq Acceptors
/\ \A Q1, Q2 \in Quorums : Q1 \cap Q2 # {}

What this does is express that

• Quorums is the set of those sets of acceptors for which more acceptors are in the set than not. That’s just a fancy way of collecting all subsets containing more than half of everyone.
• QuorumAssumption has to be true or the model checker aborts. It is satisfied if:
• all the quorums we declared actually consist of acceptors (something that you probably implicitly assumed anyway), and
• any two sets of quorums have nonempty intersection.

On to ballot numbers, for which we define

Ballot == Nat

This just means that we define a set Ballots which equals the natural numbers 0, 1, …. As mentioned earlier, when we run the model, we’re going to override Nat by some finite subset, typically restricting it to 1, 2, 3 - that’s tiny, but enough to find an interesting history without waiting.

### Messages

Now we define the set of all possible messages. In this specification, proposers are implicit. Messages originating from them are created “out of thin air” and not addressed to a specific acceptor. In practice they would be, though note that each acceptor would receive the same “message body”, and omitting the explicit originator and recipient reduces the state space. Note also that messages are not explicitly rejected but simply not reacted to. In particular, the implicit proposer has no notion of which ballot to try next. The spec lets them try arbitrary ballots instead. Bad for the state space, but good for generality.

A message is either a prepare request for a ballot, a prepare response, an accept request for a ballot with a new value, or an accept response.

Message ==      [type : {"prepare-req"}, bal : Ballot]
\cup [
type : {"prepare-rsp"}, acc : Acceptors,
\* ballot for which promise is given
promised : Ballot,
\* ballot at which val was accepted
accepted : Ballot,
val : Values
]
\cup [type : {"accept-req"}, bal : Ballot, newVal : Values]
\cup [type : {"accept-rsp"}, acc : Acceptors,
accepted : Ballot ]

Above, \cup is the union of two sets, {"prepare-req"} is a set containing as its only element the string prepare-req, and [ x : X, y : Y ] is the set of all records (TLAs version of associative arrays) with only keys x and y set and their values elements of X, Y, respectively.

### State of the Model

Since we are modelling only the acceptors and messages, the state of the mode is only the set of messages in existence, and whatever local state each acceptor stores:

VARIABLE prepared,
accepted,
value
VARIABLE msgs

The tuple <<prepared[a], accepted[a], value[a]>> will be the state that would be kept on acceptor a in a real-world implementation of the spec.

The above says awefully little about what these variables are actually like in practice, so we add a formula which we later instruct the model checker to verify in each state, namely that prepared and accepted map acceptors to ballot numbers, value maps acceptors to values, and that any message sent is an element of the above set of “legal” messages.

TypeOK == /\ prepared \in [ Acceptors -> Ballot ]
/\ accepted \in [ Acceptors -> Ballot ]
/\ value \in    [ Acceptors -> Values ]
/\ msgs \subseteq Message

How does one “send” a message, then? Like this:

Send(m) == msgs' = msgs \cup {m}

TLA models the “next state” with primed variables, so to satisfy the formula Send(m), the next state’s incarnation of msgs must contain m.

We won’t ever remove messages from msgs. By modelling msgs as a set that never shrinks, we model that messages may be received multiple times, and that they can freely reorder. Desirable properties to model because even though TCP/IP connections don’t allow reordering, sometimes we need to reconnect and no such property holds across connections!

Now, finally, things get interesting and we get to specify the initial state of the model:

Init == /\ prepared = [ a \in Acceptors |-> 0 ]
/\ accepted = [ a \in Acceptors |-> 0 ]
/\ value    = [ a \in Acceptors |-> InitialValue ]
/\ msgs = {}

Ok, maybe not too interesting. Note however that the initial state has an initial committed value, ie the register doesn’t start “empty”. This is an inconsequential simplification.

### Stub Actions

Before we write down the actions that drive the algorithm (i.e. sending and reacting to messages), we want to finish up the scaffolding. We define mock actions (actions are just formulas which contain primed variables, meaning that to satisfy them you must mutate the state):

PrepareReq(b) == FALSE
PrepareRsp(a) == FALSE
AcceptReq(b, v) == FALSE
AcceptRsp(a) == FALSE

### The Main Formula

Now, finally, we reach the centerpiece of the whole operation: The Next formula, traditionally named such because it is this formula that we’ll instruct the model checker to satisfy by deriving new reachable states.

Next == \/ \E b \in Ballot : \/ PrepareReq(b)
\/ \E v \in Values : AcceptReq(b, v)
\/ \E a \in Acceptors : PrepareRsp(a) \/ AcceptRsp(a)

Read: Satisfy Next by either satisfying PrepareReq for some ballot, or AcceptReq for some ballot and value, or by finding an acceptor for which PrepareRsp or AcceptRsp can be satisfied.

Next is just a name without formal meaning, but Spec is the default entry point for the TLA+ model checker. The below formula is a temporal formula and means that the valid behaviors of the specification are those which initially satisfy Init, and from each step to the following the formula Next is satisfied, or all the variables stay the same (“stuttering step”).

Spec == Init /\ [][Next]_<<prepared, accepted, value, msgs>>

Now hopefully it is at least somewhat clear how the model checker works: it constructs all states that satisfy Init (there could be many, though here there’s just one), and until it runs out of new states explores all state transitions that satisfy Next. Phew! You can imagine how quickly the state space blows up as you increase the size of the parameters, and hopefully it’s also clear that any infinite set is likely going to lead to an infinite state space!

### Running the Model Checker

As a last deed in this section, we give the model checker something to actually check (as of now, it would construct all behaviors, but not check anything about them). Since we’re not ready to check anything meaningful, we just assert TypeOK; we’ll add something else later.

DesiredProperties == TypeOK

There’s no real point, but now you can try out the model. If you clone the repo and check out the right commit, you’ll find a prepared model along with the TLA file we’ve assembled so far.

Open the model using the TLA toolbox (File -> Open Spec -> Add New Spec), and note how we declared Acceptors as a set of three “model values”; a model value is a value that’s completely opaque to the model checker, and not equal to any other value. We also have Values = {0, 1, 2, 3}, and Mutator(b, v) is set to (1

• b*v) % 4 (an arbitrary choice).

Furthermore, there is a “Definition Override” that sets Nat to 0..3 and we have added DesiredProperties under Invariants so that it will be checked for every state reachable in this model.

Now, click “Run”… oops, immediately errors out: “Deadlock reached”. This happens because we stubbed out the actions and so from the initial state, there is no way to satisfy the formula. That happening usually amounts to an error, and the model checker checks for it by default. Time to add the actual algorithm!

### Completing the Specification

We return to the currently stubbed-out actions PrepareReq, PrepareRsp, AcceptReq, and AcceptRsp, replacing them one by one. The result will be this commit.

First up is PrepareReq, which is the message sent by a proposer when it gets started on a new proposal (ballot).

BallotActive(b) == \E m \in msgs :
/\ m.type = "prepare-req"
/\ m.bal = b
PrepareReq(b) ==
/\ ~ BallotActive(b)
/\ Send([
type |-> "prepare-req",
bal  |-> b
])
/\ UNCHANGED(<<prepared, accepted, value>>)

A ballot is started by sending a prepare request (with the hope that responses will be received from a quorum). We could allow multiple prepare requests for a single ballot, but since they are all identical and we already model multiple-receipt for all messages, this adds only state space complexity. So a ballot will only be prepared once in this model.

More precisely, a successor (primed) state satisfies PrepareReq(b) if and only if

• it’s predecessor (i.e. the unprimed variables) contain no prepare request for ballot b (~ is negation), and
• the primed state contains a message of type prepare-req and ballot b, and
• everything else is identical.

The last condition may surprise you, but consider that if we omitted it, you could create lots of nonsensical successor states by freely mutating prepared, accepted, and value. Not what we would want!

Now that we’re warmed up, let’s get a bit more involved and hash out PrepareRsp(a):

PrepareRsp(a) ==
/\ \E m \in msgs :
/\ m.type = "prepare-req"
/\ m.bal > prepared[a]
/\ prepared' = [prepared EXCEPT ![a] = m.bal]
/\ Send([
acc      |-> a,
type     |-> "prepare-rsp",
promised |-> m.bal,
accepted |-> accepted[a],
val      |-> value[a]
])
/\ UNCHANGED <<accepted, value>>

Read: A prepare response can be sent if by an acceptor if a) a response was demanded via a prepare request (there exists a corresponding prepare request message) and b) the acceptor has not already prepared that or any larger ballot. On success, the acceptor remembers that it has prepared the new ballot, and sends a response.

The odd syntax [prepared EXCEPT ![a] = m.bal] means

same as prepared, with the exception that when evaluated at a, return m.bal

and nobody likes it, including its author Leslie Lamport.

Phew! Getting the hang of it yet? I hope so, because now it’s time for the big leagues:

AcceptReq(b, v) ==
/\ ~ \E m \in msgs : m.type = "accept-req" /\ m.bal = b
/\ \E Q \in Quorums :
LET M == {m \in msgs : /\ m.type = "prepare-rsp"
/\ m.promised = b
/\ m.acc \in Q}
IN /\ \A a \in Q : \E m \in M : m.acc = a
/\ \E m \in M :
/\ m.val = v
/\ \A mm \in M : mm.accepted \leq m.accepted
/\ LET newVal == Mutator(b, v) \* crucial difference from Paxos
IN Send([
type   |-> "accept-req",
bal    |-> b,
newVal |-> newVal
])
/\ UNCHANGED(<<accepted, value, prepared>>)

Read: An accept request can only be sent (i.e. fabricated from thin air)

1. once;
2. if prepare responses for the ballot have been received from a quorum, and
3. with a new value based on the most recently accepted value from the prepare responses.

It’s only here that we really deviate from Single-Decree Paxos by using Mutator!

Scared of AcceptRsp? Don’t worry, that one is straightforward again.

AcceptRsp(a) ==
/\ \E m \in msgs :
/\ m.type = "accept-req"
/\ m.bal \geq prepared[a]
/\ prepared' = [prepared EXCEPT ![a] = m.bal]
/\ accepted' = [accepted EXCEPT ![a] = m.bal]
/\ value'    = [value    EXCEPT ![a] = m.newVal]
/\ Send([
acc      |-> a,
type     |-> "accept-rsp",
accepted |-> m.bal
])

Read: An acceptor can reply to an accept request only if it hasn’t yet prepared a higher ballot. Before replying, it makes sure it marks the ballot as prepared (as the particular acceptor may not have received the associated prepare request earlier), and updates its accepted ballot and the new value.

That’s it already! Try running the model again - it should take some time and your laptop may begin radiating energy in the form of heat. On mine the state space exploration takes around 15s and reports a total of 791370 states.

Of course, we’re still only running the model, not really checking it. In the next section, we’ll add something that fails on some interesting histories.

## Discovering Interesting Histories

Now we have our system specified, a model and the associated sizable state space to explore - but we don’t actually know what we’re looking for. Hence, let’s return to the algorithm at hand. The result of this section will be this commit.

Without formalizing it too much, we should care in one way or another whether the “mutations line up”. That is, the values that the register stores over its (in the model, very short) lifetime should be those that Mutator creates from their predecessors. Or, in the language of compare-and-swap, we shouldn’t have one value stored in the register but then be able to run a compare-and-swap that doesn’t respect this existing value.

Let’s try to put this in a naive formula we can then have the model checker verify for all states. Remember that “committed” below means that the value at the corresponding ballot has been accepted by a majority of acceptors.

For any committed value v’ at ballot b’ > 0 and the previously committed value v at ballot b < b’, it holds that v’ = Mutator(b’, v).

Just to be clear, that assumption is not correct and perhaps you want to take a minute with pen and paper and figure out why not. Or, in the spirit of this section, let the model checker tell you why it’s wrong. But first we have to turn those words into math!

Taking the top-bottom approach, we add to our existing formula DesiredProperties two to-be-defined assertions:

DesiredProperties == /\ TypeOK
/\ OnlyOneValuePerBallot
/\ MutationsLineUp

OnlyOneValuePerBallot is easy to define; we just want to check that we never accept conflicting values for a proposal. It’s fairly clear that that can’t happen when you look at the algorithm, but it’s still good to have it checked:

OnlyOneValuePerBallot == \A b \in Ballot :
Cardinality(ValuesAt(b)) \leq 1

where ValuesAt(b) are all the values for which we’ve seen accept responses for ballot b (i.e. the value was accepted by the acceptor sending the message):

ValuesAt(b) == IF b = 0 THEN {InitialValue}
ELSE { v \in Values :
\E m \in msgs :
/\ m.type     = "accept-rsp"
/\ m.accepted = b
/\ \E mm \in msgs :
/\ mm.type   = "accept-req"
/\ mm.bal    = b
/\ mm.newVal = v

Note how we had to comb through the accept requests to find the value; it’s not sent out with the accept response since the recipient already knows it.

Now for the prize:

MutationsLineUp ==
\A b \in CommittedBallots \ {0} :
LET newVal == UnwrapSingleton(ValuesAt(b))
prevCommitBallot == BallotCommittedBefore(b)
oldVal == UnwrapSingleton(ValuesAt(prevCommitBallot))
IN  newVal = Mutator(b, oldVal)

where BallotCommittedBefore(b) is the largest ballot less than b for which a value was committed (= accepted by a quorum, not necessarily b-1!), and UnwrapSingleton turns a single-element set into its only element:

UnwrapSingleton(s) == CHOOSE v \in s : TRUE
AcceptedByQuorum(b) == \E Q \in Quorums: AcceptedBy(b) \cap Q = Q
CommittedBallots == {b \in Ballot : AcceptedByQuorum(b)} \cup {0}
BallotCommittedBefore(b) == CHOOSE c \in CommittedBallots :
/\ c < b
/\ \A cc \in CommittedBallots :
cc \geq b \/ cc \leq c

### Running the Model

As before, give the model a spin - note that since we extended DesiredProperties, the model checker is now checking more than before.

And, lo and behold, after working for a short while, execution stops and we see a complaint:

Invariant DesiredProperties is violated.

In such a situation you can get lucky and that message will be accompanied by a “stack trace” that allows you to find out which part of the formula made it fail. Alas, not this one, but we get the complete history of state transitions and a trace exploration tool. From it we can transcribe (your actual history may vary):

• ballot one and two: prepare request sent
• ballot one and two, acceptor 1: prepare response sent (existing value 0)
• ballot one, acceptor 2: prepare response sent (existing value 0)
• ballot one: accept request sent for new value 1 = Mutator(one, 0)
• ballot one: acceptor 2: accept value 1
• ballot two: acceptor 2: prepare response sent (existing value 1)
• ballot two: accept request sent for new value 3 = Mutator(two, 1)
• ballot two: acceptors 1 and 2: accept value 3
• DesiredProperties is violated because 3 is committed, but not equal to 0 = Mutator(zero, 0).

We’ll discuss this and more in the next section.

## Discussion of CAS-Paxos

In the last section, we’ve discovered a history which violated our (naive) assumption that each committed value is born out of a mutation of a previous committed value: We run two ballots concurrently, and it just so happens that without the first ballot ever committing, the second one gets to read its value, base its mutation on it, and commit (by having two out of three acceptors accept the ballot).

Does this mean we’ve found an anomaly, or, finally getting more precise, does this mean we’ve found a non-linearizable history? Let’s write this history up from the perspective of linearizability:

• time=10: the register is initially foo (which means that if you run an instance of Single Decree Paxos, you learn the value foo)
• time=10: I dispatch CAS(bar, baz)
• time=11: You dispatch CAS(foo, bar)
• time=20: I hear back that my CAS went through OK.
• You never hear back.

Note that it doesn’t matter which of us dispatches their CAS first. What matters is that though you never learn whether your CAS applied, it could have applied at any point in time with time >= 11! So it’s easy to invent legal points in time at which it applied so that things make sense:

• time=10: I dispatch CAS(bar, baz)
• time=11: You dispatch CAS(foo, bar)
• time=12: Your CAS(foo, bar) commits
• time=13: My CAS(bar, baz) commits
• time=20: I hear back that my CAS went through OK.

So this history is linearizable. Note however that that doesn’t prove that the system is! All we’ve managed to show is that it’s not broken for this particular example.

Looking back under the hood of how CAS-Paxos actually works, something noteworthy did happen that doesn’t reflect through the lens of linearizablity: When “my” PREPARE phase sends its first message, you had already gone ahead and got your new value bar accepted on one of the acceptors:

Values = [bar @ 1, foo @ 0, foo @ 0]     # value @ ballot

When you look at the system in that state from the outside, you might be tempted to say that the register stores the value foo (after all, that’s the value you can find on a majority). But that’s not correct! If you want to read the value, you must run a full phase of Single Decree Paxos. And that would either:

• talk to a majority that has bar, and have bar committed at the end:

Values = [bar @ 2, bar @ 2, foo @ 0 or bar @ 2]

• talk to a majority that does not have bar, and commit a “newer” copy of foo at the end:

Values = [bar @ 1 or foo @ 2, foo @ 2, foo @ 2]

That is, until you actually go and read the register, it doesn’t necessarily “have” a value - if in the examples below we didn’t run ACCEPT, you could contact one majority first, and then the other, and you would get different values though nobody else is using the system - definitely not linearizable!

Reading the value thus requires participating in deciding it. But it should be possible to skip the ACCEPT phase if you receive the same ballot from all possible acceptors (three in the above example).

Something similar, though less transparently, happened when my PREPARE phase picked up your value which you had managed to get accepted at only one of the nodes: It “implicitly” committed it when it committed its own update. And, actually, since your partial value might have in turn been based on a previous not-explicitly-committed value as well, that was also implicitly committed, and so on. In a different possible outcome, I wouldn’t have found your value, and would have implicitly made sure that it would never be visible, as if you had never tried to write it. That, too, is legal.

This also gives an intuitive understanding of why CAS-Paxos should be linearizable: the state of the system after a successful CAS based on an uncommitted value is equivalent to one in which you “make up” accept messages to accept that value (at its home ballot) between the main operation’s PREPARE and ACCEPT phases. Then you only have to consider the case where every value you see is committed, and that argument should be very similar to that that assures that a Single Decree Paxos register never “loses” a once-committed value.

Values = [bar @ 1, foo @ 0, foo @ 0]
Values = [bar @ 1, bar @ 1, bar @ 1] # implicit
Values = [baz @ 2, baz @ 2, foo @ 0]

### Runaway Commit

The fact that one proposal might pick up a previous incomplete proposal has practical implications on the proposer running the incomplete proposal. From its point of view, when it continues the ACCEPT phase, it will be told by other acceptors that a conflicting proposal has superseded its own. But, it has no way of finding out whether its value did make it into the system or whether it was wiped out by the concurrent proposal. Paxos (CAS or Single Decree) doesn’t fare too well when there is a lot of concurrent proposing going on anyway, so this may not be much of an issue (and if it were, some extra state could be kept around by the acceptors to mitigate).

### Properly Failing a CAS

So far, we have neglected the case in which a compare-and-swap operation fails, and in particular that in which it fails because the “previous value” is not the required one. Naively, you would perhaps consider the following behavior:

• run a PREPARE phase and collect responses from a majority
• if the value with the highest ballot does not match what we expect, tell the client the CAS failed: “I tried, but the register does not hold the value you thought it did”.

But that’s incorrect! Consider again the case of a partially committed value:

Values = [bar @ 1, foo @ 0, foo @ 0]

A PREPARE phase for CAS(foo, boo) might pick up bar as the most recent value, the client is told that the register doesn’t hold the value foo. But next, the client reads the register, winds up talking to the majority that doesn’t have bar, and learns that the value is indeed foo - we’ve got ourselves into a nonlinearizable history.

Instead, a CAS which finds an incompatible value after PREPARE must run an ACCEPT phase with that incompatible value, because only when that succeeds is it allowed to tell the client with authority that the register did not hold the correct base value. Or, it could return a more generic error to the client which doesn’t make any statement about the value of the register, but usually you want a failed CAS to report the actual value of the register, and that definitely needs the ACCEPT phase.

## Summary

We’ve introduced the CAS-Paxos algorithm, specified it in TLA+ and discussed some interesting histories, phenomena, and implications on practical implementations. Intuitively, we have seen that there is reason to believe that CAS-Paxos provides a distributed linearizable register with compare-and-swap semantics, which is a powerful primitive for building distributed systems.


text:
Poster Open Access

# Accretion efficiency and mass transfer in two binary star systems

Boneva, Daniela; Yankova, Krasimira

### JSON-LD (schema.org) Export

{
"description": "
We analyze the accretion properties of two binary star systems: the BY Draconis type variable V1803 Cyg, which is an A component of the binary system 61Cyg and the semi-regular (SR) symbiotic variable NQ Gem. In this aim, we estimate an accretion efficiency in these binaries, based on the relation between luminosity and rate of accretion. We give an appraisal on the currently active mass transfer mechanism between the components in the binaries. This could be relevant to the type of accretion, wind or disc is dominant for each of the objects. A feasible contribution of the accretion rate to the objects’ activity states, as an effect on the luminosity variations is considered. An X-ray variability of NQ Gem in the range of 0.3 – 10keV, with a maximum count rates activity mostly in the hard band part of the energy spectrum, is detected. We compare the results for both objects, according to the features of their different stellar types.
",
"creator": [
{
"affiliation": "Space Research and Technology Institute, Bulgarian Academy of Sciences",
"@type": "Person",
"name": "Boneva, Daniela"
},
{
"affiliation": "Space Research and Technology Institute, Bulgarian Academy of Sciences",
"@type": "Person",
"name": "Yankova, Krasimira"
}
],
"url": "https://zenodo.org/record/4564449",
"datePublished": "2021-02-26",
"@context": "https://schema.org/",
"identifier": "https://doi.org/10.5281/zenodo.4564449",
"@id": "https://doi.org/10.5281/zenodo.4564449",
"@type": "CreativeWork",
"name": "Accretion efficiency and mass transfer in two binary star systems"
}
92
63
views


text:
# Radicals - Rationalizing

• June 21st 2013, 06:49 PM
Mathnood768
http://puu.sh/3lies.png
The numerator is already rationalized, isn't it? I'm not really sure, but the answer isn't 2.
• June 21st 2013, 07:03 PM
topsquark
Re: Radicals - Rationalizing
Quote:

Originally Posted by Mathnood768
http://puu.sh/3lies.png
The numerator is already rationalized, isn't it? I'm not really sure, but the answer isn't 2.

You are being asked to rationalize the fraction and then state what the radicand is in this form.

-Dan
• June 21st 2013, 07:04 PM
Plato
Re: Radicals - Rationalizing
Quote:

Originally Posted by Mathnood768
http://puu.sh/3lies.png
The numerator is already rationalized, isn't it? I'm not really sure, but the answer isn't 2.

$\frac{2}{\sqrt3}=\frac{2\sqrt3}{3}$


text:
You are not logged in.

Note that this link will take you to an external site (https://oidc.mit.edu) to authenticate, and then you will be redirected back to this page.

## 1) Preparation

This lab assumes you have Python 3.5 or later installed on your machine. Like Lab 1, this lab also requires the pillow module to be installed.

The following file contains code and other resources as a starting point for this lab: lab10.zip

Most of your changes should be made to lab.py, which you will submit at the end of this lab. Importantly, you should not add any imports to the file.

This lab is worth a total of 4 points. Your score for the lab is based on:

• passing the test cases from test.py under the time limit (2 points), and
• a brief "checkoff" conversation with a staff member to discuss your code (2 points).

For this lab, you will only receive credit for a test case if it runs to completion under the time limit on the server.

Both the code submission and the checkoff for this lab come due at the last possible time for submissions to the course, Wednesday, May 15th, at 2:55 PM. Because of Institute rules, this is the last time at which assignments come due. As such, neither late days nor automatic extensions can be used on Lab 10.

## 2) Introduction

We suggest reading the entire lab before writing any code, to get a sense of the program you are being asked to write.

One way to handle the problem of reliably storing large files is to break them into pieces that are placed on multiple disks, or on multiple machines. This way, if something goes wrong with a particular file (and/or with a particular machine as a whole), the file is still available.

In this lab, you will build a multi-part downloader that assembles a data stream from multiple parts streaming individually from multiple machines. It allows the same part to be stored redundantly in multiple locations so it can be resilient to failures. Since the multipart streams you will be downloading may be nonterminating, your program will assemble the stream incrementally from its parts as they are downloaded, displaying the file or streamed sequence of files (an animated sequence of images, for example) as the download progresses.

This page describes the specification for the lab, but it also aims to provide some review on a few aspects of Python that were discussed in lecture but that have not been used explicitly in a lab yet.

Throughout this lab, we will be interested in downloading files from various web servers. We have provided a function called http_response, which is defined in http009.py, to help you with this task. http_response is a thin wrapper around functionality from Python's built-in http.client module.

That function takes a single argument (a string representing the URL of a resource we wish to look up), and it returns an HTTPResponse object.

In particular, we are interested in three or four attributes/methods of these objects. If r is the result of calling http_response, then:

• r.status gives the HTTP status code that the server returned. For this lab, we will need to know that
• 301, 302, and 307 represent redirects.
• 404 means that the specified file was not found.
• 500 means that an error occurred on the server.
• r.getheader(name) returns the HTTP response header associated with the given name.
• r.getheader('location') will provide the location if we were redirected.
• r.getheader('content-type') will tell you the media type of the response of a successful request.
• r.read(num_bytes) returns a bytestring containing at most num_bytes number of bytes read from the body of the response. If no more bytes can be read, returns an empty bytestring b''. If num_bytes is not given, return the entire page contents. See section 10 if you are unfamiliar with Python bytestrings.
• r.readline() returns a bytestring containing the next line of the body of the response. It returns an empty bytestring b'' if no more bytes can be read.
• to decode a bytestring into a string run b''.decode("utf-8")

Check Yourself:

Try calling http_response from the Python REPL for a few different URLs, to get a sense of how it behaves (you can get to a Python REPL with that function defined by running python3 -i http009.py).

Inspect the objects returned from this function, and try to extract the status code, headers, and response body for the following:

• 'https://py.mit.edu' should be a redirect.
• 'https://6009.cat-soop.org/spring19/labs/lab11' is a nonexistent file.
• 'https://6009.cat-soop.org/spring19/python' exists, and it should have a body that is 6822 bytes long.
• 'http://nonexistent.mit.edu/some_file.jpg' is trying to access a file on a computer that doesn't exist.

NOTE FOR MAC USERS

There is a known issue with the default installer for Python 3.6 and 3.7 on Mac OSX. If you are having trouble accessing files at HTTPS addresses, it is likely because there is still some action required on your part. In particular, you may need to run one of the following commands (while in the Users/your_username directory) to enable support for SSL communication:

/Applications/Python\ 3.6/Install\ Certificates.command
/Applications/Python\ 3.7/Install\ Certificates.command

### 2.2) File Manifests

In addition to being able to download regular files, there are also file manifests, which is a way of specifying how a particular file is broken down into parts. File manifests in our implementation will either end with .parts or have the Content-Type header equal to 'text/parts-manifest'.

The manifest contains several parts, each adjacent pair of which is separated by a line containing exactly two hyphens --. For example, a file picture.jpg might be broken down into three parts, which could be specified with:

http://mymachine.mit.edu/picture.jpg-part1
--
http://mymachine.mit.edu/picture.jpg-part2
--
http://mymachine.mit.edu/picture.jpg-part3

To download the contents of this file specified by the manifest, you would need to download each of the individual parts and concatenate them together.

In addition, the manifest can provide alternatives for each section (so that if one URL doesn't work we can use the other one):

http://mymachine.mit.edu/picture.jpg-part1
http://yourmachine.mit.edu/picture.jpg-part1
--
http://mymachine.mit.edu/picture.jpg-part2
http://yourmachine.mit.edu/picture.jpg-part2
--
http://mymachine.mit.edu/picture.jpg-part3
http://yourmachine.mit.edu/picture.jpg-part3

In this example, each of the three parts is stored both on mymachine.mit.edu and on yourmachine.mit.edu. For each part, if the first option is not successfully downloaded, we should try the second option (and so on until we find one that works). In general, a manifest is not limited to 2 options; there may be arbitrarily many options for each part, and each part might have a different number of options.

Manifest streams can be recursive, which means that a part might itself be specified by a URL ending in .parts (which represents a manifest stream). In the case where a part refers to a manifest stream, the entire contents of the file referred to by that manifest stream should be used.

For example, if http://mymachine.mit.edu/endless.txt.parts contains the following lines:

http://mymachine.mit.edu/verse.txt
http://yourmachine.mit.edu/verse.txt
http://hermachine.mit.edu/verse.txt
--
http://yourmachine.mit.edu/chorus.txt
--
http://mymachine.mit.edu/endless.txt.parts

Then someone downloading the file should receive an endless file alternating between the contents of verse.txt and chorus.txt.

Check Yourself:

To summarize:

• A manifest has multiple parts.
• Parts are separated by lines of --.
• Parts can have multiple URLs.
• Parts can point to URLs that are manifests themselves.

#### 2.2.1) Caching

Manifest files may have parts that are replicated multiple times in the same file. This may be obvious from the previous manifest file, which is an endless stream of two replicated text parts. Thus, we will also add the capability to cache parts of files within a single download (though we will explicitly not cache these results across multiple downloads).

Caching is a bad idea if a file changes too frequently. Therefore we are not going to cache all the files we download. We will only cache for a part if (*) is listed as a possible URL for that part in the manifest file. This indicates that the manifest file deems a particular part to be largely fixed content, so it can be safely cached within a single download.

When downloading, if we reach a part that is marked as cacheable (contains (*)), we should first check to see if any of the URLs has been cached. If the file has already been cached, we should simply use that result (without making any HTTP requests). If not, we should send a HTTP request to download the first URL in the part and store the result in the cache. Importantly, caching should not interrupt the streaming (i.e., we should still be able to stream from files as we download them, rather than having to wait for the whole file to be downloaded first).

Parts in the manifest that are not marked with an (*) should never be cached. This requires that the content for these links should not be read from the cache or stored to the cache. Thus, a sample Manifest file that supports caching could look like the following:

(*)
http://mymachine.mit.edu/verse.txt
http://yourmachine.mit.edu/verse.txt
http://hermachine.mit.edu/verse.txt
--
http://yourmachine.mit.edu/chorus.txt
(*)
--
http://mymachine.mit.edu/endless.txt.parts

For simplicitly, it is not necessary to support caching manifest files themselves, and it is not necessary to support caching infinite files (i.e., you can assume that any file you are being asked to cache is finite in length).

Check Yourself:

To summarize:

• Caching should be "off" by default and should reset at the beginning of each download_file call.
• Only cache and use cached files when (*) appears in the part of file manifest.
• Do not support infinite files. (All cached files are finite.)

### 2.3) File Sequences

In addition to manifests, we would also like to handle file sequences. In general, a file sequence is a single stream of bits that represents a sequence of multiple files. We'll use a format of our own invention, but it's not too different from, for example, a movie file (which can be thought of as a sequence of frames, each of which is an image).

If a URL contains the string -seq, the resulting stream represents a sequence of files. Each sub-file in a sequence is represented as:

• 4 bytes containing the length of the file (in bytes, represented as a single big-endian unsigned integer (see subsection 10.4)), followed by
• the raw bytes contained in the file (there should be as many bytes as were specified in the length field).

As an example, consider a file consisting of the following 5 bytes (shown in hexadecimal):

36 2E 30 30 35

and another file consisting of the following 6 bytes:

72 75 6C 65 73 21

We could encode a file sequence consisting of these two files with the following stream of 19 bytes (4-byte length + 5-byte file + 4-byte length + 6-byte file):

00 00 00 05 36 2E 30 30 35 00 00 00 06 72 75 6C 65 73 21

If a URL contains -seq and is also a manifest (the URL ends with .parts or the content type is text/parts-manifest), then it represents a manifest file that, when all parts are concatenated, represents a file sequence.

## 3) Implementation

We have provided a very small skeleton in lab.py, indicating the functions that must be defined for this lab. Beyond those, you are welcome to define whatever helper functions / classes you deem necessary.

We'll start by discussing basic downloads. You should fill in the body of the download_file function to implement a basic "streaming" downloader1.

download_file should be a generator that yields the result of the response as bytestrings of at most CHUNK_SIZE length (it should yield bytestrings of this size until it is no longer able to do so, at which point it should yield one bytestring of smaller size if the file contains additional content).

Note that, throughout this lab, we will assume that any URL refers to a potentially infinite stream (for example, a stream from a webcam). As such, your download_file function should not download the entire contents of the file and yield values from that result; rather, it should yield chunks of the file as they are downloaded.

We will also assume that any URL refers to arbitrary binary data (it could be an image, or text, or random bytes, etc.). Aside from checking whether the URL refers to a file manifest, your code should not need to change its behavior based on the type of the data (or the content-type header).

There are a couple of additional complications:

• If a request results in a redirect (status codes 301, 302, or 307 for our purposes), your downloader should follow that redirect and try the location to which you are being redirected.
• If a request gives a 404 status code, your downloader should raise a FileNotFoundError.
• If a request gives a 500 status code, or if the connection was not made because of a network error, your downloader should raise a RuntimeError.
• A status code of 200 indicates a successful request.

### 3.2) Handling Manifests

If the location given at initialization time ends with .parts or if the Content-Type header associated with a request is 'text/parts-manifest', then it represents a file manifest. In this case, rather than simply yielding the contents of that .parts file, download_file should instead yield the bytes from each of the files specified in the manifest, in the order they are specified.

In order to keep things as smooth as possible, your function should start streaming the first part as soon as it is available, rather than waiting for all parts to be available before streaming.

#### 3.2.1) Caching

You should also make sure that your program properly caches files that were indicated with (*) in any file manifests that were given (so that, if we have already retrieved their contents once in the process of downloading the file, we do not do so a second time). Your program should not cache other files.

If a file is cached, it is OK to yield the entire contents of the cached file as one bytestring (rather than splitting it up into chunks and yielding those separately).

Importantly, the cache should not persist between calls to download_file. That is, starred files that we try to download multiple times within a single top-level call to download_file should be cached, but that cache should be invalidated with every new top-level call to download_file.

### 3.3) Handling File Sequences

The description above should be enough for downloading file sequences, but it is not yet enough for interpreting them. You should not need to change any behavior in your downloader to account for file sequences. But the GUI needs to know something about how to handle file sequences in order to properly display them, so we'll add a small piece of functionality to allow us to grab individual files from the sequence.

Write a new generator called files_from_sequence(stream). Given a generator of the form described for download_file, files_from_sequence should yield the contents of each file contained in the sequence, in the order they are specified. Note that each of the chunks yielded from download_file might contain multiple files, or it might not contain an entire file. Your function will need to account for both of these cases.

## 4) Interfaces

In order to test your code, we have already provided an interface (for displaying downloaded images and/or text files) for you in gui.py in the lab distribution.

You can run the GUI from the command line by giving it a URL as argument:

$python3 gui.py URL  The GUI will then use your code to stream the file, and it will attempt to display it. You can also optionally specify an additional integer argument that specifies how long the GUI should wait between switching files in a file sequence when displaying them (this value is specified in milliseconds). ## 5) Implementation Advice This is a fairly complicated task, and so trying to write it all in one go might make the task of organizing your code (and of debugging) more difficult. You may find it easier to implement the lab in small pieces first. For example, you might: • start by writing something that downloads a single file that you know exists (after which Test1_Streaming should pass), then • introduce support for handling redirects and/or errors (after which Test2_Behaviors should pass), then • add support for handling file manifests (after which Test3_Manifest should pass), then • add support for caching (after which Test5_Caching should pass), then • add support for file streams (after which all tests should pass). You might find a different order preferable, but starting small and then adding functionality piece-by-piece is likely to make the debugging process more straightforward. ## 6) Test Files The files below provide some data for testing (roughly in order of increasing complexity): ## 7) Code Submission When you have tested locally and are satisfied that your code is working, you can use the box below to submit your code to the server for testing. No file selected This question is due on Wednesday May 15, 2019 at 02:55:00 PM. ## 8) Checkoff Once you are finished with the code, please come to a tutorial, lab session, or office hour and add yourself to the queue asking for a checkoff. You must be ready to discuss your code in detail before asking for a checkoff. You should be prepared to demonstrate your code (which should be well-commented, should avoid repetition, and should make good use of helper functions). In particular, be prepared to discuss: ### 8.1) Grade You have not yet received this checkoff. When you have completed this checkoff, you will see a grade here. ## 9) (Optional) Additional Extensions ### 9.1) Interfaces In addition to the gui.py interface, we would like to provide an interface for saving the results of downloading a file and saving its contents to disk. Modify your lab.py so that it takes two arguments when it is run from the command line: $ python3 lab.py URL FILENAME

When invoked in this way, your program should download a file from URL, and save its contents at a location given by FILENAME. If the given URL refers to a parts manifest, you should not directly save the contents of the manifest; rather, you should save the contents of the file to which that manifest refers. If the given URL refers to a sequence, then instead of saving a single file, you should save multiple files of the form FILENAME-file1, FILENAME-file2, ...; each of these files should contain one file from the sequence.

Recall that you can access command-line arguments via the sys.argv variable.

### 9.2) Files of Your Own

• an image or audio file of at least 100kB
• an image or text file of at least 100kB, split into at least 3 distinct pieces and represented as a .parts file
• a file sequence of at least 100kB, consisting of at least 3 distinct files

Note that you can make a file accessible at http://mit.edu/YOUR_ATHENA_USERNAME/www/FILENAME by creating a file called FILENAME in your Athena account under the www directory. You can use this to put your files on the web so that your downloader can reach them. See this page from IS&T for information about how to transfer files to your Athena account.

### 9.3) Infinitely Long Manifests

You are not required to deal with infinitely long manifest, however, for fun you can try.

One nice extension for this lab would be modifying your code so that, when it encounters a manifest file, it downloads all of the pieces in parallel (rather than sequentially).

### 9.5) Other Errors

What we have built in this lab is a fairly realistic system that interacts with other computers via the Internet. In such systems, there is the potential for unforeseen errors to arise. When using this system, a variety of errors could happen that the description above has not explicitly accounted for.

Think through a few possible kinds of errors that could occur but that aren't explicitly described above, and modify your code so that it handles them.

## 10) Appendix: Working with Raw Binary Data in Python

The strings in Python that we are familiar with (the str type) consist of a useful abstraction for representing text. In particular, Python strings represent sequences of characters (where each character represents a Unicode character).

These are a useful abstraction for displaying text, but the fact that they exist as an abstraction for the text means that they do not work as a representation for other kinds of data, for example images or audio (since text has a particular struture in its binary data that images or audio won't generally have). Ultimately, what can be stored on disk (or sent over the network) is a series of binary values (1's and 0's). Saving character strings to disk, for example, requires first converting them to raw binary data first.

In this lab, we will be working with binary data in a variety of formats (including not only text, but also images and audio), so we will need a different, lower-level abstraction that lets us work directly with binary data. Conveniently, Python offers just such an abstraction, through bytestrings and bytearrays.

### 10.1) Byte Strings

Python offers a built-in type called bytes that represents a sequence of raw binary data. While this does represent a sequence of 0's and 1's, the bytes type exposes those values to us not as individual bits, but rather as bytes, each of which contains 8 bits. As such, we can think of each byte as representing an integer between 0 and 255 (inclusive).

One way to construct bytestrings is directly from arrays of integers, for example:

>>> x = bytes([207, 128])
>>> y = bytes([207, 132, 32, 62, 32])

If we print the resulting value, we see a different Python syntax for bytestrings (which looks like a regular string, but with a b in front:

>>> print(x)
b'\xcf\x80'
>>> print(y)
b'\xcf\x84 > '

Note that this is not human-readable like a regular Python character string. However, it is in a format that makes it easy to write the data to disk directly, or to send it across a network (which will be relevant for this lab!).

Byte strings support indexing like regular strings. When we index into a bytestring, we get the integer value associated with the byte at that index (this will be an integer in the range 0 to 255, inclusive). Similarly, looping over a bytestring gives us integer values.

>>> print(x[0])
207
>>> for i in y:
...     print(i)
...
207
132
32
62
32

### 10.2) Converting Between Character Strings and Bytestrings

As we have mentioned above, Python has two separate internal representations for strings: character strings (str) and byte strings (bytes). The conversion between these is described by an encoding (which specifies how each character is represented as a sequence of bytes).

In order to store a character string on disk, it must first be encoded; and to view a human-readable form of a string that has been read from a file on disk, it must be decoded.

There are many different possible encodings for string data (that is, given a sequence of abstract characters, there are a number of different ways we could choose to represent those as raw binary data). Two of the most common encodings are ASCII, UTF-8, and UTF-16. As we can see, encoding the same string with two different encodings gives us two different sequences of bytes:

>>> x = "Fußgänger"
>>> u8 = x.encode('utf-8')
>>> u8
b'Fu\xc3\x9fg\xc3\xa4nger'
>>> u16 = x.encode('utf-16')
>>> u16
b'\xff\xfeF\x00u\x00\xdf\x00g\x00\xe4\x00n\x00g\x00e\x00r\x00'

When decoding, we also need to know which character encoding we are using. Trying to use the wrong encoding will either produce an unexpected answer or an error:

>>> u8.decode('utf-8')
'Fußgänger'
>>> u8.decode('utf-16')
Traceback (most recent call last):
File "<pyshell#119>", line 1, in <module>
u8.decode('utf-16')
UnicodeDecodeError: 'utf-16-le' codec can't decode byte 0x72 in position 10: truncated data

### 10.3) Reading and Writing Binary Data From Files

When we dealt with files in previous labs, we were making the (unstated) assumption that the files we were working with contained textual data (specifically, textual data encoded using the UTF-8 encoding, which is a broadly used standard).

Let's see what happens when we try to open a file that does not contain UTF-8-encoded text:

>>> with open('Havana.mp3', 'r') as f:
...
Traceback (most recent call last):
File "<stdin>", line 2, in <module>
File "/usr/local/lib/python3.7/codecs.py", line 322, in decode
(result, consumed) = self._buffer_decode(data, self.errors, final)
UnicodeDecodeError: 'utf-8' codec can't decode byte 0xff in position 45: invalid start byte

Indeed, we get an exception saying that Python does not know how to convert the data in that file into a human-readable character string! In order to grab the data from the file, we need to tell Python to open the file in binary read mode by specifying 'rb' when opening the file:

>>> with open('Havana.mp3', 'rb') as f:
...

Having done this, we have the raw binary data available to us in the variable x (as a bytestring).

>>> len(x)
3471822
>>> x[:100]
b'ID3\x04\x00\x00\x00\x00\x00#TSSE\x00\x00\x00\x0f\x00\x00\x03Lavf57.56.101\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\xff\xfbP\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00Info\x00\x00\x00\x0f\x00\x00 r\x004\xf9\xa1\x00\x02\x05'
>>> for i in x[:10]:
...     print(i)
...
73
68
51
4
0
0
0
0
0
35

### 10.4) Representing Integers with Bytestrings

As we mentioned above, each byte in a bytestring has a representation as an integer in the range 0-255 (inclusive). A few different representations for each possible byte are shown in the table on this page for reference, though it is certainly not necessary to commit that table to memory.

The question might arise, though: what do we do if we want to represent a number bigger than 255? Clearly, one byte isn't enough in that case! So we need a different convention for representing larger integers.

In general, we can use the concatenation of multiple bytes to represent larger integers. In this lab, we choose a "big-endian" representation, where the most-significant byte comes first. By this, we mean that, if we have a byte string containing bytes b_0, b_1, b_2, and b_3 (in that order), this represents an integer:

(256^3\times b_0) + (256^2\times b_1) + (256\times b_2) + b_3

In theory, we could extend this to an arbitrary number of bytes to represent arbitrarily large integers. In this lab, though, we chose to represent lengths using 4 bytes only (though this still allows us to represent integers up to 4,294,967,295).

Since we can index into bytestrings to get integer values, it is possible to compute this value directly without a complicated algorithm. Alternatively, you can look up the documentation for the int.to_bytes and int.from_bytes functions, which will handle this conversion (in either direction).

### 10.5) Byte Arrays

It is worth noting also that the bytes type, like regular Python strings, is immutable. On occasion (depending on the operation you want to perform), you may wish to work with a mutable array of bytes (such that you can mutate it by changing a character in place, by appending/extending values, etc.).

To this end, Python gives us the bytearray type. You can create a bytearray from a bytestring with bytearray(x), or you can create an empty bytearray with bytearray().

>>> ba = bytearray()
>>> ba.extend(u8)
>>> ba.extend("übergänge".encode('utf-8'))
>>> ba
bytearray(b'Fu\xc3\x9fg\xc3\xa4nger\xc3\xbcberg\xc3\xa4nge')

Note that the elements in the bytearray need to be valid bytes (integers in the range 0 to 255, inclusive). So you can extend a bytearray by an iterable of integers. But if you want to append values (or modify values), those values need to be given as integers.

It is worth noting, also, that bytearray objects can, in many ways, be treated like bytes objects. For example, they provide a decode method:

>>> ba.decode('utf-8')
'Fußgängerübergänge'

But if you need to, you can always convert back to a bytes object:

>>> x2 = bytes(ba)

Just like lists vs. tuples, the question of whether you want a byte string or a byte array is heavily dependent on the application (certain operations might only be possible on one type or the other, or certain operations might be more efficient with one type than with the other).

Footnotes

1In this case, "streaming" refers to the fact that we want to provide bytes from the file as they are being received, rather than downloading the entire file first and then returning its contents. (click to return to text)

2You may be familiar with the peer-to-peer file-sharing protocol BitTorrent, which uses this idea. It is also used in a variety of other contexts. (click to return to text)


text:
## Munson, Young and Okiishi's Fundamentals of Fluid Mechanics, Binder Ready Version 8th Edition

The verified dimensions are the following: a) Acceleration, $FLTsystem: LT^{-2}$, $MLTsystem: LT^{-2}$ b) Stress, $FLTsystem: FL^{-2}$, $MLTsystem: ML^{-1}T^{-2}$ c) Moment of a force, $FLTsystem: FL$, $MLTsystem: ML^{2}T^{-2}$ d) Volume, $FLTsystem: L^{3}$, $MLTsystem: L^{3}$ e) Work, $FLTsystem: FL$, $MLTsystem: ML^{2}T^{-2}$
Using the International System of Units: a)$Acceleration=a=\frac{m}{s^{2}}$ $FLTsystem: LT^{-2}$ $MLTsystem: LT^{-2}$ b)$Stress=\frac{N}{m^{2}}=\frac{Kg}{ms^{2}}$ $FLTsystem: FL^{-2}$ $MLTsystem: ML^{-1}T^{-2}$ c)$Moment$ $of$ $a$ $force=Nm=\frac{Kgm^{2}}{s^{2}}$ $FLTsystem: FL$ $MLTsystem: ML^{2}T^{-2}$ d)$Volume=m^{3}$ $FLTsystem: L^{3}$ $MLTsystem: L^{3}$ e)$Work=J=Nm=\frac{Kgm^{2}}{s^{2}}$ $FLTsystem: FL$ $MLTsystem: ML^{2}T^{-2}$


text:
# Tag Info

18

<x,y|x^2=y^3=1>≅PSL_2(Z) and this isomorphism identifies G with $PSL_2/T^7=1$ (where $T:z\mapsto z+1$). Result is the symmetry group of the tiling of the hyperbolic plane. From this description one can see that G is infinite (e.g. because there are infinitely many triangles in the tiling and G acts on them transitively).

13

$F_2$ acts on a certain tiling of the hyperbolic plane. It looks sort of like this: The above tiling is acted on by the modular group $\Gamma \cong \text{PSL}_2(\mathbb{Z})$, which naturally sits as a subgroup inside of the full group $\text{PSL}_2(\mathbb{R})$ of isometries of the hyperbolic plane. Abstractly, this group is the free product $C_2 \ast ... 12 Grigory has already answered your particular question. However, I wanted to point out that your question "How do you prove that a group specified by a presentation is infinite?" has no good answer in general. Indeed, in general the question of whether a group presentation defines the trivial group is undecidable. 9 First consider an unpainted$2\times 2\times 2$Rubik's cube: What is the "symmetry group"? Before we can discuss the symmetry group of this cube (or any Rubik's cube), we must be clear about what operations are allowed. There are three pertinent questions: Do rigid rotations of the cube count as "symmetries"?(If no, we must somehow exclude them.) Are ... 9 As I said in the comments above, this has a positive solution due to a recent preprint of Lars Louder, which can be found here. The paper proves that surface groups have a "single Nielsen equivalence class of generating$2g$-tuples". I'll explain what this means, and then I will explain why this solves the problem. (In the comments below, Lars Louder has ... 8 The answer to your question is yes: See Bekka–de la Harpe–Valette, Kazhdan's property$(T)$, page 69 (the standard reference on property (T), freely available on Bekka's homepage): The proof is not very difficult, and it is given in a clear fashion in the book, so it doesn't make much sense to reproduce it here. Note also ... 7 This counterexample seems to work for$\frac{1}{2}$, and beyond: $$x_g:=Cr^{\ell(g)}\qquad\forall g\in F_2$$ for the right choices of constants $$C>0\qquad\mbox{and}\qquad 0\leq r<\frac{1}{\sqrt{3}}.$$ Here$\ell(g)$denotes the word length of the element$g$, i.e. the minimal number of letters needed in the alphabet ... 7 More generally, any group$G$defined by a finite presentation with more generators than relations is infinite - in fact$G/[G,G]$is infinite. That follows from the proof of the fundamental theorem of abelian groups. You can prove it directly, by showing that there is a nontrivial epimorphism$\phi$onto${\mathbb Z}$. Let$\phi:G \to {\mathbb Z}$be any ... 7 I'm an outsider, so maybe what I'm saying is silly. I would just think about the Tits alternative application since that really gives all the intuition. To apply it---and we'll just look at the complex case---you should produce two matrices$A$and$B$that have the following properties.$A$has a dominant eigenvalue$\lambda$(i.e., the eigenspace of ... 7 This might not be the best argument, but it seems to work. First, no nontrivial finite, connected, vertex-transitive graph has a cutpoint (nontrivial here means something like cardinality at least$3$to avoid having to define cutpoint carefully). If it did, then every vertex would be a cutpoint, so you could inductively build an arbitrarily long finite ... 6 You can do this using metric currents in the sense of Ambrosio-Kirchheim. This is a rather new development of geometric measure theory, triggered by Gromov and really worked out only in the last decade. I should warn you that this is rather technical stuff and nothing for the faint-hearted. Urs Lang has a set of nice lecture notes, where you can find most ... 6 Let$z = x^2 = y^3$. This element clearly commutes with$x$and$y$. Therefore$z$lies in the center and$\langle z \rangle$is a normal subgroup. We have: $$G / \langle z \rangle = \langle x, y \mid x^2 = y^3 = 1\rangle.$$ Now the abelianization of this quotient group is$\Bbb Z_2 \times \Bbb Z_3$, which is clearly non-trivial. 6 If you think of$F$as acting by left multiplication on the vertices of$\Delta$, then the natural interpretation of the quotient graph is as a graph whose vertices are the distinct cosets$Gg$of$G$in$F$, with an edge (labelled$x$) from$Gg \to Ggx$for each$x \in \{a,a^{-1},b,b^{-1}\}$. So, if you ignore the labels, it is still a an infinite ... 6 You need to modify the definition of$\Psi$: put $$\Psi(t^na^xt^{-n})=xk^n$$ (instead of$\Psi(t^na^xt^{-n})=xk^{-n}$). The homomorphic property should follow easily along the lines of the computations given in the original question. Alternatively, you could replace$t$by$t^{-1}$in the definition of the Baumslag-Solitar group, in which case the$\Psi$... 5 Solving the relation for$c$, we conclude that there is a homomorphism$\langle\, a,b,c\mid a^2cb^3\,\rangle\to \langle a,b\rangle$given by$a\mapsto a$,$b\mapsto b$,$c\mapsto a^{-2}b^{-3}$, which is an isomorphism. There exists a homomorphism$\langle \,a,b,c\mid a^3b^3\rangle \to \mathbb Z/3\mathbb Z\times \mathbb Z/3\mathbb Z$given by$a\mapsto ...

5

Here is a different way of doing the second problem. How many homomorphisms are there from $G = \langle a,b,c \mid a^3b^3 \rangle$ to $C_6$ (cyclic group of order $6$)? We can map $a$ and $c$ to each of the $6$ elements independently, and then we must map $b$ to an element whose cube is the same as the cube of the image of $a^{-1}$. In $C_6 = \langle x ... 5 The amalgamation only identifies two isomorphic subgroups, it doesn't perform any further quotienting. So the group you are amalgamating over has to be isomorphic to a subgroup of both$A$and$B$. Thus your first statement is correct. You cannot form an amalgamated free product of$F_2$and a finite group with non-trivial amalgamation, because$F_2$... 5 Remark: For those unacquainted with Property$(T)$, the standard reference is the freely available book by Bekka-de la Harpe-Valette. Since groups with property$(T)$are finitely generated, we can assume that the rank of the free group$F$is finite. If a group$G$has property$(T)$then so does every quotient(1), recall also my answer to your ... 5 Gromov in his original 1987 book (Section 3.1) wrote a classification for arbitrary isometric group actions on hyperbolic spaces (with no further assumption) into 5 main classes. It goes at follows (the terminology is borrowed from here) 1: bounded: orbits are bounded 2: horocyclic: orbits are unbounded,$G$acts with no hyperbolic isometry (hence there's ... 5 Inspiration: in the free product$H=C_2*C_2=\langle a,b|a^2,b^2\rangle$the element$ab$has infinite order. And furthermore the only nontrivial coset of$\langle ab\rangle$is$b\langle ab\rangle$(every word in$H$is either a product of$ab$s or it is$b$followed by a product of$ab$s), so$\langle ab\rangle$has index two. The given information in this ... 5 Take$G = S_{3}$,$H = U = \langle (12) \rangle = \{ 1, (12) \}$. As a system of right coset representatives, take$R = \{ 1, (123), (132) \}$. Now choose$u = (12) \in U$, and$s = (123) \ne (132) = s'$. We have $$u s H = (12) (123) H = (13) H = \{ (13), (132) \} = (132) H = s' H.$$ Barring mistakes. 5 If$G,H$are groups then$H$is a double cover of$G$iff$H$has a normal subgroup$K$of order 2 such that$K \leq [H,H] \cap Z(H)$and$H/K \cong G$. In other words,$H$has an element$z$that (1) commutes with every element of$H$, (2) can be written as a product of commutators$z=\left(h_1^{-1} h_2^{-1} h_1 h_2\right)\cdots\left(h_{2n-1}^{-1} ...

5

(Of course the trivial group acts freely on all spheres! Let's assume $G$ is finite and nontrivial.) Since $G$ is finite, the action is certainly properly discontinuous, and since the action is given to be free, it follows that the quotient $q: X \rightarrow X/G$ is a finite covering map. Recalling that in any $n$-sheeted covering map $q: X \rightarrow Y$ ...

5

Yes, your interpretation is correct. There are no further relations since there are no loops in the Cayley graph except those deducible from the relations $a^2 = b^2 = e$. The group $\langle a, b \mid a^2, b^2 \rangle$ is known as the infinite dihedral group.

4

From linear algebra we know that every invertible matrix can be obtained from the identity matrix by a sequence of elementary row operations. The corresponding elementary matrices therefore generate the general linear group. Now you can find pre-images in ${\mathrm Aut}(F_{n})$ by considering Nielsen transformations, which match up fairly directly with the ...

4

1) $G = \bigoplus_{i=1}^{\infty} \mathbb{Z}/2\mathbb{Z}$ is residually finite but not Hopfian. It is clearly not Hopfian, and any non-identity element $g$ must have $g_i \neq 0$ for at least one $i$. Then $\pi_i(G) \cong \mathbb{Z}/2\mathbb{Z}$ is a finite quotient in which the image of $g$ is nontrivial. 2) An infinitely generated free group is ...

4

Yes if you assume a group has a normal subgroup $Z$ of finite index which is infinite cyclic then it's much easier. If $Z$ is central, then a classical theorem shows that the derived subgroup is finite. So modding out by the derived subgroup, you get an abelian group, and eventually get that the group has a homomorphism onto $\mathbf{Z}$ (with finite kernel, ...

4

There are a lot of connections in geometric group theory, which studies things like free groups. Every hyperbolic group (an infinite group with a special condition) has a space at infinity that is either a sphere or a fractal. For instance, the free group has a cantor set at infinity. Other groups have Sierpinski curves and Menger sponges. Space-filling ...

4

Here is one way to prove it: 1) If the triangle group is uniform, then Milnor-Schwarz shows that it is word-hyperbolic (since it acts properly discontinuously and cocompacty by isometries on the hyperbolic plane). 2) If the triangle group is nonuniform, then we can argue as follows: a) There is a single quasi-isometry class of nonuniform lattices in ...

4

I think the answer is yes unless one of the groups is trivial or both have order 2. Suppose $1\neq g\in G$ and $1\neq h_1,h_2\in H$ with $h_1\neq h_2$. Then for any $n$, the $2^n$ (exponential in $n$) elements $gh_{i_1}gh_{i_2}\dots gh_{i_n}$ of $G\ast H$ are all different.

Only top voted, non community-wiki answers of a minimum length are eligible


text:
# Tkinter stopwatch

As part of a personal project, I wanted to make a stopwatch with Python. I wish to show my friend but at the moment it is a little messy and long. Is there any way to make it more compact or easier to read?

    #stopwatch

from tkinter import*
import time

root=Tk()
root.configure(background=("black"))
root.title("stopwatch")
root.geometry("1000x800")
time_elapsed1=0
time_elapsed2=0
time_elapsed3=0
i=0
j=0
time1=0

def create_label(text,_x,_y):
label = Label(root, text=text,fg='white', bg="black",font=("default",10,"bold"))
label.place(x=_x,y=_y,width=100,height=45)
def start():
start_button.place_forget()
stop_button.place(x = 20, y = 300, width=300, height=100)
global time_elapsed1,time_elapsed2,time_elapsed3,time1,self_job,time2
time2=int(time.time())
if time2!=time1:
time1=time2
if time_elapsed1<59:
time_elapsed1+=1
clock_frame.config(text=str(time_elapsed3) + ":" + str(time_elapsed2)+ ":" + str(time_elapsed1))
else:
time_elapsed1=0
if time_elapsed2<59:
time_elapsed2+=1
clock_frame.config(text=(str(time_elapsed3) + ":" + str(time_elapsed2)+ ":" + str(time_elapsed1)))
else:
time_elapsed2=0
if time_elapsed3<23:
time_elapsed3+=1
clock_frame.config(text=(str(time_elapsed3) + ":" + str(time_elapsed2)+ ":" + str(time_elapsed1)))
else:
print("you left it on for too long")
self_job=root.after(1000,start)

def stop():
global self_job
if self_job is not None:
root.after_cancel(self_job)
self_job = None
stop_button.place_forget()
start_button.place(x = 20, y = 300, width=300, height=100)

def clear():
global time_elapsed1,time_elapsed2,time_elapsed3,time1,self_job,time2,label,i,j
try:
stop()
except:
start()
stop()
clock_frame.config(text="0:0:0")
time_elapsed1=0
time_elapsed2=0
time_elapsed3=0
time_1=0
time_2=0
i=0
j=0
wig=root.winfo_children()
for b in wig:
b.place_forget()
start_button.place(x = 20, y = 300, width=300, height=100)
lap_button.place(x = 660, y = 300, width=300, height=100)
reset_button.place(x = 340, y = 300, width=300, height=100)
clock_frame.place(x = 200, y = 50, width=600, height=200)

def lap():
global time_elapsed1,time_elapsed2,time_elapsed3,time1,self_job,time2,i,j
if i<9:
create_label((str(time_elapsed3)+":"+str(time_elapsed2)+ ":" + str(time_elapsed1)),20+(110*i),400+(j*50))
else:
j+=1
i=0
create_label((str(time_elapsed3)+":"+str(time_elapsed2)+ ":" + str(time_elapsed1)),20+(110*i),400+(j*50))
i+=1

clock_frame=Label(text="0:0:0",bg="black",fg="blue",font=("default",100,"bold"))
start_button=Button(text="START",bg="green",fg="black",command=start,font=("default",50,"bold"))
stop_button=Button(text="STOP",bg="red",fg="black",command=stop,font=("default",50,"bold"))
lap_button=Button(text="LAP",bg="#4286f4",fg="black",command=lap,font=("default",50,"bold"))
reset_button=Button(text="RESET",bg="orange",fg="black",command=clear,font=("default",50,"bold"))

start_button.place(x = 20, y = 300, width=300, height=100)
lap_button.place(x = 660, y = 300, width=300, height=100)
reset_button.place(x = 340, y = 300, width=300, height=100)
clock_frame.place(x = 200, y = 50, width=600, height=200)

root.mainloop()

• Welcome to Code Review! Self answers are welcome here, too: things to consider include the Style Guide for Python Code. – greybeard Mar 25 at 7:23
• Thanks, greybeard-will look into it – jayco 10125 Mar 25 at 14:15
• Can you add comments to the code you posted? It is a little hard to understand what each function or if/else block is doing. You will be more likely to get answers if you make it easy to understand what you need. – loganjones16 Mar 25 at 16:58

Have you learned how to make objects in Python? Typically when you have a GUI, you want to have a class in charge of displaying all the GUI pieces, and it has reference to an object such as a Stopwatch that takes care of all of the logic. Stopwatch class would look something like this:

import time

class Stopwatch:
def __init__(self):
self.start_time = 0
self.laps = []

def start(self):
# Implement your starting of the timer code here
self.start_time = time.time()

def lap(self):
lap = time.time()
self.laps.appen(lap)

def stop(self):
# Implement your stop timer logic
elapsed = time.time() - self.start_time

def reset(self):
# Implement your watch reset logic here
self.start_time = 0

def display_time(self):
# Return the time to display on the GUI
elapsed = time.time() - self.start_time
# Figure out how to break the time into hour:minute:second
# The time class might even have convenience functions for this sort of thing, look up the documentation
display = elapsed   # after you made it look nice
return display

Then in the GUI code you can make a Stopwatch object and let it take care of the messy work of saving times and doing math with them. The GUI class is just concerned with showing stuff the right way. Might look something like (minus positioning all the GUI components):

# GUI
root = Tk()
root.configure(background=("black"))
root.title("stopwatch")
root.geometry("1000x800")

stopwatch = Stopwatch()

def create_label(text,_x,_y):
label = Label(root, text=text,fg='white', bg="black",font=("default",10,"bold"))
label.place(x=_x,y=_y,width=100,height=45)

def setup():
pass
# Create all of the GUI components and build all the visuals

def start():
stopwatch.start()   # let it do the logical work
create_label(stopwatch.display_time())
stop_button.place()

def stop():
stopwatch.stop() # Logic and math here
# Do GUI updates for stop
create_label(stopwatch.display_time())

def clear():
stopwatch.reset()  # Logic again handled in the Stopwatch class
# Clean up GUI components

def lap():
# The Stopwatch class can keep a list of all lap times and make your life easier
stopwatch.lap()
# Next update the GUI
create_label(stopwatch.display_time())

# Good form to have all the logic run inside functions
#instead of hanging around to be accidentally executed
if __name__ == "__main__":
setup()
root.mainloop()

It will clean up your code and make it easier for you to make changes. The sooner you can learn how to use Objects, the easier your life will become, no matter the language! I leave it up to you to Google the best tutorials on Python objects.

Finally, if you are confused on where Stopwatch class should go, best practice would be to create a file called "stopwatch.py" and paste the Stopwatch class in that file. Then in your main file that is running the code, import that stopwatch by calling from stopwatch import Stopwatch. As long as the stopwatch.py file is right next to your main file, it should be able to import it.


text:
# Inspired by Patrick Corn

Calculus Level 4

$\large 1-2+3-4+5-6+\cdots$

The series $$\displaystyle \sum_{j=1}^{\infty} a_j$$ is said to be Cesàro summable, with Cesaro Sum $$A$$, if the average value of its partial sums $$\displaystyle s_k=\sum_{j=1}^k a_j$$ tends to $$A$$, meaning that $A=\lim_{n\to\infty}\frac{1}{n}\sum_{k=1}^ns_k$

Is the series $1-2+3-4+5-6 + \cdots$

Cesàro summable? If so, enter its Cesàro sum $$A$$. If not, enter 666.

×


text:
Fekete-Szeg\"{o} Functional Problems for Certain Subclasses of Bi-Univalent Functions Involving the Hohlov Operator

DOI：10.3770/j.issn:2095-2651.2020.01.001

 作者 单位 龙品红 宁夏大学数学统计学院, 宁夏 银川 750021 汤获 赤峰学院数学统计学院, 内蒙古 赤峰 024000 汪文帅 宁夏大学数学统计学院, 宁夏 银川 750021

本文介绍并研究了卷入Hohlov算子的双单值函数类$\sum$的新子类$\mathcal{N}^{a,b,c}_{\sum}(\mu,\lambda;\phi)$和$\mathcal{M}^{a,b,c}_{\sum}(\lambda;\phi)$与系数$a_2$和$a_3$的有界估计一样对应的Fekete-Szeg\"o泛函不等式也被得到.进而,与早期某些已知结果的因果关系和联系也将给出.

In the paper the new subclasses $\mathcal{N}^{a,b,c}_{\sum}(\mu,\lambda;\phi)$ and $\mathcal{M}^{a,b,c}_{\sum}(\lambda;\phi)$ of the function class $\sum$ of bi-univalent functions involving the Hohlov operator are introduced and investigated. Then, the corresponding Fekete-Szeg\"{o} functional inequalities as well as the bound estimates of the coefficients $a_2$ and $a_3$ are obtained. Furthermore, several consequences and connections to some of the earlier known results also are given.


text:
# An atom is a small unit of matter. A small atom measures about 0.0000000001 meter. How do you write the decimal as a power of 10?

Sep 15, 2016

Write the decimal in scientific notation using negative exponents.
$1 \times {10}^{-} 10$

#### Explanation:

A negative exponent means to divide.

This can be written as a fraction 1/ 1 000 000 0000

So $\frac{1}{10} ^ 10$


text:
If a school district paid a total of $35 per desk for ~$x$~ desks and a total of$30 per table for ~$y$~ tables, what was the total amount that the district paid for these desks and tables?

1. The total amount the district paid for the ~$y$~ tables was $900. 2. ~$x$~ = 90, and the total amount the district paid for the x desks was 3.5 times the total amount the district paid for the ~$y\$~ tables.

Statement (1) ALONE is sufficient, but statement (2) alone is not sufficient.

Statement (2) ALONE is sufficient, but statement (1) alone is not sufficient.

BOTH statements TOGETHER are sufficient, but NEITHER statement ALONE is sufficient.

EACH statement ALONE is sufficient.

Statements (1) and (2) TOGETHER are NOT sufficient.


text:
2019
DOI: 10.1109/lgrs.2018.2881102
View full text |Buy / Rent full text
|
|
et al.

## Abstract:Seismic reflectivity inversion is widely applied to improve the seismic resolution to obtain detailed underground understandings. Based on the convolution model, seismic inversion removes the wavelet effect by solving an optimization problem. Taking advantage of the sparsity property, the ℓ 1 norm is commonly adopted in the regularization terms to overcome the noise/interference vulnerability observed in the ℓ p-losses minimization. However, no one has provided a deterministic conclusion that ℓ 1 norm regulari… Show more

Help me understand this report

Search citation statements

Order By: Relevance

Paper Sections

Select...
2
1
1
1

Citation Types

0
9
0

Year Published

2020
2020
2021
2021

Publication Types

Select...
2
1

Relationship

0
3

Authors

Journals

##### Cited by 23 publications
(9 citation statements)
##### References 22 publications
(29 reference statements)
0
9
0
Order By: Relevance
“…In this paper, the selection of the regularization parameter is mainly based on the integrity and clarity of geological bodies in the spectral amplitude slice of horizon as a quality-control standard. How to pick a reasonable p and the regularization parameter adaptively (e.g., Li et al 2019) is also worth studying in the future.…”
Section: Discussionmentioning
confidence: 99%
“…In this paper, the selection of the regularization parameter is mainly based on the integrity and clarity of geological bodies in the spectral amplitude slice of horizon as a quality-control standard. How to pick a reasonable p and the regularization parameter adaptively (e.g., Li et al 2019) is also worth studying in the future.…”
Section: Discussionmentioning
confidence: 99%
“…The sparsity of seismic data is difficult to estimate in practice and the adequacy of the 1 norm for the reflectivity inversion problem has not been established [8], [19]. Also, 1 -norm regularization results in a biased estimate of x [20], [21], [22].…”
Section: A Prior Artmentioning
confidence: 99%
“…The advantages of adopting nonconvex regularizers over 1 have been demonstrated in sparse recovery problems [22], [24], [25]. Particularly pertinent to this discussion is the data-driven q -norm regularization (0 < q < 1) for seismic reflectivity inversion proposed by [19], wherein the optimal q was chosen based on the input data.…”
Section: A Prior Artmentioning
confidence: 99%
See 1 more Smart Citation
“…The fast iterative shrinkage-thresholding algorithm (FISTA) [11] has been employed for reflectivity inversion [12] along with an amplitude recovery boost through debiasing steps of least-squares inversion [13] and "adding back the residual" [14]. The 1 -norm, although convex, is not the best sparsity constraint for reflectivity inversion, and the accurate estimation of the sparsity of seismic reflections is challenging [15], [16]. Further, 1 -norm regularization underestimates the high-amplitude components and introduces a bias in the estimate of the sparse code x [17], [18], [19].…”
Section: Introductionmentioning
confidence: 99%


text:
Home How to properly update active record in ruby

# How to properly update active record in ruby

jose1221
1#
jose1221 Published in 2018-02-02 22:48:51Z
 I have model having update method as def udpate_something(params) update(id: params[:id], b: params[:b], c: params[:c], d: params[:d]) end  and in controller def update Model.find(id: params[:id]) .update_something(id: params[:id] b: params[:b], c: params[:c], d: params[:d]) end  Is this the right way to update or there is a better way?
Tom Lord
2#
Tom Lord Reply to 2018-02-02 23:04:15Z
 Firstly, it should be very rare (i.e. virtually unheard of!) to update the id (primary key) of a record. This is a record's identifier; by changing this, you'll mess up any associations and potentially cause a conflict with another record's id. Also, your udpate_something [SIC] method doesn't really achieve anything. It's a wrapper method that serves no purpose. Why not just do: def update Model.find(id: params[:id]) .update(b: params[:b], c: params[:c], d: params[:d]) end  Your controller method doesn't handle error messages, use strong parameters (!!) or perform any render/redirect action - but that's a separate story. There's no generic "right thing to do" across all controller actions; it really depends on what you're trying to achieve! I'd suggest looking through some basic material such as the rails documentation to see how controllers are typically structured.
 You need to login account before you can post.
Processed in 0.295273 second(s) , Gzip On .


text:
# A curious equality of integrals involving the prime counting function?

This post discusses the integral, $$I(k)=\int_0^k\pi(x)\pi(k-x)dx$$

where $$\pi(x)$$ is the prime-counting function. For example, $$I(13)=\int_0^{13}\pi(x)\pi(13-x)dx = 73$$

Using WolframAlpha, the first 50 values for $$k=1,2,3,\dots$$ are,

$$I(k) = 0, 0, 0, 0, 1, 4, 8, 14, 22, 32, 45, 58, 73, 90, 110, 132, 158, 184, 214, 246, 282, 320, 363, 406, 455, 506, 562, 618, 678, 738, 804, 872, 944, 1018, 1099, 1180, 1269, 1358, 1450, 1544, 1644, 1744, 1852, 1962, 2078, 2196, 2321, 2446, 2581, 2718,\dots$$

While trying to find if the above sequence obeyed a pattern, I noticed a rather unexpected relationship:

Q: For all $$n>0$$, is it true, $$I(6n+4) - 2\,I(6n+5) + I(6n+6) \overset{\color{red}?}= 0$$

Example, for $$n=1,2$$, then $$I(10)-2I(11)+I(12)=32-2*45+58 = 0$$ $$I(16)-2I(17)+I(18)=132-2*158+184= 0$$ and so on.

• Note your proposed equation doesn't hold for $n = 0$ as $I(4) = 0$, $I(5) = 1$ and $I(6) = 4$. – John Omielan Feb 27 '19 at 4:04
• @JohnOmielan: A typo. I meant all $n>0$. I will correct it. – Tito Piezas III Feb 27 '19 at 4:09
• I have checked to confirm what you're asking is true for $n$ up to $18$. However, I have my doubts it'll always work, partially because it doesn't work for $n = 0$. Also, a similar type condition is that $I(6n) - 2I(6n + 1) + I(6n + 2) = 2$, which holds for $1 \le n \le 5$, but at $n = 6$, the LHS becomes $0$ instead. If I get a chance, I will investigate your equation to see if I can figure out why it's true for at least the first $18$ values and, more importantly, will it always stay true. Regardless, though, it's an excellent observation you've made, even if it doesn't always hold. – John Omielan Feb 27 '19 at 4:47
• I checked your result up to $n=533$ (for $n \geq 534$, I have problems. Would you be interested by a huge table of $I(k)$ (I was able to generate it up to $k=540$). This is a very interesting problem. – Claude Leibovici Feb 27 '19 at 5:06
• Up to $k=540$, $I(k)$ is a prime for this list $$\{13,57,119,167,171,173,175,341,395,397,427,431,473,515,519\}$$ – Claude Leibovici Feb 27 '19 at 8:13

The answer is yes. Sketch of solution: $$I(k) = \int_0^k \sum_{p\le x} \sum_{q\le k-x} 1 \,dx = \sum_p \sum_{q\le k-p} \int_p^{k-q} dx = \sum_p \sum_{q\le k-p} (k-(p+q)) = \sum_{m\le k} r(m)(k-m),$$ where $$r(m)$$ is the number of ways of writing $$m$$ as the sum of two primes. Then \begin{align} I(6n+6) &{}-2I(6n+5)+I(6n+4) \\ &= \sum_{m \le 6n+4} r(m)\big((6n+6-m)-2(6n+5-m) +(6m+4-m)\big) + r(6n+5) \\&= 0 + r(6n+5); \end{align} and $$r(6n+5)=0$$ for every $$n\ge1$$, since the only way the odd integer $$6n+5$$ can be the sum of two primes is $$6n+5=2+(6n+3)$$, but $$6n+3=3(2n+1)$$ is always composite when $$n\ge1$$.
The same argument gives $$I(6n+2)-2I(6n+1)+I(6n) = r(6n+1)$$, which is $$2$$ if $$6n-1$$ is prime and $$0$$ otherwise; this is why (as observed by John Omielan) it equals $$2$$ for $$1\le n\le 5$$ but $$0$$ for $$n=6$$.
• Greg, do you know how to address Ultradark's question regarding when $I(k)$ is prime? – Tito Piezas III Feb 27 '19 at 5:31


text:
• 5-Day Free Trial
5-day free, full-access trial TTP Quant

Available with Beat the GMAT members only code

• 1 Hour Free
BEAT THE GMAT EXCLUSIVE

Available with Beat the GMAT members only code

• Free Veritas GMAT Class
Experience Lesson 1 Live Free

Available with Beat the GMAT members only code

• Free Practice Test & Review
How would you score if you took the GMAT

Available with Beat the GMAT members only code

• Get 300+ Practice Questions

Available with Beat the GMAT members only code

• Magoosh
Study with Magoosh GMAT prep

Available with Beat the GMAT members only code

• Free Trial & Practice Exam
BEAT THE GMAT EXCLUSIVE

Available with Beat the GMAT members only code

• FREE GMAT Exam
Know how you'd score today for $0 Available with Beat the GMAT members only code • 5 Day FREE Trial Study Smarter, Not Harder Available with Beat the GMAT members only code • Award-winning private GMAT tutoring Register now and save up to$200

Available with Beat the GMAT members only code

Which of the following employs reasoning most similar to the

This topic has 0 member replies
BTGmoderatorAT Moderator
Joined
22 Aug 2017
Posted:
426 messages
Followed by:
1 members

Which of the following employs reasoning most similar to the

Wed Dec 06, 2017 6:17 am
A recurring account in a commercial bank is a great investment because it allows a person to accumulate a large sum over a period of time. All people who have become wealthy through their investments have invested in a recurring account.

Which of the following employs reasoning most similar to the one above?

(A) This quadrilateral may be a rectangle because quadrilaterals and rectangles have many properties in common. For one, all rectangles are quadrilaterals but all quadrilaterals are not rectangles.
(B) Training wheels on a bicycle typically do more harm than good because they make it harder for a child to learn to ride a bike. Training wheels provide too much support and thereby make it very difficult for a child to develop a sense of balance.
(C) Algebra is a valuable subject because it helps you to score high on the GMAT quantitative section. All those who know algebra well score highly in the quantitative section of the GMAT.
(D) Penicillin is a useful drug because it helps cure many diseases. Penicillin kills the bacteria that cause these diseases.
(E) The hit-and-run approach in the game of cricket is ineffective because the teams who use it usually lose. Coaches ask the players to refrain from using the hit-and-run technique.

What's the best approach to determine the answer? Can any experts explain?

Top First Responders*

1 GMATGuruNY 65 first replies
2 Rich.C@EMPOWERgma... 46 first replies
3 Brent@GMATPrepNow 41 first replies
4 Jay@ManhattanReview 24 first replies
5 Terry@ThePrinceto... 10 first replies
* Only counts replies to topics started in last 30 days
See More Top Beat The GMAT Members

Most Active Experts

1 GMATGuruNY

The Princeton Review Teacher

129 posts
2 Rich.C@EMPOWERgma...

EMPOWERgmat

114 posts
3 Jeff@TargetTestPrep

Target Test Prep

98 posts
4 Scott@TargetTestPrep

Target Test Prep

92 posts
5 Max@Math Revolution

Math Revolution

89 posts
See More Top Beat The GMAT Experts