问:
Unable to debug gwt test for gwt 2.8 and java 1.8 version
I have upgraded gwt version to 2.8 and java 1.8. Test is running fine with gwt 2.7 and java 1.7. Do I need to add extra configurations in gwt.xml or any dependency in pom

pom :

```<code>        <dependency>
            <groupId>com.google.gwt</groupId>
            <artifactId>gwt-servlet</artifactId>
            <scope>2.8</scope>
        </dependency>
        <dependency>
            <groupId>com.google.gwt</groupId>
            <artifactId>gwt-user</artifactId>
            <scope>2.8</scope>
        </dependency>
        <dependency>
            <groupId>com.google.gwt</groupId>
            <artifactId>gwt-dev</artifactId>
            <scope>2.8</scope>
        </dependency>
        <dependency>
            <groupId>com.google.guava</groupId>
            <artifactId>guava-gwt</artifactId>
            <version>20.0</version>
        </dependency>
</code>```

Test code :

```<code>public class Test extends GWTTestCase {

    Logger logger = Logger.getLogger(this.getClass().getCanonicalName());

    /* (non-Javadoc)
     * @see com.google.gwt.junit.client.GWTTestCase#getModuleName()
     */
    @Override
    public String getModuleName() {
        return "org.field.TestJUnit";
    }

    public void testRenderAndBindTopScene() {
        GWT.log("hi");
        PageEx pageEx = GWT.create(PageEx.class);
    }
}
</code>```

TestJUnit.gwt.xml :

```<code><?xml version="1.0" encoding="UTF-8"?>
<module rename-to="Field">
    <!-- Inherit our applications main module. -->
    <inherits name='org.field.Field' />

    <source path="client" />
    <source path="shared" />

</module>
</code>```

答:
Starting with GWT 2.8, the classic dev mode is now (officially) deprecated, and tests run in prod mode by default (i.e. compiled to JavaScript).

This means you cannot set breakpoints in your Java code and expect to be reached in a Java debugger (because they are regular JUnit 3 tests, driven by the standard JUnit runner, some of the methods will actually be called, but not the test methods themselves).

You can (temporarily) re-enable dev mode for tests by passing -devMode in the -Dgwt.args= system property, as hinted in the release notes.

