问:
implementing an abstract base class function in another template base class
I have a Visual Studio 2008 C++ project where I have a class that inherits from an abstract base class and another template class that implements a function in the abstract base class. For example:

```<code>class Foo;

struct Buzz
{
    virtual ~Buzz() {};
    virtual void Buzz_Do( Foo* ) = 0;
};

class Base
{
public:
    virtual ~Base() {};
    virtual void Base_Do( Buzz* ) = 0;
};

template< class T >
class Bar
{
public:
    virtual void Base_Do( Buzz* v )
    {
        v->Buzz_Do( static_cast< T* >( this ) );
    };
};

class Foo : public Base, public Bar< Foo >
{
};

int _tmain(int argc, _TCHAR* argv[])
{
    Foo c;
    return 0;
}
</code>```

Unfortunately, this yields the compiler error:

```<code>1>MyApp.cpp(39) : error C2259: 'Foo' : cannot instantiate abstract class
1>        due to following members:
1>        'void Base::Base_Do(Buzz *)' : is abstract
1>        MyApp.cpp(17) : see declaration of 'Base::Base_Do'
</code>```

I've tried adding a public using Bar< Foo >::Base_Do; to class Foo, but that did not help.

Is there a way to make this work or will I need to put a concrete Base_Do() implementation in Foo and not use Bar<>?

Thanks,
PaulH

答:
Have you tried:

```<code>template< class T , class K>

class Bar: public K
{
public:
    virtual void Base_Do( Buzz* v )
    {
        v->Buzz_Do( static_cast< T* >( this ) );
    };
};

class Foo : public Bar< Foo, Base >
{
};
</code>```

Foo deriver from Base, which has undefined virtual method. You could make it like I wrote or make derivation virtual.

Body:
I have a Visual Studio 2008 C++ project where I have a class that inherits from an abstract base class and another template class that implements a function in the abstract base class. For example:

class Foo;

struct Buzz
{
    virtual ~Buzz() {};
    virtual void Buzz_Do( Foo* ) = 0;
};

class Base
{
public:
    virtual ~Base() {};
    virtual void Base_Do( Buzz* ) = 0;
};

template< class T >
class Bar
{
public:
    virtual void Base_Do( Buzz* v )
    {
        v->Buzz_Do( static_cast< T* >( this ) );
    };
};

class Foo : public Base, public Bar< Foo >
{
};

int _tmain(int argc, _TCHAR* argv[])
{
    Foo c;
    return 0;
}

Unfortunately, this yields the compiler error:

1>MyApp.cpp(39) : error C2259: 'Foo' : cannot instantiate abstract class
1>        due to following members:
1>        'void Base::Base_Do(Buzz *)' : is abstract
1>        MyApp.cpp(17) : see declaration of 'Base::Base_Do'

I've tried adding a public using Bar< Foo >::Base_Do; to class Foo, but that did not help.

Is there a way to make this work or will I need to put a concrete Base_Do() implementation in Foo and not use Bar<>?

Thanks,
PaulH

Body:
Have you tried:

template< class T , class K>

class Bar: public K
{
public:
    virtual void Base_Do( Buzz* v )
    {
        v->Buzz_Do( static_cast< T* >( this ) );
    };
};

class Foo : public Bar< Foo, Base >
{
};

Foo deriver from Base, which has undefined virtual method. You could make it like I wrote or make derivation virtual.


来源: stackexchange

问:
React JS How to Set State in One Component from Another Functional Component
This is absolutely not a duplicate.

This question is a React question.  The question that this is supposedly a duplicate of is straight JavaScript.

The problem was how i sent in my React function and not how i was referencing this or anything specific to "this".

This is actually very helpful as it shows how to update state in REACT!!! from one component to another which allows for more functional components which is a great thing for efficiency in REACT!!!!

So unfair.

This is absolutely not a duplicate.

Please remove the duplicate marking!

Here is the original question...

i have a couple of questions about some code i inherited.  i work on an intranet so i have to type a sample of what i am asking about.

first question, i have a "class" like the following, is it a JS class or a React class?  i assume React...

```<code>import React from 'react';

class SomeUtil {
  constructor() {
    this.doAbc = this.doAbc.bind(this)
  }

  doAbc(...){
    ...
  }
}
export default SomeUtil;
</code>```

i noticed there is no super() - should i add that?

second question has to do with creating a similar class but i can't get it to work as i want.

```<code>import React from 'react';

class SomeOtherUtil {
  constructor(someCallback) {

    this.externalCallback = someCallback

    this.doXyz = this.doXyz.bind(this)
    this.doXxz = this.doXxz.bind(this)
    **//do i need to bind externalCallback here ?**
  }

  doXyz(...){
    this.externalCallback('hello world!')
  }

  doXxz(...){
    this.externalCallback('hello bob!')
  }
}
export default SomeOtherUtil;
</code>```

now, when i use SomeOtherUtil i want to use it like this...

```<code>//inside a React Component
someRandomReactComponentMethod() {
  let myUtil = new SomeOtherUtil(this.someRandomCallback)
  myUtil.doXyz();
  myUtil.doXxz();
}
</code>```

UPDATE

i figured out my problem.  i was trying to do this...

```<code>//inside a React Component
someRandomReactComponentMethod() {
  let myUtil = new DataUtil(this.setState)
  myUtil.getThenSetData(...);
  myUtil.getAnotherWayAndSetData(...);
}
</code>```

and i had to do this instead ...

```<code>//inside a React Component
someRandomReactComponentMethod() {
  let myUtil = new DataUtil((data)=>this.setState(data))
  myUtil.getThenSetData();
  myUtil.getAnotherWayAndSetData();
}
</code>```

i'm still not convinced this is a duplicate of the question mentioned above but whatever.

Thanks for answering the first question about JS class vs React class.  Wish i could give half a vote. :)  i wasn't sure about my first question becausee react was imported at the top that it would get compiled into a react class or straight JS.  Now i know.  Also, in the past when i worked with JS objects i had to use prototype to make a new instance.  So it was confusing to me.

答:
first question, i have a "class" like the following, is it a JS class or a React class? i assume React...

React Components are JavaScript classes that extend React.Component. This example does not: it's just a class, and doesn't look like it implements the component interface.

//do i need to bind externalCallback here ?**

It depends on how it's called. If you are, for instance, responding to a click handler, you'll want to bind it so that the this value for the handler refers to the component rather than the clicked element.

ContentLicense: CC BY-SA 3.0

Body:
This is absolutely not a duplicate.

This question is a React question.  The question that this is supposedly a duplicate of is straight JavaScript.

The problem was how i sent in my React function and not how i was referencing this or anything specific to "this".

This is actually very helpful as it shows how to update state in REACT!!! from one component to another which allows for more functional components which is a great thing for efficiency in REACT!!!!

So unfair.

This is absolutely not a duplicate.

Please remove the duplicate marking!

Here is the original question...

i have a couple of questions about some code i inherited.  i work on an intranet so i have to type a sample of what i am asking about.

first question, i have a "class" like the following, is it a JS class or a React class?  i assume React...

import React from 'react';

class SomeUtil {
  constructor() {
    this.doAbc = this.doAbc.bind(this)
  }

  doAbc(...){
    ...
  }
}
export default SomeUtil;

i noticed there is no super() - should i add that?

second question has to do with creating a similar class but i can't get it to work as i want.

import React from 'react';

class SomeOtherUtil {
  constructor(someCallback) {

    this.externalCallback = someCallback

    this.doXyz = this.doXyz.bind(this)
    this.doXxz = this.doXxz.bind(this)
    **//do i need to bind externalCallback here ?**
  }

  doXyz(...){
    this.externalCallback('hello world!')
  }

  doXxz(...){
    this.externalCallback('hello bob!')
  }
}
export default SomeOtherUtil;

now, when i use SomeOtherUtil i want to use it like this...

//inside a React Component
someRandomReactComponentMethod() {
  let myUtil = new SomeOtherUtil(this.someRandomCallback)
  myUtil.doXyz();
  myUtil.doXxz();
}

UPDATE

i figured out my problem.  i was trying to do this...

//inside a React Component
someRandomReactComponentMethod() {
  let myUtil = new DataUtil(this.setState)
  myUtil.getThenSetData(...);
  myUtil.getAnotherWayAndSetData(...);
}

and i had to do this instead ...

//inside a React Component
someRandomReactComponentMethod() {
  let myUtil = new DataUtil((data)=>this.setState(data))
  myUtil.getThenSetData();
  myUtil.getAnotherWayAndSetData();
}

i'm still not convinced this is a duplicate of the question mentioned above but whatever.

Thanks for answering the first question about JS class vs React class.  Wish i could give half a vote. :)  i wasn't sure about my first question becausee react was imported at the top that it would get compiled into a react class or straight JS.  Now i know.  Also, in the past when i worked with JS objects i had to use prototype to make a new instance.  So it was confusing to me.


问:
How to insert a formula into a function so that it can be used to calculate values for consecutive rows
I'm aware that the title may be a little confusing but please allow me to clarify.
I have a column with values

```<code>> df
    Direction
    139
    118
    180
    142
    185
    224
    137
    245
</code>```

I have the following formula

```<code>((pt1 - pt2 + 180)%%360 - 180)
</code>```

I would like to insert this formula to calculate the difference between each consecutive instance
Example:

```<code>((139 - 118 + 180)%%360 - 180) = 21
((118 - 180 + 180)%%360 - 180) = -62
</code>```

Some of the things I've tried

Creating the function

```<code>angle <- function(turn1, turn2) {
  coursediff <- ((turn1 - turn2 + 180)
                 %%360 - 180)
  coursediff
}
angle(118, 180)
## [1] -62
</code>```

Trying to use it for each consecutive row for column Direction, creating a new column named Diff

```<code>df$Diff <- with(df,
     ave(Direction, ID,  FUN=function(angle) c(NA, diff(angle))))
</code>```

Or

```<code>df %>% group_by(ID) %>%
  mutate(gap=angle(c(NA,diff(Direction)), 1))
</code>```

Or

```<code>index <- function(angle) c(0, diff(angle))
DT <- data.table(df)
DT[, Diff := index(Direction), by = "ID"]
</code>```

Or even

```<code>transform(df,
          Diff=unlist(tapply(Direction, ID,
                                function(angle) c(0, diff(Direction)))))
</code>```

All the above attempts are giving me the same answers as if I were to simply take the difference per row, like so

```<code>df$Diff <- c(NA, diff(df$Direction))
</code>```

This is what I get now

```<code>> df
    Direction  Diff  ID
    139        NA    1
    118       -21    1
    180        62    1
    142       -38    1
    185        NA    2
    224        39    2
    137       -87    2
    245        108   2
</code>```

I hope someone can help me out, much appreciated!

答:
When you do

```<code>angle(118, 180)
## [1] -62
</code>```

Means

```<code>angle(line1, line2)
</code>```

You are comparing a direction with its consecutive, e.g. the next one.

In the other functions you wrote, the order is reversed, that is

```<code>angle(line2, line1)
</code>```

Just fix that and you obtain the result you want:

```<code>library(dplyr)

df %>%
  group_by(ID) %>%
  mutate(diff = (Direction - lead(Direction) + 180) %% 360 -180)
#> Source: local data frame [8 x 4]
#> Groups: ID [2]
#>
#>   Direction  Diff    ID  diff
#>       <int> <int> <int> <dbl>
#> 1       139    NA     1    21
#> 2       118   -21     1   -62
#> 3       180    62     1    38
#> 4       142   -38     1    NA
#> 5       185    NA     2   -39
#> 6       224    39     2    87
#> 7       137   -87     2  -108
#> 8       245   108     2    NA
</code>```

