text:
## Tuesday, May 29, 2007

### Parameterizing Test Methods - Revisited

In my last post on refactoring and unit tests, Steve Freeman noted in one of his blog comments ..

I can't see the point in the data provider. Why don't you just call the method three times with different arguments?

In the process of refactoring, I had used TestNG's parameterized test method feature to decouple test data from test methods. While invoking a test method multiple times with different parameter gives me the same functional result, parameterized test methods provide great scalability and a neat separation between the test logic and test data suite. Complex business methods may involve lots of complicated calculations and conditionals - a unit test of the method needs to ensure all conditionals are exercised to ensure full coverage. This may result in lots of data combinations, which if handled directly through separate invocations of the same test methods may result in real explosion of test cases.

The feature of parameterizing test methods in TestNG through DataProviders provide a great way to DRY up the test methods. I can have the test data combination either in testNG.xml or in separate factory methods with specific signatures that provide huge extensibility. The test method can then have parameters and an annotation that specify the data source. Take the following example from the earlier post :

public class AccruedInterestCalculatorTest extends MockControl {  //..  @DataProvider(name = "test1")  public Object[][] createAccruedInterestCalculationData() {    return new Object[][] {      {20, BigDecimal.valueOf(0.5), BigDecimal.valueOf(1000), BigDecimal.valueOf(30)},      {20, BigDecimal.valueOf(0.5), BigDecimal.valueOf(2000), BigDecimal.valueOf(60)},      {30, BigDecimal.valueOf(0.5), BigDecimal.valueOf(2000), BigDecimal.valueOf(90)},    };  }  //..  // the test method now accepts parameters  //..  @Test(dataProvider = "test1")  public void normalAccruedInterest(int days,    BigDecimal rate, BigDecimal principal, BigDecimal interestGold) {    new CalculatorScaffold()      .on(principal)      .forDays(days)      .at(rate)      .calculate()      .andCheck(interestGold);  }  //..}

The calculation of the accrued interest is an extremely complicated business method which needs to consider lots of alternate routes of computation and contextual data. A typical data set for testing the calculation effectively will result in repeating the test method invocation lots of times. Instead of that, the parameterization technique allows me to declare all the varying components as parameters of the test method. And the data source comes from the method createAccruedInterestCalculationData(), suitably annotated with a data source name.

Making the test method parameterized has the additional side-effect of decoupling the data set from the logic - the entire data set can be populated by non-programmers as well, typically domain guys who can enrich the test coverage by simply putting in additional data points in the factory method that generates the data. We have actually used this technique in a real life project where domain experts took part in enriching parameterized unit test cases through data fulfillment in data provider methods.

There's actually more to it. The data provider method can be used to fetch data from other complicated data sources as well e.g. database, XML etc. and with logic to generate data also. All these can be encapsulated in the DataProvider methods and transparently fed to the test methods. The logic of test data generation is completely encapsulated outside the test method. I found this feature of TestNG a real cracker ..

## Sunday, May 20, 2007

### Refactoring Unit Test Methods to speak the Domain

I do TDD, but I do not start writing unit tests before writing production code. It's not that I didn't try - I gave it an honest attempt for quite some time, before I gave up. Somehow the approach of writing tests first does not seem intuitive to me. At least I need to figure out the collaborators and the initial subset of public contracts before my TestNG plugin kicks in. Since then, it's all a game of collaborative pingpong between my production code and test code. Having said that, I honestly believe that an exhaustive unit test suite is no less important than the code itself. I take every pain to ensure that my unit tests are well organized, properly refactored and follow all principles of good programming that I espouse while writing the actual production code.

Refactoring is one practice that I preach, teach and encourage vigorously to my teammates. Same for unit tests - if I strive to make my production code speak the language of the domain, so should be my unit tests. This post is about a similar refactoring exercise to make unit tests speak the DSL. At the end of this effort of vigorous iterations and cycles of refactoring, we could achieve a well engineered unit test suite, which can probably be enhanced by the domain guys with minimum of programming knowledge.

The Class Under Test

The following is the fragment of a simplified version of an AccruedInterestCalculator, a domain class, which calculates the interest accrued for a client over a period of time. For brevity, I have a very simplified version of the class with only very simple domain logic. The idea is to develop a fluent unit test suite for this class that speaks the domain language through an iterative process of refactoring. I will be using the artillery consisting of the state of the art unit testing framework (TestNG), a dynamic mocking framework (EasyMock) and the most powerful weapon in programming - merciless refactoring.

public class AccruedInterestCalculator {  //..  //..  private IAccruedDaysCalculator accruedDaysCalculator;  private IInterestRateCalculator interestRateCalculator;   public final BigDecimal calculateAccruedInterest(final BigDecimal principal)     throws NoInterestAccruedException {    int days = accruedDaysCalculator.calculateAccruedDays();    if (days == 0) {      throw new NoInterestAccruedException("Zero accrual days for principal " + principal);    }    BigDecimal rate = interestRateCalculator.calculateRate();    BigDecimal years = BigDecimal.valueOf(days).divide(BigDecimal.valueOf(365), 2, RoundingMode.UP);    return principal.multiply(years).multiply(rate);  }  AccruedInterestCalculator setAccruedDaysCalculator(IAccruedDaysCalculator accruedDaysCalculator) {    this.accruedDaysCalculator = accruedDaysCalculator;    return this;  }  AccruedInterestCalculator setInterestRateCalculator(IInterestRateCalculator interestRateCalculator) {    this.interestRateCalculator = interestRateCalculator;    return this;  }}

and the two collaborators ..

public interface IAccruedDaysCalculator {  int calculateAccruedDays();}public interface IInterestRateCalculator {  BigDecimal calculateRate();}

Mocks are useful, but Noisy ..

I am a big fan of using mocks for unit testing - EasyMock is my choice of dynamic mocking framework. Mocks provide the most seamless way of handling collaborators while writing unit tests for a class. However, often, I find mocks introducing lots of boilerplate codes which need to be repeated for every test method that I write ..

public class AccruedInterestCalculatorTest {  protected IMocksControl mockControl;   @BeforeMethod  public final void setup() {    mockControl = EasyMock.createControl();  }   @Test  public void normalAccruedInterestCalculation() {    IAccruedDaysCalculator acalc = mockControl.createMock(IAccruedDaysCalculator.class);    IInterestRateCalculator icalc = mockControl.createMock(IInterestRateCalculator.class);     expect(acalc.calculateAccruedDays()).andReturn(2000);    expect(icalc.calculateRate()).andReturn(BigDecimal.valueOf(0.5));     mockControl.replay();     BigDecimal interest =      new AccruedInterestCalculator()        .setAccruedDaysCalculator(acalc)        .setInterestRateCalculator(icalc)        .calculateAccruedInterest(BigDecimal.valueOf(2000.00));     mockControl.verify();  }}

Refactoring! Refactoring!

Have a look at the above test method - the mock framework setup and controls pollute the actual business logic that I would like to test. Surely, not a very domain friendly approach. As Howard has pointed to, in one of his NFJS writings, we can abstract away the mock stuff into separate methods within the test class, or still better in a separate MockControl class altogether. This makes the actual test class lighter and free of some of the noise. Here is the snapshot after one round of refactoring ..

// mock controls delegated to class MockControlpublic class AccruedInterestCalculatorTest extends MockControl {   @BeforeMethod  public final void setup() {    mockControl = EasyMock.createControl();  }   @Test  public void normalAccruedInterestCalculation() {    IAccruedDaysCalculator acalc = newMock(IAccruedDaysCalculator.class);    IInterestRateCalculator icalc = newMock(IInterestRateCalculator.class);     expect(acalc.calculateAccruedDays()).andReturn(2000);    expect(icalc.calculateRate()).andReturn(BigDecimal.valueOf(0.5));     replay();     BigDecimal interest =      new AccruedInterestCalculator()        .setAccruedDaysCalculator(acalc)        .setInterestRateCalculator(icalc)        .calculateAccruedInterest(BigDecimal.valueOf(2000.00));     verify();  }}

and the new MockControl class ..

public abstract class MockControl {  protected IMocksControl mockControl;   protected final <T> T newMock(Class<T> mockClass) {    return mockControl.createMock(mockClass);  }   protected final void replay() {    mockControl.replay();  }   protected final void verify() {    mockControl.verify();  }}

The test class AccruedInterestCalculatorTest is now cleaner and the test method is lighter in baggage from the guts of the mock calls. But still it is not sufficiently close to speaking the domain language. One of the litmus tests which we often do to check the domain friendliness of unit tests is to ask a domain guy to explain the unit test methods (annotated with @Test) and, if possible, to enhance them. This will definitely be a smell to them, with the remaining litterings of mock creation and training still around. The domain guy in this case, nods a big NO, Eclipse kicks in, and we start the next level of refactoring.

One thing strikes me - each test method is a composition of the following steps :

1. create mocks

2. setup mocks

3. replay

4. do the actual stuff

5. verify

And refactoring provides me the ideal way to scaffold all of these behind fluent interfaces for the contract that we plan to test. How about a scaffolding class that encapsulates these steps ? I keep the scaffold as a private inner class and try to localize all the mockeries in one place. And the scaffold can always expose fluent interfaces to be used by the test methods. Here is what we have after a couple of more rounds of iterative refactoring ..

public class AccruedInterestCalculatorTest extends MockControl {  private IAccruedDaysCalculator acalc;  private IInterestRateCalculator icalc;   @BeforeMethod  public final void setup() {    mockControl = EasyMock.createControl();    acalc = newMock(IAccruedDaysCalculator.class);    icalc = newMock(IInterestRateCalculator.class);  }   // the scaffold class encapsulating all mock methods  private class CalculatorScaffold {    private BigDecimal principal;    private int days;    private BigDecimal rate;    private BigDecimal interest;     CalculatorScaffold on(BigDecimal principal) {      this.principal = principal;      return this;    }     CalculatorScaffold forDays(int days) {      this.days = days;      return this;    }     CalculatorScaffold at(BigDecimal rate) {      this.rate = rate;      return this;    }     CalculatorScaffold calculate() {      expect(acalc.calculateAccruedDays()).andReturn(days);      expect(icalc.calculateRate()).andReturn(rate);      replay();       interest =        new AccruedInterestCalculator()        .setAccruedDaysCalculator(acalc)        .setInterestRateCalculator(icalc)        .calculateAccruedInterest(principal);       verify();      return this;    }     void andCheck(BigDecimal interestGold) {      assert interest.compareTo(interestGold) == 0;    }  }  //..  //.. the actual test methods   @Test  public void normalAccruedInterest() {    new CalculatorScaffold()      .on(BigDecimal.valueOf(1000.00))      .forDays(days)      .at(BigDecimal.valueOf(0.5))      .calculate()      .andCheck(BigDecimal.valueOf(30.0));  }  @Test  public void normalAccruedInterest() {      new CalculatorScaffold()      .on(BigDecimal.valueOf(2000.00))      .forDays(days)      .at(BigDecimal.valueOf(0.5))      .calculate()      .andCheck(BigDecimal.valueOf(60.0));  }  //..  //.. other methods}

This class has test methods which now look more closer to the domain, with all mock controls refactored away to the scaffold class. Do you think the domain guys will be able to add more methods to add to the richness of coverage ? The accrued interest calculation is actually quite complicated with more collaborators and more domain logic than what I have painted here. Hence it is quite natural that we need to enrich the test cases with more possibilities and test coverage. Instead of making separate methods which work on various combinations of days, rate and principal (and other factors in reality), why not DRY them up with parameterized tests ?

Parameterized Tests in TestNG

TestNG provides a great feature for providing parameters in test methods using the DataProvider annotation. DRY up your test methods with parameters .. here is what it looks like in our case ..

public class AccruedInterestCalculatorTest extends MockControl {  private IAccruedDaysCalculator acalc;  private IInterestRateCalculator icalc;   @BeforeMethod  public final void setup() {    mockControl = EasyMock.createControl();    acalc = newMock(IAccruedDaysCalculator.class);    icalc = newMock(IInterestRateCalculator.class);  }   @DataProvider(name = "test1")  public Object[][] createAccruedInterestCalculationData() {    return new Object[][] {      {20, BigDecimal.valueOf(0.5), BigDecimal.valueOf(1000), BigDecimal.valueOf(30)},      {20, BigDecimal.valueOf(0.5), BigDecimal.valueOf(2000), BigDecimal.valueOf(60)},      {30, BigDecimal.valueOf(0.5), BigDecimal.valueOf(2000), BigDecimal.valueOf(90)},    };  }  private class CalculatorScaffold {    //..    //.. same as above  }   // the test method now accepts parameters  //..  @Test(dataProvider = "test1")  public void normalAccruedInterest(int days,     BigDecimal rate, BigDecimal principal, BigDecimal interestGold) {    new CalculatorScaffold()      .on(principal)      .forDays(days)      .at(rate)      .calculate()      .andCheck(interestGold);  }   @Test(expectedExceptions = {NoInterestAccruedException.class})  public void zeroAccruedDays() {    new CalculatorScaffold()      .on(BigDecimal.valueOf(2000))      .forDays(0)      .at(BigDecimal.valueOf(0.5))      .calculate()      .andCheck(BigDecimal.valueOf(90));  }}

The test methods look DRY, speak the domain language and do no longer have to administer the mock controls. All test conditions and results are now completely decoupled from the test methods and fed to them through the annotated provider methods. Now the domain guy is happy!

## Thursday, May 10, 2007

### XML - Not for Human Consumption

I have never been a big fan of using XML as a language for human interaction. I always felt that XML is too noisy for human comprehension and never a pleasing sight for your eyes. In an earlier post I had pitched in with the idea of using Lisp s-expressions as executable XML instead of the plethora of angle brackets polluting your comprehension power. XML is meant for machine interpretation, the hierarchical processing of XML documents gives you the raw power when you are programming for the machine. But, after all, Programs must be written for people to read, and only incidentally for machines to execute (from SICP).

With the emergence of the modern stream of scripting languages, XML is definitely taking a backseat in handling issues like software builds and configuration management. People are no longer amused with the XML hell of Maven and have been desperately looking for alternatives. Buildr, a drop-in replacement for Maven uses Ruby (inspired by Rake), SCons uses Python scripts, Groovy has also been used in the configuration space for Jini-based ComputeCycles project (via Artima). XML has also started looking like just yet another option for configuring your beans in the Spring community. We are just spoilt with other options of configuration - Spring JavaConfig uses Java configuration, Springy does it with JRuby, Groovy SpringBuilder does it with Groovy.

Configuration and builds of systems are nontrivial activities and need a mix of both declarative and procedural programming. Using XML as the brute force approach towards this has resulted in complex hierarchical structures, too complex for human comprehension. A perfect example in hand is Maven which attempts to do too many things with XML. The result is extremely complex XML hell much to the anguish of developers and build managers. A big build system configured using Maven becomes a maintenance nightmare in no time.

People are getting increasingly used to the comforts of DSLs and configurations of large systems have never been too trivial an artifact. Hence it is logical that we would like to have something which provides a cool humane interface. And XML is definitely not one of them ..

## Wednesday, May 02, 2007

### Unit Tests - Another Great Tool for Refactoring

In my last post on unit testing, I had talked about some techniques on how to make your classes unit test friendly. Unit testing is the bedrock of writing good software - never compromise on writing unit tests for the next class that you design. Unit testing is about testing classes in isolation - get them out of the natural environment and take them for a ride. That way unit tests give you a feedback about the correctness of the behavior of the *unit* as a whole. The other aspect of unit tests which I find extremely useful while designing classes is the support for refactoring. Unit tests are great vehicles for refactoring object collaborations - thus there is a 2-way feedback loop between class design and its unit test design. And once you have cycled through rounds of iteration in this feedback loop, you can expect to have stabilized your abstractions and collaborations.

Here's an example ..

class Payroll {  // ..  // ..  void calculateSalary(Employee emp) {    BigDecimal charge = emp.getSalary();    // calculate total salary including taxes  }}

When I look at the possible unit test for the class Payroll, the first thing that strikes me is the argument Employee in calculateSalary(). The first attempt tries to instantiate an Employee and invoke the method calculateSalary() from the test case :

class PayrollTest extends TestCase {  // ..  // ..  public void testSalaryCalculation() {    Employee emp = new Employee(..);    // ..   }}

A Mockery of sorts ..

Instantiating an Employee object brings into action lots of other machineries like the database layer, the ORM layer etc., which we already know should be best kept away from the unit test harness. Think Mocks ..

When you need to mock a concrete class, take a second look, if necessary take a third look as well. Mock roles, not objects and roles are best specified through interfaces. In the above example, we are really exploiting the fact that an employee is salaried and has a basic salary component for being employed in a company. In this method calculateSalary(), we are not concerned with the other details of the Employee class, which may be used in other context within the software.

Extract Interface

Now I have a new interface Salaried as :

interface Salaried {  BigDecimal getBasicSalary();}

and ..

public class Employee implements Salaried {  // ..}

The method calculateSalary() now takes an interface Salaried instead of the concrete class Employee - and the mock becomes idiomatic in the test case (I am using EasyMock as the mocking framework) :

class Payroll {  // ..  // ..  public void calculateSalary(Salaried emp) {    // ..  }}class PayrollTest extends TestCase {  // ..  // ..  public void testSalaryCalculation() {    IBillable mock = createMock(Salaried .class);    expect(mock.getBasicSalary()).andReturn(BigDecimal.valueOf(7000));    replay(mock);    // ..   }}

Thus unit testing helped me use the Extract Interface principle and improve the collaboration between my classes. Notice how the class Payroll now collaborates with a more generic role Salaried instead of a concrete class Employee. Tomorrow if the company decides to employ contractors with different salary computation, we will have a separate abstraction :

public class Contractor implements Salaried {  // ..  // ..  BigDecimal getBasicSalary() {    // .. different implementation than Employee  }  // ..}

but the class Payroll remains unaffected, since it now collaborates with Salaried and NOT any concrete implementation.


text:
# How do you evaulate 17\times \frac { 1} { 4} ?

Mar 3, 2018

See below.

#### Explanation:

Since this equation has a whole number being multiplied by a fraction, you must first make that whole number into a fraction as well. Let's pretend the number is $2$. $2$ is the same as if you had instead written $\frac{2}{1}$. So, $17$ would be the same thing as if you had written $\frac{17}{1}$. This is because it is saying that $1$ can go into $17$, $17$ times.

The equation you have now is

$\frac{17}{1} \cdot \frac{1}{4}$

Now, to multiply a fraction, you must multiply the numerators by the numerators, and the denominaters by the denominaters.

$\frac{17 \cdot 1}{1 \cdot 4}$

From this, you will get the fraction $\frac{17}{4}$, which is your answer.

format: plain


text:
# Artin motives, References for.

I find the following description of Artin motives in Wikipedia. Since these seem to be quite related to number theory, I am interested to learn more in that context. I request the experts available in MO to provide me a reference which can be more useful to me than this terse description. Any comments and explanations also will be helpful. I apologize for asking a seemingly basic question; but I find it impossible to wade through the numerous references available on motives.

Fix a field $k$ and consider the functor finite separable extensions $K$ of $k$ → finite sets with a (continuous) action of the absolute Galois group of $k$ which maps $K$ to the (finite) set of embeddings of $K$ into an algebraic closure of $k$. In Galois theory this functor is shown to be an equivalence of categories. Notice that fields are $0$-dimensional. Motives of this kind are called Artin motives. By $\mathbb Q$-linearizing the above objects, another way of expressing the above is to say that Artin motives are equivalent to finite $\mathbb Q$-vector spaces together with an action of the Galois group.

I have some idea of what are pure motives and mixed motives, in the context of algebraic varieties. What I exactly have in mind is to understand the modern statement of equivariant Tamagawa number conjecture. This would appear to be the simplest instance to keep in mind, if I go ahead.

-
I remember there was something on Artin motives in Yves Andre's book. –  Evgeny Shinder Jan 15 '10 at 23:15
Thanks, I will look into it(though I am French-handicapped). –  Anweshi Jan 15 '10 at 23:19

André's book is the main reference for the "yoga" of motives. You'll find a description of Artin motives in the Voevodsky formalism in

Beilinson and Vologodsky - http://www.math.uiuc.edu/K-theory/0832/

Wildehaus - http://www.math.uiuc.edu/K-theory/0918/

From the tannakian view point, Artin motives are just representation of the usual Galois group. So, as motives, Artin motives are not that interesting. It's just the usual Galois theory of fields.

-
This was very helpful. So it is just a motivic picture of the usual Galois theory; just a different way of looking at a simpler thing? –  Anweshi Jan 15 '10 at 23:43
Yes it is. Artin motives are motives of 0-dimensional varieties: the (products of) H^0(L/K) for finite extensions L/K. Grothendieck's vision of motives was as a universal cohomolgy theory but also as higher dimensional version of Galois theory. From the tannakian point of view, the inclusion of Artin motives in all motives corresponds to the fact that the absolute Galois group (seen as the pro-algebraic group limproj Sepc(Q[Gal(L/K)]^*)) is a quotient of the motivic Galois group of K. –  AFK Jan 16 '10 at 0:56
Thanks for the explanation. So if I understood correctly, Artin motives introduce a geometric Galois theory, suitably integrated into a bigger picture according to the visions of Grothendieck. –  Anweshi Jan 16 '10 at 6:25
To YBL: One small nitpick. It seems to me that 'permutation representation' is not good terminology here. As I understand it, this could refer either to a realization as a group of permutations or a linear representation naturally associated to such a realization. Of course many linear representations are not of this form. Importantly, no non-trivial irreducible representation is of this form. Since the category of motives is supposed to induce a decomposition of varieties into 'irreducible objects' in some suitable sense, it's important to draw this distinction. –  Minhyong Kim Jan 16 '10 at 10:36
You're right this wasn't clear. I meant "permutative Q[G]-module" as in Beilinson and Vologodsky's notes par 2.4. –  AFK Jan 16 '10 at 12:02

A motive is a chunk of a variety cut out by correspondences. (If you like, it is something of which we can take cohomology.)

Artin motives are what one gets by restricting to zero-dimensional varieties. If the ground field is algebraically closed then zero-dimensional varieties are simply finite unions of points, so there is not much to say; the only invariant is the number of points.

But if the ground field $K$ is not algebraically closed (but is perfect, e.g. char $0$, so that we can describe all finite extensions by Galois theory), then there are many interesting $0$-dimensional motives, and in fact the category of Artin motives (with coefficients in a field $F$ of characteristic $0$, say) is equal to the category of continuous representations of $Gal(\overline{K}/K)$ on $F$-vector spaces (where the $F$-vector spaces are given their discrete topoogy; in other words, the representation must factor through $Gal(E/K)$ for some finite extension $E$ of $K$).

Perhaps from a geometric perspective, these motives seem less interesting than others. On the other hand, number theoretically, they are very challenging to understand. The Artin conjecture about the holomorphicity of $L$-functions of Artin motives, which is the basic reciprocity conjecture regarding such motives, remains very wide open, with very few non-abelian cases known. (Of course, for representations with abelian image, these conjectures amount to class field theory, which is already quite non-trivial.)

-
Thanks, this was very helpful. As I mentioned, the aim was to get to the equivariant Tamagawa number conjecture. Are there any specific suggestions towards that? –  Anweshi Jan 16 '10 at 2:50
The conjecture on Artin L-functions does not follow from Khare's work on Serre's conjectures? –  Anweshi Jan 16 '10 at 3:07
The case of 2-dimensional odd representations, in the case $K = {\mathbb Q}$, follows from Khare--Wintenberger--Kisin. This is an example of one of the very few non-abelian cases'' that are known. –  Emerton Jan 16 '10 at 4:02
@Emerton. Your answer was extremely helpful to me, and it was very enlightening to read it. However I am accepting YBL's answer since I had asked for references and he gave me some. I hope you don't mind. –  Anweshi Jan 16 '10 at 20:16
@Emerton. So are Artin motives just another way of looking at Galois representations defined over number fields? –  Anweshi Jan 16 '10 at 21:24


text:
# Chinese Remainder Theorem Modified

Suppose we have a set of n congruences of form $$X \equiv a1 \pmod p$$ $$X \equiv a2 \pmod q$$ $$X \equiv a3 \pmod r$$

where p, q, r are relatively prime. Let $$P = \Pi \hspace{5pt}p^aq^br^c$$

How can we calculate $$X \mod P$$

-

You can lift the original congruence into the form $$X \equiv a_1'\pmod {p^a}$$ where $a_1'$ belongs to the set of all residue classes such that $a_1' \equiv a_1 \pmod p$.

Do something similar for $q$ and $r$. Then applying the Chinese Remainder Theorem to $p^a,\ q^b$ and $r^c$ will give you the set of necessary results.

Note that there will be many solutions. In general we will have $p^{a-1}$ lifted congruence classes for the first congruence, $q^{b-1}$ for the second congruence and $r^{c-1}$ for the third. Each triplet will correspond to a unique solution giving a total of $p^{a-1}q^{b-1}r^{c-1}$ solutions modulo $P$.

-
Thanks for the help. Let's say we are given X % 3 = r(say) and I need to find X % 27. Is there any way to do it? –  Aayush Bahuguna Oct 28 '12 at 8:20
Yes, it would be the set of congruence classes $$\left\{r,\ r+3,\ r+6,\ \cdots,\ r+24\right\}$$ –  EuYu Oct 28 '12 at 8:22
With X given is it possible to find which congruence class X % 27 will belong? –  Aayush Bahuguna Oct 28 '12 at 8:25
Like I said, the solution is not unique. Suppose $X \equiv 2 \pmod 3$ then we cannot uniquely specify $X \pmod{27}$. All we can say is that $X$ will belong to one of the congruence classes $$X\in\left\{2,\ 5,\ 8,\ \cdots,\ 23,\ 26\right\}$$ –  EuYu Oct 28 '12 at 8:27
Wouldn't it be $p^{a-1}q^{b-1}r^{c-1}$ lifted congruences? For example, if we know $x\bmod{2}$ there are $2^{4-1}=8$ possible values of $y\bmod{2^4}$ so that $x\equiv y\pmod{2}$, not $2^{4-2}(2-1)+1=5$. –  robjohn Oct 28 '12 at 8:51
show 1 more comment

I do not think we can if $a,b,c\ge 2$.

Suppose $X\equiv 1\pmod{4}$. Can we find $X\pmod{16}$?

-
If that is all you know, and $a>1$, $b>1$ or $c>1$, then you can't.


text:
## Symptoms

Services like systemd-journald and systemd-logind show a failed state with error code 228/SECCOMP, and return an error message when attempted to be started using systemctl. This also caused journald logs to not be created or updated for any services.

## Problem

The problem on my… »

• ### An even smarterer html_truncate tag for Jekyll

As you know, I am using Jekyll to generate this blog. When setting mine up I read how Benjamin Thomas read how Jack Moffitt set up his Jekyll installation, and thought the idea of an html_truncate filter was pretty cool, and thought the… »

• ### Mini vMac with colour (on Linux)

As I posted some time ago, Mini vMac now supports colour display when emulating a Macintosh II. As I discovered today, however, this isn't as simple as it seems, and many links have gone dead since I last tried, so here are my notes… »

• ### A Comparison of English Translations of ‘A Cruel Angel's Thesis’

Disclaimer: I know zero Japanese. When I see ‘残酷’, I read ‘cánkù’. This post is based on the generously-licenced work of Wiktionary and others.

• ### Welcome to the new home of ‘$sudo FIXIT!!’ I've just completed the migration of all blog posts and comments from the old Blogger site to this new Jekyll/HashOver-based blog. Hooray for open source software! Along with the revamped site and layout comes a name change: Goodbye,$ sudo FIXIT!!,… »
$$\LaTeX$$ is fantastic, but sometimes it does strange things, like breaking \urls only at certain points. Using tricks like this glorious \UrlBreaks hack, one can force URLs to break at any point, but for some reason, this does not work in… »


text:
# Is there a relation between total futures and the amount of production?

I have a multipart question about futures and production.

Lets take corn as an example. We add up the total 1 year futures of corn, call this weight $A$ kg. Next, we can get a reasonable estimate of how much the world corn production will be in 1 year call this $B$ kg.

(1) Is there a relation between $A$ and $B$?

(2) Can nonproducers of a good sell futures?

If yes, suppose noncorn farmers sell corn futures. Then $A$ may appear greater than $B$.

(3) Then how does the supply and demand work? i.e., will this cause the corn price to go down in 1 year? My confusion is, the supply and demand curves I have seen only assume $B$ and not $A$. Can the demand depend on $A$?

(4) When $A>B$, what happens if everybody who bought the futures want their corn?

PS: I am a newbie, so if this sounds dumb please explain that too. Thanks.

It is not a dumb question, but very confusing to me at a basic level. The Open Interest in futures (what you call A) has nothing at all to do with the total production (what you call B). The futures market is just a derivative market, where side bets are made as to what the PRICE of the crop will be. You cannot use it to infer what the PRODUCTION will be.

Of course speculators (non-producers) can both sell and buy futures.

What consumers will eat however, is physical wheat (i.e. B), not A. A is not edible. A only tells you how many people are interested in making side bets on the price of wheat (for speculative or hedging purposes). Keep in mind also that for every seller of futures there is a buyer (i.e. futures are in zero net supply, there are A futures long but also A futures short, netting out to zero).

(Added July 22, 2016)

A word about delivery. Futures are designed so that only a small percentage of contracts will be delivered. From the wheat buyer point of view delivery has 2 disadvantages: 1) it takes place at a warehouse chosen by the exchange, not necessarily one convenient to you. 2) The buyer receives wheat selected by the seller, subject only to minimum quality standards set by the exchange. When I buy oranges or bananas at a supermarket I like to carefully choose the fruits myself based on my preferences; I would not like it if the seller "assigned" fruit to me sight unseen.

Similarly, when delivery approaches wheat futures buyers will visit local warehouses and personally select the wheat they prefer, they will then buy the wheat and close out the long futures contract. Thus the futures serve only as price insurance, the actual physical wheat is purchased in the cash market.

A > B and everybody wanting delivery would break the system (like everyone pulling money out of their bank at the same time, or everyone trying to exit a stadium fire at the same time), but is very unlikely. The Futures Exchange and the CFTC watch to make sure there is "orderly liquidation" (i.e. a sharp decrease in A) in the days prior to delivery.


text: `hyperref` is a package capable of producing hypertext links in documents. If your question is about cross-referencing in general, choose . If it's specifically about PDF features, consider to choose .


text:
This article provides detailed information on sampling audio signals and transferring the data to a PC for analysis.

### Why?

In a previous article, I presented a straightforward MEMS microphone circuit that can be included in a robot system or just about any other electronics project. If you’re undecided about how exactly to produce your analog audio, start with that article. If you already have a working microphone interface and now you want to sample and analyze the audio data, you’re ready for this article.

We all know the advantages of digital data when it comes to processing and storage. But why transfer the data to a PC? Well, the answer is obvious if your goal is simply to record sound and then analyze it or save it for future enjoyment. But what if the goal is in-system processing? PC analysis is valuable even when the end application requires the robot itself to process the audio data—the powerful and user-friendly software available for PCs can help you to develop and fine-tune the algorithms that will eventually be implemented in the robot’s processor.

### Sampling and Timing

Once you have a buffered audio signal, there are two main tasks required for getting that audio data to a PC: analog-to-digital conversion and robot-to-PC data transfer.

Let’s first look at the analog-to-digital conversion, particularly the timing details involved. The following schematic excerpt shows the microphone circuit and the connection to the EFM8 microcontroller:

And here is the PCB layout, with the microphone output signal highlighted in blue:

#### Sample Rate

In general, the standard range of audible frequencies is 20 Hz to 20 kHz. That’s a maximum or optimal range; the real range varies greatly from person to person. Furthermore, for many types of sound reproduction, we do not have to represent the entire audible frequency range. For example, reliable voice communication is possible when the audio signals are restricted to frequencies below 4 kHz, and an upper limit of 10 kHz allows for decent (not great) music reproduction. A standard sampling rate for good-quality audio is 44.1 kHz—just enough to support frequencies up to 20 kHz.

My point here is that you are not bound to a 20 kHz bandwidth. You choose the bandwidth according to the audio quality that you want, then you configure your ADC for a sample rate that is about twice as high as the bandwidth. I’m running my 14-bit EFM8 ADC at 16 kHz, which allows me to capture frequencies up to almost 8 kHz.

#### Storing vs. Sending

Digital audio may seem like old technology, but audio data still requires a lot of memory in the context of a microcontroller. If you’re sampling at 14 bits and 16 thousand samples per second (i.e., 16 ksps), each second of audio requires 32 thousand bytes of data. If your MCU has only 4 kB of RAM, you’re limited to one-eighth of a second. There’s not much you can do with a 125-millisecond recording.

Thus, for this project, we will not store audio data. Instead, we will transfer it to the PC continuously, in real time: as soon as each 14-bit sample is generated by the ADC, we send both bytes out the serial port. You can use the same hardware-plus-software arrangement discussed in this article on incorporating microphones into robotics—i.e., a Pololu USB-to-UART converter board (see photo below) and YAT (“Yet Another Terminal”).

When the transfer is complete, we move the data from YAT to Excel.

#### Timing Conflict?

The primary concern here is ensuring that both bytes are successfully transferred before a new ADC sample arrives. An ADC running at 16 ksps will generate one sample every 62.5 µs. The UART hardware must transfer 10 bits per byte (8 data bits plus one start bit and one stop bit). That’s 20 bits total, and then we also need a small amount of time for interrupt handling and execution of the necessary instructions. So let’s include some margin and say that 25-bit periods must fit within the 62.5 µs between ADC samples.

$$\frac{62.5\ \mu s}{25\ bit\ periods}=\frac{2.5\ \mu s}{bit\ period}$$

$$baud\ rate=\frac{1}{bit\ period}=400\ kbaud$$

We’ll increase the baud rate to the closest standard value, which is 460800. The limitations of the EFM8’s divider hardware result in an actual baud rate of 453704. Is that close enough? My conclusion from this article is that UART communication will usually be reliable when the baud rates are not different by more than 3.75%. The difference between 460800 and 453704 is about 1.5%, so it should be fine.

Before we move on, let’s use a debug signal and a scope to confirm that we don’t have a timing conflict.