Alternatively, you can run the tests in "manual" mode (you'll be given a URL to open in your browser, where you can debug the JavaScript), or you could pass the -Dgwt.htmlunit.debug system property when running tests with the HtmlUnit run style (the default) to show a debugger window (note: I have no idea how to use it).

…or "debug" the "good old way" by logging things; and/or making a small repro-case as a GWT app that you can run in your browser.

Body:
I have upgraded gwt version to 2.8 and java 1.8. Test is running fine with gwt 2.7 and java 1.7. Do I need to add extra configurations in gwt.xml or any dependency in pom

pom :

        <dependency>
            <groupId>com.google.gwt</groupId>
            <artifactId>gwt-servlet</artifactId>
            <scope>2.8</scope>
        </dependency>
        <dependency>
            <groupId>com.google.gwt</groupId>
            <artifactId>gwt-user</artifactId>
            <scope>2.8</scope>
        </dependency>
        <dependency>
            <groupId>com.google.gwt</groupId>
            <artifactId>gwt-dev</artifactId>
            <scope>2.8</scope>
        </dependency>
        <dependency>
            <groupId>com.google.guava</groupId>
            <artifactId>guava-gwt</artifactId>
            <version>20.0</version>
        </dependency>

Test code :

public class Test extends GWTTestCase {

    Logger logger = Logger.getLogger(this.getClass().getCanonicalName());

    /* (non-Javadoc)
     * @see com.google.gwt.junit.client.GWTTestCase#getModuleName()
     */
    @Override
    public String getModuleName() {
        return "org.field.TestJUnit";
    }

    public void testRenderAndBindTopScene() {
        GWT.log("hi");
        PageEx pageEx = GWT.create(PageEx.class);
    }
}

TestJUnit.gwt.xml :

<?xml version="1.0" encoding="UTF-8"?>
<module rename-to="Field">

    <inherits name='org.field.Field' />

    <source path="client" />
    <source path="shared" />

</module>


来源: stackexchange

问:
Ruby on Rails complex search through foreign keys
Hi in my application I'm trying to search for an employee based on the skills. I have 3 classes involved Employee, Employee_skills and Skills

Could anyone point me in the direction of how to go about this search as everything I've tried returned errors. Here are their modals.

Employee

```<code>class Employee < ActiveRecord::Base
has_secure_password

has_many :employee_events
has_many :employee_skills , :class_name => EmployeeSkill, :foreign_key => "employee_id"
has_many :employee_projects
has_many :equipments
has_many :time_entry

has_one :holiday
has_one :role
has_one :skill
has_one :tax

accepts_nested_attributes_for :skill

  validates :email, :presence => true, :uniqueness => true
  validates :password, :confirmation => true #password_confirmation attr
  validates_length_of :password, :in => 6..20, :on => :create

  def self.search(search)
  if search
    where('empLastName LIKE ?', "%#{search}%")
  else
    where(:all)
  end
end

  end
</code>```

Employee_skills

```<code>class EmployeeSkill < ActiveRecord::Base

belongs_to :employee, :class_name => Employee, :foreign_key => "employee_id"
belongs_to :project
belongs_to :skill, :class_name => Skill, :foreign_key => "skill_id"

end
</code>```

Skills

```<code>class Skill < ActiveRecord::Base

has_many :employee_skills

def self.search(search)
  where("skillType LIKE ?", "%#{search}%")
end

end
</code>```

答:
First of all, no need to specify class_name or foreign_key, because belongs_to :employee already refers to class Employee and foreign key employee_id.

And you could use has_and_belongs_to_many association, which is right for your needs: http://guides.rubyonrails.org/association_basics.html#the-has-and-belongs-to-many-association

```<code>class Employee < ActiveRecord::Base
  has_and_belongs_to_many :skills
end

class Skill < ActiveRecord::Base
  has_and_belongs_to_many :employees
end
</code>```

And the migration:

```<code>class CreateEmployeesSkills < ActiveRecord::Migration
  create_table :employees_skills, id: false do |t|
    t.belongs_to :employee, index: true
    t.belongs_to :skill, index: true
  end
end
</code>```

ContentLicense: CC BY-SA 3.0

Body:
Hi in my application I'm trying to search for an employee based on the skills. I have 3 classes involved Employee, Employee_skills and Skills

Could anyone point me in the direction of how to go about this search as everything I've tried returned errors. Here are their modals.

Employee

class Employee < ActiveRecord::Base
has_secure_password

has_many :employee_events
has_many :employee_skills , :class_name => EmployeeSkill, :foreign_key => "employee_id"
has_many :employee_projects
has_many :equipments
has_many :time_entry

has_one :holiday
has_one :role
has_one :skill
has_one :tax

accepts_nested_attributes_for :skill

  validates :email, :presence => true, :uniqueness => true
  validates :password, :confirmation => true #password_confirmation attr
  validates_length_of :password, :in => 6..20, :on => :create

  def self.search(search)
  if search
    where('empLastName LIKE ?', "%#{search}%")
  else
    where(:all)
  end
end

  end

Employee_skills

class EmployeeSkill < ActiveRecord::Base

belongs_to :employee, :class_name => Employee, :foreign_key => "employee_id"
belongs_to :project
belongs_to :skill, :class_name => Skill, :foreign_key => "skill_id"

end

Skills

class Skill < ActiveRecord::Base

has_many :employee_skills

def self.search(search)
  where("skillType LIKE ?", "%#{search}%")
end

end

Body:
First of all, no need to specify class_name or foreign_key, because belongs_to :employee already refers to class Employee and foreign key employee_id.

And you could use has_and_belongs_to_many association, which is right for your needs: http://guides.rubyonrails.org/association_basics.html#the-has-and-belongs-to-many-association

class Employee < ActiveRecord::Base
  has_and_belongs_to_many :skills
end

class Skill < ActiveRecord::Base
  has_and_belongs_to_many :employees
end

And the migration:

class CreateEmployeesSkills < ActiveRecord::Migration
  create_table :employees_skills, id: false do |t|
    t.belongs_to :employee, index: true
    t.belongs_to :skill, index: true
  end
end


问:
This simply regular expression is really slow, why?
I have written this really simple regular expression which checks if the whole string represents one or more hexadecimal numbers (optionally starting with "0x", separated by comma, minus sign or a whitespace character):

```<code>/^((0x)?[0-9A-F]+[,\-\s]*)+$/i
</code>```

To me, this regex is very straightforward, but this simple test crashs Firefox and Edge at all, Chrome takes 100% CPU usage for about 15 seconds and then returns the expected result "false":

```<code>/^((0x)?[0-9A-F]+[,\-\s]*)+$/i.test("012345678901234567890123456789_0");
</code>```

Has anyone an idea what's wrong here?

答:
It is a usual case of a catastrophic backtracking (see your regex demo) when a group contains two subpatterns with one of them being optional.

You need to regroup the pattern as

```<code>/^(?:0x)?[0-9A-F]+(?:[,\s-]+(?:0x)?[0-9A-F]+)*$/i
</code>```

Now, it will match:

^ - start of string

(?:0x)?[0-9A-F]+ - hex number

(?:[,\s-]+(?:0x)?[0-9A-F]+)* - zero or more sequences of

[,\s-]+ - 1+ space, , or - symbols (remove + if only 1 must be matched)

(?:0x)?[0-9A-F]+ - hex number

$ - end of string.

See the regex demo.

Body:
I have written this really simple regular expression which checks if the whole string represents one or more hexadecimal numbers (optionally starting with "0x", separated by comma, minus sign or a whitespace character):

/^((0x)?[0-9A-F]+[,\-\s]*)+$/i

To me, this regex is very straightforward, but this simple test crashs Firefox and Edge at all, Chrome takes 100% CPU usage for about 15 seconds and then returns the expected result "false":

/^((0x)?[0-9A-F]+[,\-\s]*)+$/i.test("012345678901234567890123456789_0");

Has anyone an idea what's wrong here?

Body:
It is a usual case of a catastrophic backtracking (see your regex demo) when a group contains two subpatterns with one of them being optional.

You need to regroup the pattern as

/^(?:0x)?[0-9A-F]+(?:[,\s-]+(?:0x)?[0-9A-F]+)*$/i

Now, it will match:

^ - start of string

(?:0x)?[0-9A-F]+ - hex number

(?:[,\s-]+(?:0x)?[0-9A-F]+)* - zero or more sequences of

[,\s-]+ - 1+ space, , or - symbols (remove + if only 1 must be matched)

(?:0x)?[0-9A-F]+ - hex number

$ - end of string.

See the regex demo.


问:
How to find set difference in Mysql?
What is the 'except' equivalent command in mysql?

```<code>SELECT name FROM table1 except SELECT name FROM table2
</code>```

答:
As mentioned by @Lelio Faieta: Phpmyadmin is just a tool to access and operate on mysql database.

But if you want to achieve the "except" concept try like this:

```<code>SELECT name FROM table1 where name NOT IN( SELECT name FROM table2)
</code>```

This will give you names in table1 that are not in table2.

ContentLicense: CC BY-SA 4.0

Title: How to find set difference in Mysql?

Body:
What is the 'except' equivalent command in mysql?

SELECT name FROM table1 except SELECT name FROM table2

Body:
As mentioned by @Lelio Faieta: Phpmyadmin is just a tool to access and operate on mysql database.

But if you want to achieve the "except" concept try like this:

SELECT name FROM table1 where name NOT IN( SELECT name FROM table2)

This will give you names in table1 that are not in table2.


问:
enum to string in modern C++11 / C++14 / C++17 and future C++20

Contrary to all other similar questions, this question is about using the new C++ features.

2008 c Is there a simple way to convert C++ enum to string?

2008 c Easy way to use variables of enum types as string in C?

2008 c++ How to easily map c++ enums to strings

2008 c++ Making something both a C identifier and a string?

2008 c++ Is there a simple script to convert C++ enum to string?

2009 c++ How to use enums as flags in C++?

2011 c++ How to convert an enum type variable to a string?

2011 c++ Enum to String C++

2011 c++ How to convert an enum type variable to a string?

2012 c How to convert enum names to string in c

2013 c Stringifying an conditionally compiled enum in C

After reading many answers, I did not yet find any:

Elegant way using C++11, C++14 or C++17 new features

Or something ready-to-use in Boost

Else something planned for C++20

Example

An example is often better than a long explanation.

You can compile and run this snippet on Coliru.

(Another former example is also available)

```<code>#include <map>
#include <iostream>

struct MyClass
{
    enum class MyEnum : char {
        AAA = -8,
        BBB = '8',
        CCC = AAA + BBB
    };
};

// Replace magic() by some faster compile-time generated code
// (you're allowed to replace the return type with std::string
// if that's easier for you)
const char* magic (MyClass::MyEnum e)
{
    const std::map<MyClass::MyEnum,const char*> MyEnumStrings {
        { MyClass::MyEnum::AAA, "MyClass::MyEnum::AAA" },
        { MyClass::MyEnum::BBB, "MyClass::MyEnum::BBB" },
        { MyClass::MyEnum::CCC, "MyClass::MyEnum::CCC" }
    };
    auto   it  = MyEnumStrings.find(e);
    return it == MyEnumStrings.end() ? "Out of range" : it->second;
}

int main()
{
   std::cout << magic(MyClass::MyEnum::AAA) <<'\n';
   std::cout << magic(MyClass::MyEnum::BBB) <<'\n';
   std::cout << magic(MyClass::MyEnum::CCC) <<'\n';
}
</code>```

Constraints

Please no valueless duplication of other answers or basic link.

Please avoid bloat macro-based answer, or try to reduce the #define overhead as minimum as possible.

Please no manual enum -> string mapping.

Nice to have

Support enum values starting from a number different from zero

Support negative enum values

Support fragmented enum values

Support class enum (C++11)

Support class enum : <type> having any allowed <type> (C++11)

Compile-time (not run-time) conversions to a string,

or at least fast execution at run-time (e.g. std::map is not a great idea...)

constexpr (C++11, then relaxed in C++14/17/20)

noexcept (C++11)

C++17/C++20 friendly snippet

One possible idea could be using the C++ compiler capabilities to generate C++ code at compilation-time using meta-programming tricks based on variadic template class and constexpr functions...

答:
If your enum looks  like

```<code>enum MyEnum
{
  AAA = -8,
  BBB = '8',
  CCC = AAA + BBB
};
</code>```

You can move the content of the enum to a new file:

```<code>AAA = -8,
BBB = '8',
CCC = AAA + BBB
</code>```

And then the values can be surrounded by a macro:

```<code>// default definition
#ifned ITEM(X,Y)
#define ITEM(X,Y)
#endif

// Items list
ITEM(AAA,-8)
ITEM(BBB,'8')
ITEM(CCC,AAA+BBB)

// clean up
#undef ITEM
</code>```

Next step may be include the items in the enum again:

```<code>enum MyEnum
{
  #define ITEM(X,Y) X=Y,
  #include "enum_definition_file"
};
</code>```

And finally you can generate utility functions about this enum:

```<code>std::string ToString(MyEnum value)
{
  switch( value )
  {
    #define ITEM(X,Y) case X: return #X;
    #include "enum_definition_file"
  }

  return "";
}

MyEnum FromString(std::string const& value)
{
  static std::map<std::string,MyEnum> converter
  {
    #define ITEM(X,Y) { #X, X },
    #include "enum_definition_file"
  };

  auto it = converter.find(value);
  if( it != converter.end() )
    return it->second;
  else
    throw std::runtime_error("Value is missing");
}
</code>```

The solution can be applied to older C++ standards and it does not use modern C++ elements but it can be used to generate lot of code without too much effort and maintenance.

Body:
Contrary to all other similar questions, this question is about using the new C++ features.

2008 c Is there a simple way to convert C++ enum to string?

2008 c Easy way to use variables of enum types as string in C?

2008 c++ How to easily map c++ enums to strings

2008 c++ Making something both a C identifier and a string?

2008 c++ Is there a simple script to convert C++ enum to string?

2009 c++ How to use enums as flags in C++?

2011 c++ How to convert an enum type variable to a string?

2011 c++ Enum to String C++

2011 c++ How to convert an enum type variable to a string?

2012 c How to convert enum names to string in c

2013 c Stringifying an conditionally compiled enum in C

After reading many answers, I did not yet find any:

Elegant way using C++11, C++14 or C++17 new features

Or something ready-to-use in Boost

Else something planned for C++20

Example

An example is often better than a long explanation.

You can compile and run this snippet on Coliru.

(Another former example is also available)

#include <map>
#include <iostream>

struct MyClass
{
    enum class MyEnum : char {
        AAA = -8,
        BBB = '8',
        CCC = AAA + BBB
    };
};

// Replace magic() by some faster compile-time generated code
// (you're allowed to replace the return type with std::string
// if that's easier for you)
const char* magic (MyClass::MyEnum e)
{
    const std::map<MyClass::MyEnum,const char*> MyEnumStrings {
        { MyClass::MyEnum::AAA, "MyClass::MyEnum::AAA" },
        { MyClass::MyEnum::BBB, "MyClass::MyEnum::BBB" },
        { MyClass::MyEnum::CCC, "MyClass::MyEnum::CCC" }
    };
    auto   it  = MyEnumStrings.find(e);
    return it == MyEnumStrings.end() ? "Out of range" : it->second;
}

int main()
{
   std::cout << magic(MyClass::MyEnum::AAA) <<'\n';
   std::cout << magic(MyClass::MyEnum::BBB) <<'\n';
   std::cout << magic(MyClass::MyEnum::CCC) <<'\n';
}

Constraints

Please no valueless duplication of other answers or basic link.

Please avoid bloat macro-based answer, or try to reduce the #define overhead as minimum as possible.

Please no manual enum -> string mapping.

Nice to have

Support enum values starting from a number different from zero

Support negative enum values

Support fragmented enum values

Support class enum (C++11)

Support class enum : <type> having any allowed <type> (C++11)

Compile-time (not run-time) conversions to a string,

or at least fast execution at run-time (e.g. std::map is not a great idea...)

constexpr (C++11, then relaxed in C++14/17/20)

noexcept (C++11)

C++17/C++20 friendly snippet

One possible idea could be using the C++ compiler capabilities to generate C++ code at compilation-time using meta-programming tricks based on variadic template class and constexpr functions...

Body:
If your enum looks  like

enum MyEnum
{
  AAA = -8,
  BBB = '8',
  CCC = AAA + BBB
};

You can move the content of the enum to a new file:

AAA = -8,
BBB = '8',
CCC = AAA + BBB

And then the values can be surrounded by a macro:

// default definition
#ifned ITEM(X,Y)
#define ITEM(X,Y)
#endif

// Items list
ITEM(AAA,-8)
ITEM(BBB,'8')
ITEM(CCC,AAA+BBB)

// clean up
#undef ITEM

Next step may be include the items in the enum again:

enum MyEnum
{
  #define ITEM(X,Y) X=Y,
  #include "enum_definition_file"
};

And finally you can generate utility functions about this enum:

std::string ToString(MyEnum value)
{
  switch( value )
  {
    #define ITEM(X,Y) case X: return #X;
    #include "enum_definition_file"
  }

  return "";
}

MyEnum FromString(std::string const& value)
{
  static std::map<std::string,MyEnum> converter
  {
    #define ITEM(X,Y) { #X, X },
    #include "enum_definition_file"
  };

  auto it = converter.find(value);
  if( it != converter.end() )
    return it->second;
  else
    throw std::runtime_error("Value is missing");
}

The solution can be applied to older C++ standards and it does not use modern C++ elements but it can be used to generate lot of code without too much effort and maintenance.


问:
IList.Cast<typeof(T)>() returns error, syntax looks ok
```<code>public static IList<T> LoadObjectListAll<T>()
{
    ISession session = CheckForExistingSession();
    var cfg = new NHibernate.Cfg.Configuration().Configure();
    var returnList = session.CreateCriteria(typeof(T));
    var list = returnList.List();
    var castList = list.Cast<typeof(T)>();
    return castList;
}
</code>```

<p>So, I'm getting a build error where I am casting the "list" element to a generic IList .... can anyone see a glaring error here? </p>

答: The IList is an IList<T>, it just got fubared by markdown when she posted it. I tried to format it, but I missed escaping the <T>..Fixing that now.</p>

OwnerDisplayName: Sara Chipps

ContentLicense: CC BY-SA 2.5

Body:
public static IList<T> LoadObjectListAll<T>()
{
    ISession session = CheckForExistingSession();
    var cfg = new NHibernate.Cfg.Configuration().Configure();
    var returnList = session.CreateCriteria(typeof(T));
    var list = returnList.List();
    var castList = list.Cast<typeof(T)>();
    return castList;
}

So, I'm getting a build error where I am casting the "list" element to a generic IList .... can anyone see a glaring error here?

OwnerDisplayName: Jonathan Holland


问:
Alternatives to the Turing Test
So we learned a bit about the Turing Test in my AI class.  This got me thinking about it.  I can see a few limitations with it:

It's limited to a certain context.  What if I'm not designing an AI to converse with humans?

It favors acting humanly over acting rationally.  For example, if I'm designing an AI to control nuclear missiles, do I really want it to act human?  Granted, this is an extreme example, but you get the idea.

It could be influenced by factors that don't indicate that the computer can think humanly.  For example, suppose I ask what 2334 * 321 is.  I could tell if the device is a computer because it will probably answer me fairly quickly while a human would have to figure it out.  The solution?  Make the computer pause.

Now, I'm sure that the Turing Test still has its place in determining machine intelligence.  But I see it as being fairly limited in scope.  Are there any alternatives?  For that matter, am I wrong as to what I perceive to be its limitations?

EDIT:  Let me be clear:  I'm not suggesting that the Turing Test should be abandoned.  I'm just curious if there are any other tests that overcome its limitations (probably trading them for other limitations).

答:
Philip K Dick would have a field day with this one...

1). What other contexts exist? AI-Dolphin? Human intelligence is the only one we have direct experience of (and philosophy still isn't sure about that), the only one we can even begin to approach anything empirical and measurable. Everything else would be second order abstraction. At best

2). Do you really want AI to act rationally? Rationality says nothing of morality which can take you some scary places. Humans who act purely rationally do some pretty fecked up things. Even if you broaden rationality to logicality - the two are not the same - there's still something ineffably more about being human.

3). well that's the trick isn't it? You can't just pause because most real humans will not be able to answer that at all, or will answer in very human terms - "err, about 750k ish". Turing is all about appearances.

Don't get caught up in the technical too much, it's more of a philisophical hypothesis.

OwnerDisplayName: Jason Baker

Title: Alternatives to the Turing Test

LastEditorDisplayName: Rob

OwnerDisplayName: annakata


问:
Python decorator for function completion
Is it possible to develop a decorator to determine if a function successfully completed without crashing ? Something like the decorator below but it must detect if the function ran successfully. </p>

```<code>def functionStartDecorator():
    print("Function has started")
    def decoratorWrapper(functionToBeDecorated):
        def wrapper(*args, **kwargs):
            #Todo log function has run
            return functionToBeDecorated(*args, **kwargs)
        return wrapper
    return decoratorWrapper
</code>```