Body:
I'm aware that the title may be a little confusing but please allow me to clarify.
I have a column with values

> df
    Direction
    139
    118
    180
    142
    185
    224
    137
    245

I have the following formula

((pt1 - pt2 + 180)%%360 - 180)

I would like to insert this formula to calculate the difference between each consecutive instance
Example:

((139 - 118 + 180)%%360 - 180) = 21
((118 - 180 + 180)%%360 - 180) = -62

Some of the things I've tried

Creating the function

angle <- function(turn1, turn2) {
  coursediff <- ((turn1 - turn2 + 180)
                 %%360 - 180)
  coursediff
}
angle(118, 180)
## [1] -62

Trying to use it for each consecutive row for column Direction, creating a new column named Diff

df$Diff <- with(df,
     ave(Direction, ID,  FUN=function(angle) c(NA, diff(angle))))

Or

df %>% group_by(ID) %>%
  mutate(gap=angle(c(NA,diff(Direction)), 1))

Or

index <- function(angle) c(0, diff(angle))
DT <- data.table(df)
DT[, Diff := index(Direction), by = "ID"]

Or even

transform(df,
          Diff=unlist(tapply(Direction, ID,
                                function(angle) c(0, diff(Direction)))))

All the above attempts are giving me the same answers as if I were to simply take the difference per row, like so

df$Diff <- c(NA, diff(df$Direction))

This is what I get now

> df
    Direction  Diff  ID
    139        NA    1
    118       -21    1
    180        62    1
    142       -38    1
    185        NA    2
    224        39    2
    137       -87    2
    245        108   2

I hope someone can help me out, much appreciated!

Body:
When you do

angle(118, 180)
## [1] -62

Means

angle(line1, line2)

You are comparing a direction with its consecutive, e.g. the next one.

In the other functions you wrote, the order is reversed, that is

angle(line2, line1)

Just fix that and you obtain the result you want:

library(dplyr)

df %>%
  group_by(ID) %>%
  mutate(diff = (Direction - lead(Direction) + 180) %% 360 -180)
#> Source: local data frame [8 x 4]
#> Groups: ID [2]
#>
#>   Direction  Diff    ID  diff
#>       <int> <int> <int> <dbl>
#> 1       139    NA     1    21
#> 2       118   -21     1   -62
#> 3       180    62     1    38
#> 4       142   -38     1    NA
#> 5       185    NA     2   -39
#> 6       224    39     2    87
#> 7       137   -87     2  -108
#> 8       245   108     2    NA


问:
reading Jframe attribute and writing its value to an xml file
I writing a java program that will read the content of JFrame and based on the value of that an xml file will be created which will contain the attributes and its corresponding value.
I have two classes one having java swing and another creating an xml file.
On my frame i have few check boxes and few combo boxes and I want to create the xml containing attribute and value of these.
I am not able to set the value of these attributes at all in my CreateXML.java file.
If anybody has some solution please help me out.

Regards,
SHK

答:
AlexR is basically right.

However, a far simpler solution to the larger problem is to look into the usage of XMLEncoder, which should handle all of this for you.

ContentLicense: CC BY-SA 2.5


问:
Count of each unique element in a list
Say I have a list of countries

```<code>l = ['India', 'China', 'China', 'Japan', 'USA', 'India', 'USA']
</code>```

and then I have a list of unique countries

```<code>ul = ['India', 'China', 'Japan', 'USA']
</code>```

I want to have a count of each unique country in the list in ascending order. So output should be as follows:

```<code>Japan 1
China 2
India 2
USA   2
</code>```

答:
If you don't want to use a Counter you can count yourself (you already know the unique elements because you have ul) using a dictionary:

```<code>l = ['India', 'China', 'China', 'Japan', 'USA', 'India', 'USA']
ul = ['India', 'China', 'Japan', 'USA']

cnts = dict.fromkeys(ul, 0)  # initialize with 0

# count them
for item in l:
    cnts[item] += 1

# print them in ascending order
for name, cnt in sorted(cnts.items(), key=lambda x: x[1]):  # sort by the count in ascending order
    print(name, cnt)
    # or in case you need the correct formatting (right padding for the name):
    # print('{:<5}'.format(name), cnt)
</code>```

which prints:

```<code>Japan 1
China 2
India 2
USA   2
</code>```

Title: Count of each unique element in a list

Body:
Say I have a list of countries

l = ['India', 'China', 'China', 'Japan', 'USA', 'India', 'USA']

and then I have a list of unique countries

ul = ['India', 'China', 'Japan', 'USA']

I want to have a count of each unique country in the list in ascending order. So output should be as follows:

Japan 1
China 2
India 2
USA   2

Body:
If you don't want to use a Counter you can count yourself (you already know the unique elements because you have ul) using a dictionary:

l = ['India', 'China', 'China', 'Japan', 'USA', 'India', 'USA']
ul = ['India', 'China', 'Japan', 'USA']

cnts = dict.fromkeys(ul, 0)  # initialize with 0

# count them
for item in l:
    cnts[item] += 1

# print them in ascending order
for name, cnt in sorted(cnts.items(), key=lambda x: x[1]):  # sort by the count in ascending order
    print(name, cnt)
    # or in case you need the correct formatting (right padding for the name):
    # print('{:<5}'.format(name), cnt)

which prints:

Japan 1
China 2
India 2
USA   2


问:
Kivy: Is there any widget similar to listview that allows to show a column but with another value (code) related to it?
The problem is simple but I don't know how to solve in Kivy.
    I have some data like: code, name, adress, passport, etc.
    I like to show only the name (can be repeated) in a widget like listview, but when the name is selected I want to know which code is related to it.

Thank's

答:
I have a workarround with a gridlayout (could be a box but...) here is the code:

```<code>    while not fin:
        texto = dataSwitch.GetCampo("RCONS", "DIRECCION")
        codigo = dataSwitch.GetCampo("RCONS", "CODIGO")
        label = Label(text = texto)
        label.codigo = codigo
        label.seleccionable = True
        label.seleccionado = False
        self.g_consorcios.add_widget(label)
        if not dataSwitch.MoveCursor("RCONS"):
            fin = True
</code>```

In the Label I have put everything I need, then I need to get the touched label and call a method to do selection in this I call case on_press_algo

```<code>def on_touch_down(self, touch):
    ret = super(ConsorciosScreen, self).on_touch_down(touch)
    if ret:
        x2, y2 = self.g_consorcios.parent.to_local(touch.x, touch.y)
        for node in self.g_consorcios.children:
            if node.collide_point(x2, y2):
                self.savex = x2
                self.savey = y2
                self.savenode = node
        ret = True
    return ret
def on_touch_up(self, touch):
    ret = super(ConsorciosScreen, self).on_touch_up(touch);
    if ret:
        for node in self.g_consorcios.children:
            x2, y2 = self.g_consorcios.parent.to_local(touch.x, touch.y)
            if node.collide_point(x2, y2):
                if node == self.savenode:
                    if x2 <= self.savex + 10 and x2 >= self.savex - 10 and y2 <= self.savey + 10 and y2 >= self.savey - 10:
                        self.on_press_algo(node)
        ret = True
    return ret;
</code>```

Finally in on_press_algo I pretend the selection and voila, I have my data in nodo.

```<code>    if hasattr(nodo, "seleccionable"):
        if nodo.seleccionado:
            nodo.seleccionado = False
            nodo.color = (1,1,1,1)
        else:
            for node in self.g_consorcios.children:
                if hasattr(node, "seleccionable"):
                    node.color = (1,1,1,1)
                    node.seleccionado = False
            nodo.seleccionado = True
            nodo.color = (1,0,0,1)
</code>```

Body:
I have a workarround with a gridlayout (could be a box but...) here is the code:

    while not fin:
        texto = dataSwitch.GetCampo("RCONS", "DIRECCION")
        codigo = dataSwitch.GetCampo("RCONS", "CODIGO")
        label = Label(text = texto)
        label.codigo = codigo
        label.seleccionable = True
        label.seleccionado = False
        self.g_consorcios.add_widget(label)
        if not dataSwitch.MoveCursor("RCONS"):
            fin = True

In the Label I have put everything I need, then I need to get the touched label and call a method to do selection in this I call case on_press_algo

def on_touch_down(self, touch):
    ret = super(ConsorciosScreen, self).on_touch_down(touch)
    if ret:
        x2, y2 = self.g_consorcios.parent.to_local(touch.x, touch.y)
        for node in self.g_consorcios.children:
            if node.collide_point(x2, y2):
                self.savex = x2
                self.savey = y2
                self.savenode = node
        ret = True
    return ret
def on_touch_up(self, touch):
    ret = super(ConsorciosScreen, self).on_touch_up(touch);
    if ret:
        for node in self.g_consorcios.children:
            x2, y2 = self.g_consorcios.parent.to_local(touch.x, touch.y)
            if node.collide_point(x2, y2):
                if node == self.savenode:
                    if x2 <= self.savex + 10 and x2 >= self.savex - 10 and y2 <= self.savey + 10 and y2 >= self.savey - 10:
                        self.on_press_algo(node)
        ret = True
    return ret;

Finally in on_press_algo I pretend the selection and voila, I have my data in nodo.

    if hasattr(nodo, "seleccionable"):
        if nodo.seleccionado:
            nodo.seleccionado = False
            nodo.color = (1,1,1,1)
        else:
            for node in self.g_consorcios.children:
                if hasattr(node, "seleccionable"):
                    node.color = (1,1,1,1)
                    node.seleccionado = False
            nodo.seleccionado = True
            nodo.color = (1,0,0,1)


问:
Missing help description for task based WCF service
I'm currently hosting a few web services from within a WPF application. I also have enabled automatic help pages to simplify the service documentation. Every OperationContract is decorated with a Description attribute, containing information about the method.

However, whenever I take a look at my help pages, I realize that only methods with a return type of void will correctly display their Description attribute here. Methods returning Task or Task<t> will only say "Service at localhost:XXXXX/ServiceEndpoint".

As this pattern is used for IPC, I rely a lot on async operation contracts, so most of them will return a Task or Task<t>. Is there any way to fix this issue so the help gets displayed correctly?

```<code>namespace App
{
    [ServiceContract]
    public interface IMainService
    {
        [OperationContract]
        [WebGet(UriTemplate = "visibility")]
        [Description("Gets the main window visibility.")]
        Task<bool> GetVisibilityAsync();

        [OperationContract]
        [WebInvoke(UriTemplate = "visibility", Method = "PUT")]
        [Description("Sets the main window visibility.")]
        Task SetVisibilityAsync(bool isVisible);

        [OperationContract]
        [WebInvoke(UriTemplate = "menu", Method = "PUT")]
        [Description("Navigates to the main menu.")]
        void NavigateToMainMenu();

        [OperationContract]
        [WebInvoke(UriTemplate = "shutdown", Method = "PUT")]
        [Description("Requests the application to shutdown.")]
        void RequestApplicationShutdown();
    }
}
</code>```

Here is my app.config

```<code><system.web>
    <compilation debug="false" targetFramework="4.5" />
  </system.web>

  <system.serviceModel>
    <services>

      <service name="App.MainService" behaviorConfiguration="rpcServiceBehavior">
        <endpoint binding="webHttpBinding"
                  contract="App.IMainService"
                  behaviorConfiguration="webHttpBehavior"
                  name="RpcEndpoint"/>
        <host>
          <baseAddresses>
            <add baseAddress="http://localhost:25565/main"/>
          </baseAddresses>
        </host>
      </service>

    </services>

    <behaviors>
      <serviceBehaviors>
        <behavior name="rpcServiceBehavior" >
          <serviceMetadata httpGetEnabled="true" />
          <serviceDebug includeExceptionDetailInFaults="true" />
        </behavior>
      </serviceBehaviors>
      <endpointBehaviors>
        <behavior name="webHttpBehavior">
          <webHttp helpEnabled="true" automaticFormatSelectionEnabled="true"/>
        </behavior>
      </endpointBehaviors>
    </behaviors>
  </system.serviceModel>

  <system.webServer>
    <modules runAllManagedModulesForAllRequests="true"/>
  </system.webServer>
</code>```

