问:
Splash Screen image background in LinearLayout not fit
I used an image as a background of LinearLayout in splash screen activity but it show not fit for the screen. I don't know how to use attribute for it to stretching it.</p>

```<code><?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/activity_splash"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.myproject.SplashActivity"
    android:orientation="horizontal"
    android:background="@drawable/my_image_background">

</LinearLayout>
</code>```

答:
Try following if scaleType="fitxy" doesn't work with imageview.

android:fitSystemWindows="true"

```<code><?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
 xmlns:tools="http://schemas.android.com/tools"
 android:id="@+id/activity_splash"
 android:layout_width="match_parent"
 android:layout_height="match_parent"
 tools:context="com.myproject.SplashActivity"
 android:orientation="horizontal"
 android:background="@drawable/my_image_background"
 android:fitSystemWindows="true">
</code>```

Body:
I used an image as a background of LinearLayout in splash screen activity but it show not fit for the screen. I don't know how to use attribute for it to stretching it.

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/activity_splash"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.myproject.SplashActivity"
    android:orientation="horizontal"
    android:background="@drawable/my_image_background">

</LinearLayout>

Body:
Try following if scaleType="fitxy" doesn't work with imageview.

android:fitSystemWindows="true"

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
 xmlns:tools="http://schemas.android.com/tools"
 android:id="@+id/activity_splash"
 android:layout_width="match_parent"
 android:layout_height="match_parent"
 tools:context="com.myproject.SplashActivity"
 android:orientation="horizontal"
 android:background="@drawable/my_image_background"
 android:fitSystemWindows="true">


来源: stackexchange

问:
Set System.AreaPath and System.IterationPath readonly in TFS
How can I set the field read-only "System.AreaPath" within a state (such as "Approved") when I have a certain value in another field ??? I have already set the conditions of "WHEN" but then "System.AreaPath" field I will always remain impossible to set read-only. Thanks Gabriele</p>

答:
The READONLY rule couldn't be used on system fields except System.State and System.Reason. In this MSDN document, it says:

System fields are fields which have System.Name reference names, for
  example System. Title and System.State. TFS restricts customization of
  these fields.

The System.AreaPath and System.IterationPath are both system fields.

So the READONLY couldn't be used on those 2 field. If you do want them to be readonly, you could set the readonly property to True of System.AreaPath's control.

```<code><Control FieldName="System.AreaPath" ReadOnly="True" Type="WorkItemClassificationControl" Label="&Area" LabelPosition="Left"  />
</code>```

ContentLicense: CC BY-SA 3.0

Body:
The READONLY rule couldn't be used on system fields except System.State and System.Reason. In this MSDN document, it says:

System fields are fields which have System.Name reference names, for
  example System. Title and System.State. TFS restricts customization of
  these fields.

The System.AreaPath and System.IterationPath are both system fields.

So the READONLY couldn't be used on those 2 field. If you do want them to be readonly, you could set the readonly property to True of System.AreaPath's control.

<Control FieldName="System.AreaPath" ReadOnly="True" Type="WorkItemClassificationControl" Label="&amp;Area" LabelPosition="Left"  />


问:
C++: Dynamically loading classes from dlls
For my current project I want to be able to load some classes from a dll (which is not always the same, and may not even exist when my app is compiled). There may also be several alternative dll's for a given class (eg an implementation for Direct3D9 and one for OpenGL), but only one of the dlls will be loaded/used at any one time.

I have a set of base classes that define the interface plus some basic methods/members (ie the ones for refrence counting) of the classes I want to load, which the dll projects then derive from when creating there classes.

```<code>//in namespace base
class Sprite : public RefCounted//void AddRef(), void Release() and unsigned refCnt
{
public:
    virtual base::Texture *GetTexture()=0;
    virtual unsigned GetWidth()=0;
    virtual unsigned GetHeight()=0;
    virtual float GetCentreX()=0;
    virtual float GetCentreY()=0;
    virtual void SetCentre(float x, float y)=0;

    virtual void Draw(float x, float y)=0;
    virtual void Draw(float x, float y, float angle)=0;
    virtual void Draw(float x, float y, float scaleX, flota scaleY)=0;
    virtual void Draw(float x, float y, float scaleX, flota scaleY, float angle)=0;
};
</code>```

The thing is I'm not sure how to do it all so that the executable and other dlls can load and use these classes since ive only ever used dlls where there was only one dll and I could have the Visual Studio linker sort it all out using the .lib file I get when compileing dll's.