答:
I did something like this. Do you see any issues with this code ?</p>

```<code>def functionStartDecorator():
    def decoratorWrapper(functionToBeDecorated):
        def wrapper(*args, **kwargs):
            try:
                print("Function has started")
                result=functionToBeDecorated(*args, **kwargs)
                print("Function has complete")
                return result
            except:
                print ("Function failed")
        return wrapper
    return decoratorWrapper

@functionStartDecorator()
def simplefunc():
    return "somthing"
</code>```

Body:
Is it possible to develop a decorator to determine if a function successfully completed without crashing ? Something like the decorator below but it must detect if the function ran successfully.

def functionStartDecorator():
    print("Function has started")
    def decoratorWrapper(functionToBeDecorated):
        def wrapper(*args, **kwargs):
            #Todo log function has run
            return functionToBeDecorated(*args, **kwargs)
        return wrapper
    return decoratorWrapper

Body:
I did something like this. Do you see any issues with this code ?

def functionStartDecorator():
    def decoratorWrapper(functionToBeDecorated):
        def wrapper(*args, **kwargs):
            try:
                print("Function has started")
                result=functionToBeDecorated(*args, **kwargs)
                print("Function has complete")
                return result
            except:
                print ("Function failed")
        return wrapper
    return decoratorWrapper

@functionStartDecorator()
def simplefunc():
    return "somthing"


问:
shiny ui.r code is not working
This is my code for ui.r - it is not working. Please help me out.</p>

```<code>library(shiny)
library(plotly)
shinyUI(fluidPage(
  titlePanel("Coronary Heart Disease"),
  sidebarLayout(
    sidebarPanel(
      sliderInput("slider 1","age",15,65,42.82),
      sliderInput("slider 2","trestbps",145,170,120),
      radioButtons("radio", label = h2("radio buttons"),
                   choices = list("choices 1"= male, "choice 2"=female),
                   selected = male),
      hr(),
      fluidRow(column(2,verbatimTextOutput(value)))
    ),
      sliderInput("slider 4","cholestrol",342,177,266),
      sliderInput("slider 5","fbs",0,1,1)
    ),
    mainPanel(
      tabsetPanel(type="tabs",
                  tabsetPanel("instruction",
                              p(""),
p("this web application will calculate the chances of coronary heart disease in a person based on five variables"),
p("just change the five slider value and see the probability value changes correspondingly")

                              ),
tabPanel("probability of having coronary heart disease (%)",h1(textOutput(pred1)))

                  )
    )

    )

  )
</code>```

答:
Your code is extremally messy with lots of brackets that are open and not closed, no commas, the choices in radioButtons wrongly formatted, etc...

Here is smthg that i have created out of this what You provided:

```<code>library(shiny)

ui= fluidPage(
  titlePanel("Coronary Heart Disease"),
  sidebarLayout(
    sidebarPanel(
      sliderInput("slider 1","age",15,65,42.82),
      sliderInput("slider 2","trestbps",145,170,120),
      radioButtons("radio", label = h2("radio buttons"),
                   choices = list("choices 1"= "male", "choice 2"="female"),
                   selected = "male"),
      hr(),
    verbatimTextOutput("value"),
    sliderInput("slider 4","cholestrol",342,177,266),
    sliderInput("slider 5","fbs",0,1,1)),
  mainPanel(
    tabsetPanel(type="tabs",
                tabsetPanel("instruction",
                            p(""),
                            p("this web application will calculate the chances of coronary heart disease in a person based on five variables"),
                            p("just change the five slider value and see the probability value changes correspondingly")

                ),
                tabPanel("probability of having coronary heart disease (%)",textOutput("pred1"))

    )
  ))

)

server= function(input, output,session) {}

shinyApp(ui, server)
</code>```

You should have stated more clearly that what you want is to check out Your code formatting! Please take care for the future about clear Question!

Title: shiny ui.r code is not working

Body:
This is my code for ui.r - it is not working. Please help me out.

library(shiny)
library(plotly)
shinyUI(fluidPage(
  titlePanel("Coronary Heart Disease"),
  sidebarLayout(
    sidebarPanel(
      sliderInput("slider 1","age",15,65,42.82),
      sliderInput("slider 2","trestbps",145,170,120),
      radioButtons("radio", label = h2("radio buttons"),
                   choices = list("choices 1"= male, "choice 2"=female),
                   selected = male),
      hr(),
      fluidRow(column(2,verbatimTextOutput(value)))
    ),
      sliderInput("slider 4","cholestrol",342,177,266),
      sliderInput("slider 5","fbs",0,1,1)
    ),
    mainPanel(
      tabsetPanel(type="tabs",
                  tabsetPanel("instruction",
                              p(""),
p("this web application will calculate the chances of coronary heart disease in a person based on five variables"),
p("just change the five slider value and see the probability value changes correspondingly")

                              ),
tabPanel("probability of having coronary heart disease (%)",h1(textOutput(pred1)))

                  )
    )

    )

  )

Body:
Your code is extremally messy with lots of brackets that are open and not closed, no commas, the choices in radioButtons wrongly formatted, etc...

Here is smthg that i have created out of this what You provided:

library(shiny)

ui= fluidPage(
  titlePanel("Coronary Heart Disease"),
  sidebarLayout(
    sidebarPanel(
      sliderInput("slider 1","age",15,65,42.82),
      sliderInput("slider 2","trestbps",145,170,120),
      radioButtons("radio", label = h2("radio buttons"),
                   choices = list("choices 1"= "male", "choice 2"="female"),
                   selected = "male"),
      hr(),
    verbatimTextOutput("value"),
    sliderInput("slider 4","cholestrol",342,177,266),
    sliderInput("slider 5","fbs",0,1,1)),
  mainPanel(
    tabsetPanel(type="tabs",
                tabsetPanel("instruction",
                            p(""),
                            p("this web application will calculate the chances of coronary heart disease in a person based on five variables"),
                            p("just change the five slider value and see the probability value changes correspondingly")

                ),
                tabPanel("probability of having coronary heart disease (%)",textOutput("pred1"))

    )
  ))

)

server= function(input, output,session) {}

shinyApp(ui, server)

You should have stated more clearly that what you want is to check out Your code formatting! Please take care for the future about clear Question!


问:
Subclassing foreign Service does not work
I'm trying to subclassing the FileCollectionService class from third party extension. But it takes not place.

ext_typoscript_setup.txt:

```<code>config.tx_extbase{
persistence{
    classes{
        SKYFILLERS\SfFilecollectionGallery\Service\FileCollectionService {
            subclasses {
                TxFileCollectionService = FalkRoeder\MyExt\Service\FileCollectionService
            }
        }

    }
}
</code>```

}

my FileCollectionService.php put in Classes/Service

```<code><?php
namespace FalkRoeder\MyExt\Service;

/**
 * FileCollectionService
 */
class FileCollectionService extends \SKYFILLERS\SfFilecollectionGallery\Service\FileCollectionService {

    /**
     * @return array
     */
    public function methodToOverwrite() {
    ...
    }
}
</code>```

答:
Try to something Like this.</p>

```<code>config.tx_extbase{
    persistence{
        classes{
            SKYFILLERS\\SfFilecollectionGallery\\Service\\FileCollectionService {
                subclasses {
                    TxFileCollectionService = VendorName\ExtensionKey\Classes\Utility\FileCollectionService

                }
            }

        }
    }
}
</code>```

Body:
I'm trying to subclassing the FileCollectionService class from third party extension. But it takes not place.

ext_typoscript_setup.txt:

config.tx_extbase{
persistence{
    classes{
        SKYFILLERS\SfFilecollectionGallery\Service\FileCollectionService {
            subclasses {
                TxFileCollectionService = FalkRoeder\MyExt\Service\FileCollectionService
            }
        }

    }
}

}

my FileCollectionService.php put in Classes/Service

<?php
namespace FalkRoeder\MyExt\Service;

/**
 * FileCollectionService
 */
class FileCollectionService extends \SKYFILLERS\SfFilecollectionGallery\Service\FileCollectionService {

    /**
     * @return array
     */
    public function methodToOverwrite() {
    ...
    }
}

Body:
Try to something Like this.

config.tx_extbase{
    persistence{
        classes{
            SKYFILLERS\\SfFilecollectionGallery\\Service\\FileCollectionService {
                subclasses {
                    TxFileCollectionService = VendorName\ExtensionKey\Classes\Utility\FileCollectionService

                }
            }

        }
    }
}


问:
Removing unused factors from grouped facet_grid bar plot
I have read through the first page of results for this search but nothing seems to be working.

I need to create a plot that drops the unused levels on X, so that Strongly disagree, Disagree, and Mildyl disagree are grouped into the facet of 'detractors', then Uncertain and Mildly agree are grouped into the facet of 'Passive', and Agree and Strongly agree are grouped into 'Promoters'.

Here is a dput of the data

```<code>structure(list(area = c("NPS.recomm", "invest", "commit", "involve",
"all.consid", "exit.in", "FBM.recomm", "NPS.recomm", "invest",
"commit", "involve", "all.consid", "exit.in", "FBM.recomm", "NPS.recomm",
"invest", "commit", "involve", "all.consid", "exit.in", "FBM.recomm"
), response.cat = c("Strongly \ndisagree", "Disagree", "Mildly \ndisagree",
"Uncertain", "Mildly \nagree", "Agree", "Strongly \nagree", "Strongly \ndisagree",
"Disagree", "Mildly \ndisagree", "Uncertain", "Mildly \nagree",
"Agree", "Strongly \nagree", "Strongly \ndisagree", "Disagree",
"Mildly \ndisagree", "Uncertain", "Mildly \nagree", "Agree",
"Strongly \nagree"), response.set = c("Detractors", "Detractors",
"Detractors", "Passive", "Passive", "Promoters", "Promoters",
"Detractors", "Detractors", "Detractors", "Passive", "Passive",
"Promoters", "Promoters", "Detractors", "Detractors", "Detractors",
"Passive", "Passive", "Promoters", "Promoters"), split = structure(c(1L,
1L, 1L, 1L, 1L, 1L, 1L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 3L, 3L, 3L,
3L, 3L, 3L, 3L), .Label = c("curr.score", "prior.score", "bench.score"
), class = "factor"), score = c(7, 6, 3, 15, 16, 39, 14, 5, 4,
4, 15, 22, 33, 18, 14, 10, 6, 16, 15, 29, 10)), row.names = c(NA,
-21L), .Names = c("area", "response.cat", "response.set", "split",
"score"), class = "data.frame")
</code>```

And here is the current code

```<code>col.set <- c("dodgerblue4", "#FF9933", "gold")
plot.labels <- c("group1","group2","group3")
curr.plot <- ggplot(plot.data, aes(response.cat, score)) +
  facet_grid(. ~ response.set, scales="free_x", space = "free_x") +
  geom_bar(aes(fill = split), position = "dodge", stat="identity")+
  scale_fill_manual(values=c(col.set), labels= plot.labels )+
  ylim(c(0,100))+
  theme(legend.title = element_blank(), legend.position = "bottom",
        legend.text=element_text(colour= "gray23"), legend.key.height=unit(3,"mm")) +
  theme(axis.title= element_blank()) +
  scale_x_discrete(limits = c("Strongly \ndisagree","Disagree","Mildly \ndisagree","Uncertain","Mildly \nagree","Agree","Strongly \nagree"))+
  geom_text(aes(fill = split, label = paste0(score,"%")), colour = "gray23", vjust=-1, position=position_dodge(.9),size=3)+
  theme(panel.grid.minor.y = element_blank()) +
  theme(panel.grid.major.y = element_line(colour = "gray")) +
  theme(panel.grid.major.x =element_blank(), panel.grid.minor.x =element_blank()) +
  theme(panel.background = element_rect(fill="white")) +
  theme(axis.text.x = element_text(colour = "gray23")) +
  theme(axis.text.y = element_text(colour = "gray23")) +
  theme(axis.ticks.y=element_blank())
</code>```