答:
Try to debug with another browser (or in incognito mode).

Explanation:

This is because you probably added a few descriptions, checked it on your browser. Then you added more description tags and checked it again on your browser which, instead of reloading the page, opened the one in cache. Browser will open page in browser in cache instead of reloading it when the page is static.

Body:
I'm currently hosting a few web services from within a WPF application. I also have enabled automatic help pages to simplify the service documentation. Every OperationContract is decorated with a Description attribute, containing information about the method.

However, whenever I take a look at my help pages, I realize that only methods with a return type of void will correctly display their Description attribute here. Methods returning Task or Task<t> will only say "Service at localhost:XXXXX/ServiceEndpoint".

As this pattern is used for IPC, I rely a lot on async operation contracts, so most of them will return a Task or Task<t>. Is there any way to fix this issue so the help gets displayed correctly?

namespace App
{
    [ServiceContract]
    public interface IMainService
    {
        [OperationContract]
        [WebGet(UriTemplate = "visibility")]
        [Description("Gets the main window visibility.")]
        Task<bool> GetVisibilityAsync();

        [OperationContract]
        [WebInvoke(UriTemplate = "visibility", Method = "PUT")]
        [Description("Sets the main window visibility.")]
        Task SetVisibilityAsync(bool isVisible);

        [OperationContract]
        [WebInvoke(UriTemplate = "menu", Method = "PUT")]
        [Description("Navigates to the main menu.")]
        void NavigateToMainMenu();

        [OperationContract]
        [WebInvoke(UriTemplate = "shutdown", Method = "PUT")]
        [Description("Requests the application to shutdown.")]
        void RequestApplicationShutdown();
    }
}

Here is my app.config

<system.web>
    <compilation debug="false" targetFramework="4.5" />
  </system.web>

  <system.serviceModel>
    <services>

      <service name="App.MainService" behaviorConfiguration="rpcServiceBehavior">
        <endpoint binding="webHttpBinding"
                  contract="App.IMainService"
                  behaviorConfiguration="webHttpBehavior"
                  name="RpcEndpoint"/>
        <host>
          <baseAddresses>
            <add baseAddress="http://localhost:25565/main"/>
          </baseAddresses>
        </host>
      </service>

    </services>

    <behaviors>
      <serviceBehaviors>
        <behavior name="rpcServiceBehavior" >
          <serviceMetadata httpGetEnabled="true" />
          <serviceDebug includeExceptionDetailInFaults="true" />
        </behavior>
      </serviceBehaviors>
      <endpointBehaviors>
        <behavior name="webHttpBehavior">
          <webHttp helpEnabled="true" automaticFormatSelectionEnabled="true"/>
        </behavior>
      </endpointBehaviors>
    </behaviors>
  </system.serviceModel>

  <system.webServer>
    <modules runAllManagedModulesForAllRequests="true"/>
  </system.webServer>


问:
JQuery - siblings based on next()
Siblings based on next(), but looks like it is still based on the selector before next function, so I used next() for siblings, but not working. The section commented out is working in JSFiddle, anyone can figure it out the second JS code? Thanks!

```<code>$('.touch').click(function() {
  $(this).next().toggle().siblings().next().hide();
});
</code>```

答:
next() refers to the next child of the parent, so next has to be applied to the parent element. So you would do something like this to grab the next sibling.</p>

```<code> $(this).parent().next()....
</code>```

Title: JQuery - siblings based on next()

Body:
Siblings based on next(), but looks like it is still based on the selector before next function, so I used next() for siblings, but not working. The section commented out is working in JSFiddle, anyone can figure it out the second JS code? Thanks!

$('.touch').click(function() {
  $(this).next().toggle().siblings().next().hide();
});

Body:
next() refers to the next child of the parent, so next has to be applied to the parent element. So you would do something like this to grab the next sibling.

 $(this).parent().next()....


问:
Android 7.0 Toggle Airplane Mode Programatically
I have tried all solutions already provided on StackOverflow but they are all quite old and no one seem to have tried it for nougat. I am making a utility tool which allows a user to toggle airplane mode on nougat, Someone please share a way to do that programatically. Also I have not been able to find any help regarding notification pull down programatically.</p>

答: You can't toggle airplane mode programatically. Check the Official Android 4.2 API Documentation</p>


答:
I have a Visual Studio 2008 C++
  project where I have a class that
  inherits from a virtual base class and
  another template class that implements
  a function in the virtual base class.

Wrong: Your code has no virtual base classes.