                    SI_INTERRUPT (ADC0EOC_ISR, ADC0EOC_IRQn)
{

while(!SCON0_TI);
SCON0_TI = 0;

while(!SCON0_TI);
SCON0_TI = 0;

Num_Samples_Sent++;
if(Num_Samples_Sent == 15999)
{
//stop Timer5 (one more conversion will occur)
SFRPAGE = TIMER5_PAGE;
TMR5CN0_TR5 = 0;
}

}

As you can see, C2ADAPTER_LEDGRN goes high at the beginning of the interrupt routine (i.e., when a new ADC sample becomes available) and low at the end of the interrupt routine, at which point the bytes have been transferred and the processor is ready to start idly waiting for the next sample. The cursors in this first scope capture confirm that the rising edges are separated by ~62.5 µs.

You can already see that there is ample time between the completion of the data transfer and the arrival of the next sample. To be precise, we have 18.8 µs of spare time, which is 30% of the ADC sampling period:

### YAT and Excel

The bytes are sent using the code shown above (you can remove the C2ADAPTER_LEDGRN = HIGH and C2ADAPTER_LEDGRN = LOW statements if you want to). You can explore the firmware in detail by looking through the source files and the hardware configuration file:

Refer to this article for details on using YAT and Excel. However, be warned that YAT could give you problems if you’re dealing with large quantities of data. Apparently, it doesn’t like having lots of data in the terminal monitor, so the save-to-file technique becomes inconvenient.

An alternative approach is to use a log file, but I had serious difficulties with the logging functionality—so serious that I abandoned YAT and decided to write my own C# serial-port logging software that does exactly what I want. Here it is:

So far it’s working well. I’ll probably continue adding functionality until I have a general-purpose serial-port program that efficiently and reliably does (once again) exactly what I need it to do, and nothing more. I’ll make the logger available for download when I’m confident that it’s stable and can adequately handle error scenarios.

It’s currently arranged for 16,000 audio samples, which corresponds to one second of recording time, and it does the following:

• converts bytes to ADC counts and millivolts
• generates two time-domain plots of the audio data
• performs spectral analysis by calculating and plotting Fast Fourier Transform (FFT) data; click here for instructions on using Excel’s FFT functionality

In the following video, I am generating a single-tone audio signal using this website. The EFM8 gathers and transfers 16,000 audio samples, which are stored by my logger software and imported into Excel. You can see that the frequency of the spike in the Fourier plot corresponds to the frequency of the original signal. (I’m doing a 1024-point FFT, which results in a frequency resolution of 15.625 Hz. So, in general, the original and measured audio frequencies won’t be exactly the same.)

### Summary

We’ve discussed some important details related to the digitization of audio signals, and we used custom hardware in conjunction with Excel to visualize and analyze digital audio data. And I even developed some handy serial-port software along the way—a good reminder that projects don’t always follow the expected route.


text:
## Tuesday, 12 June 2018

### candle.m Function Released

I have just noticed that my previously accepted candlestick plot function now appears to have been released, release date 14 December 2017, as part of the Octave financial package. The function reference is at https://octave.sourceforge.io/financial/function/candle.html

## Thursday, 7 June 2018

### Update on Improved Currency Strength Indicator

Following on from my previous post I have now slightly changed the logic and coding behind the idea, which can be seen in the code snippet below
%  aud_cad
mse_vector(1) = log( ( current_data(1,1) * ( aud_x / cad_x ) ) / current_data(2,1) )^2 ;
%  xau_aud
mse_vector(46) = log( ( current_data(1,46) * ( gold_x / aud_x ) ) / current_data(2,46) )^2 ;
mse_vector(47) = log( ( current_data(1,47) * ( gold_x / cad_x ) ) / current_data(2,47) )^2 ;
Essentially the change simultaneously optimises, using Octave's fminunc function, for both the gold_x and all currency_x geometric multipliers together rather than just optimising for gold and then analytically deriving the currency multipliers. The rationale for this change is shown in the chart below,
which shows the optimisation errors for the "old" way of doing things, in black, and the revised way in blue. Note that this is a log scale, so the errors for the revised way are orders of magnitude smaller, implying a better model fit to the data.

This next chart shows the difference between the two methods of calculating a gold index ( black is old, blue is new ),
this one shows the calculated USD index
and this one the GBP index in blue, USD in green and the forex pair cross rate in black
The idea(s) I am going to look at next is using these various calculated indices as inputs to algorithms/trading decisions.

## Monday, 28 May 2018

### An Improved Currency Strength Indicator plus Gold and Silver Indices?

In the past I have blogged about creating a currency strength indicator ( e.g. here, here and here ) and this post talks about a new twist on this idea.

The motivation for this came about from looking at chart plots such as this,
which shows Gold prices in the first row, Silver in the second and a selection of forex cross rates in the third and final row. The charts are on a daily time scale and show prices since the beginning of 2018 up to and including 25th May, data from Oanda.

If one looks at the price of gold and asks oneself if the price is moving up or down, the answer will depend on which gold price currency denomination chart one looks at. In the latter part of the charts ( from about time ix 70 onwards ) the gold price goes up in pounds Sterling and Euro and down in US dollars. Obviously, by looking at the relevant exchange rates in the third row, a large part of this gold price movement is due to changes in the strength of the underlying currencies. Therefore, the problem to be addressed is that movements in the price of gold are confounded with movements in the price of the currencies, and it would be ideal if the gold price movement could be separated out from the currency movements, which would then allow for the currency strengths to also be determined.

One approach I have been toying with is to postulate a simple, geometric change model whereby the price of gold is multiplied by a constant, let's call it x_g, for example x_g = 1.01 represents a 1% increase in the "intrinsic" value of gold, and then adjust the obtained value of this multiplication to take in to account the change in the value of the currency. The code box below expresses this idea, in somewhat clunky Octave code.
% xau_gbp using gbp_usd
new_val_gold_in_old_currency_value = current_data(1,1) * x_g ;
new_val_gold_in_new_currency_value = new_val_gold_in_old_currency_value * exp( -log( current_data(2,6) / current_data(1,6) ) ) ;
mse_vector(1) = log( current_data(2,1) / new_val_gold_in_new_currency_value )^2 ;

% xau_usd using gbp_usd
new_val_gold_in_old_currency_value = current_data(1,2) * x_g ;
new_val_gold_in_new_currency_value = new_val_gold_in_old_currency_value * exp( log( current_data(2,6) / current_data(1,6) ) ) ;
mse_vector(2) = log( current_data(2,2) / new_val_gold_in_new_currency_value )^2 ;
For this snippet, current_data is a 2-dimensional vector containing yesterday's and today's gold prices in GBP and USD, plus yesterday's and today's GBP_USD exchange rates.

The above would be repeated for all gold price currency denominations and the relevant forex pairs and be part of a function, for x_g, which is to be minimised by the Octave fminunc function. Observant readers might note that the error to be minimised is the square of the log of the accuracy ratio. Interested readers are referred to the paper A Better Measure of Relative Prediction Accuracy for Model Selection and Model Estimation for an explanation of this and why it is a suitable error metric for a geometric model.

The chart below is a repeat of the one above, with the addition of a gold index, a silver index and currency strengths indices calculated from a preliminary subset of all gold price currency denominations using the above methodology.
In the first two rows, the blue lines are the calculated gold and silver indices, all normalised to start at the first price at the far left of each respective currency denomination. The silver index was calculated using the relationship between the gold x_g value and the xau xag ratio. Readers will see that these indices are similarly invariant to the currency in which they are expressed ( the geometric bar to bar changes in the indices are identical ) but each is highly correlated to its underlying currency. They could be calculated from an arbitrary index starting point, such as 100, and therefore can be considered to be an index of the changes in the intrinsic value of gold.

When it comes to currency strengths most indicators I have come across are variations of a single theme, namely: averages of all the changes for a given set of forex pairs, whether these changes be expressed as logs, percentages, values or whatever. Now that we have an absolute, intrinsic value gold index, it is a simple matter to parse out the change in the currency from the change in the gold price in this currency.

The third row of the second chart above shows these currency strengths for the two base currencies plotted - GBP and EUR - again normalised to the first charted price on the left. Although in this chart only observable for the Euro, it can be seen that the index again is invariant, similar to gold and silver above. Perhaps more interestingly, the red line is a cumulative product of the ratio of base currency index change to the term currency index change, normalised as described above. It can be seen that the red line almost exactly overwrites the underlying black line, which is the actual cross rate plot. This red line is plotted as a sanity check and it is gratifying to see such an accurate overwrite.

I think this idea shows great promise and for the nearest future I shall be working to extend it beyond the preliminary data set used above. More in due course.

## Friday, 2 March 2018

### Hidden Markov Modelling of Synthetic Periodic Time Series Data

I am currently working on a method of predicting/projecting cyclic price action, based upon John Ehlers' sinewave indicator code, and to test it I am using Octave's implementation of a Hidden Markov model in the Octave statistics package hosted at Sourceforge.

Basically I measure the dominant cycle period ( using either the above linked sinewave indicator code or autocorrelation periodogram code ) and use the vector of measured dominant cycle periods as input to the hmmestimate function. Using the output from this, the hmmgenerate function is then used to generate a new period vector, these periods are converted to a slowly, periodically varying sine wave, and additive white Gaussian noise is added to the signal to produce a final signal upon which Monte Carlo testing of my proposed indicator can be conducted. A typical plot of the varying, dominant cycle periods looks like
whilst the noisy sine wave signal derived from this looks like this.
The relevant Octave code for all this is shown in the two code boxes below
clear all ;

% load all datafile names from Oanda
cd /home/dekalog/Documents/octave/oanda_data/daily ;
oanda_files_d = glob( "*_ohlc_daily" ) ; % cell with filenames matching *_ohlc_daily, e.g. eur_usd_ohlc_daily

all_transprobest = zeros( 75 , 75 ) ;

for ii = 1 : 124

filename = oanda_files_d{ ii } ;
current_data_d = load( "-binary" , filename ) ;
data = getfield( current_data_d , filename ) ;
midprice = ( data( : , 3 ) .+ data( : , 4 ) ) ./ 2 ;
period = autocorrelation_periodogram_2_5( midprice ) ;
period(1:49) = [] ;
min_val = min( period ) ; max_val = max( period ) ;
hmm_periods = period .- ( min_val - 1 ) ; hmm_states = hmm_periods ;

[ transprobest , outprobest ] = hmmestimate( hmm_periods , hmm_states ) ;
all_transprobest( min_val : max_val , min_val : max_val ) = all_transprobest( min_val : max_val , min_val : max_val ) .+ transprobest ;

endfor

all_transprobest = all_transprobest ./ 124 ;
[ i , j ] = find( all_transprobest ) ;

if ( min(i) == min(j) && max(i) == max(j) )
transprobest = all_transprobest( min(i):max(i) , min(j):max(j) ) ;
outprobest = eye( size(transprobest,1) ) ;
hmm_min_period_add = min(i) - 1 ;
endif

cd /home/dekalog/Documents/octave/period/hmm_period ;
save all_hmm_periods_daily transprobest outprobest hmm_min_period_add ;

and
clear all ;
cd /home/dekalog/Documents/octave/snr ;
cd /home/dekalog/Documents/octave/period/hmm_period ;

[ gen_period , gen_states ] = hmmgenerate( 2500 , transprobest , outprobest ) ;
gen_period = gen_period .+ hmm_min_period_add ;
gen_sine = sind( cumsum( 360 ./ gen_period ) ) ;
noise_val = mean( [ all_snr(:,1) ; all_snr(:,2) ] ) ;
noisy_sine = awgn( gen_sine , noise_val ) ;
[s,s1,s2,s3] = sinewave_indicator( noisy_sine ) ; s2(1:50) = s1(1:50) ;

figure(1) ; plot( gen_period , 'k' , 'linewidth' , 2 ) ;
figure(2) ; plot( gen_sine , 'k' , 'linewidth' , 2 , noisy_sine , 'b' , 'linewidth' , 2 , s , 'r' , 'linewidth' , 2 , ...
s1 , 'g' , 'linewidth' , 2 , s2 , 'm' , 'linewidth' , 2 ) ;
legend( "Gen Sine" , "Noisy Sine" , "Sine Ind" , "Sine Ind lead1" , "Sine Ind Lead2" ) ;

I hope readers find this useful if they need to generate synthetic, cyclic data for their own development/testing purposes too.


text:
# Physics Questions and Answers – Capacitors and Capacitance

«
»

This set of Physics Multiple Choice Questions & Answers (MCQs) focuses on “Capacitors and Capacitance”.

1. What is the dimensional formula of capacitance of a capacitor?
a) M1L2T-4I-2
b) M-1L-2T4I2
c) M-1L-2T6
d) M-2L2T4
View Answer

Answer: b
Explanation: We know that Capacitance=Charge*(voltage)-1
Now charge=current*time=[I1T1].
voltage=electric field*distance, and electric field=force*(charge)-1
Since we know the dimensional formula of force is [M1L1T-2], therefore,
Electric field=[M1L1T-2] * [I1T1]-1=[M1L1T-3I-1].
Finally, voltage becomes=[M1L1T-3I-1] *L.
Hence, we conclude that dimensional formula of capacitance is [I1T1] * ([M1L1T-3I-1] *L)-1 that is M-1L-2T4I2.
advertisement

2. When ‘n’ capacitors are connected in series the total capacitance(C) of the combination is given by ______
a) C=C1+C2+C3+C4+…..+Cn
b) C=C1*C2*C3*C4*…..*Cn
c) $$\frac {1}{C} = \frac {1}{C_1} + \frac {1}{C_2} + \frac {1}{C_3} + ……. + \frac {1}{C_n}$$
d) C=$$\frac {(C_1+C_2+C_3+C_4+……+C_n)}{n}$$
View Answer