Which produces the below, you can see the detractors facet looks right, but the other two facets contain unused factors. I just want the X labels appearing once across the bottom.Also weird how it has spaced the facets given the number of categories in each.

Any ideas?

答:
The problem is your use of scale_x_discrete. You can transform response.cat into an ordered factor instead:

```<code>plot.data$response.cat <- factor(plot.data$response.cat, levels = c("Strongly \ndisagree","Disagree","Mildly \ndisagree","Uncertain","Mildly \nagree","Agree","Strongly \nagree"))

ggplot(plot.data, aes(response.cat, score)) +
  facet_grid(. ~ response.set, scales="free_x", space = "free_x") +
  geom_bar(aes(fill = split), position = "dodge", stat="identity")+
  scale_fill_manual(values=c(col.set), labels= plot.labels )+
  ylim(c(0,100))+
  theme(legend.title = element_blank(), legend.position = "bottom",
        legend.text=element_text(colour= "gray23"), legend.key.height=unit(3,"mm")) +
  theme(axis.title= element_blank()) +
  geom_text(aes(fill = split, label = paste0(score,"%")), colour = "gray23", vjust=-1, position=position_dodge(.9),size=3)+
  theme(panel.grid.minor.y = element_blank()) +
  theme(panel.grid.major.y = element_line(colour = "gray")) +
  theme(panel.grid.major.x =element_blank(), panel.grid.minor.x =element_blank()) +
  theme(panel.background = element_rect(fill="white")) +
  theme(axis.text.x = element_text(colour = "gray23")) +
  theme(axis.text.y = element_text(colour = "gray23")) +
  theme(axis.ticks.y=element_blank())
</code>```

Body:
I have read through the first page of results for this search but nothing seems to be working.

I need to create a plot that drops the unused levels on X, so that Strongly disagree, Disagree, and Mildyl disagree are grouped into the facet of 'detractors', then Uncertain and Mildly agree are grouped into the facet of 'Passive', and Agree and Strongly agree are grouped into 'Promoters'.

Here is a dput of the data

structure(list(area = c("NPS.recomm", "invest", "commit", "involve",
"all.consid", "exit.in", "FBM.recomm", "NPS.recomm", "invest",
"commit", "involve", "all.consid", "exit.in", "FBM.recomm", "NPS.recomm",
"invest", "commit", "involve", "all.consid", "exit.in", "FBM.recomm"
), response.cat = c("Strongly \ndisagree", "Disagree", "Mildly \ndisagree",
"Uncertain", "Mildly \nagree", "Agree", "Strongly \nagree", "Strongly \ndisagree",
"Disagree", "Mildly \ndisagree", "Uncertain", "Mildly \nagree",
"Agree", "Strongly \nagree", "Strongly \ndisagree", "Disagree",
"Mildly \ndisagree", "Uncertain", "Mildly \nagree", "Agree",
"Strongly \nagree"), response.set = c("Detractors", "Detractors",
"Detractors", "Passive", "Passive", "Promoters", "Promoters",
"Detractors", "Detractors", "Detractors", "Passive", "Passive",
"Promoters", "Promoters", "Detractors", "Detractors", "Detractors",
"Passive", "Passive", "Promoters", "Promoters"), split = structure(c(1L,
1L, 1L, 1L, 1L, 1L, 1L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 3L, 3L, 3L,
3L, 3L, 3L, 3L), .Label = c("curr.score", "prior.score", "bench.score"
), class = "factor"), score = c(7, 6, 3, 15, 16, 39, 14, 5, 4,
4, 15, 22, 33, 18, 14, 10, 6, 16, 15, 29, 10)), row.names = c(NA,
-21L), .Names = c("area", "response.cat", "response.set", "split",
"score"), class = "data.frame")

And here is the current code

col.set <- c("dodgerblue4", "#FF9933", "gold")
plot.labels <- c("group1","group2","group3")
curr.plot <- ggplot(plot.data, aes(response.cat, score)) +
  facet_grid(. ~ response.set, scales="free_x", space = "free_x") +
  geom_bar(aes(fill = split), position = "dodge", stat="identity")+
  scale_fill_manual(values=c(col.set), labels= plot.labels )+
  ylim(c(0,100))+
  theme(legend.title = element_blank(), legend.position = "bottom",
        legend.text=element_text(colour= "gray23"), legend.key.height=unit(3,"mm")) +
  theme(axis.title= element_blank()) +
  scale_x_discrete(limits = c("Strongly \ndisagree","Disagree","Mildly \ndisagree","Uncertain","Mildly \nagree","Agree","Strongly \nagree"))+
  geom_text(aes(fill = split, label = paste0(score,"%")), colour = "gray23", vjust=-1, position=position_dodge(.9),size=3)+
  theme(panel.grid.minor.y = element_blank()) +
  theme(panel.grid.major.y = element_line(colour = "gray")) +
  theme(panel.grid.major.x =element_blank(), panel.grid.minor.x =element_blank()) +
  theme(panel.background = element_rect(fill="white")) +
  theme(axis.text.x = element_text(colour = "gray23")) +
  theme(axis.text.y = element_text(colour = "gray23")) +
  theme(axis.ticks.y=element_blank())

Which produces the below, you can see the detractors facet looks right, but the other two facets contain unused factors. I just want the X labels appearing once across the bottom.Also weird how it has spaced the facets given the number of categories in each.

Any ideas?

Body:
The problem is your use of scale_x_discrete. You can transform response.cat into an ordered factor instead:

plot.data$response.cat <- factor(plot.data$response.cat, levels = c("Strongly \ndisagree","Disagree","Mildly \ndisagree","Uncertain","Mildly \nagree","Agree","Strongly \nagree"))

ggplot(plot.data, aes(response.cat, score)) +
  facet_grid(. ~ response.set, scales="free_x", space = "free_x") +
  geom_bar(aes(fill = split), position = "dodge", stat="identity")+
  scale_fill_manual(values=c(col.set), labels= plot.labels )+
  ylim(c(0,100))+
  theme(legend.title = element_blank(), legend.position = "bottom",
        legend.text=element_text(colour= "gray23"), legend.key.height=unit(3,"mm")) +
  theme(axis.title= element_blank()) +
  geom_text(aes(fill = split, label = paste0(score,"%")), colour = "gray23", vjust=-1, position=position_dodge(.9),size=3)+
  theme(panel.grid.minor.y = element_blank()) +
  theme(panel.grid.major.y = element_line(colour = "gray")) +
  theme(panel.grid.major.x =element_blank(), panel.grid.minor.x =element_blank()) +
  theme(panel.background = element_rect(fill="white")) +
  theme(axis.text.x = element_text(colour = "gray23")) +
  theme(axis.text.y = element_text(colour = "gray23")) +
  theme(axis.ticks.y=element_blank())


问:
Vertically middle align text in a bootstrap column
I need tree cells in tree columns(col-4), with an image, that determines the height of the cell, and vertically middle-aligned text, like this:

This is what I get (CodePen Here):

      Some text red-yellow

      some other text long text some other long text lightgreen-gray

      this is another long long long text that should be here skyblue-violet

```

Where is the problem ?

答:
Try this. Use display: table; for parent class and display: table-cell; vertical-align: middle; for child elements. This will give you vertical align correctly.

    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">

            Some text red-yellow

            some other text long text some other long text lightgreen-gray

            this is another long long long text that should be here skyblue-violet

```

Body:
I need tree cells in tree columns(col-4), with an image, that determines the height of the cell, and vertically middle-aligned text, like this:

This is what I get (CodePen Here):

      Some text red-yellow

      some other text long text some other long text lightgreen-gray

      this is another long long long text that should be here skyblue-violet

Where is the problem ?

Body:
Try this. Use display: table; for parent class and display: table-cell; vertical-align: middle; for child elements. This will give you vertical align correctly.

<html>

<head>

    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.0/jquery.min.js"></script>
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
    <style>
        a {
            display: block;
        }
        .customclass {
            display: table;
        }
        .customclass img, .customclass a{
            display: table-cell;
            vertical-align: middle;
        }
    </style>
</head>

<body>
    <div class="row">
        <div class="col-xs-4 text-center customclass" style="background:red">
            <img src="http://placehold.it/75">
            <a style="background: yellow">Some text red-yellow</a>
        </div>

        <div class="col-xs-4 text-center customclass" style="background:lightgreen">
            <img src="http://placehold.it/75">
            <a style="background: gray">some other text long text some other long text lightgreen-gray</a>
        </div>
        <div class="col-xs-4 text-center customclass" style="background:skyblue">
            <img src="http://placehold.it/75">
            <a style="background: violet">this is another long long long text that should be here skyblue-violet</a>
        </div>
    </div>
</body>

</html>


问:
Saving data to a file vs. saving it to MySQL DB
Using a PHP script I need to update a number every 5 seconds while somebody is on my page. So let's say I have 300 visitors, each one spending about 1 minute on the page and every 5 seconds they stay on the page the number will be changed...which is a total of 3600 changes per minute. I would prefer to update the number in my MySQL database, except I'm not sure if it's not too inefficient to have so many MySQL connections (just for the one number change), when I could just change the number in a file.

P.S.: I have no idea weather 3600 connections/minute is a high number or not, but what about this case in general, considering an even higher number of visitors. What is the most efficient way to do this?

答:
If you save to file, you have to solve concurrency issues (and all but the currently reading/writing process will have to wait). The db solves this for you. For better performance you could use memcached.

Maybe you could do without this "do every 5s for each user" by another means (e.g. saving current time and subtracting next time the user does something). This depends on your real problem.


问:
Create matrix all possible combinations for n numbers
So this is the first question that i post.
I'm having some problems with the creation of a matrix in Matlab.
I would like to create a matrix that containts all possible unique combinations for the numbers [1,2,3] (thus without any duplicate combinations).

Meaning that it will create a matrix that looks like the following:

1 2

1 3

1 2 3

2 3

Thanks in advance!

答:
You cannot have a matrix like that. You can only have:

```<code>1 2 NaN
1 3 NaN
1 2 3
2 3 NaN
</code>```

You can have cell array like A = cell(4,1); A{1} = [1, 2]; A{2} = ...

And if you wish to get the code that would generate all those possibilities (what I believe you actually want), then change your question and show what you have attempted already.

Now lets assume this is what you really want. You should do recursion. Pseudocode solution would be like:

```<code>generatelist(numbers)
if numbers is empty, return [];
else return cell array length numbers+1, where first element is empty and the remaining ones have that numberX + output of generatelist(numbers > numberX).
</code>```

To get rid of single element answers, parse them out at the end, it will simplify recursion part slightly.
To get the matrix, find the longest cell and number of the combination, create matrix with nans and fill the values.

Body:
You cannot have a matrix like that. You can only have:

1 2 NaN
1 3 NaN
1 2 3
2 3 NaN

You can have cell array like A = cell(4,1); A{1} = [1, 2]; A{2} = ...

And if you wish to get the code that would generate all those possibilities (what I believe you actually want), then change your question and show what you have attempted already.

Now lets assume this is what you really want. You should do recursion. Pseudocode solution would be like:

generatelist(numbers)
if numbers is empty, return [];
else return cell array length numbers+1, where first element is empty and the remaining ones have that numberX + output of generatelist(numbers > numberX).

To get rid of single element answers, parse them out at the end, it will simplify recursion part slightly.
To get the matrix, find the longest cell and number of the combination, create matrix with nans and fill the values.