Here is your code (as I'm writing this):

```<code>class Foo;

struct Buzz
{
    virtual ~Buzz() {};
    virtual void Buzz_Do( Foo* ) = 0;
};

class Base
{
public:
    virtual ~Base() {};
    virtual void Base_Do( Buzz* ) = 0;
};

template< class T >
class Bar
{
public:
    virtual void Base_Do( Buzz* v )
    {
        v->Buzz_Do( static_cast< T* >( this ) );
    };
};

class Foo : public Base, public Bar< Foo >
{
};

int _tmain(int argc, _TCHAR* argv[])
{
    Foo c;
    return 0;
}
</code>```

Further,

Wrong: The pure virtual member function Buzz_Do is not implemented anywhere.

Wrong: Your code lacks a main function (although readers could supply one, I guess).

Wrong: The macro (or type) _TCHAR is nowhere defined.

Having said that, virtual inheritance – which you claim that your actual code is using – is one possible answer to the question that it seems you intended to ask.

However, with your invalid presented code and incorrect assertions about that code, not much can reasonably be said. I note that others have tried anyway. Perhaps, if you're lucky, one of those answers will fit the bill, but it's just a game of chance.

Cheers & hth.,

Title: implementing an abstract base class function in another template base class

Body:
I have a Visual Studio 2008 C++
  project where I have a class that
  inherits from a virtual base class and
  another template class that implements
  a function in the virtual base class.

Wrong: Your code has no virtual base classes.

Here is your code (as I'm writing this):

class Foo;

struct Buzz
{
    virtual ~Buzz() {};
    virtual void Buzz_Do( Foo* ) = 0;
};

class Base
{
public:
    virtual ~Base() {};
    virtual void Base_Do( Buzz* ) = 0;
};

template< class T >
class Bar
{
public:
    virtual void Base_Do( Buzz* v )
    {
        v->Buzz_Do( static_cast< T* >( this ) );
    };
};

class Foo : public Base, public Bar< Foo >
{
};

int _tmain(int argc, _TCHAR* argv[])
{
    Foo c;
    return 0;
}

Further,

Wrong: The pure virtual member function Buzz_Do is not implemented anywhere.

Wrong: Your code lacks a main function (although readers could supply one, I guess).

Wrong: The macro (or type) _TCHAR is nowhere defined.

Having said that, virtual inheritance – which you claim that your actual code is using – is one possible answer to the question that it seems you intended to ask.

However, with your invalid presented code and incorrect assertions about that code, not much can reasonably be said. I note that others have tried anyway. Perhaps, if you're lucky, one of those answers will fit the bill, but it's just a game of chance.

Cheers & hth.,


答:
first: no, you class does not extend any class, so you do not have to call super. I think you're confusing something like

```<code>class SomeComponent extends React.Component {
  constructor(props) {
    super(props)
    ...
  }
}
</code>```

second, depends what you want the this context to be - if you want it to be SomeOtherUtil then yes, you need to bind it... but you probably don't.

Title: React JS How to Set State in One Component from Another Functional Component

Body:
first: no, you class does not extend any class, so you do not have to call super. I think you're confusing something like

class SomeComponent extends React.Component {
  constructor(props) {
    super(props)
    ...
  }
}

second, depends what you want the this context to be - if you want it to be SomeOtherUtil then yes, you need to bind it... but you probably don't.


问:
What is $model in Yii2?
I'm new to MVC and Yii Framework. The $model variable seems very confusing to me.

Where is it declared in the fist place? Where does it come from?

When I work with GridView I see that some functions take $model as a parameter. Neither model nor model search of this GridView declares $model variable anywhere. Yet it is widely used in all sorts of data management. It just doesn't make sense to me.

So I need a simple, straight forward, "for dummies" explanation of $model variable in Yii Framework v2. Help in clarifying these questions is much appreciated:
1. What is the origin of $model variable?
2. How to identify what model of the app is the $model variable representing when it's used in view files?
3. There are sometimes multiple $model variables in a single view file. Do all of them represent one model class? How to distinguish them when used for multiple classes?

Thanks.

答:
The $model is a var as the others  ...normally in the yii2 samples  contain an instance of a model class (as tiplically an active record=)

assuming you have a class

```<code> class Category extends \yii\db\ActiveRecord
 {
  ........
</code>```

a tipical code  could be

```<code> $model = Category::findOne($id);
</code>```

where Category::findOne($id) find an instance form database using $id as primary key and assign the result to $model ..

then you can access  to the instance attribute (eg:attribute1) using

```<code>$model->attribute1
</code>```

you can take a look at this guide

http://www.yiiframework.com/doc-2.0/guide-index.html
http://www.yiiframework.com/doc-2.0/guide-structure-models.html
http://www.yiiframework.com/doc-2.0/guide-db-active-record.html

Title: What is $model in Yii2?

Body:
The $model is a var as the others  ...normally in the yii2 samples  contain an instance of a model class (as tiplically an active record=)

assuming you have a class

 class Category extends \yii\db\ActiveRecord
 {
  ........

a tipical code  could be

 $model = Category::findOne($id);

where Category::findOne($id) find an instance form database using $id as primary key and assign the result to $model ..

then you can access  to the instance attribute (eg:attribute1) using

$model->attribute1

you can take a look at this guide

http://www.yiiframework.com/doc-2.0/guide-index.html
http://www.yiiframework.com/doc-2.0/guide-structure-models.html
http://www.yiiframework.com/doc-2.0/guide-db-active-record.html


问:
404 error on azure for Asp.Net Web Api Project
I have deployed exact same solution on two servers, one is my own server in my basement and the other one is Microsoft Azure. The project is developed using Asp.Net Web Api 2.
On my own windows server running IIS 8.5 it totally works. For test, you can simply browse this link in your browser and see the error message {"Message":"The requested resource does not support http method 'GET'."} which shows the API has been hit.1

But exact same project on my Azure domain here, you just get a message saying

The resource you are looking for has been removed, had its name
  changed, or is temporarily unavailable.

Everything about these two deployments is the same (to the best of my knowledge) and I was wondering if there is any further steps necessary on Web Api app deployment in MS Azure which I am missing.

答:
Ah, my problem was probably a common one. I was using

```<code>rootconfig = System.Web.Configuration.WebconfigurationManager.OpenWebConfiguration(null);
</code>```

and that was returning the root web because the parameter was null.
When I ran it local that worked fine, but after I deployed the root Config was NOT what I wanted and my code was failing.

Switched to direct access via

```<code>stringVal = WebconfigurationManager.AppSettings["Foobar"].ToString();
</code>```

Nice. Plus less overhead.

Body:
Ah, my problem was probably a common one. I was using

rootconfig = System.Web.Configuration.WebconfigurationManager.OpenWebConfiguration(null);

and that was returning the root web because the parameter was null.
When I ran it local that worked fine, but after I deployed the root Config was NOT what I wanted and my code was failing.

Switched to direct access via

stringVal = WebconfigurationManager.AppSettings["Foobar"].ToString();

Nice. Plus less overhead.


问:
How do you create a sitemap index in Django?
The Django documentation is very minimal and I can't seem to get this to work.

Currently I have 3 individual sitemaps, and I would like to create a sitemap index for them:

```<code>(r'^sitemap1\.xml$', 'django.contrib.sitemaps.views.sitemap', {'sitemaps':sitemap1}),
(r'^sitemap2\.xml$', 'django.contrib.sitemaps.views.sitemap', {'sitemaps':sitemap2}),
(r'^sitemap3\.xml$', 'django.contrib.sitemaps.views.sitemap', {'sitemaps':sitemap3}),
</code>```

The Django documentation mentions adding something along the lines of:

```<code>url(r'^sitemap-(?P<section>.+)\.xml$', views.sitemap, {'sitemaps': sitemaps},name='django.contrib.sitemaps.views.sitemap'),
</code>```

What is "section" in this case? And how do I access this index file? Is it downloadable or is it accessible via a url?

Any help is greatly appreciated!

Edit
Basically I would like to accomplish this in Django: https://support.google.com/webmasters/answer/75712

答:
If you included the app with a namespace (e.g. include('myapp.urls', namespace='myapp'), then you need to include the namespace when reversing, e.g. {% url 'myapp:my_url_name' %} or reverse('myapp:my_url_name').

```<code>url(r'^sitemap-(?P<section>.+)\.xml$', cache_page(86400)(views.sitemap), {'sitemaps': sitemaps}, name='sitemapsname'),
url(r'^sitemap\.xml$', cache_page(86400)(views.index), {'sitemaps': sitemaps, 'sitemap_url_name': 'posts:sitemapsname'}),
</code>```

note: posts:sitemapsname is my app

see source code of Django: https://github.com/django/django/blob/master/django/contrib/sitemaps/views.py

Body:
The Django documentation is very minimal and I can't seem to get this to work.

Currently I have 3 individual sitemaps, and I would like to create a sitemap index for them:

(r'^sitemap1\.xml$', 'django.contrib.sitemaps.views.sitemap', {'sitemaps':sitemap1}),
(r'^sitemap2\.xml$', 'django.contrib.sitemaps.views.sitemap', {'sitemaps':sitemap2}),
(r'^sitemap3\.xml$', 'django.contrib.sitemaps.views.sitemap', {'sitemaps':sitemap3}),

The Django documentation mentions adding something along the lines of:

url(r'^sitemap-(?P
.+)\.xml$', views.sitemap, {'sitemaps': sitemaps},name='django.contrib.sitemaps.views.sitemap'),

What is "section" in this case? And how do I access this index file? Is it downloadable or is it accessible via a url?

Any help is greatly appreciated!

Edit
Basically I would like to accomplish this in Django: https://support.google.com/webmasters/answer/75712

Body:
If you included the app with a namespace (e.g. include('myapp.urls', namespace='myapp'), then you need to include the namespace when reversing, e.g. {% url 'myapp:my_url_name' %} or reverse('myapp:my_url_name').

url(r'^sitemap-(?P<section>.+)\.xml$', cache_page(86400)(views.sitemap), {'sitemaps': sitemaps}, name='sitemapsname'),
url(r'^sitemap\.xml$', cache_page(86400)(views.index), {'sitemaps': sitemaps, 'sitemap_url_name': 'posts:sitemapsname'}),

note: posts:sitemapsname is my app

see source code of Django: https://github.com/django/django/blob/master/django/contrib/sitemaps/views.py


问:
Rails: Customize Devise Confirmable module?
I have my Rails app setup with Devise, but it's still in the development stages. I also have a Thor task that creates the default Admin user.

Problem is Devise won't let that admin user login to the site until the account is confirmed. Is there any way I can disable the confirmable module for the creation of specific users, such as Admin?

My Thor task:

```<code>class Setup < Thor
  desc "create_admin [EMAIL] [PASSWORD]", "Creates the administrative user."
  def create_admin(email = "admin@bogus.com", password = "testpassword123")
    require File.expand_path('config/environment.rb') # load Rails environment
    admin = User.create(:email => email, :password => password, :password_confirmation => password)
    admin.assign_role :admin
    puts "Admin user (#{ email }) created."
  end
end
</code>```

答:
just coment :confirmable in User or Admin model

```<code>devise :database_authenticatable, :recoverable, :rememberable, :trackable, #:confirmable...
</code>```

In config/inicializers/devise.rb
you can set here how many time user have to confirm his account

Body:
I have my Rails app setup with Devise, but it's still in the development stages. I also have a Thor task that creates the default Admin user.

Problem is Devise won't let that admin user login to the site until the account is confirmed. Is there any way I can disable the confirmable module for the creation of specific users, such as Admin?

My Thor task:

class Setup < Thor
  desc "create_admin [EMAIL] [PASSWORD]", "Creates the administrative user."
  def create_admin(email = "admin@bogus.com", password = "testpassword123")
    require File.expand_path('config/environment.rb') # load Rails environment
    admin = User.create(:email => email, :password => password, :password_confirmation => password)
    admin.assign_role :admin
    puts "Admin user (#{ email }) created."
  end
end

Body:
just coment :confirmable in User or Admin model

devise :database_authenticatable, :recoverable, :rememberable, :trackable, #:confirmable...

In config/inicializers/devise.rb
you can set here how many time user have to confirm his account


问:
How to set clientId from URL with getClientIdFromUrl()
How to set client Id from URL "site.com/?clientId=1576731351.1495454236"

I try to use in

```<code>ga('create', 'UA-XXXXX-Y', 'auto', {
  'clientId': getClientIdFromUrl()
});
</code>```

But error:

Uncaught ReferenceError: getClientIdFromUrl is not defined

How to set clientId? How to define getClientIdFromUrl?
I get this code from official google page https://developers.google.com/analytics/devguides/collection/analyticsjs/cross-domain#setting_the_client_id_on_the_destination_domain

答:
This seems to come straight from the example on the comm docs. This function is not defined you are supposed to define it yourself. Here's an example definition from this other StackOverflow question.

```<code>function getClientIdFromUrl() {
    var url = window.location.href;
    var regex = new RegExp("[?&]clientId(=([^&#]*)|&|#|$)"),
        results = regex.exec(url);
    if (!results) return null;
    if (!results[2]) return '';
    return decodeURIComponent(results[2].replace(/\+/g, " "));
}
</code>```

That being said this is fairly unusual in Google Analytics implementations. You haven't shared much about your use case, but if all you are trying to do is pass clientIds from one domain to the other I would instead take a look at the Linker plugin.

Body:
How to set client Id from URL "site.com/?clientId=1576731351.1495454236"

I try to use in

ga('create', 'UA-XXXXX-Y', 'auto', {
  'clientId': getClientIdFromUrl()
});

But error:

Uncaught ReferenceError: getClientIdFromUrl is not defined

How to set clientId? How to define getClientIdFromUrl?
I get this code from official google page https://developers.google.com/analytics/devguides/collection/analyticsjs/cross-domain#setting_the_client_id_on_the_destination_domain

Body:
This seems to come straight from the example on the comm docs. This function is not defined you are supposed to define it yourself. Here's an example definition from this other StackOverflow question.

function getClientIdFromUrl() {
    var url = window.location.href;
    var regex = new RegExp("[?&]clientId(=([^&#]*)|&|#|$)"),
        results = regex.exec(url);
    if (!results) return null;
    if (!results[2]) return '';
    return decodeURIComponent(results[2].replace(/\+/g, " "));
}

That being said this is fairly unusual in Google Analytics implementations. You haven't shared much about your use case, but if all you are trying to do is pass clientIds from one domain to the other I would instead take a look at the Linker plugin.


问:
How to Update (Add/Modify/Delete) keys in AppSettings section of web.config at runtime
I like to Update keys/Values defined in AppSettings section of Web.config at runtime. however I DO NOT want to actually save them to Web.config file.

I have a huge web application that have consists of many modules, DLLs and source code files. A bunch of critical information ranged from database configuration, encryption keys, username and passwords for webservices are saved in AppSettings section of the web.config file. Recent project requirement needs me to move these values out of web.config and keep in a secure storage.

I already secured these values in an external location and I can read them back when application starts.

here is the sample code.

Global.asax

```<code>public class Global: System.Web.HttpApplication {
    protected void Application_Start(object sender, EventArgs e) {
        Dictionary<string, string> secureConfig = new Dictionary<string,string>{};

        // --------------------------------------------------------------------
        // Here I read and decrypt keys and add them to secureConfig dictionary
        // To test assume the following line is a key stored in secure sotrage.
        //secureConfig = SecureConfig.LoadConfig();
        secureConfig.Add("ACriticalKey","VeryCriticalValue");
        // --------------------------------------------------------------------

        foreach (KeyValuePair<string, string> item in secureConfig) {
            ConfigurationManager.AppSettings.Add(item.Key, item.Value);
        }
    }
}
</code>```

As you may noticed it is not feasible to change references to AppSettings in a massive code created by multiple programming teams to read their settings from my secureConfig dictionary and on the other hand I should not save these values in web.config file which is available to web administrators and operators, system admins and cloud admins.

To Make programmers life easier, I want to let them add their values to AppSettings section of web.config during development, but they will be removed from there and put to secure storage later during deployment, however these values should be available to program transparently as they are still in AppSettings section.

Question: how can I add values to AppSettings at runtime so program can read them using ConfigurationManager.AppSettings["ACriticalKey"] to get "VeryCriticalValue" without saving them in Web.Config?

Please note: ConfigurationManager.AppSettings.Add(item.Key, item.Value); gives me ConfigurationErrorsException with message The configuration is read only.

Please note: Preferably some settings should be able to stay in AppSettings as before

答:
I know this is an old question, but I ran into the same problem and I found that Set works in the same way as Add, and does not throw an exception, so just replace Add with Set, like so:</p>

```<code>ConfigurationManager.AppSettings.Set(item.Key, item.Value);
</code>```

Body:
I like to Update keys/Values defined in AppSettings section of Web.config at runtime. however I DO NOT want to actually save them to Web.config file.

I have a huge web application that have consists of many modules, DLLs and source code files. A bunch of critical information ranged from database configuration, encryption keys, username and passwords for webservices are saved in AppSettings section of the web.config file. Recent project requirement needs me to move these values out of web.config and keep in a secure storage.

I already secured these values in an external location and I can read them back when application starts.

here is the sample code.

Global.asax

public class Global: System.Web.HttpApplication {
    protected void Application_Start(object sender, EventArgs e) {
        Dictionary<string, string> secureConfig = new Dictionary<string,string>{};

        // --------------------------------------------------------------------
        // Here I read and decrypt keys and add them to secureConfig dictionary
        // To test assume the following line is a key stored in secure sotrage.
        //secureConfig = SecureConfig.LoadConfig();
        secureConfig.Add("ACriticalKey","VeryCriticalValue");
        // --------------------------------------------------------------------

        foreach (KeyValuePair<string, string> item in secureConfig) {
            ConfigurationManager.AppSettings.Add(item.Key, item.Value);
        }
    }
}

As you may noticed it is not feasible to change references to AppSettings in a massive code created by multiple programming teams to read their settings from my secureConfig dictionary and on the other hand I should not save these values in web.config file which is available to web administrators and operators, system admins and cloud admins.

To Make programmers life easier, I want to let them add their values to AppSettings section of web.config during development, but they will be removed from there and put to secure storage later during deployment, however these values should be available to program transparently as they are still in AppSettings section.

Question: how can I add values to AppSettings at runtime so program can read them using ConfigurationManager.AppSettings["ACriticalKey"] to get "VeryCriticalValue" without saving them in Web.Config?

Please note: ConfigurationManager.AppSettings.Add(item.Key, item.Value); gives me ConfigurationErrorsException with message The configuration is read only.

Please note: Preferably some settings should be able to stay in AppSettings as before

Body:
I know this is an old question, but I ran into the same problem and I found that Set works in the same way as Add, and does not throw an exception, so just replace Add with Set, like so:

ConfigurationManager.AppSettings.Set(item.Key, item.Value);


问:
jquery animate rotate div multiple times on click
I would like to rotate this div on click using animate (not rotate, no plugins), and also set how many times it can rotate. Here is the code

$('#foo').animate({  borderSpacing: -90 }, {
    step: function(now,fx) {
      $(this).css('-webkit-transform','rotate('+now+'deg)');
      $(this).css('-moz-transform','rotate('+now+'deg)');
      $(this).css('transform','rotate('+now+'deg)');
    },
    duration:'slow'
},'linear');```
<pre class="snippet-code-css lang-css prettyprint-override"><code>body {
    font-family: sans-serif;
}

#foo {
    width:100px;
    height:100px;
    position:absolute;
    top:100px;
    left:100px;
    border-spacing: 0;
    background-color:red;
}</code>```

Text

See inspiration```

答:
1st: You need to use deg instead of borderSpacing to avoid reset every time

2nd: I create two functions one for rotate and another one to reset the rotation

3rd: add data attribute to catch the angle and the change on it

The next code/comments will explain those steps: Please read the comments on code carefully

$(document).ready(function(){
  $('#foo').on('click' , function(){ // element click event
    var rotate_deg = parseInt($(this).data('rotate')); // get the data-rotate attribute in this case will return -90 change it on html if you like
    var next_rotation_angle = rotate_deg - 90; //for a new rotation angle .. in this case I use rotate_deg * 2 change it as you like
    var Times = 3; // how many rotate available
    if(rotate_deg / 90 >= -Times){
      RotateIt($(this) , rotate_deg); // run a function to rotate the element
      $(this).data('rotate' , next_rotation_angle); // append a new angle to data-rotate attribute
    }else{alert('Can not click any more')}
  });
  $('#reset_rotation').on('click' , function(){ // reset button click event
    ResetRotate($('#foo')); // reset the element rotation to 0
    $('#foo').data('rotate' , '-90');
  });
});
//function to rotate .. use this code to rotate any element you need by using RotateIt(element , rotate_deg);
function RotateIt(el , deg){
  $(el).stop().animate({deg: deg}, {
      step: function(now,fx) {
        $(this).css('-webkit-transform','rotate('+now+'deg)');
        $(this).css('-moz-transform','rotate('+now+'deg)');
        $(this).css('transform','rotate('+now+'deg)');
      },
      duration:'slow'
  },'linear');
}
// function to reset the rotate .. while deg here is 0 no need to set deg as an argument
function ResetRotate(el){
  $(el).stop().animate({deg: 0}, {
      step: function(now,fx) {
        $(this).css('-webkit-transform','rotate('+now+'deg)');
        $(this).css('-moz-transform','rotate('+now+'deg)');
        $(this).css('transform','rotate('+now+'deg)');
      },
      duration:'slow'
  },'linear');
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>body {
    font-family: sans-serif;
}

#foo {
    width:100px;
    height:100px;
    position:absolute;
    top:100px;
    left:100px;
    border-spacing: 0;
    background-color:red;
}</code>```

Text

See inspiration
<button id="reset_rotation">Reset Rotation</button>```

Body:
I would like to rotate this div on click using animate (not rotate, no plugins), and also set how many times it can rotate. Here is the code

$('#foo').animate({  borderSpacing: -90 }, {
    step: function(now,fx) {
      $(this).css('-webkit-transform','rotate('+now+'deg)');
      $(this).css('-moz-transform','rotate('+now+'deg)');
      $(this).css('transform','rotate('+now+'deg)');
    },
    duration:'slow'
},'linear');

body {
    font-family: sans-serif;
}

#foo {
    width:100px;
    height:100px;
    position:absolute;
    top:100px;
    left:100px;
    border-spacing: 0;
    background-color:red;
}

Text

See inspiration

Body:
1st: You need to use deg instead of borderSpacing to avoid reset every time

2nd: I create two functions one for rotate and another one to reset the rotation

3rd: add data attribute to catch the angle and the change on it

The next code/comments will explain those steps: Please read the comments on code carefully

$(document).ready(function(){
  $('#foo').on('click' , function(){ // element click event
    var rotate_deg = parseInt($(this).data('rotate')); // get the data-rotate attribute in this case will return -90 change it on html if you like
    var next_rotation_angle = rotate_deg - 90; //for a new rotation angle .. in this case I use rotate_deg * 2 change it as you like
    var Times = 3; // how many rotate available
    if(rotate_deg / 90 >= -Times){
      RotateIt($(this) , rotate_deg); // run a function to rotate the element
      $(this).data('rotate' , next_rotation_angle); // append a new angle to data-rotate attribute
    }else{alert('Can not click any more')}
  });
  $('#reset_rotation').on('click' , function(){ // reset button click event
    ResetRotate($('#foo')); // reset the element rotation to 0
    $('#foo').data('rotate' , '-90');
  });
});
//function to rotate .. use this code to rotate any element you need by using RotateIt(element , rotate_deg);
function RotateIt(el , deg){
  $(el).stop().animate({deg: deg}, {
      step: function(now,fx) {
        $(this).css('-webkit-transform','rotate('+now+'deg)');
        $(this).css('-moz-transform','rotate('+now+'deg)');
        $(this).css('transform','rotate('+now+'deg)');
      },
      duration:'slow'
  },'linear');
}
// function to reset the rotate .. while deg here is 0 no need to set deg as an argument
function ResetRotate(el){
  $(el).stop().animate({deg: 0}, {
      step: function(now,fx) {
        $(this).css('-webkit-transform','rotate('+now+'deg)');
        $(this).css('-moz-transform','rotate('+now+'deg)');
        $(this).css('transform','rotate('+now+'deg)');
      },
      duration:'slow'
  },'linear');
}

body {
    font-family: sans-serif;
}

#foo {
    width:100px;
    height:100px;
    position:absolute;
    top:100px;
    left:100px;
    border-spacing: 0;
    background-color:red;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="foo" data-rotate="-90">Text</div>
<p>See <a href="http://jsfiddle.net/ryleyb/ERRmd/">inspiration</a>
<button id="reset_rotation">Reset Rotation</button>


问:
How to convert a set of bytes in an array from hexa to decimal (python)?
I have a file which contains in each line a set of bytes for example:

```<code>4655d16c690f2789c2d3e803e388637f
16161b1504137217336d403e2a03c669
fa79c5ffe35d112915f0f3243fc68fb4
87d57d0a63e52b6df869eb5c0aac4328
640c2eefb7829d863f7aa686bc513acc
4024767c463558b7c7cd0ffd4f0aaa6d
18ee0b17f5b5206df0443e658b105990
7b40bf42d2cfc290eed4c4edcb9d3e91
b57dad9833c3e174e05a5ae75cac70ed
</code>```

I want to convert line in an array,then convert byte in decimal, for example:

```<code>4655d16c690f2789c2d3e803e388637f
</code>```

The result is:

```<code>46 55 d1 6c 69 0f 27 89 c2 d3 e8 03 e3 88 63 7f
</code>```

Then convert each byte in decimal:

```<code> [70,85,209,108,105,15,39,137,194,211,232,3,136,227,99,127]
</code>```

I try by using this code ,

```<code>with open(Srcpath, 'r') as f:
        with open(Destpath, 'w') as fp:
            for key in f:
                key_Separated=[key[i:i+2] for i in range(0, len(key), 2)]
                rejoined = ' '.join(key_Separated)
                Decimal= [i for i, b in enumerate(rejoined ) if b=='1']
                print(Decimal)
                fp.write(str(Decimal))
</code>```

so it gives this wrong results:

```<code>[43]
[21, 45]
[27, 42]
[13, 31, 37, 42]
[16, 21, 28]
[13, 36]
[12, 43, 46]
[0, 6, 18, 27, 37]
</code>```

How could I correct them please?

Body:
I have a file which contains in each line a set of bytes for example:

4655d16c690f2789c2d3e803e388637f
16161b1504137217336d403e2a03c669
fa79c5ffe35d112915f0f3243fc68fb4
87d57d0a63e52b6df869eb5c0aac4328
640c2eefb7829d863f7aa686bc513acc
4024767c463558b7c7cd0ffd4f0aaa6d
18ee0b17f5b5206df0443e658b105990
7b40bf42d2cfc290eed4c4edcb9d3e91
b57dad9833c3e174e05a5ae75cac70ed

I want to convert line in an array,then convert byte in decimal, for example:

4655d16c690f2789c2d3e803e388637f

The result is:

46 55 d1 6c 69 0f 27 89 c2 d3 e8 03 e3 88 63 7f

Then convert each byte in decimal:

 [70,85,209,108,105,15,39,137,194,211,232,3,136,227,99,127]

I try by using this code ,

with open(Srcpath, 'r') as f:
        with open(Destpath, 'w') as fp:
            for key in f:
                key_Separated=[key[i:i+2] for i in range(0, len(key), 2)]
                rejoined = ' '.join(key_Separated)
                Decimal= [i for i, b in enumerate(rejoined ) if b=='1']
                print(Decimal)
                fp.write(str(Decimal))

so it gives this wrong results:

[43]
[21, 45]
[27, 42]
[13, 31, 37, 42]
[16, 21, 28]
[13, 36]
[12, 43, 46]
[0, 6, 18, 27, 37]

How could I correct them please?

Body:
Python has a built-in library for the conversion you want.  Given your data as data.txt:

#!python3
from binascii import unhexlify
from pprint import pprint

with open('data.txt') as f:
    pprint([list(unhexlify(line.strip())) for line in f])

[[70, 85, 209, 108, 105, 15, 39, 137, 194, 211, 232, 3, 227, 136, 99, 127],
 [22, 22, 27, 21, 4, 19, 114, 23, 51, 109, 64, 62, 42, 3, 198, 105],
 [250, 121, 197, 255, 227, 93, 17, 41, 21, 240, 243, 36, 63, 198, 143, 180],
 [135, 213, 125, 10, 99, 229, 43, 109, 248, 105, 235, 92, 10, 172, 67, 40],
 [100, 12, 46, 239, 183, 130, 157, 134, 63, 122, 166, 134, 188, 81, 58, 204],
 [64, 36, 118, 124, 70, 53, 88, 183, 199, 205, 15, 253, 79, 10, 170, 109],
 [24, 238, 11, 23, 245, 181, 32, 109, 240, 68, 62, 101, 139, 16, 89, 144],
 [123, 64, 191, 66, 210, 207, 194, 144, 238, 212, 196, 237, 203, 157, 62, 145],
 [181, 125, 173, 152, 51, 195, 225, 116, 224, 90, 90, 231, 92, 172, 112, 237]]

If using Python 2 a byte string doesn't convert into a list of integers, so there is another loop to do the conversion:

#!python2
from binascii import unhexlify
from pprint import pprint

with open('data.txt') as f:
    pprint([[ord(b) for b in unhexlify(line.strip())] for line in f])


问:
How do I create a HashMap literal?
How I can create a HashMap literal in Rust? In Python I can do it so:

hashmap = {
   'element0': {
       'name': 'My New Element',
       'childs': {
           'child0': {
               'name': 'Child For Element 0',
               'childs': {
                   ...
               }
           }
       }
   },
   ...
}
```
<p>And in Go like this:</p>
<pre class="lang-golang prettyprint-override"><code>type Node struct {
    name string
    childs map[string]Node
}

hashmap := map[string]Node {
    "element0": Node{
        "My New Element",
        map[string]Node {
            'child0': Node{
                "Child For Element 0",
                map[string]Node {}
            }
        }
    }
}
</code>```

答:
I recommend the maplit crate.

To quote from the documentation:

Macros for container literals with specific type.

use maplit::hashmap;

let map = hashmap!{
    "a" => 1,
    "b" => 2,
};
```

The maplit crate uses => syntax for the mapping macros. It is not possible to use : as separator due to syntactic the restrictions in regular macro_rules! macros.

Note that rust macros are flexible in which brackets you use for the invocation. You can use them as hashmap!{} or hashmap![] or hashmap!(). This crate suggests {} as the convention for the map & set macros, it matches their Debug output.

Macros

btreemap  Create a BTreeMap from a list of key-value pairs

btreeset  Create a BTreeSet from a list of elements.

hashmap   Create a HashMap from a list of key-value pairs

hashset   Create a HashSet from a list of elements.

ContentLicense: CC BY-SA 4.0

Title: How do I create a HashMap literal?

Body:
How I can create a HashMap literal in Rust? In Python I can do it so:

hashmap = {
   'element0': {
       'name': 'My New Element',
       'childs': {
           'child0': {
               'name': 'Child For Element 0',
               'childs': {
                   ...
               }
           }
       }
   },
   ...
}

And in Go like this:

type Node struct {
    name string
    childs map[string]Node
}

hashmap := map[string]Node {
    "element0": Node{
        "My New Element",
        map[string]Node {
            'child0': Node{
                "Child For Element 0",
                map[string]Node {}
            }
        }
    }
}

Body:
I recommend the maplit crate.

To quote from the documentation:

Macros for container literals with specific type.

use maplit::hashmap;

let map = hashmap!{
    "a" => 1,
    "b" => 2,
};

The maplit crate uses => syntax for the mapping macros. It is not possible to use : as separator due to syntactic the restrictions in regular macro_rules! macros.

Note that rust macros are flexible in which brackets you use for the invocation. You can use them as hashmap!{} or hashmap![] or hashmap!(). This crate suggests {} as the convention for the map & set macros, it matches their Debug output.

Macros

btreemap  Create a BTreeMap from a list of key-value pairs

btreeset  Create a BTreeSet from a list of elements.

hashmap   Create a HashMap from a list of key-value pairs

hashset   Create a HashSet from a list of elements.


问:
Node.js - Globals config file with inter-dependent variables
I have a globals.js file that needs to be accessible across multiple files in my app.

These globals are inter-dependent, and I would like to set up my data file so that the parameters are relative to one another. I am trying the following:

```<code>const config = {
  "canvas": {
    "width": 600,
  },
  "shape": {
    "width": function() {
      return config.canvas.width*0.9;
    };
  },
};

module.exports = config;
</code>```

The idea is that if I change the canvas.width property, all changes will cascade down.

A big problem with this approach is that now I need to remember which global variables are functions. So for example in another file I would need to access it like this:

```<code>const config = require('./globals.js');
let width = config.shape.width();
</code>```

Ideally I would like to access all globals as normal properties. To be clear, none of this needs to be dynamic (ie, recalculated at runtime) - once the app is running all these globals can be set in stone.

What's the best way to achieve this? Should I somehow "pre-compute" or "pre-build" the object?

答: You're likely looking for JavaScript's get syntax, which lets you access computed values as if they were properties. From your example, it's not obvious that this is absolutely necessary, since you could remember that you need to call a function. But if you really want to avoid explicit function calls, use a getter.

Body:
I have a globals.js file that needs to be accessible across multiple files in my app.

These globals are inter-dependent, and I would like to set up my data file so that the parameters are relative to one another. I am trying the following:

const config = {
  "canvas": {
    "width": 600,
  },
  "shape": {
    "width": function() {
      return config.canvas.width*0.9;
    };
  },
};

module.exports = config;

The idea is that if I change the canvas.width property, all changes will cascade down.

A big problem with this approach is that now I need to remember which global variables are functions. So for example in another file I would need to access it like this:

const config = require('./globals.js');
let width = config.shape.width();

Ideally I would like to access all globals as normal properties. To be clear, none of this needs to be dynamic (ie, recalculated at runtime) - once the app is running all these globals can be set in stone.

What's the best way to achieve this? Should I somehow "pre-compute" or "pre-build" the object?


问:
SQLite Read Uncommitted in same transaction as write
I'm using SQLite.Net from sqlite.org

I open a connection and begin a transaction. Inside the transaction I insert some rows. In the same transaction I attempt to read the data I have written which I expected to be the default (within the same transaction) however it does not seem to be the case.

I have open the database in WAL mode.

How can I read uncommited in the current transaction?

答: OK, this was my bad - I was actually reading on a different connection ...</p>


问:
Best practice for running a daily Python screen-scraping script 50 times (8.3 minutes total) per user?
On the front-end, I have a PHP webapp that allows users to create a list of their websites (5 max).

On the back-end, a Python script runs daily (and has ~10 iterations) for each website that the user registers. Each script per website takes about 10 seconds to run through all iterations and finish its scraping. It then makes a CSV file with its findings.

So, in total, that's up to (5 websites * 10 iterations =) 50 iterations at 8.3 total minutes per user.

Right now, the script works when I manually feed it a URL, so I'm wondering how to make it dynamically part of the webapp.

How do I programmatically add and remove scripts that run daily depending on the number of users and the websites each user has each day?

How would I schedule this script to run for each website of each user, passing in the appropriate parameters?

I'm somewhat acquainted with cronjobs, as it's the only thing I know of that is made for routine processes.

答: Do you need to run the script 50 times per user, or only when the user has logged into your service to check on things?


问:
How to retroactively delete a commit from a git repository?
I want to remove a commit from a git repository. Not the last one, thus a git reset won't work.

I have this: A->B->C->D->...

And now I want to have only

```<code>A->B->D->...
</code>```

Thus, I want to change the past on a way as if C never had been existed.

How can I do that?

The possible inconsistencies with the remote repositories are a non-issue (I have full control over them). It is not a problem if the commit ids change, too.

答:
If you have a simple, linear set of changes to copy to new commits, use git rebase -i as in Alejandro C.'s answer.  If not, do not mix git rebase -i with git rebase -p: it really won't work well.

Instead, first, use git replace to construct an alternative history: make a replacement for the commit that comes after the one(s) you want removed, where the replacement's parent is the next-earlier commit you want Git to "see" when it uses replacements (which it does by default).  Then, once you have the desired history, run an otherwise-no-operation git filter-branch to copy the commits.  The copied commits will, like the rest of Git, use the "pretend history" from the replacement, so they will in fact have that as their real history, and when git filter-branch makes the branch names point to the newly copied branch tips, the replacement history will now be the actual history.

(Then, as with any git filter-branch operation, you must clean away the refs/original/ references.  It's also wise to all of this in a temporary spare repository in case you goof it up. :-) )

Body:
I want to remove a commit from a git repository. Not the last one, thus a git reset won't work.

I have this: A->B->C->D->...

And now I want to have only

A->B->D->...

Thus, I want to change the past on a way as if C never had been existed.

How can I do that?

The possible inconsistencies with the remote repositories are a non-issue (I have full control over them). It is not a problem if the commit ids change, too.


问:
Most efficient way to delete all core objects in objective c
How could I delete all core objects without slowing down my app.

I have my app connected to a mysql database and every time I make an update on the database, the only way it updates on the app is if I delete all the core data and then reload it. However, this seems to take 30 seconds to do.

答: Deleting objects is very fast! I realized my program was slow due to me adding images to the core data. </p>


问:
Eligibility traces in TensorFlow
According to Sutton's book - Reinforcement Learning: An Introduction, the update equation of Network weights is given by:

where et is the eligibility trace.
This is similar to a Gradient Descent update with an extra et.

Can this eligibility trace be included in the tf.train.GradientDescentOptimizer in TensorFlow?

答:
Here's a simple example of using tf.contrib.layers.scale_gradient to do elementwise multiplication of gradients. In the forward pass it's just an identity op, and in the backward pass it multiplies gradients by its second argument.

```<code>import tensorflow as tf

with tf.Graph().as_default():
  some_value = tf.constant([0.,0.,0.])
  scaled = tf.contrib.layers.scale_gradient(some_value, [0.1, 0.2, 0.3])
  (some_value_gradient,) = tf.gradients(tf.reduce_sum(scaled), some_value)
  with tf.Session():
    print(scaled.eval())
    print(some_value_gradient.eval())
</code>```

Prints:

```<code>[ 0.  0.  0.]
[ 0.1         0.2         0.30000001]
</code>```

Title: Eligibility traces in TensorFlow

Body:
Here's a simple example of using tf.contrib.layers.scale_gradient to do elementwise multiplication of gradients. In the forward pass it's just an identity op, and in the backward pass it multiplies gradients by its second argument.

import tensorflow as tf

with tf.Graph().as_default():
  some_value = tf.constant([0.,0.,0.])
  scaled = tf.contrib.layers.scale_gradient(some_value, [0.1, 0.2, 0.3])
  (some_value_gradient,) = tf.gradients(tf.reduce_sum(scaled), some_value)
  with tf.Session():
    print(scaled.eval())
    print(some_value_gradient.eval())

Prints:

[ 0.  0.  0.]
[ 0.1         0.2         0.30000001]


问:
Is it possible to conditionally load libraries in Lua?
I'm making a script for mpv, and in it I load the mpv library like this:

```<code>-- script.lua

local mp = require('mp')
</code>```

I'm using the busted unit test framework to write tests for this, and they're contained in a separate file, like this:

```<code>-- script-tests.lua

describe('my script unit tests', function()
    local script = require('script')

    it('...', function()
        assert.is_true(true)
    end)
end)
</code>```

The problem occurs when I run the unit tests, I get this:

./script.lua:1: module 'mp' not found:No LuaRocks module found for mp

I understand mp is available when my script is run within mpv, but not when I run my unit tests. Is there any way to stop this require when running the unit tests? or am I thinking about this in the wrong way?

Solution

In the end I created a stub mp (trying to use a global flag like Adam suggested, but it wouldn't work). Here it is:

```<code>-- script.lua

local plugin = {}
local mpv_loaded, mp = pcall(require, 'mp')

plugin.mp = mp

---------------------------------------------------------------------
-- Stub MPV library for unit tests
if not mpv_loaded then
    plugin.mp = {}

    function plugin.mp.osd_message(message)
        plugin.mp.message = message
    end

    function plugin.mp.log(level, message)
        -- stub
    end

    function plugin.mp.add_forced_key_binding(...)
        -- stub
    end

    function plugin.mp.remove_key_binding(...)
        -- stub
    end
end

---------------------------------------------------------------------
-- Display message on screen.
function plugin:show_message(message)
    self.mp.osd_message(message)
end

return plugin
</code>```

```<code>-- script-tests.lua

describe('my script unit tests', function()
    local plugin = require('script')

    it('...', function()
        message = 'It is better to play than do nothing.'
        plugin:show_message(message)

        assert.is_same(plugin.mp.message, message)
    end)

end)
</code>```

答:
You could set a global variable in your unit tests and conditionally require the mp module.

For example, in your unit test, set a _UNITTEST variable:

```<code>-- script-tests.lua
_UNITTEST = true

describe('my script unit tests', function()
    local script = require('script')

    it('...', function()
        assert.is_true(true)
    end)
end)
</code>```

Then, in your script:

```<code>-- script.lua
local mp = not _UNITTEST and require('mp')
</code>```

A similar technique is used in the Busted documentation to expose local values for testing. If you need to test functions that depend on the mp module, then you may want to look into providing a stub implementation.

Body:
I'm making a script for mpv, and in it I load the mpv library like this:

-- script.lua

local mp = require('mp')

I'm using the busted unit test framework to write tests for this, and they're contained in a separate file, like this:

-- script-tests.lua

describe('my script unit tests', function()
    local script = require('script')

    it('...', function()
        assert.is_true(true)
    end)
end)

The problem occurs when I run the unit tests, I get this:

./script.lua:1: module 'mp' not found:No LuaRocks module found for mp

I understand mp is available when my script is run within mpv, but not when I run my unit tests. Is there any way to stop this require when running the unit tests? or am I thinking about this in the wrong way?

Solution

In the end I created a stub mp (trying to use a global flag like Adam suggested, but it wouldn't work). Here it is:

-- script.lua

local plugin = {}
local mpv_loaded, mp = pcall(require, 'mp')

plugin.mp = mp

---------------------------------------------------------------------
-- Stub MPV library for unit tests
if not mpv_loaded then
    plugin.mp = {}

    function plugin.mp.osd_message(message)
        plugin.mp.message = message
    end

    function plugin.mp.log(level, message)
        -- stub
    end

    function plugin.mp.add_forced_key_binding(...)
        -- stub
    end

    function plugin.mp.remove_key_binding(...)
        -- stub
    end
end

---------------------------------------------------------------------
-- Display message on screen.
function plugin:show_message(message)
    self.mp.osd_message(message)
end

return plugin

-- script-tests.lua

describe('my script unit tests', function()
    local plugin = require('script')

    it('...', function()
        message = 'It is better to play than do nothing.'
        plugin:show_message(message)

        assert.is_same(plugin.mp.message, message)
    end)

end)

Body:
You could set a global variable in your unit tests and conditionally require the mp module.

For example, in your unit test, set a _UNITTEST variable:

-- script-tests.lua
_UNITTEST = true

describe('my script unit tests', function()
    local script = require('script')

    it('...', function()
        assert.is_true(true)
    end)
end)

Then, in your script:

-- script.lua
local mp = not _UNITTEST and require('mp')

A similar technique is used in the Busted documentation to expose local values for testing. If you need to test functions that depend on the mp module, then you may want to look into providing a stub implementation.


问:
Trying To Filter Only Rows That Meet Two Criteria
I promise I have read through the Query information page, but obviously I am missing/misunderstanding something.

I have a Table that has the statuses for multiple departments (the fields are Strings). When a user loads that table I want App Maker to hide jobs that have been finished.

The way we categorize a job as finishes is when:

The Inventory Status = Complete and when the The Delivery Status = Delivered.

Both these conditions need to be met.

Example:

Inventory (Complete) + Delivery (Delivered) = hide

Inventory (In Progress) + Delivery (Delivered) = don't hide

Inventory (Complete) + Delivery (Scheduled) = don't hide

I tried the following, however it hides all the example listed above, not just the first one.

```<code>var datasource = app.datasources.SystemOrders;
var inventory = ['Complete'];
var delivery = ['Delivered'];
    datasource.query.filters.InventoryStatus._notIn = inventory;
    datasource.query.filters.DeliveryStatus._notIn = delivery;
    datasource.load();
</code>```

I have also tried this:

```<code>var datasource = app.datasources.SystemOrders;
    datasource.query.filters.InventoryStatus._notIn = 'Complete';
    datasource.query.filters.DeliveryStatus._notIn = 'Delivered';
    datasource.load();
</code>```

But I get this error:

Type mismatch: Cannot set type String for property _notIn. Type List is expected. at SystemOrders.ToolBar.Button2.onClick:2:46

Any help would be greatly appreciated.

答:
Vasyl answer my question perfectly, but I wanted to add a few details in case anyone needs to do the same thing and aren't familiar with using the Datasource Query Builder.

All I did was click the Database I was using and then clicked the Datasources section at the top.

I clicked Add Datasource, named it a new name and pasted Vasyl's code into the Query Builder Expression box.

Two new boxes appear below it allowing me to enter the desired statuses that I wanted to filter out.

Lastly I went back to my Table and changed its datasource to my newly created datasource.

Since you are changing your datasource, if you have any extra code on there it may need to be updated to point to the new datasource.

Example:
I had some buttons that would filter entries for the various departments.

So this:

```<code>widget.datasource.query.clearFilters();
var datasource = app.datasources.SystemOrders;
var statuses = ['Complete'];
     datasource.query.filters.WarehouseStatus._notIn = statuses;
     datasource.load();
</code>```

had to change to this:

```<code>widget.datasource.query.clearFilters();
var datasource = app.datasources.SystemOrders_HideComplete;
var statuses = ['Complete'];
     datasource.query.filters.WarehouseStatus._notIn = statuses;
     datasource.load();
</code>```

Body:
I promise I have read through the Query information page, but obviously I am missing/misunderstanding something.

I have a Table that has the statuses for multiple departments (the fields are Strings). When a user loads that table I want App Maker to hide jobs that have been finished.

The way we categorize a job as finishes is when:

The Inventory Status = Complete and when the The Delivery Status = Delivered.

Both these conditions need to be met.

Example:

Inventory (Complete) + Delivery (Delivered) = hide

Inventory (In Progress) + Delivery (Delivered) = don't hide

Inventory (Complete) + Delivery (Scheduled) = don't hide

I tried the following, however it hides all the example listed above, not just the first one.

var datasource = app.datasources.SystemOrders;
var inventory = ['Complete'];
var delivery = ['Delivered'];
    datasource.query.filters.InventoryStatus._notIn = inventory;
    datasource.query.filters.DeliveryStatus._notIn = delivery;
    datasource.load();

I have also tried this:

var datasource = app.datasources.SystemOrders;
    datasource.query.filters.InventoryStatus._notIn = 'Complete';
    datasource.query.filters.DeliveryStatus._notIn = 'Delivered';
    datasource.load();

But I get this error:

Type mismatch: Cannot set type String for property _notIn. Type List is expected. at SystemOrders.ToolBar.Button2.onClick:2:46

Any help would be greatly appreciated.

Body:
Vasyl answer my question perfectly, but I wanted to add a few details in case anyone needs to do the same thing and aren't familiar with using the Datasource Query Builder.

All I did was click the Database I was using and then clicked the Datasources section at the top.

I clicked Add Datasource, named it a new name and pasted Vasyl's code into the Query Builder Expression box.

Two new boxes appear below it allowing me to enter the desired statuses that I wanted to filter out.

Lastly I went back to my Table and changed its datasource to my newly created datasource.

Since you are changing your datasource, if you have any extra code on there it may need to be updated to point to the new datasource.

Example:
I had some buttons that would filter entries for the various departments.

So this:

widget.datasource.query.clearFilters();
var datasource = app.datasources.SystemOrders;
var statuses = ['Complete'];
     datasource.query.filters.WarehouseStatus._notIn = statuses;
     datasource.load();

had to change to this:

widget.datasource.query.clearFilters();
var datasource = app.datasources.SystemOrders_HideComplete;
var statuses = ['Complete'];
     datasource.query.filters.WarehouseStatus._notIn = statuses;
     datasource.load();


问:
Tcl: How to replace variable string?
Input file is a tcl script and it looks like:

```<code>set PATH /user/abc/path
set PATH2 /user/abc/path2
...
read_verilog ${PATH}/src/vlog/code_1.v
read_verilog $PATH/src/vlog/code_2.v
read_vhdl ${PATH2}/src/vhd/code_3.vh
read_vhdl $PATH2/src/vhd/code_4.vh
[other commands ...]
</code>```

Need to check if the source file is exist and print out none-exist files.
If none of the file is exist, the output looks like:

```<code>read_verilog ${PATH}/src/vlog/code_1.v
read_verilog $PATH/src/vlog/code_2.v
read_vhdl ${PATH2}/src/vhd/code_3.vh
read_vhdl $PATH2/src/vhd/code_4.vh
</code>```

And below is my script:

```<code>#!/usr/bin/tclsh
set input_file    "input.tcl"

set input_fpt        [open $input_file r]
set input_lines_all  [read $input_fpt]
set input_lines      [split $input_lines_all "\n"]

set PATH /user/abc/PATH
set PATH /user/dgc/PATH2

foreach line $input_lines {
   if { [string match "read_verilog *" $line] || [string match "read_vhdl*" $line] } {
      regexp {[read_verilog read_vhdl] (.*)} $line matched file

      if { [string match {*[{P]AT[H}]*} $file] } {
         set abs_file [string map {${PATH} /user/abc/PATH} $file]
      } elseif { [string match "*PATH2*" $file] } {
         set abs_file [string map {${PATH2} /user/abc/PATH2} $file]
      } else {
         set abs_file $file
      }

      if { ![file exists $abs_file] } {
         puts $line
      }
   }
}
</code>```

My script can't check $PATH and not sure if there is a more efficient way to do the job.

答:
The simplest way of doing just the substitutions you want is with the string map command. Build up the map piece by piece first, then apply it to your string.

```<code>set map {}
lappend map {$PATH} $PATH
lappend map {${PATH}} $PATH
lappend map {$PATH2} $PATH2
lappend map {${PATH2}} $PATH2

set modified [string map $map $inputString]
</code>```

You can apply the map as many times as you want once you have built it, and transform your data either a line at a time or all in one go. However, you might be better off just evaluating the file as a Tcl script. That can be an incredibly useful approach to some types of parsing (especially when used in conjunction with a safe interpreter) if the input is suitable, which yours appears to be.

Title: Tcl: How to replace variable string?

Body:
Input file is a tcl script and it looks like:

set PATH /user/abc/path
set PATH2 /user/abc/path2
...
read_verilog ${PATH}/src/vlog/code_1.v
read_verilog $PATH/src/vlog/code_2.v
read_vhdl ${PATH2}/src/vhd/code_3.vh
read_vhdl $PATH2/src/vhd/code_4.vh
[other commands ...]

Need to check if the source file is exist and print out none-exist files.
If none of the file is exist, the output looks like:

read_verilog ${PATH}/src/vlog/code_1.v
read_verilog $PATH/src/vlog/code_2.v
read_vhdl ${PATH2}/src/vhd/code_3.vh
read_vhdl $PATH2/src/vhd/code_4.vh

And below is my script:

#!/usr/bin/tclsh
set input_file    "input.tcl"

set input_fpt        [open $input_file r]
set input_lines_all  [read $input_fpt]
set input_lines      [split $input_lines_all "\n"]

set PATH /user/abc/PATH
set PATH /user/dgc/PATH2

foreach line $input_lines {
   if { [string match "read_verilog *" $line] || [string match "read_vhdl*" $line] } {
      regexp {[read_verilog read_vhdl] (.*)} $line matched file

      if { [string match {*[{P]AT[H}]*} $file] } {
         set abs_file [string map {${PATH} /user/abc/PATH} $file]
      } elseif { [string match "*PATH2*" $file] } {
         set abs_file [string map {${PATH2} /user/abc/PATH2} $file]
      } else {
         set abs_file $file
      }

      if { ![file exists $abs_file] } {
         puts $line
      }
   }
}

My script can't check $PATH and not sure if there is a more efficient way to do the job.

Body:
The simplest way of doing just the substitutions you want is with the string map command. Build up the map piece by piece first, then apply it to your string.

set map {}
lappend map {$PATH} $PATH
lappend map {${PATH}} $PATH
lappend map {$PATH2} $PATH2
lappend map {${PATH2}} $PATH2

set modified [string map $map $inputString]

You can apply the map as many times as you want once you have built it, and transform your data either a line at a time or all in one go. However, you might be better off just evaluating the file as a Tcl script. That can be an incredibly useful approach to some types of parsing (especially when used in conjunction with a safe interpreter) if the input is suitable, which yours appears to be.


问:
I am trying to integrate Dropbox into my website. What does "curl" mean and how do I use it?
I went on the /list_folders method in the HTTP Developers guide (https://www.dropbox.com/developers/documentation/http/documentation#files-list_folder) and it has "curl" as the example of how to use it. How do I put this in my HTML/JS code to pull in the folders? Thanks!</p>

答:
You can look at the reference for the JavaScript Dropbox library here which will guide you through creating a front-end website that utilizes the API. CURL is a very popular command line script used to transfer data over many supported protocols, but not something you can use from the browser.

More on the Dropbox API, this example Javascript script will show you how to list files.

The partial documentation can be found here.


问:
Android throwing up Error using jtwitter
I am trying to write a twitter application on Android target 2.2 (using some sample code that I found on the net and using Marko Gargenta's O'Reilly text). I am stuck with the problem as in the log below. The source code is given first followed by the log. Any idea what's going wrong here ? Also does anyone have or can point to a sample jtwitter code working on Android.

Thanks,
Ravi

```<code>protected String doInBackground(String... statuses) {
  try {

         //Autho information
         /*OAuthSignpostClient oauthclient = new OAuthSignpostClient(cons_key,
           cons_secret, access_token, access_secret);*/

         OAuthSignpostClient oauthclient = new OAuthSignpostClient(access_token, access_secret,"oob");

         //***POSTING TO TWITTER CURRENTLY DOES NOT WORK WITH THIS INTERFACE
         twitter = new Twitter(mytwitterusername, oauthclient);
         //twitter.setAPIRootUrl("http://learningandroid.status.net/api");

   //***POSTING TO TWITTER CURRENTLY DOES NOT WORK WITH THIS INTERFACE
   Log.i(Logtag, "Status currently is " + statuses[0]);

   Twitter.Status status = twitter.updateStatus(statuses[0]);
   //return status.text;
   return statuses[0];
  } catch (TwitterException e) {
   Log.e(Logtag, e.toString());
   e.printStackTrace();
   return "Failed to post to Twitter";
  }
</code>```

}

Log file:

```<code>E/dalvikvm(  719): Could not find method javax.swing.JOptionPane.showInputDialog, referenced from method winterwell.jtwi
tter.OAuthSignpostClient.askUser
W/dalvikvm(  719): VFY: unable to resolve static method 443: Ljavax/swing/JOptionPane;.showInputDialog (Ljava/lang/Objec
t;)Ljava/lang/String;
W/dalvikvm(  719): VFY:  rejecting opcode 0x71 at 0x0000
W/dalvikvm(  719): VFY:  rejected Lwinterwell/jtwitter/OAuthSignpostClient;.askUser (Ljava/lang/String;)Ljava/lang/Strin
g;
W/dalvikvm(  719): Verifier rejected class Lwinterwell/jtwitter/OAuthSignpostClient;
W/dalvikvm(  719): threadid=17: thread exiting with uncaught exception (group=0x4000fe70)
E/AndroidRuntime(  719): Uncaught handler: thread AsyncTask #1 exiting due to uncaught exception
E/AndroidRuntime(  719): java.lang.RuntimeException: An error occured while executing doInBackground()
E/AndroidRuntime(  719):        at android.os.AsyncTask$3.done(AsyncTask.java:200)
E/AndroidRuntime(  719):        at java.util.concurrent.FutureTask$Sync.innerSetException(FutureTask.java:234)
E/AndroidRuntime(  719):        at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:258)
E/AndroidRuntime(  719):        at java.util.concurrent.FutureTask.run(FutureTask.java:122)
E/AndroidRuntime(  719):        at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(ThreadPoolExecutor.java:648)
E/AndroidRuntime(  719):        at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:673)
E/AndroidRuntime(  719):        at java.lang.Thread.run(Thread.java:1058)
E/AndroidRuntime(  719): Caused by: java.lang.VerifyError: winterwell.jtwitter.OAuthSignpostClient
E/AndroidRuntime(  719):        at com.ravi.tweeto.StatusActivity$PostToTwitter.doInBackground(StatusActivity.java:81)
E/AndroidRuntime(  719):        at com.ravi.tweeto.StatusActivity$PostToTwitter.doInBackground(StatusActivity.java:1)
E/AndroidRuntime(  719):        at android.os.AsyncTask$2.call(AsyncTask.java:185)
E/AndroidRuntime(  719):        at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:256)
E/AndroidRuntime(  719):        ... 4 more
I/Process (  585): Sending signal. PID: 719 SIG: 3
I/dalvikvm(  719): threadid=7: reacting to signal 3
I/dalvikvm(  719): Wrote stack trace to '/data/anr/traces.txt'
----
</code>```

答: Basically the JTwitter library has calls to Java swing classes that are not in the Android SDK as it does not use swing.  I had to get the source for JTwitter and remove the swing code for my application to work.  Hope this helps.</p>

Body:
I am trying to write a twitter application on Android target 2.2 (using some sample code that I found on the net and using Marko Gargenta's O'Reilly text). I am stuck with the problem as in the log below. The source code is given first followed by the log. Any idea what's going wrong here ? Also does anyone have or can point to a sample jtwitter code working on Android.

Thanks,
Ravi

protected String doInBackground(String... statuses) {
  try {

         //Autho information
         /*OAuthSignpostClient oauthclient = new OAuthSignpostClient(cons_key,
           cons_secret, access_token, access_secret);*/

         OAuthSignpostClient oauthclient = new OAuthSignpostClient(access_token, access_secret,"oob");

         //***POSTING TO TWITTER CURRENTLY DOES NOT WORK WITH THIS INTERFACE
         twitter = new Twitter(mytwitterusername, oauthclient);
         //twitter.setAPIRootUrl("http://learningandroid.status.net/api");

   //***POSTING TO TWITTER CURRENTLY DOES NOT WORK WITH THIS INTERFACE
   Log.i(Logtag, "Status currently is " + statuses[0]);

   Twitter.Status status = twitter.updateStatus(statuses[0]);
   //return status.text;
   return statuses[0];
  } catch (TwitterException e) {
   Log.e(Logtag, e.toString());
   e.printStackTrace();
   return "Failed to post to Twitter";
  }

}

Log file:

E/dalvikvm(  719): Could not find method javax.swing.JOptionPane.showInputDialog, referenced from method winterwell.jtwi
tter.OAuthSignpostClient.askUser
W/dalvikvm(  719): VFY: unable to resolve static method 443: Ljavax/swing/JOptionPane;.showInputDialog (Ljava/lang/Objec
t;)Ljava/lang/String;
W/dalvikvm(  719): VFY:  rejecting opcode 0x71 at 0x0000
W/dalvikvm(  719): VFY:  rejected Lwinterwell/jtwitter/OAuthSignpostClient;.askUser (Ljava/lang/String;)Ljava/lang/Strin
g;
W/dalvikvm(  719): Verifier rejected class Lwinterwell/jtwitter/OAuthSignpostClient;
W/dalvikvm(  719): threadid=17: thread exiting with uncaught exception (group=0x4000fe70)
E/AndroidRuntime(  719): Uncaught handler: thread AsyncTask #1 exiting due to uncaught exception
E/AndroidRuntime(  719): java.lang.RuntimeException: An error occured while executing doInBackground()
E/AndroidRuntime(  719):        at android.os.AsyncTask$3.done(AsyncTask.java:200)
E/AndroidRuntime(  719):        at java.util.concurrent.FutureTask$Sync.innerSetException(FutureTask.java:234)
E/AndroidRuntime(  719):        at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:258)
E/AndroidRuntime(  719):        at java.util.concurrent.FutureTask.run(FutureTask.java:122)
E/AndroidRuntime(  719):        at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(ThreadPoolExecutor.java:648)
E/AndroidRuntime(  719):        at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:673)
E/AndroidRuntime(  719):        at java.lang.Thread.run(Thread.java:1058)
E/AndroidRuntime(  719): Caused by: java.lang.VerifyError: winterwell.jtwitter.OAuthSignpostClient
E/AndroidRuntime(  719):        at com.ravi.tweeto.StatusActivity$PostToTwitter.doInBackground(StatusActivity.java:81)
E/AndroidRuntime(  719):        at com.ravi.tweeto.StatusActivity$PostToTwitter.doInBackground(StatusActivity.java:1)
E/AndroidRuntime(  719):        at android.os.AsyncTask$2.call(AsyncTask.java:185)
E/AndroidRuntime(  719):        at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:256)
E/AndroidRuntime(  719):        ... 4 more
I/Process (  585): Sending signal. PID: 719 SIG: 3
I/dalvikvm(  719): threadid=7: reacting to signal 3
I/dalvikvm(  719): Wrote stack trace to '/data/anr/traces.txt'
----


问:
same code for different type database
I am going to start an application in Asp.Net. In this app the database can be different but I want to use same C# code. That means for right now the database is SQL Server and its connection string will be defined in Web.Config file. But in later database may be MySQL or NETEZZA(IBM). But I want that only changing connection string but my C# logic should be same. How would I do it? Please suggest me. So For now I can not use any object of sql like SQLConnection or SQLCommand. I want to make it like generic.</p>

答: The partial answer is to use an ORM (EF, NHibernate). It won't be as simple as changing a single line to switch between them, but you won't need to rewrite your code. Adjusting a few config lines on the ORM should do the trick.</p>

Title: same code for different type database


问:
How can i move my UIImage vertically from top to bottom
i want the UIImage to move on the screen vertically downwards and when it reaches to the end it should again start from the top. how can i do it???

please help
Thanks

答:
Assuming your UIImage is in a UIImageView and the image view is 320 x 480 in size...

Your animation block can call a method when it is complete.  This method resets the position of your UIImageView and then starts the animation over.

Animation Block:

```<code>-(void)animate {
    [UIView beginAnimations:nil context:NULL];
    [UIView setAnimationDuration:.3];
    [UIView setAnimationCurve:UIViewAnimationCurveEaseInOut];
    [UIView setAnimationBeginsFromCurrentState:YES];
    [UIView setAnimationDelegate:self];
    [UIView setAnimationDidStopSelector:@selector(myCallback:finished:context:)];

    CGRect frame = yourImageView.frame;
    frame.origin = CGPointMake(0, 480);
    yourImageView.frame = frame;

    [UIView commitAnimations];

}
</code>```

Callback:

```<code>(void)myCallback:(NSString *)animationID finished:(NSNumber *)finished context:(void *)context {

    CGRect frame = yourImageView.frame;
    frame.origin = CGPointMake(0, 0)
    yourImageView.frame = frame;
    [self animate];
}
</code>```

Body:
Assuming your UIImage is in a UIImageView and the image view is 320 x 480 in size...

Your animation block can call a method when it is complete.  This method resets the position of your UIImageView and then starts the animation over.

Animation Block:

-(void)animate {
    [UIView beginAnimations:nil context:NULL];
    [UIView setAnimationDuration:.3];
    [UIView setAnimationCurve:UIViewAnimationCurveEaseInOut];
    [UIView setAnimationBeginsFromCurrentState:YES];
    [UIView setAnimationDelegate:self];
    [UIView setAnimationDidStopSelector:@selector(myCallback:finished:context:)];

    CGRect frame = yourImageView.frame;
    frame.origin = CGPointMake(0, 480);
    yourImageView.frame = frame;

    [UIView commitAnimations];

}

Callback:

(void)myCallback:(NSString *)animationID finished:(NSNumber *)finished context:(void *)context {

    CGRect frame = yourImageView.frame;
    frame.origin = CGPointMake(0, 0)
    yourImageView.frame = frame;
    [self animate];
}