Answer: c
Explanation: The equivalent capacitance of the parallel plate capacitors connected in series is given by the sum of the reciprocals of the individual capacitances. That is mathematically,
$$\frac {1}{C} = \frac {1}{C_1} + \frac {1}{C_2} + \frac {1}{C_3} + ……. + \frac {1}{C_n}$$

3. What is the value of capacitance of a capacitor if it has a charge of 9C and voltage of 5V?
a) 1.8F
b) 45F
c) 4.5F
d) 8.1F
View Answer

Answer: a
Explanation: Since we know that capacitance=$$\frac {charge}{voltage}$$.
Therefore capacitance=$$\frac {9}{5}$$=1.8F.
Note: Join free Sanfoundry classes at Telegram or Youtube
advertisement
advertisement

4. The total capacitance of capacitors connected in parallel is given by _____
a) product of the individual capacitors in parallel
b) sum of all the individual capacitors in parallel
c) sum of their reciprocals
d) product of their reciprocals
View Answer

Answer: b
Explanation: The equivalent capacitance of the capacitors connected in parallel is given by sum of their individual capacitances, that is if there are n capacitors in parallel the total capacitance is given by, C=C1+C2+C3+C4+…..+Cn.

5. What is the total charge on the parallel plate capacitor shown?

a) 2Q
b) $$\frac {Q}{2}$$
c) 0
d) $$\frac {-Q}{2}$$
View Answer

