问:
App crashes when i open it with Fragments
I have this problem:

I'm trying to create an App with 2 buttons on a Layout and this buttons open 2 different Fragments, but the problem is that when I open the app it crashes.

Here's my code:

MainActivity:

```<code>package com.example.akroma.feina_final;

import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.support.v4.app.Fragment;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;

public class MainActivity extends AppCompatActivity implements View.OnClickListener {

    Button boton1,boton2;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        boton1 = (Button) findViewById(R.id.button2);
        boton1.setOnClickListener(this);
        boton2 = (Button) findViewById(R.id.button);
        boton2.setOnClickListener(this);

    }

    @Override
    public void onClick(View v) {

        Fragment fragment;

        android.support.v4.app.FragmentManager fm = getSupportFragmentManager();
        android.support.v4.app.FragmentTransaction ft = fm.beginTransaction();

        switch (v.getId()) {
            case R.id.button:

                fragment = new FragmentOne();
                ft.replace(R.id.fragment_container, fragment);
                ft.commit();
                break;

            case R.id.button2:
                fragment = new FragmentTwo();
                ft.replace(R.id.fragment_container, fragment);
                ft.commit();
                break;
        }
    }

}
</code>```

I created the fragments standard (Blank).

Name of fragments:

FragmentOne
FragmentTwo

```<code>    <?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_marginTop="10dp"
    android:layout_marginBottom="10dp"
    android:orientation="vertical"
    tools:context="com.example.akroma.feina_final.MainActivity">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal">

        <Button
            android:id="@+id/button2"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="Mapa" />

        <Button
            android:id="@+id/button"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="Negocis" />

    </LinearLayout>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent">

        <fragment
            android:id="@+id/fragment_container"
            android:layout_width="match_parent"
            android:layout_height="match_parent" />

    </LinearLayout>

</LinearLayout>
</code>```

Name of fragments on the tree:

FragmentOne

FragmentTwo

Edit: error:                                                                               Error inflating class fragment

Solution to the inflating:

Thanks to: @svkaka

```<code>Change the fragment for:

    <View
        android:id="@+id/fragment_container"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />
</code>```

New error:

must implement OnFragmentInteractionListener

Any ideas? I don't know what I'm doing bad.

Thanks in advance

答:
Replace this

```<code><fragment
            android:id="@+id/fragment_container"
            android:layout_width="match_parent"
            android:layout_height="match_parent" />
</code>```

with this

```<code><View
            android:id="@+id/fragment_container"
            android:layout_width="match_parent"
            android:layout_height="match_parent" />
</code>```

U are mixing dynamic and static fragments

Body:
I have this problem:

I'm trying to create an App with 2 buttons on a Layout and this buttons open 2 different Fragments, but the problem is that when I open the app it crashes.

Here's my code:

MainActivity:

package com.example.akroma.feina_final;

import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.support.v4.app.Fragment;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;

public class MainActivity extends AppCompatActivity implements View.OnClickListener {

    Button boton1,boton2;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        boton1 = (Button) findViewById(R.id.button2);
        boton1.setOnClickListener(this);
        boton2 = (Button) findViewById(R.id.button);
        boton2.setOnClickListener(this);

    }

    @Override
    public void onClick(View v) {

        Fragment fragment;

        android.support.v4.app.FragmentManager fm = getSupportFragmentManager();
        android.support.v4.app.FragmentTransaction ft = fm.beginTransaction();

        switch (v.getId()) {
            case R.id.button:

                fragment = new FragmentOne();
                ft.replace(R.id.fragment_container, fragment);
                ft.commit();
                break;

            case R.id.button2:
                fragment = new FragmentTwo();
                ft.replace(R.id.fragment_container, fragment);
                ft.commit();
                break;
        }
    }

}

I created the fragments standard (Blank).

Name of fragments:

FragmentOne
FragmentTwo

    <?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_marginTop="10dp"
    android:layout_marginBottom="10dp"
    android:orientation="vertical"
    tools:context="com.example.akroma.feina_final.MainActivity">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal">

        <Button
            android:id="@+id/button2"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="Mapa" />

        <Button
            android:id="@+id/button"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="Negocis" />

    </LinearLayout>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent">

        <fragment
            android:id="@+id/fragment_container"
            android:layout_width="match_parent"
            android:layout_height="match_parent" />

    </LinearLayout>

</LinearLayout>

Name of fragments on the tree:

FragmentOne

FragmentTwo

Edit: error:                                                                               Error inflating class fragment

Solution to the inflating:

Thanks to: @svkaka

Change the fragment for:

    <View
        android:id="@+id/fragment_container"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

New error:

must implement OnFragmentInteractionListener

Any ideas? I don't know what I'm doing bad.

Thanks in advance

Body:
Replace this

<fragment
            android:id="@+id/fragment_container"
            android:layout_width="match_parent"
            android:layout_height="match_parent" />

with this

<View
            android:id="@+id/fragment_container"
            android:layout_width="match_parent"
            android:layout_height="match_parent" />

U are mixing dynamic and static fragments


来源: stackexchange

问:
How to add a point to chart.js line chart?
I created a graph to represent the BMI (Body math index) values, using chart.js

My question, is there any way to add a point or mark on specific point that represent the BMI for the patient under test like below:

答:
Chart.js uses a canvas, so, using the same ctx variable you passed to chart.js:</p>

```<code>ctx.beginPath();
ctx.fillStyle = "#000";//or whatever color
ctx.arc(0,0,20,0,Math.PI*2); //maybe too big for you, but you get the point
ctx.fill();
</code>```

ContentLicense: CC BY-SA 3.0

Body:
Chart.js uses a canvas, so, using the same ctx variable you passed to chart.js:

ctx.beginPath();
ctx.fillStyle = "#000";//or whatever color
ctx.arc(0,0,20,0,Math.PI*2); //maybe too big for you, but you get the point
ctx.fill();


问:
can't cast wrapper to object
I have two long variables and I wanted to cast them to an object type. I know that if I cast the long variables to Long wrapper, then cast the wrappers to an object it will work, but the compiler says "cannot cast from Long to text" text is an a object type.</p>

```<code>private quantity start;
private quantity end;

public quantity(long s , long e) {
    Long e1 = (Long) e;
    Long s1 = (Long) s;
    start = (quantity) s1;
    end = (quantity) e1;
}
</code>```

答:
If your purpose is to have a string representation of long then you can use the following.

```<code>Long.toString(number);
</code>```

and then you can assign it to the text type. I am assuming here that text is representing some string data.

Title: can't cast wrapper to object

Body:
I have two long variables and I wanted to cast them to an object type. I know that if I cast the long variables to Long wrapper, then cast the wrappers to an object it will work, but the compiler says "cannot cast from Long to text" text is an a object type.

private quantity start;
private quantity end;

public quantity(long s , long e) {
    Long e1 = (Long) e;
    Long s1 = (Long) s;
    start = (quantity) s1;
    end = (quantity) e1;
}

Body:
If your purpose is to have a string representation of long then you can use the following.

Long.toString(number);

and then you can assign it to the text type. I am assuming here that text is representing some string data.


问:
C++: More precise timing intervals
I need to periodically do a particular task and am currently using nanosleep.

The task needs to be run every second or every 10 seconds.

Is there a better way to do this than:

```<code>while(true)
{
 doTask();
 sleep();
}
</code>```

Walter

答: One of the options could be to create a thread that will do the task with specified timeout.</p>

ContentLicense: CC BY-SA 2.5

Title: C++: More precise timing intervals

Body:
I need to periodically do a particular task and am currently using nanosleep.

The task needs to be run every second or every 10 seconds.

Is there a better way to do this than:

while(true)
{
 doTask();
 sleep();
}

Walter


问:
Weight random number towards range
Let's say I'm getting  random number in the range using:

```<code>random.randrange(100)
</code>```

Let's say that if it gives a number less than or equal to 25, you win and if it gives a number greater than 25, I win. I would then have a 75% chance to win.

How can I weight the chances of the number being greater than 25 by some percentage, say 1%.

So basically I'm trying to tilt the odds of me winning by another 1%, without changing just saying, "you win at 24 or less."

Let me know if this is unclear.

答:
If you want 1% of 25% you need to use a larger sample and use a value accordingly: 100000 and 249750.

Another solution is adding an if with a change of 1% winning if the player lost the first try.

```<code>if random.range(100) > 25
  return "You Win"
else
 if random.range(100) < 1
   return "You Win"
 else
  return "You Lose"
</code>```

Title: Weight random number towards range

Body:
Let's say I'm getting  random number in the range using:

random.randrange(100)

Let's say that if it gives a number less than or equal to 25, you win and if it gives a number greater than 25, I win. I would then have a 75% chance to win.

How can I weight the chances of the number being greater than 25 by some percentage, say 1%.

So basically I'm trying to tilt the odds of me winning by another 1%, without changing just saying, "you win at 24 or less."

Let me know if this is unclear.

Body:
If you want 1% of 25% you need to use a larger sample and use a value accordingly: 100000 and 249750.

Another solution is adding an if with a change of 1% winning if the player lost the first try.

if random.range(100) > 25
  return "You Win"
else
 if random.range(100) < 1
   return "You Win"
 else
  return "You Lose"


答:
Get a random number smaller than your range. Say you want 1-100 with mostly 60s.

Random 1-5

When 1, random 60-69

Otherwise, random 1-100

Will be 28% 60s, if my math is correct

--z

For your example, I believe you'd want to random 1-100, then on 1 random 26-100. That's not exactly a 1% increase, but you can fiddle with the math to get the percents you want.

Title: Weight random number towards range


问:
set array to property of a structure
I'm using C#. Trying to do a structure with array property. It is my code:

```<code>namespace ConsoleApplication3

{
    struct Dummy
    {
        public bool one;
        public string two;
        public int[] three;

        public Dummy(bool o, string t, int[] th)
        {
            one = o; two=t; three=th;
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
           int[] K = {5,2};
           Dummy d = new Dummy(true, "mnm", K);
            Console.WriteLine("{0} {1} {2}", d.one, d.two, d.three);

            Console.Write("Press any key to continue . . . ");
            Console.ReadKey(true);
        }
    }
}
</code>```

However d.three is System.Int32[] but not {5, 2}. How can I fix it?

答: PrintArray(int[] array). There iterate over each element and stringify it. </p>

Title: set array to property of a structure

Body:
I'm using C#. Trying to do a structure with array property. It is my code:

namespace ConsoleApplication3

{
    struct Dummy
    {
        public bool one;
        public string two;
        public int[] three;

        public Dummy(bool o, string t, int[] th)
        {
            one = o; two=t; three=th;
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
           int[] K = {5,2};
           Dummy d = new Dummy(true, "mnm", K);
            Console.WriteLine("{0} {1} {2}", d.one, d.two, d.three);

            Console.Write("Press any key to continue . . . ");
            Console.ReadKey(true);
        }
    }
}

However d.three is System.Int32[] but not {5, 2}. How can I fix it?