I dont mind using factory methods for instancing the classes, many of them do already by design (Ie a sprite class is created by the main Graphics class, eg Graphics->CreateSpriteFromTexture(base::Texture*)

EDIT:
When I needed to write some c++ dlls for use in python I used a library called pyCxx. The resulting dll basicly only exported one method, which created an instance of the "Module" class, which could then contain factory methods to create other classes etc.

The resulting dll could be imported in python just with "import [dllname]".

```<code>//dll compiled as cpputill.pyd
extern "C" void initcpputill()//only exported method
{
    static CppUtill* cpputill = new CppUtill;
}

class CppUtill : public Py::ExtensionModule<CppUtill>
{
public:
    CppUtill()
    : Py::ExtensionModule<CppUtill>("cpputill")
    {
        ExampleClass::init_type();

        add_varargs_method("ExampleClass",&CppUtill::ExampleClassFactory, "ExampleClass(), create instance of ExampleClass");
        add_varargs_method("HelloWorld",  &CppUtill::HelloWorld,  "HelloWorld(), print Hello World to console");

        initialize("C Plus Plus module");
    }
...
class ExampleClass
...
    static void init_type()
    {
        behaviors().name("ExampleClass");
        behaviors().doc ("example class");
        behaviors().supportGetattr();
        add_varargs_method("Random", &ExampleClass::Random, "Random(), get float in range 0<=x<1");
    }
</code>```

How exactly does that work, and could I use it in a purely c++ enviroment to solve my problem here?

答:
[Edit: whilst I was composing all this, Paulius Maruška edited his comment to say basically the same. So apologies for any duplication. Though I suppose you've now got one for spare :)]

Off the top of my head, and assuming Visual C++...

You need to use LoadLibrary to load a DLL in dynamically, then use GetProcAddress to retrieve from it the address of a function that will create the actual derived class that the DLL code implements. How you decide to do this precisely is up to you (the DLLs need finding, the way the expose their functionality needs specifying, etc.) so for now let's assume that plugins only provides new Sprite implementations.

To do this, decide on the signature of the function in the DLL that the main program will call to create one of these new sprites. This one looks suitable:

```<code>typedef Sprite *(*CreateSpriteFn)();
</code>```

Then, from the main program, you'll have to load a DLL (again, how you find this DLL is up to you) and get the sprite creation function from it. I've decided that the sprite creation function will be called "CreateSprite":

```<code>HMODULE hDLL=LoadLibrary(pDLLName);
CreateSpriteFn pfnCreateSprite=CreateSpriteFn(GetProcAddress(hDLL,"CreateSprite"));
</code>```

Then to actually create one of these, just call the function:

```<code>Sprite *pSprite=(*pfnCreateSprite)();
</code>```

Once you are done with the DLL and there are no objects left that were created by it, you then use FreeLibrary to get rid of it:

```<code>FreeLibrary(hDLL);
</code>```

To create a DLL that sports this interface, write the code for the derived class and so on then somewhere in the DLL code provide the CreateSprite function that the calling program needs, using the appropriate signature:

```<code>__declspec(dllexport)
extern "C"
Sprite *CreateSprite()
{
    return new MyNewSprite;
}
</code>```

The dllexport thing means that you can use GetProcAddress to pick this function up by name, and the extern "C" ensures that the name is unmangled and doesn't end up as "CreateSprite@4" or something like.

Two other notes:

GetProcAddress returns 0 if it couldn't find the function, so you can use this to scan through a list of DLLs (e.g., returned from FindFirstFile and friends) looking for DLLs that support the interface, and/or try to find multiple entry points and support multiple types per plugin.

if the main program is going to delete the sprite using the delete operator, this requires that both DLL and main program are built using the same runtime library, so that the main program's delete and the DLL's new are both using the same heap. You can work around this to some extent by having the DLL provide a DeleteSprite function, that deletes the sprite using the DLL's runtime library rather than the main program's, but you still have to take care about the rest of your program, so you may just want to force DLL writers to use the same runtime library as your program. (I wouldn't say you'd be in good company by doing this, but it's not uncommon. 3D Studio MAX requires this, for example.)

OwnerDisplayName: Fire Lancer

ContentLicense: CC BY-SA 2.5

Body:
For my current project I want to be able to load some classes from a dll (which is not always the same, and may not even exist when my app is compiled). There may also be several alternative dll's for a given class (eg an implementation for Direct3D9 and one for OpenGL), but only one of the dlls will be loaded/used at any one time.

I have a set of base classes that define the interface plus some basic methods/members (ie the ones for refrence counting) of the classes I want to load, which the dll projects then derive from when creating there classes.

//in namespace base
class Sprite : public RefCounted//void AddRef(), void Release() and unsigned refCnt
{
public:
    virtual base::Texture *GetTexture()=0;
    virtual unsigned GetWidth()=0;
    virtual unsigned GetHeight()=0;
    virtual float GetCentreX()=0;
    virtual float GetCentreY()=0;
    virtual void SetCentre(float x, float y)=0;

    virtual void Draw(float x, float y)=0;
    virtual void Draw(float x, float y, float angle)=0;
    virtual void Draw(float x, float y, float scaleX, flota scaleY)=0;
    virtual void Draw(float x, float y, float scaleX, flota scaleY, float angle)=0;
};

The thing is I'm not sure how to do it all so that the executable and other dlls can load and use these classes since ive only ever used dlls where there was only one dll and I could have the Visual Studio linker sort it all out using the .lib file I get when compileing dll's.

I dont mind using factory methods for instancing the classes, many of them do already by design (Ie a sprite class is created by the main Graphics class, eg Graphics->CreateSpriteFromTexture(base::Texture*)

EDIT:
When I needed to write some c++ dlls for use in python I used a library called pyCxx. The resulting dll basicly only exported one method, which created an instance of the "Module" class, which could then contain factory methods to create other classes etc.

The resulting dll could be imported in python just with "import [dllname]".

//dll compiled as cpputill.pyd
extern "C" void initcpputill()//only exported method
{
    static CppUtill* cpputill = new CppUtill;
}

class CppUtill : public Py::ExtensionModule<CppUtill>
{
public:
    CppUtill()
    : Py::ExtensionModule<CppUtill>("cpputill")
    {
        ExampleClass::init_type();

        add_varargs_method("ExampleClass",&CppUtill::ExampleClassFactory, "ExampleClass(), create instance of ExampleClass");
        add_varargs_method("HelloWorld",  &CppUtill::HelloWorld,  "HelloWorld(), print Hello World to console");

        initialize("C Plus Plus module");
    }
...
class ExampleClass
...
    static void init_type()
    {
        behaviors().name("ExampleClass");
        behaviors().doc ("example class");
        behaviors().supportGetattr();
        add_varargs_method("Random", &ExampleClass::Random, "Random(), get float in range 0<=x<1");
    }

How exactly does that work, and could I use it in a purely c++ enviroment to solve my problem here?

LastEditorDisplayName: Fire Lancer

Body:
[Edit: whilst I was composing all this, Paulius Maruška edited his comment to say basically the same. So apologies for any duplication. Though I suppose you've now got one for spare :)]

Off the top of my head, and assuming Visual C++...

You need to use LoadLibrary to load a DLL in dynamically, then use GetProcAddress to retrieve from it the address of a function that will create the actual derived class that the DLL code implements. How you decide to do this precisely is up to you (the DLLs need finding, the way the expose their functionality needs specifying, etc.) so for now let's assume that plugins only provides new Sprite implementations.

To do this, decide on the signature of the function in the DLL that the main program will call to create one of these new sprites. This one looks suitable:

typedef Sprite *(*CreateSpriteFn)();

Then, from the main program, you'll have to load a DLL (again, how you find this DLL is up to you) and get the sprite creation function from it. I've decided that the sprite creation function will be called "CreateSprite":

HMODULE hDLL=LoadLibrary(pDLLName);
CreateSpriteFn pfnCreateSprite=CreateSpriteFn(GetProcAddress(hDLL,"CreateSprite"));

Then to actually create one of these, just call the function:

Sprite *pSprite=(*pfnCreateSprite)();

Once you are done with the DLL and there are no objects left that were created by it, you then use FreeLibrary to get rid of it:

FreeLibrary(hDLL);

To create a DLL that sports this interface, write the code for the derived class and so on then somewhere in the DLL code provide the CreateSprite function that the calling program needs, using the appropriate signature:

__declspec(dllexport)
extern "C"
Sprite *CreateSprite()
{
    return new MyNewSprite;
}

The dllexport thing means that you can use GetProcAddress to pick this function up by name, and the extern "C" ensures that the name is unmangled and doesn't end up as "CreateSprite@4" or something like.

Two other notes:

GetProcAddress returns 0 if it couldn't find the function, so you can use this to scan through a list of DLLs (e.g., returned from FindFirstFile and friends) looking for DLLs that support the interface, and/or try to find multiple entry points and support multiple types per plugin.

if the main program is going to delete the sprite using the delete operator, this requires that both DLL and main program are built using the same runtime library, so that the main program's delete and the DLL's new are both using the same heap. You can work around this to some extent by having the DLL provide a DeleteSprite function, that deletes the sprite using the DLL's runtime library rather than the main program's, but you still have to take care about the rest of your program, so you may just want to force DLL writers to use the same runtime library as your program. (I wouldn't say you'd be in good company by doing this, but it's not uncommon. 3D Studio MAX requires this, for example.)

OwnerDisplayName: please delete me

LastEditorDisplayName: please delete me


问:
bind dropdown with XML file
I have this XML file:

```<code><questions>
  <question id="title">
    <option>
      <text>Mr</text>
      <value>Mr</value>
    </option>
    <option>
      <text>Ms</text>
      <value>Ms</value>
    </option>
  </question>
  <question id="organisation">
    <option>
      <text>org1</text>
      <value>org1</value>
    </option>
    <option>
      <text>org2</text>
      <value>org2</value>
    </option>
  </question>
</questions>
</code>```

How do I bind each question to a specific drop-down in c#?

Thanks

答:
You can use XDocument

```<code>string xml = ""; /* your xml */
XDocument xDocument = XDocument.Parse(xml);
foreach(XElement questionElement in xDocument.Root.Elements("question"))
{
 foreach(XElement optionElement in questionElement.Elements("option"))
 {
  string text = optionElement.Element("text").Value;
  string value = optionElement.Element("value").Value;
  /* do something with them here */
 }
}
</code>```

Using the attribute id to bind all select boxes:

```<code>string xml = ""; /* your xml */
XDocument xDocument = XDocument.Parse(xml);
foreach(XElement questionElement in xDocument.Root.Elements("question"))
{
 string id = questionElement.Attribute("id").Value;
 foreach(XElement optionElement in questionElement.Elements("option"))
 {
   string text = optionElement.Element("text").Value;
   string value = optionElement.Element("value").Value;
   /* bind selectbox options here, using id,text,value */
 }
}
</code>```

Using id to bind one select box:

```<code>string id = "title";
string xml = ""; /* your xml */
XDocument xDocument = XDocument.Parse(xml);
XElement questionElement = xDocument.Root.Elements("question").SingleOrDefault(e => e.Attribute("id").Value == "title");
if (questionElement != null)
{
 foreach(XElement optionElement in questionElement.Elements("option"))
 {
  string text = optionElement.Element("text").Value;
  string value = optionElement.Element("value").Value;
  /* bind selectbox options here, using id,text,value */
 }
}
</code>```

Title: bind dropdown with XML file

Body:
I have this XML file:

<questions>
  <question id="title">
    <option>
      <text>Mr</text>
      <value>Mr</value>
    </option>
    <option>
      <text>Ms</text>
      <value>Ms</value>
    </option>
  </question>
  <question id="organisation">
    <option>
      <text>org1</text>
      <value>org1</value>
    </option>
    <option>
      <text>org2</text>
      <value>org2</value>
    </option>
  </question>
</questions>

How do I bind each question to a specific drop-down in c#?

Thanks

Body:
You can use XDocument

string xml = ""; /* your xml */
XDocument xDocument = XDocument.Parse(xml);
foreach(XElement questionElement in xDocument.Root.Elements("question"))
{
 foreach(XElement optionElement in questionElement.Elements("option"))
 {
  string text = optionElement.Element("text").Value;
  string value = optionElement.Element("value").Value;
  /* do something with them here */
 }
}

Using the attribute id to bind all select boxes:

string xml = ""; /* your xml */
XDocument xDocument = XDocument.Parse(xml);
foreach(XElement questionElement in xDocument.Root.Elements("question"))
{
 string id = questionElement.Attribute("id").Value;
 foreach(XElement optionElement in questionElement.Elements("option"))
 {
   string text = optionElement.Element("text").Value;
   string value = optionElement.Element("value").Value;
   /* bind selectbox options here, using id,text,value */
 }
}

Using id to bind one select box:

string id = "title";
string xml = ""; /* your xml */
XDocument xDocument = XDocument.Parse(xml);
XElement questionElement = xDocument.Root.Elements("question").SingleOrDefault(e => e.Attribute("id").Value == "title");
if (questionElement != null)
{
 foreach(XElement optionElement in questionElement.Elements("option"))
 {
  string text = optionElement.Element("text").Value;
  string value = optionElement.Element("value").Value;
  /* bind selectbox options here, using id,text,value */
 }
}


问:
How do I make an alternative required field in MVC 4 application?
I have a Model which have both phone number and email in MVC 4. It's something like registration. So user can provide either email or cellphone number or both of them. However I can't make a alternative required field of them.
My Model is like

```<code>public class RegisterModel
    {
        [Required]
        [Display(Name = "User name")]
        [UsernameValidator(ErrorMessage = "Only Letters and numbers")]
        [System.Web.Mvc.Remote("IsUserExitst", "Account", HttpMethod = "POST", ErrorMessage = "This user name already exists. Try a new one.")]
        public string UserName { get; set; }

        [Required]
        [StringLength(100, ErrorMessage = "The {0} must be at least {2} characters long.", MinimumLength = 6)]
        [DataType(DataType.Password)]
        [Display(Name = "Password")]
        public string Password { get; set; }

        [DataType(DataType.Password)]
        [Display(Name = "Confirm password")]
        [System.ComponentModel.DataAnnotations.Compare("Password", ErrorMessage = "The password and confirmation password do not match.")]
        public string ConfirmPassword { get; set; }

        [Required]
        [MaxLength(50)]
        [EmailOrPhoneValidator(ErrorMessage = "Invalid Phone number")]
        [Display(Name = "Phone number")]
        [System.Web.Mvc.Remote("IsMobOrEmailExists", "Account", HttpMethod = "POST", ErrorMessage = "This Phone number or Email already exists. Try a new one.")]
        public string MobileNo { get; set; }

        [Required]
        [MaxLength(50)]
        [EmailAddress(ErrorMessage = "Invalid Email address")]
        [Display(Name = "Email")]
        [System.Web.Mvc.Remote("IsEmailExists", "Account", HttpMethod = "POST", ErrorMessage = "This Email already exists. Try a new one.")]
        public string Email { get; set; }
    }
</code>```

Here I want to use Email and PhoneNo alternatively. I want to write a class which works as Custom required field. I have gone through this Questions,

Question Here the answer provided a solution combined with javascript. But I won't use it. I will write down the class file and implement my logics here.

RequiredIf is seems the exact suggestion of my question, but I so tired to try that solution. I am not capable to understand how to import the .dll in my project. and it's developed in Mvc 3

Another solution, but here they have combined the alternative properties in a class. So how do I do as my properties are completely separate. So what to do.

答:
I would go with solution 2 and create a RequiredIf validation attribute. No need to import any DLLs since you can just create the class yourself. Here is an example of what the attribute could look like. It's from a RequiredIfTrue attribute I use in my own code and I exchanged the validation logic to look for empty values

```<code>public class RequiredIfEmpty : ValidationAttribute
{
    private string _fieldName;

    public RequiredIfEmpty(string fieldName)
    {
        _fieldName = fieldName;
    }

    protected override ValidationResult IsValid(object value, ValidationContext validationContext)
    {
        var property = validationContext.ObjectType.GetProperty(_fieldName);
        if (property == null)
        {
            throw new ArgumentException("No property with the name " + _fieldName + " found.");
        }

        string fieldValue = (string)property.GetValue(validationContext.ObjectInstance, null);
        if (String.IsNullOrWhiteSpace(fieldValue))
        {
            return (value != null && !String.IsNullOrWhiteSpace((string)value) ? ValidationResult.Success : new ValidationResult(ErrorMessage));
        }
        else
        {
            return ValidationResult.Success;
        }
    }
}
</code>```

In your ViewModel you can use the attribute like any other attribute but you have to specify the name of the alternative property

```<code>[RequiredIfEmpty("Email", ErrorMessage = "Phone number invalid")]
[MaxLength(50)]
[Display(Name = "Phone number")]
[System.Web.Mvc.Remote("IsMobOrEmailExists", "Account", HttpMethod = "POST", ErrorMessage = "This Phone number or Email already exists. Try a new one.")]
public string MobileNo { get; set; }
</code>```

Body:
I have a Model which have both phone number and email in MVC 4. It's something like registration. So user can provide either email or cellphone number or both of them. However I can't make a alternative required field of them.
My Model is like

public class RegisterModel
    {
        [Required]
        [Display(Name = "User name")]
        [UsernameValidator(ErrorMessage = "Only Letters and numbers")]
        [System.Web.Mvc.Remote("IsUserExitst", "Account", HttpMethod = "POST", ErrorMessage = "This user name already exists. Try a new one.")]
        public string UserName { get; set; }

        [Required]
        [StringLength(100, ErrorMessage = "The {0} must be at least {2} characters long.", MinimumLength = 6)]
        [DataType(DataType.Password)]
        [Display(Name = "Password")]
        public string Password { get; set; }

        [DataType(DataType.Password)]
        [Display(Name = "Confirm password")]
        [System.ComponentModel.DataAnnotations.Compare("Password", ErrorMessage = "The password and confirmation password do not match.")]
        public string ConfirmPassword { get; set; }

        [Required]
        [MaxLength(50)]
        [EmailOrPhoneValidator(ErrorMessage = "Invalid Phone number")]
        [Display(Name = "Phone number")]
        [System.Web.Mvc.Remote("IsMobOrEmailExists", "Account", HttpMethod = "POST", ErrorMessage = "This Phone number or Email already exists. Try a new one.")]
        public string MobileNo { get; set; }

        [Required]
        [MaxLength(50)]
        [EmailAddress(ErrorMessage = "Invalid Email address")]
        [Display(Name = "Email")]
        [System.Web.Mvc.Remote("IsEmailExists", "Account", HttpMethod = "POST", ErrorMessage = "This Email already exists. Try a new one.")]
        public string Email { get; set; }
    }

Here I want to use Email and PhoneNo alternatively. I want to write a class which works as Custom required field. I have gone through this Questions,

Question Here the answer provided a solution combined with javascript. But I won't use it. I will write down the class file and implement my logics here.

RequiredIf is seems the exact suggestion of my question, but I so tired to try that solution. I am not capable to understand how to import the .dll in my project. and it's developed in Mvc 3

Another solution, but here they have combined the alternative properties in a class. So how do I do as my properties are completely separate. So what to do.

Body:
I would go with solution 2 and create a RequiredIf validation attribute. No need to import any DLLs since you can just create the class yourself. Here is an example of what the attribute could look like. It's from a RequiredIfTrue attribute I use in my own code and I exchanged the validation logic to look for empty values

public class RequiredIfEmpty : ValidationAttribute
{
    private string _fieldName;

    public RequiredIfEmpty(string fieldName)
    {
        _fieldName = fieldName;
    }

    protected override ValidationResult IsValid(object value, ValidationContext validationContext)
    {
        var property = validationContext.ObjectType.GetProperty(_fieldName);
        if (property == null)
        {
            throw new ArgumentException("No property with the name " + _fieldName + " found.");
        }

        string fieldValue = (string)property.GetValue(validationContext.ObjectInstance, null);
        if (String.IsNullOrWhiteSpace(fieldValue))
        {
            return (value != null && !String.IsNullOrWhiteSpace((string)value) ? ValidationResult.Success : new ValidationResult(ErrorMessage));
        }
        else
        {
            return ValidationResult.Success;
        }
    }
}

In your ViewModel you can use the attribute like any other attribute but you have to specify the name of the alternative property

[RequiredIfEmpty("Email", ErrorMessage = "Phone number invalid")]
[MaxLength(50)]
[Display(Name = "Phone number")]
[System.Web.Mvc.Remote("IsMobOrEmailExists", "Account", HttpMethod = "POST", ErrorMessage = "This Phone number or Email already exists. Try a new one.")]
public string MobileNo { get; set; }


问:
How to determine type of a variable? (not the type of the object)
I'm in the immediate window in Visual Studio. There's a variable p. How can I deduce the type of the variable p?

I tried p.GetType() but that returns the type of object p. In my case, this is a very specific type (eg. sometimes ChessPlayer, sometimes TennisPlayer). I'd like to know the type of the variable, ie. the type that determines what methods are available on the variable p.

Edit: I think this is a reasonable thing to want to do. I am trying to inspect the variable p but I don't know it is! Normally in Visual Studio I just hover the mouse on the variable and it tells me its type, or I type . and the autocomplete lists its methods. However none of that works in the immediate window, all I have is this variable p I don't know what it is or what I can do with it :(

答: As an alternative to using the immediate window, if you only want to see the type of the variable, you can simply add a variable watch and check the type in the watch window.</p>


问:
What's going wrong with my code for Euler Project #1?
Can anyone tell me where it is my program is going wrong here? I just don't see it...

```<code>x_3 = []
i=0
while 3*i < 1000:
    sum_3 = 3*i
    x_3.extend([sum_3])
    i += 1

x_5 = []
j = 0
while 5*j < 1000:
    sum_5 = 5*j
    j += 1
    x_5.extend([sum_5])

answer = sum(x_5) + sum(x_3)
print(answer)
266333
</code>```

Which is not correct.

答:
I'd use the following to calculate this:

```<code>def calcEuler(x1,x2):
    return sum(num for num in xrange(1000) if not (num % x1 and num % x2))

print(calcEuler(3,5))
</code>```

You seem to be adding up all number that are between 0 and 1000 that are multiples of 3 and 5.  However, you are double recording the ones that are multiples of both, like 15, 30, etc. So, I combined the two loops.

Body:
Can anyone tell me where it is my program is going wrong here? I just don't see it...

x_3 = []
i=0
while 3*i < 1000:
    sum_3 = 3*i
    x_3.extend([sum_3])
    i += 1

x_5 = []
j = 0
while 5*j < 1000:
    sum_5 = 5*j
    j += 1
    x_5.extend([sum_5])

answer = sum(x_5) + sum(x_3)
print(answer)
266333

Which is not correct.

Body:
I'd use the following to calculate this:

def calcEuler(x1,x2):
    return sum(num for num in xrange(1000) if not (num % x1 and num % x2))

print(calcEuler(3,5))

You seem to be adding up all number that are between 0 and 1000 that are multiples of 3 and 5.  However, you are double recording the ones that are multiples of both, like 15, 30, etc. So, I combined the two loops.


问:
random noise block on user interface by using JavaFX
I am writing a JAVAFX program and there are some random blockers which happen sometimes. But I've totally no idea where it comes and how to solve this issue.

Like the picture below, there should be 2 buttons but 2 blank areas block the button(even mouse events cannot be passed) and I cannot see anything.
Some blank areas blocked GUI

Since it is randomly generated, I've no idea how to debug to find them..Can someone give me some suggetions?

Really thanks a lot!!!

Edit: Does someone know why all animations in JavaFx program become lag after specifying -Dprism.order=sw?

答: This rendering issue maybe cause by incorrectly using multi-threads. Things like too many events from remote server come in, some of handlers are processing GUI tasks outside GUI thread.</p>


问:
CsScript with Mono: How to make mono not treat warnings as errors
I use CSScriptLibrary.dll to execute C# code in my application which runs on both Windows and Linux. Problem is, right now, I need to use #pragma disable warning to disable all kinds of warnings that may arise in order to get the scripts to compile on Mono which is a very ugly hack.

```<code>// the following simple script will not execute on Mono due to a warning that a is not used.
var code = "public class Script { public object Run() { var a=1; return 2+3; }}"
// here is how the script is executed using CsScriptLibrary
try
{
    var asm = new AsmHelper(CSScript.LoadCode(code, "cs", null, true));
    // if we reach that point, the script compiled
    var obj = asm.CreateAndAlignToInterface<IScript>("*");
    // now run it:
    var result=obj.Run();
}
catch (CompilerException e)
{
    // on .net compiler exceptions are only raised when there are errors
    // on mono I get an exception here, even for warnings like unused variable
}
</code>```

I already tried to set the default compiler parameters of CSScript to instruct the mono compiler to disregard warnings. Here is what I tried (based on documentation of compiler switches of Mono compiler:

```<code>CSScript.GlobalSettings.DefaultArguments = "-warn:0 -warnaserror-";
</code>```

But I had no success and I am not even sure if this is the right way to go. Anyway, for the sake of completeness I note here that CSScript.GlobalSettings.DefaultArguments defaults to /c /sconfig /co:/warn:0 in CSScript.

Does anyone know how to get CSScript.LoadCode to disregard warnings on Mono or at least not treat them as errors?

答:
Here are two solutions (found with help of Oleg Shilo). You can either include the desired compiler option directly in the script:

```<code>//css_co -warn:0
using System;
...
</code>```

or you can substitute CSScript.LoadCode with LoadWithConfig, which allows passing compiler options directly. Something like this:

```<code>static public Assembly LoadCode(string scriptText, bool debugBuild, params string[] refAssemblies)
{
    string tempFile =  System.IO.Path.GetTempPath() + Guid.NewGuid().ToString() +".cs";
    try
    {
        using (StreamWriter sw = new StreamWriter(tempFile))
            sw.Write(scriptText);
        return LoadWithConfig(scriptFile, null, debugBuild, CSScript.GlobalSettings, "-warn:0", refAssemblies);
    }
    finally
    {
        if (!debugBuild)
        {
            //delete temp file
        }
    }
}
</code>```

It should be noted, that the second solution will bypass the built in assembly caching performed in LoadCode. It is easy enough to cache the compiled script object though.

Body:
I use CSScriptLibrary.dll to execute C# code in my application which runs on both Windows and Linux. Problem is, right now, I need to use #pragma disable warning to disable all kinds of warnings that may arise in order to get the scripts to compile on Mono which is a very ugly hack.

// the following simple script will not execute on Mono due to a warning that a is not used.
var code = "public class Script { public object Run() { var a=1; return 2+3; }}"
// here is how the script is executed using CsScriptLibrary
try
{
    var asm = new AsmHelper(CSScript.LoadCode(code, "cs", null, true));
    // if we reach that point, the script compiled
    var obj = asm.CreateAndAlignToInterface<IScript>("*");
    // now run it:
    var result=obj.Run();
}
catch (CompilerException e)
{
    // on .net compiler exceptions are only raised when there are errors
    // on mono I get an exception here, even for warnings like unused variable
}

I already tried to set the default compiler parameters of CSScript to instruct the mono compiler to disregard warnings. Here is what I tried (based on documentation of compiler switches of Mono compiler:

CSScript.GlobalSettings.DefaultArguments = "-warn:0 -warnaserror-";

But I had no success and I am not even sure if this is the right way to go. Anyway, for the sake of completeness I note here that CSScript.GlobalSettings.DefaultArguments defaults to /c /sconfig /co:/warn:0 in CSScript.

Does anyone know how to get CSScript.LoadCode to disregard warnings on Mono or at least not treat them as errors?

Body:
Here are two solutions (found with help of Oleg Shilo). You can either include the desired compiler option directly in the script:

//css_co -warn:0
using System;
...

or you can substitute CSScript.LoadCode with LoadWithConfig, which allows passing compiler options directly. Something like this:

static public Assembly LoadCode(string scriptText, bool debugBuild, params string[] refAssemblies)
{
    string tempFile =  System.IO.Path.GetTempPath() + Guid.NewGuid().ToString() +".cs";
    try
    {
        using (StreamWriter sw = new StreamWriter(tempFile))
            sw.Write(scriptText);
        return LoadWithConfig(scriptFile, null, debugBuild, CSScript.GlobalSettings, "-warn:0", refAssemblies);
    }
    finally
    {
        if (!debugBuild)
        {
            //delete temp file
        }
    }
}

It should be noted, that the second solution will bypass the built in assembly caching performed in LoadCode. It is easy enough to cache the compiled script object though.


问:
On Click Event JS Loader Wordpress
So I got a wordpress website, tailored and CSSed to work as a mobile application on apache cordova and everythign is working fine.

Since it's highly reliable on the inAppBrowser the user doesn't get to see the browser loader after clicking a tile or a button and might think that the application is not responding.

My question is, is there a way to make any click event in wordpress's home page generate a spinner or a loader without having to mess with the php files?

If not then how could this be achieved?

答:
Try click event on button id:</p>

```<code>$('#button_ID').click(function(){
  $('#loader_img').show(); // Show Loader
  $.ajax({
    Your Code ...
   success:function(result){
   $('#loader_img').hide();  //Hide Loader
   }
}
</code>```

Title: On Click Event JS Loader Wordpress

Body:
Try click event on button id:

$('#button_ID').click(function(){
  $('#loader_img').show(); // Show Loader
  $.ajax({
    Your Code ...
   success:function(result){
   $('#loader_img').hide();  //Hide Loader
   }
}


问:
I can't create login in django 1.10.1 version
I know it is basic to create login User Authentication. And I am a newbie here in using Django.

I have a problem in creating User Authentication:

Views.py

```<code>def Logins(request):
if request.method == 'POST':
    username = request.POST['username']
    password = request.POST['password']
    user = authenticate(username=username, password=password)
    if user is not None and user.is_active:
        login(request, user)
        return HttpResponseRedirect('music/login')
    return HttpResponseRedirect('music/login')
form = Userlogin
return render(request, 'music/login.html', {'Login_form': Userlogin})
</code>```

urls.py
    url(r'^login/$', views.Logins, name='login'),

It shows
    It shows MultiValueDictKeyError at /music/login/.
    "'username'"
    Request Method: POST
    Request URL:    http://127.0.0.1:8000/music/login/
    Django Version: 1.10.4
    Exception Type: MultiValueDictKeyError
    Exception Value:

    "'username'"

login.html

```<code>{% block body %}
{% if form.errors %}
<p>Something is wrong</p>
{% endif %}

<form action="" method="post">
    {% csrf_token %}
    <label for="email">Login:</label>
    <label for="password">Password:</label>
    <input type="password" name="password" value="" id="username">

    <input type="submit" value="login" />

</form>
{% endblock %}
</code>```

Thanks in advance.

答:
The MultiValueDictKeyError seems to be because request.POST['username'] does not exist.

Add a username field in your login form.

```<code><form action="" method="post">
    {% csrf_token %}
    <label for="username">Username:</label>
    <input type="text" name="username">
    <label for="email">Login:</label>
    <label for="password">Password:</label>
    <input type="password" name="password" value="" id="username">
    <input type="submit" value="login" />

</form>
</code>```

Body:
I know it is basic to create login User Authentication. And I am a newbie here in using Django.

I have a problem in creating User Authentication:

Views.py

def Logins(request):
if request.method == 'POST':
    username = request.POST['username']
    password = request.POST['password']
    user = authenticate(username=username, password=password)
    if user is not None and user.is_active:
        login(request, user)
        return HttpResponseRedirect('music/login')
    return HttpResponseRedirect('music/login')
form = Userlogin
return render(request, 'music/login.html', {'Login_form': Userlogin})

urls.py
    url(r'^login/$', views.Logins, name='login'),

It shows
    It shows MultiValueDictKeyError at /music/login/.
    "'username'"
    Request Method: POST
    Request URL:    http://127.0.0.1:8000/music/login/
    Django Version: 1.10.4
    Exception Type: MultiValueDictKeyError
    Exception Value:

    "'username'"

login.html

{% block body %}
{% if form.errors %}

Something is wrong

{% endif %}

<form action="" method="post">
    {% csrf_token %}
    Login:
    Password:
    <input type="password" name="password" value="" id="username">

    <input type="submit" value="login" />

</form>
{% endblock %}

Thanks in advance.

Body:
The MultiValueDictKeyError seems to be because request.POST['username'] does not exist.

Add a username field in your login form.

<form action="" method="post">
    {% csrf_token %}
    <label for="username">Username:</label>
    <input type="text" name="username">
    <label for="email">Login:</label>
    <label for="password">Password:</label>
    <input type="password" name="password" value="" id="username">
    <input type="submit" value="login" />

</form>


问:
How to change 1,000,000 price to 1,XXX,XXX using php or javascript?
This is my source code:

```<code>preg_replace('/[A-Z0-9]/', 'X', number_format('1000000'));
</code>```

Result: x,xxx,xxx

But, I want the result like 1,xxx,xxx, i.e., don't replace the first number.

答:
Try this.</p>

```<code>echo preg_replace('/(?!^)\S/',  'X', number_format('1000000'));
</code>```

Body:
This is my source code:

preg_replace('/[A-Z0-9]/', 'X', number_format('1000000'));

Result: x,xxx,xxx

But, I want the result like 1,xxx,xxx, i.e., don't replace the first number.

Body:
Try this.

echo preg_replace('/(?!^)\S/',  'X', number_format('1000000'));


问:
Yii2 Call api method from backend controllers
I have implemented API based on advanced template following Yii Rest API documentation. And I want to call API methods from backend controllers. Is it possible to do?

Thanks

答:
you can use postman for testing your api.
first download your version of postman then choose your method. then determine your inputs and your url. and finally press send button.
your url might be like

```<code>http://yourdomain.com/backend/web/index.php?r=yourController/yourAction
</code>```

that yourdomain.com is your domain and yourController are controller and yourAction are your action.

Body:
you can use postman for testing your api.
first download your version of postman then choose your method. then determine your inputs and your url. and finally press send button.
your url might be like

http://yourdomain.com/backend/web/index.php?r=yourController/yourAction

that yourdomain.com is your domain and yourController are controller and yourAction are your action.


问:
With function in mockery with datetime objects
I am trying to mock a method that should have a datetime object of a set value passed to it

```<code>$mock->shouldReceive('setDatetime')
            ->with($datetime)
            ->once;
</code>```

I'm fairly new to mockery but I don’t understand how 'with' is working. If $datetime is the exact object that is being passed into 'setDatetime' then it satisfies the condition perfectly. If it is a datetime object, but not exactly same object, i.e. all the values are the same, but it is a different instantiated DateTime object, then it doesn't work. The Datetime object I'm currently passing to setDatetime has been altered using DateInterval. Is there anyway i can test whether the datetime object being received has the same values even if it isn't the same object.

答:
This is possible by giving a closure to your with().

To give the closure to the with function Mockery gives you a Closure matcher

```<code>Mockery\Matcher\Closure
</code>```

This class will take a closure and use it to match the value you get.

How you would implement this is like this:

```<code>$expectedDateTime = new DateTime();
$mock->shouldReceive('setDatetime')
            ->with
               (new Closure(
                 function($datetime) use ($expectedDateTime) {
                   return $datetime->getTimestamp() === $expectedDateTime->getTimeStamp()
                 }
               )
            )->once;
</code>```

The epextedDateTime is of course the date time that it should be but for example purposes added here. You can also create that DateTime object in the closure if you dont need it outside the assertion, you won't need the use in the closure then.

And of course you can check/assert whatever you want in the closure as an example I did the easiest test of checking if the timestamps are equal.

Body:
I am trying to mock a method that should have a datetime object of a set value passed to it

$mock->shouldReceive('setDatetime')
            ->with($datetime)
            ->once;

I'm fairly new to mockery but I don’t understand how 'with' is working. If $datetime is the exact object that is being passed into 'setDatetime' then it satisfies the condition perfectly. If it is a datetime object, but not exactly same object, i.e. all the values are the same, but it is a different instantiated DateTime object, then it doesn't work. The Datetime object I'm currently passing to setDatetime has been altered using DateInterval. Is there anyway i can test whether the datetime object being received has the same values even if it isn't the same object.

Body:
This is possible by giving a closure to your with().

To give the closure to the with function Mockery gives you a Closure matcher

Mockery\Matcher\Closure

This class will take a closure and use it to match the value you get.

How you would implement this is like this:

$expectedDateTime = new DateTime();
$mock->shouldReceive('setDatetime')
            ->with
               (new Closure(
                 function($datetime) use ($expectedDateTime) {
                   return $datetime->getTimestamp() === $expectedDateTime->getTimeStamp()
                 }
               )
            )->once;

The epextedDateTime is of course the date time that it should be but for example purposes added here. You can also create that DateTime object in the closure if you dont need it outside the assertion, you won't need the use in the closure then.

And of course you can check/assert whatever you want in the closure as an example I did the easiest test of checking if the timestamps are equal.


问:
No arguments Provided! - PHP Contact form
When I hit Send Message on my contact form it takes me to a mysite.com/mail.php and give me the error No arguments Provided!

Here is my HTML

```<code><form id="myForm" method="post" action="../mail.php">

            <div class="row">
                    <div class="medium-6 columns">
                        <input type="text" name="name" value="" placeholder="Your Name">
                    </div>
                    <div class="medium-6 columns">
                        <input type="text" name="website" value="" placeholder="Website">
                    </div>
                    <div class="medium-6 columns">
                        <input type="email" name="email" value="" placeholder="Email">
                    </div>
                    <div class="medium-6 columns">
                        <input type="text" name="service" value="" placeholder="Service Needed">
                    </div>
            </div>

            <div class="row">
                <div class="columns">
                    <label for="textarea">
                        <textarea name="message" rows="8" cols="80" placeholder="Tell me about your project"></textarea>
                    </label>
                </div>
            </div>

        <div class="row">
            <div class="columns">
                <input name="Submit" type="submit" class="button" value="Send Message">
            </div>
        </div>

        </form>
</code>```

Here is the PHP

```<code><?php
if(empty($_POST['name'])        ||
   empty($_POST['email'])       ||
   empty($_POST['website'])     ||
     empty($_POST['service'])   ||
   empty($_POST['message'])   ||
   !filter_var($_POST['email'],FILTER_VALIDATE_EMAIL))
   {
    echo "No arguments Provided!";
    return false;
   }

$name = $_POST['name'];
$email_address = $_POST['email'];
$message = $_POST['message'];

// Create the email and send the message
$to = 'myemail@gmail.comm';
$email_subject = "Website Contact Form SRC:  $name";
$email_body = "You have received a new message from your website contact form.\n\n"."Here are the details:\n\nName: $name\n\nEmail: $email_address\n\nPhone: $phone\n\nMessage:\n$message";
$headers = "From: myemail@gmail.comm\n";
$headers .= "Reply-To: $email_address";
mail($to,$email_subject,$email_body,$headers);
return true;
?>
</code>```

答:
Validate the data by one, so you know, what's missing and can return that to the user:</p>

```<code><?php
    $errors = [];

    if (empty($_POST['name'])) {
        $errors[] = 'No name provided';
    }

    if (empty($_POST['email'])) {
        $errors[] = 'No email provided';
    }

    if (!filter_var($_POST['email'],FILTER_VALIDATE_EMAIL)) {
        $errors[] = 'Email format wrong';
    }

    if (empty($_POST['website'])) {
        $errors[] = 'No website provided';
    }

    if (empty($_POST['service'])) {
        $errors[] = 'No service provided';
    }

    if (empty($_POST['message'])) {
        $errors[] = 'No message provided';
    }

    if (count($errors)) {
        print_r($errors); // Or return to previous window with errors
    }
</code>```

Body:
When I hit Send Message on my contact form it takes me to a mysite.com/mail.php and give me the error No arguments Provided!

Here is my HTML

<form id="myForm" method="post" action="../mail.php">

                        <input type="text" name="name" value="" placeholder="Your Name">

                        <input type="text" name="website" value="" placeholder="Website">

                        <input type="email" name="email" value="" placeholder="Email">

                        <input type="text" name="service" value="" placeholder="Service Needed">

                        <textarea name="message" rows="8" cols="80" placeholder="Tell me about your project"></textarea>

                <input name="Submit" type="submit" class="button" value="Send Message">

        </form>

Here is the PHP

<?php
if(empty($_POST['name'])        ||
   empty($_POST['email'])       ||
   empty($_POST['website'])     ||
     empty($_POST['service'])   ||
   empty($_POST['message'])   ||
   !filter_var($_POST['email'],FILTER_VALIDATE_EMAIL))
   {
    echo "No arguments Provided!";
    return false;
   }

$name = $_POST['name'];
$email_address = $_POST['email'];
$message = $_POST['message'];

// Create the email and send the message
$to = 'myemail@gmail.comm';
$email_subject = "Website Contact Form SRC:  $name";
$email_body = "You have received a new message from your website contact form.\n\n"."Here are the details:\n\nName: $name\n\nEmail: $email_address\n\nPhone: $phone\n\nMessage:\n$message";
$headers = "From: myemail@gmail.comm\n";
$headers .= "Reply-To: $email_address";
mail($to,$email_subject,$email_body,$headers);
return true;
?>

Body:
Validate the data by one, so you know, what's missing and can return that to the user:

<?php
    $errors = [];

    if (empty($_POST['name'])) {
        $errors[] = 'No name provided';
    }

    if (empty($_POST['email'])) {
        $errors[] = 'No email provided';
    }

    if (!filter_var($_POST['email'],FILTER_VALIDATE_EMAIL)) {
        $errors[] = 'Email format wrong';
    }

    if (empty($_POST['website'])) {
        $errors[] = 'No website provided';
    }

    if (empty($_POST['service'])) {
        $errors[] = 'No service provided';
    }

    if (empty($_POST['message'])) {
        $errors[] = 'No message provided';
    }

    if (count($errors)) {
        print_r($errors); // Or return to previous window with errors
    }


问:
iOS App Crashing on iOS 4.2 but not 4.0, simulator not showing logs
Using XCode 3.2.5 I can run my application on iOS Simulator using the 4.2 SDK. However, it crashes on the following function, more specifically, the presentModalViewController call:

```<code>- (void)login {
    //check to see if they logged in correctly here
    /*UIAlertView *alert = [[UIAlertView alloc] initWithTitle:nil message:@"Login Failed!"
                                               delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil];
    [alert show];
    [alert release];*/

    [self presentModalViewController:self.accountsViewController animated:YES];
}
</code>```

However, on XCode 4 Dev Preview, I can't even access 4.2 SDK in the Simulator, so I'm forced to use 4.0 SDK. In 4.0, that function works find and as expected. I have two issues:

Why is the 4.2 SDK in the Simulator not reporting the reason it crashed in XCode 3.2.5? It used to be that when my app would crash in debugging mode in the Simulator, XCode would pop up the reason. However, it's not anymore.

Why would that simple line crash in 4.2 but not 4.0. Could it be the different XCode versions?

答: It was some sort of weird issue between XCode version. I recreated the whole add using solely XCode 3.2.5 and the same exact code now works.</p>

Body:
Using XCode 3.2.5 I can run my application on iOS Simulator using the 4.2 SDK. However, it crashes on the following function, more specifically, the presentModalViewController call:

- (void)login {
    //check to see if they logged in correctly here
    /*UIAlertView *alert = [[UIAlertView alloc] initWithTitle:nil message:@"Login Failed!"
                                               delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil];
    [alert show];
    [alert release];*/

    [self presentModalViewController:self.accountsViewController animated:YES];
}

However, on XCode 4 Dev Preview, I can't even access 4.2 SDK in the Simulator, so I'm forced to use 4.0 SDK. In 4.0, that function works find and as expected. I have two issues:

Why is the 4.2 SDK in the Simulator not reporting the reason it crashed in XCode 3.2.5? It used to be that when my app would crash in debugging mode in the Simulator, XCode would pop up the reason. However, it's not anymore.

Why would that simple line crash in 4.2 but not 4.0. Could it be the different XCode versions?


问:
how to call angularjs function which is appended in div
```<code>$scope.showtbleoption =  function(id)
{
    console.log(id);
    $("#showoption").empty();
    $("#showoption").append('<button class="btn btn-info" ng-click="editrc(id)">');
};
</code>```

how to call editrc() function in angularjs controller ?

答: You can use the ng-bind-html directive to bind the html's to the template dynamically . You will however have to compile the html using $compile by doing $compile() . Any expressions mentioned in the compiled html could call the definitions you provide in the controller .

Body:
$scope.showtbleoption =  function(id)
{
    console.log(id);
    $("#showoption").empty();
    $("#showoption").append('<button class="btn btn-info" ng-click="editrc(id)">');
};

how to call editrc() function in angularjs controller ?

Body: You can use the ng-bind-html directive to bind the html's to the template dynamically . You will however have to compile the html using $compile by doing $compile(<html>) . Any expressions mentioned in the compiled html could call the definitions you provide in the controller .


问:
WHere can I find the CSV file if I use write.csv in a R notebook on DSX
I have scored some data in a R notebook and used the write.csv method to create a CSV file of the scored data stored in a data frame. What is the best way to retrieve this file on DSX ?</p>

答:
When you write to the file system, you can work with the file on the server. For example in a Python notebook, you can use !ls to list files, or !cat <filename> to look at the content. But we currently have no easy way to transfer files from the server to your workstation. I therefore agree with Greg Filla's answer that writing to Object Storage instead of the file system is the best way to make your results downloadable.

Nevertheless, if your file is small and formatting isn't critical, you could use !cat <filename> and copy the output from the notebook into a text editor. For binary files, or when formatting is critical, I've also used !base64 <filename> in the notebook for encoding and base64 -d on the workstation for decoding a file. But it's cumbersome.


问:
Abstract Factory Design Pattern implementation in C++ using Qt Creator
I am trying to make all the creational design patterns and I'm having some trouble with the abstract factory method. I normally program in Python, however, I had heard C++ was good for really having to understand design patterns explicitly, which is proving to be right, err.

I'm basically following this guide on Tutorials Point.

My question is how would I change my current code to correctly implement the abstract factory method in C++ with a factory producer as I believe its something to do with my Factory Producer extra layer of abstraction that is causing my issues. I have included all my code.

I tried to make a simple diagram to explain better but it's not the most formal UML but is essentially what I would like to make. My main.cpp file should illustrate better the functionality I'm trying to understand how to make.

P.s. I'm just trying to improve to apply for jobs so please let me know if you have any feedback on writing better SO questions, coding style, variable naming or even C++ conventions.

Main

main.cpp - Main implementation file

Tests creating an abstract factory, abstract sword and abstract warrior.

```<code>#include "factoryproducer.h"

using namespace std;

int main(int argc, char *argv[]) {
    AbstractFactory* warriorFactory = FactoryProducer::createFactory("warriorfactory");

    Warrior* tinyWarrior = warriorFactory->createWarrior("tinywarrior");
    Warrior* normalWarrior = warriorFactory->createWarrior("normalwarrior");
    Warrior* largeWarrior = warriorFactory->createWarrior("largewarrior");
    Warrior* giantWarrior = warriorFactory->createWarrior("giantwarrior");

    cout<<tinyWarrior->getName().toStdString()<<endl;
    cout<<normalWarrior->getName().toStdString()<<endl;
    cout<<largeWarrior->getName().toStdString()<<endl;
    cout<<giantWarrior->getName().toStdString()<<endl;

    AbstractFactory* SwordFactory = FactoryProducer::createFactory("swordfactory");

    Sword* tinySword = swordFactory->createSword("tinysword");
    Sword* normalSword = swordFactory->createSword("normalsword");
    Sword* largeSword = swordFactory->createSword("largesword");
    Sword* giantSword = swordFactory->createSword("giantsword");

    cout<<tinySword->getName().toStdString()<<endl;
    cout<<normalSword->getName().toStdString()<<endl;
    cout<<largeSword->getName().toStdString()<<endl;
    cout<<giantSword->getName().toStdString()<<endl;

    return a.exec();
}
</code>```

Abstract Factory Class

abstractfactory.h - Abstract Factory header file

```<code>#ifndef ABSTRACTFACTORY_H
#define ABSTRACTFACTORY_H

#include "warrior.h"
#include "sword.h"
#include <QString>

class AbstractFactory {
public:
    // Public Methods
    ~AbstractFactory();
    virtual Warrior* createWarrior(QString warriorType) = 0;
    virtual Sword* createSword(QString swordType) = 0;
};

#endif // ABSTRACTFACTORY_H
</code>```

abstractfactory.cpp Abstract Factory implementation file

```<code>#include "abstractfactory.h"

AbstractFactory::~AbstractFactory(){}
</code>```

Factory Producer Class

factoryproducer.h - Factory Producer header file

```<code>#ifndef FACTORYPRODUCER_H
#define FACTORYPRODUCER_H

#include "abstractfactory.h"
#include "warriorfactory.h"
#include "swordfactory.h"
#include <QString>

class FactoryProducer {
public:
    // Public Methods
    static AbstractFactory* createFactory(QString factoryType);
};

#endif // FACTORYPRODUCER_H
</code>```

factoryproducer.cpp - Factory Producer implementation file

```<code>#include "factoryproducer.h"

AbstractFactory* AbstractFactory::createFactory(QString factoryType) {
    if (factoryType == nullptr) {
        return nullptr;
    }

    if (QString::compare(factoryType, "WARRIORFACTORY", Qt::CaseInsensitive) == 0) {
        return new WarriorFactory();
    }

    if (QString::compare(factoryType, "SWORDFACTORY", Qt::CaseInsensitive) == 0) {
        return new SwordFactory();
    }

    return nullptr;
}
</code>```

Abstract Warrior Class

warrior.h - Abstract Warrior header file

```<code>#ifndef WARRIOR_H
#define WARRIOR_H

#include "tinywarrior.h"
#include "normalwarrior.h"
#include "largewarrior.h"
#include "giantwarrior.h"
#include <QString>

class Warrior {
public:
    // Public Methods
    ~Warrior();
    virtual QString getName() = 0;
    virtual QString getPicture() = 0;
};

#endif // WARRIOR_H
</code>```

warrior.cpp - Abstract Warrior implementation file

```<code>#include "warrior.h"

Warrior::~Warrior(){}
</code>```

Abstract Sword Class

sword.h - Abstract Sword header file

```<code>#ifndef SWORD_H
#define SWORD_H

#include "tinysword.h"
#include "normalsword.h"
#include "largesword.h"
#include "giantsword.h"
#include <QString>

class Sword {
public:
    // Public Methods
    ~Sword();
    virtual QString getName() = 0;
    virtual QString getPicture() = 0;
};

#endif // SWORD_H
</code>```

sword.cpp - Abstract Sword implementation file

```<code>#include "sword.h"

Sword::~Sword(){}
</code>```

Concrete TinySword Class

tinysword.h - Concrete Tiny Sword header file

```<code>#ifndef TINYSWORD_H
#define TINYSWORD_H

#include "sword.h"

class TinySword : public Sword {
public:
    // Public Methods
    TinySword();
    ~TinySword();
    QString getName();
    QString getPicture();
private:
    // Private Member Variables
    QString m_name;
    QString m_picture;
};

#endif // TINYSWORD_H
</code>```

tinysword.cpp - Concrete Tiny Sword implementation file

```<code>#ifndef ABSTRACTFACTORY_H
#define ABSTRACTFACTORY_H

#include "warrior.h"
#include "sword.h"
#include <QString>

class AbstractFactory {
public:
    // Public Methods
    ~AbstractFactory();
    virtual Warrior* createWarrior(QString warriorType) = 0;
    virtual Sword* createSword(QString swordType) = 0;
};

#endif // ABSTRACTFACTORY_H
</code>```0

Concrete Normal Sword

normalsword.h - Concrete Normal Sword header file

```<code>#ifndef ABSTRACTFACTORY_H
#define ABSTRACTFACTORY_H

#include "warrior.h"
#include "sword.h"
#include <QString>

class AbstractFactory {
public:
    // Public Methods
    ~AbstractFactory();
    virtual Warrior* createWarrior(QString warriorType) = 0;
    virtual Sword* createSword(QString swordType) = 0;
};

#endif // ABSTRACTFACTORY_H
</code>```1

normalsword.cpp - Concrete Normal Sword implementation file

```<code>#ifndef ABSTRACTFACTORY_H
#define ABSTRACTFACTORY_H

#include "warrior.h"
#include "sword.h"
#include <QString>

class AbstractFactory {
public:
    // Public Methods
    ~AbstractFactory();
    virtual Warrior* createWarrior(QString warriorType) = 0;
    virtual Sword* createSword(QString swordType) = 0;
};

#endif // ABSTRACTFACTORY_H
</code>```2

Concrete Large Sword Class

largesword.h - Concrete Large Sword header file

```<code>#ifndef ABSTRACTFACTORY_H
#define ABSTRACTFACTORY_H

#include "warrior.h"
#include "sword.h"
#include <QString>

class AbstractFactory {
public:
    // Public Methods
    ~AbstractFactory();
    virtual Warrior* createWarrior(QString warriorType) = 0;
    virtual Sword* createSword(QString swordType) = 0;
};

#endif // ABSTRACTFACTORY_H
</code>```3

largesword.cpp - Concrete Large Sword implementation file

```<code>#ifndef ABSTRACTFACTORY_H
#define ABSTRACTFACTORY_H

#include "warrior.h"
#include "sword.h"
#include <QString>

class AbstractFactory {
public:
    // Public Methods
    ~AbstractFactory();
    virtual Warrior* createWarrior(QString warriorType) = 0;
    virtual Sword* createSword(QString swordType) = 0;
};

#endif // ABSTRACTFACTORY_H
</code>```4

Concrete Giant Sword Class

giantsword.h - Concrete Giant Sword header file

```<code>#ifndef ABSTRACTFACTORY_H
#define ABSTRACTFACTORY_H

#include "warrior.h"
#include "sword.h"
#include <QString>

class AbstractFactory {
public:
    // Public Methods
    ~AbstractFactory();
    virtual Warrior* createWarrior(QString warriorType) = 0;
    virtual Sword* createSword(QString swordType) = 0;
};

#endif // ABSTRACTFACTORY_H
</code>```5

giantsword.cpp - Concrete Giant Sword implementation file

```<code>#ifndef ABSTRACTFACTORY_H
#define ABSTRACTFACTORY_H

#include "warrior.h"
#include "sword.h"
#include <QString>

class AbstractFactory {
public:
    // Public Methods
    ~AbstractFactory();
    virtual Warrior* createWarrior(QString warriorType) = 0;
    virtual Sword* createSword(QString swordType) = 0;
};

#endif // ABSTRACTFACTORY_H
</code>```6

Concrete Tiny Warrior Class

tinywarrior.h - Concrete Tiny Warrior header file

```<code>#ifndef ABSTRACTFACTORY_H
#define ABSTRACTFACTORY_H

#include "warrior.h"
#include "sword.h"
#include <QString>

class AbstractFactory {
public:
    // Public Methods
    ~AbstractFactory();
    virtual Warrior* createWarrior(QString warriorType) = 0;
    virtual Sword* createSword(QString swordType) = 0;
};

#endif // ABSTRACTFACTORY_H
</code>```7

tinywarrior.cpp - Concrete Tiny Warrior implementation file

```<code>#ifndef ABSTRACTFACTORY_H
#define ABSTRACTFACTORY_H

#include "warrior.h"
#include "sword.h"
#include <QString>

class AbstractFactory {
public:
    // Public Methods
    ~AbstractFactory();
    virtual Warrior* createWarrior(QString warriorType) = 0;
    virtual Sword* createSword(QString swordType) = 0;
};

#endif // ABSTRACTFACTORY_H
</code>```8

Concrete Normal Warrior Class

normalwarrior.h - Concrete Normal Warrior header file

```<code>#ifndef ABSTRACTFACTORY_H
#define ABSTRACTFACTORY_H

#include "warrior.h"
#include "sword.h"
#include <QString>

class AbstractFactory {
public:
    // Public Methods
    ~AbstractFactory();
    virtual Warrior* createWarrior(QString warriorType) = 0;
    virtual Sword* createSword(QString swordType) = 0;
};

#endif // ABSTRACTFACTORY_H
</code>```9

normalwarrior.cpp Concrete Normal Warrior implementation

```<code>#include "abstractfactory.h"

AbstractFactory::~AbstractFactory(){}
</code>```0

Concrete Large Warrior Class

largewarrior.h Concrete Large Warrior header file

```<code>#include "abstractfactory.h"

AbstractFactory::~AbstractFactory(){}
</code>```1

largewarrior.cpp Concrete Large Warrior implementation file

```<code>#include "abstractfactory.h"

AbstractFactory::~AbstractFactory(){}
</code>```2

Concrete Giant Warrior Class

giantwarrior.h - Concrete Giant Warrior header file

```<code>#ifndef GIANTWARRIOR_H
#define GIANTWARRIOR_H

#include "warrior.h"

class GiantWarrior : public Warrior {
public:
    // Methods
    GiantWarrior();
    ~GiantWarrior();
    QString getName();
    QString getPicture();
    void setXPosition(int x);
    int getXPosition();
private:
    // Private Member Variables
    QString m_name;
    QString m_picture;
};

#endif // GIANTWARRIOR_H
</code>```

giantwarrior.cpp - Concrete Giant Warrior implementation file

```<code>#include "giantwarrior.h"

GiantWarrior::GiantWarrior(){
    m_name = "Giant Warrior";
    m_picture = ":/images/giant-warrior.png";
}

GiantWarrior::~GiantWarrior(){}

QString GiantWarrior::getName() {
    return m_name;
}

QString GiantWarrior::getPicture() {
    return m_picture;
}
</code>```

答:
Obviously I cannot talk about your potential future employer, but I personally wouldn't be thrilled by the code you produce. Regardless of whether it works as intended or not, there is a number of problems with it:

it is too verbose, too much code that does too little, this has several implications - you waste time as a developer, you produce code that isn't clean and concise and would be hard to maintain

stuff like cout<<tinySword->getName().toStdString()<<endl; - don't do that, use that space bar

either use Qt or use std:: - no point of mixing the two, doing redundant conversions and so on

your code involves a bunch of string comparisons, those are fairly slow operations, which are best to be avoided whenever possible, strings make sense if you are doing a modular plugin architecture, where the plugins implement types which are not present in the core, but not in your particular scenario

do we really need a separate class for every tiny variation? A small sword, a big sword, a huge sword? How about just a single Sword class, with a nice uint size; member and a size enum?

your scenario doesn't exactly call for abstract factories either, you'd be better off using a single, versatile factory, especially in the case of game object management

comparing a QString to nullptr, really?

writing getters and setters - now that's cool, right? I mean why simply have them public, since you have both a read and write accessor, when you can make them private, and write the extra code to make the private member defacto public. That's what OOP is all about... Contrary to popular belief, I'd say writing setters and getters is only justified when it involves greater complexity than direct member access.

you only have getters for the name and picture, implying those are static constructs. In that case, why even store those as member variables? Needless memory overhead?

It would seem your great wall of code could easily be reduced to something that is just as functional, performs much better, and is much more readable and maintainable.

Body:
I am trying to make all the creational design patterns and I'm having some trouble with the abstract factory method. I normally program in Python, however, I had heard C++ was good for really having to understand design patterns explicitly, which is proving to be right, err.

I'm basically following this guide on Tutorials Point.

My question is how would I change my current code to correctly implement the abstract factory method in C++ with a factory producer as I believe its something to do with my Factory Producer extra layer of abstraction that is causing my issues. I have included all my code.

I tried to make a simple diagram to explain better but it's not the most formal UML but is essentially what I would like to make. My main.cpp file should illustrate better the functionality I'm trying to understand how to make.

P.s. I'm just trying to improve to apply for jobs so please let me know if you have any feedback on writing better SO questions, coding style, variable naming or even C++ conventions.

Main

main.cpp - Main implementation file

Tests creating an abstract factory, abstract sword and abstract warrior.

#include "factoryproducer.h"

using namespace std;

int main(int argc, char *argv[]) {
    AbstractFactory* warriorFactory = FactoryProducer::createFactory("warriorfactory");

    Warrior* tinyWarrior = warriorFactory->createWarrior("tinywarrior");
    Warrior* normalWarrior = warriorFactory->createWarrior("normalwarrior");
    Warrior* largeWarrior = warriorFactory->createWarrior("largewarrior");
    Warrior* giantWarrior = warriorFactory->createWarrior("giantwarrior");

    cout<<tinyWarrior->getName().toStdString()<<endl;
    cout<<normalWarrior->getName().toStdString()<<endl;
    cout<<largeWarrior->getName().toStdString()<<endl;
    cout<<giantWarrior->getName().toStdString()<<endl;

    AbstractFactory* SwordFactory = FactoryProducer::createFactory("swordfactory");

    Sword* tinySword = swordFactory->createSword("tinysword");
    Sword* normalSword = swordFactory->createSword("normalsword");
    Sword* largeSword = swordFactory->createSword("largesword");
    Sword* giantSword = swordFactory->createSword("giantsword");

    cout<<tinySword->getName().toStdString()<<endl;
    cout<<normalSword->getName().toStdString()<<endl;
    cout<<largeSword->getName().toStdString()<<endl;
    cout<<giantSword->getName().toStdString()<<endl;

    return a.exec();
}

Abstract Factory Class

abstractfactory.h - Abstract Factory header file

#ifndef ABSTRACTFACTORY_H
#define ABSTRACTFACTORY_H

#include "warrior.h"
#include "sword.h"
#include <QString>

class AbstractFactory {
public:
    // Public Methods
    ~AbstractFactory();
    virtual Warrior* createWarrior(QString warriorType) = 0;
    virtual Sword* createSword(QString swordType) = 0;
};

#endif // ABSTRACTFACTORY_H

abstractfactory.cpp Abstract Factory implementation file

#include "abstractfactory.h"

AbstractFactory::~AbstractFactory(){}

Factory Producer Class

factoryproducer.h - Factory Producer header file

#ifndef FACTORYPRODUCER_H
#define FACTORYPRODUCER_H

#include "abstractfactory.h"
#include "warriorfactory.h"
#include "swordfactory.h"
#include <QString>

class FactoryProducer {
public:
    // Public Methods
    static AbstractFactory* createFactory(QString factoryType);
};

#endif // FACTORYPRODUCER_H

factoryproducer.cpp - Factory Producer implementation file

#include "factoryproducer.h"

AbstractFactory* AbstractFactory::createFactory(QString factoryType) {
    if (factoryType == nullptr) {
        return nullptr;
    }

    if (QString::compare(factoryType, "WARRIORFACTORY", Qt::CaseInsensitive) == 0) {
        return new WarriorFactory();
    }

    if (QString::compare(factoryType, "SWORDFACTORY", Qt::CaseInsensitive) == 0) {
        return new SwordFactory();
    }

    return nullptr;
}

Abstract Warrior Class

warrior.h - Abstract Warrior header file

#ifndef WARRIOR_H
#define WARRIOR_H

#include "tinywarrior.h"
#include "normalwarrior.h"
#include "largewarrior.h"
#include "giantwarrior.h"
#include <QString>

class Warrior {
public:
    // Public Methods
    ~Warrior();
    virtual QString getName() = 0;
    virtual QString getPicture() = 0;
};

#endif // WARRIOR_H

warrior.cpp - Abstract Warrior implementation file

#include "warrior.h"

Warrior::~Warrior(){}

Abstract Sword Class

sword.h - Abstract Sword header file

#ifndef SWORD_H
#define SWORD_H

#include "tinysword.h"
#include "normalsword.h"
#include "largesword.h"
#include "giantsword.h"
#include <QString>

class Sword {
public:
    // Public Methods
    ~Sword();
    virtual QString getName() = 0;
    virtual QString getPicture() = 0;
};

#endif // SWORD_H

sword.cpp - Abstract Sword implementation file

#include "sword.h"

Sword::~Sword(){}

Concrete TinySword Class

tinysword.h - Concrete Tiny Sword header file

#ifndef TINYSWORD_H
#define TINYSWORD_H

#include "sword.h"

class TinySword : public Sword {
public:
    // Public Methods
    TinySword();
    ~TinySword();
    QString getName();
    QString getPicture();
private:
    // Private Member Variables
    QString m_name;
    QString m_picture;
};

#endif // TINYSWORD_H

tinysword.cpp - Concrete Tiny Sword implementation file

#include "tinysword.h"

TinySword::TinySword(){
    m_name = "Tiny Sword";
    m_picture = "";
}

TinySword::~TinySword(){}

QString TinySword::getName() {
    return m_name;
}

QString TinySword::getPicture() {
    return m_picture;
}

Concrete Normal Sword

normalsword.h - Concrete Normal Sword header file

#ifndef NORMALSWORD_H
#define NORMALSWORD_H

#include "sword.h"

class NormalSword : public Sword {
public:
    // Public Methods
    NormalSword();
    ~NormalSword();
    QString getName();
    QString getPicture();
private:
    // Private Member Variables
    QString m_name;
    QString m_picture;
};

#endif // NORMALSWORD_H

normalsword.cpp - Concrete Normal Sword implementation file

#include "normalsword.h"

NormalSword::NormalSword() {
    m_name = "Normal Sword";
    m_picture = "";
}

NormalSword::~NormalSword(){}

QString NormalSword::getName() {
    return m_name;
}

QString NormalSword::getPicture() {
    return m_picture;
}

Concrete Large Sword Class

largesword.h - Concrete Large Sword header file

#ifndef LARGESWORD_H
#define LARGESWORD_H

#include "sword.h"

class LargeSword : public Sword {
public:
    // Public Methods
    LargeSword();
    ~LargeSword();
    QString getName();
    QString getPicture();
private:
    // Private Member Variables
    QString m_name;
    QString m_picture;
};

#endif // LARGESWORD_H

largesword.cpp - Concrete Large Sword implementation file

#include "largesword.h"

LargeSword::LargeSword() {
    m_name = "Large Sword";
    m_picture = "";
}

LargeSword::~LargeSword(){}

QString LargeSword::getName() {
    return m_name;
}

QString LargeSword::getPicture() {
    return m_picture;
}

Concrete Giant Sword Class

giantsword.h - Concrete Giant Sword header file

#ifndef GIANTSWORD_H
#define GIANTSWORD_H

#include "sword.h"

class GiantSword : public Sword {
public:
    // Public Methods
    GiantSword();
    ~GiantSword();
    QString getName();
    QString getPicture();
private:
    // Private Member Variables
    QString m_name;
    QString m_picture;
};

#endif // GIANTSWORD_H

giantsword.cpp - Concrete Giant Sword implementation file

#include "giantsword.h"

GiantSword::GiantSword() {
    m_name = "Giant Sword";
    m_picture = "";
}

GiantSword::~GiantSword(){}

QString GiantSword::getName() {
    return m_name;
}

QString GiantSword::getPicture() {
    return m_picture;
}

Concrete Tiny Warrior Class

tinywarrior.h - Concrete Tiny Warrior header file

#ifndef TINYWARRIOR_H
#define TINYWARRIOR_H

#include "warrior.h"

class TinyWarrior : public Warrior {
public:
    // Methods
    TinyWarrior();
    ~TinyWarrior();
    QString getPicture();
private:
    // Private Member Variables
    QString m_name;
    QString m_picture;
};

#endif // TINYWARRIOR_H

tinywarrior.cpp - Concrete Tiny Warrior implementation file

#include "tinywarrior.h"

TinyWarrior::TinyWarrior(){
    m_name = "Tiny Warrior";
    m_picture = ":/images/tiny-warrior.png";
}

TinyWarrior::~TinyWarrior(){}

QString TinyWarrior::getName() {
    return m_name;
}

QString TinyWarrior::getPicture() {
    return m_picture;
}

Concrete Normal Warrior Class

normalwarrior.h - Concrete Normal Warrior header file

#ifndef NORMALWARRIOR_H
#define NORMALWARRIOR_H

#include "warrior.h"

class NormalWarrior : public Warrior {
public:
    // Public Methods
    NormalWarrior();
    ~NormalWarrior();
    QString getName();
    QString getPicture();
private:
    // Private Member Variables
    QString m_name;
    QString m_picture;
};

#endif // NORMALWARRIOR_H

normalwarrior.cpp Concrete Normal Warrior implementation

#include "normalwarrior.h"

NormalWarrior::NormalWarrior() {
    m_name = "Normal Warrior";
    m_picture = ":/images/normal-warrior.png";
}

NormalWarrior::~NormalWarrior(){}

QString NormalWarrior::getName() {
    return m_name;
}

QString NormalWarrior::getPicture() {
    return m_picture;
}

Concrete Large Warrior Class

largewarrior.h Concrete Large Warrior header file

#ifndef LARGEWARRIOR_H
#define LARGEWARRIOR_H

#include "warrior.h"

class LargeWarrior : public Warrior {
public:
    // Methods
    LargeWarrior();
    ~LargeWarrior();
    QString getName();
    QString getPicture();
private:
    // Private Member Variables
    QString m_name;
    QString m_picture;
};

#endif // LARGEWARRIOR_H

largewarrior.cpp Concrete Large Warrior implementation file

#include "largewarrior.h"

LargeWarrior::LargeWarrior(){
    m_name = "Large Warrior";
    m_picture = ":/images/large-warrior.png";
}

LargeWarrior::~LargeWarrior(){}

QString LargeWarrior::getName() {
    return m_name;
}

QString LargeWarrior::getPicture() {
    return m_picture;
}

Concrete Giant Warrior Class

giantwarrior.h - Concrete Giant Warrior header file

#ifndef GIANTWARRIOR_H
#define GIANTWARRIOR_H

#include "warrior.h"

class GiantWarrior : public Warrior {
public:
    // Methods
    GiantWarrior();
    ~GiantWarrior();
    QString getName();
    QString getPicture();
    void setXPosition(int x);
    int getXPosition();
private:
    // Private Member Variables
    QString m_name;
    QString m_picture;
};

#endif // GIANTWARRIOR_H

giantwarrior.cpp - Concrete Giant Warrior implementation file

#include "giantwarrior.h"

GiantWarrior::GiantWarrior(){
    m_name = "Giant Warrior";
    m_picture = ":/images/giant-warrior.png";
}

GiantWarrior::~GiantWarrior(){}

QString GiantWarrior::getName() {
    return m_name;
}

QString GiantWarrior::getPicture() {
    return m_picture;
}


问:
Intellisense not working in SQL Server 2012
I have enabled the intellisense in SQL Server 2012 and refresh the local cache. But it's not working.Enable option: Tools -> Options -> Text Editor -> Transact-SQL -> General -> IntelliSense.Please suggest your solution.</p>

答: I got solution. I have downloaded Sql complete for Sql server 2012 and installed it. It was working now.</p>


问:
multithreading in java to print abc using 3 threads
the task is to print abc repeatedly using three threads infinite number of times
my code is

```<code>package javap;

public class Pattern {

    volatile int status=1;
    public static void main(String[] args) {

        Pattern p = new Pattern();

        A1 a=new A1(p);
        B1 b=new B1(p);
        C1 c=new C1(p);

        a.start();
        b.start();
        c.start();
    }
}

class A1 extends Thread{
    Pattern p1;

    A1(Pattern p){
        this.p1 = p;
    }

    @Override
    public void run() {

        try{
            synchronized (p1) {

                for (int i = 0; i < 100; i++) {

                    while(p1.status!=1){
                        p1.wait();
                    }

                    System.out.print("A ");
                    p1.status = 2;
                  p1.notifyAll();
                }

            }
        }catch (Exception e) {
            System.out.println("Exception 1 :"+e.getMessage());
        }

    }

}

class B1 extends Thread{

    Pattern p2;

    B1(Pattern p2){
        this.p2 = p2;
    }

    @Override
    public void run() {

        try{
            synchronized (p2) {

                for (int i = 0; i < 100; i++) {

                    while(p2.status!=2){
                        p2.wait();
                    }

                    System.out.print("B ");
                    p2.status = 3;
                   p2.notifyAll();
                }

            }
        }catch (Exception e) {
            System.out.println("Exception 2 :"+e.getMessage());
        }

    }
}

class C1 extends Thread{

    Pattern p3;

    C1(Pattern p){
        this.p3 = p;
    }

    @Override
    public void run() {

        try{
            synchronized (p3) {

                for (int i = 0; i < 100; i++) {

                    while(p3.status!=3){
                       p3.wait();
                    }

                    System.out.print("C ");
                    p3.status = 1;
                   p3.notifyAll();
                }

            }
        }catch (Exception e) {
            System.out.println("Exception 3 :"+e.getMessage());
        }

    }
}
</code>```

when i tried using for(;;) or while(true) my ide hangs and i am nt getting any output
so i restricted it to 100 times.
is there anyway that i can make this run infinite number of times.

thanks in advance

答:
I have modified your logic a little, and it is getting the output stream A B C with an interval of 1000 milliseconds (better for visualization).

```<code>public class Pattern {

    volatile int status = 1;

    public static void main(String[] args) {

        Pattern p = new Pattern();

        A1 a = new A1(p);
        B1 b = new B1(p);
        C1 c = new C1(p);

        a.start();
        b.start();
        c.start();
    }
}

class A1 extends Thread {
    Pattern p1;

    A1(Pattern p) {
        this.p1 = p;
    }

    @Override
    public void run() {

        try {
            synchronized (p1) {
                while (true) {
                    while (p1.status != 1) {
                        try {
                            p1.wait();
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                    System.out.print("A ");
                    p1.status = 2;
                    p1.notifyAll();
                }
            }
        } catch (Exception e) {
            System.out.println("Exception 1 :" + e.getMessage());
        }

    }

}

class B1 extends Thread {

    Pattern p2;

    B1(Pattern p2) {
        this.p2 = p2;
    }

    @Override
    public void run() {

        try {
            synchronized (p2) {
                while (true) {
                    while (p2.status != 2) {
                        try {
                            p2.wait();
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                    System.out.print("B ");
                    p2.status = 3;
                    p2.notifyAll();
                }
            }
        } catch (Exception e) {
            System.out.println("Exception 2 :" + e.getMessage());
        }

    }
}

class C1 extends Thread {

    Pattern p3;

    C1(Pattern p) {
        this.p3 = p;
    }

    @Override
    public void run() {

        try {
            synchronized (p3) {
                while (true) {
                    while (p3.status != 3) {
                        try {
                            p3.wait();
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                    System.out.print("C ");
                    Thread.sleep(1000);
                    p3.status = 1;
                    p3.notifyAll();
                }
            }
        } catch (Exception e) {
            System.out.println("Exception 3 :" + e.getMessage());
        }

    }
}
</code>```

Output: A B C A B C A B C A B C A B C .....

Body:
the task is to print abc repeatedly using three threads infinite number of times
my code is

package javap;

public class Pattern {

    volatile int status=1;
    public static void main(String[] args) {

        Pattern p = new Pattern();

        A1 a=new A1(p);
        B1 b=new B1(p);
        C1 c=new C1(p);

        a.start();
        b.start();
        c.start();
    }
}

class A1 extends Thread{
    Pattern p1;

    A1(Pattern p){
        this.p1 = p;
    }

    @Override
    public void run() {

        try{
            synchronized (p1) {

                for (int i = 0; i < 100; i++) {

                    while(p1.status!=1){
                        p1.wait();
                    }

                    System.out.print("A ");
                    p1.status = 2;
                  p1.notifyAll();
                }

            }
        }catch (Exception e) {
            System.out.println("Exception 1 :"+e.getMessage());
        }

    }

}

class B1 extends Thread{

    Pattern p2;

    B1(Pattern p2){
        this.p2 = p2;
    }

    @Override
    public void run() {

        try{
            synchronized (p2) {

                for (int i = 0; i < 100; i++) {

                    while(p2.status!=2){
                        p2.wait();
                    }

                    System.out.print("B ");
                    p2.status = 3;
                   p2.notifyAll();
                }

            }
        }catch (Exception e) {
            System.out.println("Exception 2 :"+e.getMessage());
        }

    }
}

class C1 extends Thread{

    Pattern p3;

    C1(Pattern p){
        this.p3 = p;
    }

    @Override
    public void run() {

        try{
            synchronized (p3) {

                for (int i = 0; i < 100; i++) {

                    while(p3.status!=3){
                       p3.wait();
                    }

                    System.out.print("C ");
                    p3.status = 1;
                   p3.notifyAll();
                }

            }
        }catch (Exception e) {
            System.out.println("Exception 3 :"+e.getMessage());
        }

    }
}

when i tried using for(;;) or while(true) my ide hangs and i am nt getting any output
so i restricted it to 100 times.
is there anyway that i can make this run infinite number of times.

thanks in advance

Body:
I have modified your logic a little, and it is getting the output stream A B C with an interval of 1000 milliseconds (better for visualization).

public class Pattern {

    volatile int status = 1;

    public static void main(String[] args) {

        Pattern p = new Pattern();

        A1 a = new A1(p);
        B1 b = new B1(p);
        C1 c = new C1(p);

        a.start();
        b.start();
        c.start();
    }
}

class A1 extends Thread {
    Pattern p1;

    A1(Pattern p) {
        this.p1 = p;
    }

    @Override
    public void run() {

        try {
            synchronized (p1) {
                while (true) {
                    while (p1.status != 1) {
                        try {
                            p1.wait();
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                    System.out.print("A ");
                    p1.status = 2;
                    p1.notifyAll();
                }
            }
        } catch (Exception e) {
            System.out.println("Exception 1 :" + e.getMessage());
        }

    }

}

class B1 extends Thread {

    Pattern p2;

    B1(Pattern p2) {
        this.p2 = p2;
    }

    @Override
    public void run() {

        try {
            synchronized (p2) {
                while (true) {
                    while (p2.status != 2) {
                        try {
                            p2.wait();
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                    System.out.print("B ");
                    p2.status = 3;
                    p2.notifyAll();
                }
            }
        } catch (Exception e) {
            System.out.println("Exception 2 :" + e.getMessage());
        }

    }
}

class C1 extends Thread {

    Pattern p3;

    C1(Pattern p) {
        this.p3 = p;
    }

    @Override
    public void run() {

        try {
            synchronized (p3) {
                while (true) {
                    while (p3.status != 3) {
                        try {
                            p3.wait();
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                    System.out.print("C ");
                    Thread.sleep(1000);
                    p3.status = 1;
                    p3.notifyAll();
                }
            }
        } catch (Exception e) {
            System.out.println("Exception 3 :" + e.getMessage());
        }

    }
}

Output: A B C A B C A B C A B C A B C .....


问:
Python: Extract single line from file
Very new, please be nice and explain slowly and clearly. Thanks :)

I've tried searching how to extract a single line in python, but all the responses seem much more complicated (and confusing) than what I'm looking for. I have a file, it has a lot of lines, I want to pull out just the line that starts with #.

My file.txt:

```<code>"##STUFF"
"##STUFF"
#DATA 01 02 03 04 05
More lines here
More lines here
More lines here
</code>```

My attempt at a script:

```<code>file = open("file.txt", "r")

splitdata = []

for line in file:
    if line.startswith['#'] = data
    splitdata = data.split()
    print splitdata

#expected output:
#splitdata = [#DATA, 1, 2, 3, 4, 5]
</code>```

The error I get:

line.startswith['#'] = data

TypeError: 'builtin_function_or_method' object does not support item assignment

That seems to mean it doesn't like my "= data", but I'm not sure how to tell it that I want to take the line that starts with # and save it separately.

答:
Correct the if statement and the indentation,</p>

```<code>for line in file:
    if line.startswith('#'):
        print line
</code>```

Title: Python: Extract single line from file

Body:
Very new, please be nice and explain slowly and clearly. Thanks :)

I've tried searching how to extract a single line in python, but all the responses seem much more complicated (and confusing) than what I'm looking for. I have a file, it has a lot of lines, I want to pull out just the line that starts with #.

My file.txt:

"##STUFF"
"##STUFF"
#DATA 01 02 03 04 05
More lines here
More lines here
More lines here

My attempt at a script:

file = open("file.txt", "r")

splitdata = []

for line in file:
    if line.startswith['#'] = data
    splitdata = data.split()
    print splitdata

#expected output:
#splitdata = [#DATA, 1, 2, 3, 4, 5]

The error I get:

line.startswith['#'] = data

TypeError: 'builtin_function_or_method' object does not support item assignment

That seems to mean it doesn't like my "= data", but I'm not sure how to tell it that I want to take the line that starts with # and save it separately.

Body:
Correct the if statement and the indentation,

for line in file:
    if line.startswith('#'):
        print line


问:
How can I convert the output from a ostream_iterator to a string?
I am implementing a toString method in C++ primarily using the ostream_iterator.

```<code>std::ostream_iterator<int> output(std::cout, " ");
</code>```

After printing to the console, however, I wish to return the output of the ostream_iterator as a string. Is this direct conversion possible?

答:
If you want a string-like object that uses the std::ostream interface rather than the STL container interface, that’s std::stringstream, or the deprecated std::strstream  The closest thing to a generic wrapper that turns anything that can be serialized with cout << into a std::string would be to write to a std::stringstream and then read the data back out.  This will end up making at least one expensive copy, however.  Here’s an implementation:

```<code>#include <cstdlib>
#include <iostream>
#include <iterator>
#include <sstream>
#include <string>

using std::cout;
using std::endl;
using isit = std::istream_iterator<char>;

template <typename T> std::string to_string(const T& x)
// Must be able to print a T with std::ostream::operator<<.
{
  std::stringstream buffer;
  buffer << x;

  const isit begin(buffer);     // The start of the stream object.
  static const isit end;        // Default object is the end-of-stream iterator.

  return std::string( begin, end );
}

int main(void)
{
  const std::string output_string = to_string("Testing:") + " " +
    to_string(1) + ", " + to_string(2ULL) + ", " + to_string(3.0) +
    to_string('.');

  cout << output_string << endl;
  return EXIT_SUCCESS;
}
</code>```

You can use a std::ostream_iterator<char> to write to a std::stringstream, rather than <<, and then a std::istream_iterator<char> as shown to copy from that to a string.

You can write data from a std::istream to a std::string with a std::istream_iterator.  Sort of.  The formatting can be wonky.

If you want to read data from a std::string using an iterator, its iterator type is std::string::iterator and an iterator to the front of the string is s.begin(), like other STL containers.

If you just have a bunch of data stored in memory that you want to send to both an output iterator and a string, you can use one of its other constructors.

Body:
I am implementing a toString method in C++ primarily using the ostream_iterator.

std::ostream_iterator<int> output(std::cout, " ");

After printing to the console, however, I wish to return the output of the ostream_iterator as a string. Is this direct conversion possible?

Body:
If you want a string-like object that uses the std::ostream interface rather than the STL container interface, that’s std::stringstream, or the deprecated std::strstream  The closest thing to a generic wrapper that turns anything that can be serialized with cout << into a std::string would be to write to a std::stringstream and then read the data back out.  This will end up making at least one expensive copy, however.  Here’s an implementation:

#include <cstdlib>
#include <iostream>
#include <iterator>
#include <sstream>
#include <string>

using std::cout;
using std::endl;
using isit = std::istream_iterator<char>;

template <typename T> std::string to_string(const T& x)
// Must be able to print a T with std::ostream::operator<<.
{
  std::stringstream buffer;
  buffer << x;

  const isit begin(buffer);     // The start of the stream object.
  static const isit end;        // Default object is the end-of-stream iterator.

  return std::string( begin, end );
}

int main(void)
{
  const std::string output_string = to_string("Testing:") + " " +
    to_string(1) + ", " + to_string(2ULL) + ", " + to_string(3.0) +
    to_string('.');

  cout << output_string << endl;
  return EXIT_SUCCESS;
}

You can use a std::ostream_iterator<char> to write to a std::stringstream, rather than <<, and then a std::istream_iterator<char> as shown to copy from that to a string.

You can write data from a std::istream to a std::string with a std::istream_iterator.  Sort of.  The formatting can be wonky.

If you want to read data from a std::string using an iterator, its iterator type is std::string::iterator and an iterator to the front of the string is s.begin(), like other STL containers.

If you just have a bunch of data stored in memory that you want to send to both an output iterator and a string, you can use one of its other constructors.