问:
OpenCV - Python Bag Of Words(BoW) generating histograms from dictionary
I have been trying to create an image classifier in Python OpenCV 3.2.0 using keypoints and the bag of words technique. After some reading I found that I could peform this as follows

Extract image descriptors using AKAZE

Perform k-means clustering on the descriptors to generate the dictionary

Generate histograms of images based on dictionary

Train SVM using histograms

I managed to do steps 1 and 2 but have gotten stuck on steps 3 and 4.

I generated the histograms by using the labels returned by k-means clustering successfully (I think). However, when I wanted to use new test data that was not used to generate the dictionary I had some unexpected results. I tried to use a FLANN matcher like in this tutorial but the results I get from generating the histograms from the label data does not match the data returned from the FLANN matching.

I load up the images:

```<code>dictionary_size = 512
# Loading images
imgs_data = []
# imreads returns a list of all images in that directory
imgs = imreads(imgs_path)
for i in xrange(len(imgs)):
    # create a numpy to hold the histogram for each image
    imgs_data.insert(i, np.zeros((dictionary_size, 1)))
</code>```

I then create an array of descriptors (desc):

```<code>def get_descriptors(img, detector):
    # returns descriptors of an image
    return detector.detectAndCompute(img, None)[1]

# Extracting descriptors
detector = cv2.AKAZE_create()

desc = np.array([])
# desc_src_img is a list which says which image a descriptor belongs to
desc_src_img = []
for i in xrange(len(imgs)):
    img = imgs[i]
    descriptors = get_descriptors(img, detector)
    if len(desc) == 0:
        desc = np.array(descriptors)
    else:
        desc = np.vstack((desc, descriptors))
    # Keep track of which image a descriptor belongs to
    for j in range(len(descriptors)):
        desc_src_img.append(i)
# important, cv2.kmeans only accepts type32 descriptors
desc = np.float32(desc)
</code>```

The descriptors are then clustered using k-means:

```<code># Clustering
criteria = (cv2.TERM_CRITERIA_EPS + cv2.TERM_CRITERIA_MAX_ITER, 10, 0.01)
flags = cv2.KMEANS_PP_CENTERS
# desc is a type32 numpy array of vstacked descriptors
compactness, labels, dictionary = cv2.kmeans(desc, dictionary_size, None, criteria, 1, flags)
</code>```

Then I create histograms for each image using the labels returned from k-means:

```<code># Getting histograms from labels
size = labels.shape[0] * labels.shape[1]
for i in xrange(size):
    label = labels[i]
    # Get this descriptors image id
    img_id = desc_src_img[i]
    # imgs_data is a list of the same size as the number of images
    data = imgs_data[img_id]
    # data is a numpy array of size (dictionary_size, 1) filled with zeros
    data[label] += 1

ax = plt.subplot(311)
ax.set_title("Histogram from labels")
ax.set_xlabel("Visual words")
ax.set_ylabel("Frequency")
ax.plot(imgs_data[0].ravel())
</code>```

This outputs a histogram like this  which is very evenly distributed and what I expect.

I then attempt to do the same thing on the same image but using FLANN:

```<code>matcher = cv2.FlannBasedMatcher_create()
matcher.add(dictionary)
matcher.train()

descriptors = get_descriptors(imgs[0], detector)

result = np.zeros((dictionary_size, 1), np.float32)
# flan matcher needs descriptors to be type32
matches = matcher.match(np.float32(descriptors))
for match in matches:
    visual_word = match.trainIdx
    result[visual_word] += 1

ax = plt.subplot(313)
ax.set_title("Histogram from FLANN")
ax.set_xlabel("Visual words")
ax.set_ylabel("Frequency")
ax.plot(result.ravel())
</code>```

This outputs a histogram like this  which is very unevenly distributed and does not match up with the first histogram.

You can view the full code and images on GitHub. Change "imgs_path" (line 20) to a directory with images before running it.

Where am I going wrong? Why are the histograms so different? How do I generate the histograms for new data using the dictionary?

As a side note I tried using the OpenCV BOW implementation but found another issue where it gave the error: "_queryDescriptors.type() == trainDescType in function cv::BFMatcher::knnMatchImpl" and that's why I am trying to implement it myself. If someone could provide a working example using Python OpenCV BOW and AKAZE then that would be just as good.

答:
It seems that you cannot train a FlannBasedMatcher using a dictionary before hand as show below:

```<code>matcher = cv2.FlannBasedMatcher_create()
matcher.add(dictionary)
matcher.train()
</code>```

However you can pass the dictionary in when matching like this:

```<code>matcher = cv2.FlannBasedMatcher_create()

...

matches = matcher.match(np.float32(descriptors), dictionary)
</code>```

I am not entirely sure why this. Perhaps its that the train method is only meant to be used by the match method as hinted in this post.

Also according to the opencv docs the parameters for match are:

queryDescriptors – Query set of descriptors.

trainDescriptors – Train set of descriptors. This set is not added to the train descriptors collection stored in the class object.

matches – Matches. If a query descriptor is masked out in mask , no match is added for this descriptor. So, matches size may be smaller than the query descriptors count.

So I guess you are just supposed to pass the dictionary in as trainDescriptors because that is what it is.

If anyone could shed more light on this it would be appreciated.

Here are the results after using the above method:

You can see the full updated code here.

Body:
I have been trying to create an image classifier in Python OpenCV 3.2.0 using keypoints and the bag of words technique. After some reading I found that I could peform this as follows

Extract image descriptors using AKAZE

Perform k-means clustering on the descriptors to generate the dictionary

Generate histograms of images based on dictionary

Train SVM using histograms

I managed to do steps 1 and 2 but have gotten stuck on steps 3 and 4.

I generated the histograms by using the labels returned by k-means clustering successfully (I think). However, when I wanted to use new test data that was not used to generate the dictionary I had some unexpected results. I tried to use a FLANN matcher like in this tutorial but the results I get from generating the histograms from the label data does not match the data returned from the FLANN matching.

I load up the images:

dictionary_size = 512
# Loading images
imgs_data = []
# imreads returns a list of all images in that directory
imgs = imreads(imgs_path)
for i in xrange(len(imgs)):
    # create a numpy to hold the histogram for each image
    imgs_data.insert(i, np.zeros((dictionary_size, 1)))

I then create an array of descriptors (desc):

def get_descriptors(img, detector):
    # returns descriptors of an image
    return detector.detectAndCompute(img, None)[1]

# Extracting descriptors
detector = cv2.AKAZE_create()

desc = np.array([])
# desc_src_img is a list which says which image a descriptor belongs to
desc_src_img = []
for i in xrange(len(imgs)):
    img = imgs[i]
    descriptors = get_descriptors(img, detector)
    if len(desc) == 0:
        desc = np.array(descriptors)
    else:
        desc = np.vstack((desc, descriptors))
    # Keep track of which image a descriptor belongs to
    for j in range(len(descriptors)):
        desc_src_img.append(i)
# important, cv2.kmeans only accepts type32 descriptors
desc = np.float32(desc)

The descriptors are then clustered using k-means:

# Clustering
criteria = (cv2.TERM_CRITERIA_EPS + cv2.TERM_CRITERIA_MAX_ITER, 10, 0.01)
flags = cv2.KMEANS_PP_CENTERS
# desc is a type32 numpy array of vstacked descriptors
compactness, labels, dictionary = cv2.kmeans(desc, dictionary_size, None, criteria, 1, flags)

Then I create histograms for each image using the labels returned from k-means:

# Getting histograms from labels
size = labels.shape[0] * labels.shape[1]
for i in xrange(size):
    label = labels[i]
    # Get this descriptors image id
    img_id = desc_src_img[i]
    # imgs_data is a list of the same size as the number of images
    data = imgs_data[img_id]
    # data is a numpy array of size (dictionary_size, 1) filled with zeros
    data[label] += 1

ax = plt.subplot(311)
ax.set_title("Histogram from labels")
ax.set_xlabel("Visual words")
ax.set_ylabel("Frequency")
ax.plot(imgs_data[0].ravel())

This outputs a histogram like this  which is very evenly distributed and what I expect.

I then attempt to do the same thing on the same image but using FLANN:

matcher = cv2.FlannBasedMatcher_create()
matcher.add(dictionary)
matcher.train()

descriptors = get_descriptors(imgs[0], detector)

result = np.zeros((dictionary_size, 1), np.float32)
# flan matcher needs descriptors to be type32
matches = matcher.match(np.float32(descriptors))
for match in matches:
    visual_word = match.trainIdx
    result[visual_word] += 1

ax = plt.subplot(313)
ax.set_title("Histogram from FLANN")
ax.set_xlabel("Visual words")
ax.set_ylabel("Frequency")
ax.plot(result.ravel())

This outputs a histogram like this  which is very unevenly distributed and does not match up with the first histogram.

You can view the full code and images on GitHub. Change "imgs_path" (line 20) to a directory with images before running it.

Where am I going wrong? Why are the histograms so different? How do I generate the histograms for new data using the dictionary?

As a side note I tried using the OpenCV BOW implementation but found another issue where it gave the error: "_queryDescriptors.type() == trainDescType in function cv::BFMatcher::knnMatchImpl" and that's why I am trying to implement it myself. If someone could provide a working example using Python OpenCV BOW and AKAZE then that would be just as good.

Body:
It seems that you cannot train a FlannBasedMatcher using a dictionary before hand as show below:

matcher = cv2.FlannBasedMatcher_create()
matcher.add(dictionary)
matcher.train()

However you can pass the dictionary in when matching like this:

matcher = cv2.FlannBasedMatcher_create()

...

matches = matcher.match(np.float32(descriptors), dictionary)

I am not entirely sure why this. Perhaps its that the train method is only meant to be used by the match method as hinted in this post.

Also according to the opencv docs the parameters for match are:

queryDescriptors – Query set of descriptors.

trainDescriptors – Train set of descriptors. This set is not added to the train descriptors collection stored in the class object.

matches – Matches. If a query descriptor is masked out in mask , no match is added for this descriptor. So, matches size may be smaller than the query descriptors count.

So I guess you are just supposed to pass the dictionary in as trainDescriptors because that is what it is.

If anyone could shed more light on this it would be appreciated.

Here are the results after using the above method:

You can see the full updated code here.


问:
Android RatingBar shows extra remainder
I'm using the standard Android RatingBar. It seems to behave quite weird. For some reason I can't select only full stars. It always shows a little bit more or less. Also the .setNumStars property doesn't seem to work. I'm using the following code:

```<code>RatingBar ratingbar = new RatingBar(this);
ratingbar.setLayoutParams(lp);
ratingbar.setVisibility(View.VISIBLE);
ratingbar.setNumStars(5);
ratingbar.setStepSize(1);
ratingbar.setRating(1);
linearLayoutReviews.addView(ratingbar);
</code>```

When I select 1 star it selects one star:

When I select 2 stars:

When I select 3 stars:

When I select 4 stars:

And when I select 5 stars:

So for some reason it shows more than 5 stars, and there will always be a remainder of the next star selected

EDIT

When I set .setNumStars to 6 I can select them one by one, but than ofcourse, I have six

EDIT

This is the xml of the LinearLayout

```<code><LinearLayout
                android:id="@+id/linearLayoutReviews"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginEnd="10dp"
                android:layout_marginLeft="10dp"
                android:layout_marginRight="10dp"
                android:layout_marginStart="10dp"
                android:orientation="vertical"
                app:layout_constraintLeft_toLeftOf="parent"
                app:layout_constraintRight_toRightOf="parent"
                app:layout_constraintTop_toBottomOf="@+id/textView5"></LinearLayout>
</code>```

答:
You have added  RatingBar multiple times LinearLayout that's why its showing previous RatingBar in your LinearLayout .