Answer: c
Explanation: Since the total charge on a capacitor is given by sum of the charges on the two parallel plates, here charge on each plate is equal and opposite, hence –Q+Q=0. Therefore, the total charge on the capacitor is 0.
Take Physics - Class 12 Mock Tests - Chapterwise!
Start the Test Now: Chapter 1, 2, 3, 4, 5, 6, 7, 8, 9, 10
advertisement

6. What happens to the capacitance when a dielectric material is inserted between the plates of a parallel plate capacitor?
a) Capacitance decreases
b) Capacitance remains same
c) Capacitance increases
d) Depends upon the material of the dielectric
View Answer

Answer: c
Explanation: When a dielectric material is inserted between the plates of the parallel plate capacitor, the capacitance of the capacitor increases with a factor of K. That is C=KC0.

Sanfoundry Global Education & Learning Series – Physics – Class 12.

advertisement

To practice all areas of Physics, here is complete set of 1000+ Multiple Choice Questions and Answers.

advertisement
advertisement
Subscribe to our Newsletters (Subject-wise). Participate in the Sanfoundry Certification contest to get free Certificate of Merit. Join our social networks below and stay updated with latest contests, videos, internships and jobs!

Youtube | Telegram | LinkedIn | Instagram | Facebook | Twitter | Pinterest
Manish Bhojasia, a technology veteran with 20+ years @ Cisco & Wipro, is Founder and CTO at Sanfoundry. He lives in Bangalore, and focuses on development of Linux Kernel, SAN Technologies, Advanced C, Data Structures & Alogrithms. Stay connected with him at LinkedIn.

