Listview not displaying below RelativeLayout

Question: ListView is not showing, any assistance is greatly appreciated! I am able to display products with ListView alone but I cannot figure out how to display it below my Relative Layout.
Cart.java:
 public class Cart extends AppCompatActivity {

    private String user;
    static CartChangeListener cartChangeListener;
    ProductsAdapter adaptCart;
    ArrayList<Product> cartItems = new ArrayList<>();
    Menu menu;
    float total = (float)0.00;
    float shipCost = 15;
    float tax = (float)0.07;
    String URI;
    TextView subTotal;
    TextView shipping;
    TextView taxes;
    TextView totals;

    @Override
    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_cart);
        View header = getLayoutInflater().inflate(R.layout.activity_cart, null);
        //ListView.addHeaderView(headerView);
        user = MainActivity.currentAccount.getUsername();
        if(user == null || user.equals("Guest")) {
            shipCost = (float)0.00;
            tax = (float)0.00;
        }
        if(user != null && !(user.equals("Guest"))) {
            new getCartIcon().execute();
            //View header = getLayoutInflater().inflate(R.layout.activity_cart, null);
            //View footer = getLayoutInflater().inflate(R.layout.activity_search, null);
            ListView listView = (ListView) findViewById(R.id.list_cart_view);
            new returnCartItems().execute();
            //if (!(cartItems.isEmpty())) {
                adaptCart = new ProductsAdapter(Cart.this, 0, cartItems);
                listView.setOnItemClickListener(new ListView.OnItemClickListener() {
                    @Override
                    public void onItemClick(AdapterView<?> parent, View v, int position, long id) {

                        try {
                            ProductsAdapter.ViewHolder holder = new ProductsAdapter.ViewHolder();
                            holder.product_name = (TextView) v.findViewById(R.id.product_name);
                            holder.product_dept = (TextView) v.findViewById(R.id.product_dept);
                            holder.product_desc = (TextView) v.findViewById(R.id.product_desc);
                            holder.product_price = (TextView) v.findViewById(R.id.product_price);
                            holder.product_qty = (TextView) v.findViewById(R.id.product_qty);
                            holder.product_img = (ImageView) findViewById(R.id.icon);

                            URI = "http://www.michaelscray.com/Softwear/graphics/";
                            String dept = "Dept: ";
                            String money = "$";
                            String qty = "Qty: ";
                            URI += cartItems.get(position).getProduct_img();
                            Uri uris = Uri.parse(URI + cartItems.get(position).getProduct_img());
                            URI uri = java.net.URI.create(URI);
                            holder.product_name.setText(cartItems.get(position).getProduct_name());
                            holder.product_desc.setText(cartItems.get(position).getProduct_desc());
                            holder.product_dept.setText(dept + cartItems.get(position).getProduct_dept());
                            holder.product_price.setText(money + String.valueOf(cartItems.get(position).getPrice()));
                            holder.product_qty.setText(qty + String.valueOf(cartItems.get(position).getProduct_qty()));
                            Picasso.with(getApplicationContext()).load(URI).error(R.mipmap.ic_launcher).into(holder.product_img);

                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                });

                listView.setAdapter(adaptCart);
            //}
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        super.onCreateOptionsMenu(menu);
        getMenuInflater().inflate(R.menu.menu_main, menu);
        this.menu = menu;
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // toggle nav drawer on selecting action bar app icon/title
        return true;
    }

    public class getCartIcon extends AsyncTask<Void, Void, Void> {
        String tempUser = user;
        int cartNum = 0;
        float tempTotal;

        @Override
        protected void onPreExecute() {
            subTotal = (TextView) findViewById(R.id.textView_subTotal);
            shipping = (TextView) findViewById(R.id.textView_shipping);
            totals = (TextView) findViewById(R.id.textView_total);
            taxes = (TextView) findViewById(R.id.textView_taxes);
        }

        @Override
        protected Void doInBackground(Void... arg0) {
            if(tempUser != null) {
                try {
                    Connection conn = ConnectDB.getConnection();
                    String queryString = "SELECT * FROM Orders WHERE `User_Name` = '" + tempUser + "'";

                    PreparedStatement st = conn.prepareStatement(queryString);
                    //st.setString(1, tempUser);

                    final ResultSet result = st.executeQuery(queryString);

                    while (result.next()) {
                        try {
                            tempTotal += result.getFloat("Price");
                            //skus.add(result.getInt("SKU"));
                        } catch(SQLException e) {
                            e.printStackTrace();
                        }
                        cartNum++;
                        //setTotal(result.getFloat(String.valueOf("Price")));
                        }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            return null;
        }

        protected void onPostExecute(Void result) {
            getCartItems(cartNum);
            subTotal.setText(String.valueOf(tempTotal));
            shipping.setText(String.valueOf(shipCost));
            tax = tempTotal * tax;
            taxes.setText(String.valueOf(tax));
            totals.setText(String.valueOf(tempTotal + shipCost + tax));
            //setTotal(tempTotal);
            //super.onPostExecute(result);
        }
    }

    public class returnCartItems extends AsyncTask<Void, Void, Void> {
        String tempUser = user;
        Product product = null;
        List<Integer> skus = new ArrayList<>();
        //String descr = "DETAILS: \n\n";

        @Override
        protected void onPreExecute() {

        }

        @Override
        protected Void doInBackground(Void... arg0) {
            if(tempUser != null) {
                try {
                    Connection conn = ConnectDB.getConnection();
                    String queryString = "SELECT * FROM Orders WHERE `User_Name` = '" + tempUser + "'";

                    PreparedStatement st = conn.prepareStatement(queryString);
                    //st.setString(1, tempUser);

                    final ResultSet result = st.executeQuery(queryString);

                    while (result.next()) {
                        try {
                            skus.add(result.getInt("SKU"));
                        } catch(SQLException e) {
                            e.printStackTrace();
                        }
                    }
                    conn.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }

                try {
                    Connection conn = ConnectDB.getConnection();
                    String queryString = "SELECT * FROM Inventory";

                    PreparedStatement st = conn.prepareStatement(queryString);
                    //st.setString(1, tempUser);

                    final ResultSet result = st.executeQuery(queryString);

                    while (result.next()) {
                        for(int i=0; i < skus.size(); i++) {
                            if(skus.get(i) == result.getInt("SKU")) {
                                product = new Product();
                                product.setProduct_name(result.getString("Name"));
                                product.setProduct_dept(result.getString("Department"));
                                product.setProduct_desc(result.getString("Description"));
                                product.setPrice(result.getFloat("Price"));
                                product.setProduct_qty(result.getInt("Quantity"));
                                product.setProduct_img(result.getString("Image"));
                                cartItems.add(product);
                                /*
                                descr += "Product: " + result.getString("Name") + "\n" +
                                "Department: " + result.getString("Department") + "\n" +
                                "Price: $" + result.getFloat("Price") + "\n\n";
                                */
                            }
                        }
                    }
                    conn.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            return null;
        }

        protected void onPostExecute(Void result) {
            super.onPostExecute(result);
        }
    }

    public void setTotal(float total) {
        this.total += total;
    }

    public float getTotal() {
        return total;
    }

    public void getCartItems(int cart) {

        MenuItem cartMenuItem = (MenuItem) menu.findItem(R.id.action_cart);
        if (cart == 0) {
            cartMenuItem.setIcon(R.drawable.cart0);
        }
        if (cart == 1) {
            cartMenuItem.setIcon(R.drawable.cart1);
        }
        if (cart == 2) {
            cartMenuItem.setIcon(R.drawable.cart2);
        }
        if (cart == 3) {
            cartMenuItem.setIcon(R.drawable.cart3);
        }
        if (cart == 4) {
            cartMenuItem.setIcon(R.drawable.cart4);
        }
        if (cart == 5) {
            cartMenuItem.setIcon(R.drawable.cart5);
        }
        if (cart > 5) {
            cartMenuItem.setIcon(R.drawable.cart5plus);
        }
        if (cart > 10) {
            cartMenuItem.setIcon(R.drawable.cart10plus);
        }
    }
    }

ProductsAdapter.java:
public class ProductsAdapter extends ArrayAdapter<Product> {

    private Activity activity;
    private ArrayList<Product> products;
    private static LayoutInflater inflater = null;
    String money = "$";
    String dept = "Dept: ";
    String qty ="Qty: ";
    static String URI;

    public ProductsAdapter(Activity activity, int textViewResourceId, ArrayList<Product> product) {
        super(activity, textViewResourceId, product);
        try {
            this.activity = activity;
            this.products = product;
            inflater = (LayoutInflater) activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            //imageLoader = new ImageLoader(activity.getApplicationActivity());
        } catch (Exception e) {
            return;
        }
    }

    @Override
    public int getCount() {
        return products.size();
    }

    public Product getItem(Product position) {
        return position;
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    public static class ViewHolder {
        public TextView product_name;
        public TextView product_desc;
        public TextView product_dept;
        public TextView product_price;
        public TextView product_qty;
        public ImageView product_img;
    }

    public View getView(int position, View convertView, ViewGroup parent) {
        View vi = convertView;
        final ViewHolder holder;
        try {
            if(convertView == null) {
                vi = inflater.inflate(R.layout.activity_search, parent, false);
                holder = new ViewHolder();
                holder.product_name = (TextView) vi.findViewById(R.id.product_name);
                holder.product_dept = (TextView) vi.findViewById(R.id.product_dept);
                holder.product_desc = (TextView) vi.findViewById(R.id.product_desc);
                holder.product_price = (TextView) vi.findViewById(R.id.product_price);
                holder.product_qty = (TextView) vi.findViewById(R.id.product_qty);
                holder.product_img = (ImageView) vi.findViewById(R.id.icon);
                vi.setTag(holder);
            }
            else {
                holder = (ViewHolder) vi.getTag();
            }
            URI = "http://www.michaelscray.com/Softwear/graphics/";
            URI += products.get(position).getProduct_img();
            Uri uri = Uri.parse(URI + products.get(position).getProduct_img());
            holder.product_name.setText(products.get(position).getProduct_name());
            holder.product_desc.setText(products.get(position).getProduct_desc());
            holder.product_dept.setText(dept + products.get(position).getProduct_dept());
            holder.product_price.setText(money + String.valueOf(products.get(position).getPrice()));
            holder.product_qty.setText(qty + String.valueOf(products.get(position).getProduct_qty()));
            Picasso.with(getContext()).load(URI).error(R.mipmap.ic_launcher).into(holder.product_img);
        }
        catch(Exception e) {

        }

        return vi;
    }

}

And, activity_cart.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/llSliderCart"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"

    android:orientation="vertical" >

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="50dp"
        android:background="#5e80ab"
        android:orientation="vertical" >

        <TextView
            android:id="@+id/summary"
            android:layout_width="254dp"
            android:layout_height="55dp"
            android:gravity="center"
            android:text="CART SUMMARY"
            android:textColor="#ffffff"
            android:textSize="18sp"
            android:textStyle="bold"
            android:layout_alignParentStart="true"
            android:layout_toStartOf="@+id/checkout_btn" />

        <Button
            android:layout_width="wrap_content"
            android:layout_height="fill_parent"
            android:text="Checkout"
            android:id="@+id/checkout_btn"
            android:background="@drawable/shape"
            android:layout_alignParentBottom="false"
            android:layout_alignParentEnd="false"
            android:layout_alignParentRight="true"
            android:paddingLeft="1dp"
            android:paddingTop="1dp"
            android:paddingRight="1dp"
            android:paddingBottom="1dp"
            android:textStyle="bold"
            android:textColor="#ffffff" />
    </RelativeLayout>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="@dimen/cart_rows"
        android:background="#ffffff"
        android:orientation="horizontal" >

        <TextView
            android:layout_width="120dp"
            android:layout_height="wrap_content"
            android:layout_gravity="center_vertical"
            android:gravity="right"
            android:paddingRight="20dp"
            android:text="Subtotal"
            android:textColor="#a4a4a4"
            android:textSize="@dimen/text_normal" />

        <View
            android:layout_width="1dp"
            android:layout_height="match_parent"
            android:background="@color/vertical_divider_welcome" />

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="center_vertical"
            android:gravity="right"
            android:paddingLeft="20dp"
            android:text="@string/currency"
            android:textColor="#a4a4a4"
            android:textSize="@dimen/text_normal" />

        <TextView
            android:id="@+id/textView_subTotal"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_gravity="center_vertical"
            android:gravity="right"
            android:paddingRight="20dp"
            android:text="0.00"
            android:textColor="#a4a4a4"
            android:textSize="@dimen/text_normal" />
    </LinearLayout>

    <View
        android:layout_width="match_parent"
        android:layout_height="1dp"
        android:background="@color/vertical_divider_welcome" />

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="@dimen/cart_rows"
        android:background="#ffffff"
        android:orientation="horizontal" >

        <TextView
            android:layout_width="120dp"
            android:layout_height="wrap_content"
            android:layout_gravity="center_vertical"
            android:gravity="right"
            android:paddingRight="20dp"
            android:text="Shipping"
            android:textColor="#a4a4a4"
            android:textSize="@dimen/text_normal" />

        <View
            android:layout_width="1dp"
            android:layout_height="match_parent"
            android:background="@color/vertical_divider_welcome" />

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="center_vertical"
            android:gravity="right"
            android:paddingLeft="20dp"
            android:text="@string/currency"
            android:textColor="#a4a4a4"
            android:textSize="@dimen/text_normal" />

        <TextView
            android:id="@+id/textView_shipping"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_gravity="center_vertical"
            android:gravity="right"
            android:paddingRight="20dp"
            android:text="0.00"
            android:textColor="#a4a4a4"
            android:textSize="@dimen/text_normal" />
    </LinearLayout>

    <View
        android:layout_width="match_parent"
        android:layout_height="1dp"
        android:background="@color/vertical_divider_welcome" />

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="@dimen/cart_rows"
        android:background="#ffffff"
        android:orientation="horizontal" >

        <TextView
            android:layout_width="120dp"
            android:layout_height="wrap_content"
            android:layout_gravity="center_vertical"
            android:gravity="right"
            android:paddingRight="20dp"
            android:text="Tax"
            android:textColor="#a4a4a4"
            android:textSize="@dimen/text_normal" />

        <View
            android:layout_width="1dp"
            android:layout_height="match_parent"
            android:background="@color/vertical_divider_welcome" />

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="center_vertical"
            android:gravity="right"
            android:paddingLeft="20dp"
            android:text="@string/currency"
            android:textColor="#a4a4a4"
            android:textSize="@dimen/text_normal" />

        <TextView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_gravity="center_vertical"
            android:gravity="right"
            android:paddingRight="20dp"
            android:text="0"
            android:textColor="#a4a4a4"
            android:textSize="@dimen/text_normal"
            android:id="@+id/textView_taxes" />
    </LinearLayout>

    <View
        android:layout_width="match_parent"
        android:layout_height="1dp"
        android:background="@color/vertical_divider_welcome" />

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="@dimen/cart_rows"
        android:background="#ffffff"
        android:orientation="horizontal" >

        <TextView
            android:layout_width="120dp"
            android:layout_height="wrap_content"
            android:layout_gravity="center_vertical"
            android:gravity="right"
            android:paddingRight="20dp"
            android:text="Total"
            android:textStyle="bold"
            android:textColor="@color/blue"
            android:textSize="@dimen/text_title" />

        <View
            android:layout_width="1dp"
            android:layout_height="match_parent"
            android:background="@color/vertical_divider_welcome" />

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="center_vertical"
            android:gravity="right"
            android:paddingLeft="20dp"
            android:text="@string/currency"
            android:textStyle="bold"
            android:textColor="@color/blue"
            android:textSize="@dimen/text_title" />

        <TextView
            android:id="@+id/textView_total"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_gravity="center_vertical"
            android:gravity="right"
            android:textStyle="bold"
            android:paddingRight="20dp"
            android:text="0.00"
            android:textColor="@color/blue"
            android:textSize="@dimen/text_title" />
    </LinearLayout>

    <View
        android:layout_width="match_parent"
        android:layout_height="1dp"
        android:background="@color/vertical_divider_welcome" />

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

        <TextView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="Cart contents:"
            android:id="@+id/contents"
            android:background="@color/vertical_divider_welcome"
            android:textStyle="bold|italic"
            android:layout_alignParentEnd="false"
            android:layout_alignParentStart="false" />

    </RelativeLayout>

    <ListView
        android:layout_width="wrap_content"
        android:layout_height="0dp"
        android:layout_weight="1"
        android:orientation="vertical"
        android:id="@+id/list_cart_view">
    </ListView>

</LinearLayout>

Thanks again!
Answer: While your RelativeLayout(the one just before the ListView) have match_parent as height, it will take the remaining space of the window... so there is no place for your ListView to be shown.
Comment: I have changed the height to the respective RelativeLayout to wrap_content and it is still not showing anything with the ListView. Thank your for your comment!
Comment: The **sum** of your layout childrens height is greater than the screen height, this is why your list still not shown.
Answer: Try this..
Give id to the above Relative layout and use the same below.
<ListView
        android:layout_width="wrap_content"
        android:layout_height="0dp"
        android:layout_weight="1"
        android:orientation="vertical"
        android:layout_below="@id/"
        android:id="@+id/list_cart_view">
    </ListView>

Comment: I am now getting the error: " Invalid layout param in a LinearLayout:layout_below". Thanks for your comment!
Comment: It's parent is Linearlayout?
Comment: Yes, would that have to be changed?
Comment: NO, you will have to then make many moifications. android:layout_height="wrap_content" ,  use this property in all of your LinearLayouts or android:layout_height="match_parent" in the root linear Layout.


Are the functions of substitute chords different in minor and major?

Question: I am studying substitute chords,
and secondary triads with two common notes can substitute primary triads.
I know that a chord, in which the root and third notes are common, has a stronger surrogate
function.
However, I saw an explanation on the Internet Wiki (Korean) that the chords that substitute different chords depending on major and minor. it is as below

major
ii - Secondary chords / Secondary chords substitute subdominant
chords, and correspond to Re, Fah, and R in the name of the
commandment. In general, the form of the first dislocation is widely
used.
iii - Represents a third chord / dominant chord, and corresponds to
mi, sol, and si in the name of the command.
vi - It represents the sixth chord / tonic chord, and corresponds to
Ra, Do, and Mi in the name of the command.
vii° - There is no 7th chord / surrogate chord, and according to the
name of the command, it corresponds to Si, Re, and Pa. Since it is a
reduced triad, the resonance of the basic position is unstable, so it
is generally used in the form of the first potential.
All standards are in C major.
minor
In minor, the direction of use of chords on the same intervals
depending on the harmonic minor scale, natural minor scale, and
melodic minor scale.
ii° - Secondary chords / Secondary chords substitute subdominant
chords and correspond to Si, Re, and Pa in the name of the
commandment.
III+ - Represents the third chord / dominant chord, and corresponds to
do, mi, and sol♯ in the name of the command. Since it is an augmented
triad, I tend to use 'do' as a non-harmonic consonant and resolve it
with V rather than being used independently.
III5♮ - 3rd chord / Tonic chord, and corresponds to do, mi, and sol in
the name of the command.
VI - 6th chord / It Secondary chords substitute subdominant chords,
and according to the name of the commandment, it corresponds to F, D,
and Do. Only when used in the deceptive cadence, it substitutes for
the tonic chord.
vii° - There is no 7th chord / surrogate chord, and it corresponds to
sol♯, si, and re according to the name of the command.
♮VII - 7th chord / 'Once' represents the dominant chord, and
corresponds to sol, si, and re in the name of the command. However,
rather than maintaining the functionality within the minor key, it
tends to be used as a V in the major key when the harmonious flow is
converted into the context of a parallel major key.
All standards are A minor.

What I'm particularly confused about here is that VI is described as a substitute for subdominant in minor, so why is it different from major?
Comment: @Aaron It's a very unreliable source, but may have omitted some explanation there. And I put it on the bounty because I thought might be able to catch what someone omitted here. Just give me a chance. I'll wait and accept your answer if no answer.
Comment: I see you've posted a bounty. What exactly are you looking for?
Comment: @Aaron Because someone might know why they explained it that way.
Comment: Well, without knowing what the author was thinking, I'd say it's just not a reliable source. These are basic, well-known functions of the `vi` chord in both major and minor.
Answer: The vi and VI chords in major and minor, respectively, may both substitute for the tonic (in a deceptive cadence) or the subdominant. Why the text mentions these functions only for minor is not clear.


k-aray necklaces with fixed/conserved positions

Question: I asked a question in a previous post about enumerating all possible k-ary bracelets with certain positions fixed to a specific bead/character. I asked a few mathematicians, and it seems its quite difficult to do so in a reasonable way.
However, it turns out that I am only looking for necklaces, not bracelets. Eg I only care about rotations, not reflections.
Hopefully its ok to ask the basically the same question again, Im thinking it might be more feasible to enumerate if you only have to factor in rotations.
To restate the question, say I have k possible integers to pick from, and my program randomly picks from the set of k when generating necklaces of length n, I know I can enumerate the maximum possible unique necklaces that could be generated for n/k using the equation listed here. This is great because now I have an upper bound on my programs duration and know when to stop running if I have already found all possible unique necklaces for a given n/k
However, my program also has the option to conserve, or fix, any particular value from the set of k, at any position in the necklace. It allows this to be done for as many positions of length n that you want.
For example, given n = 4, and k = [0, 1, 2, 3, 4, 5, 6], and considering the following necklaces equivalent:
[0,0,0,1] and [1,0,0,0]
I can use the formula as mentioned here to calculate easily how many unique necklaces I can possibly generate.
But if the user of my program specifies that they want the generated necklaces to always have the value 1 at position 1 and the value 2 at position 4, eg the random necklace generator will only create sequences such as:
[1,0,0,2] or [1,6,4,2] or [1,2,3,2]
The question is: given necklaces of length n containing any selection of characters from set k with f positions in n being fixed to c different values from k, is it possible to enumerate the total unique necklaces that could be made
Comment: To help people pitch their answers, do you know any group theory? (Not) Burnside's lemma? Pólya enumeration theory?
Comment: Im very new to this kind of mathematics, Im actually normally a web developer who is building something to help a mate who is doing his phd. it took me ages to work out how to convert the necklace enumeration formula from that wiki article i linked into code.
Comment: If you want to generate a list of all the distinct necklaces then it's probably easier to skip the maths and just generate all strings which meet the additional constraints, rejecting those which have a rotation which also meets the constraints and is lexicographically smaller. But you mention "*random necklace generator*", so is your final goal to write some software which selects the necklaces uniformly, avoiding biases towards those which have multiple valid rotations?
Comment: i already have written the software, im looking for a mathematical formula to calculate the upper bounds of how long it should run, since it randomly generates the sequences and checks for uniqueness as it goes in a big long loop. for non-necklace sequences, and plain necklaces, i know when i have found all possible options (eg i know when to stop the loop), but also more to the point if the number of sequences requested is the same as the maximum possible, i switch to a non-random generation.
Comment: if however, the user requests sequences with fixed position, i have no way of knowing what the maximum possible sequences is, so cant  terminate the loop with confidence, and more importantly dont know if the maximum number of sequences has been requested so as to switch from random to sequential generation
Answer: This isn't a full answer to the question as asked, but I hope it's a sufficient answer to the underlying question.
Partial coupon collector
Suppose there are $N$ distinct necklaces and you have a method which uniformly generates a random one. You want to select $n$ different ones. If you do so by the simple process of generating and adding to a set until the size of the set is $n$, the expected number of times you have to call the generation method is $$\frac{N}{N} + \frac{N}{N-1} + \cdots + \frac{N}{N-n+1}$$ as a truncated sum from the coupon collector problem.
Suppose you also have a method to generate the complete set of $N$ necklaces, and it is about as expensive as calling the random generation $N$ times. You can then do a partial shuffle to select $n$ of them.
At what value of $n$ should you prefer the sequential generator to the random generator? The answer is when $n > (1 - \frac{1}{e})N$. (There must be a proof of that somewhere on this site; I haven't found it, but if anyone can find one then feel free to edit, removing this parenthetical and adding a link).
For practical purposes we can approximate that as $n > \frac{2}{3}N$. Note that this implies that you can optimise your existing solution for non-necklaces and plain necklaces.
Single constraint
The single constraint that position $i$ has colour $j$ is just a constraint that there be at least one bead of colour $j$. The number of necklaces satisfying this single constraint is the number of necklaces with $k$ colours minus the number without colour $j$, so $$\frac{1}{n}\sum_{d\mid n}\varphi(d)\left( k^{\frac{n}{d}} - (k-1)^{\frac{n}{d}} \right)$$
Asymptotics of necklaces with constraints
For $n$-element necklaces over $k$ colours without constraints, the first order approximation is that there are about $\frac{1}{n} k^n$ distinct necklaces. This is easy to understand: there are $k^n$ strings of $n$ elements over $k$ symbols, and the majority of them are aperiodic so that the $n$ rotations are distinct.
If we now constrain $f > 1$ positions, the first order approximation is $k^{n-f}$. This is again easy to understand: in general, the rotations of a valid string will not satisfy all $f$ constraints. (Note: if the constraints are periodic then this argument needs modification to take account of the periodicity. E.g. if the constraints are automatically satisfied by a rotation of $\frac{n}{2}$ then the first order approximation is $\frac{1}{2}k^{n-f}$). The second-order correction is $O(k^{n-f-1})$. If $k$ is large then the $O$ would have to be hiding a large constant for $N$ to get below $\frac{2}{3}k^{n-f}$. In fact, I suspect that the second-order correction can be stated much more tightly as $O(k^{\frac{1}{2}(n-f)})$, but I haven't tried to prove this.
Putting it together: a practical approach
Calculate an upper bound $U$ using the formula for unconstrained necklaces, as a precaution for the small-$k$ case. Define an estimate $\tilde N = \min(U, k^{n-f})$ for the number of solutions, with corrections for periodicity as discussed. If $n > \frac{2}{3} \tilde N$, use sequential generation. Otherwise use random generation, but as a further precaution count the number of times you call the random generator. If the count passes e.g. $1.5 \tilde N$, abort the random generation and switch to sequential generation, logging the parameters for a more specific follow-up question.
Comment: Ahhhhh i get it now, sorry for my misunderstanding
Comment: holy crap thats an in-depth explanation. im not a mathematician by any stretch so it will take me a while (and lots of googling) to parse exactly what is being said here, but thank you so much for taking the time to explain it in such detail.
Comment: ah yep the constrainsts i believe are periodic, eg rotations of the string still count as valid, as long as in one of those rotations the string has the correct characters fixed at the correct positions. when you say If k is large then the O would have to be hiding a large constant for N to get below 23kn−f. - fyi k is currently a set of 32 'characters' (hell it could just be numbers from 1-32) from which the sequences of n length are being randomly generated
Comment: @MatthewPrasinov, that's not what I mean by periodic constraints. As an example of aperiodic constraints, consider $n=6$ with position 0 forced to colour 0 and position 3 forced to colour 1. Then a rotation by three can never meet the constraints. As an example of periodic constraints, consider $n=6$ with position 0 forced to colour 0 and position 3 forced to colour 0. Then a string which meets the constraints is guaranteed to always meet the constraints after a rotation by 3, so we have a correction factor.
Comment: ah, sorry for the confusion, i didnt explain properly perhaps. in my program, if n = 6 and position 0 is fixed to 0 and position 3 is fixed to 1, then all 6 rotations of that sequence are considered equivalent and subsequently ignored
Comment: for example [1,0,0,2,0,0] is considered equivalent to [2,0,0,1,0,0] and [0,1,0,0,2,0]...

the constraint only affects how the linear sequence is generated, but once a particular linear sequence that matches that constraint is made, all rotations are removed from the possible future pool of new sequences... or am i still misunderstanding what you mean?
Comment: Yes, that's the necklace equivalence. My point is that if you have no constraints, $[0, 1, 0, 1, 2, 0]$ and its six rotations are all the same necklace, which is the source of the $\frac{1}{n}$ in the formula for counting unconstrained necklaces. If you add the constraints $a[0]=0,a[3]=1$ then the rotations no longer meet the constraints, so you're not double-counting and don't need to divide by $n$. But if the constraints are $a[0]=0,a[3]=0$ then $[0,a,b,0,c,d]$ rotates to $[0,c,d,0,a,b]$ which still meets the constraints, so you need a correction factor for double-counting.


How to add a user/login Link to the Maintenance Mode page?

Question: I have my site in Maintenance Mode. I know I can get to my login page by going to http://example.com/login .
My client wants a login link on the Maintenance Mode page (when in this mode). Before I say "no this is not possible", I am wondering if this is possible. I could add this to the Maintenance template page right? I already have a custom Maintenance Mode page.
EDIT: Where the http://adaptivethemes.com/how-to-theme-the-user-login-page-in-maintenance-mode
solution works, its not what I want. All I want is a link to the user login page displayed on the Maintenance Page.
I did try this: I added html to the maintenance php template:
Login

HOWEVER this only show a link that was NOT clickable. Also how would I get to the User login page if I am testing this on a test server, but the domain will be different than on the test server. Change the domain once on the production server?
Answer: Yes, you should be able to. You can create a maintenance page template similar to any other in Drupal, "maintenance-page.tpl.php". However, to get that to work you probably have to make some changes to your template.php file.
More info can be found here: http://adaptivethemes.com/how-to-theme-the-user-login-page-in-maintenance-mode although I believe that example is from Drupal 6, but the idea should be fairly similar for Drupal 7 as well.
Comment: The only issue I have your suggestion that it prompts user on maintenance page for user login credentials when all I want is a link.
Comment: Ok as a temp solution I just added HTML to maintenance-page.tpl.php.
Comment: @BenjaminJones I don't see why you wouldn't just be able to add a textual link then on the maintenance page to /user/login just as with any standard href link.
Answer: Using the maintenance-page.tpl.php file is indeed a vaid approach for this. However if you use that approach, there are two maintenance page files that you should create. You can duplicate your theme's page.tpl.php twice and name them:

maintenance-page.tpl.php: This file controls the page that is displayed when the site is in "maintenance mode" but the database connection and database are still functioning correctly.
maintenance-page--offline.tpl.php: This file controls the page that is displayed when Drupal cannot access the database (for whatever reason).

For more details on this, and related changes in settings.php, refer to the community documentation about Theming the Drupal maintenance page.


nginx node.js & socket.io 504 timeout

Question: Nginx config
server {
    listen        *:80;
    server_name   live.domain.com;

    server_tokens off;
    charset utf-8;

        error_log       /var/log/nginx/live-error.log info;
        access_log      /var/log/nginx/live-access.log;

    location / {
        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection "upgrade";
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header Host $http_host;
        proxy_set_header X-NginX-Proxy true;
        proxy_pass http://127.0.0.1:1337;
        proxy_redirect off;
    }
}

When node.js is working everything is okay, but if node.js not started and I try to load page http://live.domain.com/socket.io/socket.io.js it makes me wait 30 seconds (read_timeout).
I want make it so, that if node.js not running I'm getting 404 or 502 error right away without 30 seconds waiting for timeout.
In other words: I need to check node.js on client side right away.
Answer: A flexible solution would be to use upstream:
upstream backend {
    server 127.0.0.1:1337    max_fails=1 fail_timeout=5s;
}

server {
    listen        *:80;
    server_name   live.domain.com;

    server_tokens off;
    charset utf-8;

        error_log       /var/log/nginx/live-error.log info;
        access_log      /var/log/nginx/live-access.log;

    location / {
        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection "upgrade";
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header Host $http_host;
        proxy_set_header X-NginX-Proxy true;
        proxy_pass http://backend;
        proxy_redirect off;
    }
}

This way you can additionally control how many failures are tolerated and you can have multiple servers in one upstream.
Answer: Set proxy_connect_timeout to lower value:
proxy_connect_timeout 2s;

Answer: Please see my answer here, there could also be a problem with csf if you're on Linux:
https://serverfault.com/a/713874/150138

nginx node.js & socket.io 504 timeout


Configure url() source in tailwind.config

Question: When using url() in theming in tailwind.config.js, e.g.,
theme: {
  backgroundImage: {
    abc: 'url(/myImage.png)
  }

eventually this URL is using the stylesheet source which for me just so happens to be a CDN setup by shopify hydrogen. Is there a way to use the active domain instead of CSS source? Using the active domain exposes the image correctly.
What is interesting to note is that tailwind.css does reference fonts with the same url() and this seems to work as PostCSS processes the fonts and serves them from the CDN
@font-face {
  font-family: 'SourceSans';
  font-display: swap;
  font-weight: 600;
  src: url('./fonts/SourceSans/SemiBold.ttf') format('opentype');
}

Answer: Consider using the same ./ prefix (instead of /) in your background image values as you do for your @font-face.
The url() function works the same way whereever it is used, so if it works in the src in @font-face, you can use the same strategy in backgroundImage:
abc: 'url(./myImage.png)',

Comment: Thanks, the images are kept intentionally in the public/ directory whereas the fonts are in a styles/ dir with tailwind.css. It seems to me that postcss is intentionally processing the fonts and putting them in a different output dir that must be set by hydrogen env variable or something.


When $A^TA = I$, what matrix is orthogonal to what?

Question: When $A^TA = I$, I am told it is orthogonal. What does that mean?
$A = \begin{bmatrix}cos\theta & & -sin\theta \\ \\ sin\theta & & cos\theta\end{bmatrix}, A^T = \begin{bmatrix}cos\theta & & sin\theta \\ \\ -sin\theta & & cos\theta\end{bmatrix}$
Comment: A is an orthogonal matrix on it's own
Comment: You could start by asking yourself what $A$ is.
Comment: That is *the definition* of an orthogonal matrix. It means that a matrix (with real entries) is called orthogonal if and only if its inverse is equal to its transpose.
Comment: It is a rotation matrix.
Comment: @user122358: Nope. The diagonal 2x2 matrix with entries -1 and +1 is orthogonal, but I wouldn't call it a rotation matrix.
Comment: See also [Why is an orthogonal matrix called orthogonal?](http://math.stackexchange.com/questions/650379)
Comment: @Jyrki Lahtonen You raise a good point. Your example has determinant $-1$ and is sometimes called an improper orthogonal matrix instead of a special orthogonal Martz (which has determinant $1$). The latter is a rotation matrix and the former combines a rotation (in this case the identity!) with a reflection.
Answer: It means that the row vectors (and also the column vectors) form an orthogonal basis, that means if $A$ has dimension $n\times n$, $A$ consists of $n$ linear independent and pairwise orthogonal vectors spanning $\mathbb R_n$
Comment: Even more, the vectors form am orthonormal-system, the additional property is that the vectors have length $1$
Answer: Perhaps the term is suggestive of matrix $\mathbf{A}$ being orthogonal to another matrix $\mathbf{B}$ in some sense like $$\mathbf{A}.\mathbf{B}=0$$ as it would be if $A$ and $B$ were orthogonal vectors. However this is not what it means when considering matrices.
For matrices ìt refers to the set of columns being orthogonal (actually orthonormal) in the usual sense for vectors
$$\mathbf{c_i}.\mathbf{c_j}=\delta_{ij}$$ The same is true for the set of rows.
Because the columns are orthogonal (and rows)  the matrix itself is called orthogonal. These matrices have the property you stated.
(Try it with the columns or rows of your 2x2 matrix.)


How to boost Solr search results by document type?

Question: Note: I'm using Sunspot with Rails, but a generic Solr response could still guide me in the right direction if you're not familiar with Sunspot's DSL.
I have a few models similar to these:
class Book < ActiveRecord::Base
  searchable do
    text :title, boost: 2.0
    text :content
  end
end

class Article < ActiveRecord::Base
  searchable do
    text :title, boost: 2.0
    text :content
  end
end

I'm needing to do a fulltext search in all models at the same time for a mixed result, but articles should be considered a bit more relevant than books in the search results.
My current code to perform the search is as follows.
search = Sunspot.search do
  fulltext search_terms, minimum_match: 1
end

This correctly returns mixed results, but I'd need Article results to be boosted in comparison to Book results. I want to be clear that this is NOT the same as listing all Article results first and then listing all Book results. There could still be some mix depending on how Solr ranks the results based on their overall content.
I'm guessing I'll need to use some boost function but can't figure out exactly how.
Any pointers?
Answer: Sunspot generally tries to expose these kinds of things as functions within the "search" block. Checking the Sunspot docs shows this…
# Posts with pizza, scored higher if featured
Post.search do
  fulltext 'pizza' do
    boost(2.0) { with(:featured, true) }
  end
end

That's from https://sunspot.github.io/docs/#Search_In_Depth

Because Sunspot indexes the model name into the "type" field, I think you could adapt that thusly:
boost(10.0) { with(:type, "Article") }

Alas. If you do try this, you'll get an error like this:
Sunspot::UnrecognizedFieldError: No field configured for Article, Book with name 'type'

That's because current versions of Sunspot's DSL in this case reference the fields are defined in the searchable block, whereas the type field is kind of a special case. Perhaps a good opportunity for a contribution to Sunspot there?
Knowing that, we have a possible workaround, and that is to define our own custom type-related field on your documents. Perhaps call it source to avoid clobbering the special cased defaults, though testing may show that not to be a big deal.
Leading me to this final code example (untested, ymmv, etc!)
class Article < ActiveRecord::Base
  searchable do
    text :title, boost: 2.0
    text :content
    string :source do
      class.name
    end
  end
end

Sunspot.search(Article, Book) do
  fulltext(search_terms) do
    minimum_match 1
    boost(ARTICLE_BOOST) { where(source, "Article") }
  end
end


Completar valores em coluna baseado em condição e valor em outra coluna

Question: Estou tentando há um tempo resolver isso, mas não deu certo.
Tenho essa tabela abaixo. O que quero é que a coluna inchikey seja completada de acordo com a coluna "cid_pub_chem". Se vcs repararem, nas linhas 1 e 2, temos o valor de 31253 para a coluna "cid_pub_chem" e valores para a coluna "inchikey" mas nas linhas 5 e 6 eu tenho o mesmo valor de "cid_pub_chem", porém a coluna "inchikey" está com NA. Deve ser muito simples resolver isso, mas não teve jeito...
abc = structure(
  list(cid_pub_chem = c("31253", "31253", "6654", "11040762", "31253", "31253"),
       inchikey = c("UAHWPYUMFXYFJY-UHFFFAOYSA-N", "UAHWPYUMFXYFJY-UHFFFAOYSA-N", "GRWFGVWFFZKLTI-UHFFFAOYSA-N", "WPOQYXKDKVBMSB-UHFFFAOYSA-N", NA, NA),
       height = c("37740", "25556", "39861", "51715", "26048", "52332")),
  row.names = c(NA, -6L),
  class = "data.frame")

Qualquer ajuda é bem vinda. Postei umas perguntas no stackoverflow em inglês (não sabia da existência desse), mas faz uns bons meses e eu esqueci como formatar melhor o código (aliás, como faz isso?). Desculpem...
Answer: Um das formas de fazer isso é construir um "dicionário" ou "gabarito" com os valores que você quer unir e então realizar uma união.
O código para criar o gabarito pode ser algo assim:
library(tidyverse)
valores <- abc %>%
  filter(!is.na(inchikey)) %>%
  select(cid_pub_chem, inchikey) %>%
  unique()

E então podemos remover a coluna com as informações erradas e repreencher ela usando o gabarito que acabamos de criar.
abc %>%
  select(-inchikey) %>%
  left_join(valores, "cid_pub_chem")
#>   cid_pub_chem height                    inchikey
#> 1        31253  37740 UAHWPYUMFXYFJY-UHFFFAOYSA-N
#> 2        31253  25556 UAHWPYUMFXYFJY-UHFFFAOYSA-N
#> 3         6654  39861 GRWFGVWFFZKLTI-UHFFFAOYSA-N
#> 4     11040762  51715 WPOQYXKDKVBMSB-UHFFFAOYSA-N
#> 5        31253  26048 UAHWPYUMFXYFJY-UHFFFAOYSA-N
#> 6        31253  52332 UAHWPYUMFXYFJY-UHFFFAOYSA-N


Is this a sensible/valid definition for "isotropic metric space"?

Question: For a metric space, $(X,d)$, define the following:

for every $x \in X$, the local similitude group, $Sim(X, x)$, is the set of all surjective similitudes $X \to X$ which fix $x$.
for every $x \in X$, the local isometry group, $Iso(X, x)$, is the set of all surjective isometries $X \to X$ which fix $x$.
the (global) isometry group, $Iso(X)$, is the group of all surjective isometries $X \to X$.
an ang is a triple of points $(r_1, v, r_2)$. (The notation is meant to be suggestive, $r_1$ stands for "ray № 1", $v$ stands for "vertex", $r_2$ stands for  "ray № 2", and the word has three letters because it denotes a triple of points).
A point $b \in X$ is said to be between points $a,c \in X$ if and only if $$d(a,c) = d(a,b) + d(b,c) $$ i.e. if the triangle inequality becomes an equality.
An angle is an equivalence class of angs under the following equivalence relation: $(r_1^*, v, r_2^*) \sim (\tilde{r_1}, v, \tilde{r_2})$ if and only if (1) [ $r_1^*$ is between $v$ and $\tilde{r_1}$, or $\tilde{r_1}$ is between $r_1^*$ and $v$];  and (2)  [$r_2^*$ is between $v$ and $\tilde{r_2}$, or $\tilde{r_2}$ is between $r_2^*$ and $v$].
an angle measure is a function from the set of all angles in $(X,d)$ to $\mathbb{R}$, which is (1) invariant under the action of the global isometry group, i.e. if two angles (have representatives which) are related by an isometry then they must have the same angle measure, (2) for angles with a given vertex $v$, the angle measure must be invariant under the action of $Sim(X,v)$.
two angles are congruent if and only if they have the same angle measure.

In particular, note that two congruent angles need not be related by a surjective isometry, and two congruent angles need not be related by a surjective vertex-fixing similitude, even though the converses of these statements are automatically true by the definition of angle measure.

isotropic metric space - two angs with the same vertex $v$ are congruent if and only if they are related by the action of the local similitude group, $Sim(X,x)$.

This is an attempt to say, for general metric spaces, that "the notion of angle is rotationally invariant, i.e. does not depend on direction", even though we don't have a notion of rotation in general metric spaces. Basically, that the local isometry group at each point is "rich enough" (has enough "rotations") so as to be compatible with the angle measure.
<Examples> Riemannian manifolds, since (unlike for general Finslerian manifolds), the metric tensor tensor depends only on position, not position and direction. (See also.)
Finite-dimensional Banach spaces with norm induced by an inner product. <Examples>
We say that, given two angs $(r_1^*, v^*, r_2^*)$ and $(\tilde{r_1}, \tilde{v}, \tilde{r_2})$, they satisfy the SAS (Side-Angle-Side) criterion if and only if (1) they are congruent, i.e. they have the same angle measure $(r_1^*, v^*, r_2^*) \sim (\tilde{r_1}, \tilde{v}, \tilde{r_2})$, (2) $d(r_1^*, v^*) = d(\tilde{r_1}, \tilde{v})$, and (3) $d(r_2^*, v^*) = d(\tilde{r_2}, \tilde{v})$.
We say that a metric space $(X,d)$ satisfies the SAS (Side-Angle-Side) Postulate if and only if, given two angs satisfying the SAS criterion, they are related by the global isometry group.

Lemma: A metric space which satisfies the SAS Postulate is isotropic.

Proof: Still working on it -- the lemma might not be true with the given definitions, which would suggest that the definitions need to be changed/fixed.
Notes:
 On definition 6:
 Is this definition of angle compatible with already existing generalizations, e.g. (1)(2) ?
Also this definition of angle only seems to make sense when the notions of (1) betweenness and of (2) homothetic transformations/scaling/$Sim(X,x)$ coincide with each other. (I want to say this occurs when the metric space is an externally convex M-space.) However, that only occurs in really special spaces. Also it seems like this definition tries to make the notion of angle symmetric in $r_1$ and $r_2$, which we shouldn't necessarily expect to be the case (see page 4 here).
$\tilde{6}$ (alternate). An angle is an equivalence class of angs, with two angs equivalent if and only if they have the same vertex $v$ and are related by the local similitude group, i.e. if $d(v, r_1^*) = \lambda d(v, \tilde{r_1})$ and $d(v, r_2^*) = \lambda d(v, \tilde{r_2})$ for some $\lambda > 0$. Note: This definition would also make isotropic metric space below much easier to understand, allowing one to replace angs with angles.
On definition 7:
For really degenerate, "non-homogeneous", metric spaces, would it make more sense to create a separate angle measure function for each point, the same way there is a separate local isometry or similitude group for each point, and concomitantly drop the requirement that the angle measures have to be invariant under the global isometry group $Iso(X)$? The idea is that "angle measure" should be the "infinitesimal" and "scale-invariant" analog of "distance" for a metric space, so it's really only invariance under $Sim(X,v)$ at each $v$ which is most crucial for describing that.
Also, although it's necessary to define congruence of angles, the same way the metric is necessary to define congruence of pairs of points, there doesn't seem to be any "natural" choice of angle measure except in special cases where "circles" and their "circumferences" make sense.
Related questions:
(1)(2)(3)(4)(5)(6)(7)(8)(9)(10)(11)(12)(13)(14)(15)(16)(17)(18)(19)(20)(21)(22)(23)(24)(25)(26)(27)(28)(29)(30)(31)(32)(33)(34)(35)(36)(37)(38)(39)(40)(41)(42)(43)(44)(45)(46)
Answer: This would be a better solution:
Define an angle to be a triple of points $(r_1, v, r_2)$ in the metric space.
We say that angles $(r_1, v, r_2)$ and $(\rho_1, v, \rho_2)$ are related by the action of the local similitude group $Sim(X,v)$ if and only if there exists an $f \in Sim(X,v)$ such that $f(r_1) = \rho_1$ and $f(r_2) = \rho_2$.
We write this as $(r_1, v, r_2) \sim_v (\rho_1, v, \rho_2)$.
(Because of the implicit assumption that $f$ is surjective, this relationship is symmetric - just use $f^{-1}$. The $Id$ is in $Sim(X,v)$ so the relationship is also reflexive, and the fact that $Sim(X,v)$ is closed under composition means that the relationship is also transitive -- i.e. it's an equivalence relation.)
Denote the set of all angles with vertex $v \in X$ by $angle (X,v)$.
For each point $v \in X$, we define an angle measure to be any real-valued function $\measuredangle_v: angle(X,v) \to \mathbb{R}$ with the following constraint: if $(r_1, v, r_2)$ and $(\rho_1, v, \rho_2)$ are related by the action of $Sim(X,v)$, i.e. $(r_1, v, r_2) \sim_v (\rho_1, v, \rho_2)$, then $\measuredangle_v((r_1, v, r_2))=\measuredangle_v((\rho_1, v, \rho_2))$.
We say that two angles $(s_1, v, s_2)$ and $(\sigma_1, v, \sigma_2)$ are congruent if they have the same angle measure, written $(s_1, v, s_2) \cong_v (\sigma_1, v, \sigma_2)$, in other words $$(s_1, v, s_2) \cong_v (\sigma_1, v, \sigma_2) \iff \measuredangle_v((s_1, v, s_2)) = \measuredangle_v((\sigma_1, v, \sigma_2)) \,. $$
Note that $(r_1, v, r_2) \sim_v (\rho_1, v, \rho_2) \implies (r_1, v, r_2) \cong_v (\rho_1, v, \rho_2) \,, $ BUT $$(r_1, v, r_2) \cong_v (\rho_1, v, \rho_2) \kern.6em\not\kern -.6em \implies  (r_1, v, r_2) \sim_v (\rho_1, v, \rho_2) \,.$$
We say that two angles $(r_1, v, r_2)$ and $(\rho_1, v, \rho_2)$ satisfy the SAS criterion if and only if: $$(r_1, v, r_2) \cong_v (\rho_1, v, \rho_2) \,, \quad d(r_1, v) = d(\rho_1, v) \,, \text{ and  }d(r_2, v)=d(\rho_2, v) \,.$$
Then one can say that the angle measure $\measuredangle_v$ is isotropic at $v$ if and only if: two angles $(r_1, v, r_2)$ and $(\rho_1, v, \rho_2)$ satisfying the SAS criterion is equivalent to them being isometric to each other.
(I.e., two angles satisfy the SAS criterion if and only if they can be "rotated into each other", i.e. are related by the action of the local isometry group $Iso(X,x)$.)
With these definitions, the proof of the lemma above is immediate. Also, we can skip out on the ugly definitions of ang and angle from above and have fewer equivalence relations to deal with.
The only downside is that we have to define the extra data of an angle measure at every single point. While the data does have a compatibility requirement with the space's metric, there nevertheless (as defined) is no "natural" way to choose an angle measure at a point, so the relationship between the angle measure at each point and the metric is not canonical, but even more problematically, as a result there is no canonical relationship between the angle measures at different points (the way there would be if all of the angle measures were derived from the metric, which is common to each point of the metric space).
In practice though, this might be the best we can expect. While there is a canonical way to choose an angle measure for the Euclidean plane, even as soon as we do something simple, like change the norm we use for $\mathbb{R}^2$, ambiguity arises about whether we should continue to use the (isotropic) angle measure from Euclidean space, or if we should use a (non-isotropic) angle measure derived from the norm's unit ball. Anyway, my concern wasn't how much of the definition of angle measure for the Euclidean plane should I imitate, my concern was what properties does angle measure have in the Euclidean case which can be stated in the case of a completely general metric space without making any additional assumptions about the objects which exist on the space or what properties it satisfies, and this is what I came up with.
Still, it would be possible to go even further, by allowing $\measuredangle_v$ to map into any set, not just $\mathbb{R}$ (although ideally it would still be the case that $\measuredangle_v$ maps into the same set for all $v \in X$). (For some idea of what this might look like for a set other than $\mathbb{R}$, see here, although I am not sure whether the proposed definition of angle measure satisfies my single basic property, that two angles related by the action of the local similitude group possess the same angle measure.)


Vocal Cords Catching at Lowest Note

Question: I'm working on increasing my vocal range, and I've gotten to G2 as the lowest note that I can sing clearly and loudly.  However, for some reason, whenever I try to sing F2, just one pitch lower, it's as though my vocal cords are catching on something, making the tone very unstable and sort of... it's hard to describe.  Like a combination of screechy and whiny.  I can technically hit the note, but whenever it's stable I can't increase the volume past a whisper, whereas even one pitch higher it's perfectly clear.
Yesterday when I managed to get it perfectly a few times I could feel the difference, so my main question is, what is actually happening?  I know the way to fix it - just practice more - but I'm really curious as to why it's like that currently.
Comment: It's possible that your ability to sing this note resets every day. I have similar low volume "problems" at the extreme ends of my singing range, and I find that I can temporarily increase my range with the proper vocal exercises.
Comment: It's called "vocal fry" and it happens when your vocal chords are inefficiently resonating. You lack the control and air management for them to resonate the note, and that's the resulting sound.
Answer: To be honest, it doesn't sound like you are doing anything wrong.  From your description, I think you've just hit the low end of your vocal range.  We all have a low and high note that try as we might, we just physically can't get past.  Sounds like you found your low note.  I don't think practicing more is the solution - it will just be frustrating and might damage your voice.
Comment: I don't agree with you Jamie. If the singer is able to sing the note occasionally and presumably without forcing anything, it seems more like a matter of technique. Practicing is one way to overcome this limitation.

Vocal Cords Catching at Lowest Note


How to rotate the cube and have its sides expanded using css html?

Question: i want to rotate the cube and its faces expanded. i have tried something like below,
.wrapper{
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%,-50%);
 }
 .cube-wrap {
     width: 40px;
     height: 40px;
     -webkit-perspective: 2000px;
     -webkit-perspective-origin: 50% -500px;
 }
 .single-box {
     background-size: cover;
     display: block;
     position: absolute;
     width: 40px;
     height: 40px;
     background-color: #60c2ef;
    -webkit-transform: rotateY(45deg) translateZ(-200px) rotateX(15deg);
    -webkit-transform-origin: 50% 50% 0;
 }
 .box {
     -webkit-transform-style: preserve-3d;
     -webkit-animation: rotate 1.5s infinite ease;
 }
 .side-front {
     animation: side-front-animation 3s ease infinite;
     animation-delay: 100ms;
     transform: rotateY(0deg) translateZ(150px);
     animation-fill-mode: forwards;
     transform-origin: 50% 50%;
     background-color: #007dc5;
     -webkit-transform: translateZ(20px);
 }
 .side-back {
     animation: side-back-animation 3s ease infinite;
     animation-delay: 100ms;
     transform: rotateY(-180deg) translateZ(150px);
     animation-fill-mode: forwards;
     transform-origin: 50% 50%;
     background-color: #007dc5;
     border: #ffffff;
     -webkit-transform: rotateY(180deg) translateZ(20px);
 }
 .side-top {
     animation: side-top-animation 3s ease infinite;
     animation-delay: 0;
     transform: rotateX(90deg) translateZ(150px);
     animation-fill-mode: forwards;
     transform-origin: 50% 50%;
     background-color: #007dc5;
     -webkit-transform: rotateX(90deg) translateZ(20px);
 }
 .side-bottom {
     animation: side-bottom-animation 3s ease infinite;
     animation-delay: 0;
     transform: rotateX(-90deg) translateZ(150px);
     animation-fill-mode: forwards;
     transform-origin: 50% 50%;
     background-color: #007dc5;
     -webkit-transform: rotateX(-90deg) translateZ(20px);
 }
 .side-left {
     animation: side-left-animation 3s ease infinite;
     animation-delay: 100ms;
     transform: rotateY(-90deg) translateZ(150px);
     animation-fill-mode: forwards;
     transform-origin: 50% 50%;
     background-color: #007dc5;
     -webkit-transform: rotateY(-90deg) translateZ(20px);
 }
 .side-right {
     animation: side-right-animation 3s ease infinite;
     animation-delay: 100ms;
     transform: rotateY(90deg) translateZ(150px);
     animation-fill-mode: forwards;
     transform-origin: 50% 50%;
     background-color: #007dc5;
     -webkit-transform: rotateY(90deg) translateZ(20px);
 }

 @-webkit-keyframes rotate {
     0% { -webkit-transform: rotateY(0); }
     100% { -webkit-transform: rotateY(360deg); }
 }

 @-webkit-keyframes side-top-animation {
     0% { opacity: 1; transform: rotateX(90deg) translateZ(150px)}
     20% { opacity: 1; transform: rotateX(90deg) translateZ(75px)}
     70% {  opacity: 1; transform: rotateX(90deg) translateZ(75px) }
     90% {  opacity: 1; transform: rotateX(90deg) translateZ(150px) }
     100% {  opacity: 1; transform: rotateX(90deg) translateZ(150px) }
 }

 @-webkit-keyframes side-bottom-animation {
     0% { opacity: 1; transform: rotateX(-90deg) translateZ(150px)}
     20% { opacity: 1; transform: rotateX(-90deg) translateZ(75px)}
     70% {  opacity: 1; transform: rotateX(-90deg) translateZ(75px) }
     90% {  opacity: 1; transform: rotateX(-90deg) translateZ(150px) }
     100% {  opacity: 1; transform: rotateX(-90deg) translateZ(150px) }
 }

 @-webkit-keyframes side-front-animation {
     0% { opacity: 1; transform: rotateY(0deg) translateZ(150px)}
     20% { opacity: 1; transform: rotateY(0deg) translateZ(75px)}
     70% {  opacity: 1; transform: rotateY(0deg) translateZ(75px) }
     90% {  opacity: 1; transform: rotateY(0deg) translateZ(150px) }
     100% {  opacity: 1; transform: rotateY(0deg) translateZ(150px) }
 }
 @-webkit-keyframes side-back-animation {
     0% { opacity: 1; transform: rotateY(-180deg) translateZ(150px)}
     20% { opacity: 1; transform: rotateY(-180deg) translateZ(75px)}
     70% {  opacity: 1; transform: rotateY(-180deg) translateZ(75px) }
     90% {  opacity: 1; transform: rotateY(-180deg) translateZ(150px) }
     100% {  opacity: 1; transform: rotateY(-180deg) translateZ(150px) }
 }

 @-webkit-keyframes side-left-animation {
     0% { opacity: 1; transform: rotateY(-90deg) translateZ(150px)}
     20% { opacity: 1; transform: rotateY(-90deg) translateZ(75px)}
     70% {  opacity: 1; transform: rotateY(-90deg) translateZ(75px) }
     90% {  opacity: 1; transform: rotateY(-90deg) translateZ(150px) }
     100% {  opacity: 1; transform: rotateY(-90deg) translateZ(150px) }
 }
 @-webkit-keyframes side-right-animation {
     0% { opacity: 1; transform: rotateY(90deg) translateZ(150px)}
     20% { opacity: 1; transform: rotateY(90deg) translateZ(75px)}
     70% {  opacity: 1; transform: rotateY(90deg) translateZ(75px) }
     90% {  opacity: 1; transform: rotateY(90deg) translateZ(150px) }
     100% {  opacity: 1; transform: rotateY(90deg) translateZ(150px) }
 }

The above code works. it rotates and spins but the faces are not close enough to look like a cube. how can i fix this.
could someone help me with this. thanks.
I am not knowing how to add the animations to the cube faces. and the cube should like in image below.
Comment: So you just want to make it look likes a cube rather than plate that are not connected?
Answer: In your code change the height and width of .single-box to 150px to match make a box, then to compensate the changes in the animation also change the height and width of .cube-wrap to the same value of .single-box.
So you get something like this

.wrapper{
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%,-50%);
 }
 .cube-wrap {
     width: 130px;
     height: 130px;
     -webkit-perspective: 2000px;
     -webkit-perspective-origin: 50% -500px;
 }
 .single-box {
     background-size: cover;
     display: block;
     position: absolute;
     width: 130px;
     height: 130px;
     background-color: #60c2ef;
    -webkit-transform: rotateY(45deg) translateZ(-200px) rotateX(15deg);
    -webkit-transform-origin: 50% 50% 0;
 }
 .box {
     -webkit-transform-style: preserve-3d;
     -webkit-animation: rotate 1.5s infinite ease;
 }
 .side-front {
     animation: side-front-animation 3s ease infinite;
     animation-delay: 100ms;
     transform: rotateY(0deg) translateZ(300px);
     animation-fill-mode: forwards;
     transform-origin: 50% 50%;
     background-color: #007dc5;
     -webkit-transform: translateZ(20px);
 }
 .side-back {
     animation: side-back-animation 3s ease infinite;
     animation-delay: 100ms;
     transform: rotateY(-180deg) translateZ(150px);
     animation-fill-mode: forwards;
     transform-origin: 50% 50%;
     background-color: #007dc5;
     border: #ffffff;
     -webkit-transform: rotateY(180deg) translateZ(20px);
 }
 .side-top {
     animation: side-top-animation 3s ease infinite;
     animation-delay: 0;
     transform: rotateX(90deg) translateZ(150px);
     animation-fill-mode: forwards;
     transform-origin: 50% 50%;
     background-color: #007dc5;
     -webkit-transform: rotateX(90deg) translateZ(20px);
 }
 .side-bottom {
     animation: side-bottom-animation 3s ease infinite;
     animation-delay: 0;
     transform: rotateX(-90deg) translateZ(150px);
     animation-fill-mode: forwards;
     transform-origin: 50% 50%;
     background-color: #007dc5;
     -webkit-transform: rotateX(-90deg) translateZ(20px);
 }
 .side-left {
     animation: side-left-animation 3s ease infinite;
     animation-delay: 100ms;
     transform: rotateY(-90deg) translateZ(150px);
     animation-fill-mode: forwards;
     transform-origin: 50% 50%;
     background-color: #007dc5;
     -webkit-transform: rotateY(-90deg) translateZ(20px);
 }
 .side-right {
     animation: side-right-animation 3s ease infinite;
     animation-delay: 100ms;
     transform: rotateY(90deg) translateZ(150px);
     animation-fill-mode: forwards;
     transform-origin: 50% 50%;
     background-color: #007dc5;
     -webkit-transform: rotateY(90deg) translateZ(20px);
 }

 @-webkit-keyframes rotate {
     0% { -webkit-transform: rotateY(0); }
     100% { -webkit-transform: rotateY(360deg); }
 }

 @-webkit-keyframes side-top-animation {
     0% { opacity: 1; transform: rotateX(90deg) translateZ(150px)}
     20% { opacity: 1; transform: rotateX(90deg) translateZ(75px)}
     70% {  opacity: 1; transform: rotateX(90deg) translateZ(75px) }
     90% {  opacity: 1; transform: rotateX(90deg) translateZ(150px) }
     100% {  opacity: 1; transform: rotateX(90deg) translateZ(150px) }
 }

 @-webkit-keyframes side-bottom-animation {
     0% { opacity: 1; transform: rotateX(-90deg) translateZ(150px)}
     20% { opacity: 1; transform: rotateX(-90deg) translateZ(75px)}
     70% {  opacity: 1; transform: rotateX(-90deg) translateZ(75px) }
     90% {  opacity: 1; transform: rotateX(-90deg) translateZ(150px) }
     100% {  opacity: 1; transform: rotateX(-90deg) translateZ(150px) }
 }

 @-webkit-keyframes side-front-animation {
     0% { opacity: 1; transform: rotateY(0deg) translateZ(150px)}
     20% { opacity: 1; transform: rotateY(0deg) translateZ(75px)}
     70% {  opacity: 1; transform: rotateY(0deg) translateZ(75px) }
     90% {  opacity: 1; transform: rotateY(0deg) translateZ(150px) }
     100% {  opacity: 1; transform: rotateY(0deg) translateZ(150px) }
 }
 @-webkit-keyframes side-back-animation {
     0% { opacity: 1; transform: rotateY(-180deg) translateZ(150px)}
     20% { opacity: 1; transform: rotateY(-180deg) translateZ(75px)}
     70% {  opacity: 1; transform: rotateY(-180deg) translateZ(75px) }
     90% {  opacity: 1; transform: rotateY(-180deg) translateZ(150px) }
     100% {  opacity: 1; transform: rotateY(-180deg) translateZ(150px) }
 }

 @-webkit-keyframes side-left-animation {
     0% { opacity: 1; transform: rotateY(-90deg) translateZ(150px)}
     20% { opacity: 1; transform: rotateY(-90deg) translateZ(75px)}
     70% {  opacity: 1; transform: rotateY(-90deg) translateZ(75px) }
     90% {  opacity: 1; transform: rotateY(-90deg) translateZ(150px) }
     100% {  opacity: 1; transform: rotateY(-90deg) translateZ(150px) }
 }
 @-webkit-keyframes side-right-animation {
     0% { opacity: 1; transform: rotateY(90deg) translateZ(150px)}
     20% { opacity: 1; transform: rotateY(90deg) translateZ(75px)}
     70% {  opacity: 1; transform: rotateY(90deg) translateZ(75px) }
     90% {  opacity: 1; transform: rotateY(90deg) translateZ(150px) }
     100% {  opacity: 1; transform: rotateY(90deg) translateZ(150px) }
 }

Comment: thanks for the answer the animation is exactly what i needed. but the cube should be like in the question that i have updated. thanks.


Display Password Validation Rules in Registration form before Submitting

Question: I'm new to Laravel and I just installed breeze on my project.
Everything works very well with breeze authentication and how it displays errors on sign up form after clicking the submit button.
But I would like the users to see what are the password rules (Like minimum length and so on) even before submitting.
Is it Possible?! If yes, then how?!
Laravel v9.38.0 (PHP v8.1.6)
Comment: you can read https://tallpad.com/series/inertiajs-laravel-misc/lessons/prevalidate-forms-in-inertiajs-and-laravel-applications
Comment: I guess you could "simply" edit the available auth components/views and add that information
Comment: There are at least a hall a dozen ways to accomplish this. As @brombeer stated, you could put the requirements on the page, under the password field, next to it, above it, in a help pop-up and so on. Alternatively, you could use JS (jQuery, Formvalidator, etc.) or Laravel Livewire, just depends on which way you want to implement it.
Answer: You can achieve that in javascript.
You can also do real-time validation with Livewire. If you only use it for the password real-time check, you better go with some handmade JS.
Livewire doc: https://laravel-livewire.com/docs/2.x/input-validation#real-time-validation


Better Method of Solving Certain Differential Equations than Eigenvalues and Eigenvectors

Question: I have been told that there is a much better method to solving differential equations than with eigenvalues and eigenvectors. However, unfortunately I was not explained this method. Can anyone present methods at which, generally, are much better than taking the eigenvalue/eigenvector route? I presume this method(s) are unorthodox, thus not well known. When I say "better" I am speaking in regards to computational complexity and efficiency. When providing answer, it would be helpful to provide a solution to an DE using both eigenvalue/eigenvector method and proposed method.
Comment: Solution to linear ODE with constant coefficient matrix is givens by matrix exponential. There are much better methods to compute matrix exponential than Jordan decomposition like scaling and squaring with Pade approximation
Answer: If you are willing to learn linear algebra, assuming "better" is more rigorous you could learn how to put matrices into Jordan canonical form and exponentiate them.
Comment: when I state "better" I am meaning more efficient in time and complexity.


Amanda/Zmanda backup-recovery Local server

Question: I am trying to recover some files from a tape on Linux, that were placed on there through an amdump. The problem is in order to use amrecover you have to set up the server. Which I do not really know how to do. Is there a walk around? or perhaps an easy way to do this on one machine. When I attempt to use amrecover I get
<code>amrecover>listhost
</code>
It says their are no hosts.I cannot sign on to a host thus cannot use am-recover on my tape.
Answer: Well just in case someone had a similar problem, just use amrestore. I know you wont be able to pick and choose the files but it works fine.
Answer: I know this is an old post, but just in case if anyone is looking for instructions on how to use "amrestore", refer the below steps.
Amrestore is a type of Bare Metal Recovery, which means it will restore all the data in the tape. So you will not have an option to select what you want to restore.
The first step is to Load the tape you want to restore from, in the tape drive. This can be done using the mtx command.
mtx -f /dev/sg10 load 4 0
In this case, sg10 is the changer library, 4 is the slot in which the tape is stored and 0 is the Tape drive number.
If you are using a single tape drive instead of a changer, you can directly proceed to the next step.
The next step is to run the amrestore command against the tape drive.
amrestore -r /dev/nst0 localhost (hostname is optional, nst0 stands for drive 0)
Running this command will give a file with .RAW format.
The filename will look something like this.
hostname.dle_name.date_time.file_number.RAW
Run the amrestore command once again on the .RAW file considering it as a holding file.
amrestore --holding hostname.dle_name.date_time.file_number.RAW
The output of this command will be a tar file (hostname.dle_name.date_time.file_number) which can be extracted to get the files restored
tar -xvf hostname.dle_name.date_time.file_number
Hope this helps.
Answer: I think you can refer the below link to know how to restore data in Amanda.
https://wiki.zmanda.com/index.php/How_To:Recover_Data


Exposed Filter Results Displaying in Nested DIVs (using view-dom-id-)

Question: I am trying to create a page that displays a bunch of resources with a filter to allow the end-user to sort the resources by type.  I am using the following versions:

Drupal 7.28
Views 7.x-3.8
Semantic Views 7.x-1.0-alpha1
Bootstrap 3

VIEWS SETTING:

Format: Semantic Views
Show: Semantic Views: Fields
Filter Criteria: Content: Resource Type (exposed)
Exposed form in block: Yes
Exposed form style: Basic
Use AJAX: Yes

The functionality works and the results are displayed based on what's selected in the resource type drop-down filter. However, the results are displaying in nested divs each time the form gets submitted and I can't figure out why. :(
SOURCE CODE BEFORE SUBMISSION

            [script for the $rows]

SOURCE CODE AFTER 1st SUBMISSION

                   [script for the $rows]

SOURCE CODE AFTER 2nd SUBMISSION

                        [script for the $rows]

To theme the exposed filter as a block, I did the following:
copied the 'views-exposed-form.tpl.php' file in sites/all/modules/views/theme and pasted it in my theme directory and renamed accordingly (views-exposed-form--[view name].tpl.php). I did not edit the script in the template.  (My reference: http://timonweb.com/how-display-views-exposed-filter-block-and-theme-it)
Then in my views-view--[view name].tpl.php, I added the following script:
<?php if ($rows): ?>

        <div class="view-dom-id-<?php print $dom_id; ?>">

                <?php print $rows; ?>

<?php elseif ($empty): ?>

    <?php print $empty; ?>

<?php endif; ?>

I don't really understand what view-dom-id- does even after reading a bunch of articles...but I added in as a div after reading the following post: https://www.drupal.org/node/690748.  If I don't have it in the views template, then the filter doesn't work.
DEFAULT SCRIPT IN views-exposed-form--[view name].tpl.php
<?php if (!empty($q)): ?>
  <?php
   // This ensures that, if clean URLs are off, the 'q' is added first so that
   // it shows up first in the URL.
    print $q;
 ?>
<?php endif; ?>

     <?php foreach ($widgets as $id => $widget): ?>
      <div id="<?php print $widget->id; ?>-wrapper" class="views-exposed-widget views-widget-<?php print $id; ?>">
    <?php if (!empty($widget->label)): ?>
      <label for="<?php print $widget->id; ?>">
        <?php print $widget->label; ?>

    <?php endif; ?>
    <?php if (!empty($widget->operator)): ?>

        <?php print $widget->operator; ?>

    <?php endif; ?>

      <?php print $widget->widget; ?>

    <?php if (!empty($widget->description)): ?>

        <?php print $widget->description; ?>

    <?php endif; ?>

<?php endforeach; ?>
<?php if (!empty($sort_by)): ?>

    <?php print $sort_by; ?>

    <?php print $sort_order; ?>

<?php endif; ?>
<?php if (!empty($items_per_page)): ?>

    <?php print $items_per_page; ?>

<?php endif; ?>
<?php if (!empty($offset)): ?>

    <?php print $offset; ?>

<?php endif; ?>

  <?php print $button; ?>

  <?php if (!empty($reset_button)): ?>

    <?php print $reset_button; ?>

  <?php endif; ?>

I've spent 2 days trying to debug, so any guidance would be greatly appreciated!!
Thank you for taking the time to read
Comment: Does it work OK with one of built-in themes and only repeat divs for your theme?
Comment: Hi Molot, Thank you for the speedy help!  I just tried this in the Bartik theme and YES, it does work okay in the built-in theme and the results are not displaying in nested divs. Hmm...
Answer: UPDATE: I realized my issue -- In my Views template, I needed to place my divs outside of the  :-p
Thank you, Molot, for leading me in the right direction!  My original thought was that it was an AJAX issue, but after the issue disappeared when I used a pre-built theme, I looked more into the template.php and my template files (views-view--[view name].tpl.php).  It works now with the following:

            <?php if ($rows): ?>

                <?php print $rows; ?>

            <?php elseif ($empty): ?>

                <?php print $empty; ?>

            <?php endif; ?>

Comment: Glad my pointer helped. I couldn't figure it out from your code (it was about midnight where I live), but maybe that's better? Now you know one debugging trick that often helps.
Comment: Oh wow, I can't express how grateful I am for you taking the time to answer my question so late in the day! I was looking at all sorts of posts that was taking me further away from the issue.  Thanks again for leading me in the right direction and for teaching me a debugging trick!


Dúvida na declaração de método

Question: Observem o seguinte código:
 class Program
{
    int marks;
    static int maxmarx = 50;
    void CalcularPorcentagem()
    {
        int porcento = (this.marks * 100) / Program.maxmarx;

        Console.WriteLine(porcento);

    }

Depois de testar dos dois jeitos a seguir, notei que o programa retorna o mesmo valor quando a classe é instanciada. Portanto, gostaria de saber qual a diferença entre usar:
     int porcento = (this.marks * 100) / Program.maxmarx;

ou
     int porcento = (this.marks * 100) / maxmarx;

Comment: Acredito que para este exemplo não há diferença, mas o primeiro modo te permite diferenciar o atributo de classe de uma variável local, caso haja conflito de nomes no escopo. Por exemplo, se neste método existir a variável local `int maxmarx = 1`, o primeiro modo funcionará perfeitamente, enquanto o segundo produzirá um resultado "inesperado".
Comment: Eu escreveria `var porcento = marks * 100 / maxmarx;`, se a variável fosse usada em outro lugar, senão, nem ela existiria.
Comment: Aqui sua resposta: https://pt.stackoverflow.com/questions/54012/qual-a-fun%C3%A7%C3%A3o-de-um-m%C3%A9todo-est%C3%A1tico
Comment: A segunda resposta trata especificamente do assunto abordado nesta pergunta. Se achar que não, me avise.
Comment: Então, Anderson, ela faz menção ao valor declarado na variável local da classe Program. Caso eu precise referenciar o valor 50, determinado na criação da classe, eu utilizo o Program. Entretanto, se eu desejo utilizar um valor diferente de 50, eu devo chamá-la sem o Program., devido ao valor com o qual eu quero trabalhar ser diferente?
Answer: Você está dentro da classe Program referenciando a variável estática maxmarx; ou seja, dentro da classe ele enxerga a variável sem precisar referenciar a classe.
Então tanto Program.maxmarx quanto maxmarx têm o mesmo resultado.
Answer:
Portanto, gostaria de saber qual a diferença entre usar

Da forma que está apresentado, dentro de um bloco de código (método) onde não se tem nenhuma outra variável chamada maxmarx, nenhuma.
Agora, se tivesse uma variável local chamada maxmarx, aí sim, para referenciar a variável estática é obrigatório referenciar utilizando o nome da classe (Program.maxmarx).

Fora desse cenário (variável local com o mesmo nome), referenciar da forma aprensetada ou não fica a critério do desenvolvedor/time de desenvolvimento.
É a mesma discussão entre referenciar uma varivável de instância com this ou não. Por exemplo: this.marks * 100 ou marks * 100? O resultado é o mesmo.
Normalmente, esse "tipo de codagem" é abordada/discutida no inicio do projeto pelo time de desenvolvimento, para que todos desenvolvedores trabalhem da mesma maneira.
Comment: O correto é "não se tem" no lugar de "não tem-se", pois o "não" é classificado como fator de próclise e possui força atrativa sobre o pronome. :x
Comment: @AndersonCarlosWoss caraca, valeu. Vou arrumar :P

Dúvida na declaração de método


Bernoulli Numbers and radius of convergence

Question: consider the function $f(x)=\frac{x}{e^x-1}$.
Since the function $\frac{1}{f(x)}=\frac{e^x-1}{x}=\sum\limits_{k=0}^{\infty} \frac{x^k}{(k+1)!}$ has a taylor expansion with $\frac{1}{f(0)}\neq 0$ we know that $f(x)$ must have a taylor expansion in some neighborhood of 0, i.e. we can write
$f(x)=\sum\limits_{k=0}^{\infty} B_n \frac{x^n}{n!}$ in some neighborhood $(-\delta, \delta)$ with $\delta>0$.
In Wikipedia and other sources, I've read the radius of convergence of the series $\sum\limits_{k=0}^{\infty} B_n \frac{x^n}{n!}$ is actually $(-2\pi,2\pi)$. Is that true and how con one prove it? Further, does the Taylor series converge for all $\vert x \vert< 2\pi$ against f(x) ? How can I see it?
I hope someone can explain it to me.
Best regards
Answer: Although it is possible to get distracted by connections to subtler things, observe that $f(z)=z/(e^z-1)$ is holomorphic on $|z|<2\pi$, has simple poles at $\pm 2\pi i$, and is holomorphic on $\{|z|<4\pi\}$ with $\pm 2\pi i$ removed. A power series converges on the largest disk in which a function is holomorphic, so the radius of convergence is $2\pi$.
Comment: In other words (I agree with them) the best way to study real power series is to use complex power series.
Comment: @GeraldEdgar, indeed! The power series of the function $f(z)=1/(1+z^2)$ at $0$ powerfully illustrates this point, to my mind: the function is well-behaved on $\mathbb R$, (rhetorically) why should the power series fail to converge beyond $\pm 1$? :) Well, because its behavior in the complex plane is a genuine phenomenon that constrains its behavior on the real line, etc.
Answer: Try computing the radius of convergence $r = \limsup \sqrt[n]{B_n}$.  It is related to the Riemann Zeta function.
$$ \frac{B_n}{2n!} = \zeta(2n)\frac{2 }{(2\pi)^{2n}}$$
with $\zeta(2n) \to 1$ and $2^{1/n} \to 1$.
I wonder then, how to write the analytic continuation, since $f(x)$ is clearly defined outside of $|x| < 2\pi$.
Comment: I don't understand the last comment: the analytic continuation is simply the function $x/(e^x-1)$ we started with (well, analytic but for simple poles at nonzero multiples of $2\pi i$).
Comment: @NoamD.Elkies Can you give me a working infinite series when $x = 3\pi$ ?
Comment: Not an elementary closed form, but for each $n$ you can compute the $(x-3\pi)^n/n!$ coefficient by differentiating $x/(e^x-1)$ $n$ times and substituting $x=3\pi$.
Comment: @NoamD.Elkies Sorry that wasn't fair.  You could expand around $x = n \in \mathbb{Z}[i]$ for $|n| > 2\pi > 6$.  There could be a "transition map" between the series for various $n$.


Cox regression different results with different combinations of variables

Question: I need help understanding how to use cox hazzard model to calculate risk of death in data from a cohort study.
I have a set of data on physical activity and I want to do a cox regression on mortality to calculate the risk of death from active time.
I have months from t1 as time, death as status and a selection of numeric data on physical activity.
One set with minutes of low intensity activity
One set with minutes of moderate to high intensity activity
One set with minutes of sedentary time
I also a set of dichotomous data on wether or not the participants fulfilled the recommendations for daily physical.
If I run all of these together as predictor variables, I get different Exp(b) values compared to running only a selection.
Should I run each variable in separate tests and put them together in a table?
Answer: Certainly you get different results from different models, that's to be expected.
Which variables you should include is a question of model building and variable selection, which have been discussed here many times. There are various schools of thought. There are automated methods such as backwards and forwards, but these are not good and are disdained by most of the people on this list. You can use better automated methods such as LASSO.
My own view is that you should include variables not based strictly on their statistical significance, AIC values or whatever but on what makes sense for your situation.
If you include all three types of active (high, low, sedentary) then you will be looking at the relationship between each of these and mortality after controlling for the others. This answers questions such as "for given amounts of high and low intensity activity, what is the relationship between mortality and amount of sedentary activity"?
You might even want to look at interactions among these variables, since the relationship between (say) sedentary activity and mortality might be different at different levels of high intensity activity.
It's a complex process. You might want to hire a consultant to help.
Answer: Any regression model can suffer from omitted-variable bias if a predictor related to outcome is not included in the model. As noted for example on this page, the coefficients for the included predictors can then be biased away from their true values. This occurs in linear regression only when the omitted predictors are correlated with the included predictors, but in logistic or Cox regressions it occurs regardless of such correlations among the predictors.
Thus your differences in Cox regression coefficients between a combined, multiple-regression, model and the single-predictor models is to be expected. The inherent omitted-variable bias in Cox regressions means that the coefficients from the single-predictor models are unlikely to represent the predictors' true relationships with outcome.
For a Cox model the best strategy is to include as many outcome-related predictors in a multiple-regression model as is reasonable without overfitting, given the scale of your study. To avoid overfitting, a usual rule of thumb is that 10-20 events (deaths in your study) are needed for each predictor that you evaluate in the model.
As @Peter Flom notes in his answer, in your study you might need to examine interactions among your predictors; if interaction terms are related to outcome, omitting them also risks omitted-variable bias in coefficient estimates. (In terms of avoiding overfitting, each interaction term adds an effective predictor with an associated requirement for more events.)  So I agree strongly with his recommendation to work with a statistical consultant. If the study is important enough to undertake in the first place, it should be important enough to analyze the results in the way most likely to provide a clean answer to your underlying questions.


About multi threading

Question: How to kill the thread?
.....
How to restart them again in multi threading?
Comment: Best way to kill a thread is by drowning. Threads can't swim.
Comment: The actual page that explains the dangers of thread primitives is http://java.sun.com/javase/6/docs/technotes/guides/concurrency/threadPrimitiveDeprecation.html
Comment: There is Thread.stop(): http://java.sun.com/javase/6/docs/api/java/lang/Thread.html#stop() , but it is not recommended that you do that: http://java.sun.com/javase/6/docs/technotes/guides/concurrency/threadPrimitiveDeprecation.html
Comment: @chetans, you should rewrite this so it's more specific and makes more sense.
Comment: What do you mean by 'restart' a thread?
Answer: Since your post is tagged "Java," I have a good idea of what you are saying. Let's say you start a thread by doing:
Thread foo = new Thread(someRunnable);
foo.start();

Now that destroy and friends are deprecated, you need a way to kill the thread. Luckily for you, there has always been the concept of "interrupts." Simply change your runnable so that, on interrupt, it exits. Then call the thread's interrupt method.
foo.interrupt();

If you wrote your Runnable to handle this correctly, it will stop whatever it is doing and terminate.
Answer: Thread.stop() kills a thread, but you definitely don't want to do this (see the API documentation for an explanation why).  Thread.interrupt() sends an asynchronous notification to a thread, so that it can shut itself gracefully.
For a comprehensive text on Java multithreading, I recommend B. Goetz, Java Concurrency in Practice, Addison-Wesley Professional.
Comment: Thread.stop() is kind of like putting a car traveling at 60mph in park to stop it...definitely stops it, but you're going to leave a sad, sad trail of twisted metal along the way and your car won't ever quite be the same ;-)
Comment: also, Thread.interrupt wont always interrupt a thread waiting on IO. if youre serious about designing for interruption you need a way to forcibly close any IO streams your target thread might be waiting on
Answer: The preferred way for a Thread to die is for the execution of the run method to go to completion:
Thread t = new Thread(new Runnable() {
  public void run() {
    // Do something...

    // Thread will end gracefully here.
  }
}

Once a thread gracefully dies in the example above, the Thread cannot be restarted. (Trying to call Thread.start on a thread that has already been started will cause an IllegalThreadStateException.)
In that case, one can make another instance of the thread and call start on that.
Probably a good place to get more information on threading would be Lesson: Concurrency from The Java Tutorials.
Answer: i wrap my worker threads up in their own class and use a terminated property to kill the thread proc loop.
sorry i dont have a java version to hand right now but you should get the idea from this
http://pastie.org/880516
using System.Threading;

namespace LoaderDemo
{
    class ParserThread
    {
        private bool m_Terminated;
        private AutoResetEvent m_Signal;
        private string m_FilePath;
        ...

        public ParserThread(AutoResetEvent signal, string filePath)
        {
            m_Signal = signal;
            m_FilePath = filePath;

            Thread thrd = new Thread(this.ThreadProc);
            thrd.Start();
        }

        public bool Terminated {
            set { m_Terminated = value; }
        }

        private Guid Parse(ref string s)
        {
            //parse the string s and return a populated Guid object
            Guid g = new Guid();

            // do stuff...

            return g;
        }

        private void ThreadProc()
        {
            TextReader tr = null;
            string line = null;
            int lines = 0;

            try
            {
                tr = new StreamReader(m_FilePath);
                while ((line = tr.ReadLine()) != null)
                {
                    if (m_Terminated) break;

                    Guid g = Parse(ref line);
                    m_GuidList.Add(g);
                    lines++;
                }

                m_Signal.Set(); //signal done

            }
            finally
            {
                tr.Close();
            }

        }

    }
}

Answer: The best way to kill a thread is to set up a flag for the thread to watch. Program the thread to exit when it sees the flag is set to true. There's no way to restart a killed thread.
Comment: The best way to kill a thread is to call Thread.interrupt() and have the thread also monitor its interrupt status periodically. Adding yet another boolean is entirely redundant.
Comment: In addition to what EJP said, the hand-rolled flag doesn't play well with executors.
Answer: If you want to start, stop, restart threads at will, maybe using the Java 5 concurrency package would be a good idea. You can have an Executor that will do a bit of work, and when you need that bit of work to be done again, you can just re-schedule it to be done in the executor.
Answer: Regarding your first query on killing thread:
You can find more details about topic in below SE questions:
How to properly stop the Thread in Java?
How can I kill a thread? without using stop();
How to start/stop/restart a thread in Java?
Regarding your second query of re-starting thread, it's not possible in java.
You can find below details in documentation page

public void start()
Causes this thread to begin execution; the Java Virtual Machine calls the run method of this thread.
The result is that two threads are running concurrently: the current thread (which returns from the call to the start method) and the other thread (which executes its run method).

It is never legal to start a thread more than once. In particular, a thread may not be restarted once it has completed execution.
Instead of plain Threads, you can use advanced concurrent API for thread life cycle management. Have a look at this post for ExecutorService details :
How to properly use Java Executor?

About multi threading