So remove all current RatingBar from LinearLayout first and then add new RatingBar.

I have added one line in your code  see below: it may help you:

```<code>RatingBar ratingbar = new RatingBar(this);
ratingbar.setLayoutParams(lp);
ratingbar.setVisibility(View.VISIBLE);
ratingbar.setNumStars(5);
ratingbar.setStepSize(1);
ratingbar.setRating(1);
//In your code add the lines given below
linearLayoutReviews.removeAllViews();
linearLayoutReviews.addView(ratingbar);
</code>```

Title: Android RatingBar shows extra remainder

Body:
I'm using the standard Android RatingBar. It seems to behave quite weird. For some reason I can't select only full stars. It always shows a little bit more or less. Also the .setNumStars property doesn't seem to work. I'm using the following code:

RatingBar ratingbar = new RatingBar(this);
ratingbar.setLayoutParams(lp);
ratingbar.setVisibility(View.VISIBLE);
ratingbar.setNumStars(5);
ratingbar.setStepSize(1);
ratingbar.setRating(1);
linearLayoutReviews.addView(ratingbar);

When I select 1 star it selects one star:

When I select 2 stars:

When I select 3 stars:

When I select 4 stars:

And when I select 5 stars:

So for some reason it shows more than 5 stars, and there will always be a remainder of the next star selected

EDIT

When I set .setNumStars to 6 I can select them one by one, but than ofcourse, I have six

EDIT

This is the xml of the LinearLayout

<LinearLayout
                android:id="@+id/linearLayoutReviews"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginEnd="10dp"
                android:layout_marginLeft="10dp"
                android:layout_marginRight="10dp"
                android:layout_marginStart="10dp"
                android:orientation="vertical"
                app:layout_constraintLeft_toLeftOf="parent"
                app:layout_constraintRight_toRightOf="parent"
                app:layout_constraintTop_toBottomOf="@+id/textView5"></LinearLayout>

Body:
You have added  RatingBar multiple times LinearLayout that's why its showing previous RatingBar in your LinearLayout .

So remove all current RatingBar from LinearLayout first and then add new RatingBar.

I have added one line in your code  see below: it may help you:

RatingBar ratingbar = new RatingBar(this);
ratingbar.setLayoutParams(lp);
ratingbar.setVisibility(View.VISIBLE);
ratingbar.setNumStars(5);
ratingbar.setStepSize(1);
ratingbar.setRating(1);
//In your code add the lines given below
linearLayoutReviews.removeAllViews();
linearLayoutReviews.addView(ratingbar);


问:
What is the relationship between a thread and its parent stack?
pthreads all have their own stack and share the heap. They inherit various aspects of the parent at creation time (sig masks, fpenv etc.). There seems to be little said about the relationship between the child thread and the parents stack.

So can I pass the address of something on the parent stack to a child thread via pthread_create and expect this to work? Is the child thread able to see the stack of the parent process? Does the childs stack get populated with a copy of the parent stack at creation time?

It's useful to me to know what is guaranteed by the standard and what practically works.

答:
Given the appropriate lifetime, sure.

