问:
Why do I have to .bind(this) for methods defined in React component class, but not in regular ES6 class
Something that is puzzling me is why when I define a react component class, values contained in the this object are undefined in methods defined (this is available in lifecycle methods) within the class unless I use .bind(this) or define the method using an arrow function for example in the following code this.state will be undefined in the renderElements function because I did not define it with an arrow function and did not use .bind(this)

```<code>class MyComponent extends React.Component {
    constructor() {
        super();
        this.state = { elements: 5 }
    }

    renderElements() {
        const output = [];

        // In the following this.state.elements will be undefined
        // because I have not used  .bind(this) on this method in the constructor
        // example: this.renderElements = this.renderElements.bind(this)
        for(let i = 0; i < this.state.elements; i ++){
            output.push(<div key={i} />);
        }

        return output;
    }

    // .this is defined inside of the lifecycle methods and
    // therefore do not need call .bind(this) on the render method.
    render() {
        return (
            <div onClick={this.renderElements}></div>
        );
    }
}
</code>```

Then in the following example I do not need to use .bind(this) or an arrow function, this is available as expected in speak function

```<code>class Animal {
    constructor(name) {
        this.name = name;
    }

    speak() {
        console.log(this.name + ' makes a noise.');
    }
}

class Dog extends Animal {
    speak() {
        console.log(this.name + ' barks.');
    }
}

var d = new Dog('Mitzie');
d.speak();
</code>```

http://jsbin.com/cadoduxuye/edit?js,console

To clarify, my question is two part. One) why in the second code example  do I not need to call .bind(this) to the speak function, but I do in the React component for the renderElements function and Two) why do the lifecycle methods (render, componentDidMount, etc) already have access to the class' this object, but renderElements does not.

In the React docs it says the following

[React Component Class] Methods follow the same semantics as regular ES6 classes, meaning that they don't automatically bind this to the instance.

But clearly they do, as the second code example I've posted shows.

Update

Both links in the first two comments show a working example of React classes NOT using .bind(this) on class methods and it works fine. But still in the docs is explicitly says you need to bind your methods, or use an arrow function. In a project using gulp and babel I can reproduce. Could it mean browsers have updated things?

Update 2

My initial code example had this.renderElements() called directly in the render function. That would work as expected without binding the function, or defining it with an arrow function. The issue occurs when I put the function as an onClick handler.

Update 3

The issue occurs when I put the function as an onClick handler.

In fact it is not an issue at all. The context of this changes when passed to the onClick handler, so that's just how JS works.

答:
Just always put the autoBind(this); code in your constructor and never worry about method pointers.

npm install --save auto-bind-inheritance

```<code>const autoBind = require('auto-bind-inheritance');

class Animal {
  constructor(name) {
    autoBind(this);
    this.name = name;
  }

  printName() { console.log(this.name); }
  ...
}

let m = new Animal('dog');
let mpntr = m.printName;
m.printName() //> 'dog'
mpntr()       //> 'dog', because auto-bind, binds 'this' to the method.
</code>```

Body:
Something that is puzzling me is why when I define a react component class, values contained in the this object are undefined in methods defined (this is available in lifecycle methods) within the class unless I use .bind(this) or define the method using an arrow function for example in the following code this.state will be undefined in the renderElements function because I did not define it with an arrow function and did not use .bind(this)

class MyComponent extends React.Component {
    constructor() {
        super();
        this.state = { elements: 5 }
    }

    renderElements() {
        const output = [];

        // In the following this.state.elements will be undefined
        // because I have not used  .bind(this) on this method in the constructor
        // example: this.renderElements = this.renderElements.bind(this)
        for(let i = 0; i < this.state.elements; i ++){
            output.push(
);
        }

        return output;
    }

    // .this is defined inside of the lifecycle methods and
    // therefore do not need call .bind(this) on the render method.
    render() {
        return (

        );
    }
}

Then in the following example I do not need to use .bind(this) or an arrow function, this is available as expected in speak function

class Animal {
    constructor(name) {
        this.name = name;
    }

    speak() {
        console.log(this.name + ' makes a noise.');
    }
}

class Dog extends Animal {
    speak() {
        console.log(this.name + ' barks.');
    }
}

var d = new Dog('Mitzie');
d.speak();

http://jsbin.com/cadoduxuye/edit?js,console

To clarify, my question is two part. One) why in the second code example  do I not need to call .bind(this) to the speak function, but I do in the React component for the renderElements function and Two) why do the lifecycle methods (render, componentDidMount, etc) already have access to the class' this object, but renderElements does not.

In the React docs it says the following

[React Component Class] Methods follow the same semantics as regular ES6 classes, meaning that they don't automatically bind this to the instance.

But clearly they do, as the second code example I've posted shows.

Update

Both links in the first two comments show a working example of React classes NOT using .bind(this) on class methods and it works fine. But still in the docs is explicitly says you need to bind your methods, or use an arrow function. In a project using gulp and babel I can reproduce. Could it mean browsers have updated things?

Update 2

My initial code example had this.renderElements() called directly in the render function. That would work as expected without binding the function, or defining it with an arrow function. The issue occurs when I put the function as an onClick handler.

Update 3

The issue occurs when I put the function as an onClick handler.

In fact it is not an issue at all. The context of this changes when passed to the onClick handler, so that's just how JS works.

Body:
Just always put the autoBind(this); code in your constructor and never worry about method pointers.

npm install --save auto-bind-inheritance

const autoBind = require('auto-bind-inheritance');

class Animal {
  constructor(name) {
    autoBind(this);
    this.name = name;
  }

  printName() { console.log(this.name); }
  ...
}

let m = new Animal('dog');
let mpntr = m.printName;
m.printName() //> 'dog'
mpntr()       //> 'dog', because auto-bind, binds 'this' to the method.


来源: stackexchange

问:
NPV and IRR in Spotfire 7.6
I'm aware that NPV and IRR are possible in Spotfire 7.7 using TERR Agg functions.

I have a data file with cash-flows and associated dates. I need to be able to select sub-sets of that data set and calculate a live NPV / IRR result.

Does anyone have a work-around to do this in 7.6?

答:
We have time series data with cashflow as well.  I calculate a new column that discounts every value and then sums and aggregates those as needed for the NPV calculation.

Simple calc column :

```<code>[Cashflow ($M)] / (1.1 ^ (Year([Date]) - 2018))
</code>```

We discount at a 10% rate.
My understanding is that you need to use TERR for IRR. A good post on it is here:

https://community.tibco.com/questions/i-am-new-spotfire-and-am-trying-setup-dynamic-irr-calculation-given-cashflows-i-want-be

ContentLicense: CC BY-SA 3.0

Title: NPV and IRR in Spotfire 7.6

Body:
We have time series data with cashflow as well.  I calculate a new column that discounts every value and then sums and aggregates those as needed for the NPV calculation.

Simple calc column :

[Cashflow ($M)] / (1.1 ^ (Year([Date]) - 2018))

We discount at a 10% rate.
My understanding is that you need to use TERR for IRR. A good post on it is here:

https://community.tibco.com/questions/i-am-new-spotfire-and-am-trying-setup-dynamic-irr-calculation-given-cashflows-i-want-be


问:
Dictionary initialization syntax
```<code>def __init__(self, devices, queue):
    '''
    '''
    self.devices = devices
    self.queue = queue

    values = {k:0 for k in devices.keys()}
    values[0xbeef] = len(values) # the number of devices
    super(CallbackDataBlock, self).__init__(values)
</code>```

Can someone help me explain the following two lines:

values = {k:0 for k in devices.keys()}

What does k:0 do?

values[0xbeef] = len(values) # the number of devices

Does this mean that new item {0xbeef: length} is appended in the dict?

答: {k:0 for k in devices.keys()} creates a dictionary with all keys and 0 for all values. And your assessment is correct, it creates a new key with {value of 0xbeef : number of keys in the dictionary}

Title: Dictionary initialization syntax

Body:
def __init__(self, devices, queue):
    '''
    '''
    self.devices = devices
    self.queue = queue

    values = {k:0 for k in devices.keys()}
    values[0xbeef] = len(values) # the number of devices
    super(CallbackDataBlock, self).__init__(values)

Can someone help me explain the following two lines:

values = {k:0 for k in devices.keys()}

What does k:0 do?

values[0xbeef] = len(values) # the number of devices

Does this mean that new item {0xbeef: length} is appended in the dict?


问:
Android Binding strategy, should the adapter do the work, or the view?
I'm not sure if this is just something that is up to developer opinion but I am creating an android app and have a Listview that displays a custom view.  My layout basically consists of a View (as an xml resource file and a class that derives from the view that is the root), a Domain Model object (has the data to be bound to the view) and an adapter which derives from BaseAdapter that binds the data from the Domain Model to the View in the getViewMethod as follows:

Model: SampleItem

Custom View: SampleView

Adapter: (code below)

```<code>   public View getView(int position, View convertView, ViewGroup parent) {
  SampleView sampleView;

  SampleItem item = (SampleItem)getItem(position);

  if(convertView == null) {
   sampleView = new SampleView(_context);
  }
  else {
   sampleView = (SampleView)convertView;
  }

  sampleView.setTitle(item.getTitle());
  sampleView.setContentText(item.getContent());
  sampleView.setItemRowNumer(item.getRowNumber());
  ... //etc
  return sampleView;
}
</code>```

This is how I've always seen it done, but I wonder is this the right way to do it.

My thought, coming from a different approach to data binding, is that the actual view class doesn't have a concept of what it's model is, and diverting the control to how data is bound to it to an adapter class that may not exist if moved elsewhere.

I was thinking that the custom view class has a reference to the object that is bound to it and in it's  constructor it populates the view based on the data.  So the adapter is essentially a shell class that only does this:

```<code>   public View getView(int position, View convertView, ViewGroup parent) {
  SampleView sampleView;

  SampleItem item = (SampleItem)getItem(position);

  if(convertView == null) {
   sampleView = new SampleView(_context, item);
  }
  else {
   sampleView = (SampleView)convertView;
  }

  return sampleView;
 }
</code>```

And the actual constructor for the view would know its model and populate itself as opposed to the Adapter doing work that seems outside of it's responsibility.

