Webform: Hide the "add more" button

Question: I would like to get rid of the ajax "add more items" button at the bottom of a multiple elements form item.
The D8 webform I'm building has a custom composite element with multiple values allowed. The table form display has nice + and – buttons in each row. The "Add x more items" element below the table is not needed.
In the advanced tab, under "Multiple settings", there is only an option to hide the +/– buttons, not the "Add x more items" element.
Additional information:
Webform module version: 8.x-5.0-rc7
YAML Source (excerpt):
   fieldset_teilnehmer:
    '#type': fieldset
    '#title': Teilnehmer
    teilnehmer:
      '#type': custom_composite
      '#title': Teilnehmer
      '#required': true
      '#required_error': 'Bitte tragen Sie die Teilnehmer ein.'
      '#multiple__label': Teilnehmer
      '#multiple__labels': Teilnehmer
      '#multiple__min_items': '5'
      '#multiple__empty_items': '5'
      '#multiple__sorting': false
      '#element':
        teilnehmer_name:
          '#type': textfield
          '#title': Name
        teilnehmer_alter:
          '#type': select
          '#options':
            18: ≥18
            17: 17
            16: 16
            15: 15
            14: 14
            13: 13
            12: 12
            11: 11
            10: 10
            9: 9
            8: 8
            7: 7
            6: 6
            5: 5
            4: 4
            3: 3
            2: 2
            1: 1
            0: 0
          '#title': Alter

Comment: You can always hide it with css !!
Comment: Yes, CSS is something I will consider – looking at the code, I will have to make both `#edit-fieldname-add-submit` and `.form-item-fieldname-add-more-items` invisible.
Answer: If you set the
"Minimum amount of items" and
"Number of empty items" to the same number the add more won't appear.
Here is a screenshot

Here is the YAML source for basic multiple text field
textfield:
  '#type': textfield
  '#title': textfield
  '#multiple': 5
  '#multiple__min_items': '5'
  '#multiple__empty_items': '5'

Here is the YAML source for multiple custom composite
custom_composite:
  '#type': custom_composite
  '#title': custom_composite
  '#multiple': 5
  '#multiple__min_items': '5'
  '#multiple__empty_items': '5'
  '#multiple__sorting': false
  '#multiple__operations': false
  '#element':
    textfield:
      '#type': textfield
      '#title': textfield
    select:
      '#type': select
      '#options': days
      '#title': select

Comment: The key trick is '#multiple', '#multiple__min_items', and '#multiple__empty_items' all have to be same value.
Comment: Okay, that is not currently supported. You should use CSS. On mobile, the 'Add more' is needed because the add/remove buttons are hidden.
Comment: Unfortunately, this does not work for. I've tried your example, with various equal values for min_items and empty_items.
Comment: What version of the Webform module are you using?

Please post an example of the generated YAML.
Comment: Sure. See edits above.
Comment: '#multiple: 5' means there is a fixed number of five elements, therefore webform will not display the add more button, and not display the + and – buttons next to each row. But that's not what I'm looking for, as I need an arbitrary number of elements (unlimited).
Comment: OK, thanks. I think, this issue is probably not specific to webforms, but to Drupal's Form API.

Webform: Hide the "add more" button


Bootstrap - hook in image gallery

Question: So I've been working with this site (http://cee.cgreen.ca/index.php?page=designs) (this is a prototype), but bootstrap always seems to be wonky. There always some hook that catches the products into one for its own row etc. I can't seem to figure it out. ;-;
    // HTML

 //twitter span

 //contained image

/** CSS **/
#products {
    text-align: center;
    color: #999999;
    text-decoration: none;
    font: 12px "proxima-nova";
    margin-left:auto;
    margin-right:auto;
    max-width:100%;
}

.product-grid{
  color: #666666;
  margin:10px;
}

.generated-height .product-grid-item {
  width: 177px;
  position: absolute;

  bottom: 0;

  }

.product-grid img{
  display: block;
  margin: 0 auto;
  }

.product-grid a{
  text-decoration: none;
  display: block;
  color: #333333;

  }

.product-grid .product-link{
  display: block;
  position: relative;
  z-index: 1;
  text-decoration: none;
  margin: 0;
  min-height: 50px;
  /* for ie6: */
  width: 100%;
  }

.product-grid .product-link .over{

    position: Absolute;
    top: 0;
    left: 0;
    display: none;
}

.product-photo{
  max-width: 100%;
}
.ie6 .product-grid{ overflow: hidden; }

.span4 {
  width: 300px;
}

.row-fluid .span4 {
  width: 31.91489%;
  *width: 31.8617%;
}

Comment: Please state what exactly the problem is what is the desired result.
Comment: I think you'll want to load the `bootstrap-responsive.css` as well. And you need to close your rows after you reach a total span of 12 (where you put the comment `row 2`in your html)
Comment: The bootstrap is loaded (responsive.css) via the index.php page where all the spans are there and such. I have a picture of the problem. It like's the rows are completely fine and there's a malfunction every five rows. Ex:
http://img541.imageshack.us/img541/9850/iu7i.jpg

I tried the 12 row thing. Didn't work!
Answer: For the product section, you have 6 span4s in each row.
Spans should add up to 12 in each row, so change this to 3 span4s for each row , and do away with your custom CSS
.span4 {
 width: 300px;
}

Bootstrap - hook in image gallery


Deviceinfo without scanning

Question: Can we know the bdaddress and rssi of all nearby ble devices without continuous lescanning? As the continuous lescan will consume more power and also we would not be able to properly make connection to a device while active scanning is going on in background.
The lescan background process also gets killed when we are disconnected from the connected state with any ble device
Also with how many peripherals can a central device be connected to simultanoeusly with bluez-4.101 stack?
Answer: Yes you are right you cannot make connection while you are scanning for Low Energy devices and number of devices that can be connected to the central device is entirely dependent on the Software Stack you are using for BLE.
Like in CC2540  you can connect 3 devices at a time.
For RSSI and bluetooth address you refer function le_advertising_report according to bluez-4.101 stack.

Deviceinfo without scanning


NSString to NSDate and then changing the format

Question: I thought I had the "hard" part done but that doesn't seem to be the case.  I retrieve a date from an RSS feed that I would like to convert to a NSDate and then change it to the simple format (MM/DD/YYYY).  The date comes in this format on the RSS feed:
Thu, 1 Nov 2012 17:41:56 CST
I have converted it to an NSDate successfully.
NSDateFormatter *df = [[NSDateFormatter alloc] init];
[df setDateFormat:@"E, d MMM yyyy HH:mm:ss zzz"];
NSDate *date = [[NSDate alloc] init];
//[df setDateStyle:NSDateFormatterMediumStyle]; Using these seems to change what it expects from the string I guess?
//[df setTimeStyle:NSDateFormatterMediumStyle];
date = [df dateFromString:string];
[self.tempItem setPubDate:[df dateFromString:string]];
NSLog(@"%@", [df dateFromString:string]);

So I get my date just fine, but like I said before I want to just convert it to a simple date.
When I use setDateStyle I end up with null values.  When I don't use it, I get correct dates, just not in the format I want it to end up being.
Answer:
just not in the format I want it to end up being.

Because NSLog() doesn't know about the format - how would it? NSDate doesn't have any built-in "format". You have to obtain a string from the date object by using NSDateFormatter once again. Basically the workflow you'll have to use is roughly:

retrieve an NSString from the RSS feed
Create a date formatter
Set its format according to the format of the string
Get an NSDate object from the date formatter
Re-set the format of the NSDateFormatter to the format you desire
Obtain a properly formatted NSString using the date and the date formatter objects.
Comment: Thank you. I did not originally understand that the formatting did not actually change the NSDate object but how it appears when going out to strings and such.  Since this was going on a tableview anyways I now know I can wait all the way until I set the label text to format it how I want.
Answer: Just create another NSDateFormatter to convert NSDate to NSString

NSDateFormatter *dfSimple = [[NSDateFormatter alloc] init];
[dfSimple setTimeStyle:NSDateFormatterNoStyle];
[dfSimple setDateStyle:NSDateFormatterMediumStyle];
NSLog(@"%@", [dfSimple stringFromDate: date]);

It is better to create 2 NSDateFormatter objects in this case


Example of a REST service implemented in ASP.NET MVC