Subscribe to his free Masterclasses at Youtube & technical discussions at Telegram SanfoundryClasses.


text:
+0

# How would I graph this?

0
42
1

How would I graph this?

Guest Oct 4, 2017

#1
+1221
+1

This is an example of a piecewise function.

$$\begin{array}{cc} \{ & \begin{array}{cc} 0 &\text{if}& x\leq -3 \\ x+1 &\text{if}& -2 Unfortunately, I am not an expert with LaTeX, so I do not know how to enlarge the bracket to the appropriate size. Maybe someone is more adept. Anyway, the best advice I can give for problems like these is to do them one step at a time. Let's worry about the topmost function and work our way downward. \(-1\hspace{1mm}\text{if}\hspace{1mm}x\leq3$$

If y=-1, that means that no matter what the input is, the output will always be -1. Therefore, plot this such that y=-1. However, we must be mindful of the domain restriction. This is only true when the input (x) is less than or equal to 3. 4, for example, does not exist because that input is outside of the domain restriction. Be sure to have a closed circle at (3,-1) to indicate that that value is included. Now, let's worry about the next piece!

$$x+1\hspace{1mm}\text{if}\hspace{1mm} -2 Plot the function \(y=x+1$$ just like you normally would. Just like before, we then take into account the currect restriction. Be sure to have an open circle at the point $$(-2,-1)$$ because it is not included, and be sure to have a closed circle at $$(2,3)$$ because that point is included according to the domain restriction.

$$x\hspace{1mm}\text{if}\hspace{1mm}4\leq x\leq6$$

Plot the function as if the equation was $$y=x$$. Then, chop off the points where x and then only include the domain values bounded between 4 and 6. Be sure to have closed circles.

Click anywhere on this sentence to be sent to a graph of this specific peicewise function.

TheXSquaredFactor  Oct 4, 2017
edited by TheXSquaredFactor  Oct 4, 2017
Sort:

#1
+1221
+1

This is an example of a piecewise function.

$$\begin{array}{cc} \{ & \begin{array}{cc} 0 &\text{if}& x\leq -3 \\ x+1 &\text{if}& -2 Unfortunately, I am not an expert with LaTeX, so I do not know how to enlarge the bracket to the appropriate size. Maybe someone is more adept. Anyway, the best advice I can give for problems like these is to do them one step at a time. Let's worry about the topmost function and work our way downward. \(-1\hspace{1mm}\text{if}\hspace{1mm}x\leq3$$

If y=-1, that means that no matter what the input is, the output will always be -1. Therefore, plot this such that y=-1. However, we must be mindful of the domain restriction. This is only true when the input (x) is less than or equal to 3. 4, for example, does not exist because that input is outside of the domain restriction. Be sure to have a closed circle at (3,-1) to indicate that that value is included. Now, let's worry about the next piece!

$$x+1\hspace{1mm}\text{if}\hspace{1mm} -2 Plot the function \(y=x+1$$ just like you normally would. Just like before, we then take into account the currect restriction. Be sure to have an open circle at the point $$(-2,-1)$$ because it is not included, and be sure to have a closed circle at $$(2,3)$$ because that point is included according to the domain restriction.

$$x\hspace{1mm}\text{if}\hspace{1mm}4\leq x\leq6$$

Plot the function as if the equation was $$y=x$$. Then, chop off the points where x and then only include the domain values bounded between 4 and 6. Be sure to have closed circles.

Click anywhere on this sentence to be sent to a graph of this specific peicewise function.

TheXSquaredFactor  Oct 4, 2017
edited by TheXSquaredFactor  Oct 4, 2017

### 16 Online Users

We use cookies to personalise content and ads, to provide social media features and to analyse our traffic. We also share information about your use of our site with our social media, advertising and analytics partners.  See details


text:
Home OALib Journal OALib PrePrints Submit Ranking News My Lib FAQ About Us Follow Us+
 Title Keywords Abstract Author All
Search Results: 1 - 10 of 100 matches for " "
 Page 1 /100 Display every page 5 10 20 Item
 Carla Biggio Physics , 2002, DOI: 10.1103/PhysRevD.66.044009 Abstract: We discuss a new method for gauge symmetry breaking in theories with one extra dimension compactified on the orbifold S^1/Z_2. If we assume that fields and their derivatives can jump at the orbifold fixed points, we can implement a generalized Scherk-Schwarz mechanism that breaks the gauge symmetry. We show that our model with discontinuous fields is equivalent to another with continuous but non periodic fields; in our scheme localized lagrangian terms for bulk fields appear.
 Franco Strocchi Physics , 2015, Abstract: The concepts of symmetry, symmetry breaking and gauge symmetries are discussed, their operational meaning being displayed by the observables {\em and} the (physical) states. For infinitely extended systems the states fall into physically disjoint {\em phases} characterized by their behavior at infinity or boundary conditions, encoded in the ground state, which provide the cause of symmetry breaking without contradicting Curie Principle. Global gauge symmetries, not seen by the observables, are nevertheless displayed by detectable properties of the states (superselected quantum numbers and parastatistics). Local gauge symmetries are not seen also by the physical states; they appear only in non-positive representations of field algebras. Their role at the Lagrangian level is merely to ensure the validity on the physical states of local Gauss laws, obeyed by the currents which generate the corresponding global gauge symmetries; they are responsible for most distinctive physical properties of gauge quantum field theories. The topological invariants of a local gauge group define superselected quantum numbers, which account for the $\theta$ vacua.
 High Energy Physics - Phenomenology , 2007, DOI: 10.1016/j.physletb.2007.07.053 Abstract: We investigate a 5D SU(6) grand gauge-Higgs unification model compactified on an orbifold S^1/Z_2. Ordinary quarks and leptons, together with right-handed neutrinos, are just accommodated into a minimal set of representations of the gauge group, without introducing any exotic states. The proton decay turns out to be forbidden at least at the tree level. We also find a correct electroweak symmetry breaking SU(2)_L \times U(1)_Y \to U(1)_{em} is easily realized by introducing suitable number of adjoint fermions.
 Physics , 2001, DOI: 10.1016/S0550-3213(02)00252-3 Abstract: It has been conjectured that spontaneous chiral symmetry breaking in strongly coupled vectorlike gauge theories falls into only three different classes, depending on the gauge group and the representations carried by the fermions. We test this proposal by studying SU(2), SU(3) and SU(4) lattice gauge theories with staggered fermions in different irreducible representations. Staggered fermions away from the continuum limit should, for all complex representations, still belong to the continuum class of spontaneous symmetry breaking. But for all real and pseudo-real representations we show that staggered fermions should belong to incorrect symmetry breaking classes away from the continuum, thus generalizing previous results. As an unambiguous signal for whether chiral symmetry breaks, and which breaking pattern it follows, we look at the smallest Dirac eigenvalue distributions. We find that the patterns of symmetry breaking are precisely those conjectured.
 R Assumpcao Physics , 2007, Abstract: Employing an arbitrary velocity gauge transformation this contribution argues that the breaking of time symmetry is a natural consequence of irreversibility.
 Physics , 2003, DOI: 10.1143/PTP.109.831 Abstract: We study the unitarity bounds of the scattering amplitudes in the extra dimensional gauge theory where the gauge symmetry is broken by the boundary condition. The estimation of the amplitude of the diagram including four massive gauge bosons in the external lines shows that the asymptotic power behavior of the amplitude is canceled. The calculation will be done in the 5 dimensional standard model and the SU(5) grand unified theory, whose 5th dimensional coordinate is compactified on $S^1/Z_2$. The broken gauge theories through the orbifolding preserve the unitarity at high energies similarly to the broken gauge theories where the gauge bosons obtain their masses through the Higgs mechanism. We show that the contributions of the Kaluza-Klein states play a crucial role in conserving the unitarity.
 Physics , 1996, DOI: 10.1016/S0550-3213(97)00030-8 Abstract: The phenomenology associated with gauge-mediated supersymmetry breaking is presented. A renormalization group analysis of the minimal model is performed in which the constraints of radiative electroweak symmetry breaking are imposed. The resulting superpartner and Higgs boson spectra are highly correlated and depend on only a few parameters. Superpartner mass ratios and sum rules are identified which can be tested at future colliders. Some of these relations are logarithmically sensitive to the messenger scale, while others allow gauge-mediation to be distinguished from other schemes for tansmitting supersymmetry breaking. Deviations from the minimal model, such as larger messenger representations and additional contributions to Higgs sector masses, can in some circumstances dramatically modify the low energy spectrum. These modifications include a slepton or Higgsino as the lightest standard model superpartner, or exotic mass relations among the scalars and gauginos. The contribution to $b \to s \gamma$ and resulting bound on superpartner masses are also presented for the minimal model. Finally, the unique collider signatures of heavy charged particle production, or decay to the Goldstino within a detector are discussed.
 Michael Grady Physics , 2006, Abstract: Simulations of pure-gauge SU(2) lattice gauge theory are performed in the minimal Coulomb gauge. This leaves a residual or remnant gauge symmetry still active which is global in three directions but still local in one. Using averaged fourth-dimension pointing links as a spin-like order parameter, the remnant symmetry appears to undergo spontaneous symmetry breaking at around $\beta = 2.6$. Both the Binder cumulant and the magnetization itself exhibit crossings in this region using lattices up to $20^4$, and a susceptibility peak is also observed. Finite size scaling indicates a weak first-order transition. The symmetry breaking is also observed to take place in the fundamental-adjoint plane, and is coincident with the strong first-order transition that exists there at large $\beta_{\rm{adjoint}}$. This provides confirmation that this phase transition is a symmetry-breaking transition. A well-known theorem concerning the instantaneous Coulomb potential has previously proven that a transition where such a Coulomb-gauge remnant symmetry breaks is necessarily deconfining.
 Physics , 2015, DOI: 10.3390/math3040984 Abstract: For the description of observables and states of a quantum system, it may be convenient to use a canonical Weyl algebra of which only a subalgebra $\mathcal A$, with a non-trivial center $\mathcal Z$, describes observables, the other Weyl operators playing the role of intertwiners between inequivalent representations of $\mathcal A$. In particular, this gives rise to a gauge symmetry described by the action of $\mathcal Z$. A distinguished case is when the center of the observables arises from the fundamental group of the manifold of the positions of the quantum system. Symmetries which do not commute with the topological invariants represented by elements of $\mathcal Z$ are then spontaneously broken in each irreducible representation of the observable algebra, compatibly with an energy gap; such a breaking exhibits a mechanism radically different from Goldstone and Higgs mechanisms. This is clearly displayed by the quantum particle on a circle, the Bloch electron and the two body problem.
 Physics , 1997, DOI: 10.1088/0305-4470/30/16/019 Abstract: We show how the widely used concept of spontaneous symmetry breaking can be explained in causal perturbation theory by introducing a perturbative version of quantum gauge invariance. Perturbative gauge invariance, formulated exclusively by means of asymptotic fields, is discussed for the simple example of Abelian U(1) gauge theory (Abelian Higgs model). Our findings are relevant for the electroweak theory, as pointed out elsewhere.
 Page 1 /100 Display every page 5 10 20 Item


text:
# Understanding the mechanism of Blanc chloromethylation

I have seen this question: Mechanism for chloromethylation of benzene.

The answer there uses a picture from wikipedia which confuses me. It gives $$\ce{H2C=O <=>C[HCl] H2C+-OH <-> H2C=O+H}$$ and the benzene attacking the $\ce{C}$ from $\ce{H2C=O+H}$, not the $\ce{C}$ from $\ce{H2C+-OH}$ as I would have expected.

Is it only a quirk in the picture or do I have some fundamental misconceptions?

• I found the question this is a duplicate of. chemistry.stackexchange.com/questions/37870/… Different reaction, same question, although it is a poor answer. Maybe mark that as a dupe of this – orthocresol Jan 7 '16 at 16:14
• @orthocresol I agree, but my resonance structure is easier, as it has only two parts ;-) – Gyro Gearloose Jan 7 '16 at 16:18

Resonance is a concept which expresses a more realistic bonding situation through a set of conformations. Therefore the following can only be treated as one structure: $$\Bigg[~\ce{H2\overset{+}{C}-OH <-> H2C=\overset{+}{O}H}~\Bigg]$$ It is therefore irrelevant in which structure you indicate the nucleophilic attack since it is the same carbon. Usually you would rather draw it the way that the arrow points to the structure where the carbon carries the positive charge, since you would expect this structure to have a higher contribution to the ground state.

• So my misunderstanding is that resonance is not some equilibrium state but rather a quantum mechanic "dead and alive" at the same time, like Schroedingers Cat? – Gyro Gearloose Jan 7 '16 at 16:13
• @GyroGearloose yes that is pretty much the case. There would be a couple of more resonance structures, but they are not too important, so most of the times you neglect them. Whenever you see resonance structures think of them as one state. – Martin - マーチン Jan 7 '16 at 16:59

The result is the same no matter which resonance form you use. Resonance forms are only formal representations, extreme forms of the true structure which is somewhere in between.

Note that to get from the blue resonance form to the red resonance form, you'd need to push an arrow:

So there is no real difference which resonance form you use - in the end you would draw exactly the same arrows. In the blue reaction, you draw two arrows. In the red reaction, you only draw one arrow. But, to get from the blue resonance form to the red resonance form, you have to draw one arrow anyway.

Don't read too much into the number of arrows or whatever - the only point I am trying to make is that from a mechanism-drawing perspective, it does not matter which resonance form you use, because all roads lead to the same product anyway. All those arrows are just formal bookkeeping.

• I could (naively?) interpret $\ce{H2C+-OH}$ as Lewis acid, but not so $\ce{H2C=O+H}$. – Gyro Gearloose Jan 7 '16 at 16:28
• @GyroGearloose No, since those are the same thing, if one is a Lewis acid, the other must be as well. – jerepierre Jan 7 '16 at 16:59
• Bookkeeping... You like that word, don't you. Nice pictures! +1 – Martin - マーチン Jan 7 '16 at 17:01


text:
# Lesson 5: Constructional requirements for suspended timber floors

## INTRODUCTION

The consideration of constructional requirements for suspended timber floor will provide you with the knowledge needed to ensure successful work. Requirements involved in the construction will guide you to undertake the construction of suspended timber floor. The knowledge will enable you achieve good construction results.

Objective
 The objective of this coarse is to facilitate to stakeholders how to improve quality of work on distant learning mode online.

## LESSON CONTENT

The constructional requirements for suspended timber floor will involve strategies regarding the methods of work, the position of facilities and materials. The analysis of these requirements will enable you see the essence of quality work. REQUIREMENTS ON METHODS The following techniques will result in good suspended timber Floor: -- Correct position of an oversite concrete. -- Correct construction of honey combed sleeper walls to carry the suspended timber floor members. -- Provision of a wall plate on the sleeper wall. -- Provision of damp proof course between sleeper wall and floor joist. -- Provision of floor joist to receive the floor boards -- Air vent provision within the external wall is necessary to

  promote free circulation of air around the wooden members
of the floor to prevent decaying.

REQUIREMENTS ON MATERIALS For effective functioning of the suspended floor, the following material requirements are important:

-- All materials used are required to be of good quality.
-- The timber members are required to be well seasoned to prevent any pre-mature decaying.
-- The sizing of the floor joist and wall plates must be according to the specified sizes and shapes for such work.
-- Timber members’ strength and durability should be enhanced through the use of appropriate preservatives.

REQUIREMENTS ON QUALITTY. The quality of the suspended timber floor is very important towards ensuring that it serves the purpose. The timber members especially the joist, boards, wall plates and others are required to have a uniform selection. This will enable you to determine how effective the suspended timber floor can be. Template:SUMMARY Interview at least 2 women who had given birth {{ask if thet had experience any problems/difficulties during ist trimester. if any what were they what did they did to overcome those problems