问:
the way of writing constructor, deconstructor and copy constructor for matrix class
I am trying to create a constructor, destructor, and copy constructor for  a matrix class, and I am not so sure if I am doing it well.

In particular, I am not sure about 2 things:

Is the destructor suppose to free memory also for the memory that is allocated in the copy-constructor?

As to the line Mat[i][j]=other[i][j] (see in the code below), I wonder if I should write Mat[i][j]=other.Mat[i][j] instead?

```<code>class Matrix
{
private:
    int rows;
    int cols;
    int **Mat;

public:
    Matrix (const int &rows,const int &cols);
    Matrix (const Matrix &other);
    ~Matrix ();
};

Matrix::Matrix(const int &n_rows,const int &n_cols) //constructor of class Matrix
{
    rows=n_rows;
    cols=n_cols;
    Mat=new int* [cols];

    for(int i =0;i<rows;i++)
       Mat[i]=new int[cols];

    for(int i=0;i<rows;i++)
      for(int j=0;j<cols;j++)
        Mat[i][j]=0;
}

Matrix::~Matrix () //destructor
{
    for(int i =0;i<rows;i++)
        delete Mat[i];

    delete[] Mat;
}

Matrix::Matrix(const Matrix &other)  //copy constructor
{
    cols=other.cols;
    rows=other.rows;
    Mat=new int* [other.rows];

    for(int i =0;i<other.rows;i++)
       Mat[i]=new int[other.cols];

    for(int i=0;i<other.rows;i++)
      for(int j=0;j<other.cols;j++)
            Mat[i][j]=other[i][j];
}
</code>```

答:
A constructor is a class operation that initializes an object instance of a specific class.

The object creation involves several operations such as:

Allocating memory to store the structure for the new object

Initializing the object's attributes properly.

A copy constructor is a special case of constructor, that takes an instance of the same class as an input parameter. - It is still a constructor, performing the same operations mentioned above.

A destructor is a class operation which is responsible for finalizing an object when it is not to be used anymore.

An object can be constructed using any constructor it defines, either ordinary or copy constructor. When you delete that object, any memory allocated by your class should be deallocated in the destructor.

Hope this helps.

As for your code related question; when invoking a copy constructor, you pass an existing object instance of the class. Since you don't have any operator overloading implemented, you access the object's property like you said in #2.

I am not sure if this answers your questions fully, but I hope it helps.

Body:
I am trying to create a constructor, destructor, and copy constructor for  a matrix class, and I am not so sure if I am doing it well.

In particular, I am not sure about 2 things:

Is the destructor suppose to free memory also for the memory that is allocated in the copy-constructor?

As to the line Mat[i][j]=other[i][j] (see in the code below), I wonder if I should write Mat[i][j]=other.Mat[i][j] instead?

class Matrix
{
private:
    int rows;
    int cols;
    int **Mat;

public:
    Matrix (const int &rows,const int &cols);
    Matrix (const Matrix &other);
    ~Matrix ();
};

Matrix::Matrix(const int &n_rows,const int &n_cols) //constructor of class Matrix
{
    rows=n_rows;
    cols=n_cols;
    Mat=new int* [cols];

    for(int i =0;i<rows;i++)
       Mat[i]=new int[cols];

    for(int i=0;i<rows;i++)
      for(int j=0;j<cols;j++)
        Mat[i][j]=0;
}

Matrix::~Matrix () //destructor
{
    for(int i =0;i<rows;i++)
        delete Mat[i];

    delete[] Mat;
}

Matrix::Matrix(const Matrix &other)  //copy constructor
{
    cols=other.cols;
    rows=other.rows;
    Mat=new int* [other.rows];

    for(int i =0;i<other.rows;i++)
       Mat[i]=new int[other.cols];

    for(int i=0;i<other.rows;i++)
      for(int j=0;j<other.cols;j++)
            Mat[i][j]=other[i][j];
}


问:
NoClassDefFoundError: Could not initialize XXX class after deploying on spark standalone cluster
I wrote a spark streaming application built with sbt. It works perfectly fine locally, but after deploying on the cluster, it complains about a class I wrote which clearly in the fat jar (checked using jar tvf). The following is my project structure. XXX object is the one that spark complains about

```<code>src
`-- main
    `-- scala
        |-- packageName
        |   `-- XXX object
        `-- mainMethodEntryObject
</code>```

My submit command:

```<code>$SPARK_HOME/bin/spark-submit \
  --class mainMethodEntryObject \
  --master REST_URL\
  --deploy-mode cluster \
  hdfs:///FAT_JAR_PRODUCED_BY_SBT_ASSEMBLY
</code>```

Specific error message:

```<code>java.lang.NoClassDefFoundError: Could not initialize class XXX
</code>```

答:
It's difficult to say without the code but it looks like a problem of serialization of your XXX object. I can't say I'm understand perfectly why, but the point is that the object is not shipped to the executor.

The solution that worked for me is to convert your object to a class that extends Serializable and just instantiate it where you need it. So basically, if I'm not wrong you have

```<code>object test {
   def foo = ...
}
</code>```

which would be used as test.foo in your main, but you need at minimum

```<code>class Test extends Serializable {
   def foo = ...
}
</code>```

and then in your main have val test = new Test at the beginning and that's it.

Body:
I wrote a spark streaming application built with sbt. It works perfectly fine locally, but after deploying on the cluster, it complains about a class I wrote which clearly in the fat jar (checked using jar tvf). The following is my project structure. XXX object is the one that spark complains about

src
`-- main
    `-- scala
        |-- packageName
        |   `-- XXX object
        `-- mainMethodEntryObject

My submit command:

$SPARK_HOME/bin/spark-submit \
  --class mainMethodEntryObject \
  --master REST_URL\
  --deploy-mode cluster \
  hdfs:///FAT_JAR_PRODUCED_BY_SBT_ASSEMBLY

Specific error message:

java.lang.NoClassDefFoundError: Could not initialize class XXX

Body:
It's difficult to say without the code but it looks like a problem of serialization of your XXX object. I can't say I'm understand perfectly why, but the point is that the object is not shipped to the executor.

The solution that worked for me is to convert your object to a class that extends Serializable and just instantiate it where you need it. So basically, if I'm not wrong you have

object test {
   def foo = ...
}

which would be used as test.foo in your main, but you need at minimum

class Test extends Serializable {
   def foo = ...
}

and then in your main have val test = new Test at the beginning and that's it.


问:
Why do these two methods of loading images from SQL CE into a WPF Image produce different results?
In a ValueConverter, I was trying to convert a System.Data.Linq.Binary (SQL CE image) to a BitmapImage. This method works (image is show correctly on the form):

```<code>public object Convert(object value, Type targetType, object parameter,
                                                     CultureInfo culture) {
    Binary binary = value as Binary;
    if (binary != null) {
        BitmapImage bitmap = new BitmapImage();
        bitmap.BeginInit();
        bitmap.StreamSource = new MemoryStream(binary.ToArray());
        bitmap.EndInit();
        return bitmap;
    }
    return null;
}
</code>```

This method does NOT work (but no exception is thrown, strangely):

```<code>public object Convert(object value, Type targetType, object parameter,
                                                     CultureInfo culture) {
    Binary binary = value as Binary;
    if (binary != null) {
        using (var stream = new MemoryStream(binary.ToArray())) {
            BitmapImage bitmap = new BitmapImage();
            bitmap.BeginInit();
            bitmap.StreamSource = stream;
            bitmap.EndInit();
            return bitmap;
        }
    }
    return null;
}
</code>```

Good programming practice states that you should dispose of any streams you create... so I'm confused why the second method doesn't work, but the first does. Any insights?

答: My guess would that when you are disposing the MemoryStream, you are nullifying the StreamSource of the bitmap. So, when the bitmap tries to render, there is no valid data available.

Body:
In a ValueConverter, I was trying to convert a System.Data.Linq.Binary (SQL CE image) to a BitmapImage. This method works (image is show correctly on the form):

public object Convert(object value, Type targetType, object parameter,
                                                     CultureInfo culture) {
    Binary binary = value as Binary;
    if (binary != null) {
        BitmapImage bitmap = new BitmapImage();
        bitmap.BeginInit();
        bitmap.StreamSource = new MemoryStream(binary.ToArray());
        bitmap.EndInit();
        return bitmap;
    }
    return null;
}

This method does NOT work (but no exception is thrown, strangely):

public object Convert(object value, Type targetType, object parameter,
                                                     CultureInfo culture) {
    Binary binary = value as Binary;
    if (binary != null) {
        using (var stream = new MemoryStream(binary.ToArray())) {
            BitmapImage bitmap = new BitmapImage();
            bitmap.BeginInit();
            bitmap.StreamSource = stream;
            bitmap.EndInit();
            return bitmap;
        }
    }
    return null;
}

Good programming practice states that you should dispose of any streams you create... so I'm confused why the second method doesn't work, but the first does. Any insights?


问:
Surprising implicit assumptions in intuitionistic definitions
I'm trying to make sense of something that surprised me.  Consider the following two definitions.

```<code>Require Import List.
Variable A:Type.

Inductive NoDup : list A -> Prop :=
  NoDup_nil : NoDup nil
| NoDup_cons : forall x l, ~ In x l -> NoDup l -> NoDup (x :: l).

Inductive Dup : list A -> Prop :=
  Dup_hd : forall x l, In x l -> Dup (x :: l)
| Dup_tl : forall x l, Dup l  -> Dup (x :: l).
</code>```

My first intuition was that they say the same thing (but negated).  However, @Arthur Azevedo De Amorim showed that they are not exactly equivalent (or see here). If ~ NoDup l -> Dup l then it must be the case that forall (a b:A), ~ a <> b -> a = b.  Thus, an extra assumption on the type A sneaks in if one uses ~ NoDup rather than Dup when stating one's proof goal.

I tried to spot where this extra assumption is introduced, to get a mental model of what happened, so I will see it myself next time.  My current explanation is that

it is the ~ In x l argument to NoDup_cons that is responsible, because

~ In x l terms can only be created if one can prove that a certain x is different from the first element in the list, the second element in the list, etc.

So when I destruct a term om type NoDup (_::_) I get a term ~ In _ _ that can only have been created for a type A for which  ~ a <> b -> a = b must hold.

Q: is that  an ok 'informal' way to think about it, or is there a better way to understand it, so I don't fall into that trap again?

Also, I found that the Coq library contains NoDup and not Dup, so perhaps some lemmas are weaker than they need to be, because they were formulated using NoDup instead of Dup. However, they could be formulated with Dup because ~Dup l -> NoDup l.

答:
I think the lesson to take out of this example is that you need to be more careful when thinking about negations in intuitionistic logic.  In particular, your statement "they say the same thing (but negated)" makes sense in classical logic: it means either of the equivalent statements P <-> ~Q or ~P <-> Q.  However, in intuitionistic logic these two statements are not equivalent, so you would have to be more specific about which of these two (if either) is actually true.