Pretty clearly, allowing stack-based structures to be deallocated in the parent before the other thread has finished with them is a bad idea:(

Otherwise, no actual problem.  It's all one process, so no accessability issues at all. It is not uncommon, and not, in itself, bad practice.

Whether it's a good idea in any particular case, is up to you to determine and design accordingly:)

It's easiest if such practices are left to pool and/or app-lifetime threads, (ie, those never explicitly terminated/destroyed until the OS kills them as process termination).  That ensures that all process threads are stopped before any memory is deallocated.


问:
how to make the following scala immutable
Suppose I have the following code:

BroadcastMessage gets a list of groups of students in the form of iterators that can only be traversed once

On call to sendMessage it will send message to all students in the groups.

```<code>class BroadcastMessage(message:String,groups:List[Iterator[Student]]) {

  def sendMessage:Unit = {
      groups.foreach(group=>group.foreach(sendeMessage))
  }

  private def sendMessage(student:Student): Unit ={
    EmailClient.sendMessage(student.email,message)
  }

}

case class Student(id: String,email:String)
</code>```

Say that student can exist in several groups and we don't want to send him more than one email.

The mutable solution would be to add mutable set and to add the id of the student to the set and only send the message if the id exists in the set.

```<code>class BroadcastMessage(message:String,groups:List[Iterator[Student]]) {
  // evil mutable set
  private var set:scala.collection.mutable.Set[String] = Set()

  def sendMessage:Unit = {
      groups.foreach(group=>group.foreach(sendeMessage))
  }

  private def sendMessage(student:Student): Unit ={
    if (set.add(student.id)) {
      EmailClient.sendMessage(student.email, message)
    }
  }

}
</code>```

How do I implement it in immutable way?

答:
If you have no memory restrictions, you can just do this:</p>

```<code>def sendMessage:Unit = {
    groups.flatten.distinct.foreach(sendMessage)
}
</code>```

Body:
Suppose I have the following code:

BroadcastMessage gets a list of groups of students in the form of iterators that can only be traversed once

On call to sendMessage it will send message to all students in the groups.

class BroadcastMessage(message:String,groups:List[Iterator[Student]]) {

  def sendMessage:Unit = {
      groups.foreach(group=>group.foreach(sendeMessage))
  }

  private def sendMessage(student:Student): Unit ={
    EmailClient.sendMessage(student.email,message)
  }

}

case class Student(id: String,email:String)

Say that student can exist in several groups and we don't want to send him more than one email.

The mutable solution would be to add mutable set and to add the id of the student to the set and only send the message if the id exists in the set.

class BroadcastMessage(message:String,groups:List[Iterator[Student]]) {
  // evil mutable set
  private var set:scala.collection.mutable.Set[String] = Set()

  def sendMessage:Unit = {
      groups.foreach(group=>group.foreach(sendeMessage))
  }

  private def sendMessage(student:Student): Unit ={
    if (set.add(student.id)) {
      EmailClient.sendMessage(student.email, message)
    }
  }

}

How do I implement it in immutable way?

Body:
If you have no memory restrictions, you can just do this:

def sendMessage:Unit = {
    groups.flatten.distinct.foreach(sendMessage)
}


问:
How to convert a list<list<object>> to object[,]?
I have the following static class to build an dynamic object Array:

```<code>public class oDataArray
{
    public static List<List<object>> GetDataObject(DbCommand command)
    {
        List<List<object>> oDataList = new List<List<object>>();

        using (DbDataReader dr = command.ExecuteReader())
        {
            if (dr.HasRows)
            {
                while (dr.Read())
                {
                    List<object> oData = new List<object>();

                    for (int i = 0; i < dr.FieldCount; i++)
                    {
                        oData.Add(dr[i]);
                    }
                    oDataList.Add(oData);
                }
            }
            dr.Close();
        }
        return oDataList;
    }
}
</code>```

I tried to convert it to a 2 dimensional object array via:

```<code>object[,] myNewObjectArray = oDataArray.GetDataObject(anyDbCommand).ToArray<object>().ToArray<object>();
</code>```

But it will not work!? :(
What I'm doing wrong?

答:
How about,

oDataArray.GetDataObject(anyDbCommand).Select(a => a.ToArray()).ToArray();

Some explanation:

Select(a => a.ToArray()) crates an enumerable of type object[],

ToArray() creates an array of arrays.

Body:
I have the following static class to build an dynamic object Array:

public class oDataArray
{
    public static List<List<object>> GetDataObject(DbCommand command)
    {
        List<List<object>> oDataList = new List<List<object>>();

        using (DbDataReader dr = command.ExecuteReader())
        {
            if (dr.HasRows)
            {
                while (dr.Read())
                {
                    List<object> oData = new List<object>();

                    for (int i = 0; i < dr.FieldCount; i++)
                    {
                        oData.Add(dr[i]);
                    }
                    oDataList.Add(oData);
                }
            }
            dr.Close();
        }
        return oDataList;
    }
}

I tried to convert it to a 2 dimensional object array via:

object[,] myNewObjectArray = oDataArray.GetDataObject(anyDbCommand).ToArray<object>().ToArray<object>();

But it will not work!? :(
What I'm doing wrong?


问:
What are these extra instructions when disassembling simple binary?
this is a bit of a noobish question... Here's a quick bit of background.
I'm learning about assembly, so I wrote a really simple C program, compiled it with gcc -m32 -O0 -o prog.elf and then ran objdump against it with objdump -M intel -d prog.elf.

The C code is:

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

int main() {
    int a = 1;
    int b = 2;
    a = a + b;

    return (0);
}
</code>```

Which seems simple enough. The generated Intel assembly (with my comments) is:

```<code>push   ebp                       ; Push previous stack frame.
mov    ebp, esp                  ; Move SP to EBP to set new stack frame.
sub    esp, 0xc                  ; Reserve 0xc bytes for local variables.
xor    eax, eax                  ; Clear eax.
mov    DWORD PTR [ebp-0x4], 0x0  ; Move 0x0 into local variable ebp-0x4.
mov    DWORD PTR [ebp-0x8], 0x1  ; Move 0x1 into local variable ebp-0x8.
mov    DWORD PTR [ebp-0xc], 0x2  ; Move 0x2 into local variable ebp-0xc.
mov    ecx, DWORD PTR [ebp-0x8]  ; Move local variable ebp-0x8 into ecx.
add    ecx, DWORD PTR [ebp-0xc]  ; Add local variable ebp-0xc to ecx.
mov    DWORD PTR [ebp-0x8], ecx  ; Move value of ecx into local variable ebp-0x8.
add    esp, 0xc                  ; Set SP back to location before.
pop    ebp                       ; Restore base pointer.
ret                              ; Return
</code>```

My question is, what is ebp-0x4 doing there? It doesn't seem to be doing anything.
I'll take a guess and say it's from main()'s paramaters, which it doesn't have, but for some reason it still pushes 0x0 as a parameter if none are provided?
Also, why xor eax, eax doesn't seem to be used...

I'm just a little confused about why they're there.
If anyone can help me understand why that would be great. Thanks in advance!

答:
I'm not sure as to why you think xor eax, eax is not being used, this is a simple way to set eax to zero. Since it's often the return code from a function, it would be the equivalent of your return 0; (which doesn't need parentheses by the way).

As to why the ebp-0x4 is there, I couldn't say. I will say that the rest of the code is well and truly unoptimised so it may just be an artefact of the compilation process. It may well disappear at higher optimisation levels, especially since the entire function could basically be replaced with the one line you think is superfluous :-)

Body:
this is a bit of a noobish question... Here's a quick bit of background.
I'm learning about assembly, so I wrote a really simple C program, compiled it with gcc -m32 -O0 -o prog.elf and then ran objdump against it with objdump -M intel -d prog.elf.

The C code is:

#include <stdio.h>

int main() {
    int a = 1;
    int b = 2;
    a = a + b;

    return (0);
}

Which seems simple enough. The generated Intel assembly (with my comments) is:

push   ebp                       ; Push previous stack frame.
mov    ebp, esp                  ; Move SP to EBP to set new stack frame.
sub    esp, 0xc                  ; Reserve 0xc bytes for local variables.
xor    eax, eax                  ; Clear eax.
mov    DWORD PTR [ebp-0x4], 0x0  ; Move 0x0 into local variable ebp-0x4.
mov    DWORD PTR [ebp-0x8], 0x1  ; Move 0x1 into local variable ebp-0x8.
mov    DWORD PTR [ebp-0xc], 0x2  ; Move 0x2 into local variable ebp-0xc.
mov    ecx, DWORD PTR [ebp-0x8]  ; Move local variable ebp-0x8 into ecx.
add    ecx, DWORD PTR [ebp-0xc]  ; Add local variable ebp-0xc to ecx.
mov    DWORD PTR [ebp-0x8], ecx  ; Move value of ecx into local variable ebp-0x8.
add    esp, 0xc                  ; Set SP back to location before.
pop    ebp                       ; Restore base pointer.
ret                              ; Return

My question is, what is ebp-0x4 doing there? It doesn't seem to be doing anything.
I'll take a guess and say it's from main()'s paramaters, which it doesn't have, but for some reason it still pushes 0x0 as a parameter if none are provided?
Also, why xor eax, eax doesn't seem to be used...

I'm just a little confused about why they're there.
If anyone can help me understand why that would be great. Thanks in advance!


问:
Bootstrap Table Toggle View with Checkbox
I am using Bootstrap Table. My problem is that when there are checkboxes in my table, table toggle view will be ugly(please see the red rectangle), looks like the second picture below. Can anyone help me how to fix this? Thank you!

答:
You can hide the checkboxes in the toggle view using css.

This is how I solved a similar issue:

```<code>.card-view .title input[type="checkbox"] {
    display: none;
}
</code>```

Body:
You can hide the checkboxes in the toggle view using css.

This is how I solved a similar issue:

.card-view .title input[type="checkbox"] {
    display: none;
}


问:
Use photo and video camera?
I want use iphone camera for tacking photo or videos.

I know how to open JUST Photo Camera, and JUST Video Camera, but i don't know how to launch both in the same time.

Can i use UIImagePickerController to open both in the same time or i need create a custom view?

Below is code used just for Photo Camera and  Video Camera

```<code>-(void)photoCameraButtonAction{
    if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {

        imagePicker = [[UIImagePickerController alloc] init];
        imagePicker.delegate = self;
        imagePicker.sourceType = UIImagePickerControllerSourceTypeCamera;

        [self presentViewController:imagePicker animated:YES completion:nil];
    }
}

-(void)videoCameraButtonAction{

    if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {

        imagePicker = [[UIImagePickerController alloc] init];
        imagePicker.delegate = self;
        imagePicker.sourceType = UIImagePickerControllerSourceTypeCamera;

        NSArray *mediaTypes = [UIImagePickerController availableMediaTypesForSourceType:UIImagePickerControllerSourceTypeCamera];
        NSArray *videoMediaTypesOnly = [mediaTypes filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:@"(SELF contains %@)", @"movie"]];

        imagePicker.mediaTypes = videoMediaTypesOnly;
        imagePicker.videoQuality = UIImagePickerControllerQualityTypeMedium;
        imagePicker.videoMaximumDuration = 180;

        [self presentViewController:imagePicker animated:YES completion:nil];
    }
}
</code>```

Thank you!

答:
You can do it like that</p>

```<code>        let picker = UIImagePickerController()
        picker.delegate = self
        picker.sourceType = .camera
        picker.mediaTypes = [kUTTypeMovie as String,kUTTypeImage as String]
        self.present(picker, animated: true, completion: nil)
</code>```

Title: Use photo and video camera?

Body:
I want use iphone camera for tacking photo or videos.

I know how to open JUST Photo Camera, and JUST Video Camera, but i don't know how to launch both in the same time.

Can i use UIImagePickerController to open both in the same time or i need create a custom view?

Below is code used just for Photo Camera and  Video Camera

-(void)photoCameraButtonAction{
    if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {

        imagePicker = [[UIImagePickerController alloc] init];
        imagePicker.delegate = self;
        imagePicker.sourceType = UIImagePickerControllerSourceTypeCamera;

        [self presentViewController:imagePicker animated:YES completion:nil];
    }
}

-(void)videoCameraButtonAction{

    if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {

        imagePicker = [[UIImagePickerController alloc] init];
        imagePicker.delegate = self;
        imagePicker.sourceType = UIImagePickerControllerSourceTypeCamera;

        NSArray *mediaTypes = [UIImagePickerController availableMediaTypesForSourceType:UIImagePickerControllerSourceTypeCamera];
        NSArray *videoMediaTypesOnly = [mediaTypes filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:@"(SELF contains %@)", @"movie"]];

        imagePicker.mediaTypes = videoMediaTypesOnly;
        imagePicker.videoQuality = UIImagePickerControllerQualityTypeMedium;
        imagePicker.videoMaximumDuration = 180;

        [self presentViewController:imagePicker animated:YES completion:nil];
    }
}

Thank you!

Body:
You can do it like that

        let picker = UIImagePickerController()
        picker.delegate = self
        picker.sourceType = .camera
        picker.mediaTypes = [kUTTypeMovie as String,kUTTypeImage as String]
        self.present(picker, animated: true, completion: nil)


问:
Almost identical recursive functions
I have a function called myFunction1 whose definition is the following:

```<code>function myFunction1()
{
    if condition1 then
        doSomething1();
        myFunction1();
    else if condition2 then
        doSomething2();
        myFunction1();
    else if condition3 then
        doSomething3();
        myFunction1();
    else throw Exception;
}
</code>```

Now I want to write a second function myFunction2 which is almost identical to myFunction1 except for a single case, i.e.,

```<code>function myFunction2()
{
    if condition1 then
        doSomething4();
        myFunction2();
    else if condition2 then
        doSomething2();
        myFunction2();
    else if condition3 then
        doSomething3();
        myFunction2();
    else throw Exception;
}
</code>```

Note that it is only the first if which differs from myFuction1. How could I write myFuction2 so as to avoid duplicating code?

答:
If it's a functional language then refactoring this is easy. Just take out the difference and pass it in as an argument:

```<code>function myGenericFunction1(theThingToDo)
{
    if condition1 then
        theThingToDo();
        myFunction1();
    else if condition2 then
        doSomething2();
        myFunction1();
    else if condition3 then
        doSomething3();
        myFunction1();
    else throw Exception;
}
</code>```

Now you can either use it directly:

```<code>myGenericFunction1(doSomething1);
myGenericFunction1(doSomething4);
</code>```

Or use it to create your two functions:

```<code>function myFunction1 () {
    myGenericFunction1(doSomething1);
}

function myFunction2 () {
    myGenericFunction1(doSomething4);
}

myFunction1();
myFunction2();
</code>```

Title: Almost identical recursive functions

Body:
I have a function called myFunction1 whose definition is the following:

function myFunction1()
{
    if condition1 then
        doSomething1();
        myFunction1();
    else if condition2 then
        doSomething2();
        myFunction1();
    else if condition3 then
        doSomething3();
        myFunction1();
    else throw Exception;
}

Now I want to write a second function myFunction2 which is almost identical to myFunction1 except for a single case, i.e.,

function myFunction2()
{
    if condition1 then
        doSomething4();
        myFunction2();
    else if condition2 then
        doSomething2();
        myFunction2();
    else if condition3 then
        doSomething3();
        myFunction2();
    else throw Exception;
}

Note that it is only the first if which differs from myFuction1. How could I write myFuction2 so as to avoid duplicating code?

Body:
If it's a functional language then refactoring this is easy. Just take out the difference and pass it in as an argument:

function myGenericFunction1(theThingToDo)
{
    if condition1 then
        theThingToDo();
        myFunction1();
    else if condition2 then
        doSomething2();
        myFunction1();
    else if condition3 then
        doSomething3();
        myFunction1();
    else throw Exception;
}

Now you can either use it directly:

myGenericFunction1(doSomething1);
myGenericFunction1(doSomething4);

Or use it to create your two functions:

function myFunction1 () {
    myGenericFunction1(doSomething1);
}

function myFunction2 () {
    myGenericFunction1(doSomething4);
}

myFunction1();
myFunction2();


问:
can a aspx page have more than one aspx.cs class to inherit?
i want to know, can one aspx page have two or more code behind page?
like if i have page collge.aspx, by default it will inherit college.aspx.cs, i want to know can't it inherit more then one aspx.cs. If not then why?</p>

答:
No

C# does not support multiple inheritance.


问:
LARAVEL - Get CSRF Token to login an user using my api
I am trying to login a user using laravel and the api I made for it, I made the post code with the email and password but it returns me a token mismatch error,i guess that's because I don't pass any csrf and my doubt is how to get it.

If I understood correctly I just need to do a GET on my main domain and grab the csrf from there, from the cookies (?).

I found this, but classes are deprecated and Ii dont know how to implement with my updated code:

Found:

```<code>    CookieStore cookieStore = httpClient.getCookieStore();
List <Cookie> cookies =  cookieStore.getCookies();
for (Cookie cookie: cookies) {
    if (cookie.getName().equals("XSRF-TOKEN")) {
        CSRFTOKEN = cookie.getValue();
    }
}
</code>```

Need to implement the grab csrf part on my code:

```<code>url = new URL(AppConfig.BaseURL);
        HttpURLConnection connection = (HttpURLConnection)url.openConnection();
        connection.setRequestMethod("GET");

        // CookieStore cookieStore = connection.getCookieStore();
        // List<HttpCookie> cookies =  cookieStore.getCookies();
        // for (Cookie cookie: cookies) {
        //    if (cookie.getName().equals("XSRF-TOKEN")) {
        //        CSRFTOKEN = cookie.getValue();
        //    }
        // }
</code>```

The commented is either wrong or deprecated but can't figure out how to solve it !

答: Use Laravel Passport for authenticate your API requests https://laravel.com/docs/5.4/passport configure it for listen password_grant types and in your APP use this library https://github.com/danielsz/android-oauth2-client for make Oauth2 Api calls</p>

Body:
I am trying to login a user using laravel and the api I made for it, I made the post code with the email and password but it returns me a token mismatch error,i guess that's because I don't pass any csrf and my doubt is how to get it.

If I understood correctly I just need to do a GET on my main domain and grab the csrf from there, from the cookies (?).

I found this, but classes are deprecated and Ii dont know how to implement with my updated code:

Found:

    CookieStore cookieStore = httpClient.getCookieStore();
List <Cookie> cookies =  cookieStore.getCookies();
for (Cookie cookie: cookies) {
    if (cookie.getName().equals("XSRF-TOKEN")) {
        CSRFTOKEN = cookie.getValue();
    }
}

Need to implement the grab csrf part on my code:

url = new URL(AppConfig.BaseURL);
        HttpURLConnection connection = (HttpURLConnection)url.openConnection();
        connection.setRequestMethod("GET");

        // CookieStore cookieStore = connection.getCookieStore();
        // List<HttpCookie> cookies =  cookieStore.getCookies();
        // for (Cookie cookie: cookies) {
        //    if (cookie.getName().equals("XSRF-TOKEN")) {
        //        CSRFTOKEN = cookie.getValue();
        //    }
        // }

The commented is either wrong or deprecated but can't figure out how to solve it !


问:
JpaRepository findAll() returns empty result
JpaRepository findAll() method returns empty result. I am trying to implement rest service by using Spring-boot, h2 database and jpa.

Here is my schema.sql

```<code>CREATE TABLE IF NOT EXISTS `City` (
  `city_id` bigint(20) NOT NULL auto_increment,
  `city_name` varchar(200) NOT NULL,
PRIMARY KEY (`city_id`));
</code>```

My data.sql file includes :

```<code>INSERT INTO City (city_id,city_name) VALUES(1,'EDE');
INSERT INTO City (city_id,city_name) VALUES(2,'DRUTEN');
INSERT INTO City (city_id,city_name) VALUES(3,'DELFT');
</code>```

The City entity :

```<code>import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;

@Entity
@Table(name = "City")
public class City {

  @Id
  @GeneratedValue
  @Column(name = "city_id")
  private Long cityId;

  @Column(name = "city_name")
  private String cityName;

  public Long getCityId() {
    return cityId;
  }

  public void setCityId(Long cityId) {
    this.cityId = cityId;
  }

  public String getCityName() {
    return cityName;
  }

  public void setCityName(String cityName) {
    this.cityName = cityName;
  }

}
</code>```

The JpaRepository interface:

```<code>import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
@Repository
public interface CityRepository extends JpaRepository<City, Long> {

    @Override
    List<City> findAll();
}
</code>```

And here is my Contoller class

```<code>@RestController
@RequestMapping("/city")
public class CityController {
    @Autowired
    private CityRepository cityRepository;

    @RequestMapping(method = RequestMethod.GET, value = "/all")
    public List<City> getAllCityList(){
        return cityRepository.findAll();
    }
}
</code>```

What am I doing wrong here? The reference documentation : Spring doc

答:
You have a schema.sql and data.sql which are both executed after the DataSource has been configured and is ready. Next the EntityManagerFactory is created and by default (See the reference guide) this will create-drop the database for embedded types (like H2).

You can override this behavior by changing the spring.jpa.hibernate.ddl-auto property to anything else then create or create-drop.

Another solution is to rename your data.sql to import.sql which will be executed after Hibernate created the schema for you. You can now obviously also remove the schema.sql as Hibernate will create the schema.

If this is for learning purposes you should be fine, if you want to use this in a live production system I suggest instead of using this to use something like Flyway to manage your schema.

Body:
JpaRepository findAll() method returns empty result. I am trying to implement rest service by using Spring-boot, h2 database and jpa.

Here is my schema.sql

CREATE TABLE IF NOT EXISTS `City` (
  `city_id` bigint(20) NOT NULL auto_increment,
  `city_name` varchar(200) NOT NULL,
PRIMARY KEY (`city_id`));

My data.sql file includes :

INSERT INTO City (city_id,city_name) VALUES(1,'EDE');
INSERT INTO City (city_id,city_name) VALUES(2,'DRUTEN');
INSERT INTO City (city_id,city_name) VALUES(3,'DELFT');

The City entity :

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;

@Entity
@Table(name = "City")
public class City {

  @Id
  @GeneratedValue
  @Column(name = "city_id")
  private Long cityId;

  @Column(name = "city_name")
  private String cityName;

  public Long getCityId() {
    return cityId;
  }

  public void setCityId(Long cityId) {
    this.cityId = cityId;
  }

  public String getCityName() {
    return cityName;
  }

  public void setCityName(String cityName) {
    this.cityName = cityName;
  }

}

The JpaRepository interface:

import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
@Repository
public interface CityRepository extends JpaRepository<City, Long> {

    @Override
    List<City> findAll();
}

And here is my Contoller class

@RestController
@RequestMapping("/city")
public class CityController {
    @Autowired
    private CityRepository cityRepository;

    @RequestMapping(method = RequestMethod.GET, value = "/all")
    public List<City> getAllCityList(){
        return cityRepository.findAll();
    }
}

What am I doing wrong here? The reference documentation : Spring doc


问:
Bootstrap popover with form
I'm trying to build a bootstrap popover with a form in it. The (maybe) special case is the onclick event, which caused problems since I was not able to escape single quotes in it. I tried it with several escape sequences (\' - \\' - ") with no success. Only with " the template is rendered fine but still does not work - although I see no error message. The html code (curly braces are coming from smarty):

```<code><img src="edit.gif" alt="" data-toggle="popover" date-html="true" data-content="<textarea id='{$SUPPLIER.id}ta'>{$SUPPLIER.comment}</textarea><img src='disc.gif' alt='' onclick="alert($('{$SUPPLIER.id}ta').val);">">
</code>```

So my next attempt was to place the popover content in a hidden div and get it with a function, but no popover is shown:

```<code>//document ready

$('[data-toggle="popover"]').popover({
    html : true,
    content:function() {
        if($(this).data('container')) {
            //loads data from e.g. a hidden div
            var elem = $(this).data('container');
            //alert here shows correct content
            return $(elem).html();
        } else {
            return $(this).data('content');
        }
    }
});

//html
<img src="edit.gif" alt="" title="{get text="Set Comment"}" data-toggle="popover" data-container="#ta_container{$SUPPLIER.id}">
<div id="ta_container{$SUPPLIER.id}" class="hide">
    <textarea id="ta{$SUPPLIER.id}">{$SUPPLIER.comment}</textarea><img src="disc.gif" alt="" onclick="alert($('#ta{$SUPPLIER.orderpart_id}').val);">
</div>
</code>```

答:
Here you have a snipplet with a working example using Bootstrap-Dialog plugin.

$('.supplier-link').on('click', function(){
  // Get parameter
  var supplierId = $(this).attr('data-supplier-id');
  var supplierComment = $(this).attr('data-supplier-comment');
  // Open Dialog and provide param
  BootstrapDialog.show({
      title: 'Supplier ' + supplierId,
      message: '<textarea>' + supplierComment + '</textarea>',
      data: {
          'supId': supplierId
      },
      buttons: [
        {
            label: 'Action with supplier',
            cssClass: 'btn-primary',
            action: function(dialogRef){
                alert('Do somehting with supplier id ' + dialogRef.getData('supId'));
            }
        }
      ]
  });
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap3-dialog/1.34.9/js/bootstrap-dialog.min.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap3-dialog/1.34.9/css/bootstrap-dialog.min.css" rel="stylesheet"/>

<span class="supplier-link" data-supplier-id="Your_Smarty_SupplierIdXX" data-supplier-comment="Your_Smarty_SupplierCommentXX">img of supplier XX</span>
<br>
<span class="supplier-link" data-supplier-id="Your_Smarty_SupplierIdYY" data-supplier-comment="Your_Smarty_SupplierCommentYY">img of supplier YY</span></code>```

Title: Bootstrap popover with form

Body:
I'm trying to build a bootstrap popover with a form in it. The (maybe) special case is the onclick event, which caused problems since I was not able to escape single quotes in it. I tried it with several escape sequences (\' - \\' - ") with no success. Only with " the template is rendered fine but still does not work - although I see no error message. The html code (curly braces are coming from smarty):

<img src="edit.gif" alt="" data-toggle="popover" date-html="true" data-content="<textarea id='{$SUPPLIER.id}ta'>{$SUPPLIER.comment}</textarea>">

So my next attempt was to place the popover content in a hidden div and get it with a function, but no popover is shown:

//document ready

$('[data-toggle="popover"]').popover({
    html : true,
    content:function() {
        if($(this).data('container')) {
            //loads data from e.g. a hidden div
            var elem = $(this).data('container');
            //alert here shows correct content
            return $(elem).html();
        } else {
            return $(this).data('content');
        }
    }
});

//html

    <textarea id="ta{$SUPPLIER.id}">{$SUPPLIER.comment}</textarea>

Body:
Here you have a snipplet with a working example using Bootstrap-Dialog plugin.

$('.supplier-link').on('click', function(){
  // Get parameter
  var supplierId = $(this).attr('data-supplier-id');
  var supplierComment = $(this).attr('data-supplier-comment');
  // Open Dialog and provide param
  BootstrapDialog.show({
      title: 'Supplier ' + supplierId,
      message: '<textarea>' + supplierComment + '</textarea>',
      data: {
          'supId': supplierId
      },
      buttons: [
        {
            label: 'Action with supplier',
            cssClass: 'btn-primary',
            action: function(dialogRef){
                alert('Do somehting with supplier id ' + dialogRef.getData('supId'));
            }
        }
      ]
  });
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap3-dialog/1.34.9/js/bootstrap-dialog.min.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap3-dialog/1.34.9/css/bootstrap-dialog.min.css" rel="stylesheet"/>

<span class="supplier-link" data-supplier-id="Your_Smarty_SupplierIdXX" data-supplier-comment="Your_Smarty_SupplierCommentXX">img of supplier XX</span>
<br>
<span class="supplier-link" data-supplier-id="Your_Smarty_SupplierIdYY" data-supplier-comment="Your_Smarty_SupplierCommentYY">img of supplier YY</span>


问:
mips64el-linux-android-g++: error: unrecognized command line option '-mfpu=neon'
I am trying to run a NDK and OpenCV related project. The project builds errorless. But when i run the application I get the error:

mips64el-linux-android-g++: error: unrecognized command line option '-mfpu=neon'

My Application.mk file looks like this:

```<code>APP_STL := gnustl_shared
APP_CPPFLAGS := -frtti -fexceptions

# NEON
APP_CFLAGS += -mfpu=neon
APP_ABI := armeabi-v7a
APP_PLATFORM := android-18
APP_OPTIM := debug
APP_MODULES := nVisoDemo-1.1
NDK_TOOLCHAIN_VERSION := 4.9
HAVE_LIB_CEVA := false # CUSTOM VARIABLE USED (NOT ANYMORE) IN Android.mk
</code>```

Android.mk:

```<code># Freeimage
include $(CLEAR_VARS)
LOCAL_MODULE := libfreeimage
LOCAL_ARM_NEON := true
#LOCAL_SRC_FILES := $(NVISO_LIBS_DIR)/libfreeimage-3.14.so
LOCAL_SRC_FILES := D:/Siddharth/StudioProjects/OpenCVDemo/nvsdk/src/main/jni/Framework/nviso/libs/armeabi-v7a/libfreeimage-3.14.so
include $(PREBUILT_SHARED_LIBRARY)
</code>```

I tried to remove APP_CFLAGS += -mfpu=neon from application.mk file but then it gives all the compilation errors in cpp files..

Also to mention that the above code works flawlessly in Eclipse...but the problem is coming in Android Studio only

Any help would be appreciated..Thanks in advance..

答:
Hello I solved the issue by the following way:

Actually what @LethalProgrammer said was rite. When I removed the "APP_CFLAGS += -mfpu=neon" line from Application.mk then it should have started working but when i removed the line it give all kind of errors in my cpp files.

So problem was that i was building using commandline and also i had put .so files in jnilibs folder in app so it was building twice..

Thus i removed this from app's build.gradle

  externalNativeBuild {
          ndkBuild {
              path 'D:/Siddharth/StudioProjects/OpenCVDemo/nvsdk/src/main/jni/Android.mk'
          }
      }

So at last removing the above code from build.gradle and removing -mfpu=neon from application.mk file it started working and the app run..
Thank you all...

Body:
I am trying to run a NDK and OpenCV related project. The project builds errorless. But when i run the application I get the error:

mips64el-linux-android-g++: error: unrecognized command line option '-mfpu=neon'

My Application.mk file looks like this:

APP_STL := gnustl_shared
APP_CPPFLAGS := -frtti -fexceptions

# NEON
APP_CFLAGS += -mfpu=neon
APP_ABI := armeabi-v7a
APP_PLATFORM := android-18
APP_OPTIM := debug
APP_MODULES := nVisoDemo-1.1
NDK_TOOLCHAIN_VERSION := 4.9
HAVE_LIB_CEVA := false # CUSTOM VARIABLE USED (NOT ANYMORE) IN Android.mk

Android.mk:

# Freeimage
include $(CLEAR_VARS)
LOCAL_MODULE := libfreeimage
LOCAL_ARM_NEON := true
#LOCAL_SRC_FILES := $(NVISO_LIBS_DIR)/libfreeimage-3.14.so
LOCAL_SRC_FILES := D:/Siddharth/StudioProjects/OpenCVDemo/nvsdk/src/main/jni/Framework/nviso/libs/armeabi-v7a/libfreeimage-3.14.so
include $(PREBUILT_SHARED_LIBRARY)

I tried to remove APP_CFLAGS += -mfpu=neon from application.mk file but then it gives all the compilation errors in cpp files..

Also to mention that the above code works flawlessly in Eclipse...but the problem is coming in Android Studio only

Any help would be appreciated..Thanks in advance..