答:
The adapter should do it. Two reasons.

1) CursorAdapter#bindView: it's defined in the framework. It's idiomatic and it will be what other android programmers would expect to see while reading your code. IMHO keeping things idiomatic improves code maintenance and legibility.

2) The way AdapterView classes work in android is that they reuse the Views returned from the adapter. This is so that a lot of new objects aren't created during scroll/flick/etc. animations and UI events. In order for that to work the AdapterView passes that View back to the adapter and expects that view to be reused. IMHO the intention and expectation is for the Adapter to handle updating and rebinding that View. If you attempt your method and keep the binding in the Views constructor then the only time data binding would happen would be in the constructor. You would then need to move that binding into a separate function possibly cluttering the class interface and with inheritance getting into other problems.

For me, I prefer that a View only care about how to display something. That's all the responsibilities I really want it to worry about. I think that's enough since some views can become quite complex. I like to leave it to other classes to worry about telling the View what it should be displaying and where that data should be coming from. Sometimes this means very simple bindings, i.e., calling toString() multiple times in a row. However, it decouples the data that is being displayed from the underling data which allows for one to change with the possibility of reusing the other.

ContentLicense: CC BY-SA 2.5

Body:
I'm not sure if this is just something that is up to developer opinion but I am creating an android app and have a Listview that displays a custom view.  My layout basically consists of a View (as an xml resource file and a class that derives from the view that is the root), a Domain Model object (has the data to be bound to the view) and an adapter which derives from BaseAdapter that binds the data from the Domain Model to the View in the getViewMethod as follows:

Model: SampleItem

Custom View: SampleView

Adapter: (code below)

   public View getView(int position, View convertView, ViewGroup parent) {
  SampleView sampleView;

  SampleItem item = (SampleItem)getItem(position);

  if(convertView == null) {
   sampleView = new SampleView(_context);
  }
  else {
   sampleView = (SampleView)convertView;
  }

  sampleView.setTitle(item.getTitle());
  sampleView.setContentText(item.getContent());
  sampleView.setItemRowNumer(item.getRowNumber());
  ... //etc
  return sampleView;
}

This is how I've always seen it done, but I wonder is this the right way to do it.

My thought, coming from a different approach to data binding, is that the actual view class doesn't have a concept of what it's model is, and diverting the control to how data is bound to it to an adapter class that may not exist if moved elsewhere.

I was thinking that the custom view class has a reference to the object that is bound to it and in it's  constructor it populates the view based on the data.  So the adapter is essentially a shell class that only does this:

   public View getView(int position, View convertView, ViewGroup parent) {
  SampleView sampleView;

  SampleItem item = (SampleItem)getItem(position);

  if(convertView == null) {
   sampleView = new SampleView(_context, item);
  }
  else {
   sampleView = (SampleView)convertView;
  }

  return sampleView;
 }

And the actual constructor for the view would know its model and populate itself as opposed to the Adapter doing work that seems outside of it's responsibility.


问:
Turn a lazy graph into a strict graph without mutation - OCaml
Assume I have a (directed) graph with nodes of type

```<code>type lazy_node_t = LazyNode of int * lazy_node_t Lazy.t list;;
</code>```

where the first int is an arbitrary tag, and the list is a list of lazy nodes accessible from the current node.

Is there any way I can turn this into a graph of type node_t = Node of int * node_t list, without using any mutable values? I realize it's possible using arrays, for instance.

Thanks!

答: If you can bind names to all the nodes in your result you can create cyclic structures with let rec. For the general case, you can't give names to all the nodes. So there's no way to make a cyclic structure without mutability. This, at least, is what I've concluded.

Body:
Assume I have a (directed) graph with nodes of type

type lazy_node_t = LazyNode of int * lazy_node_t Lazy.t list;;

where the first int is an arbitrary tag, and the list is a list of lazy nodes accessible from the current node.

Is there any way I can turn this into a graph of type node_t = Node of int * node_t list, without using any mutable values? I realize it's possible using arrays, for instance.

Thanks!


问:
Difference between inline operation and calculate before operation in foreach
I make it simple (because i didn't find anything on Google, maybe because i don't know either what search).

What is the difference beetween this:

```<code>foreach(var x in g.GetList())
{
 code
}
</code>```

and this:

```<code>IEnumerable<object> list = g.GetList();
foreach(var x in list)
{
 code
}
</code>```

in terms of performance or in terms of best practices, or whatever?

答:
These two pieces of code:

```<code>foreach(var x in g.GetList())
{
 code
}
</code>```

and

```<code>IEnumerable<object> list = g.GetList();
foreach(var x in list)
{
 code
}
</code>```

have only 1 difference, and that is that you placed the result of calling g.GetList() into a variable yourself.

IL-wise, what the compiler outputs, when you compile for RELEASE mode, will be 100% identical.

Here's a sample LINQPad program:

```<code>void Main() {  }

static void Method1()
{
    foreach (var x in g.GetList()) { }
}

static void Method2()
{
    IEnumerable<object> list = g.GetList();
    foreach (var x in list) { }
}

static class g
{
    public static IEnumerable<object> GetList() => new List<object>();
}
</code>```

will produce this IL code for both Method1 and Method2:

```<code>IL_0000:  call        UserQuery+g.GetList
IL_0005:  callvirt    System.Collections.Generic.IEnumerable<System.Object>.GetEnumerator
IL_000A:  stloc.0
IL_000B:  br.s        IL_0014
IL_000D:  ldloc.0
IL_000E:  callvirt    System.Collections.Generic.IEnumerator<System.Object>.get_Current
IL_0013:  pop
IL_0014:  ldloc.0
IL_0015:  callvirt    System.Collections.IEnumerator.MoveNext
IL_001A:  brtrue.s    IL_000D
IL_001C:  leave.s     IL_0028
IL_001E:  ldloc.0
IL_001F:  brfalse.s   IL_0027
IL_0021:  ldloc.0
IL_0022:  callvirt    System.IDisposable.Dispose
IL_0027:  endfinally
IL_0028:  ret
</code>```

So there is no difference other than how you wrote the code.

Body:
I make it simple (because i didn't find anything on Google, maybe because i don't know either what search).

What is the difference beetween this:

foreach(var x in g.GetList())
{
 code
}

and this:

IEnumerable<object> list = g.GetList();
foreach(var x in list)
{
 code
}

in terms of performance or in terms of best practices, or whatever?

Body:
These two pieces of code:

foreach(var x in g.GetList())
{
 code
}

and

IEnumerable<object> list = g.GetList();
foreach(var x in list)
{
 code
}

have only 1 difference, and that is that you placed the result of calling g.GetList() into a variable yourself.

IL-wise, what the compiler outputs, when you compile for RELEASE mode, will be 100% identical.

Here's a sample LINQPad program:

void Main() {  }

static void Method1()
{
    foreach (var x in g.GetList()) { }
}

static void Method2()
{
    IEnumerable<object> list = g.GetList();
    foreach (var x in list) { }
}

static class g
{
    public static IEnumerable<object> GetList() => new List<object>();
}

will produce this IL code for both Method1 and Method2:

IL_0000:  call        UserQuery+g.GetList
IL_0005:  callvirt    System.Collections.Generic.IEnumerable<System.Object>.GetEnumerator
IL_000A:  stloc.0
IL_000B:  br.s        IL_0014
IL_000D:  ldloc.0
IL_000E:  callvirt    System.Collections.Generic.IEnumerator<System.Object>.get_Current
IL_0013:  pop
IL_0014:  ldloc.0
IL_0015:  callvirt    System.Collections.IEnumerator.MoveNext
IL_001A:  brtrue.s    IL_000D
IL_001C:  leave.s     IL_0028
IL_001E:  ldloc.0
IL_001F:  brfalse.s   IL_0027
IL_0021:  ldloc.0
IL_0022:  callvirt    System.IDisposable.Dispose
IL_0027:  endfinally
IL_0028:  ret

So there is no difference other than how you wrote the code.


问:
Find sum, difference, etc. for two numbers in C while user don't exit
I need to find the sum, diff, etc for two numbers that user input. But program first displays the menu, after that ask a user to input those numbers and do the operation. After that, it should ask a user if want to calculate something again, and if they want did it want with the old numbers or new.

I'm a total beginner at C, so I need a help with a few thing.
I got an error at Cases :

cfinal.c:49:14: warning: multi-character character constant
  [-Wmultichar]

And this one:

cfinal.c:49:14: warning: overflow converting case value to switch
  condition
            type (21075 to 83) [-Wswitch]

There is something wrong and I can't figure it out.
And the second problem is that I need to ask the user if they want to repeat all over again and if they choose Yes, did they want to do it with the new numbers or numbers used in previously calculation.
That's something I didn't even start, I don't know how.
Thanks.

Code I've so far:

```<code>#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>

int main (void)
{
    char choice;                //Define choice character type
    int first_number, second_number, firstSquare, secondSquare, firstQube, secondQube, cont;  //define intigers
    printf("Select operation you would like to do by typing shortcut:\n");
    printf("SU - sum\n");
    printf("DI - difference\n");
    printf("MU - multiplication\n");
    printf("RA - ratio\n");
    printf("SS - Sum of Squares\n");
    printf("SQ - Sum of Qubes\n");
    printf("RS - Sum of Squares\n");
    printf("RQ - Sum of Qubes\n");
    choice = (char)toupper(getchar());
    getchar ();
    printf("Enter the first number: ");
    scanf("%d", &first_number);
    getchar ();
    printf("Enter the second number:");
    scanf("%d", &second_number);
    getchar ();
    firstSquare = first_number * first_number;
    secondSquare = second_number * second_number;
    firstQube = first_number * first_number * first_number;
    secondQube = second_number * second_number * second_number;
    printf("\n");
    printf("Result is");
    switch(choice)
    {
        case 'SU':
            printf("%d + %d = %d", first_number, second_number, first_number + second_number);
            break;
        case 'DI':
            printf("%d - %d = %d", first_number, second_number, first_number - second_number);
            break;
        case 'MU':
            printf("%d * %d = %d", first_number, second_number, first_number * second_number);
            break;
        case 'SS':
            printf("%d * %d + %d * %d = %d", first_number, first_number, second_number, second_number);
            break;
        case 'SQ':
            printf("%d * %d * %d + %d * %d * %d = %d", first_number, first_number, first_number, second_number, second_number, second_number, firstQube + secondQube);
            break;
        case 'RS':
            printf("(%d * %d) / (%d * %d) = %d", first_number, first_number, second_number, second_number, firstSquare / secondSquare);
            break;
        case 'RQ':
            printf("(%d * %d * %d) / (%d * %d * %d) = %f", first_number, first_number, first_number, second_number, second_number, second_number, firstQube / secondQube);
            break;
        case 'RA':
            if (second_number == 0)
                fprintf(stderr, "The divisor can't be 0");
            else
            {
                printf("%d / %d = %f", first_number, second_number, (double)first_number / second_number);
            }
            break;
        default :
            fprintf(stderr, "Invalid entry");
            break;
    }
    printf("\n");
    for (;;)
    {
      printf("Continue (Type Y for yes or N for no)? ");
      cont = toupper(getchar());
      getchar ();
      if (cont == 'Y')
          return main(); // the difference.
      else if (cont == 'N')
          return EXIT_SUCCESS;
    }
}
</code>```