In this case, it is true that NoDup l is equivalent to ~ Dup l.  What is not true in general is that Dup l is a normal proposition (recall that a proposition P is called normal if ~~P -> P, in which case it's easy to conclude that P <-> ~~P).  Therefore, ~ NoDup l is equivalent to ~~ Dup l, which in general is a strictly weaker statement than Dup l.

One possible way to think about the difference between the two is: from a concrete proof of Dup l, it would be possible to extract a pair of indices such that the corresponding entries of l are equal (not literally as a function in Coq due to the restrictions on eliminating from Prop to Type, but you could definitely prove a lemma that there exists such a pair of indices).  On the other hand, a concrete proof of ~ NoDup l simply gives a way to take a purported proof of NoDup l and derive a contradiction from it - from which you can't necessarily extract any particular pair of indices.

(I do agree it's somewhat odd that the standard library has only NoDup and not Dup.)

Body:
I'm trying to make sense of something that surprised me.  Consider the following two definitions.

Require Import List.
Variable A:Type.

Inductive NoDup : list A -> Prop :=
  NoDup_nil : NoDup nil
| NoDup_cons : forall x l, ~ In x l -> NoDup l -> NoDup (x :: l).

Inductive Dup : list A -> Prop :=
  Dup_hd : forall x l, In x l -> Dup (x :: l)
| Dup_tl : forall x l, Dup l  -> Dup (x :: l).

My first intuition was that they say the same thing (but negated).  However, @Arthur Azevedo De Amorim showed that they are not exactly equivalent (or see here). If ~ NoDup l -> Dup l then it must be the case that forall (a b:A), ~ a <> b -> a = b.  Thus, an extra assumption on the type A sneaks in if one uses ~ NoDup rather than Dup when stating one's proof goal.

I tried to spot where this extra assumption is introduced, to get a mental model of what happened, so I will see it myself next time.  My current explanation is that

it is the ~ In x l argument to NoDup_cons that is responsible, because

~ In x l terms can only be created if one can prove that a certain x is different from the first element in the list, the second element in the list, etc.

So when I destruct a term om type NoDup (_::_) I get a term ~ In _ _ that can only have been created for a type A for which  ~ a <> b -> a = b must hold.

Q: is that  an ok 'informal' way to think about it, or is there a better way to understand it, so I don't fall into that trap again?

Also, I found that the Coq library contains NoDup and not Dup, so perhaps some lemmas are weaker than they need to be, because they were formulated using NoDup instead of Dup. However, they could be formulated with Dup because ~Dup l -> NoDup l.


问:
MATLAB: discover restricted class of properties
MATLAB R2016a introduced a documented mechanism for restricting the class of the properties of an object (I'm aware that there's also an older, different, undocumented way to do that, but I'm not using that method). For example:

```<code>classdef MyClass
    properties
        myProperty RestrictedClass
    end
end
</code>```

will restrict the property myProperty so that its values must be of class RestrictedClass.

If you've implemented such a class, is there a way to use MATLAB's class metadata interface to programmatically discover the class of the restricted property?

I was hoping that if I used

```<code>m = ?MyClass;
p = m.PropertyList(1);
</code>```

then the metaproperty object p would contain information about the class to which it was restricted - but it seems not.

Is there a way to programmatically discover it? The method would need to not involve actually instantiating the class - both because that might have side effects, and also because it would need to work with Abstract classes.

PS Also not involving anything gross like parsing the source code of the class. Imagine that I might like to do this with a class whose source code had been obfuscated using pcode.

答:
You can use the undocumented hack of converting an object to a structure in order to inspect the non-public properties of the object. The meta.Property objects contain a hidden meta.Validation object property, which has the validation information for the property:

```<code>  Validation with properties:

                 Class: [1×1 meta.class]
                  Size: [1×0 meta.ArrayDimension]
    ValidatorFunctions: {1×0 cell}
</code>```

With a given example class:

```<code>classdef SOcode
    properties
        myProperty1 double
        myProperty2 struct
    end
end
</code>```

We can inspect the meta.PropertyList to locate the values we need:

```<code>>> test = struct(codemeta.PropertyList(1))

test =

  struct with fields:

                    Name: 'myProperty1'

                    ... snip ...

                    Type: [1×1 meta.type]
              Validation: [1×1 meta.Validation]
           DefiningClass: [1×1 meta.class]

                    ... snip ...
</code>```

We can then do something like the following:

```<code>codemeta = ?SOcode;

nprops = numel(codemeta.PropertyList);
validationclass = cell(nprops, 1);

for ii = 1:nprops
    validationclass{ii} = codemeta.PropertyList(ii).Validation.Class.Name;
end
</code>```

And receive:

```<code>>> validationclass

validationclass =

  2×1 cell array

    {'double'}
    {'struct'}
</code>```

Body:
MATLAB R2016a introduced a documented mechanism for restricting the class of the properties of an object (I'm aware that there's also an older, different, undocumented way to do that, but I'm not using that method). For example:

classdef MyClass
    properties
        myProperty RestrictedClass
    end
end

will restrict the property myProperty so that its values must be of class RestrictedClass.

If you've implemented such a class, is there a way to use MATLAB's class metadata interface to programmatically discover the class of the restricted property?

I was hoping that if I used

m = ?MyClass;
p = m.PropertyList(1);

then the metaproperty object p would contain information about the class to which it was restricted - but it seems not.

Is there a way to programmatically discover it? The method would need to not involve actually instantiating the class - both because that might have side effects, and also because it would need to work with Abstract classes.

PS Also not involving anything gross like parsing the source code of the class. Imagine that I might like to do this with a class whose source code had been obfuscated using pcode.

Body:
You can use the undocumented hack of converting an object to a structure in order to inspect the non-public properties of the object. The meta.Property objects contain a hidden meta.Validation object property, which has the validation information for the property:

  Validation with properties:

                 Class: [1×1 meta.class]
                  Size: [1×0 meta.ArrayDimension]
    ValidatorFunctions: {1×0 cell}

With a given example class:

classdef SOcode
    properties
        myProperty1 double
        myProperty2 struct
    end
end

We can inspect the meta.PropertyList to locate the values we need:

>> test = struct(codemeta.PropertyList(1))

test =

  struct with fields:

                    Name: 'myProperty1'

                    ... snip ...

                    Type: [1×1 meta.type]
              Validation: [1×1 meta.Validation]
           DefiningClass: [1×1 meta.class]

                    ... snip ...

We can then do something like the following:

codemeta = ?SOcode;

nprops = numel(codemeta.PropertyList);
validationclass = cell(nprops, 1);

for ii = 1:nprops
    validationclass{ii} = codemeta.PropertyList(ii).Validation.Class.Name;
end

And receive:

>> validationclass

validationclass =

  2×1 cell array

    {'double'}
    {'struct'}


问:
PrimeNg color picker overlay hidden behind dialog
I'm using PrimeNG color picker overlay inside a dialog.

```<code><p-colorPicker [(ngModel)]="activity.color" name="color" appendTo="body"></p-colorPicker>
</code>```

The problem is that picker is not showing and expands the dialog body adding the scrollbars. I want the colorpicker to overlay over the dialog.

Setting appendTo="body" works for calendar widget, but not color picker. Based on docs I experimented with various options like e.g. specifying template variable in dialog <p-dialog #activityDialog ... and referencing it in appendTo of colorpicker, but this is not working.

答:
Update:

```<code><p-dialog [contentStyle]="{'overflow':'visible'}">
</p-dialog>
</code>```

this does it all and is documented already: here

I got it to work by setting:

```<code>:host /deep/.ui-dialog .ui-dialog-content {
    overflow: visible;
}
</code>```

in the css of the component containing the dialog.
Though :host /deep/ is  deprecated by Angular

Body:
I'm using PrimeNG color picker overlay inside a dialog.

The problem is that picker is not showing and expands the dialog body adding the scrollbars. I want the colorpicker to overlay over the dialog.

Setting appendTo="body" works for calendar widget, but not color picker. Based on docs I experimented with various options like e.g. specifying template variable in dialog <p-dialog #activityDialog ... and referencing it in appendTo of colorpicker, but this is not working.

Body:
Update:

<p-dialog [contentStyle]="{'overflow':'visible'}">
</p-dialog>

this does it all and is documented already: here

I got it to work by setting:

:host /deep/.ui-dialog .ui-dialog-content {
    overflow: visible;
}

in the css of the component containing the dialog.
Though :host /deep/ is  deprecated by Angular


问:
How to avoid creating unnecessary lists?
I keep coming across situations where I pull some information from a file or wherever, then have to massage the data to the final desired form through several steps. For example:

```<code>def insight_pull(file):
    with open(file) as in_f:
        lines = in_f.readlines()

        dirty = [line.split('    ') for line in lines]
        clean = [i[1] for i in dirty]
        cleaner = [[clean[i],clean[i + 1]] for i in range(0, len(clean),2)]
        cleanest = [i[0].split() + i[1].split() for i in cleaner]

        with open("Output_File.txt", "w") as out_f:
            out_f.writelines(' '.join(i) + '\n' for i in cleanest)
</code>```

As per the example above:

```<code>    # Pull raw data from file splitting on '   '.
    dirty = [line.split('    ') for line in lines]

    # Select every 2nd element from each nested list.
    clean = [i[1] for i in dirty]

    # Couple every 2nd element with it's predecessor into a new list.
    cleaner = [[clean[i],clean[i + 1]] for i in range(0, len(clean),2)]

    # Split each entry in cleaner into the final formatted list.
    cleanest = [i[0].split() + i[1].split() for i in cleaner]
</code>```

Seeing as I can't put all of the edits into one line or loop (since each edit depends on the edit before it), is there a better way to structure code like this?

Apologies if the question is a bit vague. Any input is much appreciated.

答:
I am assuming from your example that only the cleanest list is of any practical value to you, the rest are just intermediary steps and can be discarded without concern.

Assuming that is the case, why not just reuse the same variable with each intermediate step, so that way you are not holding multiple lists in memory?

def insight_pull(file):
    with open(file) as in_f:
        my_list = in_f.readlines()

        my_list = [line.split('    ') for line in my_list]
        my_list = [i[1] for i in my_list]
        my_list = [[my_list[i],my_list[i + 1]] for i in range(0, len(my_list),2)]
        my_list = [i[0].split() + i[1].split() for i in my_list]

    with open("Output_File.txt", "w") as out_f:
        out_f.writelines(' '.join(i) + '\n' for i in my_list)
```

Body:
I keep coming across situations where I pull some information from a file or wherever, then have to massage the data to the final desired form through several steps. For example:

def insight_pull(file):
    with open(file) as in_f:
        lines = in_f.readlines()

        dirty = [line.split('    ') for line in lines]
        clean = [i[1] for i in dirty]
        cleaner = [[clean[i],clean[i + 1]] for i in range(0, len(clean),2)]
        cleanest = [i[0].split() + i[1].split() for i in cleaner]

        with open("Output_File.txt", "w") as out_f:
            out_f.writelines(' '.join(i) + '\n' for i in cleanest)

As per the example above:

    # Pull raw data from file splitting on '   '.
    dirty = [line.split('    ') for line in lines]

    # Select every 2nd element from each nested list.
    clean = [i[1] for i in dirty]

    # Couple every 2nd element with it's predecessor into a new list.
    cleaner = [[clean[i],clean[i + 1]] for i in range(0, len(clean),2)]

    # Split each entry in cleaner into the final formatted list.
    cleanest = [i[0].split() + i[1].split() for i in cleaner]

Seeing as I can't put all of the edits into one line or loop (since each edit depends on the edit before it), is there a better way to structure code like this?

Apologies if the question is a bit vague. Any input is much appreciated.


问:
RewriteRule on litespeed question
My rule works good when I access http://domain.com/example . The Query looks good etc.

When I visis http://domain.com the index.php does not load, seem that a blank redirect is done, http://domain.com/city.php?q=

How can I get the index.php to load instead of a the Rewrite kicking in...

```<code>Options +FollowSymLinks
RewriteCond %{REQUEST_URI} !\.(css|jpg|gif|png|jar|js|html|htm|php)$
RewriteEngine On
RewriteRule ^([^/]*)$ /city.php?q=$1 [L]
</code>```

Thanks

答:
Ok, I got it.</p>

```<code>RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
</code>```

Title: RewriteRule on litespeed question

Body:
My rule works good when I access http://domain.com/example . The Query looks good etc.

When I visis http://domain.com the index.php does not load, seem that a blank redirect is done, http://domain.com/city.php?q=

How can I get the index.php to load instead of a the Rewrite kicking in...

Options +FollowSymLinks
RewriteCond %{REQUEST_URI} !\.(css|jpg|gif|png|jar|js|html|htm|php)$
RewriteEngine On
RewriteRule ^([^/]*)$ /city.php?q=$1 [L]

Thanks

Body:
Ok, I got it.

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d


问:
Spring data method name for enum
Is there any way to put enum value in method name with Spring Data? It can be done with @Query annotaion with something like this:

```<code>  @Query("select t from Ticket as t where t.status != desk.enums.TicketStatus.CLOSED")
  List<Ticket> findActiveTickets();
</code>```

where status is the enum. But how can it be done with only using method names? Using something like List<Ticket> findByStatusIsNotClosed(); will cause No property isNotClosed found for type TicketStatus.

So how can it be done without using @Query?

答:
If you're using Java 8, you can use the default keyword in the interface to delegate to a more generic method.

```<code>default List<Ticket> findActiveTickets() {
    return findByTicketStatusNotIn(ImmutableList.of(TicketStatus.CLOSED));
}

List<Ticket> findByTicketStatusNotIn(List<TicketStatus> status);
</code>```

Title: Spring data method name for enum

Body:
Is there any way to put enum value in method name with Spring Data? It can be done with @Query annotaion with something like this:

  @Query("select t from Ticket as t where t.status != desk.enums.TicketStatus.CLOSED")
  List<Ticket> findActiveTickets();

where status is the enum. But how can it be done with only using method names? Using something like List<Ticket> findByStatusIsNotClosed(); will cause No property isNotClosed found for type TicketStatus.

So how can it be done without using @Query?

Body:
If you're using Java 8, you can use the default keyword in the interface to delegate to a more generic method.

default List<Ticket> findActiveTickets() {
    return findByTicketStatusNotIn(ImmutableList.of(TicketStatus.CLOSED));
}

List<Ticket> findByTicketStatusNotIn(List<TicketStatus> status);


问:
Inner join two tables and join count from a third table
I have 2 main tables - posts and users, and a third table that stores a user's favourited post as a row. I need to do a query on a post that is joined with the user data, and also whether or not the current user has favourited post (lookup in the user_favs table).

Ultimately I want to return something like the following to the client:

```<code>{
    post_id: '...',
    title: '...',
    user_id: '...',
    username: '...',
    isFavourited: isFaved > 0 ? true : false
}
</code>```

Is this possible to do with 1 select query?

```<code>CREATE TABLE posts (
    post_id    uuid,
    title      text
    author_id  uuid
);

CREATE TABLE users (
    user_id   uuid,
    username  text
);

CREATE TABLE user_favs (
    user_id     uuid REFERENCES users ON DELETE CASCADE,
    post_id  uuid REFERENCES posts ON DELETE CASCADE
);
</code>```

My query looks like:

```<code>SELECT
    p.post_id,
    p.title,
    u.user_id,
    u.username,

    count(f.*) as isfaved
FROM posts p
JOIN users u
ON p.author_id = u.user_id AND p.post_id = '1234'
LEFT JOIN user_favs f
ON f.user_id = p.author_id AND f.post_id = '1234'
</code>```

and I've also tried:

```<code>SELECT
    p.post_id,
    p.title,
    u.user_id,
    u.username,
FROM posts p
JOIN users u
ON p.author_id = u.user_id AND p.post_id = '1234'
LEFT JOIN
    (SELECT count(*) FROM user_favs
) f ON f.user_id = p.author_id AND f.post_id = '1234'
</code>```

EDIT: Just to clarify what I'm hoping to accomplish: I'm fetching a post, returning respective author of that post, and then also checking if the post is favorited by the requesting user.

答:
i changed the tables so i can test it. With the information you gave:
Select for given post, the post information, the author and whether the current user (the logged user i guess) faved that post : </p>

```<code>drop table if exists user_favs cascade;
drop table if exists posts cascade;
drop table if exists users cascade;

CREATE TABLE users (
    user_id   int primary key,
    username  text
);

CREATE TABLE posts (
    post_id    int primary key,
    title      text,
    user_id  int references users
);

CREATE TABLE user_favs (
    user_id     int REFERENCES users ON DELETE CASCADE,
    post_id  int REFERENCES posts ON DELETE CASCADE
);

SELECT
    p.post_id,
    p.title,
    u.user_id,
    u.username,

    case when f.user_id is not null then true else false end as isfaved
FROM posts p
JOIN users u ON p.user_id = u.user_id
LEFT JOIN user_favs f on f.post_id = p.post_id
where p.post_id=1234 -- the post you want to select
and f.user_id = 4321; -- the id of the current user
</code>```

Body:
I have 2 main tables - posts and users, and a third table that stores a user's favourited post as a row. I need to do a query on a post that is joined with the user data, and also whether or not the current user has favourited post (lookup in the user_favs table).

Ultimately I want to return something like the following to the client:

{
    post_id: '...',
    title: '...',
    user_id: '...',
    username: '...',
    isFavourited: isFaved > 0 ? true : false
}

Is this possible to do with 1 select query?

CREATE TABLE posts (
    post_id    uuid,
    title      text
    author_id  uuid
);

CREATE TABLE users (
    user_id   uuid,
    username  text
);

CREATE TABLE user_favs (
    user_id     uuid REFERENCES users ON DELETE CASCADE,
    post_id  uuid REFERENCES posts ON DELETE CASCADE
);

My query looks like:

SELECT
    p.post_id,
    p.title,
    u.user_id,
    u.username,

    count(f.*) as isfaved
FROM posts p
JOIN users u
ON p.author_id = u.user_id AND p.post_id = '1234'
LEFT JOIN user_favs f
ON f.user_id = p.author_id AND f.post_id = '1234'

and I've also tried:

SELECT
    p.post_id,
    p.title,
    u.user_id,
    u.username,
FROM posts p
JOIN users u
ON p.author_id = u.user_id AND p.post_id = '1234'
LEFT JOIN
    (SELECT count(*) FROM user_favs
) f ON f.user_id = p.author_id AND f.post_id = '1234'

EDIT: Just to clarify what I'm hoping to accomplish: I'm fetching a post, returning respective author of that post, and then also checking if the post is favorited by the requesting user.

Body:
i changed the tables so i can test it. With the information you gave:
Select for given post, the post information, the author and whether the current user (the logged user i guess) faved that post :

drop table if exists user_favs cascade;
drop table if exists posts cascade;
drop table if exists users cascade;

CREATE TABLE users (
    user_id   int primary key,
    username  text
);

CREATE TABLE posts (
    post_id    int primary key,
    title      text,
    user_id  int references users
);

CREATE TABLE user_favs (
    user_id     int REFERENCES users ON DELETE CASCADE,
    post_id  int REFERENCES posts ON DELETE CASCADE
);

SELECT
    p.post_id,
    p.title,
    u.user_id,
    u.username,

    case when f.user_id is not null then true else false end as isfaved
FROM posts p
JOIN users u ON p.user_id = u.user_id
LEFT JOIN user_favs f on f.post_id = p.post_id
where p.post_id=1234 -- the post you want to select
and f.user_id = 4321; -- the id of the current user


问:
Rounded corners on material button
I'm following the tips from questions like this to create a button style like suggested on Material Design.

However, I need to change the corner radius and haven't been able to do so by inheriting Widget.AppCompat.Button.Colored style and setting the radius parameter.

How can I have the same style but with rounded corners?

答:
Also another simple way is wrap it around cardView,Remember to set the layout_width and layout_height of the cardView to wrap_content, also all the needed margin the button will need should be applied to the cardView</p>

```<code><android.support.v7.widget.CardView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            app:cardCornerRadius="8dp"
            android:layout_marginLeft="10dp"
            android:layout_marginRight="10dp"
            android:layout_marginBottom="40dp"
            app:elevation="10dp">

            <android.support.v7.widget.AppCompatButton
                android:id="@+id/login_twitter"
                android:tag="login_twitter"
                android:layout_width="300dp"
                android:layout_height="60dp"
                android:paddingLeft="10dp"
           android:foreground="?attr/selectableItemBackgroundBorderless"
                android:textColor="@color/blue_grey_ligthen_5"
                android:drawableLeft="@drawable/twitter"
                android:background="@color/twitter"
                android:text="@string/login_with_twitter" />
        </android.support.v7.widget.CardView>
</code>```

ContentLicense: CC BY-SA 4.0

Title: Rounded corners on material button

Body:
Also another simple way is wrap it around cardView,Remember to set the layout_width and layout_height of the cardView to wrap_content, also all the needed margin the button will need should be applied to the cardView

<android.support.v7.widget.CardView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            app:cardCornerRadius="8dp"
            android:layout_marginLeft="10dp"
            android:layout_marginRight="10dp"
            android:layout_marginBottom="40dp"
            app:elevation="10dp">

            <android.support.v7.widget.AppCompatButton
                android:id="@+id/login_twitter"
                android:tag="login_twitter"
                android:layout_width="300dp"
                android:layout_height="60dp"
                android:paddingLeft="10dp"
           android:foreground="?attr/selectableItemBackgroundBorderless"
                android:textColor="@color/blue_grey_ligthen_5"
                android:drawableLeft="@drawable/twitter"
                android:background="@color/twitter"
                android:text="@string/login_with_twitter" />
        </android.support.v7.widget.CardView>


答:
If you are thinking in terms of performance, you are looking for generators. Generators are much like lists, but they are evaluated lazily, meaning that each element is only produced once it's needed. For example, in the following sequence, I don't actually create 3 full lists, each element is only evaluated once. The below is just an example use of generators (as I understood that your code was just an example of the issue you run into, and not a concrete problem):

```<code># All even values from 2-18
even = (i*2 for i in range(1, 10))

# Only those divisible by 3
multiples_of_3 = (val for val in even if val % 3 == 0)

# And finally, we want to evaluate the remaining values as hex
hexes = [hex(val) for val in multiples_of_3]
# output: ['0x6', '0xc', '0x12']
</code>```

The two first expressions are generators, and the last is just a list comprehension. This will save a lot of memory when there are a lot of steps, as you don't create intermediate lists. Do note that generators cannot be indexed, and they can only be evaluated once (they're just streams of values).

Title: How to avoid creating unnecessary lists?

Body:
If you are thinking in terms of performance, you are looking for generators. Generators are much like lists, but they are evaluated lazily, meaning that each element is only produced once it's needed. For example, in the following sequence, I don't actually create 3 full lists, each element is only evaluated once. The below is just an example use of generators (as I understood that your code was just an example of the issue you run into, and not a concrete problem):

# All even values from 2-18
even = (i*2 for i in range(1, 10))

# Only those divisible by 3
multiples_of_3 = (val for val in even if val % 3 == 0)

# And finally, we want to evaluate the remaining values as hex
hexes = [hex(val) for val in multiples_of_3]
# output: ['0x6', '0xc', '0x12']

The two first expressions are generators, and the last is just a list comprehension. This will save a lot of memory when there are a lot of steps, as you don't create intermediate lists. Do note that generators cannot be indexed, and they can only be evaluated once (they're just streams of values).


问:
How to show the ten most overdue numbers in a list
I have asked a question before about this bit of code and it was answered adequately, but I have an additional question about showing the ten most overdue numbers. (This program was a part of an in-class activity, I have already received full marks for what we have done. The question I am posting here was originally going to be done in-class but we ran out of time in lecture.)

```<code>#PE 8
#11-2-17

def main():
    #import data
    winninglist=get_data()

    #find frequency for lotterynumber 1-69
    frequency=find_frequency(winninglist)

    #sort the frequency
    sortedlist=sorting(frequency)

    print("The 10 most common numbers and their corresponding frequencies are: ")
    print(sortedlist[:10])

    print("The 10 least common numbers and their corresponding frequencies are: ")
    print(sortedlist[-10:])

    #find the 10 most overdue numbers

    #find the frequency of 1-69 for the regular numbers, and 1-26 for powerball

def get_data():

    #read from the file
    infile=open('power.txt','r')
    lines=infile.readlines()
    infile.close()

    #initialize winninglist
    winninglist=[]

    #processraw data line by line, taking away new character lines, split using space, add to winninglist
    for i in range(len(lines)):
        lines[i]=lines[i].rstrip('\n')
        item=lines[i].split()
        winninglist+=item

    return winninglist

def find_frequency(winninglist):
    #frequency should be a list
    frequency=[0]*69

    #count the occurance of each number

    for i in range(69):
        for item in winninglist:
            if int(item)==(i+1):
               frequency[i]+=1

    #print(frequency)
    return frequency

def sorting(frequency):

    #record both the number and frequency
    pb_frequency=[]

    for i in range(len(frequency)):
        pb_frequency.append([i+1, frequency[i]])

    #print(pb_frequency)
    #now sort using bubble sorting
    for i in range(len(pb_frequency)):
        max=i
        for j in range(i+1, (len(pb_frequency))):
            if pb_frequency[j][1]>pb_frequency[max][1]:
                max=j

        #max has the index of the highest frequency number for this round
        #we make the exchange to bubble the largest one
        temp1=pb_frequency[i][0]
        temp2=pb_frequency[i][1]
        pb_frequency[i][0]=pb_frequency[max][0]
        pb_frequency[i][1]=pb_frequency[max][1]
        pb_frequency[max][0]=temp1
        pb_frequency[max][1]=temp2
    #print(pb_frequency)
    return pb_frequency

main()
</code>```

Here is the format of the txt file:

17 22 36 37 52 24

14 22 52 54 59 04

05 08 29 37 38 24

10 14 30 40 51 01
(the txt file has many lines of numbers like these)

I need help showing the 10 most overdue numbers. Each line has an implied date attached to it, the first line being the oldest, so, I would need code to show the 10 numbers that have occurred least recently. Is there a simple solution that I am just not seeing?

For reference, here is my last question and answer

Can you help me fix code to show the occurrence of items in a list, for only the first five items?

答:
```<code>from collections import Counter
input = ['your numbers in format of list']
d = {}

for i in input:
    if i in d:
        d.update({i: 1+d[i]})
    else:
        d.update({i: 1})

i = 0
l_min = []

while len(Counter(x for sublist in l_min for x in sublist)) < 11:
    i += 1
    l_min.append([k for k, v in d.items() if v == i])

print(l_min)
</code>```

Body:
I have asked a question before about this bit of code and it was answered adequately, but I have an additional question about showing the ten most overdue numbers. (This program was a part of an in-class activity, I have already received full marks for what we have done. The question I am posting here was originally going to be done in-class but we ran out of time in lecture.)

#PE 8
#11-2-17

def main():
    #import data
    winninglist=get_data()

    #find frequency for lotterynumber 1-69
    frequency=find_frequency(winninglist)

    #sort the frequency
    sortedlist=sorting(frequency)

    print("The 10 most common numbers and their corresponding frequencies are: ")
    print(sortedlist[:10])

    print("The 10 least common numbers and their corresponding frequencies are: ")
    print(sortedlist[-10:])

    #find the 10 most overdue numbers

    #find the frequency of 1-69 for the regular numbers, and 1-26 for powerball

def get_data():

    #read from the file
    infile=open('power.txt','r')
    lines=infile.readlines()
    infile.close()

    #initialize winninglist
    winninglist=[]

    #processraw data line by line, taking away new character lines, split using space, add to winninglist
    for i in range(len(lines)):
        lines[i]=lines[i].rstrip('\n')
        item=lines[i].split()
        winninglist+=item

    return winninglist

def find_frequency(winninglist):
    #frequency should be a list
    frequency=[0]*69

    #count the occurance of each number

    for i in range(69):
        for item in winninglist:
            if int(item)==(i+1):
               frequency[i]+=1

    #print(frequency)
    return frequency

def sorting(frequency):

    #record both the number and frequency
    pb_frequency=[]

    for i in range(len(frequency)):
        pb_frequency.append([i+1, frequency[i]])

    #print(pb_frequency)
    #now sort using bubble sorting
    for i in range(len(pb_frequency)):
        max=i
        for j in range(i+1, (len(pb_frequency))):
            if pb_frequency[j][1]>pb_frequency[max][1]:
                max=j

        #max has the index of the highest frequency number for this round
        #we make the exchange to bubble the largest one
        temp1=pb_frequency[i][0]
        temp2=pb_frequency[i][1]
        pb_frequency[i][0]=pb_frequency[max][0]
        pb_frequency[i][1]=pb_frequency[max][1]
        pb_frequency[max][0]=temp1
        pb_frequency[max][1]=temp2
    #print(pb_frequency)
    return pb_frequency

main()

Here is the format of the txt file:

17 22 36 37 52 24

14 22 52 54 59 04

05 08 29 37 38 24

10 14 30 40 51 01
(the txt file has many lines of numbers like these)

I need help showing the 10 most overdue numbers. Each line has an implied date attached to it, the first line being the oldest, so, I would need code to show the 10 numbers that have occurred least recently. Is there a simple solution that I am just not seeing?

For reference, here is my last question and answer

Can you help me fix code to show the occurrence of items in a list, for only the first five items?


问:
How can I multiply corresponding values of two 1-dimensional arrays in Java?

So far, I have created 2 arrays (x and y), each with a length of 20 and are filled with random integers.

I'm trying to multiply the value of each index in one array with the value of the same index in another array, and then storing the product in a 3rd array (z).

```<code>int z[] = new int[20];  //creating array z, which will hold the products of the corresponding indexes of arrays x and y
        for(int i = 0; i <z.length; i++)
        {
            //loop for mutliplying x and y
        }
</code>```

The result:  if array "x" looks like {4, 8, 2, 6, ... }, and array "y" looks like {7, 5, 1, 8, ... }, array "z" should be populated with {28, 40, 2, 48, ... }

I have only been able to find examples on multiplying every single value between 2 arrays, but nothing on how to multiply corresponding indexes

Edit:  Thank you, user Aominè for the solution!

The equation was simply

```<code>z[i] = x[i] * y[i];
</code>```

答:
Try something like:</p>

```<code>for(int i = 0; i < z.length; i++) {
     z[i] = x[i] * y[i];
}
</code>```

Body:
So far, I have created 2 arrays (x and y), each with a length of 20 and are filled with random integers.

I'm trying to multiply the value of each index in one array with the value of the same index in another array, and then storing the product in a 3rd array (z).

int z[] = new int[20];  //creating array z, which will hold the products of the corresponding indexes of arrays x and y
        for(int i = 0; i <z.length; i++)
        {
            //loop for mutliplying x and y
        }

The result:  if array "x" looks like {4, 8, 2, 6, ... }, and array "y" looks like {7, 5, 1, 8, ... }, array "z" should be populated with {28, 40, 2, 48, ... }

I have only been able to find examples on multiplying every single value between 2 arrays, but nothing on how to multiply corresponding indexes

Edit:  Thank you, user Aominè for the solution!

The equation was simply

z[i] = x[i] * y[i];

Body:
Try something like:

for(int i = 0; i < z.length; i++) {
     z[i] = x[i] * y[i];
}


问:
How does the Unit of Work pattern accommodate references to new aggregates?
Background

As I understand it, the Unit of Work (UoW) pattern essentially provides transaction semantics. In other words, given a domain of aggregates persisted by repositories, a UoW class allows consumers of the domain to register invocations of repository methods into an atomic operation. Say we have:

```<code>interface IAggregate<TKey> {
    TKey Id { get; }
}

interface IRepository<TEntity, in TKey> where TEntity : IAggregate<TKey> {
    TEntity Get(TKey id);
    void Save(TEntity entity);
    void Remove(TEntity entity);
}

interface IUnitOfWork {
    void RegisterSave<TEntity>(TEntity entity);
    void RegisterRemove<TEntity>(TEntity entity);
    void RegisterUnitOfWork(IUnitOfWork uow);
    void Commit();
    void Rollback();
}
</code>```

Assume the implementations of IRepository use a relational database, and the implementation of IUnitOfWork.Commit merely sets up a transaction with the database and proceeds to invoke Save or Remove on the appropriate IRepository instances for all the operations that had been registered.  I'd say what I outlined above is a standard, direct interpretation of the Aggregate Root, Repository, and UoW patterns (NHibernate/EF and all their bloated glory notwithstanding).

In the past, I have interpreted the concept of aggregate root boundaries as meaning that references from one aggregate to another should be objectified by an Id property of the target aggregate on the source aggregate. For example:

```<code>class User : IAggregate<int> {
  int Id { get; private set; }
}

class Blog : IAggregate<int> {
  int Id { get; private set; }
  int AuthorUserId { get; set; }
}
</code>```

Question

Given the above separation of concerns and interpretation of aggregate boundaries, how would one provide transactional support to consumers who transactionally need to create an aggregate and save its repository-generated Id in another aggregate? E.g. how can I create a User and a Blog transactionally with Blog.UserId set to User.Id?

I have come up with some answers (marked community wiki), but am posting my question here anyway to solicit feedback and more answers.

答:
Given the above separation of concerns and interpretation of aggregate boundaries, how would one provide transactional support to consumers who transactionally need to create an aggregate and save its repository-generated Id in another aggregate? E.g. how can I create a User and a Blog transactionally with Blog.UserId set to User.Id?

Thing is - aggregate is responsible to draw transactional boundaries too. That means - there should be no need to simultaneously create User with Blog and rollback User creation if Blog creation somehow fails.

If there is such a need - You are modeling aggregates wrong.

Just posting some quick comments that might be useful...

```<code>interface IAggregate<TKey> {
    TKey Id { get; }
}
</code>```

Interfaces should be used to define behavior (roles) and not what implementing class will hold (knowledge about key type in this case).

Can't google quickly enough to find proper explanation why exactly it's so though...
Will try later.

```<code>interface IRepository<TEntity, in TKey> where TEntity : IAggregate<TKey> {
  TEntity Get(TKey id);
  void Save(TEntity entity);
  void Remove(TEntity entity);
}
</code>```

Avoid usage of generic repositories.

```<code>interface IUnitOfWork {
  void RegisterSave<TEntity>(TEntity entity);
  void RegisterRemove<TEntity>(TEntity entity);
  void RegisterUnitOfWork(IUnitOfWork uow);
  void Commit();
  void Rollback();
}
</code>```

Avoid usage of unit of work (this one solves Your problem).

```<code>interface IAggregate<TSelf> where TSelf : IAggregate<TSelf>
{
    IKey<TSelf> Id { get; }
}
</code>```

Keep learning. Soon enough You will stop abusing interfaces & generics. :)

Body:
Background

As I understand it, the Unit of Work (UoW) pattern essentially provides transaction semantics. In other words, given a domain of aggregates persisted by repositories, a UoW class allows consumers of the domain to register invocations of repository methods into an atomic operation. Say we have:

interface IAggregate<TKey> {
    TKey Id { get; }
}

interface IRepository<TEntity, in TKey> where TEntity : IAggregate<TKey> {
    TEntity Get(TKey id);
    void Save(TEntity entity);
    void Remove(TEntity entity);
}

interface IUnitOfWork {
    void RegisterSave<TEntity>(TEntity entity);
    void RegisterRemove<TEntity>(TEntity entity);
    void RegisterUnitOfWork(IUnitOfWork uow);
    void Commit();
    void Rollback();
}

Assume the implementations of IRepository use a relational database, and the implementation of IUnitOfWork.Commit merely sets up a transaction with the database and proceeds to invoke Save or Remove on the appropriate IRepository instances for all the operations that had been registered.  I'd say what I outlined above is a standard, direct interpretation of the Aggregate Root, Repository, and UoW patterns (NHibernate/EF and all their bloated glory notwithstanding).

In the past, I have interpreted the concept of aggregate root boundaries as meaning that references from one aggregate to another should be objectified by an Id property of the target aggregate on the source aggregate. For example:

class User : IAggregate<int> {
  int Id { get; private set; }
}

class Blog : IAggregate<int> {
  int Id { get; private set; }
  int AuthorUserId { get; set; }
}

Question

Given the above separation of concerns and interpretation of aggregate boundaries, how would one provide transactional support to consumers who transactionally need to create an aggregate and save its repository-generated Id in another aggregate? E.g. how can I create a User and a Blog transactionally with Blog.UserId set to User.Id?

I have come up with some answers (marked community wiki), but am posting my question here anyway to solicit feedback and more answers.

Body:
Given the above separation of concerns and interpretation of aggregate boundaries, how would one provide transactional support to consumers who transactionally need to create an aggregate and save its repository-generated Id in another aggregate? E.g. how can I create a User and a Blog transactionally with Blog.UserId set to User.Id?

Thing is - aggregate is responsible to draw transactional boundaries too. That means - there should be no need to simultaneously create User with Blog and rollback User creation if Blog creation somehow fails.

If there is such a need - You are modeling aggregates wrong.

Just posting some quick comments that might be useful...

interface IAggregate<TKey> {
    TKey Id { get; }
}

Interfaces should be used to define behavior (roles) and not what implementing class will hold (knowledge about key type in this case).

Can't google quickly enough to find proper explanation why exactly it's so though...
Will try later.

interface IRepository<TEntity, in TKey> where TEntity : IAggregate<TKey> {
  TEntity Get(TKey id);
  void Save(TEntity entity);
  void Remove(TEntity entity);
}

Avoid usage of generic repositories.

interface IUnitOfWork {
  void RegisterSave<TEntity>(TEntity entity);
  void RegisterRemove<TEntity>(TEntity entity);
  void RegisterUnitOfWork(IUnitOfWork uow);
  void Commit();
  void Rollback();
}

Avoid usage of unit of work (this one solves Your problem).

interface IAggregate<TSelf> where TSelf : IAggregate<TSelf>
{
    IKey<TSelf> Id { get; }
}

Keep learning. Soon enough You will stop abusing interfaces & generics. :)


问:
Raw HTML vs. DOM scraping in python using mechanize and beautiful soup
I am attempting to write a program that, as an example, will scrape the top price off of this web page:

http://www.kayak.com/#/flights/JFK-PAR/2012-06-01/2012-07-01/1adults

First, I am easily able to retrieve the HTML by doing the following:

```<code>from urllib import urlopen
from BeautifulSoup import BeautifulSoup
import mechanize

webpage = 'http://www.kayak.com/#/flights/JFK-PAR/2012-06-01/2012-07-01/1adults'
br = mechanize.Browser()
data = br.open(webpage).get_data()

soup = BeautifulSoup(data)
print soup
</code>```

However, the raw HTML does not contain the price. The browser does...it's thing (clarification here might help me also)...and retrieves the price from elsewhere while it constructs the DOM tree.

I was led to believe that mechanize would act just like my browser and return the DOM tree, which I am also led to believe is what I see when I look at, for example, Chrome's Developer Tools view of the page (if I'm incorrect about this, how do I go about getting whatever that price information is stored in?) Is there something that I need to tell mechanize to do in order to see the DOM tree?

Once I can get the DOM tree into python, everything else I need to do should be a snap. Thanks!

答:
Answering my own question because in the years since asking this I have learned a lot. Today I would use Selenium Webdriver to do this job. Selenium is exactly the tool I was looking for back in 2012 for this type of web scraping project.

https://www.seleniumhq.org/download/

http://chromedriver.chromium.org/

Body:
I am attempting to write a program that, as an example, will scrape the top price off of this web page:

http://www.kayak.com/#/flights/JFK-PAR/2012-06-01/2012-07-01/1adults

First, I am easily able to retrieve the HTML by doing the following:

from urllib import urlopen
from BeautifulSoup import BeautifulSoup
import mechanize

webpage = 'http://www.kayak.com/#/flights/JFK-PAR/2012-06-01/2012-07-01/1adults'
br = mechanize.Browser()
data = br.open(webpage).get_data()

soup = BeautifulSoup(data)
print soup

However, the raw HTML does not contain the price. The browser does...it's thing (clarification here might help me also)...and retrieves the price from elsewhere while it constructs the DOM tree.

I was led to believe that mechanize would act just like my browser and return the DOM tree, which I am also led to believe is what I see when I look at, for example, Chrome's Developer Tools view of the page (if I'm incorrect about this, how do I go about getting whatever that price information is stored in?) Is there something that I need to tell mechanize to do in order to see the DOM tree?

Once I can get the DOM tree into python, everything else I need to do should be a snap. Thanks!


答:
When you want to print an array you need to enumerate each element of the array.

If you pass it to a function that expects a string like your Console.WriteLine then it calls the ToString method on that array.

But the array class doesn't implement the ToString method and calls the base class object.ToString() method. That final method just prints the name of the class

Instead you could use string.Join that enumerates the array and join the results in a string:

```<code>Console.WriteLine("{0} {1} {2}", d.one, d.two,
     "{" + string.Join(",", d.three) + "}");
</code>```

Title: set array to property of a structure

Body:
I'm using C#. Trying to do a structure with array property. It is my code:

namespace ConsoleApplication3

{
    struct Dummy
    {
        public bool one;
        public string two;
        public int[] three;

        public Dummy(bool o, string t, int[] th)
        {
            one = o; two=t; three=th;
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
           int[] K = {5,2};
           Dummy d = new Dummy(true, "mnm", K);
            Console.WriteLine("{0} {1} {2}", d.one, d.two, d.three);

            Console.Write("Press any key to continue . . . ");
            Console.ReadKey(true);
        }
    }
}

However d.three is System.Int32[] but not {5, 2}. How can I fix it?

Body:
When you want to print an array you need to enumerate each element of the array.

If you pass it to a function that expects a string like your Console.WriteLine then it calls the ToString method on that array.

But the array class doesn't implement the ToString method and calls the base class object.ToString() method. That final method just prints the name of the class

Instead you could use string.Join that enumerates the array and join the results in a string:

Console.WriteLine("{0} {1} {2}", d.one, d.two,
     "{" + string.Join(",", d.three) + "}");


问:
F#: How to Generate XML using a complex XSD
I am trying to use F# to generate XML, based on this complex XSD Schema (
http://www.nfe.fazenda.gov.br/portal/exibirArquivo.aspx?conteudo=BALgvpK9Jvo= )

but I am getting compiler error:

FS0503    A member or object constructor 'Dest' taking 0 arguments is not
  accessible from this code location. All accessible versions of method
  'Dest' take 1 arguments.

I think I gave all correct arguments:

```<code>module xsd1

open FSharp.Data
open System.Xml.Linq

type nfe = XmlProvider<Schema="nfe_v4.00.xsd", ResolutionFolder="c:/temp/nfe">

let GenerateNFe () =
    let ide = Unchecked.defaultof<nfe.Ide>
    let emit = Unchecked.defaultof<nfe.Emit>
    let mydest = nfe.Dest(cnpj=None,
                          cpf=(Some "12345678901"),
                          idEstrangeiro=None,
                          xNome=(Some "TONY"),
                          enderDest=None,
                          indleDest="",
                          ie=None,
                          isuf=None,
                          im=None,
                          email=(Some "tonyvca@oldmail.com")
                         )

    let i = nfe.InfNFe(
                       versao="4.00",
                       id="NFe123 F#",
                       ide=ide,
                       emit=emit,
                       avulsa=None,
                       dest=(Some mydest),
                       retirada=None,
                       entrega=None,
                       autXmLs=Unchecked.defaultof<nfe.AutXml[]>,
                       dets=Unchecked.defaultof<nfe.Det[]>,
                       total=Unchecked.defaultof<nfe.Total>,
                       transp=Unchecked.defaultof<nfe.Transp>,
                       cobr=None,
                       pag=Unchecked.defaultof<nfe.Pag>,
                       infAdic=None,
                       exporta=None,
                       compra=None,
                       cana=None
                      )
    i
</code>```

How can I fill the dest "property" ?

I also can not change it

```<code>let ChangeDest (n: nfe) =
    let novodest = nfe.Dest(cnpj=None,
                            cpf=Some "9999999999",
                            idEstrangeiro=None,
                            xNome=Some "NEW TONY",
                            enderDest=None,
                            indleDest=None,
                            ie=None,
                            isuf=None,
                            im=None,
                            email=Some "tonyvca@freemail.com"
                            )
    let newdocument = { n with InfNFe.dest = novodest }
    newdocument
</code>```

To make easier, I attached a sample Project with the XSD and the F# code

https://drive.google.com/open?id=1IbMpmOKfh4B-gKj4CCXTuDXlQxyUN1Wr

This does not work:

```<code>let mydest = new nfe.Dest(cnpj=None, cpf=(Some "11111111111"), idEstrangeiro=None, xNome=(Some "TONY"), enderDest=None, indleDest="indledest", ie=None, isuf=None, im=None, email=(Some "tonyvca@hotmail.com") )
</code>```

But this works:

```<code>let mydest = new nfe.Dest(None, (Some "11111111111"), None, (Some "TONY"), None, "indledest", ie=None, isuf=None, im=None, email=(Some "tonyvca@hotmail.com") )
</code>```

If I remove named parameters, up to the indleDest part, it Works, can you give a look and help me how to make it work will all named parameters written?

答:
I found the problem:
Due to a font problem and lack of autocompletion for parameter names, I was typing indleDest (INDLEDEST) but the correct was indIeDest (INDIEDEST), now it compiles fine! :D

```<code>let mydest = nfe.Dest(cnpj=None,
                      cpf=(Some "81679580515"),
                      idEstrangeiro=None,
                      xNome=(Some "TONY"),
                      enderDest=None,
                      indIeDest="",
                      ie=None,
                      isuf=None,
                      im=None,
                      email=(Some "tonyvca@hotmail.com")
                     )
</code>```

Body:
I am trying to use F# to generate XML, based on this complex XSD Schema (
http://www.nfe.fazenda.gov.br/portal/exibirArquivo.aspx?conteudo=BALgvpK9Jvo= )

but I am getting compiler error:

FS0503    A member or object constructor 'Dest' taking 0 arguments is not
  accessible from this code location. All accessible versions of method
  'Dest' take 1 arguments.

I think I gave all correct arguments:

module xsd1

open FSharp.Data
open System.Xml.Linq

type nfe = XmlProvider<Schema="nfe_v4.00.xsd", ResolutionFolder="c:/temp/nfe">

let GenerateNFe () =
    let ide = Unchecked.defaultof<nfe.Ide>
    let emit = Unchecked.defaultof<nfe.Emit>
    let mydest = nfe.Dest(cnpj=None,
                          cpf=(Some "12345678901"),
                          idEstrangeiro=None,
                          xNome=(Some "TONY"),
                          enderDest=None,
                          indleDest="",
                          ie=None,
                          isuf=None,
                          im=None,
                          email=(Some "tonyvca@oldmail.com")
                         )

    let i = nfe.InfNFe(
                       versao="4.00",
                       id="NFe123 F#",
                       ide=ide,
                       emit=emit,
                       avulsa=None,
                       dest=(Some mydest),
                       retirada=None,
                       entrega=None,
                       autXmLs=Unchecked.defaultof<nfe.AutXml[]>,
                       dets=Unchecked.defaultof<nfe.Det[]>,
                       total=Unchecked.defaultof<nfe.Total>,
                       transp=Unchecked.defaultof<nfe.Transp>,
                       cobr=None,
                       pag=Unchecked.defaultof<nfe.Pag>,
                       infAdic=None,
                       exporta=None,
                       compra=None,
                       cana=None
                      )
    i

How can I fill the dest "property" ?

I also can not change it

let ChangeDest (n: nfe) =
    let novodest = nfe.Dest(cnpj=None,
                            cpf=Some "9999999999",
                            idEstrangeiro=None,
                            xNome=Some "NEW TONY",
                            enderDest=None,
                            indleDest=None,
                            ie=None,
                            isuf=None,
                            im=None,
                            email=Some "tonyvca@freemail.com"
                            )
    let newdocument = { n with InfNFe.dest = novodest }
    newdocument

To make easier, I attached a sample Project with the XSD and the F# code

https://drive.google.com/open?id=1IbMpmOKfh4B-gKj4CCXTuDXlQxyUN1Wr

This does not work:

let mydest = new nfe.Dest(cnpj=None, cpf=(Some "11111111111"), idEstrangeiro=None, xNome=(Some "TONY"), enderDest=None, indleDest="indledest", ie=None, isuf=None, im=None, email=(Some "tonyvca@hotmail.com") )

But this works:

let mydest = new nfe.Dest(None, (Some "11111111111"), None, (Some "TONY"), None, "indledest", ie=None, isuf=None, im=None, email=(Some "tonyvca@hotmail.com") )

If I remove named parameters, up to the indleDest part, it Works, can you give a look and help me how to make it work will all named parameters written?

Body:
I found the problem:
Due to a font problem and lack of autocompletion for parameter names, I was typing indleDest (INDLEDEST) but the correct was indIeDest (INDIEDEST), now it compiles fine! :D

let mydest = nfe.Dest(cnpj=None,
                      cpf=(Some "81679580515"),
                      idEstrangeiro=None,
                      xNome=(Some "TONY"),
                      enderDest=None,
                      indIeDest="",
                      ie=None,
                      isuf=None,
                      im=None,
                      email=(Some "tonyvca@hotmail.com")
                     )


问:
Scala fold on Option return type
I am very new to Scala and i would like to return a Some[String] or a None after doing some loging but it seems the types returned are not consistent for the fold to work.

```<code>(Option[String]).fold{
            logger.info("Message append failed")
            None
          }{stuff=>
            logger.info("Message appended")
            Some(stuff)
          }
</code>```

The returned compiler error is the following Expression of type Some[String] does not conform to expected type None.type

答:
it's instructive to look at the definition of fold:

```<code>def fold[B](ifEmpty: => B)(f: A => B): B
</code>```

so, when you call

```<code>Option("hi").fold(None)(x => Some(x))
</code>```

the inferred type B is Option[Nothing] because there's no way for the compiler to know what kind of None you meant.  in this case, you can help the compiler out by using Option.empty and specifying a type:

```<code>Option("hi").fold(Option.empty[String])(x => Some(x))
</code>```

Title: Scala fold on Option return type

Body:
I am very new to Scala and i would like to return a Some[String] or a None after doing some loging but it seems the types returned are not consistent for the fold to work.

(Option[String]).fold{
            logger.info("Message append failed")
            None
          }{stuff=>
            logger.info("Message appended")
            Some(stuff)
          }

The returned compiler error is the following Expression of type Some[String] does not conform to expected type None.type

Body:
it's instructive to look at the definition of fold:

def fold[B](ifEmpty: => B)(f: A => B): B

so, when you call

Option("hi").fold(None)(x => Some(x))

the inferred type B is Option[Nothing] because there's no way for the compiler to know what kind of None you meant.  in this case, you can help the compiler out by using Option.empty and specifying a type:

Option("hi").fold(Option.empty[String])(x => Some(x))


问:
Is there a way in HTML (or ColdFusion) to have a radio button trigger a hyperlink without having to submit a form?
I want to have a pair of radio buttons sitting over an HTML table so that whenever the rb is clicked it will cause the table to rebuild (rebuild the page) by submitting a different URL variable. Is there a way to do this without having to build a form and click a submit button? I'm pretty new to this stuff so please keep any answers basic and/or show samples of code. Thanks!</p>

答:
Html is a Markup Language it will not do the logic for you. that way javascript is there . </p>

```<code><input id="gotogoogle" type="radio" name="name" value="google" checked>
<script>
    var radiob = document.getElementById("gotogoogle");

    radiob.addEventListener("change", function() {
        if(radiob.value == "google")
        {
            document.location = "http:\\www.gooogle.com"
        }
    });
</script>
</code>```

Body:
Html is a Markup Language it will not do the logic for you. that way javascript is there .

<input id="gotogoogle" type="radio" name="name" value="google" checked>
<script>
    var radiob = document.getElementById("gotogoogle");

    radiob.addEventListener("change", function() {
        if(radiob.value == "google")
        {
            document.location = "http:\\www.gooogle.com"
        }
    });
</script>


问:
How do you determine how far to normalize a database?
When creating a database structure, what are good guidelines to follow or good ways to determine how far a database should be normalized? Should you create an un-normalized database and split it apart as the project progresses? Should you create it fully normalized and combine tables as needed for performance?</p>

答: Jeff has a pretty good overview of his philosophy on his blog:  Maybe normalization isn't normal.  The main thing is: don't overdo normalization.  But I think an even bigger point to take away is that it probably doesn't matter too much.  Unless you're running the next Google, you probably won't notice much of a difference until your application grows.</p>

OwnerDisplayName: Jason Baker


问:
How to make lseek64 _actually_ return 64-bit offset?
```<code>#define _FILE_OFFSET_BITS 64
#define _LARGEFILE64_SOURCE

...

off64_t st_size;

...

st_size = (off64_t)lseek64(fd, (off64_t)0, SEEK_END);
fprintf(stderr, "QQQ st_size=%llx %lld\n", st_size, st_size);
</code>```

Then strace:

```<code>$ strace -e _llseek ./the_program
_llseek(3, 0, [20974464000], SEEK_END)  = 0
QQQ st_size=ffffffffe22cec00 -500372480
</code>```

20974464000 == 0x4E22CEC00 - good

-500372480 == 0xffffffffe22cec00 - bad

It change to (off64_t)lseek64(fd, 0, SEEK_END); it calls _llseek incorrectly:

```<code>_llseek(3, 8589934592, [8589934592], SEEK_SET) = 0
st_size=0 0
</code>```

What more should I do to ensure it gets the size correctly, without chopping off major dword?

答: Ensure you're defining _FILE_OFFSET_BITS and _LARGEFILE64_SOURCE before including sys/types.h and unistd.h. Preferably, in you compiler's command line.

Body:
#define _FILE_OFFSET_BITS 64
#define _LARGEFILE64_SOURCE

...

off64_t st_size;

...

st_size = (off64_t)lseek64(fd, (off64_t)0, SEEK_END);
fprintf(stderr, "QQQ st_size=%llx %lld\n", st_size, st_size);

Then strace:

$ strace -e _llseek ./the_program
_llseek(3, 0, [20974464000], SEEK_END)  = 0
QQQ st_size=ffffffffe22cec00 -500372480

20974464000 == 0x4E22CEC00 - good

-500372480 == 0xffffffffe22cec00 - bad

It change to (off64_t)lseek64(fd, 0, SEEK_END); it calls _llseek incorrectly:

_llseek(3, 8589934592, [8589934592], SEEK_SET) = 0
st_size=0 0

What more should I do to ensure it gets the size correctly, without chopping off major dword?


问:
How do I use LINQ to group & project objects, based on a member dictionary key?
I have a List<Predictions> that I would like to project onto a List<List<PredictionObj>>. These two classes are defined as follows:

```<code>public Predictions
{
    public Dictionary<string, double> PredictedMetrics { get; private set; }
    public DateTime PredictionTimeStamp { get; set; }
    public Predictions()
    {
        PredictedMetrics = new Dictionary<string, double>();
    }
}

public class PredictionObj
{
    public string PredictedMetricName { get; set; }
    public double PredictedMetricValue { get; set; }
    public DateTime PredictionTimeStamp { get; set; }
}
</code>```

For context, each Predictions object in the List<Predictions> list contains a collection (PredictedMetrics) of predicted values for a set of metrics, which were made at PredictionTimeStamp. I'd like to separate each of those metrics into their own list, such that there will be one list (List<PredictionObj>) for every unique PredictedMetrics key in the list. (PredictedMetricName will map to the dictionary's key, PredictedMetricValue will map to the dictionary's value). I'd like to store all of these lists in one List<List<PredictionObj>> list.

Is there a way to accomplish this using LINQ extension methods?

You can copy/paste the source below into LINQPad as an example. I'm looking for LINQ that will accomplish what GenerateSeperateMetricLists is doing:

```<code>void Main()
{
    DateTime currTime = DateTime.UtcNow;
    List<Predictions> records = new List<Predictions>();
    Predictions record1 = new Predictions();
    record1.PredictedMetrics.Add("metric1", 2.2d);
    record1.PredictedMetrics.Add("metric2", 0.2d);
    record1.PredictionTimeStamp = currTime;
    records.Add(record1);
    Predictions record2 = new Predictions();
    record2.PredictedMetrics.Add("metric1", 1.2d);
    record2.PredictedMetrics.Add("metric2", 0.1d);
    record2.PredictionTimeStamp = currTime.AddMinutes(1);
    records.Add(record2);
    Predictions record3 = new Predictions();
    record3.PredictedMetrics.Add("metric1", 3.2d);
    record3.PredictedMetrics.Add("metric2", 0.3d);
    record3.PredictionTimeStamp = currTime.AddMinutes(2);
    records.Add(record3);
    Predictions record4 = new Predictions();
    record4.PredictedMetrics.Add("metric1", 4.2d);
    record4.PredictedMetrics.Add("metric2", 0.4d);
    record4.PredictionTimeStamp = currTime.AddMinutes(3);
    records.Add(record4);

    //What's the LINQ that could replace this method?
    GenerateSeperateMetricLists(records).Dump();
}

private static List<List<PredictionObj>> GenerateSeperateMetricLists(List<Predictions> predictionRecords)
{
    var predictionMetricLists = new List<List<PredictionObj>>();
    foreach (Predictions forecastRecord in predictionRecords)
    {
        foreach (KeyValuePair<string, double> prediction in forecastRecord.PredictedMetrics)
        {
            PredictionObj predictionMetric = new PredictionObj
            {
                PredictedMetricName = prediction.Key,
                PredictedMetricValue = prediction.Value,
                PredictionTimeStamp = forecastRecord.PredictionTimeStamp
            };
            var metricList = predictionMetricLists.Where(x => x.First().PredictedMetricName == prediction.Key);
            if (metricList.Count() == 0)
            {
                predictionMetricLists.Add(new List<PredictionObj> {predictionMetric});
            }
            else
            {
                metricList.First().Add(predictionMetric);
            }
        }
    }
    return predictionMetricLists;
}

private class Predictions
{
    public Dictionary<string, double> PredictedMetrics  { get; private set; }
    public DateTime PredictionTimeStamp  { get; set; }
    public Predictions()
    {
        PredictedMetrics = new Dictionary<string, double>();
    }
}

private class PredictionObj
{
    public string PredictedMetricName  { get; set; }
    public double PredictedMetricValue  { get; set; }
    public DateTime PredictionTimeStamp  { get; set; }
}
</code>```

答:
You just need to take each Prediction and project it into a List<PredictionObj> and then convert those into a List<Prediction>:

```<code>var ans = records.SelectMany(p => p.PredictedMetrics.Select(pm => new PredictionObj { PredictedMetricName = pm.Key, PredictedMetricValue = pm.Value, PredictionTimeStamp = p.PredictionTimeStamp }))
                 .GroupBy(p => p.PredictedMetricName)
                 .Select(g => g.ToList())
                 .ToList();
</code>```

Updated for change in OP.

Body:
I have a List<Predictions> that I would like to project onto a List<List<PredictionObj>>. These two classes are defined as follows:

public Predictions
{
    public Dictionary<string, double> PredictedMetrics { get; private set; }
    public DateTime PredictionTimeStamp { get; set; }
    public Predictions()
    {
        PredictedMetrics = new Dictionary<string, double>();
    }
}

public class PredictionObj
{
    public string PredictedMetricName { get; set; }
    public double PredictedMetricValue { get; set; }
    public DateTime PredictionTimeStamp { get; set; }
}

For context, each Predictions object in the List<Predictions> list contains a collection (PredictedMetrics) of predicted values for a set of metrics, which were made at PredictionTimeStamp. I'd like to separate each of those metrics into their own list, such that there will be one list (List<PredictionObj>) for every unique PredictedMetrics key in the list. (PredictedMetricName will map to the dictionary's key, PredictedMetricValue will map to the dictionary's value). I'd like to store all of these lists in one List<List<PredictionObj>> list.

Is there a way to accomplish this using LINQ extension methods?

You can copy/paste the source below into LINQPad as an example. I'm looking for LINQ that will accomplish what GenerateSeperateMetricLists is doing:

void Main()
{
    DateTime currTime = DateTime.UtcNow;
    List<Predictions> records = new List<Predictions>();
    Predictions record1 = new Predictions();
    record1.PredictedMetrics.Add("metric1", 2.2d);
    record1.PredictedMetrics.Add("metric2", 0.2d);
    record1.PredictionTimeStamp = currTime;
    records.Add(record1);
    Predictions record2 = new Predictions();
    record2.PredictedMetrics.Add("metric1", 1.2d);
    record2.PredictedMetrics.Add("metric2", 0.1d);
    record2.PredictionTimeStamp = currTime.AddMinutes(1);
    records.Add(record2);
    Predictions record3 = new Predictions();
    record3.PredictedMetrics.Add("metric1", 3.2d);
    record3.PredictedMetrics.Add("metric2", 0.3d);
    record3.PredictionTimeStamp = currTime.AddMinutes(2);
    records.Add(record3);
    Predictions record4 = new Predictions();
    record4.PredictedMetrics.Add("metric1", 4.2d);
    record4.PredictedMetrics.Add("metric2", 0.4d);
    record4.PredictionTimeStamp = currTime.AddMinutes(3);
    records.Add(record4);

    //What's the LINQ that could replace this method?
    GenerateSeperateMetricLists(records).Dump();
}

private static List<List<PredictionObj>> GenerateSeperateMetricLists(List<Predictions> predictionRecords)
{
    var predictionMetricLists = new List<List<PredictionObj>>();
    foreach (Predictions forecastRecord in predictionRecords)
    {
        foreach (KeyValuePair<string, double> prediction in forecastRecord.PredictedMetrics)
        {
            PredictionObj predictionMetric = new PredictionObj
            {
                PredictedMetricName = prediction.Key,
                PredictedMetricValue = prediction.Value,
                PredictionTimeStamp = forecastRecord.PredictionTimeStamp
            };
            var metricList = predictionMetricLists.Where(x => x.First().PredictedMetricName == prediction.Key);
            if (metricList.Count() == 0)
            {
                predictionMetricLists.Add(new List<PredictionObj> {predictionMetric});
            }
            else
            {
                metricList.First().Add(predictionMetric);
            }
        }
    }
    return predictionMetricLists;
}

private class Predictions
{
    public Dictionary<string, double> PredictedMetrics  { get; private set; }
    public DateTime PredictionTimeStamp  { get; set; }
    public Predictions()
    {
        PredictedMetrics = new Dictionary<string, double>();
    }
}

private class PredictionObj
{
    public string PredictedMetricName  { get; set; }
    public double PredictedMetricValue  { get; set; }
    public DateTime PredictionTimeStamp  { get; set; }
}

Body:
You just need to take each Prediction and project it into a List<PredictionObj> and then convert those into a List<Prediction>:

var ans = records.SelectMany(p => p.PredictedMetrics.Select(pm => new PredictionObj { PredictedMetricName = pm.Key, PredictedMetricValue = pm.Value, PredictionTimeStamp = p.PredictionTimeStamp }))
                 .GroupBy(p => p.PredictedMetricName)
                 .Select(g => g.ToList())
                 .ToList();

Updated for change in OP.


问:
Create an Excel Macro to filter sheets with a certain title to a new workbook

I have an Excel Workbook containing ~50 different sheets. These sheets are organized into raw data and organized data summaries.

The data summaries are sheets that I'm trying to upload to an Access database, and these sheets all include the string "Summary" or "Sum" as part of their name. I'm new to VBA and I'm wondering if there is a way I can set up a script to filter out the sheets so that I am left with just the summary sheets and not the raw data sheets as part of my workbook.

Ideally I would copy the summary sheets over to a new Excel workbook since I don't want to lose my raw data. Any help? Or is this not even possible?

答:
Using the InStr() function works great for this! Bonus here is the sheets will be hidden and not deleted.

Since "Summary" contains the string "Sum" already, I didn't bother putting the logic in for that.

Macro to Hide Sheets containing "Sum"

```<code>Sub HideSheets()

   Dim sht As Worksheet

   For Each sht In Worksheets
      If (InStr(sht.Name, "Sum")) Then
         sht.Visible = xlSheetHidden
      End If
   Next

End Sub
</code>```

Macro to Show ALL Sheets

```<code>Sub ShowSheets()

   Dim sht As Worksheet

   For Each sht In Worksheets
      sht.Visible = xlSheetVisible
   Next

End Sub
</code>```

Body:
Using the InStr() function works great for this! Bonus here is the sheets will be hidden and not deleted.

Since "Summary" contains the string "Sum" already, I didn't bother putting the logic in for that.

Macro to Hide Sheets containing "Sum"

Sub HideSheets()

   Dim sht As Worksheet

   For Each sht In Worksheets
      If (InStr(sht.Name, "Sum")) Then
         sht.Visible = xlSheetHidden
      End If
   Next

End Sub

Macro to Show ALL Sheets

Sub ShowSheets()

   Dim sht As Worksheet

   For Each sht In Worksheets
      sht.Visible = xlSheetVisible
   Next

End Sub