Question: Is there a good sample of an REST service implemented in ASP.NET MVC that demonstrates the best practices and easy to understand for a beginner?
Comment: I tried to rewrote the body of the question, but I cannot really narrow it down. I need some sort of reference implementation of a rest service in asp.net mvc
Comment: You're question is very broad. Try narrowing it down by telling us what you've tried so far (and if you haven't tried anything yet, I would suggest trying to code something first and then coming back and asking a question).
Comment: Have you looked at openrasta for ideas?
Answer: Although your question is not really clear to me it seems you want some sort of REST based API?
Here's an example returning json or xml: http://omaralzabir.com/create_rest_api_using_asp_net_mvc_that_speaks_both_json_and_plain_xml/
Comment: @vdcrijsen Thanks for the link. It seems to be just what I wanted.
Answer: http://www.beletsky.net/2011/01/implementation-of-rest-service-with.html
https://github.com/alexanderbeletsky/rest.mvc.example
I think It will help you.


React DatePicker and Logging to Console

Question: I have a form in which I am using react-datePicker to allow a user to select their birthday. The component sits inside of a form. However, when my form is submitted I have not been able to log the selected birthdate to the console.
Here is some of the form code with the DatePicker component:
const Register = () => {
    const [modalIsOpen, setModalIsOpen] = useState (true)
    const { register, handleSubmit, errors } = useForm ();
    const [date, setDate] = useState(new Date());
    const handleCalendarClose = () => console.log(date);
    const handleCalendarOpen = () => console.log("Calendar opened");
    const onSubmit = (data) => console.log(data);

    const [passwordShown, setPasswordShown] = useState(false);
    const togglePasswordVisiblity = () => {
        setPasswordShown(passwordShown ? false : true);
      };

    return(
        <Modal isOpen={modalIsOpen} onRequestClose={() => setModalIsOpen(false)} className='createBorder'>
<form>

First name:

                <input name='firstName' ref={register({required: true})} className='inputs' autoComplete='off'></input>

This information will display on your profile

                {errors.firstName && This field is required}

Last name:

                <input name='lastName' ref={register({required: true})} className='inputs' autoComplete='off'></input>

This information will display on your profile

                {errors.lastName && This field is required}

Birthdate:

                {/* datepicker is not logged to the console because it is not an input field it is a component, how can we wrap the component */}
                    <DatePicker
                        ref={register({required: true})}
                        dateFormat="MM/dd/yyyy"
                        selected={date}
                        name='Birthday'
                        onChange={date => setDate(date)}
                        onCalendarClose={handleCalendarClose}
                        onCalendarOpen={handleCalendarOpen}
                        />

We'll use this information when considering what films you are qualified to test

                {errors.Birthdate && This field is required}
</form>

                Sign Up

</Modal>

Thank you in advanced
Answer: Whatever data that is not included in the from data you just simply add it to the data object while processing.
 const onSubmit = (data) => {data['birthdate']= date; console.log(data);}

React DatePicker and Logging to Console


Tabulator date formatting

Question: I am using a library called Tabulator, and one of the things it allows you to do is to edit the data while it is being pushed into the table.
Dates we use use long-date format and look something like this: 2018-07-24T04:00:00.000Z. I use formatter within the table to make it look like this : 2018-07-24. Which simply slices the string.
The problem is - when someone is trying to download pdf file it still shows the date in the long format - this needs to be fixed. I tried all the ways that Tabulators official website shows, and nothing work for me. I can't seem to figure out the proper way of doing it, perhaps someone here had some experience here and can share it with me? Just for reference formatter looks like this:
{
    title: "Due",
    field: "duedate",
    width: 80,
    formatter: function (cell, formatterParams) {
        var toRet = 'No Date';
        if (cell.getValue() != null) toRet = cell.getValue().slice(0, 10)
        return toRet;
    }
}

Essentially I need the same logic - get the cell value and slice it when downloading, or perhaps do it while data is getting pushed into the table and omit formatters all together.
P.S I understand I can just iterate through array before pushing the data and slice required fields, but was looking for more elegant solution.
Answer: As long as your are using version 3.4 or higher you can use a download accessor to do that for you:
{
    title: "Due",
    field: "duedate",
    width: 80,
    accessorDownload : function (value, data, type, params, column) {
        var toRet = 'No Date';
        if (value != null) toRet = value.slice(0, 10)
        return toRet;
    }
}

It will transform the data as it is loaded into the download extension

Tabulator date formatting


Server "times out" after opening a file

Question: So I have a .Net based CMS site.
When clicking around everything works smoothly as expected.
BUT, after opening any media such as a pdf file or a image directly (e.g:  www.mysite.com/media/mydoc.pdf) any succeeding request times out or atleast takes forever. Up to 2 minutes.
Also note this only happens in Chrome. It seems to happen for a lot of people not only me and from different locations.
Comment: I have done some further investigation. If I remove the ASP.NET Session Id cookie AFTER accessing the static file, The site keeps running smoothly.
Answer: So I found the error.
We have placed the favicon in a img-folder. While this works fine when surfing to a page it renders a 404 when surfing static-files since chrome always looks for a favicon even when loading static files.
As described in the answer here: Session data lost in Chrome only
The 404 request somehow altered the session cookie.
By adding an extra favicon to the root of the site this case was solved.

Server "times out" after opening a file


Independent Variable vs. Dependent Variable in Statistics

Question: Following are the definitions of independent variable and dependent variable I found on the internet:

<1> In statistical modelling, the dependent variable is studied to see if and how much it varies as the independent variables vary.

<2> Independent Variable: variable that causes the variation.

<3> Dependent Variable: a variable whose variation is being studied.

Here in the table above, the YouTuber is interested to know what kind of people come to his "fantasy" restaurant: teens, young adults, and so on. And, kindly notice that the age groups are not meaningful, but rather arbitrary. Clearly, this isn't an experiment: I am not interested in any cause-effect. It's a survey. The Youtuber mentioned the "age group" as an independent variable and "the number of people who dined in his restaurant last week" as a dependent variable.
My question is for the same: in what way, is the number of people visited dependent on the age group? In other words, how to know which variable is dependent and which is independent in a survey like this?
Comment: (1) and (2) blatantly contradict each other.  Consider, for instance, a regression in which you want to estimate the amount of sunlight that was available to a plant crop based on measurements of the dry weights of samples of the plants.  According to (1), the amount of sunlight is the dependent variable, but according to (2), either the plants influenced the sun or else sunlight is also the independent variable!  The Internet (generically) is an unreliable source of good or clear information about statistical concepts, so beware.  Reading a basic book on regression might be worth your time.
Comment: Please visit https://stats.stackexchange.com/help/merging-accounts to merge your accounts.  There is no need to post your question multiple times under multiple accounts -- and it is confusing and disrespectful to those who see only one of the posts.
Answer: Your YouTuber is wrong, and "age group" is not an independent variable" here.
These terms come from experimental studies, where the independent variable is what's manipulated by the experimenter and the the dependant variable is the outcome that (hypothetically) changes as a result. They are also sometimes used in analogous non-experimental settings, where the independent variable is not controlled by the experimenter but varies for some other reason.
For instance, if these variables were "Age Group" and "Proportion of visitors ordering Coke", you then might treat age group as the independent variable and the proportion ordering Coke as dependent, in order to test the hypothesis that there is an effect of age on drinks orders.
Comment: "Kinds" of variables in that sense doesn't make sense for a survey. Age is just *a* variable. Binning it into groups and counting the values is just a way of summarising that variable.
Comment: If you like you could say that "Age Group" is a categorical variable and "Number of People" is a count variable, but that's not really what you're looking for here. Context is important.
Comment: So, all am I doing is summarizing the variable "age"? And, just for curiosity, is what kind of variables are: name and age, and how?
Comment: Sorry, I don't understand your second question, but the answer to your first question is yes.


How to make an HTML table (in a fixed-width div) adapt to the width of its cells instead of its container?

Question: I'd like to make to following table adapt its width to the cells, instead of its container:

            Group 1
            Group 2
            Group 3

            A
            B
            C
            D
            E
            F
            G
            H
            I
            J
            K
            L

The width of the container is narrower than the sum of the cell width. It is okay to show horizontal scroll bar here, but the table just can't be wider than its container. If I calculate the sum width for the colspan and the table, it can do the job, but what if the cells has non-px width, like "%" or "em"? Then static px calculation can't work.
Current effect is:

The expected effect would be the table's width exceeding the container div's width.
But setting width directly to the table also has problems: the width set for cells will be ignored. For example:

            Group 1
            Group 2
            Group 3

            A
            B
            C
            D
            E
            F
            G
            H
            I
            J
            K
            L

The effect is:

Note the 2nd cell (should be 200px) is as narrow as the 1st and 3rd one.
Anybody could shed some light on this issue? Thanks in advance.
Answer: add css:
th{
    min-width:50px; /*for instance*/
}
div{
    overflow-x:scroll;
}

and remove style='table-layout: fixed; width: 1px;' from the table
Comment: by the way, I'm not sure if the A B C is content, if so, don't use TH for table content. TH means table header, and is good for the group names, but the rest should then be TD. Just in case
Comment: It is the header part of a bigger table "widget", all of these are header cells.
Comment: please ignore the width:1px; that's some testing code. I pasted here by mistake.
Comment: Thanks for the advice. The min-width approach works in most browsers but fails in IE7. Maybe I need to talk to my boss to refuse supporting IE7...
Comment: Yea don't be bothered with IE7, the few that use IE7 are probably not even in your target audience
Answer: Would positioning the table absolutely be acceptible?

This works such that the div no longer contains the table horizontally.  But, of course, the div also no longer contains the table vertically.  You could work around this by giving the div height manually, though.
Comment: Manually setting height is also hard in my case because the table content changes all the time. But even setting to absolute it seems still can't work because the container has to be "position: relative;"
Answer: Merijn's answer works, tweaked slightly, for the fixed-width cells case:
Instead of specifying a global th min-width, specify it per cell like so:
A
B
C

At least this way, your individual width's are not ignored, giving you a table wider than the container, and with irregular width cells.
Comment: yes, if there's no better choice for IE7, I'll take this approach.


Change WooCommerce external product loop add to cart button to a "view more" linked to the product

Question: I'm trying to add a "View more" button to external products on wordpress to link to the product page instead of to the external link. This way users can get more details before doing the external click (in this case it is a link to a booking system, not an affiliate).
I was able to add some code and the view more button shows now but only on the category pages
example:
https://faceup-romanorte.com/tratamiento-categoria/valoraciones/
It doesn't show tho on my other pages where I add a block to show wordpress products using Elementor
e.g. see my main page www.faceup-romanorte.com
Products are visible and if you click on them you get to the details page, but it is a bit confusing for users (we can see this through hotjar)
This is the code I added
//Modify
add_filter( 'woocommerce_loop_add_to_cart_link', 'ts_replace_add_to_cart_button', 10, 2 );
function ts_replace_add_to_cart_button( $button, $product ) {
if (is_product_category() || is_shop()) {
$button_text = __("Ver más", "woocommerce");
$button_link = $product->get_permalink();
$button = '' . $button_text . '';
return $button;
}
}

But it seems to be somehow only activating it for category pages and not on all other pages. Can someone help with this?
Main page before adding code
Category page before adding the code
When I add the code, the button does change on the category page
Category page with modified code ("Ver más" means "View Details")
But it hides the button from the main page which is also not ideal
Main page when adding code - buttons disappear
Could anyone help with what I am missing here?
Answer: For external products, to change the loop add to cart button on archive pages with a "View more button linked to the single product, use the following:
add_filter( 'woocommerce_loop_add_to_cart_link', 'replace_external_product_loop_add_to_cart_link', 100, 3 );
function replace_external_product_loop_add_to_cart_link( $button, $product, $args ) {
    // Only for external products
    if ( $product->is_type('external') ) {
        $button = sprintf( '%s',
            esc_url( $product->get_permalink() ),
            esc_attr( 'button' ),
            isset( $args['attributes'] ) ? wc_implode_html_attributes( $args['attributes'] ) : '',
            esc_html__( 'View more' )
        );
    }
    return $button;
}

Code goes in functions.php file of your child theme (or in a plugin). Tested and works.
Comment: Thank you that does the trick. One question tho. My "physical" products which are not external links, are now not displaying any button. What would I need to add to the code to also have a "View more" button on those? You can see what I mean on www.faceup-romanorte.com in the section that says Gift Cards.

Also, buttons are not aligned. When I selected the elementor align button it does align them but then they are full width. Is there a way to align them to the bottom but not extend them to full widht?


Question about the weak topology

Question: Let $H$ be a Hilbert space. The definition of the weak topology $\tau_w$ is that it is the weakest topology on $H$ such that all $\varphi \in H^\ast$ are continuous. It is a fact stated e.g. on Wikipedia that
A net $x_\lambda $ converges to $x$ in the weak topology if and only if $\varphi(x_\lambda) \to \varphi (x)$ for all $\varphi \in H^\ast$.
It is clear to me that if $x_\lambda \to x$ then $\varphi (x_\lambda) \to \varphi (x)$ because $\varphi$ is continuous (or at least I believe that this is true by using the sequence definition of continuity of a function).
What is not clear to me is the other direction:

How to prove that if $\varphi(x_\lambda) \to \varphi (x)$ for all
  $\varphi \in H^\ast$ then $x_\lambda \to x$ in the weak topology?
Answer: First, we see that $x_\lambda$ converges weakly to $x$ iff $x_\lambda-x$ converges weakly to $0$. So, just deal with $x=0$ to simplify.
Sets of the form $B = \{ x | |\phi_k(x)| < \epsilon, k=1,...,n\}$ form a
base for weak neighbourhoods of $0$.
Suppose $\phi(x_\lambda) \to 0$ for all $\phi$. Let $W$ be a weak open set containing $0$.  There is some base element $B \subset W$ of the above form
for some $\phi_1,...,\phi_n$. Then
$ ( \phi_1(x_\lambda),...,\phi_n(x_\lambda) ) \to (0,...,0)$, hence
we have $x_\lambda \in B$ eventually. Hence $x_\lambda$ converges weakly to $0$.

Question about the weak topology


If $A$ is open, then $-A$ is also Open.

Question: Problem: Let $(X, ||\cdot||)$ be a normed vector space. Suppose $A \subseteq X $ is open.
And we have $-A=\{-a:a \in A\}$. Prove that $-A$ is open.
**Proof:**As $A$ is open,  $B(x,r) \subseteq A$.
Let $x \in -A$.
Then suppose $y \in B(x,r)$
$\implies d(x,y)<r$
$\implies ||x-y||<r$ $\implies ||-x-(-y)||<r$.
So, $-y \in B(-x,r). $ Thus $y\in -A$.
I Guess this is incorrect. Also, I would like to see a full proof of it.
Comment: There's an obvious isomorphism from $A$ to $-A$...
Answer: Let $x \in -A$, then by the definition of $-A$ we have that $-x \in A$. Since $A$ is open there exists an $r >0$ such that $B(-x,r) \subset A$. Again by the definition of $-A$ we have that
$$-B(-x,r) \subset -A.$$
All that's left to show is that $-B(-x,r) = B(x,r)$, to do this we just note that
$$|-x - y| < r \iff |x - (-y)| < r.$$
Hence $B(x,r) \subset A$ and we are done.
Comment: How do you know that $-B(-x,r) \subseteq -A$
Comment: Given any $y \in -B(-x,r)$, by definition $-y \in -(-B(-x,r)) = B(-x,r)$, then we have by set inclusion that $-y \in A$, therefore $y \in -A$. This shows that $-B(-x,r) \subset -A$.
Answer: I assume your normed vector space is over either the real field or the complex field. You have noted that $||\alpha w||$ = $|\alpha|\;||w||$, so that in particular
$||-w||$ = $||w||$.

Suppose $A \subseteq X $ is open.  And we have $-A=\{-a:a \in A\}$.
Prove that $-A$ is open.

As $A$ is open, we have that for any $x \in A,$ $B(x,r_x) \subseteq A$, where $r_x >0$.
Let $x \in -A$; we want to show that $x$ is interior. $-x \in A.$
Then suppose $y \in B(x,r_{-x})$
$\implies d(x,y)<r_{-x}$
$\implies ||x-y||<r_{-x}$ $\implies ||-x-(-y)||<r_{-x}$.
So, $-y \in B(-x,r_{-x})$. Thus $-y \in A$, and hence $y\in -A$.
Answer: Here's another approach, by general abstract nonsense:

Let $X$ be a topological space and $f:X\to X$ an homeomorphism. If $A\subset X$ has the same "topological properties" as $f(A)$. For our purposes, $A$ is open in $X$ iff $f(A)$ is open in $X$.
If $(X,\|\cdot\|)$ is a normed space (or more generally a topological vector space), then the map $f:X\to X$ defined by $x\mapsto -x$ is a homeomorphism.
Letting $f$ be as before, then $f(A)=-A$.

Now put everything together.

If $A$ is open, then $-A$ is also Open.


How can i get the selected column in C#, SQL

Question: I have the following Code/SQL statement in my C# project but the select statement doesnt show the values what are in the column it only shows the column name why is this ?
my code
 string Table = ListBox2.Text;
string column= listBox1.GetItemText(listBox1.SelectedItem);

            foreach (object Tables in ListBox2.SelectedItems)
            {
                using (SqlDataAdapter SQLStatement = new SqlDataAdapter("SELECT '"+column+"' FROM " + table, ConnectionString))
                {
                    DataTable dt= new DataTable();
                    SQLStatement.Fill(dt);
                    dataGridView1.DataSource = dt;
                    dataGridView1.Refresh();

                }
            }

Comment: Not related: `dataGridView1.Refresh();` is redundant. `dataGridView1.DataSource = dt;` will update datagridview with new values.
Answer: If you use SELECT '"+column+"' FROM table_name,generated query will be something like this: SELECT "column" FROM table_name.
Please try this:
string sqlCommandStatement = string.Format("SELECT {0} FROM {1}", column,table);

using (SqlDataAdapter SQLStatement = new SqlDataAdapter(sqlCommandStatement, ConnectionString))
            {
                DataTable dt= new DataTable();
                SQLStatement.Fill(dt);
                dataGridView1.DataSource = dt;
                dataGridView1.Refresh();

            }

Comment: Yes thank you i can accept your question after 8 min
Comment: @user7235054,  You're welcome ! Please accept answer when you get min 8.
Comment: @Toshi, the question was `How can i get the selected column in C#, SQL`
Comment: @Toshi, parameters will not work in OP's case. You cannot use parameter for column or table names
Comment: Coding isn't just getting things somehow done. What if `listBox1` contains `Drop Table Customers` or what ever. The table issue can be solved by a switch
Comment: @Toshi - no you cannot use parameters for column name. Query `SELECT @IdColumnName, @AgeColumnName FROM @PersonTableName` will not work
Comment: @Toshi i dont know what you complaining about it works if you know a better way then post it ;)
Comment: @Alexandru-IonutMihai I dont know why it works so i dont get it
Comment: @Toshi,question was about `How can i get the selected column in C#, SQL`
Comment: @Fabio, you're right : Sql can't have parameters on fieldnames or tablenames, just on values.But in my case i build a string and execute it. See updated answer.
Comment: @Alexandru-IonutMihai, feel free to use any approach which works for you. This approach can be safe until this method not exposed in public API of your system(TextBox in the UI for example). If they are - then this approach need strong validation before running query.


Axios PUT Request 403 Forbidden when logged into Django

Question: Whenever I am logged into a django user and I try and send a PUT request to my URL I get a 403 Forbidden Error. However, it works both when I am not logged in and also from the Django Rest API client.
Here is my code in my frontend:
let parameters = `user/${userID}/`
    return new Promise((resolve, reject) => {
        axios({
            method: 'PUT',
            url: 'http://127.0.0.1:8000/' + parameters,
            data: updatedUser,
            headers: {
                'Content-Type': 'application/json',
            },
        })
            .then((response) => {
                resolve(response)
            })
            .catch(error => {
                console.log(error)
                // reject(error)
            })
    });

I am very confused as I can't see the difference when I am logged into a django user and when I am not, as nothing changes in the frontend. Thanks
EDIT:
This is in my urls.py
 path('user/<id>/', views.RetrieveUpdateDestroyUser.as_view()),

And this is the view:
class RetrieveUpdateDestroyUser(RetrieveUpdateDestroyAPIView):
"""
View to handle the retrieving, updating and destroying of a User.
This View will also log any changes made to the model.
"""
serializer_class = UserCreateUpdateSerializer
queryset = CustomUser.objects.all()
lookup_field = 'id'
permission_classes = (AllowAny,)

def update(self, request, *args, **kwargs):
    """
    PUT and UPDATE requests handled by this method.
    """
    return super().update(request, *args, **kwargs)

I have also tested doing POST and PUT when I am logged into a user and they don't work, but GET does. Thanks
Also tried disabled CSRF but to no avail either
Comment: Could you show the code of `/user/` endpoint on Django side?
Comment: And I guess that there are cases when `userID` variable is empty of not defined. So Axios receives wrong value of `url`.
Comment: @DmitryBelaventsev I've made an edit, thanks for helping. I currently am trying to PUT to a fixed userID that exists so unsure
Comment: I still think it's something about CSRF. Could you try the following before axios request: `axios.defaults.xsrfHeaderName = "X-CSRFTOKEN"; axios.defaults.xsrfCookieName = "csrftoken";`? And how did you try to disable CSRF?
Comment: @DmitryBelaventsev I have both of those along with `axios.defaults.withCredentials = true` in my .js file. To disable CSRF I used a method decorator with csrf_exempt. It's just weird because the axios request works when I'm not logged into any user at all but as soon as I have a user logged in, even admin, it has the 403 Forbidden for PUT and POST.
Comment: I think you did CSRF disabling in a wrong way. Try the recipe from this answer https://stackoverflow.com/a/30875830/764182
Comment: CSRF check isn't performed for anonymouse (not logged in) users. That's why it's working for them.
Comment: In the meantime you have tried disabling of csrf before. But most likely you just used @csrf_exempt decorator, which will not work for DRF.
Comment: When it will start working without CSRF, you might want to check this part of Django docs https://docs.djangoproject.com/en/3.1/ref/csrf/#ajax to see what should be done to make AJAX calls with CSRF. As for axios csrf settings - please check that cookie name and header name are the same as I've posted above.
Comment: @DmitryBelaventsev oh wow thank you so much that works now, I literally would've been stuck forever because I thought I tried it with CSRF disabled. You're a legend, cheers.
Answer: Writing this answer to summarize what we have discovered.
The problem: the AJAX (PUT) call to the DRF endpoint fails with 403 HTTP error for authenticated users and works just fine for anonymous users
Desired Behaviour: make that call working for both anonymous and authenticated users
Reason: by default DRF perform CSRF check for unsafe HTTP methods (POST, PUT, PATCH and DELETE) https://www.django-rest-framework.org/topics/ajax-csrf-cors/
Possible Solutions:

Disable CSRF check like described here https://stackoverflow.com/a/30875830/764182
Pass CSRF token within the PUT request. For more information about CSRF + AJAX in Django read here https://docs.djangoproject.com/en/3.1/ref/csrf/#ajax. For Axios and default Django settings the solution might be:

axios.defaults.xsrfHeaderName = "X-CSRFTOKEN";
axios.defaults.xsrfCookieName = "csrftoken";
axios.defaults.withCredentials = true;

Comment: Thank you!! I had the completely same problem and this was the only clue for solving


100 people with 100 dollars each, give 1 dollar to a random other person. What's the distribution?

Question: Source: http://www.decisionsciencenews.com/2017/06/19/counterintuitive-problem-everyone-room-keeps-giving-dollars-random-others-youll-never-guess-happens-next/
"Imagine a room full of 100 people with 100 dollars each. With every tick of the clock, every person with money gives a dollar to one randomly chosen other person. After some time progresses, how will the money be distributed?"
I've seen various blog posts on this that use code to simulate the distribution. My question is: what is the reason that the distribution becomes skewed rather than stay uniform, what math do I need to understand this problem?
I initially tried reasoning with expected value, that each person has at each moment an expected value of $1. So I thought it would be uniform. Clearly this can change as soon as one person goes broke, then the expected value drops.
Thanks
Comment: the links referenced by the article you link to are quite helpful...did you look at them?
Comment: I read the article referenced in it that talks about random walks and lattice points, and admittedly I didn't really understand it.
Comment: @Yashmnash I looked at them as well, and didn't find a good explanation either. Admittedly I didn't study it in detail, and even if I would, I still would not necessarily understand with my limited math skills .... I am wondering something: does it have something to do that everytime you randomly pick just 2 people where 1 person gives a dollar to the other?  That is, I am wondering if, when every 'turn' we have all 100 people give away 1 dollar to a random person, do we still get the skewed distribution? Or what if, every turn, every person gives a dollar to some random *other* person?
Comment: @Yashmnash if you don't mind, you can look at my answer. Thanks!
Answer: A perfectly even distribution is unlikely because it is too regular.  There are just so many irregular states that their probability is much higher.  On the first move, the chance that the distribution stays exactly $100$ per person is the chance you select a derangement, of which there are about $\frac {100!}e,$ out of the $100^{100}$ choices for paying dollars.  This is tiny, about $3 \cdot 10^{-43}$.
What you will really have is a(fast approach to a) stationary distribution.  Each assignment of dollars to people, including one person having all $10,000,$ will have a probability to be what you see at any point in time.  The nice regular distributions will have low probability, as will each specific irregular distribution.  The irregular distributions as a whole will have very high probability.  It is true that each person's expected value at the end of each payment is $100$, but that doesn't mean it is very likely.  It is far more unlikely that they all have exactly $100$.
Added:  there is only one arrangement with each person having exactly $100$.  There are almost $10,000$ with one person having $101$, one person having $99$, and the rest having $100$.  If you lump all the ones in the second group together, that factor $10,000$ will swamp the small amount that the specific distribution is less frequent.  If everybody has different amounts of money, there are $100!\approx 10^{157}$ ways to assign the numbers to people.
Comment: Wonderful answer. This made perfect sense to me even though I have had no statistics classes.
Answer: 'Expected value' is not the same as what actually happens. A die thrown one time has an expected value of 3.5, but that is obviously not going to be an actual outcome.
And even in case where the 'expected value' is an actual outcome, it may in fact be the very least likely actual outcome (see, for example Polya's Urn)
So, this doesn't tell you why you get the distribution you do, but it does tell you why your reasoning using the 'expected value' doesn't work.
p.s. When someone goes broke they are not out of the game; they can still receive dollars.
Answer: Your question is equivalent to asking why in our world  the Second Law of Thermodynamics holds.
Consider a box $W=1 \times L=100 \times H=10,000$ and fill it evenly with 10,000 unit cubes, shake it somewhat, and the result is the answer to your question: the even distribution is very unlike to be attained out of "chaos" (it has the lowest possible enthropy), and that is the "thermodynamic" sense of Ross answer.
Answer: I am not sure whether the OP is still interested in this question. This phenomenon is usually referred to as the "propagation of chaos": In the large population/limit, any finitely many players are unlikely to change money with each other, and each agent is feeling the influence of a so-called "mean-field". The 2019 paper "Cutoff for the mean-field zero-range process" (link: https://arxiv.org/pdf/1804.04608.pdf) published at the Annals of Probability contains the best result (in some sense) about this model: The authors established a profound result called "cutoff phenomenon" (this phenomenon is somehow ubiquitous in the study of various Markov chains). Me and my Ph.D advisor will soon submit another paper regarding this model (and including closely related models), I will post the arXiv link once it's available online.

Edit: The arXiv link of our paper is https://arxiv.org/pdf/2105.07341.pdf, you can found closely related models as well. There are also other models in econophysics, for instance the uniform reshuffling model investigated in https://arxiv.org/pdf/2104.01302.pdf.


How to expand children div height to parent's height

Question: I have the page structure as:

I want to set the height of .child equal to .parent's height (which is known), but without positioning the child absolute. So the result would be a list of children which are themselves as high as the parent.
Comment: Of course you can. The result would be a vertical list of children with each of them having the same height of the parent. And with overflow: hidden; you can just make one child visible at once
Comment: they are to be positioned side-by-side, right?
Comment: no sorry, one below the other
Comment: But each has the same height as the parent? Or total height?
Comment: This makes no sense. You can't have 3 children as large as the parent without making the parent larger.
Comment: @SlavaKnyazev but you can set children to each have the parent's defined height.
Answer: You can set the parent's height, and then just set each child's height to 100%, and it will have each child have the same height as the parent, even if that expands the parent.

.parent
.child:nth-child(1) {background-color: #f00;}
.child:nth-child(2) {background-color: #0f0;}
.child:nth-child(3) {background-color: #00f;}

.parent {
  height: 100px;
  background-color: red;
}

.child {
  height: 100%;
}

Answer: You may try using table-layout or flex-box, which will make all the children equally high:

.parent {border: 2px solid #ccf; height: 300px;}
.child:nth-child(1) {background-color: #f99;}
.child:nth-child(2) {background-color: #9f9;}
.child:nth-child(3) {background-color: #99f;}

.parent {
  display: -ms-flexbox;
  display: -webkit-flex;
  display: flex;
  -webkit-flex-direction: row;
  -ms-flex-direction: row;
  flex-direction: row;
  -webkit-flex-wrap: nowrap;
  -ms-flex-wrap: nowrap;
  flex-wrap: nowrap;
  -webkit-justify-content: flex-start;
  -ms-flex-pack: start;
  justify-content: flex-start;
  -webkit-align-content: stretch;
  -ms-flex-line-pack: stretch;
  align-content: stretch;
}
.parent .child {
  width: 33.3333%;
  -webkit-order: 0;
  -ms-flex-order: 0;
  order: 0;
  -webkit-flex: 0 1 auto;
  -ms-flex: 0 1 auto;
  flex: 0 1 auto;
  -webkit-align-self: auto;
  -ms-flex-item-align: auto;
  align-self: auto;
}

Preview
Answer: You can use the inherit property to inherit the heigtht of the parent element. Inherit will always take on the same value as the first element where this property is set.
For example:

.parent{
  height: 200px;
  width: 600px;
  display: flex;
}

.child1{
  height: inherit;
  width: 25%;
  background-color: green;
}

.child2{
  height: inherit;
    width: 25%;
    background-color: purple;
}

.child3{
  height: inherit;
    width: 25%;
    background-color: blue;
}

.child4{
  height: inherit;
    width: 25%;
    background-color: red;
}

Answer: Can use CSS Flexbox to give child elements height of Parent div.

.parent{
display:flex;
}


Simpler or faster methods to calculate a sum

Question: I would like to calculate $$s=\sum_0^{\infty}(-1)^k\frac{\Gamma(1/2+k/2)}{\Gamma(1+k/2)}.$$
To do so I did the following
\begin{align}
s&=\frac{1}{\Gamma(1/2)}\sum_0^{\infty}(-1)^k\frac{\Gamma(1/2+k/2)\Gamma(1/2)}{\Gamma(1/2+1/2+k/2)}\\
&=\frac{1}{\Gamma(1/2)}\sum_0^{\infty}(-1)^kB(\frac12+\frac k2,\frac12)\\
&=\frac{1}{\Gamma(1/2)}\sum_0^{\infty}(-1)^k2\int_0^{\frac{\pi}{2}}[\sin(x)]^{2\times(\frac12+\frac k2)-1}[\cos(x)]^{2\times\frac12-1}dx\\
&=\frac{2}{\Gamma(1/2)}\int_0^{\frac{\pi}{2}}\sum_0^{\infty}(-1)^k[\sin(x)]^{k}dx\\
&=\frac{2}{\Gamma(1/2)}\int_0^{\frac{\pi}{2}}\frac{1}{1+\sin x}dx\\
&=\frac{2}{\sqrt{\pi}}\\
\end{align}
It took me some time to think of this solution, to me it hence is not the most straightforward way to follow. I was hence wondering if there is some other way which I could learn from it.
Many thanks in advance.
Answer: An option is to insert a power of $z^k$ in each term, then split the sum into the even and odd terms:
$$ s(z) = \sum_{n=0}^{\infty} \frac{\Gamma(n+1/2)}{\Gamma(n+1)} z^{2n} - \sum_{n=0}^{\infty} \frac{\Gamma(n+1)}{\Gamma(n+3/2)} z^{2n+1}. $$
The first sum is recognisable as
$$ \sum_{n=0}^{\infty} \Gamma(1/2) \binom{-1/2}{n} z^{2n} = \frac{\sqrt{\pi}}{\sqrt{1-z^2}}. $$
The second one is more annoying: I haven't got a nice way of doing it (yet...), apart from hurling it into the hypergeometric world:
$$ {}_2F_1(a,b;c;z) = \frac{\Gamma(c)}{\Gamma(a)\Gamma(b)} \sum_{k=0}^{\infty} \frac{\Gamma(k+a)\Gamma(k+b)}{\Gamma(k+c)} \frac{z^k}{k!}, $$
so the second term is obviously
$$ \frac{1}{\Gamma(3/2)} z {}_2F_1(1,1;\tfrac{1}{2};z^2) = \frac{2}{\pi} \frac{\arcsin{z}}{\sqrt{1-z^2}}, $$
using the ancient art of "looking it up in tables". Hence we have to find
$$ \lim_{z \uparrow 1} \frac{\pi-2\arcsin{z}}{\sqrt{1-z^2}}. $$
This is straightforward after we remember that $\pi/2-\arcsin{z}=\arccos{z}$. For $\theta$ close to $0$,
$$ \cos{\theta} \sim 1 - \frac{\theta^2}{2} $$
and rearranging gives
$$ \arccos{z} \sim \sqrt{2}\sqrt{1-z}, $$
for $z$ close to $1$, which cancels with the denominator's contribution and gives your answer.
Comment: Many thanks, that looks nice! (+1)
Comment: Very nice solution, indeed !
Answer: I do not know if this is the kind of answer of interest to you; so, forgive me if I am off topic.
Playing a little with the properties of the gamma function, what you can show is that $$\sum_{k=0}^n(-1)^k\frac{ \Gamma \left(\frac{k}{2}+\frac{1}{2}\right)}{\Gamma
   \left(\frac{k}{2}+1\right)}=2 \left(\frac{1}{\sqrt{\pi
   }}-\frac{\Gamma \left(\left\lfloor \frac{n-1}{2}\right\rfloor +2\right)}{\Gamma
   \left(\left\lfloor \frac{n-1}{2}\right\rfloor +\frac{3}{2}\right)}+\frac{\Gamma
   \left(\left\lfloor \frac{n}{2}\right\rfloor +\frac{3}{2}\right)}{\Gamma
   \left(\left\lfloor \frac{n}{2}\right\rfloor +1\right)}\right)$$
Comment: Many thanks. This is nice, I will try to understand the details by myself. (+1)


Find $n$ if $\sum_{p=1}^{n}\sum_{q=p}^{n}(^nC_q)(^qC_p)=211$

Question:
Find $n$ if $\sum_{p=1}^{n}\sum_{q=p}^{n}(^nC_q)(^qC_p)=211$

I found a similar question here that makes me wonder if there is a typo in the question I am asking.
If I take the question at face value and try expanding it, I get, for $p=1$
$(^nC_1)(^1C_1)+(^nC_2)(^2C_1)+(^nC_3)(^3C_1)+...$
for $p=2$,
$(^nC_2)(^2C_2)+(^nC_3)(^3C_2)+...$
Comment: Do you have the result for the inner sum ?
Answer: Consider what happens if you start the sum at $p=0$ instead. Try to think of a combinatorial problem that the summation answers
Example combinatorial problem:

 "Suppose I have $n$ distinctly labeled balls, all originally painted white.  In how many ways can I paint them either as white, pink, and/or pink with blue polka dots?"  If you approach the problem directly?  If you approach the problem by applying a layer of pink paint to some number of them, and of those painted pink applying a layer of polka dots on top to some.  Now, modify the problem so as to ensure you have at least some polka dotted balls at the end to account for starting the sum at $p=1$ instead of at $p=0$.

$~$
Approaching indirectly:

 Break into cases, picking how many will be polkadotted in the end, noting it must be at least one.  Break into cases based on how many need a pink layer of paint.  Pick which get a layer of pink paint and of those pick which further get polkadots.  This gives $\sum\limits_{p=1}^n\sum\limits_{q=p}^n\binom{n}{q}\binom{q}{p}$

Approaching directly:

 To each ball assign as either white, pink, or polkadotted.  Remove from the count the scenario of all exclusively being white and/or pink.  $3^n-2^n$

$~$
Finding an $n$ that works

 $3^5-2^5 = 211$
Answer: We are looking for $n$ which are solutions to
\begin{align*}
\color{blue}{\sum_{p=1}^n\sum_{q=p}^n\binom{n}{q}\binom{q}{p}=211}\tag{1}
\end{align*}
Here is a starter. We can considerably simplify the binomial sum which makes it easier to look for solutions $n$.

We obtain
\begin{align*}
\color{blue}{\sum_{p=1}^n}\color{blue}{\sum_{q=p}^n\binom{n}{q}\binom{q}{p}}
&=\sum_{p=1}^n\binom{n}{p}\sum_{q=p}^n\binom{n-p}{q-p}\tag{2}\\
&=\sum_{p=1}^n\binom{n}{p}\sum_{q=0}^{n-p}\binom{n-p}{q}\tag{3}\\
&=\sum_{p=1}^n\binom{n}{p}2^{n-p}\tag{4}\\
&=\sum_{p=0}^n\binom{n}{p}2^{n-p}-2^n\tag{5}\\
&\,\,\color{blue}{=3^n-2^n}\tag{6}
\end{align*}
Now we have simplified (1) to the equation
\begin{align*}
\color{blue}{3^n-2^n=211}
\end{align*}
which can be checked for small $n$.
Comment:

In (2) we use the binomial identity
\begin{align*}
\binom{n}{q}\binom{q}{p}&=\frac{n!}{q!(n-q)!}\,\frac{q!}{p!(q-p)!}\\
&=\frac{n!}{p!(n-p)!}\,\frac{(n-p)!}{(n-q)!(q-p)!}=\binom{n}{p}\binom{n-p}{n-q}
\end{align*}

In (3) we shift the index of the inner sum and start with $q=0$. We compensate this by substituting in the summand $q\to q+p$.

In (4) we apply the binomial theorem to the inner sum.

In (5) we add the term with index $p=0$ and subtract $2^n$ for compensation.

in (6) we apply the binomial theorem again.


How do I use an OR condition in an exposed filter?

Question: I have a view with more than 10 checkboxes for the multiple selection in exposed form with some field. Using the Drupal exposed filter for the multiple fields make the query of AND, but somehow I need the multiple selections in OR condition.
Is there any way to change the query to use a OR condition?
Answer: You can make view filter with OR condition by clicking on And/Or, Rearrange link.
Answer: Sometimes we use Drupal view_query_alter to add or modify the view's where clause. To add a new WHERE clause we may use add_where property. Whenever we use an add_where, it will create a WHERE clause along with an AND condition. There will be some cases were we need to use OR instead of AND. So if you want to know more about how to use OR clause in hook_view_query_alter, read on to know more.
We can use db_or to add a new OR condition with add_where. For example see the sample code
function mymodule_views_query_alter(&$view, &$query) {
  if ('yourviewname' == $view->name && 'page' == $view->current_display) {
    $weight_parent = array(29,31);
    $or = db_or()
    ->condition('taxonomy_term_data_taxonomy_term_hierarchy.weight', 'NULL', 'IS')
    ->condition('taxonomy_term_data_node.weight', $weight_parent, 'IN');
    $query->add_where(1,$or);
  }
}


Setup a good game servers?

Question: I have a very bad experience in setting up a game server. My fail experience was that I put all the servers into one (mail, database, game and web server). In the end, mail server did not handle mails properly (cant send X number of emails), database and web getting slower and slower, not enough hardisk spaces etc.
My game requirements:

Flash engine
Mysql database for store users data
Web page
Sending emails (like newsletters every month or weekly)

After some readings, assume cost is not a problem (well, dont let my client knows about it). My current plan is:

1 server for mail(btw, i still have trauma about the mail server, cant sent emails to all users previously)
1 server for the app (web, flash games)
1 server for database
?? Do I need a backup server here??

Are those enough?
My next question is, how to link up those servers, i.e the mail + database server link to app(web) server.
And, how to do load-balancing?
I have been readings, searching the web, but I still could not really understand. Sooo, please advise.
Comment: use google apps for mail and mail chimp for bulk mailing ;)
Comment: @anthony: Thats something new to me. Sounds like a great idea. Few questions to ask: Are you saying, when sending emails we use mail chimp, when receiving we use our own email? Second, that one need to pay (i know its worth the money), but can I use gmail SMTP and send to my users instead of using this? Will it decrease the % to reach my users? Oh shit, more questions, but no characters left
Comment: Pay me £400/day, and I'll contract to you for the sysadmin services.
Comment: you use google apps for general email send and recieve. and something like mailchimp for bulk email sending to lots of people
Answer: Hire a good sysadmin who knows how to do these things.
It will be more than worth the investment.
Comment: Here is the skillset you'll need: System architect, system administrator, network administrator. From your question I deduce you know little about these fields (no offence intended, but you don't). These aren't things you can just explain in a few words. So the logical thing to do, if you need that job done for a production system, is hire someone who knows about this. BTW, if you use some form of cloud service (Like Amazone EC2), you might save quite a bit of money on running expenses.
Comment: I was told to pick this skills, sysadmin. Jack-of-all-trades.

Setup a good game servers?


Neo4j - Where to start, displaying on web?

Question: I've created a neo4j graph using Java, and it's sitting in an embedded database. What I want to do is write a web page which accepts user input, creates the graph using Java, and then returns the result to the web page, where it is traversed and displayed in a chart fashion.
I'm not sure where to start with this in terms of framework and how to query from root to all nodes in the graph. I was thinking of using play-framework.
What should I be looking for in terms of documentation to work out querying the graph using play, for example?
Thanks!
Comment: We're currently working on a play2 plugin for scala, and plan to release a preliminary version in the next week. Not sure how annoying it would be to use from Java, but it might give you an idea/starting point. https://github.com/AnormCypher/AnormCypher
Answer: You also can use Spring Data Neo4j, probably the most convenient and most stable Java solutoin right now, see http://www.springsource.org/spring-data/neo4j


Are side lengths enough to find the ratio of the diagonals of a quadrilateral?

Question: Is it possible to find the ratio of two diagonals of a quadrilateral when the length of all sides are given??
Answer: If you don't know some of the angles, then no. This is not to difficult to see by drawing some pictures (or even better, bending something like a straw into the shape of a quadrilateral, and then deforming it). Keeping all the lengths of the sides fixed, you can vary the angles to produce some fairly extreme shapes - in particular, you can draw lots of quadrilaterals with the same four side lengths, but wildly different diagonal lengths.
Note: The question has significantly changed in an edit, to ask about the ratio of the diagonals, rather than the lengths. However, the same answer applies (imagine taking a square, where the two diagonals have equal length, and squashing two opposite corners together without changing the side lengths, to get a rhombus, where the diagonals are different).


Heavyweight Jquery slideshows are slow in desktops and crash on ipad 2, android ics and iphone

Question: I am building my portfolio site (have a look here ...)
http://www.tripleagent.co.uk/projects.html
And I am using Jquery with jquery.cycle.all.js.  I added about 200 slides with my work dated many years back and a few vimeo videos with fitvid.js (it resizes the videos to fit in a responsive design). My problem is that the page is slow on a workstation computer (i7 ivy bridge and chrome) and it crashes on ipad, android and iphone. I am new on jscript and html5 so I am not sure what is going wrong.
With my limited experience I believe that its running out of memory or that the slower machines can't handle the fade animations simultaneously.
I use a typical setup for the slideshow
$("#slideshow").cycle({
    fx:'fade,',
    speed: 1000,
    slideExpr:'.slide',
    slideResize: 0,
    timeout:        7000,
    pause: 1,
    //sync: true,
    autostop: false,
    pager: '#nav',
    next: '#slideshow',
    pagerEvent: 'mouseover',
    fastOnEvent: true ,
    pagerAnchorBuilder: function(idx, slide)
    {return '

';
    },
    after:   captionsAlt ,
    });

What should I do ? I can break up the page in two and it will probably work but i was thinking that there must be a way to optimize the page instead.
Any suggestions? Is there any mistake, a bug or a bad design idea in the first place ?
Comment: Is there any online material to read further on how to sort this out?
Answer: It has been months since i asked this question.
I upgraded to the latest jquery 1.9.1, cycle.all 3.0.4 I just noticed that Safari, IE9 and mozilla don't have  much of a problem anymore. The videos play well in android 4.1+ and IOS  but it is still a bit heavy and it has some problems regarding touching and scrolling on top of the vimeo player. but i asked that already in the vimeo forums.
Comment: Thanks for the information from the first part of the answer. As for the second part: please, create a new question with link to this one. A new question inside your answer is unlikely to be answered.


Show that $-\log(1-\mathrm{e}^{\mathrm{i}x}) = -\log\left(2\sin\left(\frac{x}{2}\right)\right) + \mathrm{i}\dfrac{\pi - x}{2}$

Question: Show that
$$
-\log(1-\mathrm{e}^{\mathrm{i}x}) = -\log\left(2\sin\left(\frac{x}{2}\right)\right) + \mathrm{i}\dfrac{\pi - x}{2}.
$$
This is a last step in one of my problems, and I know the two expressions are equivalent, yet I can't seem to figure out how to manipulate the LHS to give me the RHS. Obviously I'd need to expand $e^{ix}$ using Euler's formula, but I can't see what they did. Any help would be greatly appreciated!
Comment: actually, $\pi$ should be replaced by $2n\pi$
Comment: I see how you might figure that, but [this](http://math.stackexchange.com/a/1307243/294327) suggests that what I put is also true. How can that be?
Comment: Mh.. I think it is false. $\dfrac{1}{1-e^{ix}}=\dfrac{1}{1-e^{i(2n\pi+x)}}=\dfrac{1}{2\sin\dfrac{x}{2}}e^{-i\left(\dfrac{2n\pi+x}{2}\right)}=\dfrac{1}{2\sin\dfrac{x}{2}}e^{i\left(\dfrac{2m\pi-x}{2}\right)},n=-m$
Comment: Hmm. [Let me provide the context of my problem.](http://math.stackexchange.com/questions/1551142/show-that-the-series-converges-and-is-equal-to-the-following) Restricting $0<x\leq \pi$ should give us our answer, correct?
Comment: I see nothing false in my proof. I wonder how it has stated on two problems. Please comment here one day if you can surprise me.
Answer: $1-e^{ix}=1-(cos\ x + i\ sin\ x) = 2\ sin^2\dfrac{x}{2} + 2\ i\ sin\dfrac{x}{2} cos\dfrac{x}{2} = 2\ sin\dfrac{x}{2}(cos\dfrac{x}{2}+i\ sin\dfrac{x}{2})=2\ sin\dfrac{x}{2}e^{\frac{ix}{2}}$
Comment: Awesome, thanks. From here, I got $-ln(2sin(\frac{x}{2})) + i(\frac{x}{2})$. But $e^{\frac{ix}{2}} \neq e^{\frac{i(\pi - x)}{2}}$. Where does the $\pi$ come in?
Comment: actually, $log\ z = log|z|+i(arg\ z + 2n\pi)$ Note $e^{ix}=cos\ x + i\ sin\ x \Rightarrow e^{ix}=e^{i(2n\pi+x)}$
Comment: and your text book sure has typos.
Comment: I didn't include that my problem has x restricted so that $x \neq 2\pi k$ where $k$ is any integer. I assume that should change some things.


How to center a html.H1 in Dash Plotly

Question: How do I center a text in html.H1 in ploty dash in python?
app = dash.Dash(__name__)
app.layout = html.Div([
    html.H1('Hello Dash', style={'color': 'red', 'fontSize': 40})
         ])

I want to put 'Hello Dash' right in the middle of the page. How can I do that?
Comment: You can always give it an id and use CSS to center it
Comment: honestly I know nothing about html or css, guess I can't escape it after all
Comment: You could use the dash bootstrap components and use their layout components. They use a grid system which is supposedly easier to center, control the layout etc.
Answer: Dash is generating HTML and CSS. You can see the code it produced by right clicking on the heading in your page and using 'Inspect'.
As an example, it turned 'fontSize' into CSS property 'font-size'. The CSS property to position a line of text is 'text-align' (examples). So following the same pattern, when using the 'html' method, you could refer to CSS documentation and convert the dash separated properties into camelCase when setting them in the style dictionary. Then dash will convert it back to a CSS property when rendering.
app.layout = html.Div([
    html.H1('Hello Dash', style={'textAlign': 'center'})
])

Produces this HTML with inline CSS:

Hello Dash

See dash layout docs ('More about HTML' section)

How to center a html.H1 in Dash Plotly


Existence of increasing modification

Question: I have the following, seemingly simple question:
Consider a stochastic process $(X_t)$ satisfying $X_s\le X_t$ a.s. for all $s\le t.$ My question is: Does there exist a modification $\tilde{X}$ of $X$, which almost surely has increasing sample paths $t\mapsto\tilde{X}_t(\omega)$?
I assume such a modification exists, but I did not manage to prove it.
Thanks in advance!
Answer: Let $(\tilde X_t)$ be a separable modification of $(X_t)$; for example, see Theorem 38.1 (page 558) in Billingsley's Probability and Measure (2nd edition). If $D$ is the separant, and we define $$N=\bigcup_{s<t;\, s,t\in D}\left\{\omega: \tilde X_s(\omega)>\tilde X_t(\omega) \right\},$$ then $\mathbb{P}(N)=0$, and for $\omega\notin N$ we have $t\mapsto \tilde X_t(\omega)$ is a non-decreasing function.

Existence of increasing modification


node.js pm2 on exit

Question: I'm using pm2 to running node application. I must save data before application will be closed. This code works fine in shell:
process.on('exit', function(){
    log.debug('exit');
});

process.on('SIGINT', function(){
    log.debug('SIGINT');
});

process.on('uncaughtException', function(){
    log.debug('uncaughtException');
});

When I'm stopping the application using "pm2 stop" the code doesn't work. I think that pm2 kills process.
Answer: SIGINT is generally triggered after a user-invoked shutdown (e.g. Ctrl+C). Assuming pm2 is triggering an abrupt shutdown then SIGINT won't be triggered.
Instead, you should listen for the termination signal SIGTERM which should cover both scenarios
process.on('SIGTERM', function() {
    // clean up
});

node.js pm2 on exit


Unmatched pairs for LilyPond ties and slurs

Question: In LilyPond, ties and slurs are expected to come in matched pairs. I keep coming across situations where a tie or a slur aren't matched.  For example:

As demonstrated in the MWE below, it is possible to have a tied note that goes into a coda (or repeat or some other form of musical jumping) but in LilyPond the ~ form of the tie can't be added to the first note in the coda because it is separated from it's initiating note by line breaks and additional notes

It actually surprises me that musical redirections like coda and segno aren't environments like the \repeat volta n {} \alternative{{}{}} setup but that's neither here nor there, I simply bring it up in case I'm wrong and there actually is an environment for coda's and segno notation and jumping.

I frequently use a lilypond-book compile to produce only one or two bars to include in a document, and I may want an a tie or slur to be implicitly started, but I only care about presenting the bar in question following the tie or slur marking.

I know LilyPond is designed more for typesetting than understanding flow, but can I force LilyPond to print a tie or a slur without having an original note in mind?
    \version "2.18.2"
    {
      \relative c'' \repeat unfold 2 {
          c4 c c c~
        }

        % Set coda sign as rehearsal mark and adjust size if needed
        \once \override Score.RehearsalMark.font-size = #4
        \mark \markup { \musicglyph #"scripts.coda" }
        \relative c'' \repeat unfold 2 {
          c4 c c c
        }

       \break

       \once \override Score.RehearsalMark.extra-offset = #'( -4.5 . 0 )

       \once \override Score.RehearsalMark.font-size = #5
       \mark \markup { \musicglyph #"scripts.coda" }

       % The coda
       \relative c'' \repeat unfold 5 {
          ~c4 c c c
        }
        \bar"|."
    }

To get this MWE to successfully compile, all that is needed is to remove the ~ in front of the last c4 in the final unfold environment.
Comment: As of v2.23 `\repeat segno` exists, see: [1.4.1 Long Repeats - Segno repeat structure](https://lilypond.org/doc/v2.23/Documentation/notation/long-repeats#segno-repeat-structure)
Answer: Turns out Lilypond has a command to add tied notes that may be unmatched due to codas or repeat signs:
If you follow the tied note that is other wise unable to be connected with the tie-initiator with the command \repeatTie, the tie shows up in the right place.
I thought there would have been a more general environment style solution so while this works for ties, I haven't yet found an equivalent solution for the slurs.
It took me a while to figure out that \repeatTie has to follow, not precede, the note you wish to connect.
\version "2.18.2"
{
  \relative c'' \repeat unfold 2 {
      c4 c c c~
    }

    % Set coda sign as rehearsal mark and adjust size if needed
    \once \override Score.RehearsalMark.font-size = #4
    \mark \markup { \musicglyph #"scripts.coda" }
    \relative c'' \repeat unfold 2 {
      c4 c c c
    }

   \break

   \once \override Score.RehearsalMark.extra-offset = #'( -4.5 . 0 )

   \once \override Score.RehearsalMark.font-size = #5
   \mark \markup { \musicglyph #"scripts.coda" }

   % The coda
   \relative c'' \repeat unfold 5 {
      c4\repeatTie c c c
    }
    \bar"|."
}

Answer: The problem here is the \repeat unfold 2 { ... } after the first coda sign.
That does not contain a ~ for "start tie." When it is expanded, Lilypond has finished typesetting its last note, without a tie.
So the in the following ~c4, the ~ has nothing to attach itself to.
One fix is just to remove the \repeat unfold 2 and put the ~ where it belongs:
\relative c'' { c4 c c c | c c c c~ }

   \break
   ...
   % The coda
   \relative c'' \repeat unfold 5 {
      c4 c c c
    }

If you really want to keep the \repeat unfold construct, you can make a parallel passage consisting only of spacer rests, and start the tie from inside that:
    \mark \markup { \musicglyph #"scripts.coda" }
    \relative c'' {
        << \repeat unfold 2 { c4 c c c }
           { s4*7 s4~ }
        >>
    }

   \break
    ...
   % The coda
   \relative c'' \repeat unfold 5 {
      c4 c c c
    }
    \bar"|."

This works because the ~ is "merged" with the notes after the \repeat unfold has been expanded. Incidentally, this is also a good way to attach different dynamic marks, etc, to different repeats of the music in a \repeat unfold.
Comment: I'm not sure I'm following this completely.  My actual situation doesn't use `repeat`, but it does use other instrument specific melody creation commands for score and part layouts, so I have tried to start with the first solution you describe.  As you describe lilypond has not typeset a tie when it does it's last note.  To my understanding, that's the whole problem.  The tied note I need to "link" is in the middle of a block of notes, it's not at the end of the line. Unfortunately spacers give unwanted space and the tie just gets added to the wrong side of the desired note.
Comment: If you post an example that shows your *real* problem, you might get a better answer. To be honest, I found your original question hard to understand - and how it relates to Lilypond-book wasn't clear at all. The basic question seemed to be "why doesn't the tie into the coda (that starts on the second system) work?" which is what I answered. Sorry if that wasn't the question you really wanted to ask.


Docker error from CMD command prompt: Something went wrong running an SSH Command

Question: I am using the following tutorial to install TensorFlow on my Windows machine, using Docker: http://www.netinstructions.com/how-to-install-and-run-tensorflow-on-a-windows-pc/

I installed Docker
I opened quickstart terminal
I set up a new virtual box "vdocker"
From within quickstart terminal, I ran
docker-machine ls and got:
NAME      ACTIVE   DRIVER       STATE     URL                         SWARM
default   *        virtualbox   Running   tcp://192.168.99.100:2376
vdocker   -        virtualbox   Running   tcp://192.168.99.101:2376

I opened up a command prompt from Windows Start menu (first as a non-administrator, and later as administrator), and when I do
docker-machine ls
I get the following:

In particular, I get stuck on this step of the tutorial I included above:
FOR /f "tokens=*" %i IN ('docker-machine env --shell cmd vdocker') DO %i

I cannot run the above in CMD successfully.
I found online solutions that say to regenerate certificates, remove default, re-create default and I tried them, with no luck. Hints would be appreciated!
Answer:
In particular, I get stuck on this step of the tutorial I included above:
FOR /f "tokens=*" %i IN ('docker-machine env --shell cmd vdocker') DO %i

That is not the command you show in the screenshot. There, the path has spaces in it, which causes the initial C:\Program do be passed to DO %i. That is, it first tries to execute DO C:\Program which is not an executable.
I am assuming the other problems are also related to the fact that the installation directory name contains spaces.


If $x^5 ≡ 2 $(mod $17$) then $x ≡ 15 $(mod $17$)

Question: How am I suppose to reduce the $x^5$ Should I write the entire table ?
Answer: You probably know that $x^{p-1}\equiv 1 \pmod p$ for non-zero $x$. So in our case the exponent we have, $5$, is relatively prime to $p-1=17-1=16$.
So there exist integers $a,b$ such that $5a+16b=1$. (E.g. $a=-3,b=1$) does So $x\equiv x^{5a+16b}\equiv x^{5a}(x^{16})^b\equiv x^{5a}\equiv (x^5)^a\equiv 2^{-3}\equiv 2^{16-3}\equiv 2^{13} \pmod {17}$.
Now $2^{13}$ reduces to $15$ modulo 17.
Comment: So we know 5 and 16 are coprime. How do you get 5a  + 16b = 1 ?
Comment: In general if $\gcd(x,y)=k$, you can always find integers $a,b$ such that $ax+by=k$.
Comment: omg ur absolutely right? I forgot about that theorem. Thanks
Comment: How is $2^{-3}$ = $2^{16-3}$
Comment: Because $2^{16}\equiv 1 \pmod 17$ You can multiply by $(2^{16})^k$ for free anywhere in your calculations.
Answer: FLT $x^{16}\equiv 1 \mod 17$
So $(x^5)^3x \equiv 8x \equiv 1 \mod 17$
So $16x \equiv -x \equiv 2 \mod 17$
So $x \equiv -2 \equiv 15 \mod 17$


Best suited algorithm for prediction of purchase or no purchase based on click stream data

Question: Could anyone please suggest the best suited model to be used for the prediction if a customer who has visited the website will buy a product based on the click stream data.Also,it would be great if you could provide necessary resources to analyse the same.
Answer: Take a look to the following algo/repositories:
https://github.com/aksnzhy/xlearn/blob/master/README.md
"xLearn can be used for solving large-scale machine learning problems. First, xLearn supports out-of-core training, which can handle very large data (TB) by just leveraging the disk of a PC. In addition, xLearn supports distributed training, which scales beyond billions of example across many machines by using the parameter server framework."
https://github.com/fmfn/FTRLp/blob/master/README.md
From the last one description:
"More over this method is very efficient at obtaining sparsity and has proven to perform very well in massive Click-Through-Rate prediction tasks."
Answer: Always remember that every machine learning problem is unique in itself. No two datasets can be the same. One model might give a better result on your performance measure on one problem but may give the worst result on some other problem.
Since you mentioned that you need a $0/1$ prediction, you might want to play around with supervised learning algorithms. Some of the popular ones are K Nearest Neighbors, Naive Bayes, Random Forests, SVM, Logistic Regression, Neural Networks (or if you have enough computation resources you might also want to try out Deep Neural Networks).
Visualize the data the data and find out if it is linearly separable on the given features. If yes, bingo! Otherwise, try out to project features in some high dimensional space and then apply the models.


"IIS Manager Permissions" icon missing from Windows Server 2019 IIS

Question: I wanted to setup web deployment from Visual Studio into an AWS EC2 instance.
First, I launched a EC2 instance of Windows Server 2019 Base. I added IIS and ASP.NET Windows features. Then I downloaded Web Deploy 3.6 msi and chose to install "complete features".
After that, I started IIS manager, and went to "Default web site". Under the "Management" group, I expect to see a "IIS Manager Permissions" icon, but it was not there. I need it to enter the user name/password, which will be used by my Visual Studio to connect to this IIS.
Where did I get it wrong?
Answer: IIS Manager Permissions is only visible if you enabled Management Service role service,
https://docs.microsoft.com/en-us/iis/manage/remote-administration/configuring-remote-administration-and-feature-delegation-in-iis-7#configuring-remote-connections-in-iis-manager
Comment: Thank you Lex! Now the "IIS Manager Permissions" icon is shown. I then proceeded to setup web deploy following https://docs.microsoft.com/en-us/iis/install/installing-publishing-technologies/installing-and-configuring-web-deploy-on-iis-80-or-later. On step 9, "Right-click the site that you are configuring, point to Deploy", the "Deploy" context menu item is not there. What is missing this time?
Comment: @SillyDude go back to this step https://docs.microsoft.com/en-us/iis/install/installing-publishing-technologies/installing-and-configuring-web-deploy-on-iis-80-or-later#using-the-web-deploy-installer-to-install-web-deploy Were you able to select all features to be installed? If you didn't enable all features, then some functionality can be missing.
Comment: I worked out - I had to uninstall Web Deploy then install it. Then the "Deploy" context menu will appear when I right click the site on IIS.


What is the difference between host_check_live command and Ping service

Question: We are using Nagios based Op5 to monitors servers.
Do we need to have Ping service too for servers as I guess host_check_live (command: $USER2$/check_host -H $HOSTADDRESS$)  command already uses Ping to see if it alive.
Isn't Ping redundant?
Comment: Side note: you'll want to use check_icmp instead of check_ping if you have more than a few hundred hosts. It must be setuid root (just like the ping binary) but is about 10x faster.
Answer: At least on my NAGIOS installation, check_host-alive actually runs check-ping:
define command{
        command_name    check-host-alive
        command_line    $USER1$/check_ping -H $HOSTADDRESS$ -w 3000.0,80% -c 5000.0,100% -p 5
        }

There are two things that make me think that defining this as a check separate to stock check_ping is not redundant.
Firstly, those thresholds are crazily high.  For no normal server am I happy with an RTT of 2900ms or packet losses of 70%.  Those thresholds are really only useful as a test of whether a server is actually, genuinely down.  Here's an example of thresholds when I actually care about the values returned:
check_ping!200.0,20%!600.0,60%

So there's a quantitative difference between the way PING is used to check host availability, and when used a service in its own right, and that alone justifies making a distinction between ping-as-host-up-test and ping-as-link-quality-test.
Secondly, some of my monitored hosts can't be PINGed, sometimes for reasons outside my control.  In those cases, I'll use a simple TCP connectivity check to a monitored port, or in one case the output of traceroute.
Edit: it just occurred to me that you might be asking "why PING a host to check if it's up if we're only going to PING it again as a service check".  If that's your question, then reason 1 above still applies.  But also, I often don't care about PING as a service check - poor quality links will show up in the many other services that are monitored.  So PING's not redundant in most of those cases.  If you don't care about the output of PING other than a test for host-up, don't run it as a service check either.
Answer: The default nagios host check is based on ping.  If you have implemented a separate service check for ping that would be redundant.
Comment: Fixing your basic host check to have appropriate sensitivity seems like a better bet than having redundant checks.
Comment: I'm sorry if I've been unclear.  When I use it as a host check, I really don't care about latency, high packet losses, etc.  I only care if the host is down beyond all reasonable doubt, so that I get one HOST DOWN alert instead of 22 SERVICE DOWN alerts.  When I use it as a link quality check, as a service, I do care about those things.  I'm trying to determine different data when I use `check_ping` in two different ways.  Is that any clearer?
Comment: Now it is clearer.  I don't use nagios for marginal network monitoring.  smokeping or something else that can show you the history seems like a better fit to those issues.  But if you insist on doing it all in nagios, then you are not as redundant as you initially appeared.
Comment: I'm not entirely sure I agree - see above!


Rewrite empty Fields on Feeds periodic Import

Question: I have set up a periodic feed importer in drupal which imports nodes and updates existing nodes.
Lets assume the imported xml consits of two fields: the title and a long text field.
I import the nodes in the morning with the following content:
title   long text field
1       long text 1
2       long text 2
3       long text 3

So three nodes were correctly created with the two fields. But if I import later and the content of the xml has changed to the following:
title   long text field
1       long text 1
2
3       long text 3

As you can see the long text field of the second node is empty, but feeds doesn't update the field. The value after reimport is still 'long text 2'.
I haven't found an option or a module to achieve this. I have tried to manipulate the input data via
hook_feeds_after_parse(FeedsSource $source, FeedsParserResult $result) {
  // replace empty results with ' ' (one space), so they gets replaced
  for ($i=0; $i < sizeof($result->items); $i++) {
    for ($o=0; $o < sizeof($result->items[$i]); $o++) {
      if (empty($result->items[$i]['xpathparser:'.$o])) {
        $result->items[$i]['xpathparser:'.$o] = ' ';
      }
    }
  }
}

But feeds only jumps into the function if it detects changes in the xml, but i think empty fields don't get considered.
Comment: I fear I don't really understand your question? I have used feeds myself and it works as you describe: If the field is empty in the updated xml, the new import will also update the node's field and empty it. Or?
Comment: no, in my project feeds doesn´t empty the field :(
Answer: Yes, this is a known problem of feeds. However, there is a patch for it and will be included in the next release as I know. You can already apply the patch now yourself:https: www.drupal.org/node/1107522
It is #161 in the link above.
I am using it for a while and tested it too, it works for your scenario above.
There is one problem with email and URL fields: Feeds still creates the field when the import is empty and this results in empty fields shown.


Combine two or more filter criteria in views

Question: I want to combine two or more filter criteria to a dropdown in views filter criteria. so that i can select a filter criteria in the dropdown box and can search with a string in a text box. so that the result will be similar to the string from the filter criteria which is selected from the dropdown listbox(combination of filter criterias).
Is there any way to combine the filter criteria as dropdown...?
Comment: I don't understand the part "so that i can select a filter criteria in the dropdown box and can search with a string in a text box" How many filter do you have? You want to combine few filter as dropdown and one filter is as text box?
Comment: This may help http://drupal.stackexchange.com/questions/40629/combine-several-exposed-filters-into-one-exposed-search-form
Comment: i am using a using a dropdown list and a textbox. I want to use the dropdown to select the main filter and i will use a text box to search for a string. so the result will be similar to the string from the text box with the selected filter criteria.
Comment: i want to add two fields like `Content: Title` and `Content: Body (body)` together in a dropdown. so that i can select a field from the dropdown and search some string in that field using the textbox string.
Comment: I am still not able to understand completely you want to accomplish. If you expose `Content: Title` and `Content: Body (body)` filter those will be exposed as textfield. right? How you suppose to combine them as dropdown?
Comment: Do you want something like this https://www.dropbox.com/s/jgenr05lo8r3173/Voila_Capture%202014-08-01_11-01-15_pm.png
Comment: yes exactly the same as in the png @MutantMahesh. can u help me out to get that dropdown...?
Comment: That exactly is not possible with just configuring the views and with any other contributed module. But you can combine two or more filters in one expose filter with *Global: combine field filter"* or with [Views Filter Populate](http://drupal.org/project/views_filters_populate). IF you want that exactly then you have to code in custom module with two hooks `hook_views_exposed_form_alter` and `hook_views_query_alter`.
Comment: i will try with the hook functions which u have provided @MutantMahesh
Answer: I Found this problem interesting and spend little time over this. Here is the solution i come with.

Create a view with title and Body field.
Add two filters Content:Title and Content:Body with Contains operator, expose these two filters.
Create a custom module with the following hooks.
//custom.module
function custom_form_views_exposed_form_alter(&$form, &$form_state, $form_id) {

if ($form_id == 'views_exposed_form' && $form_state['view']->name == 'VIEW_NAME') {

    // Unset the title and body filter info so that it doesn't print any label.
    unset($form['#info']['filter-title']);
    unset($form['#info']['filter-body_value']);
    // Unset the title and body filter
    unset($form['title']);
    unset($form['body_value']);

    $form_element = array();
    $options = array(
    // '' => '-Select-',
      'title' => 'Title',
      'body' => 'Body',
    );
    $form_element['search_within'] = array(
      '#type' => 'select',
      '#title' => t('Search within'),
      '#options' => $options,
      '#default_value' => !empty($form_state['search_within']) ? $form_state['search_within'] : '',
      '#description' => t('Set the Title or Body within which you want to search.'),
      '#prefix' => '
',
      '#suffix' => '
',
    );
    $form_element['search_box'] = array(
      '#type' => 'textfield',
      '#title' => t('Search term'),
      '#default_value' => !empty($form_state['search_box']) ? $form_state['search_box'] : '',
      '#description' => t('Enter the term which you want to search.'),
      '#prefix' => '
',
      '#suffix' => '
',
    );
    $form = $form_element + $form;
}
}

function custom_views_query_alter(&$view, &$query) {
if ($view->name == 'VIEWS_NAME') {
    if (!empty($view->exposed_input['search_box']) && $view->exposed_input['search_within'] == 'title') {
    // Add title filter condition if title is selected
        $query->where[1]['conditions'][] = array(
          'field' => 'node.title',
          'value' => '%' . $view->exposed_input['search_box'] . '%',
          'operator' => 'LIKE',
          );
    }
    if (!empty($view->exposed_input['search_box']) && $view->exposed_input['search_within'] == 'body') {
    // Create join with fiedl_data_body table.
    // source:
    // https://api.drupal.org/api/views/includes!handlers.inc/function/views_join%3a%3aconstruct/
    // https://www.drupal.org/node/2049051#comment-7784967
        $join = new views_join;
        $extra = array();
        $extra[] = array(
          'table' => 'field_data_body',
          'field' => 'entity_type',
          'value' => 'node',
          'operator' => '=',
          );
        $extra[] = array(
          'table' => 'field_data_body',
          'field' => 'deleted',
          'value' => '0',
          'operator' => '=',
          );
        $join->construct('field_data_body', 'node', 'nid', 'entity_id', $extra);
    // Add join to query; 'node' is the left table name
        $view->query->add_relationship('field_data_body',$join,'node');
    // Add fields from table (or where clause, or whatever)
        $view->query->add_field('field_data_body','entity_id');
    // Add body filter condition if body is selected
        $query->where[1]['conditions'][] = array(
          'field' => 'field_data_body.body_value',
          'value' => '%' . $view->exposed_input['search_box'] . '%',
          'operator' => 'LIKE',
          );
    }
}
}

Note: This solution will only work with Contains operator and very case specific. It would be great if somebody will create a generic views filter handler to combine exposed filter as select list and allow search within selected filter.
Comment: This solution helped me out of the issue. tq @MutantMahesh
Answer: You may need the Better Exposed Filters module for this.
Make sure the fields that you want to filter through are in your fields area, even if they are not visible.
Add a new filter criteria. You are looking for the one named Global: Combine fields filter. From here you can choose two of the fields that you have added to the Fields area.
Set your operator to contains and make sure it is exposed.
Comment: i need it as dropdown list box like in the below link. https://www.dropbox.com/s/jgenr05lo8r3173/Voila_Capture%202014-08-01_11-01-15_pm.png


Equivalence of wedge and tensor product with Levi-Civita symbol

Question: In this answer the following is stated in the 2-dim case:
\begin{eqnarray}
v\land w & = & \frac{1}{2!}(v\land w-w\land v) \\
& = & \frac{1}{2!}\epsilon_{\mu\nu}v^{\mu}\land w^{\nu} \\
& = & \frac{1}{2!}\epsilon_{\mu\nu}(v^{\mu}\otimes w^{\nu}-w^{\nu}\otimes v^{\mu}) \\
& = & \epsilon_{\mu\nu}v^{\mu}\otimes w^{\nu}.
\end{eqnarray}

NB:

I wanted to see the index mechanics at play replicating what was done in this answer, building a 2-vector from two vectors in $v, w \in\mathbb R^3, $ such as $v=1e_1+3e_2-2e_3$ and $w=5e_1+2e_2+8e_3:$
$$v\wedge w=(1\cdot e_1 + 3 \cdot e_2 - 2 \cdot e_3) \wedge (5\cdot e_1 + 2 \cdot e_2 + 8 \cdot e_3) = \\[2ex]
1\cdot 5 \cdot e_1 \wedge e_1 + 1\cdot 2 \cdot e_1 \wedge e_2 + 1\cdot 8 \cdot e_1 \wedge e_3 \\
+3\cdot 5 \cdot e_2\wedge e_1 +3\cdot 2 \cdot e_2\wedge e_2 +3\cdot 8 \cdot e_2\wedge e_3  \\
-2\cdot 5 \cdot e_3\wedge e_1 -2\cdot 2 \cdot e_3\wedge e_2 -2\cdot 8 \cdot e_3\wedge e_3 = \\[2ex]
5 \cdot \mathbb O + 2 \cdot e_1 \wedge e_2 - 8 \cdot e_3 \wedge e_1 \\
-15 \cdot e_1\wedge e_2 +6 \cdot \mathbb O +24 \cdot e_2\wedge e_3  \\
-10 \cdot e_3\wedge e_1 +4 \cdot e_2\wedge e_3 -16 \cdot \mathbb O = \\[2ex]
\bbox[5px,border:2px solid red]
{
28 \cdot e_2\wedge e_3-18 \cdot e_3\wedge e_1 - 13 \cdot e_1\wedge e_2}$$
starting off at the end, and trying to calculate $\epsilon_{\mu\nu}v^\mu\otimes w^\nu:$
$$\epsilon_{\mu\nu}v^\mu\otimes w^\nu= \\[2ex]
\color{blue}{\epsilon_{11}} 1\cdot 5 \cdot e_1 \otimes e_1 + \color{blue}{\epsilon_{12}} 1\cdot 2 \cdot e_1 \otimes e_2 + \color{blue}{\epsilon_{13}} 1\cdot 8 \cdot e_1 \otimes e_3 + \\
\color{blue}{\epsilon_{21}} 3\cdot 5 \cdot e_2\otimes e_1 + \color{blue}{\epsilon_{22}} 3\cdot 2 \cdot e_2\otimes e_2 + \color{blue}{\epsilon_{23}} 3\cdot 8 \cdot e_2\otimes e_3 + \\
\color{blue}{\epsilon_{31}} (-2)\cdot 5 \cdot e_3\otimes e_1 +\color{blue}{\epsilon_{32}}(-2)\cdot 2 \cdot e_3\otimes e_2 +\color{blue}{\epsilon_{33}}(-2)\cdot 8 \cdot e_3\otimes e_3 = \\[2ex]
\color{blue}0\cdot 1\cdot 5 \cdot e_1 \otimes e_1 + \color{blue}1\cdot 1\cdot 2 e_1 \otimes e_2 + \color{blue}1 \cdot 1\cdot 8  e_1 \otimes e_3 + \\
\color{blue}{(-1)}\cdot 3\cdot 5  e_2\otimes e_1 + \color{blue}0 \cdot 3\cdot 2  e_2\otimes e_2 + \color{blue}1 \cdot 3\cdot 8  e_2\otimes e_3 + \\
\color{blue}{(-1)}\cdot (-2)\cdot 5  e_3\otimes e_1 +\color{blue}{(-1)}\cdot(-2)\cdot 2  e_3\otimes e_2 +\color{blue}0\cdot (-2)\cdot 8 \cdot e_3\otimes e_3 = \\[2ex]
\bbox[5px,border:2px solid red]
{
2 e_1 \otimes e_2 + 8  e_1 \otimes e_3 - 15  e_2\otimes e_1 + 24 e_2\otimes e_3 + 10  e_3\otimes e_1 + 4  e_3\otimes e_2}
$$

How do I reconcile these two results?

NB: This is impossible to reconcile as per the comments: A change of signs cannot relate $v\otimes w$ to $w\otimes v$ - the initial equations are not correct.

The second issue is reflected on my extended comment / "answer" below, and makes reference to the use of the Levi-Civita symbols seemingly undoing the usual change of signs when permuting wedge products...

The essential issue is that the LeviCivita symbols don't seem to naturally "handle" the basis of the wedge product, as well as they do, say, in the case of the cross product. How should the LC symbols be applied in the wedge product?
Comment: The formula stated in that answer is just plain wrong, as there is no way to use a sign to relate $v\otimes w$ and $w\otimes v$.
Comment: @AntoniParellada Yup, precisely.
Comment: What is "LC symbol"?
Comment: @lisyarus Levi Civita. Probably not standard.
Comment: @TedShifrin I gather from your comment that this would be the problem step in the [Physics.SE answer](https://physics.stackexchange.com/a/496815/150551) referenced above: $\begin{align}&\small{\frac{1}{2!}}\epsilon_{\mu\nu}(v^{\mu}\otimes w^{\nu}-w^{\nu}\otimes v^{\mu}) \\
 =& \epsilon_{\mu\nu}v^{\mu}\otimes w^{\nu}\end{align}.$
Answer: Let me dive a bit into two ways of looking at exterior products.
The first one, which is how I prefer it, is to view $v \wedge w$ as an element of the exterior square $\Lambda^2 V$ of the original vector space $V$ that contains vectors $v$ and $w$. It is a vector space of dimension ${\dim V \choose 2}=\frac{\dim V \cdot(\dim V-1)}{2}$ crafted specifically as the place where exterior products of 2 vectors live.
The second way, that is more common in classical differential geometry & physics, is to embed $\Lambda^2 V$ as a subspace of $V \otimes V$, namely the space of alternating (antisymmetric) tensors. The embedding looks like this:
$$v \wedge w \mapsto \frac{1}{2!}(v\otimes w - w \otimes v)$$
or like this
$$v \wedge w \mapsto v\otimes w - w \otimes v$$
Using these embeddings implicitly, one can view this as the definition of the wedge product, taking values in the space of alternating tensors, completely skipping the exterior square part.
Both embeddings seem to be in use in literature; the difference, as I see it, is only a matter of taste: some calculations get easier with the first embedding, and some with the second (unless we work over a field of scalars that has $\operatorname{char}\neq 0$).
It is not entirely clear to me whether you intend to use the first or the second embedding, and indeed this is precisely the reason I tend not to like the idea of identifying wedge products with alternating tensors. Once we work solely in $\Lambda^2 V$, everything is precisely defined.

As for calculating the wedge product of $v=1e_1+3e_2−2e_3$  and $w=5e_1+2e_2+8e_3$, using, say, the second embedding, one could go like this:
$$v \wedge w = v \otimes w - w \otimes v = \\
= (1e_1+3e_2−2e_3) \otimes (5e_1+2e_2+8e_3) - (5e_1+2e_2+8e_3) \otimes (1e_1+3e_2−2e_3) = \\
= \big[5e_1\otimes e_1 + 2e_1\otimes e_2+8e_1\otimes e_3+15e_2\otimes e_1+6e_2\otimes e_2+24e_2\otimes e_3-10e_3\otimes e_1-4e_3\otimes e_2-16e_3\otimes e_3\big] - \big[5e_1\otimes e_1+15e_1\otimes e_2-10e_1\otimes e_3+2e_2\otimes e_1+6e_2\otimes e_2-4e_2\otimes e_3+8e_3\otimes e_1+24e_3\otimes e_2-16e_3\otimes e_3\big] = \\
= -13e_1\otimes e_2+18e_1\otimes e_3+13e_2\otimes e_1+28e_2\otimes e_3-18e_3\otimes e_1-28e_3\otimes e_2 = \\
= -13(e_1\otimes e_2-e_2\otimes e_1)+28(e_2\otimes e_3-e_3\otimes e_2)-18(e_3\otimes e_1-e_1\otimes e_3) = \\
= -13e_1\wedge e_2 +28e_2\wedge e_3 - 18 e_3\wedge e_1$$

As for the linked physics.se answer, the crucial thing is that it works in 2 dimensions. Using the second embedding, we get
$$v \wedge w = (v^1w^2-v^2w^1) e_1 \wedge e_2$$
and since the wedge product of any two vectors is proportional to $e_1 \wedge e_2$, it is common to identify 2-vectors with numbers (see Hodge dual). In this case, dropping the $e_1 \wedge e_2$ part, we get
$$v \wedge w = \epsilon_{ij}v^iw^j$$
In general, the n-fold wedge product of n vectors is a multiple of $e_1 \wedge \dots \wedge e_n$ and is commonly identified with numbers; the wedge product can be computed using the Levi-Civita with n indices:
$$v_1 \wedge \dots \wedge v_n = \epsilon_{i_1\dots i_n}v_1^{i_1}v_2^{i_2}\dots v_n^{i_n}$$
which is actually the same as the determinant.
Comment: Your explanation is wonderful. I know you are being tactful or respectful, but it sounds as though you went to the Physics.SE [post](https://physics.stackexchange.com/a/496815/150551), and are a bit skeptical of that answer... Or is it that my attempt to mirror [your answer to a similar question](https://math.stackexchange.com/a/2842978/152225) failing at some fundamental level?
Comment: @AntoniParellada Thank you! Yes, I failed to understand what the physics.se post means. I have some ideas, though; I'll update the answer.
Comment: Would you go about calculating the RHS of the equation the same way I did in the OP, resulting in $2 e_1 \otimes e_2 + 8  e_1 \otimes e_3 - 15  e_2\otimes e_1 + 24 e_2\otimes e_3 + 10  e_3\otimes e_1 + 4  e_3\otimes e_2$?
Comment: @AntoniParellada Sure. I've updated the answer.
Comment: I really appreciate your effort to help with this problem, and I wonder if you could take it a bit farther, and look into the calculations in the equations on the Physics.SE referenced at the top of the OP, assuming that on the RHS of the equation the basis vectors are implied, as in [this post](https://math.stackexchange.com/a/1441801/152225).
Comment: For example, would it be possible to make sense of the initial set of equations in the question, and carry out the calculations with the two vectors $v$ and $w$ if we assume that $\frac{1}{2!}\epsilon_{\mu\nu}v^{\mu}\land w^{\nu}$ is $\frac{1}{2!}v^\mu w^\nu \epsilon_{\mu\nu} e_\mu\wedge e_\nu$?
Comment: See my "answer"/extended comments below...
Comment: @AntoniParellada I seem to have understood what the physics.se answer means; I updated the answer.
Comment: Did you incorporate Prof. Shifrin's comments?
Answer: I feel that the answer you copied, in order to point out some problems with it, on physics stack exchange, is not as bad as you think.  That answerer simply got mixed up between the notation of the O.P., $x^0$ and $x^1$ (passing to two Euclidean dimensions, as he did, which is a good pedagogic strategy), and his own, which was $v$ and $w$.  So, in context, it seems to me he means $x^0$ = v and $x^1$ =w.  This is another good pedagogic strategy since the superscripts on $dx^0$ do not indicate components at all.  But then he fell back into the superscripts, putting them on the v and w, which was just carelessness.  Since $w^1$ really means $v$, and $w^2$ means w, and $v^1$ means v, and $v^2$ means w, due to carelessness, the manipulation is justified by the usual splitting the sum into two sums and making a "change of variable" in one of them, which is what I think he intended, instead of "commuting", which as you and Prof. Shifrin point out, is invalid.
Indeed, you must see that he did not mean components, since you can't take the tensor product of components, so he couldn't have possibly really meant what he carelessly wrote.
I do feel that such carelessness is made less avoidable by the usual sloppy use of indices for two purposes: one, to enumerate the elements of a set, like the four elements of a basis set, and two, to enumerate the components of a vector, like the four components of a four-vector.  But this ambiguity is common, and one must get used to it, at least in Physics.
Comment: Thank you so much!
Answer: More like an extended comment...
If we assume that the RHS of the equation is really meant to signify
$$\frac{1}{2!}\epsilon_{\mu\nu}v^\mu w^\nu \, e_\mu\wedge e_\nu,$$
the only way I can see a way to use LeviCivita symbols is to establish basis vectors for the wedge product ahead of time, as in $\{e_1 \wedge e_2, \;e_2 \wedge e_3, \; e_1 \wedge e_3\}.$
Remembering that $v=1e_1+3e_2-2e_3$ and $w=5e_1+2e_2+8e_3,$
We can establish a parallel with the use of LC symbols in the cross product - and algebraically identical operation in 3-dim:
$$\begin{align}
v \times w &= \begin{vmatrix}3 &- 2\\2&8 \end{vmatrix} e_1 - \begin{vmatrix}1 &- 2\\5 &8 \end{vmatrix} e_2 + \begin{vmatrix}1 & 3\\5& 2 \end{vmatrix} e_3\\[2ex]
&= \epsilon_{ijk}\;v_i\,w_j\; e_k                                      \\[2ex]
&= \epsilon_{123} \;  1\cdot 2\;e_3 + \epsilon_{213}\; 3\cdot 5 \; e_3\\
&+ \epsilon_{132} \;  1\cdot 8\; e_2 + \epsilon_{312}\; (-2)\cdot 5 \; e_2 \\
&+ \epsilon_{231} \;  3\cdot 8\; e_1 + \epsilon_{321}\; (-2)\cdot 2 \; e_1                                                           \\[2ex]
&= 1 \;\cdot  2\;e_3 + (-1)\;\cdot 15 \; e_3\\
&-1 \;  \cdot 8\; e_2 + 1\; \cdot (-10) \; e_2 \\
&+ 1 \;  \cdot 24\; e_1 -1\; \cdot (-4) \; e_1                                                           \\[2ex]
&=28 \,e_1 -18 \, e_2 -13 \,e_3
\end{align}$$
If we can replace the basis vectors above with bivector basis $e_1\wedge e_2$ instead of $e_3;$ $e_2\wedge e_3$ for $e_1;$ and $e_1\wedge e_3,$ or even better, $e_3 \wedge e_1$ for $e_2, $ we end up with a strict correspondence of coefficients with correct sign. However, in the use of LC symbols for the crossproduct, we didn't have to arrange the basis vectors just so - the symbols took care of matching coefficients with the corresponding $e_1,$ $e_2$ or $e_3.$

I just don't see how this can be extrapolated to the wedge product...