答:
getchar returns a single character. if you want to use string 'xy', 'd99' etc you will have to read a string. How to read a line from the console in C?

Second you cannot switch on a string you need to do

```<code>if(strcmp(input,"SU")==0)
{
....
}
else if (strcmp(input, "DQ") == 0)
{
}
...
else
{
... error
</code>```

}

Body:
I need to find the sum, diff, etc for two numbers that user input. But program first displays the menu, after that ask a user to input those numbers and do the operation. After that, it should ask a user if want to calculate something again, and if they want did it want with the old numbers or new.

I'm a total beginner at C, so I need a help with a few thing.
I got an error at Cases :

cfinal.c:49:14: warning: multi-character character constant
  [-Wmultichar]

And this one:

cfinal.c:49:14: warning: overflow converting case value to switch
  condition
            type (21075 to 83) [-Wswitch]

There is something wrong and I can't figure it out.
And the second problem is that I need to ask the user if they want to repeat all over again and if they choose Yes, did they want to do it with the new numbers or numbers used in previously calculation.
That's something I didn't even start, I don't know how.
Thanks.

Code I've so far:

#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>

int main (void)
{
    char choice;                //Define choice character type
    int first_number, second_number, firstSquare, secondSquare, firstQube, secondQube, cont;  //define intigers
    printf("Select operation you would like to do by typing shortcut:\n");
    printf("SU - sum\n");
    printf("DI - difference\n");
    printf("MU - multiplication\n");
    printf("RA - ratio\n");
    printf("SS - Sum of Squares\n");
    printf("SQ - Sum of Qubes\n");
    printf("RS - Sum of Squares\n");
    printf("RQ - Sum of Qubes\n");
    choice = (char)toupper(getchar());
    getchar ();
    printf("Enter the first number: ");
    scanf("%d", &first_number);
    getchar ();
    printf("Enter the second number:");
    scanf("%d", &second_number);
    getchar ();
    firstSquare = first_number * first_number;
    secondSquare = second_number * second_number;
    firstQube = first_number * first_number * first_number;
    secondQube = second_number * second_number * second_number;
    printf("\n");
    printf("Result is");
    switch(choice)
    {
        case 'SU':
            printf("%d + %d = %d", first_number, second_number, first_number + second_number);
            break;
        case 'DI':
            printf("%d - %d = %d", first_number, second_number, first_number - second_number);
            break;
        case 'MU':
            printf("%d * %d = %d", first_number, second_number, first_number * second_number);
            break;
        case 'SS':
            printf("%d * %d + %d * %d = %d", first_number, first_number, second_number, second_number);
            break;
        case 'SQ':
            printf("%d * %d * %d + %d * %d * %d = %d", first_number, first_number, first_number, second_number, second_number, second_number, firstQube + secondQube);
            break;
        case 'RS':
            printf("(%d * %d) / (%d * %d) = %d", first_number, first_number, second_number, second_number, firstSquare / secondSquare);
            break;
        case 'RQ':
            printf("(%d * %d * %d) / (%d * %d * %d) = %f", first_number, first_number, first_number, second_number, second_number, second_number, firstQube / secondQube);
            break;
        case 'RA':
            if (second_number == 0)
                fprintf(stderr, "The divisor can't be 0");
            else
            {
                printf("%d / %d = %f", first_number, second_number, (double)first_number / second_number);
            }
            break;
        default :
            fprintf(stderr, "Invalid entry");
            break;
    }
    printf("\n");
    for (;;)
    {
      printf("Continue (Type Y for yes or N for no)? ");
      cont = toupper(getchar());
      getchar ();
      if (cont == 'Y')
          return main(); // the difference.
      else if (cont == 'N')
          return EXIT_SUCCESS;
    }
}

Body:
getchar returns a single character. if you want to use string 'xy', 'd99' etc you will have to read a string. How to read a line from the console in C?

Second you cannot switch on a string you need to do

if(strcmp(input,"SU")==0)
{
....
}
else if (strcmp(input, "DQ") == 0)
{
}
...
else
{
... error

}


问:
Can I store the same option value for more than one toggle button in a control box?
I have a list of questions each with 4 possible answers that are displayed as toggle buttons on my form. What I want to do is if the user chooses either of the first two buttons, the Option Value stored is "1", if they choose either of the last two buttons, the Option Value stored should be "0". The option values must be different for each toggle button in a control group. Is there a way to recode the toggle buttons to store the desired response? (I work in psychology, thus the bait and switch of offering 4 choices to the user when really only two responses are recorded).

Here is what I have tried:

I tried thinking about a recode as jcarroll suggested, but this is a circular reference:

```<code>Private Sub Q1_Click()
If Me.Q1 = 1 Or 2 Then
Me.Q1 = 1
Else:
Me.Q1 = 0
End If
End Sub
</code>```

I could recode into another variable but that is just as clunky as using a SQL statement on the data post-hoc, for instance:

NewVariable=Iif([Q1]=1,1,iif([Q1]=2,1,0)

Finally, I tried to code have both toggle buttons have the same Option Value (which causes both to look pressed if either is pressed) and recode the unpressed toggle button's back color. But while my code looks correct to me, this did not change the pressed color of the toggle button (which I think has to do with over riding toggle button design settings):

```<code>Private Sub Frame5_Click()
If Toggle8.Value = True Then
Toggle9.BackColor = &HFF00&
Else
Toggle9.BackColor = &H8000000F
End If
End Sub
</code>```

答:
I could not come up with any programming solutions on the form itself to solve this. The alternative is that I wrote a procedure to apply to the data after it is collected which will be stored as 1,2,3,4 to convert it to 0 or 1. This procedure also sums up the 1's. I have 50 variables/questions that will be passed through this procedure (as well as another like it that converts 3&4 to 1).</p>

```<code>Public Function Recode1(ParamArray arg()) As Variant
Dim Size As Integer, skips As Integer, i As Integer, result As Variant
'Recodes first two toggle buttons as "1" for AQ assessment

Size = UBound(arg) + 1

For i = 0 To Size - 1

If IsNull(arg(i)) Or Not (IsNumeric(arg(i))) Or arg(i) = -99 Then
skips = skips + 1
Else
If arg(i) = 1 Or arg(i) = 2 Then
result = result + 1
Else:
result = result + 0
End If
End If
End sub
</code>```

Body:
I have a list of questions each with 4 possible answers that are displayed as toggle buttons on my form. What I want to do is if the user chooses either of the first two buttons, the Option Value stored is "1", if they choose either of the last two buttons, the Option Value stored should be "0". The option values must be different for each toggle button in a control group. Is there a way to recode the toggle buttons to store the desired response? (I work in psychology, thus the bait and switch of offering 4 choices to the user when really only two responses are recorded).

Here is what I have tried:

I tried thinking about a recode as jcarroll suggested, but this is a circular reference:

Private Sub Q1_Click()
If Me.Q1 = 1 Or 2 Then
Me.Q1 = 1
Else:
Me.Q1 = 0
End If
End Sub

I could recode into another variable but that is just as clunky as using a SQL statement on the data post-hoc, for instance:

NewVariable=Iif([Q1]=1,1,iif([Q1]=2,1,0)

Finally, I tried to code have both toggle buttons have the same Option Value (which causes both to look pressed if either is pressed) and recode the unpressed toggle button's back color. But while my code looks correct to me, this did not change the pressed color of the toggle button (which I think has to do with over riding toggle button design settings):

Private Sub Frame5_Click()
If Toggle8.Value = True Then
Toggle9.BackColor = &HFF00&
Else
Toggle9.BackColor = &H8000000F
End If
End Sub

Body:
I could not come up with any programming solutions on the form itself to solve this. The alternative is that I wrote a procedure to apply to the data after it is collected which will be stored as 1,2,3,4 to convert it to 0 or 1. This procedure also sums up the 1's. I have 50 variables/questions that will be passed through this procedure (as well as another like it that converts 3&4 to 1).

Public Function Recode1(ParamArray arg()) As Variant
Dim Size As Integer, skips As Integer, i As Integer, result As Variant
'Recodes first two toggle buttons as "1" for AQ assessment

Size = UBound(arg) + 1

For i = 0 To Size - 1

If IsNull(arg(i)) Or Not (IsNumeric(arg(i))) Or arg(i) = -99 Then
skips = skips + 1
Else
If arg(i) = 1 Or arg(i) = 2 Then
result = result + 1
Else:
result = result + 0
End If
End If
End sub


答:
If you mean literally elements of exactly value 0, then yes, you can do what you suggested in the question. Note that when testing these operations for multi-dimensional arrays, it can sometimes help to simplify by working with 1d arrays:

```<code>>>> a = np.array([1, 2, 4, 0, 1, 0, 7, 0], dtype="float32")
>>> a[a==0] = 1
>>> a
array([ 1.,  2.,  4.,  1.,  1.,  1.,  7.,  1.], dtype=float32)
</code>```

As first mentioned by @Divikar, you can use np.isclose to get rid of the errors caused by the floats.

Title: Numpy boolean masking -- multidimension and floats

Body:
I have a huge 4 dimensional array, but for this example I will use a 3-dimenisonal array, x.

The array is of type float.

I'm trying to use boolean masking to locate specific numbers and then change those numbers to another number.

However, it seems I'm unable to locate some float numbers despite them being a
element in my array 'x'

x is a 32,32,3 array

Here is how a portion of my x array  looks like :

>>> x

array([[[ -71.71074,  -74.05614,  -69.5538 ],
        [ -87.14036,  -89.44238,  -86.85358],
        [ -81.05044,  -88.24616,  -89.58144],
        ...,
        [  26.94098,   -4.307  ,  -24.44078],
        [  21.60692,  -10.70848,  -30.00036],
        [  17.826  ,  -11.4736 ,  -28.89246]],

       [[-114.0993 , -115.29484, -111.36412],
        [-129.3446 , -134.45914, -130.4656 ],
        [-112.2169 , -127.1767 , -131.10234],
        ...,
        [  -7.04254,  -47.13862,  -75.90018],
        [ -10.33038,  -51.55898,  -80.49918],
        [  -7.1568 ,  -47.38368,  -73.45104]],

       [[-104.72472, -110.64818, -109.2514 ],
        [-112.71662, -126.49748, -129.01922],
        [ -80.47348, -107.05546, -121.47586],
        ...,
        [ -11.21066,  -49.95824,  -79.29398],
        [  -8.59094,  -49.54152,  -79.06528],
        [ -19.59134,  -60.55772,  -87.22356]],

       ...,
       [[  81.44628,   44.0467 ,  -18.1421 ],
        [  76.41156,   29.2665 ,  -77.77894],
        [  74.07492,   38.1989 ,  -84.73544],
        ...,
        [  35.75964,    9.99658,  -40.87088],
        [ -68.68902,  -92.7463 , -104.75116],
        [ -72.51674,  -90.86008,  -93.10554]],

       [[  52.9319 ,   12.62384,  -18.64896],
        [  47.53098,   -1.58318,  -70.6934 ],
        [  60.71512,   19.8131 ,  -82.16812],
        ...,
        [  58.50748,   23.66242,  -18.25642],
        [ -28.58606,  -62.64844,  -78.71842],
        [ -42.9967 ,  -72.2858 ,  -79.60626]],

       [[  49.26526,   17.05222,    0.55436],
        [  41.40204,    3.34674,  -19.9712 ],
        [  52.13484,   16.24322,  -26.9406 ],
        ...,
        [  89.22164,   58.30292,   26.16942],
        [  24.43504,   -7.61742,  -29.90624],
        [  -3.63908,  -33.8503 ,  -42.38186]]])

So I picked numbers within this array and see if I could locate them using boolean masking. However, only some numbers were located:

This located the element:

>>> x[x==60.71512]
array([ 60.71512])

However, this didn't locate the element

>>> x[x==-28.58606]
array([], dtype=float64)

#empty array result despite being an element within my array

I'm confused by this behavior.

My ultimate goal is to locate all 0 elements within my 4-dimensional arrays and
convert them .1.

y is my 4-dimesional array (holding images)

I was assuming y[y==0] = .1 would work, but now do the strange behavior above,
I'm not sure if the empty arrays I'm getting are due to the behavior above or due to there not actually being zeros in my array.

Also, since I"m dealing with floats, should it be y[y==0.00]?

Body:
If you mean literally elements of exactly value 0, then yes, you can do what you suggested in the question. Note that when testing these operations for multi-dimensional arrays, it can sometimes help to simplify by working with 1d arrays:

>>> a = np.array([1, 2, 4, 0, 1, 0, 7, 0], dtype="float32")
>>> a[a==0] = 1
>>> a
array([ 1.,  2.,  4.,  1.,  1.,  1.,  7.,  1.], dtype=float32)

As first mentioned by @Divikar, you can use np.isclose to get rid of the errors caused by the floats.


问:
Add extra icons to rocksolid icon picker
Hi I need to add extra icons to rocksolid icon sets. I follwed the instructions in https://rocksolidthemes.com/de/contao/blog/iconfont-anpassen-icons-hinzufuegen and successfully downloaded the new icon set and copied to the desired folder. But the new icons are not showing in the picker. I need to know whether the new icons were lost when the rocksolid is upgraded? If yes, what is the remedy for this? Can I add more than one icon files in the configuration?</p>

答:
But the new icons are not showing in the picker.

This is probably a caching problem. Please try to delete all browser cache after replacing the font files in the template directory. Further make sure the new font files have the same font names as the original files ("replace" the original files in the template font folder). You also have to update/replace the font css file as stated at the end of the linked article:

Roughly translated: "To see the new icons in Icon Picker copy the file style.css of the downloaded font packet to the font folder of your template and rename it to rocksolid-icons.css. Delete rocksolid-icons.html if this file exists."

I need to know whether the new icons were lost when the rocksolid is upgraded

The font files are part of the template and included in the template folder. So you should make a backup of the template folder before updating to a newer version of the used rocksolid template. After updating the rocksolid template you can again replace the font files and css within the template folder to get your own icons back in place...


问:
How to call a function a certain time after a web service has been called?
How to call a function a certain time after a web service has been called?

I need to check if a request has been accepted 30s after the request has been created, something like that:

```<code>public function create_request(Request $request)
{
    $user_id = $request->id;

    $validator = Validator::make(
        $request->all(),
        array(
            'request_id' => 'required|numeric|exists:requests,id,user_id,' . $user_id,
        ));

    // Create Request
    $requests = new Requests;
    $requests->user_id = $user_id;

    if ($request->service_type)
        $requests->request_type = $request->service_type;

    $requests->status = REQUEST_NEW;
    $requests->confirmed_provider = $request->provider_id;
    $requests->request_start_time = date("Y-m-d H:i:s");
    $requests->s_address = $request->s_address ? $request->s_address : "";

    if ($request->s_latitude) {
        $requests->s_latitude = $request->s_latitude;
    }
    if ($request->s_longitude) {
        $requests->s_longitude = $request->s_longitude;
    }

    $requests->save();

    sleep(30);

    $request = Requests::where('id', '=', $request->request_id)->first();

    if ($request['provider_status'] == 0) {
        Requests::where('id', '=', $request['id'])->delete();
        $response_array = array('success' => true , 'message' => Helper::get_message(121));
    } else {
        $response_array = array('success' => false, 'error' => Helper::get_error_message(161), 'error_code' => 132);
    }

    return response()->json($response_array, 200);

}
</code>```

The problem with this approach is that the sleep function (sleep(30);) is causing the web service response (return response()->json($response_array, 200);) to be delayed too.

I was expecting something similar to setTimeout(function(){ alert("Hello"); }, 30000); in Javascript

答:
I would create a separate background process to check if $requests->save() was done for the request.

Because it's a separate process you have to save something in persistant storage like a database, and have a way to identify it.

You would run the script like this

```<code>  exec('php script.php arg1 > /dev/null &')
</code>```

This will run script.php non-blocking, which means the current script will continue on without waiting for response from exec. arg1 will show up in the $_SERVER array as argv with the first argument being the name of the running script.

In that script you would delay for 30's then do your check.

No problem.

Windows is a bit more complicated for a non-blocking script. But it can be done using wScript.Shell

```<code>$wShell = new \COM('WScript.Shell');
$cmd = 'cmd /C php script.php arg1';
$oExec = $wShell->Run($cmd, 0, false);
</code>```

Body:
How to call a function a certain time after a web service has been called?

I need to check if a request has been accepted 30s after the request has been created, something like that:

public function create_request(Request $request)
{
    $user_id = $request->id;

    $validator = Validator::make(
        $request->all(),
        array(
            'request_id' => 'required|numeric|exists:requests,id,user_id,' . $user_id,
        ));

    // Create Request
    $requests = new Requests;
    $requests->user_id = $user_id;

    if ($request->service_type)
        $requests->request_type = $request->service_type;

    $requests->status = REQUEST_NEW;
    $requests->confirmed_provider = $request->provider_id;
    $requests->request_start_time = date("Y-m-d H:i:s");
    $requests->s_address = $request->s_address ? $request->s_address : "";

    if ($request->s_latitude) {
        $requests->s_latitude = $request->s_latitude;
    }
    if ($request->s_longitude) {
        $requests->s_longitude = $request->s_longitude;
    }

    $requests->save();

    sleep(30);

    $request = Requests::where('id', '=', $request->request_id)->first();

    if ($request['provider_status'] == 0) {
        Requests::where('id', '=', $request['id'])->delete();
        $response_array = array('success' => true , 'message' => Helper::get_message(121));
    } else {
        $response_array = array('success' => false, 'error' => Helper::get_error_message(161), 'error_code' => 132);
    }

    return response()->json($response_array, 200);

}

The problem with this approach is that the sleep function (sleep(30);) is causing the web service response (return response()->json($response_array, 200);) to be delayed too.

I was expecting something similar to setTimeout(function(){ alert("Hello"); }, 30000); in Javascript

Body:
I would create a separate background process to check if $requests->save() was done for the request.

Because it's a separate process you have to save something in persistant storage like a database, and have a way to identify it.

You would run the script like this

  exec('php script.php arg1 > /dev/null &')

This will run script.php non-blocking, which means the current script will continue on without waiting for response from exec. arg1 will show up in the $_SERVER array as argv with the first argument being the name of the running script.

In that script you would delay for 30's then do your check.

No problem.

Windows is a bit more complicated for a non-blocking script. But it can be done using wScript.Shell

$wShell = new \COM('WScript.Shell');
$cmd = 'cmd /C php script.php arg1';
$oExec = $wShell->Run($cmd, 0, false);


问:
Killing processes opened with popen()?
I'm opening a long-running process with popen().  For debugging, I'd like to terminate the process before it has completed.  Calling pclose() just blocks until the child completes.

How can I kill the process?  I don't see any easy way to get the pid out of the resource that popen() returns so that I can send it a signal.

I suppose I could do something kludgey and try to fudge the pid into the output using some sort of command-line hackery...

答:
Just send a kill (or abort) signal using kill function:

php http://php.net/manual/en/function.posix-kill.php

c/c++ http://linux.die.net/man/3/kill

Title: Killing processes opened with popen()?


问:
Custom toolbar using ConstraintLayout in android
I am trying to create my own custom Toolbar for my project. Currently I am using RelativeLayout to create it. But I wanna avoid deep hierarchy of Views. So I wanna create it using ConstrainLayout. How can I achieve the following in ConstraintLayout.

Code for the above layout:

```<code><RelativeLayout
            android:id="@+id/customAppBarLayout"
            android:layout_width="match_parent"
            android:layout_height="?attr/actionBarSize"
            android:paddingEnd="10dp"
            android:paddingStart="10dp">

            <ImageView
                android:id="@+id/toolbarCloseButton"
                android:layout_width="30dp"
                android:layout_height="30dp"
                android:layout_centerVertical="true"
                android:adjustViewBounds="true"
                app:srcCompat="@drawable/ic_cancel" />

            <TextView
                android:id="@+id/toolbarTitle"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_centerVertical="true"
                android:layout_marginStart="15dp"
                android:layout_toEndOf="@+id/toolbarCloseButton"
                android:textColor="#000"
                android:textSize="18sp"
                tools:text="Puzzle" />

            <RelativeLayout
                android:layout_width="30dp"
                android:layout_height="30dp"
                android:layout_alignParentEnd="true"
                android:layout_centerVertical="true">

                <ImageView
                    android:id="@+id/coinIcon"
                    android:layout_width="match_parent"
                    android:layout_height="match_parent"
                    android:layout_centerHorizontal="true"
                    android:layout_centerVertical="true"
                    android:paddingBottom="2dp"
                    android:paddingRight="2dp"
                    app:srcCompat="@drawable/ic_single_coin"
                    tools:ignore="MissingPrefix" />

                <TextView
                    android:id="@+id/prizeSize"
                    android:layout_width="16dp"
                    android:layout_height="16dp"
                    android:layout_alignParentBottom="true"
                    android:layout_alignParentEnd="true"
                    android:layout_centerInParent="true"
                    android:background="@drawable/circular_background"
                    android:focusable="true"
                    android:focusableInTouchMode="true"
                    android:freezesText="true"
                    android:gravity="center"
                    android:marqueeRepeatLimit="marquee_forever"
                    android:maxEms="20"
                    android:maxLines="1"
                    android:padding="1dp"
                    android:scrollHorizontally="true"
                    android:textColor="#fff"
                    android:textSize="6sp"
                    tools:text="100" />
            </RelativeLayout>
        </RelativeLayout>
</code>```

How this can be done in ConstraintLayout ?

答:
You need to add your custom layout inside the toolbar code:</p>

```<code><?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.Toolbar xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/toolBar"
    android:layout_width="match_parent"
    android:layout_height="@dimen/abc_action_bar_default_height_material"
    android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar" >

    <!-- your custom layout here -->
    <include android:id="@+id/actionBar" layout="@layout/action_bar_layout"/>

</android.support.v7.widget.Toolbar>
</code>```

Body:
I am trying to create my own custom Toolbar for my project. Currently I am using RelativeLayout to create it. But I wanna avoid deep hierarchy of Views. So I wanna create it using ConstrainLayout. How can I achieve the following in ConstraintLayout.

Code for the above layout:

<RelativeLayout
            android:id="@+id/customAppBarLayout"
            android:layout_width="match_parent"
            android:layout_height="?attr/actionBarSize"
            android:paddingEnd="10dp"
            android:paddingStart="10dp">

            <ImageView
                android:id="@+id/toolbarCloseButton"
                android:layout_width="30dp"
                android:layout_height="30dp"
                android:layout_centerVertical="true"
                android:adjustViewBounds="true"
                app:srcCompat="@drawable/ic_cancel" />

            <TextView
                android:id="@+id/toolbarTitle"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_centerVertical="true"
                android:layout_marginStart="15dp"
                android:layout_toEndOf="@+id/toolbarCloseButton"
                android:textColor="#000"
                android:textSize="18sp"
                tools:text="Puzzle" />

            <RelativeLayout
                android:layout_width="30dp"
                android:layout_height="30dp"
                android:layout_alignParentEnd="true"
                android:layout_centerVertical="true">

                <ImageView
                    android:id="@+id/coinIcon"
                    android:layout_width="match_parent"
                    android:layout_height="match_parent"
                    android:layout_centerHorizontal="true"
                    android:layout_centerVertical="true"
                    android:paddingBottom="2dp"
                    android:paddingRight="2dp"
                    app:srcCompat="@drawable/ic_single_coin"
                    tools:ignore="MissingPrefix" />

                <TextView
                    android:id="@+id/prizeSize"
                    android:layout_width="16dp"
                    android:layout_height="16dp"
                    android:layout_alignParentBottom="true"
                    android:layout_alignParentEnd="true"
                    android:layout_centerInParent="true"
                    android:background="@drawable/circular_background"
                    android:focusable="true"
                    android:focusableInTouchMode="true"
                    android:freezesText="true"
                    android:gravity="center"
                    android:marqueeRepeatLimit="marquee_forever"
                    android:maxEms="20"
                    android:maxLines="1"
                    android:padding="1dp"
                    android:scrollHorizontally="true"
                    android:textColor="#fff"
                    android:textSize="6sp"
                    tools:text="100" />
            </RelativeLayout>
        </RelativeLayout>

How this can be done in ConstraintLayout ?

Body:
You need to add your custom layout inside the toolbar code:

<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.Toolbar xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/toolBar"
    android:layout_width="match_parent"
    android:layout_height="@dimen/abc_action_bar_default_height_material"
    android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar" >

    <!-- your custom layout here -->
    <include android:id="@+id/actionBar" layout="@layout/action_bar_layout"/>

</android.support.v7.widget.Toolbar>


问:
itunes rss with c# MVC
Hello all I am trying to create a live updated RSS feed for itunes using asp.net MVC.  I can't seem to get the feed to validate and when you navigate to the page the xml is not formatted like it is when I made one with a webforms.

This is the View

```<code>            @model IEnumerable<lofbc.org.Models.media>

            @{
                Layout = null;
            }

            <?xml version="1.0" encoding="UTF-8" ?>

            <rss xmlns:atom="http://www.w3.org/2005/Atom" xmlns:itunes="http://www.itunes.com/dtds/podcast-1.0.dtd" xmlns:itunesu="http://www.itunesu.com/feed" version="2.0">

                <channel>
                    <title>Life of Faith Bible Church Podcast</title>
                    <link>@Request.Url.Host</link>
                    <description>Welcome to Life of Faith Bible Church! We are dedicated to bringing you life-changing resources through our podcast and audio messages. You will find a wealth of material that will help you triumph in every area of life.</description>
                    <language>en-us</language>
                    <copyright>New Life Media copyright @DateTime.Now.Year</copyright>
                    <atom:link href="https://www.lofbc.org/rss" rel="self" type="application/rss+xml" />

                    <!--itunes specific-->
                    <itunes:author>Life of Faith Bible Church</itunes:author>
                    <itunes:summary>Welcome to Life of Faith Bible Church! We are dedicated to bringing you life-changing resources through our podcast and audio messages. You will find a wealth of material that will help you triumph in every area of life.</itunes:summary>
                    <itunes:owner>
                        <itunes:name>Life of Faith Bible Church</itunes:name>
                        <itunes:email>justin@lofbc.org</itunes:email>
                    </itunes:owner>
                    <itunes:explicit>No</itunes:explicit>
                    <itunes:image href="http://www.lofbc.org/rss/artwork/artwork.jpg" />
                    <itunes:category text="Religion & Spirituality"> </itunes:category>

                    @foreach (var item in Model)
                        {
                            var date = item.createdDate.ToString("yyyy");
                            var path = item.audioPath.ToString().Replace(".f4v", ".mp3");

                        <item>
                            <title>@item.title</title>
                            <url>http://lofbc-media.s3.amazonaws.com/@date/Audio/mp3/@path</url>
                            <pubDate>@item.createdDate.ToString("MMM dd, yyyy")</pubDate>
                            <description>@item.description</description>
                            <enclosure url="http://lofbc-media.s3.amazonaws.com/@item.createdDate.ToString("yyyy"))/Audio/mp3/@item.audioPath.ToString().Replace(".f4v", ".mp3")" length=""  type="audio/mpeg" />

                            <itunes:summary>@item.description</itunes:summary>
                        </item>
                    }
                </channel>
            </rss>
</code>```

and this is the controller

```<code>            using lofbc.org.context;
            using lofbc.org.Models;
            using System;
            using System.Collections.Generic;
            using System.Data.SqlClient;
            using System.Linq;
            using System.Web;
            using System.Web.Mvc;

            namespace lofbc.org.Controllers
            {
                public class rssController : Controller
                {
                    // GET: rss
                    public ActionResult Index()
                    {
                        using (ServiceArchivesEntities db = new ServiceArchivesEntities())
                        {
                            try
                            {
                                DateTime startDate = DateTime.Parse("01/01/2015 00:00:00");

                                var MT = (from a in db.tbl_media
                                          join b in db.tbl_media_ministers
                                          on a.MinisterID equals b.ID
                                          select new media
                                          {
                                              id = a.ID,
                                              createdDate = (DateTime)a.CreatedDate,
                                              title = a.Title,
                                              minister = b.Title + " " + b.FirstName + " " + b.LastName,
                                              audioPath = a.PathToAudio,
                                              videoPath = a.PathToVideo,
                                              views = a.Views,
                                              listens = a.Listens,
                                              status = a.Status
                                          }).Where(t => t.status == 2 && t.createdDate >= startDate).OrderByDescending(t => t.createdDate).Take(100).ToList();

                                return View(MT);
                            }
                            catch (SqlException ex)
                            {
                                Response.Write(ex.ToString());
                                return View();
                            }

                        }
                    }
                }
            }
</code>```

Live demo http://development.lofbc.org/rss

答:
```<code>        <itunes:category text="Religion & Spirituality"> </itunes:category>
</code>```

would need to be

```<code>    <itunes:category text="Religion & Spirituality"> </itunes:category>
</code>```

iTunes may also be objecting the the extra blank lines before the <?xml.  Pack the Razor code as tight as possible at the top of the page:

```<code>@model IEnumerable<lofbc.org.Models.media>
@{  Layout = null;  }
<?xml version="1.0" encoding="UTF-8" ?>
<rss xmlns:atom="http://www.w3.org/2005/Atom"   ....
</code>```

Title: itunes rss with c# MVC

Body:
Hello all I am trying to create a live updated RSS feed for itunes using asp.net MVC.  I can't seem to get the feed to validate and when you navigate to the page the xml is not formatted like it is when I made one with a webforms.

This is the View

            @model IEnumerable<lofbc.org.Models.media>

            @{
                Layout = null;
            }

            <?xml version="1.0" encoding="UTF-8" ?>

            <rss xmlns:atom="http://www.w3.org/2005/Atom" xmlns:itunes="http://www.itunes.com/dtds/podcast-1.0.dtd" xmlns:itunesu="http://www.itunesu.com/feed" version="2.0">

                <channel>
                    <title>Life of Faith Bible Church Podcast</title>
                    <link>@Request.Url.Host</link>
                    <description>Welcome to Life of Faith Bible Church! We are dedicated to bringing you life-changing resources through our podcast and audio messages. You will find a wealth of material that will help you triumph in every area of life.</description>
                    <language>en-us</language>
                    <copyright>New Life Media copyright @DateTime.Now.Year</copyright>
                    <atom:link href="https://www.lofbc.org/rss" rel="self" type="application/rss+xml" />

                    <itunes:author>Life of Faith Bible Church</itunes:author>
                    <itunes:summary>Welcome to Life of Faith Bible Church! We are dedicated to bringing you life-changing resources through our podcast and audio messages. You will find a wealth of material that will help you triumph in every area of life.</itunes:summary>
                    <itunes:owner>
                        <itunes:name>Life of Faith Bible Church</itunes:name>
                        <itunes:email>justin@lofbc.org</itunes:email>
                    </itunes:owner>
                    <itunes:explicit>No</itunes:explicit>
                    <itunes:image href="http://www.lofbc.org/rss/artwork/artwork.jpg" />
                    <itunes:category text="Religion & Spirituality"> </itunes:category>

                    @foreach (var item in Model)
                        {
                            var date = item.createdDate.ToString("yyyy");
                            var path = item.audioPath.ToString().Replace(".f4v", ".mp3");

                        <item>
                            <title>@item.title</title>
                            <url>http://lofbc-media.s3.amazonaws.com/@date/Audio/mp3/@path</url>
                            <pubDate>@item.createdDate.ToString("MMM dd, yyyy")</pubDate>
                            <description>@item.description</description>
                            <enclosure url="http://lofbc-media.s3.amazonaws.com/@item.createdDate.ToString("yyyy"))/Audio/mp3/@item.audioPath.ToString().Replace(".f4v", ".mp3")" length=""  type="audio/mpeg" />

                            <itunes:summary>@item.description</itunes:summary>
                        </item>
                    }
                </channel>
            </rss>

and this is the controller

            using lofbc.org.context;
            using lofbc.org.Models;
            using System;
            using System.Collections.Generic;
            using System.Data.SqlClient;
            using System.Linq;
            using System.Web;
            using System.Web.Mvc;

            namespace lofbc.org.Controllers
            {
                public class rssController : Controller
                {
                    // GET: rss
                    public ActionResult Index()
                    {
                        using (ServiceArchivesEntities db = new ServiceArchivesEntities())
                        {
                            try
                            {
                                DateTime startDate = DateTime.Parse("01/01/2015 00:00:00");

                                var MT = (from a in db.tbl_media
                                          join b in db.tbl_media_ministers
                                          on a.MinisterID equals b.ID
                                          select new media
                                          {
                                              id = a.ID,
                                              createdDate = (DateTime)a.CreatedDate,
                                              title = a.Title,
                                              minister = b.Title + " " + b.FirstName + " " + b.LastName,
                                              audioPath = a.PathToAudio,
                                              videoPath = a.PathToVideo,
                                              views = a.Views,
                                              listens = a.Listens,
                                              status = a.Status
                                          }).Where(t => t.status == 2 && t.createdDate >= startDate).OrderByDescending(t => t.createdDate).Take(100).ToList();

                                return View(MT);
                            }
                            catch (SqlException ex)
                            {
                                Response.Write(ex.ToString());
                                return View();
                            }

                        }
                    }
                }
            }

Live demo http://development.lofbc.org/rss

Body:
        <itunes:category text="Religion & Spirituality"> </itunes:category>

would need to be

    <itunes:category text="Religion &amp; Spirituality"> </itunes:category>

iTunes may also be objecting the the extra blank lines before the <?xml.  Pack the Razor code as tight as possible at the top of the page:

@model IEnumerable<lofbc.org.Models.media>
@{  Layout = null;  }
<?xml version="1.0" encoding="UTF-8" ?>
<rss xmlns:atom="http://www.w3.org/2005/Atom"   ....


问:
Is there a way to record the phone screen using ARCore SDK?
I want to record phone screen in a video format.

Is there a way to record my screen using ARcore android SDK??

答:
Try to see if this works for you - https://stackoverflow.com/a/31547690/855984

The only thing that sucks about it is that you'll need to be tethered via USB cable to control the recording.

Android Studio will sample whatever it is you are seeing on your device provided that you're the owner of the process. Won't work for ripping other stuff visuals like Netflix for example.


问:
Should OLAP databases be denormalized for read performance?
I always thought that databases should be denormalized for read performance, as it is done for OLAP database design, and not exaggerated much further 3NF for OLTP design.

PerformanceDBA in various posts, for ex.,  in Performance of different aproaches to time-based data defends the paradigm that database should be always well-designed by normalization to 5NF and 6NF (Normal Form).

Have I understood it correctly (and what had I understood correctly)?

What's wrong with the traditional denormalization approach/paradigm design of OLAP databases (below 3NF) and the advice that 3NF is enough for most practical cases of OLTP databases?

For example:

"The simple truth ... is that 6NF, executed properly, is the data warehouse" (PerformanceDBA)

I should confess that I could never grasp the theories that denormalization facilitates read performance. Can anybody give me references with good logical explanations of this and of the contrary beliefs?

What are sources to which I can refer when trying to convince my stakeholders that OLAP/Data Warehousing databases should be normalized?

To improve visibility I copied here from comments:

"It would be nice if participants would
  add (disclose) how many real-life (no
  science projects included)
  data-warehouse implementations in 6NF
  they have seen or participated in.
  Kind of a quick-pool. Me = 0." – Damir
  Sudarevic

Wikipedia's Data Warehouse article tells:

"The normalized approach [vs. dimensional one by Ralph Kimball], also
  called the 3NF model (Third Normal Form) whose supporters are
  referred to as “Inmonites”, believe in Bill Inmon's approach in which
  it is stated that the data warehouse should be modeled using an E-R
  model/normalized model."

It looks like the normalized data warehousing approach (by Bill Inmon) is perceived as not exceeding 3NF (?)

I just want to understand what is the origin of the myth (or ubiquitous axiomatic belief) that data warehousing/OLAP is synonym of denormalization?

Damir Sudarevic answered that they are well-paved approach. Let me return to the question: Why is denormalization believed to facilitate reading?

答:
Mythology

I always thought that databases should be denormalized for reading, as it is done for OLAP database design, and not exaggerated much further 3NF for OLTP design.

There's a myth to that effect.  In the Relational Database context, I have re-implemented six very large so-called "de-normalised" "databases"; and executed over eighty assignments correcting problems on others, simply by Normalising them, applying Standards and engineering principles. I have never seen any evidence for the myth.  Only people repeating the mantra as if it were some sort of magical prayer.

Normalisation vs Un-normalised

("De-normalisation" is a fraudulent term I refuse to use it.)

This is a scientific industry (at least the bit that delivers software that does not break; that put people on the Moon; that runs banking systems; etc).  It is governed  by the laws of physics, not magic. Computers and software are all finite, tangible, physical objects that are subject to the laws of physics. According to the secondary and tertiary education I received:

it is not possible for a bigger, fatter, less organised object to perform better than a smaller, thinner, more organised object.

Normalisation yields more tables, yes, but each table is much smaller.  And even though there are more tables, there are in fact (a) fewer joins and (b) the joins are faster because the sets are smaller.  Fewer Indices are required overall, because each smaller table needs fewer indices. Normalised tables also yield much shorter row sizes.

for any given set of resources, Normalised tables:

fit more rows into the same page size

therefore fit more rows into the same cache space, therefore overall throughput is increased)

therefore fit more rows into the same disk space, therefore the no of I/Os is reduced; and when I/O is called for, each I/O is more efficient.

.

it is not possible for an object that is heavily duplicated to perform better than an object that is stored as a single version of the truth.  Eg. when I removed the 5 x duplication at the table and column level, all the transactions were reduced in size; the locking reduced; the Update Anomalies disappeared. That substantially reduced contention and therefore increased concurrent use.

The overall result was therefore much, much higher performance.

In my experience, which is delivering both OLTP and OLAP from the same database, there has never been a need to "de-normalise" my Normalised structures, to obtain higher speed for read-only (OLAP) queries.  That is a myth as well.

No, the "de-normalisation" requested by others reduced speed, and it was eliminated.  No surprise to me, but again, the requesters were surprised.

Many books have been written by people, selling the myth. It needs to be recognised that these are non-technical people; since they are selling magic, the magic they sell has no scientific basis, and they conveniently avoid the laws of physics in their sales pitch.

(For anyone who wishes to dispute the above physical science, merely repeating the mantra will no have any effect, please supply specific evidence supporting the mantra.)

Why is the Myth Prevalent ?

Well, first, it is not prevalent among scientific types, who do not seek ways of overcoming the laws of physics.

From my experience, I have identified three major reasons for the prevalence:

For those people who cannot Normalise their data, it is a convenient justification for not doing so.  They can refer to the magic book and without any evidence for the magic, they can reverently say "see a famous writer validates what I have done".  Not Done, most accurately.

Many SQL coders can write only simple, single-level SQL.  Normalised structures require a bit of SQL capability.  If they do not have that; if they cannot produce SELECTs without using temporary tables; if they cannot write Sub-queries, they will be psychologically glued to the hip to flat files (which is what "de-normalised" structures are), which they can process.

People love to read books, and to discuss theories.  Without experience. Especially re magic.  It is a tonic, a substitute for actual experience.  Anyone who has actually Normalised a database correctly has never stated that "de-normalised is faster than normalised".  To anyone stating the mantra, I simply say "show me the evidence", and they have never produced any.  So the reality is, people repeat the mythology for these reasons, without any experience of Normalisation. We are herd animals, and the unknown is one of our biggest fears.

That is why I always include "advanced" SQL and mentoring on any project.

My Answer

This Answer is going to be ridiculously long if I answer every part of your question or if I respond to the incorrect elements in some of the other answers. Eg. the above has answered just one item.  Therefore I will answer your question in total without addressing the specific components, and take a different approach.  I will deal only in the science related to your question, that I am qualified in, and very experienced with.

Let me present the science to you in manageable segments.

The typical model of the six large scale full implementation assignments.

These were the closed "databases" commonly found in small firms, and the organisations were large banks

very nice for a first generation, get-the-app-running mindset, but a complete failure in terms of performance, integrity and quality

they were designed for each app, separately

reporting was not possible, they could only report via each app

since "de-normalised" is a myth, the accurate technical definition is, they were un-normalised

In order to "de-normalise" one must Normalise first; then reverse the process a little
in every instance where people showed me their "de-normalised" data models, the simple fact was, they had not Normalised at all; so "de-normalisation" was not possible; it was simply un-normalised

since they did not have much Relational technology, or the structures and control of Databases, but they were passed off as "databases", I have placed those words in quotation marks

as is scientifically guaranteed for un-normalised structures, they suffered multiple versions of the truth (data duplication) and therefore high contention and low concurrency, within each of them

they had an additional problem of data duplication across the "databases"

the organisation was trying to keep all those duplicates synchronised, so they implemented replication; which of course meant an additional server; ETL and synching scripts to be developed; and maintained; etc

needless to say, the synching was never quite enough and they were forever changing it

with all that contention and low throughput, it was no problem at all justifying a separate server for each "database".  It did not help much.

So we contemplated the laws of physics, and we applied a little science.

We implemented the Standard concept that the data belongs to the corporation (not the departments) and the corporation wanted one version of the truth.  The Database was pure Relational, Normalised to 5NF.  Pure Open Architecture, so that any app or report tool could access it.  All transactions in stored procs (as opposed to uncontrolled strings of SQL all over the network).  The same developers for each app coded the new apps, after our "advanced" education.

Evidently the science worked.  Well, it wasn't my private science or magic, it was ordinary engineering and the laws of physics.  All of it ran on one database server platform; two pairs (production & DR) of servers were decommissioned and given to another department. The 5 "databases" totalling 720GB were Normalised into one Database totalling 450GB. About 700 tables (many duplicates and duplicated columns) were normalised into  500 unduplicated tables.  It performed much faster, as in 10 times faster overall, and more than 100 times faster in some functions.  That did not surprise me, because that was my intention, and the science predicted it, but it surprised the people with the mantra.

More Normalisation

Well, having had success with Normalisation in every project, and confidence with the science involved, it has been a natural progression to Normalise more, not less.  In the old days 3NF was good enough, and later NFs were not yet identified.  In the last 20 years, I have only delivered databases that had zero update anomalies, so it turns out by todays definitions of NFs, I have always delivered 5NF.

Likewise, 5NF is great but it has its limitations.  Eg. Pivoting large tables (not small result sets as per the MS PIVOT Extension) was slow.  So I (and others) developed a way of providing Normalised tables such that Pivoting was (a) easy and (b) very fast.  It turns out, now that 6NF has been defined, that those tables are 6NF.

Since I provide OLAP and OLTP from the same database, I have found that, consistent with the science, the more Normalised the structures are:

the faster they perform

and they can be used in more ways (eg Pivots)

So yes, I have consistent and unvarying experience, that not only is Normalised much, much faster than un-normalised or "de-normalised"; more Normalised is even faster than less normalised.

One sign of success is growth in functionality (the sign of failure is growth in size without growth in functionality).  Which meant they immediately asked us for more reporting functionality, which meant we Normalised even more, and provided more of those specialised tables (which turned out years later, to be 6NF).

Progressing on that theme.  I was always a Database specialist, not a data warehouse specialist, so my first few projects with warehouses were not full-blown implementations, but rather, they were substantial performance tuning assignments.  They were in my ambit, on products that I specialised in.

Let's not worry about the exact level of normalisation, etc, because we are looking at the typical case. We can take it as given that the OLTP database was reasonably normalised, but not capable of OLAP, and the organisation had purchased a completely separate OLAP platform, hardware; invested in developing and maintaining masses of ETL code; etc.  And following implementation then spent half their life managing the duplicates they had created. Here the book writers and vendors need to be blamed, for the massive waste of hardware and separate platform software licences they cause organisations to purchase.

If you have not observed it yet, I would ask you to notice the similarities between the Typical First Generation "database" and the Typical Data Warehouse

Meanwhile, back at the farm (the 5NF Databases above) we just kept adding more and more OLAP functionality.  Sure the app functionality grew, but that was little, the business had not changed.  They would ask for more 6NF and it was easy to provide (5NF to 6NF is a small step; 0NF to anything, let alone 5NF, is a big step; an organised architecture is easy to extend).

One major difference between OLTP and OLAP, the basic justification of separate OLAP platform software, is that the OLTP is row-oriented, it needs transactionally secure rows, and fast; and the OLAP doesn't care about the transactional issues, it needs columns, and fast.  That is the reason all the high end BI or OLAP platforms are column-oriented, and that is why the OLAP models (Star Schema, Dimension-Fact) are column-oriented.

But with the 6NF tables:

there are no rows, only columns; we serve up rows and columns at same blinding speed

the tables (ie. the 5NF view of the 6NF structures) are already organised into Dimension-Facts.  In fact they are organised into more Dimensions than any OLAP model would ever identify, because they are all Dimensions.

Pivoting entire tables with aggregation on the fly (as opposed to the PIVOT of a small number of derived columns) is (a) effortless, simple code and (b) very fast

What we have been supplying for many years, by definition, is Relational Databases with at least 5NF for OLTP use, and 6NF for OLAP requirements.

Notice that it is the very same science that we have used from the outset; to move from Typical un-normalised "databases" to 5NF Corporate Database.  We are simply applying more of the proven science, and obtaining higher orders of functionality and performance.

Notice the similarity between 5NF Corporate Database and 6NF Corporate Database

The entire cost of separate OLAP hardware, platform software, ETL, administration, maintenance, are all eliminated.

There is only one version of the data, no update anomalies or maintenance thereof; the same data served up for OLTP as rows, and for OLAP as columns

The only thing we have not done, is to start off on a new project, and declare pure 6NF from the start.  That is what I have lined up next.

What is Sixth Normal Form ?

Assuming you have a handle on Normalisation (I am not going to not define it here), the non-academic definitions relevant to this thread are as follows. Note that it applies at the table level, hence you can have a mix of 5NF and 6NF tables in the same database:

Fifth Normal Form: all Functional Dependencies resolved across the database

in addition to 4NF/BCNF

every non-PK column is 1::1 with its PK

and to no other PK

No Update Anomalies

.

Sixth Normal Form: is the irreducible NF, the point at which the data cannot be further reduced or Normalised (there will not be a 7NF)

in addition to 5NF

the row consists of a Primary Key, and at most, one non-key column

eliminates The Null Problem

What Does 6NF Look Like ?

The Data Models belong to the customers, and our Intellectual Property is not available for free publication.  But I do attend this web-site, and provide specific answers to questions.  You do need a real world example, so I will publish the Data Model for one of our internal utilities.

This one is for the collection of server monitoring data (enterprise class database server and OS) for any no of customers, for any period.  We use this to analyse performance issues remotely, and to verify any performance tuning that we do.  The structure has not changed in over ten years (added to, with no change to the existing structures), it is typical of the specialised 5NF that many years later was identified as 6NF.  Allows full pivoting; any chart or graph to be drawn, on any Dimension (22 Pivots are provided but that is not a limit); slice and dice; mix and match. Notice they are all Dimensions.

The monitoring data or Metrics or vectors can change (server version changes; we want to pick up something more) without affecting the model (you may recall in another post I stated EAV is the bastard son of 6NF; well this is full 6NF, the undiluted father, and therefore provides all features of EAV, without sacrificing any Standards, integrity or Relational power); you merely add rows.

▶Monitor Statistics Data Model◀. (too large for inline; some browsers cannot load inline; click the link)

It allows me to produce these ▶Charts Like This◀, six keystrokes after receiving a raw monitoring stats file from the customer. Notice the mix-and-match; OS and server on the same chart; a variety of Pivots.  (Used with permission.)

Readers who are unfamiliar with the Standard for Modelling Relational Databases may find the ▶IDEF1X Notation◀ helpful.

6NF Data Warehouse

This has been recently validated by Anchor Modeling, in that they are now presenting 6NF as the "next generation" OLAP model for data warehouses. (They do not provide the OLTP and OLAP from the single version of the data, that is ours alone).

Data Warehouse (Only) Experience

My experience with Data Warehouses only (not the above 6NF OLTP-OLAP Databases), has been several major assignments, as opposed to full implementation projects. The results were, no surprise:

consistent with the science, Normalised structures perform much faster; are easier to maintain; and require less data synching. Inmon, not Kimball.

consistent with the magic, after I Normalise a bunch of tables, and deliver substantially improved performance via application of the laws of physics, the only people surprised are the magicians with their mantras.

Scientifically minded people do not do that; they do not believe in, or rely upon, silver bullets and magic; they use and hard work science to resolve their problems.

Valid Data Warehouse Justification

That is why I have stated in other posts, the only valid justification for a separate Data Warehouse platform, hardware, ETL, maintenance, etc, is where there are many Databases or "databases", all being merged into a central warehouse, for reporting and OLAP.

Kimball

A word on Kimball is necessary, as he is the main proponent of "de-normalised for performance" in data warehouses. As per my definitions above, he is one of those people who have evidently never Normalised in their lives; his starting point was un-normalised (camouflaged as "de-normalised") and he simply implemented that in a Dimension-Fact model.

Of course, to obtain any performance, he had to "de-normalise" even more, and create further duplicates, and justify all that.

So therefore it is true, in a schizophrenic sort of way, that "de-normalising" un-normalised structures, by making more specialised copies, "improves read performance". It is not true when the whole is taking into account; it is true only inside that little asylum, not outside.

Likewise it is true, in that crazy way, that where all the "tables" are monsters, that "joins are expensive" and something to be avoided.  They have never had the experience of joining smaller tables and  sets, so they cannot believe the scientific fact that more, smaller tables are faster.

they have experience that creating duplicate "tables" is faster, so they cannot believe that eliminating duplicates is even faster than that.

his Dimensions are added to the un-normalised data. Well the data is not Normalised, so no Dimensions are exposed. Whereas in a Normalised model, the Dimensions are already exposed, as an integral part of the data, no addition is required.

that well-paved path of Kimball's leads to the cliff, where more lemmings fall to their deaths, faster.  Lemmings are herd animals, as long as they are walking the path together, and dying together, they die happy. Lemmings do not look for other paths.

All just stories, parts of the one mythology that hang out together and support each other.

Your Mission

Should you choose to accept it.  I am asking you to think for yourself, and to stop entertaining any thoughts that contradict science and the laws of physics. No matter how common or mystical or mythological they are.  Seek evidence for anything before trusting it.  Be scientific, verify new beliefs for yourself.  Repeating the mantra "de-normalised for performance" won't make your database faster, it will just make you feel better about it. Like the fat kid sitting in the sidelines telling himself that he can run faster than all the kids in the race.

on that basis, even the concept "normalise for OLTP" but do the opposite, "de-normalise for OLAP" is a contradiction.  How can the laws of physics work as stated on one computer, but work in reverse on another computer ?  The mind boggles.  It is simply not possible, the work that same way on every computer.

Questions ?

ContentLicense: CC BY-SA 4.0


问:
Better than FileObserver
I'm curious to know if there's a better way to monitor a directory for file changes/creations/deletions than FileObserver. FileObserver requires a constant reference to it, which requires a constantly running service, which is difficult and a bad practice, right?

I'd appreciate any insight as to how you monitor the filesystem without, say, draining battery or having to keep a service running. (In newer Android versions, the service is killed when you swipe the app off the recent apps stack.)

Thanks!

答:
PS: It's been a long time since you asked the question but maybe the answer will be usefull for others.

You could try to create a kernel module to monitor a directory or a specific file. The targetted events can be written to a file and accessed from user space with an application or service.

Title: Better than FileObserver


问:
Strong connection between CoreData Entity and a View
How would you recommend to store data from CoreData in memory when we have such structure:

CoreData Tables/Entities -> Model Class -> UIView.

Do I really need Model Class with the same number of fields like in CoreData Entities (NSManagedObject)?

Should I store Entity.ObjectID in my views?

How would I make a strong connection between CoreData Entity and a view? Let's say in my code there is an array of entities, where each entity is shown in its own view. If I update data in a view, I need to update only specific instance of CoreData Entity.

Can't figure out what is the best approach to handle this.

Thank you!

答:
Do I really need Model Class with the same number of fields like in CoreData Entities (NSManagedObject)?

This is usually how it's done. Automatic subclass generation is built in to Xcode. If you don't like Xcode's classes there's mogenerator, a highly regarded long running open source project that provides an alternative approach.


问:
How do i change one value in a csv file?
I want to just change a single value, do I have to make a whole new file? Say if I am collecting data about people and someones information changes or they want to change their password, what do I do?</p>

答: You have to read it, change the specific line and write a new file or overwrite the old one.</p>


问:
Owl Carrousel with Swapping multiple div's
I am trying to achieve "a div always swap to next div on clicking a button named "Vote Now" in owl carousel" but it only one time swap accurate to next div on clicking the button other time it does not swap accurate to next div here is my fiddle link.

```<code><script type="text/javascript">
    $(document).ready(function() {
        $(".go-swap").click(function() {
            $("#currnt").swap({
                target: "next",
                opacity: "0.5",
                speed: 1000,
            });
        });
    });
</script>
<script type="text/javascript">
    $(document).ready(function() {
        $('.item').hover(function(){
            $(this).attr('id', 'currnt');
            $(this).parent().prev().children().attr('id', 'next')},
            function(){
                $(this).attr('id', '');
                $(this).parent().prev().children().attr('id', '')
            });
        });
</script>
<section id="demos">
  <div class="row">
    <div class="large-12 columns">
      <div class="owl-carousel owl-theme">
        <div class="item" data-hash="zero">
          <h4>0</h4>
            <a href="javascript://" class="go-swap"><button>Vote Now</button></a>
        </div>

        <div class="item" data-hash="one">
          <h4>1</h4>
            <a href="javascript://" class="go-swap"><button>Vote Now</button></a>
        </div>
        <div class="item" data-hash="two">
          <h4>2</h4>
            <a href="javascript://" class="go-swap"><button>Vote Now</button></a>
        </div>
        <div class="item" data-hash="three">
          <h4>3</h4>
            <a href="javascript://" class="go-swap"><button>Vote Now</button></a>
        </div>
        <div class="item" data-hash="four">
          <h4>4</h4>
            <a href="javascript://" class="go-swap"><button>Vote Now</button></a>
        </div>
      </div>
    </div>
  </div>
</section>
</code>```

答:
It's a little hard to understand what you are trying to achieve, you can move to the next slide on click like this

```<code>$(document).ready(function() {
      var slider =  $('.owl-carousel')

    slider.owlCarousel({
        items: 4,
        loop: false,
        center: false,
        margin: 10,
        callbacks: true,
        URLhashListener: true,
        autoplayHoverPause: true,
        startPosition: 'URLHash'
      });

     $(".go-swap").click(function() {
            slider.trigger('next.owl.carousel');
      });

});
</code>```

fiddle here - https://jsfiddle.net/Jim_Miraidev/uu8ukac6/

Is this what yo were looking for?

Body:
I am trying to achieve "a div always swap to next div on clicking a button named "Vote Now" in owl carousel" but it only one time swap accurate to next div on clicking the button other time it does not swap accurate to next div here is my fiddle link.

0

            <button>Vote Now</button>

1

            <button>Vote Now</button>

2

            <button>Vote Now</button>

3

            <button>Vote Now</button>

4

            <button>Vote Now</button>

Body:
It's a little hard to understand what you are trying to achieve, you can move to the next slide on click like this

$(document).ready(function() {
      var slider =  $('.owl-carousel')

    slider.owlCarousel({
        items: 4,
        loop: false,
        center: false,
        margin: 10,
        callbacks: true,
        URLhashListener: true,
        autoplayHoverPause: true,
        startPosition: 'URLHash'
      });

     $(".go-swap").click(function() {
            slider.trigger('next.owl.carousel');
      });

});

fiddle here - https://jsfiddle.net/Jim_Miraidev/uu8ukac6/

Is this what yo were looking for?


问:
how is it possible to use flowtype to define a prop in react context of a component?
When using flowtype to define a prop in the context in this way

```<code>// @flow
type MyType = Object;
class CustomView extends React.Component {
    static childContextTypes = {
        someProp: MyType
    }
    getChildContext() {
        return {
            someProp: this.props.someProp
        };
    }
}
</code>```

I got the following error:

CustomView: type specification of child context someProps is
  invalid; the type checker function must return null or an Error
  but returned a object. You may have forgotten to pass an argument to
  the type checker creator (arrayOf, instanceOf, objectOf, oneOf,
  oneOfType, and shape all require an argument).

So I am forced to use propTypes.object instead of Object.

答:
No, you cannot use a Flow type as a type in childContextTypes. The reason is that childContextTypes is checked at runtime, and Flow types do not have any runtime representation. Therefore the "types" in childContextTypes must be values - specifically the values provided by the prop-types npm package.

The use of MyType in your example is actually a syntax error: MyType appears in the position of an object property value which must be a value, not a type.

Body:
When using flowtype to define a prop in the context in this way

// @flow
type MyType = Object;
class CustomView extends React.Component {
    static childContextTypes = {
        someProp: MyType
    }
    getChildContext() {
        return {
            someProp: this.props.someProp
        };
    }
}

I got the following error:

CustomView: type specification of child context someProps is
  invalid; the type checker function must return null or an Error
  but returned a object. You may have forgotten to pass an argument to
  the type checker creator (arrayOf, instanceOf, objectOf, oneOf,
  oneOfType, and shape all require an argument).

So I am forced to use propTypes.object instead of Object.


问:
Why does an instance method have this type in Swift?
Given this code:

```<code>struct Foo {
    func f() {}
}

let f = Foo.f // (Foo) -> () -> ()
</code>```

Why does f have the type (Foo) -> () -> () and not (Foo) -> ()? Wouldn’t it make sense for instance methods like Foo.f to be directly interchangeable with free functions of type (Foo) -> …?

答:
It's because, by saying this:

```<code>let f = Foo.f
</code>```

you've described f as a class method, Foo.f. But in your declaration of Foo, f is an instance method. You have thus accidentally discovered the deep dark secret that instance methods are class methods in disguise; you are seeing the signature of the secret class method.

If you had said

```<code>let f = Foo().f
</code>```

you would have gotten the expected result.

Body:
Given this code:

struct Foo {
    func f() {}
}

let f = Foo.f // (Foo) -> () -> ()

Why does f have the type (Foo) -> () -> () and not (Foo) -> ()? Wouldn’t it make sense for instance methods like Foo.f to be directly interchangeable with free functions of type (Foo) -> …?

Body:
It's because, by saying this:

let f = Foo.f

you've described f as a class method, Foo.f. But in your declaration of Foo, f is an instance method. You have thus accidentally discovered the deep dark secret that instance methods are class methods in disguise; you are seeing the signature of the secret class method.

If you had said

let f = Foo().f

you would have gotten the expected result.