问:
C# Validation Pattern - Best practice to validate an Entity over a certain operation
I might be trying to solve this problem in a wrong way and I've also found lots of solutions but none of them answer my particular question.

In short, I want to validate an object (i.e. argument, entity, etc.) over a an operation (i.e. Insert, Update, Select, etc.).

I've created a small code sample here only for 1 class and 2 operations. But in my actual project, there are many more classes like Person and operations.

Person.cs

```<code>public class Person
{
   public int Id {get;set;}
   public string Name {get;set;}
   public DateTime Birthdate {get;set;}
   public BeverageSelectionType BeverageSelection {get;set;}
}
</code>```

BeverageSelectionType.cs

```<code>public enum BeverageSelectionType
{
    NotSet,
    Juice,
    Beer,
    Water
}
</code>```

IService.cs

```<code>public interface IService
{
   void Update(Person person);
   Person Add(Person person);
}
</code>```

PersonSevice.cs (To explain it simple, I chose as service, but in reality I use repository pattern and UnitOfWork which I thought writing them here would be long)

```<code>public class PersonService : IService
{
    public void Update(Person person)
    {
        if(person.BeverageSelection == BeverageSelectionType.NotSet
           || (person.BeverageSelection == BeverageSelectionType.Beer && person.Birthdate < DateTime.Now.AddYears(-18))
          )
         throw new MyInvalidException("Parameters NOT valid for UPDATE operation");

         //Do update with expected parameters
    }

    public Person Add(Person person)
    {
        if(person.Birthdate <= DateTime.MinValue || person.Birthdate >= DateTime.MaxValue)
         throw new MyInvalidException("Parameters NOT valid for ADD operation");

         //Do add with expected parameters
    }
}
</code>```

I need to design such as generic as possible approach for Validation that helps to validate entities against operations. I just don't want to add validation logic in to each service.

Here is another approach that every Entity knows itself when and how it is valid but I though was useful but still believe not good enough:

Person.cs

```<code>public class Person
{
       public int Id {get;set;}
       public string Name {get;set;}
       public DateTime Birthdate {get;set;}
       public BeverageSelectionType BeverageSelection {get;set;}

   public bool IsValid(ModelValidationType modelValidationType)
   {
       switch(modelValidationType)
       {
           case ModelValidationType.Update:
               if(person.BeverageSelection == BeverageSelectionType.NotSet
           || (person.BeverageSelection == BeverageSelectionType.Beer && person.Birthdate < DateTime.Now.AddYears(-18))
          )
          return false;

           case ModelValidationType.Add:
            if(person.Birthdate <= DateTime.MinValue || person.Birthdate >= DateTime.MaxValue)
             return false;
       }

     return true;
   }
}
</code>```

How would you implement the most proper validation approach?

Thanks in advance

答:
following the way I would implement it. After the code some clarification.

```<code>public class Person
{
    private int id;
    private DateTime birthdate;
    private BeverageSelectionType beverageSelectionType;

    public string Name { get; private set; }

    public Person(string name, DateTime birthdate)
    {
        if(birthdate <= DateTime.MinValue || birthdate >= DateTime.MaxValue)
            throw new ArgumentOutOfRangeException(nameof(birthdate));

        id = 0
        Name = name;
        this.birthdate = birthdate;
    }

    public void OrderBeverage(BeverageSelectionType beverageSelectionType)
    {
        if(beverageSelectionType == BeverageSelectionType.Beer $$
           birthdate > DateTime.Now.AddYears(-18))
        {
            throw new InvalidOperationException("Person is not old enough for beer, sorry bro")
        }

        this.beverageSelectionType = beverageSelectionType;
    }
}
</code>```

1. Private fields over properties

I would always recommend to hide everything thats not important to the outside. This is basic encapsulation or information hiding. If you dont have a strong reason to make something public, dont do it.

2. Constructor

Your person seems to need always a name and a birthdate. Because of that, I would ensure this with a constructor. Do you have a reason to instantiate a invalid object? If no -> dont let it happen.

3. Method with 'eager validation'

In this example, validation happens in your method. This is good because your client code can operate on that and decide what to do before persistence is triggered.

In general you mix two things in one class. One is the concept of a person and one the concept of an order. I would recomend to not break this abstractions. I would suggest that your person class offers something like

```<code>public bool IsAdult();
</code>```

And some Order class that gets a person and your beverage selection and determines if it is a valid order or not.

Body:
I might be trying to solve this problem in a wrong way and I've also found lots of solutions but none of them answer my particular question.

In short, I want to validate an object (i.e. argument, entity, etc.) over a an operation (i.e. Insert, Update, Select, etc.).

I've created a small code sample here only for 1 class and 2 operations. But in my actual project, there are many more classes like Person and operations.

Person.cs

public class Person
{
   public int Id {get;set;}
   public string Name {get;set;}
   public DateTime Birthdate {get;set;}
   public BeverageSelectionType BeverageSelection {get;set;}
}

BeverageSelectionType.cs

public enum BeverageSelectionType
{
    NotSet,
    Juice,
    Beer,
    Water
}

IService.cs

public interface IService
{
   void Update(Person person);
   Person Add(Person person);
}

PersonSevice.cs (To explain it simple, I chose as service, but in reality I use repository pattern and UnitOfWork which I thought writing them here would be long)

public class PersonService : IService
{
    public void Update(Person person)
    {
        if(person.BeverageSelection == BeverageSelectionType.NotSet
           || (person.BeverageSelection == BeverageSelectionType.Beer && person.Birthdate < DateTime.Now.AddYears(-18))
          )
         throw new MyInvalidException("Parameters NOT valid for UPDATE operation");

         //Do update with expected parameters
    }

    public Person Add(Person person)
    {
        if(person.Birthdate <= DateTime.MinValue || person.Birthdate >= DateTime.MaxValue)
         throw new MyInvalidException("Parameters NOT valid for ADD operation");

         //Do add with expected parameters
    }
}

I need to design such as generic as possible approach for Validation that helps to validate entities against operations. I just don't want to add validation logic in to each service.

Here is another approach that every Entity knows itself when and how it is valid but I though was useful but still believe not good enough:

Person.cs

public class Person
{
       public int Id {get;set;}
       public string Name {get;set;}
       public DateTime Birthdate {get;set;}
       public BeverageSelectionType BeverageSelection {get;set;}

   public bool IsValid(ModelValidationType modelValidationType)
   {
       switch(modelValidationType)
       {
           case ModelValidationType.Update:
               if(person.BeverageSelection == BeverageSelectionType.NotSet
           || (person.BeverageSelection == BeverageSelectionType.Beer && person.Birthdate < DateTime.Now.AddYears(-18))
          )
          return false;

           case ModelValidationType.Add:
            if(person.Birthdate <= DateTime.MinValue || person.Birthdate >= DateTime.MaxValue)
             return false;
       }

     return true;
   }
}

How would you implement the most proper validation approach?

Thanks in advance

Body:
following the way I would implement it. After the code some clarification.

public class Person
{
    private int id;
    private DateTime birthdate;
    private BeverageSelectionType beverageSelectionType;

    public string Name { get; private set; }

    public Person(string name, DateTime birthdate)
    {
        if(birthdate <= DateTime.MinValue || birthdate >= DateTime.MaxValue)
            throw new ArgumentOutOfRangeException(nameof(birthdate));

        id = 0
        Name = name;
        this.birthdate = birthdate;
    }

    public void OrderBeverage(BeverageSelectionType beverageSelectionType)
    {
        if(beverageSelectionType == BeverageSelectionType.Beer $$
           birthdate > DateTime.Now.AddYears(-18))
        {
            throw new InvalidOperationException("Person is not old enough for beer, sorry bro")
        }

        this.beverageSelectionType = beverageSelectionType;
    }
}

1. Private fields over properties

I would always recommend to hide everything thats not important to the outside. This is basic encapsulation or information hiding. If you dont have a strong reason to make something public, dont do it.

2. Constructor

Your person seems to need always a name and a birthdate. Because of that, I would ensure this with a constructor. Do you have a reason to instantiate a invalid object? If no -> dont let it happen.

3. Method with 'eager validation'

In this example, validation happens in your method. This is good because your client code can operate on that and decide what to do before persistence is triggered.

In general you mix two things in one class. One is the concept of a person and one the concept of an order. I would recomend to not break this abstractions. I would suggest that your person class offers something like

public bool IsAdult();

And some Order class that gets a person and your beverage selection and determines if it is a valid order or not.


来源: stackexchange

问:
Retrieve privileges using security role rather than using system user
Here is my code:

```<code>RetrievePrincipalAccessRequest request = new RetrievePrincipalAccessRequest();
request.Principal = new EntityReference("systemuser", new Guid("GUID of system user record."));
// record for which we want to check the access
request.Target = new EntityReference("account", new Guid("GUID of account record."));
try
{
    RetrievePrincipalAccessResponse responce = (RetrievePrincipalAccessResponse)organisationservice.Execute(request);
}
catch (Exception ex)
{
    Console.WriteLine("error" + ex.Message.ToString());
}
</code>```

It take out "can access| can edit| can read" privilege for system user and a
security principal can be either user or team but not a security role, therefore is there any C# code which can retrieve privileges using a security role.

I have Dynamic CRM Online instance.

Thanks :-)

答:
Yes, if you want to retrieve all privileges for a security role you can use RetrieveRolePrivilegesRoleRequest like this:

```<code>var roleRequest = new RetrieveRolePrivilegesRoleRequest { RoleId = new Guid("securityRoleId") };
var roleReponse = service.Execute(roleRequest);
</code>```

Replace "securityRoleId" with your securityrole.Id.ToString() and service with your organisationservice.

roleResponse.RolePrivileges will contain a long list of privilege IDs which are not very useful on their own. You could get the name of all of these privileges like this:

```<code>var privilegeQuery = new QueryExpression { EntityName = "privilege", ColumnSet = new ColumnSet(true) };

var filter = new FilterExpression(LogicalOperator.Or);

foreach (var p in roleResponse.RolePrivileges)
    filter.AddCondition("privilegeid", ConditionOperator.Equal, p.PrivilegeId);

privilegeQuery.Criteria = filter;

var privileges = service.RetrieveMultiple(privilegeQuery);
</code>```

Now you will have all columns (attributes) for all privileges for a given security role stored in privileges.

I think/hope that answers your question. However to go one step further, you could filter your privileges by the entity they refer to as well:

```<code>var contactPrivileges = privileges.Entities.ToList()
            .Where(p => p.GetAttributeValue<string>("name").ToLower()
            .Contains("contact"))
            .ToList();
</code>```

ContentLicense: CC BY-SA 3.0

Body:
Here is my code:

RetrievePrincipalAccessRequest request = new RetrievePrincipalAccessRequest();
request.Principal = new EntityReference("systemuser", new Guid("GUID of system user record."));
// record for which we want to check the access
request.Target = new EntityReference("account", new Guid("GUID of account record."));
try
{
    RetrievePrincipalAccessResponse responce = (RetrievePrincipalAccessResponse)organisationservice.Execute(request);
}
catch (Exception ex)
{
    Console.WriteLine("error" + ex.Message.ToString());
}

It take out "can access| can edit| can read" privilege for system user and a
security principal can be either user or team but not a security role, therefore is there any C# code which can retrieve privileges using a security role.

I have Dynamic CRM Online instance.

Thanks :-)

Body:
Yes, if you want to retrieve all privileges for a security role you can use RetrieveRolePrivilegesRoleRequest like this:

var roleRequest = new RetrieveRolePrivilegesRoleRequest { RoleId = new Guid("securityRoleId") };
var roleReponse = service.Execute(roleRequest);

Replace "securityRoleId" with your securityrole.Id.ToString() and service with your organisationservice.

roleResponse.RolePrivileges will contain a long list of privilege IDs which are not very useful on their own. You could get the name of all of these privileges like this:

var privilegeQuery = new QueryExpression { EntityName = "privilege", ColumnSet = new ColumnSet(true) };

var filter = new FilterExpression(LogicalOperator.Or);

foreach (var p in roleResponse.RolePrivileges)
    filter.AddCondition("privilegeid", ConditionOperator.Equal, p.PrivilegeId);

privilegeQuery.Criteria = filter;

var privileges = service.RetrieveMultiple(privilegeQuery);

Now you will have all columns (attributes) for all privileges for a given security role stored in privileges.

I think/hope that answers your question. However to go one step further, you could filter your privileges by the entity they refer to as well:

var contactPrivileges = privileges.Entities.ToList()
            .Where(p => p.GetAttributeValue<string>("name").ToLower()
            .Contains("contact"))
            .ToList();


问:
Optional dependencies in a pip requirements file
How can I specify optional dependencies in a pip requirements file?

According to the pip documentation this is possible, but the documentation doesn't explain how to do it, and I can't find any examples on the web.

答:
In 2015 PEP-0508 defined a way to specify optional dependencies in requirements.txt:

```<code>requests[security]
</code>```

That means that yourpackage needs requests for its security option. You can install it as:

```<code>pip install yourpackage[security]
</code>```

ContentLicense: CC BY-SA 4.0

Body:
In 2015 PEP-0508 defined a way to specify optional dependencies in requirements.txt:

requests[security]

That means that yourpackage needs requests for its security option. You can install it as:

pip install yourpackage[security]


问:
Rendering a spark view to a string
I'm trying to render a partial view as a string so it can be returned as HTML to a jquery ajax call. After a lot of searching I found this code.

```<code>public string RenderAsString(string viewName, string modelName, object model)
{
    // Set up your spark engine goodness.
    var settings = new SparkSettings().SetPageBaseType(typeof(SparkView));
    var templates = new FileSystemViewFolder(Server.MapPath("~/Views"));
    var engine = new SparkViewEngine(settings) { ViewFolder = templates };

    // "Describe" the view (the template, it is a template after all), and its details.
    var descriptor = new SparkViewDescriptor().AddTemplate(@"Shared\" + viewName + ".spark");

    // Create a spark view engine instance
    var view = (SparkView)engine.CreateInstance(descriptor);

    // Add the model to the view data for the view to use.
    view.ViewData[modelName] = model;

    // Render the view to a text writer.
    var writer = new StringWriter(); view.RenderView(writer);

    // Convert to string
    return writer.ToString();
}
</code>```

But when the following line executes:

```<code>var view = (SparkView)engine.CreateInstance(descriptor);
</code>```

I get the following error:

Dynamic view compilation failed.  An
  object reference is required for the
  non-static field, method, or property
  'DomainModel.Entities.Region.Id.get.

This is my partial view:

```<code><ViewData Model="Region" />

<div id="${ Region.Id }" class="active-translation-region-widget" >
    <label>${Region.RegionName}</label>
        ${ Html.CheckBox("Active") }
</div>
</code>```

It doesn't seem to recognise the model.

P.S. When I call the view from a parent view like so

```<code><for each="var region in Model">
    <ActiveTranslationRegion Region="region" if="region.Active==true"></ActiveTranslationRegion>
</for>
</code>```

It renders perfectly. What am I doing wrong?

答:
Just from looking at it, I think the following line is the problem:

```<code><ViewData Model="Region" />
</code>```

Instead it should read:

```<code><viewata model="Region" />
</code>```

Note the lower case "model". This is because model is a special case since behind the scenes it performs a cast to a strongly typed viewmodel. The top one will define a variable called Model in the generated view class and assign the value Region to it. Using the lowercase option below will actually create a Model variable, but also cast it to strongly typed instance of Region that comes from the ViewData dictionary.

Note When using Model in the code though, like you did in the for each loop, it needs to be upper case which is correct in your case. Once again, this is the only special case because it's pulling a strongly typed model from the ViewData dictionary.

One other thing - <viewata model="Region" /> must be declared in the parent view, and it can only be defined once per page, so you cannot redefine it in a partial view. If it's a partial view, you should rather use it by passing in a part of the model like you have done in your second example above.

The reason for your exception above is because it's trying to get the Id property as a static item off the Region Type, rather than querying the Id property on your instance of Region as part of your viewmodel.

As a side note, the code to get where you want is a little mangled. You can find neater ways of doing what you want by checking out some of the Direct Usage Samples, but I understand this was probably just a spike to see it working... :)

Update in response to your follow up question/answer

I'm fairly sure that the problem is with passing the Region into the following call:

```<code><ActiveTranslationRegion Region="region" if="region.Active==true">
</code>```

... is again down to naming. Yes, you can only have one model per view as I said before, so what you need to do is remove the following from the top of your partial:

```<code><viewdata model="Region" />
</code>```

That's what's causing an issue. I would then rename the item going into your partial like so:

```<code><ActiveTranslationRegion ActiveRegion="region" if="region.Active==true">
</code>```

and then your partial would look like this:

```<code><form action="/Translation/DeactivateRegion" class="ui-widget-content active-translation-region-widget">
    <input type="hidden" name="Id" value="${ActiveRegion.Id}" />
    <label class="region-name">${ ActiveRegion.RegionName }</label>
    <input class="deactivate-region-button" type="image" src=${Url.Content("~/Content/Images/Deactivate.png")} alt="Deactivate" />
</form>
</code>```

Note I'm using ActiveRegion because in the Spark parser, ActiveRegion gets declared as a variable and assigned the value of region in the current scope as you loop through the for loop. No need to stick religiously to the model - because you've gone and passed in a piece of the model now that you've declared as ActiveRegion. Oh, and you could stick with the name Region if you really want, I just changed it to make a point, and because you've got a Type called Region in your code and I'm not a big fan of the quirky issues using the same name for a variable as a type can bring about. Plus it makes it a little clearer.

The disadvantage of calling the Html.RenderPartial method is not immediately obvious. One thing you lose is the 3-pass rendering that Spark provides. If you use the tag syntax (which is preferable) you'll be able to stack partials within partials to multiple levels down passing variables that feed each partial what they need down the stack. It gets really powerful - start thinking data grid type structures where rows and cells are individual partials that are fed the variables they need from the model, all kept nice and clean in separate manageable view files. Don't stop there though, start thinking about targeting header and footer content base on variables or three column layouts that create a dashboard that renders all sorts on individually stacked partials many levels deep.

You lose all of that flexibility when you use the bog standard ASP.NET MVC Helper method Html.RenderPartial() - careful of doing that, there's more than likely a solution like the one above.

Let me know if that works...

All the best

Rob G

ContentLicense: CC BY-SA 2.5

Title: Rendering a spark view to a string

Body:
I'm trying to render a partial view as a string so it can be returned as HTML to a jquery ajax call. After a lot of searching I found this code.

public string RenderAsString(string viewName, string modelName, object model)
{
    // Set up your spark engine goodness.
    var settings = new SparkSettings().SetPageBaseType(typeof(SparkView));
    var templates = new FileSystemViewFolder(Server.MapPath("~/Views"));
    var engine = new SparkViewEngine(settings) { ViewFolder = templates };

    // "Describe" the view (the template, it is a template after all), and its details.
    var descriptor = new SparkViewDescriptor().AddTemplate(@"Shared\" + viewName + ".spark");

    // Create a spark view engine instance
    var view = (SparkView)engine.CreateInstance(descriptor);

    // Add the model to the view data for the view to use.
    view.ViewData[modelName] = model;

    // Render the view to a text writer.
    var writer = new StringWriter(); view.RenderView(writer);

    // Convert to string
    return writer.ToString();
}

But when the following line executes:

var view = (SparkView)engine.CreateInstance(descriptor);

I get the following error:

Dynamic view compilation failed.  An
  object reference is required for the
  non-static field, method, or property
  'DomainModel.Entities.Region.Id.get.

This is my partial view:

<ViewData Model="Region" />

    ${Region.RegionName}
        ${ Html.CheckBox("Active") }

It doesn't seem to recognise the model.

P.S. When I call the view from a parent view like so

<for each="var region in Model">
    <ActiveTranslationRegion Region="region" if="region.Active==true"></ActiveTranslationRegion>
</for>

It renders perfectly. What am I doing wrong?

Body:
Just from looking at it, I think the following line is the problem:

<ViewData Model="Region" />

Instead it should read:

<viewata model="Region" />

Note the lower case "model". This is because model is a special case since behind the scenes it performs a cast to a strongly typed viewmodel. The top one will define a variable called Model in the generated view class and assign the value Region to it. Using the lowercase option below will actually create a Model variable, but also cast it to strongly typed instance of Region that comes from the ViewData dictionary.

Note When using Model in the code though, like you did in the for each loop, it needs to be upper case which is correct in your case. Once again, this is the only special case because it's pulling a strongly typed model from the ViewData dictionary.

One other thing - <viewata model="Region" /> must be declared in the parent view, and it can only be defined once per page, so you cannot redefine it in a partial view. If it's a partial view, you should rather use it by passing in a part of the model like you have done in your second example above.

The reason for your exception above is because it's trying to get the Id property as a static item off the Region Type, rather than querying the Id property on your instance of Region as part of your viewmodel.

As a side note, the code to get where you want is a little mangled. You can find neater ways of doing what you want by checking out some of the Direct Usage Samples, but I understand this was probably just a spike to see it working... :)

Update in response to your follow up question/answer

I'm fairly sure that the problem is with passing the Region into the following call:

<ActiveTranslationRegion Region="region" if="region.Active==true">

... is again down to naming. Yes, you can only have one model per view as I said before, so what you need to do is remove the following from the top of your partial:

<viewdata model="Region" />

That's what's causing an issue. I would then rename the item going into your partial like so:

<ActiveTranslationRegion ActiveRegion="region" if="region.Active==true">

and then your partial would look like this:

<form action="/Translation/DeactivateRegion" class="ui-widget-content active-translation-region-widget">
    <input type="hidden" name="Id" value="${ActiveRegion.Id}" />
    <label class="region-name">${ ActiveRegion.RegionName }</label>
    <input class="deactivate-region-button" type="image" src=${Url.Content("~/Content/Images/Deactivate.png")} alt="Deactivate" />
</form>

Note I'm using ActiveRegion because in the Spark parser, ActiveRegion gets declared as a variable and assigned the value of region in the current scope as you loop through the for loop. No need to stick religiously to the model - because you've gone and passed in a piece of the model now that you've declared as ActiveRegion. Oh, and you could stick with the name Region if you really want, I just changed it to make a point, and because you've got a Type called Region in your code and I'm not a big fan of the quirky issues using the same name for a variable as a type can bring about. Plus it makes it a little clearer.

The disadvantage of calling the Html.RenderPartial method is not immediately obvious. One thing you lose is the 3-pass rendering that Spark provides. If you use the tag syntax (which is preferable) you'll be able to stack partials within partials to multiple levels down passing variables that feed each partial what they need down the stack. It gets really powerful - start thinking data grid type structures where rows and cells are individual partials that are fed the variables they need from the model, all kept nice and clean in separate manageable view files. Don't stop there though, start thinking about targeting header and footer content base on variables or three column layouts that create a dashboard that renders all sorts on individually stacked partials many levels deep.

You lose all of that flexibility when you use the bog standard ASP.NET MVC Helper method Html.RenderPartial() - careful of doing that, there's more than likely a solution like the one above.

Let me know if that works...

All the best

Rob G


问:
What causes "resource temporarily unavailable" in v4l2
I have compiled adv7180 driver available here.

I am unloading the ov5642 cameradriver(which in my case is built-in) and loading the adv7180_tvin module and after I am loading mxcv4l2_capture module which creates video0 in /dev/.
(dmesg command says: "mxc camera on IPU2_CSI1 registered as video0")

But when I try to access video0 with v4l2-ctl I got a message "resource temporarily unavailable" or when I am using gstreamer I got message "Can not open /dev/video0" (but the device is really created).

Is that a problem in device tree settings or it can be caused by something else? Which tools should I use to find out what causes this issue?

My device tree settings look like below:

```<code>&i2c3{
adv7180: adv7180@20{
compatible = "adv,adv7180";
reg = <0x20>;
clocks = <&clks IMX6QDL_CLK_CKO2>;
clock-names = "csi_mclk";
pwn-gpios = <&gpio3 10 GPIO_ACTIVE_LOW>;
ipu_id = <1>;
csi_id = <1>;
mclk = <24000000>;
mclk_source = <0>;
pinctrl-names = "default";
pinctrl-0 = <&pinctrl_hummingboard2_parallel>;

cvbs = <1>;

};
};
</code>```

I need to add that before adv7180 I was using above settings for ov5642 camera (excluding cvbs setting) and everything worked properly.

EDIT:

Ok I got one clue.

When I load modules in dmesg message "mxc_v4l2_master_attach: ipu(0:1)/csi(1:1)/mipi(0:0) doesn't match" shows.
But it only happens when ipu_id=<1> in v4l2_cap device tree settings and in adv7180 settings. When i change ipu_id to ipu_id=<0> in v4l2 settings and adv7180 dmesg now shows "parallel attach to IPU1 CSI1 and I can access the /dev/video0 succesfully with v4l2-ctl tool.

But In my case there is only one possibility to use IPU2_CSI1.

Why can't I set IPU2 to adv7180 when I was using it successfully to ov5642 ?

答:
Thanks for Your answer.
My pinmuxing looks like this:

```<code> &iomuxc{
 hummingboard2{
  pinctrl_hummingboard2_parallel: hummingboard2_parallel{
 fsl,pins = <
 MX6QDL_PAD_EIM_A24__IPU2_CSI1_DATA19 0x0b0b1
 MX6QDL_PAD_EIM_A23__IPU2_CSI1_DATA18 0x0b0b1
 MX6QDL_PAD_EIM_A22__IPU2_CSI1_DATA17 0x0b0b1
 MX6QDL_PAD_EIM_A21__IPU2_CSI1_DATA16 0x0b0b1
 MX6QDL_PAD_EIM_A20__IPU2_CSI1_DATA15 0x0b0b1
 MX6QDL_PAD_EIM_A19__IPU2_CSI1_DATA14 0x0b0b1
 MX6QDL_PAD_EIM_A18__IPU2_CSI1_DATA13 0x0b0b1
 MX6QDL_PAD_EIM_A17__IPU2_CSI1_DATA12 0x0b0b1
 MX6QDL_PAD_EIM_DA11__IPU2_CSI1_HSYNC 0x0b0b1
 MX6QDL_PAD_EIM_DA12__IPU2_CSI1_VSYNC 0x0b0b1
 MX6QDL_PAD_EIM_A16__IPU2_CSI1_PIXCLK 0x0b0b1

 MX6QDL_PAD_EIM_DA10__GPIO3_IO10 0x400130b1
 >;
 };
 };
 };
</code>```

and it's been working succesively with ov5642 camera.
No I see that the adv7180 driver does not take an ipu_id as an argument from device tree so I think it is using the default ipu which is (I think) IPU1.

I've been playing arround how to change settings in IOMUXC_GPR1. Bit 20 needs to be set ("enable parallel interface to IPU2 CSI1). But have got no more ideas how to do it in device tree.

Body:
I have compiled adv7180 driver available here.

I am unloading the ov5642 cameradriver(which in my case is built-in) and loading the adv7180_tvin module and after I am loading mxcv4l2_capture module which creates video0 in /dev/.
(dmesg command says: "mxc camera on IPU2_CSI1 registered as video0")

But when I try to access video0 with v4l2-ctl I got a message "resource temporarily unavailable" or when I am using gstreamer I got message "Can not open /dev/video0" (but the device is really created).

Is that a problem in device tree settings or it can be caused by something else? Which tools should I use to find out what causes this issue?

My device tree settings look like below:

&i2c3{
adv7180: adv7180@20{
compatible = "adv,adv7180";
reg = <0x20>;
clocks = <&clks IMX6QDL_CLK_CKO2>;
clock-names = "csi_mclk";
pwn-gpios = <&gpio3 10 GPIO_ACTIVE_LOW>;
ipu_id = <1>;
csi_id = <1>;
mclk = <24000000>;
mclk_source = <0>;
pinctrl-names = "default";
pinctrl-0 = <&pinctrl_hummingboard2_parallel>;

cvbs = <1>;

};
};

I need to add that before adv7180 I was using above settings for ov5642 camera (excluding cvbs setting) and everything worked properly.

EDIT:

Ok I got one clue.

When I load modules in dmesg message "mxc_v4l2_master_attach: ipu(0:1)/csi(1:1)/mipi(0:0) doesn't match" shows.
But it only happens when ipu_id=<1> in v4l2_cap device tree settings and in adv7180 settings. When i change ipu_id to ipu_id=<0> in v4l2 settings and adv7180 dmesg now shows "parallel attach to IPU1 CSI1 and I can access the /dev/video0 succesfully with v4l2-ctl tool.

But In my case there is only one possibility to use IPU2_CSI1.

Why can't I set IPU2 to adv7180 when I was using it successfully to ov5642 ?

Body:
Thanks for Your answer.
My pinmuxing looks like this:

 &iomuxc{
 hummingboard2{
  pinctrl_hummingboard2_parallel: hummingboard2_parallel{
 fsl,pins = <
 MX6QDL_PAD_EIM_A24__IPU2_CSI1_DATA19 0x0b0b1
 MX6QDL_PAD_EIM_A23__IPU2_CSI1_DATA18 0x0b0b1
 MX6QDL_PAD_EIM_A22__IPU2_CSI1_DATA17 0x0b0b1
 MX6QDL_PAD_EIM_A21__IPU2_CSI1_DATA16 0x0b0b1
 MX6QDL_PAD_EIM_A20__IPU2_CSI1_DATA15 0x0b0b1
 MX6QDL_PAD_EIM_A19__IPU2_CSI1_DATA14 0x0b0b1
 MX6QDL_PAD_EIM_A18__IPU2_CSI1_DATA13 0x0b0b1
 MX6QDL_PAD_EIM_A17__IPU2_CSI1_DATA12 0x0b0b1
 MX6QDL_PAD_EIM_DA11__IPU2_CSI1_HSYNC 0x0b0b1
 MX6QDL_PAD_EIM_DA12__IPU2_CSI1_VSYNC 0x0b0b1
 MX6QDL_PAD_EIM_A16__IPU2_CSI1_PIXCLK 0x0b0b1

 MX6QDL_PAD_EIM_DA10__GPIO3_IO10 0x400130b1
 >;
 };
 };
 };

and it's been working succesively with ov5642 camera.
No I see that the adv7180 driver does not take an ipu_id as an argument from device tree so I think it is using the default ipu which is (I think) IPU1.

I've been playing arround how to change settings in IOMUXC_GPR1. Bit 20 needs to be set ("enable parallel interface to IPU2 CSI1). But have got no more ideas how to do it in device tree.


问:
keyboard search button enter
i have a employees form that contain button i i start my project when i want to search i have to click by mouse arrow on search can i choose another option by clicking enter button for search for more details for my project i'm using visual studio 2017 c# forms if any detail is missing please just notice

答:
The easiest way is to set your Form's AcceptButton property to your save button and you will get the 'enter to click' behavior by default. You can either set it through the designer or in you form constructor code:

```<code>this.AcceptButton = this.YourSaveButton;
</code>```

Another option is to set the KeyPreview property to True on the Form. From here you can handle KeyDown events and look for the 'enter' event to handle the button click.

Title: keyboard search button enter

Body:
The easiest way is to set your Form's AcceptButton property to your save button and you will get the 'enter to click' behavior by default. You can either set it through the designer or in you form constructor code:

this.AcceptButton = this.YourSaveButton;

Another option is to set the KeyPreview property to True on the Form. From here you can handle KeyDown events and look for the 'enter' event to handle the button click.


问:
Seaborn – how to interpret the values of the x-axis in a distplot?
I have a dataframe in which each row represents a date where a number of events were logged in a database.

Every event has a date it concerns, so for example an event that was logged on 2017-02-03 might belong to 2017-02-02 (meaning it was logged the day after it happened).

I'm trying to visualize the distribution of each column in a distplot, to get an idea of the distance between when an event was logged, and the date it concerns ("Do people log events on the same day, the day after, or even later?").

So far I've made a function that iterates over each column and plots it into a seaborn distplot.

```<code>def plot(dates):
    plt.figure(figsize=(45,25))
    for date in dates:
        sns.distplot(df[date], kde=False, bins=len(dates))
    return
</code>```

The plot then looks like this:

However, I can't understand how to interpret the values on the x-axis.

It shows a range from 0 - 3500, what does that mean?

Are there any other better ways to visualize this?

答:
sns.distplot is a histogram. That means that it shows how often a certain value falls into a certain bin.

Here, you calculate the histogram of every column. So in the plot you find how often a certain value occurs in this column. "How often" is the y-axis, the value is on the x axis.

Because you're doing it for every one of the n columns of the dataframe, you end up with n different histograms (each with a different color).

For example, there is only one value above 3000 in each column, therfore you see a small bar around 3000 in the plot. On the other hand there are many values between 0 and 100 in each column, so you see a large bar around 0.

Body:
I have a dataframe in which each row represents a date where a number of events were logged in a database.

Every event has a date it concerns, so for example an event that was logged on 2017-02-03 might belong to 2017-02-02 (meaning it was logged the day after it happened).

I'm trying to visualize the distribution of each column in a distplot, to get an idea of the distance between when an event was logged, and the date it concerns ("Do people log events on the same day, the day after, or even later?").

So far I've made a function that iterates over each column and plots it into a seaborn distplot.

def plot(dates):
    plt.figure(figsize=(45,25))
    for date in dates:
        sns.distplot(df[date], kde=False, bins=len(dates))
    return

The plot then looks like this:

However, I can't understand how to interpret the values on the x-axis.

It shows a range from 0 - 3500, what does that mean?

Are there any other better ways to visualize this?


问:
Error when enabling auto login of macOS app using a helper
I'm trying to have my app auto launch on login following Tim's tutorial: http://blog.timschroeder.net/2012/07/03/the-launch-at-login-sandbox-project/

I followed the instructions to the letter but I'm getting an error when I re-login to my computer as follows:

```<code>Jan 10 12:55:01 pc61 com.apple.xpc.launchd[1] (com.myApp.macgap.helper[25725]): Could not resolve CFBundleIdentifier specified by service: -10814: com.myApp.macgap.helper
Jan 10 12:55:01 pc61 com.apple.xpc.launchd[1] (com.myApp.macgap.helper): Service only ran for 0 seconds. Pushing respawn out by 10 seconds.
</code>```

To outline:

I have my main app called "myApp" (ID: com.myApp.macgap )

In that app I have a helper app with ID: com.myApp.macgap.helper

When you launch the main app and go to preferences, you have an option to enable auto login (to fit to the Apple compliance rules)

I log out of my computer, log back in and look at the console to see what's going on (that's how I get the code above)

Another point worth mentioning, is when I do "Show package content" on the app and double click the helper app, it does launch the main app...

答:
I was struggling with this for hours. I had many apps with auto login but a new one just did not want to work.

Strangely this worked on the development machine:

Build App as normal

Move it to Application directory

Clean Xcode (CMD+k)!!

Enable auto login in the app.

Logout Login

I accidentally noticed that the system started the app (it tries in every 10 sec) when I clean Xcode :)

Body:
I'm trying to have my app auto launch on login following Tim's tutorial: http://blog.timschroeder.net/2012/07/03/the-launch-at-login-sandbox-project/

I followed the instructions to the letter but I'm getting an error when I re-login to my computer as follows:

Jan 10 12:55:01 pc61 com.apple.xpc.launchd[1] (com.myApp.macgap.helper[25725]): Could not resolve CFBundleIdentifier specified by service: -10814: com.myApp.macgap.helper
Jan 10 12:55:01 pc61 com.apple.xpc.launchd[1] (com.myApp.macgap.helper): Service only ran for 0 seconds. Pushing respawn out by 10 seconds.

To outline:

I have my main app called "myApp" (ID: com.myApp.macgap )

In that app I have a helper app with ID: com.myApp.macgap.helper

When you launch the main app and go to preferences, you have an option to enable auto login (to fit to the Apple compliance rules)

I log out of my computer, log back in and look at the console to see what's going on (that's how I get the code above)

Another point worth mentioning, is when I do "Show package content" on the app and double click the helper app, it does launch the main app...


问:
How to bind dropdownlist data to complex class?
I am using asp.net mvc 2.0(default binding model) and I have this problem.

I have a strongly typed view that has a dropdownlist

```<code><%= Html.DropDownList("List", "-----")%>
</code>```

Now I have a model class like

```<code>Public class Test
{
    public List { get; set; }
    public string Selected {get; set;}

    public Test()
    {
           List = new List();
           selected = "";
    }
}
</code>```

Now I have in my controller this

```<code>    public ActionResult TestAction()
    {
        Test ViewModel = new Test();
        ViewModel.List = new SelectList(GetList(), "value", "text", "selected");
        return View(Test);
    }

   [AcceptVerbs(HttpVerbs.Post)]
    public ActionResult TestAction(Test ViewModel)
    {
          return View();
    }
</code>```

Now when I load up the TestAction page for the first time it populates the dropdown list as expected.

Now I want to post the selected value back to the server(the dropdownlist is within a form tag with some other textboxes). So I am trying to bind it automatically when it comes in as seen (Test ViewModel)

However I get this big nasty error.

```<code>Server Error in '/' Application.
No parameterless constructor defined for this object.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

Exception Details: System.MissingMethodException: No parameterless constructor defined for this object.

Source Error:

An unhandled exception was generated during the execution of the current web request. Information regarding the origin and location of the exception can be identified using the exception stack trace below.

Stack Trace:

[MissingMethodException: No parameterless constructor defined for this object.]
   System.RuntimeTypeHandle.CreateInstance(RuntimeType type, Boolean publicOnly, Boolean noCheck, Boolean& canBeCached, RuntimeMethodHandleInternal& ctor, Boolean& bNeedSecurityCheck) +0
   System.RuntimeType.CreateInstanceSlow(Boolean publicOnly, Boolean skipCheckThis, Boolean fillCache) +98
   System.RuntimeType.CreateInstanceDefaultCtor(Boolean publicOnly, Boolean skipVisibilityChecks, Boolean skipCheckThis, Boolean fillCache) +241
   System.Activator.CreateInstance(Type type, Boolean nonPublic) +69
   System.Activator.CreateInstance(Type type) +6
   System.Web.Mvc.DefaultModelBinder.CreateModel(ControllerContext controllerContext, ModelBindingContext bindingContext, Type modelType) +403
   System.Web.Mvc.DefaultModelBinder.BindSimpleModel(ControllerContext controllerContext, ModelBindingContext bindingContext, ValueProviderResult valueProviderResult) +544
   System.Web.Mvc.DefaultModelBinder.BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext) +479
   System.Web.Mvc.DefaultModelBinder.GetPropertyValue(ControllerContext controllerContext, ModelBindingContext bindingContext, PropertyDescriptor propertyDescriptor, IModelBinder propertyBinder) +45
   System.Web.Mvc.DefaultModelBinder.BindProperty(ControllerContext controllerContext, ModelBindingContext bindingContext, PropertyDescriptor propertyDescriptor) +658
   System.Web.Mvc.DefaultModelBinder.BindProperties(ControllerContext controllerContext, ModelBindingContext bindingContext) +147
   System.Web.Mvc.DefaultModelBinder.BindComplexElementalModel(ControllerContext controllerContext, ModelBindingContext bindingContext, Object model) +98
   System.Web.Mvc.DefaultModelBinder.BindComplexModel(ControllerContext controllerContext, ModelBindingContext bindingContext) +2504
   System.Web.Mvc.DefaultModelBinder.BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext) +548
   System.Web.Mvc.ControllerActionInvoker.GetParameterValue(ControllerContext controllerContext, ParameterDescriptor parameterDescriptor) +474
   System.Web.Mvc.ControllerActionInvoker.GetParameterValues(ControllerContext controllerContext, ActionDescriptor actionDescriptor) +181
   System.Web.Mvc.ControllerActionInvoker.InvokeAction(ControllerContext controllerContext, String actionName) +830
   System.Web.Mvc.Controller.ExecuteCore() +136
   System.Web.Mvc.ControllerBase.Execute(RequestContext requestContext) +111
   System.Web.Mvc.ControllerBase.System.Web.Mvc.IController.Execute(RequestContext requestContext) +39
   System.Web.Mvc.<>c__DisplayClass8.<BeginProcessRequest>b__4() +65
   System.Web.Mvc.Async.<>c__DisplayClass1.<MakeVoidDelegate>b__0() +44
   System.Web.Mvc.Async.<>c__DisplayClass8`1.<BeginSynchronous>b__7(IAsyncResult _) +42
   System.Web.Mvc.Async.WrappedAsyncResult`1.End() +141
   System.Web.Mvc.Async.AsyncResultWrapper.End(IAsyncResult asyncResult, Object tag) +54
   System.Web.Mvc.Async.AsyncResultWrapper.End(IAsyncResult asyncResult, Object tag) +40
   System.Web.Mvc.MvcHandler.EndProcessRequest(IAsyncResult asyncResult) +52
   System.Web.Mvc.MvcHandler.System.Web.IHttpAsyncHandler.EndProcessRequest(IAsyncResult result) +38
   System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +8836913
   System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +184
</code>```

So how can I do this?

答:
THANK YOU Shaharyar!! (and Oded... your "better solution" gives the same error as he originally posted about)

```<code><%= Html.DropDownListFor(model => model.Selected, Model.List) %>
</code>```

Works like a charm, now time for me to figure out why.

Body:
I am using asp.net mvc 2.0(default binding model) and I have this problem.

I have a strongly typed view that has a dropdownlist

<%= Html.DropDownList("List", "-----")%>

Now I have a model class like

Public class Test
{
    public List { get; set; }
    public string Selected {get; set;}

    public Test()
    {
           List = new List();
           selected = "";
    }
}

Now I have in my controller this

    public ActionResult TestAction()
    {
        Test ViewModel = new Test();
        ViewModel.List = new SelectList(GetList(), "value", "text", "selected");
        return View(Test);
    }

   [AcceptVerbs(HttpVerbs.Post)]
    public ActionResult TestAction(Test ViewModel)
    {
          return View();
    }

Now when I load up the TestAction page for the first time it populates the dropdown list as expected.

Now I want to post the selected value back to the server(the dropdownlist is within a form tag with some other textboxes). So I am trying to bind it automatically when it comes in as seen (Test ViewModel)

However I get this big nasty error.

Server Error in '/' Application.
No parameterless constructor defined for this object.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

Exception Details: System.MissingMethodException: No parameterless constructor defined for this object.

Source Error:

An unhandled exception was generated during the execution of the current web request. Information regarding the origin and location of the exception can be identified using the exception stack trace below.

Stack Trace:

[MissingMethodException: No parameterless constructor defined for this object.]
   System.RuntimeTypeHandle.CreateInstance(RuntimeType type, Boolean publicOnly, Boolean noCheck, Boolean& canBeCached, RuntimeMethodHandleInternal& ctor, Boolean& bNeedSecurityCheck) +0
   System.RuntimeType.CreateInstanceSlow(Boolean publicOnly, Boolean skipCheckThis, Boolean fillCache) +98
   System.RuntimeType.CreateInstanceDefaultCtor(Boolean publicOnly, Boolean skipVisibilityChecks, Boolean skipCheckThis, Boolean fillCache) +241
   System.Activator.CreateInstance(Type type, Boolean nonPublic) +69
   System.Activator.CreateInstance(Type type) +6
   System.Web.Mvc.DefaultModelBinder.CreateModel(ControllerContext controllerContext, ModelBindingContext bindingContext, Type modelType) +403
   System.Web.Mvc.DefaultModelBinder.BindSimpleModel(ControllerContext controllerContext, ModelBindingContext bindingContext, ValueProviderResult valueProviderResult) +544
   System.Web.Mvc.DefaultModelBinder.BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext) +479
   System.Web.Mvc.DefaultModelBinder.GetPropertyValue(ControllerContext controllerContext, ModelBindingContext bindingContext, PropertyDescriptor propertyDescriptor, IModelBinder propertyBinder) +45
   System.Web.Mvc.DefaultModelBinder.BindProperty(ControllerContext controllerContext, ModelBindingContext bindingContext, PropertyDescriptor propertyDescriptor) +658
   System.Web.Mvc.DefaultModelBinder.BindProperties(ControllerContext controllerContext, ModelBindingContext bindingContext) +147
   System.Web.Mvc.DefaultModelBinder.BindComplexElementalModel(ControllerContext controllerContext, ModelBindingContext bindingContext, Object model) +98
   System.Web.Mvc.DefaultModelBinder.BindComplexModel(ControllerContext controllerContext, ModelBindingContext bindingContext) +2504
   System.Web.Mvc.DefaultModelBinder.BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext) +548
   System.Web.Mvc.ControllerActionInvoker.GetParameterValue(ControllerContext controllerContext, ParameterDescriptor parameterDescriptor) +474
   System.Web.Mvc.ControllerActionInvoker.GetParameterValues(ControllerContext controllerContext, ActionDescriptor actionDescriptor) +181
   System.Web.Mvc.ControllerActionInvoker.InvokeAction(ControllerContext controllerContext, String actionName) +830
   System.Web.Mvc.Controller.ExecuteCore() +136
   System.Web.Mvc.ControllerBase.Execute(RequestContext requestContext) +111
   System.Web.Mvc.ControllerBase.System.Web.Mvc.IController.Execute(RequestContext requestContext) +39
   System.Web.Mvc.<>c__DisplayClass8.<BeginProcessRequest>b__4() +65
   System.Web.Mvc.Async.<>c__DisplayClass1.<MakeVoidDelegate>b__0() +44
   System.Web.Mvc.Async.<>c__DisplayClass8`1.<BeginSynchronous>b__7(IAsyncResult _) +42
   System.Web.Mvc.Async.WrappedAsyncResult`1.End() +141
   System.Web.Mvc.Async.AsyncResultWrapper.End(IAsyncResult asyncResult, Object tag) +54
   System.Web.Mvc.Async.AsyncResultWrapper.End(IAsyncResult asyncResult, Object tag) +40
   System.Web.Mvc.MvcHandler.EndProcessRequest(IAsyncResult asyncResult) +52
   System.Web.Mvc.MvcHandler.System.Web.IHttpAsyncHandler.EndProcessRequest(IAsyncResult result) +38
   System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +8836913
   System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +184

So how can I do this?

Body:
THANK YOU Shaharyar!! (and Oded... your "better solution" gives the same error as he originally posted about)

<%= Html.DropDownListFor(model => model.Selected, Model.List) %>

Works like a charm, now time for me to figure out why.


问:
Can you get the number of lines of code from a GitHub repository?
In a GitHub repository you can see “language statistics”, which displays the percentage of the project that’s written in a language. It doesn’t, however, display how many lines of code the project consists of. Often, I want to quickly get an impression of the scale and complexity of a project, and the count of lines of code can give a good first impression. 500 lines of code implies a relatively simple project, 100,000 lines of code implies a very large/complicated project.

So, is it possible to get the lines of code written in the various languages from a GitHub repository, preferably without cloning it?

The question “Count number of lines in a git repository” asks how to count the lines of code in a local Git repository, but:

You have to clone the project, which could be massive. Cloning a project like Wine, for example, takes ages.

You would count lines in files that wouldn’t necessarily be code, like i13n files.

If you count just (for example) Ruby files, you’d potentially miss massive amount of code in other languages, like JavaScript. You’d have to know beforehand which languages the project uses. You’d also have to repeat the count for every language the project uses.

All in all, this is potentially far too time-intensive for “quickly checking the scale of a project”.

答:
You can use GitHub API to get the sloc like the following function

```<code>function getSloc(repo, tries) {

    //repo is the repo's path
    if (!repo) {
        return Promise.reject(new Error("No repo provided"));
    }

    //GitHub's API may return an empty object the first time it is accessed
    //We can try several times then stop
    if (tries === 0) {
        return Promise.reject(new Error("Too many tries"));
    }

    let url = "https://api.github.com/repos" + repo + "/stats/code_frequency";

    return fetch(url)
        .then(x => x.json())
        .then(x => x.reduce((total, changes) => total + changes[1] + changes[2], 0))
        .catch(err => getSloc(repo, tries - 1));
}
</code>```

Personally I made an chrome extension which shows the number of SLOC on both github project list and project detail page. You can also set your personal access token to access private repositories and bypass the api rate limit.

You can download from here https://chrome.google.com/webstore/detail/github-sloc/fkjjjamhihnjmihibcmdnianbcbccpnn

Source code is available here https://github.com/martianyi/github-sloc

Body:
You can use GitHub API to get the sloc like the following function

function getSloc(repo, tries) {

    //repo is the repo's path
    if (!repo) {
        return Promise.reject(new Error("No repo provided"));
    }

    //GitHub's API may return an empty object the first time it is accessed
    //We can try several times then stop
    if (tries === 0) {
        return Promise.reject(new Error("Too many tries"));
    }

    let url = "https://api.github.com/repos" + repo + "/stats/code_frequency";

    return fetch(url)
        .then(x => x.json())
        .then(x => x.reduce((total, changes) => total + changes[1] + changes[2], 0))
        .catch(err => getSloc(repo, tries - 1));
}

Personally I made an chrome extension which shows the number of SLOC on both github project list and project detail page. You can also set your personal access token to access private repositories and bypass the api rate limit.

You can download from here https://chrome.google.com/webstore/detail/github-sloc/fkjjjamhihnjmihibcmdnianbcbccpnn

Source code is available here https://github.com/martianyi/github-sloc


问:
Is there a shortcut to move between header and source file in VC++?
This is a feature I have grown accustomed to in Eclipse (Ctrl+Tab). Is there an equivalent in Visual C++?

答:
You could add this macro to your VS config (via Tools -> Macros -> Macro Explorer) then assign a hotkey to it (via Tools -> Options -> Environment -> Keyboard).

I only just wrote it (been meaning to try this for ages!) but it seems to work so far, in both VS2008 and VS2010.

Since it's a macro you can edit it to include whatever rules you want (e.g. looking in other folders, or special naming rules if you have a single header shared by multiple cpp files or similar).

Here's the macro (I'm sure it could be better written; I'm unfamiliar with the VS objects and only realised macros were using .Net about half-way through writing the thing :)):

```<code>Sub FileSwitch()
    Try
        Dim CurrentPath As String = DTE.ActiveDocument.FullName
        Dim OtherPath As String

        If (IO.Path.HasExtension(CurrentPath)) Then
            Dim CurrentExtension As String = IO.Path.GetExtension(CurrentPath)

            Select Case CurrentExtension
                Case ".h", ".hpp", ".hxx"
                    OtherPath = IO.Path.ChangeExtension(CurrentPath, ".cpp")
                    If (Not IO.File.Exists(OtherPath)) Then
                        OtherPath = IO.Path.ChangeExtension(CurrentPath, ".c")
                        If (Not IO.File.Exists(OtherPath)) Then
                            OtherPath = IO.Path.ChangeExtension(CurrentPath, ".cxx")
                        End If
                    End If
                Case ".cpp", ".c", ".cxx"
                    OtherPath = IO.Path.ChangeExtension(CurrentPath, ".h")
                    If (Not IO.File.Exists(OtherPath)) Then
                        OtherPath = IO.Path.ChangeExtension(CurrentPath, ".hpp")
                        If (Not IO.File.Exists(OtherPath)) Then
                            OtherPath = IO.Path.ChangeExtension(CurrentPath, ".hxx")
                        End If
                    End If
                Case Else
            End Select
            If (OtherPath <> Nothing) Then
                DTE.ItemOperations.OpenFile(OtherPath)
            End If
        End If

    Catch ex As System.Exception
        MsgBox(ex.Message)
    End Try
End Sub
</code>```

Here's a (very wide :)) screenshot showing what the macro editor and hotkey/options dialogs should look like, to help those not familiar with them:

Body:
You could add this macro to your VS config (via Tools -> Macros -> Macro Explorer) then assign a hotkey to it (via Tools -> Options -> Environment -> Keyboard).

I only just wrote it (been meaning to try this for ages!) but it seems to work so far, in both VS2008 and VS2010.

Since it's a macro you can edit it to include whatever rules you want (e.g. looking in other folders, or special naming rules if you have a single header shared by multiple cpp files or similar).

Here's the macro (I'm sure it could be better written; I'm unfamiliar with the VS objects and only realised macros were using .Net about half-way through writing the thing :)):

Sub FileSwitch()
    Try
        Dim CurrentPath As String = DTE.ActiveDocument.FullName
        Dim OtherPath As String

        If (IO.Path.HasExtension(CurrentPath)) Then
            Dim CurrentExtension As String = IO.Path.GetExtension(CurrentPath)

            Select Case CurrentExtension
                Case ".h", ".hpp", ".hxx"
                    OtherPath = IO.Path.ChangeExtension(CurrentPath, ".cpp")
                    If (Not IO.File.Exists(OtherPath)) Then
                        OtherPath = IO.Path.ChangeExtension(CurrentPath, ".c")
                        If (Not IO.File.Exists(OtherPath)) Then
                            OtherPath = IO.Path.ChangeExtension(CurrentPath, ".cxx")
                        End If
                    End If
                Case ".cpp", ".c", ".cxx"
                    OtherPath = IO.Path.ChangeExtension(CurrentPath, ".h")
                    If (Not IO.File.Exists(OtherPath)) Then
                        OtherPath = IO.Path.ChangeExtension(CurrentPath, ".hpp")
                        If (Not IO.File.Exists(OtherPath)) Then
                            OtherPath = IO.Path.ChangeExtension(CurrentPath, ".hxx")
                        End If
                    End If
                Case Else
            End Select
            If (OtherPath <> Nothing) Then
                DTE.ItemOperations.OpenFile(OtherPath)
            End If
        End If

    Catch ex As System.Exception
        MsgBox(ex.Message)
    End Try
End Sub

Here's a (very wide :)) screenshot showing what the macro editor and hotkey/options dialogs should look like, to help those not familiar with them:


问:
Node.js SELECT*FROM a table in a SQL database
My problem is that I can enter data from my input boxes into an SQL table, but the problem is that the text from the table will not show on the page i want to. What works is that the playlist page will show the a href links depending on how many playlists i have made just not the text.

I have left out the database details for security reasons.

playlist.jade

```<code>extends layout

block content
  h1= title
  p Welcome to #{title}

   h1 My Playlists
   br
   a(href='/login') Login
   br
   a(href='/users/createPlaylist') Create a new Playlists
   br
   a(href='/users/playlistCreated') test
   br

   for playlist, i in playlists
    a(href='/users/playlistCreated') | #{playlist.text}
    br
</code>```

users.js

```<code>var express = require('express');
var mysql = require('mysql');
var router = express.Router();

var dbConnectionInfo = {
  host : '',
  user : '',
  password : '',
  database : 'audio_collections'
};

router.get('/createPlaylist', function(req, res, next) {
  res.render('new_playlist');
});

router.get('/playlistCreated', function(req, res, next) {
  res.render('name_of_created_playlist');
});

router.get('/songCreated', function(req, res, next) {
  res.render('song_page');
});

router.get('/newSong', function(req, res, next) {
  res.render('new_song');
});

router.post('/newPlaylist', function(req, res, next) {

  var dbConnection = mysql.createConnection(dbConnectionInfo);
  dbConnection.connect();

  dbConnection.on('error', function(err) {
    if (err.code == 'PROTOCOL_SEQUENCE_TIMEOUT') {
      // Let's just ignore this
      console.log('Got a DB PROTOCOL_SEQUENCE_TIMEOUT Error ... ignoring ');
    } else {
      // I really should do something better here
      console.log('Got a DB Error: ', err);
    }
  });

  var playlist = {
    text:  req.body.thePlaylist
  };

  dbConnection.query('INSERT INTO Playlists (playlist_name) VALUES(?)',     [playlist.text], function(err, results, fields) {
// error will be an Error if one occurred during the query
// results will contain the results of the query
// fields will contain information about the returned results fields (if  any)
    if (err) {
      throw err;
    }

    // notice that results.insertId will give you the value of the AI (auto-increment) field
    playlist.id = results.insertId;

    // Going to convert my joke object to a JSON string a print it out to the console
    console.log(JSON.stringify(playlist));

    // Close the connection and make sure you do it BEFORE you redirect
    dbConnection.end();

    res.redirect('/');
  });

  router.post('/newSongAdded', function(req, res, next) {

  var dbConnection = mysql.createConnection(dbConnectionInfo);
  dbConnection.connect();

  dbConnection.on('error', function(err) {
    if (err.code == 'PROTOCOL_SEQUENCE_TIMEOUT') {
      // Let's just ignore this
      console.log('Got a DB PROTOCOL_SEQUENCE_TIMEOUT Error ... ignoring ');
    } else {
      // I really should do something better here
      console.log('Got a DB Error: ', err);
    }
  });

  var song = {
    text: req.body.theSong,
    url: req.body.theSongURL
  };

  dbConnection.query('INSERT INTO Songs (song_name, song_url) VALUES(?,?)',[song.text, song.url], function(err, results,fields) {
    // error will be an Error if one occurred during the query
    // results will contain the results of the query
    // fields will contain information about the returned results fields (if any)
    if (err) {
      throw err;
    }

    // notice that results.insertId will give you the value of the AI (auto-increment) field
    song.id = results.insertId;

    // Going to convert my joke object to a JSON string a print it out to the console
    console.log(JSON.stringify(song));

    // Close the connection and make sure you do it BEFORE you redirect
    dbConnection.end();

    res.redirect('/');
  });

 });
});

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

index.js

```<code>var express = require('express');
var mysql = require('mysql');
var router = express.Router();

var dbConnectionInfo = {
  host : '',
  user : '',
  password : '',
  database : 'audio_collections'
};

/* GET home page. */
router.get('/login', function(req, res, next) {
  res.render('login');
});

router.post('/login', function(req, res, next) {
  var username = req.body.username;

  username = username.trim();

  if (username.length == 0) {
    res.redirect('/login');
  }
  else {
    req.session.username = username;
    res.redirect('/');
  }
});

router.get('/', function(req, res, next) {
  var dbConnection = mysql.createConnection(dbConnectionInfo);
  dbConnection.connect();

  dbConnection.on('error', function(err) {
    if (err.code == 'PROTOCOL_SEQUENCE_TIMEOUT') {
      // Let's just ignore this
      console.log('Got a DB PROTOCOL_SEQUENCE_TIMEOUT Error ... ignoring ');
    } else {
      // I really should do something better here
      console.log('Got a DB Error: ', err);
    }
  });

  dbConnection.query('SELECT * FROM Playlists', function(err, results, fields){
    if (err) {
      throw err;
    }

    var allPlaylists = new Array();

    for (var i = 0; i < results.length; i++) {
      var playlist = {
        id: results[i].id,
        text: results[i].text
      };

      console.log(JSON.stringify(playlist));

      allPlaylists.push(playlist);
    }

    dbConnection.end();

    res.render('playlists', {playlists: allPlaylists});
  });

  router.get('/users/playlistCreated', function(req, res, next) {
    var dbConnection = mysql.createConnection(dbConnectionInfo);
    dbConnection.connect();

    dbConnection.on('error', function(err) {
      if (err.code == 'PROTOCOL_SEQUENCE_TIMEOUT') {
        // Let's just ignore this
        console.log('Got a DB PROTOCOL_SEQUENCE_TIMEOUT Error ... ignoring ');
      } else {
        // I really should do something better here
        console.log('Got a DB Error: ', err);
      }
    });

    dbConnection.query('SELECT * FROM Songs', function(err, results, fields){
      if (err) {
        throw err;
      }

      var allSongs = new Array();

      for (var i = 0; i < results.length; i++) {
        var song = {};
        song.id = results[i].id;
        song.text = results[i].text;
        song.url = results[i].url;

        console.log(JSON.stringify(song));

        allSongs.push(song);
      }

      dbConnection.end();

      res.render('name_of_created_playlist', {songs: allSongs});
    });
  });
});

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

new_playlist.jade

```<code>extends layout

block content

    form(method='POST', action='/users/newPlaylist')
      div
        label(for='thePlaylist') Name of Playlist
        div
          textarea(type='text', name='thePlaylist')
          br
          input(type='submit', name='Add new Playlist')

    a(href='/') Cancel
</code>```

Here is the database and table setups

database and table setup

I would really appreciate the help and I have been stuck on this for a week now.

答:
Got it fixed I didnt need the for loops inside my array

Only needed var allPlaylist = results; Since results is an array already

Body:
My problem is that I can enter data from my input boxes into an SQL table, but the problem is that the text from the table will not show on the page i want to. What works is that the playlist page will show the a href links depending on how many playlists i have made just not the text.

I have left out the database details for security reasons.

playlist.jade

extends layout

block content
  h1= title
  p Welcome to #{title}

   h1 My Playlists
   br
   a(href='/login') Login
   br
   a(href='/users/createPlaylist') Create a new Playlists
   br
   a(href='/users/playlistCreated') test
   br

   for playlist, i in playlists
    a(href='/users/playlistCreated') | #{playlist.text}
    br

users.js

var express = require('express');
var mysql = require('mysql');
var router = express.Router();

var dbConnectionInfo = {
  host : '',
  user : '',
  password : '',
  database : 'audio_collections'
};

router.get('/createPlaylist', function(req, res, next) {
  res.render('new_playlist');
});

router.get('/playlistCreated', function(req, res, next) {
  res.render('name_of_created_playlist');
});

router.get('/songCreated', function(req, res, next) {
  res.render('song_page');
});

router.get('/newSong', function(req, res, next) {
  res.render('new_song');
});

router.post('/newPlaylist', function(req, res, next) {

  var dbConnection = mysql.createConnection(dbConnectionInfo);
  dbConnection.connect();

  dbConnection.on('error', function(err) {
    if (err.code == 'PROTOCOL_SEQUENCE_TIMEOUT') {
      // Let's just ignore this
      console.log('Got a DB PROTOCOL_SEQUENCE_TIMEOUT Error ... ignoring ');
    } else {
      // I really should do something better here
      console.log('Got a DB Error: ', err);
    }
  });

  var playlist = {
    text:  req.body.thePlaylist
  };

  dbConnection.query('INSERT INTO Playlists (playlist_name) VALUES(?)',     [playlist.text], function(err, results, fields) {
// error will be an Error if one occurred during the query
// results will contain the results of the query
// fields will contain information about the returned results fields (if  any)
    if (err) {
      throw err;
    }

    // notice that results.insertId will give you the value of the AI (auto-increment) field
    playlist.id = results.insertId;

    // Going to convert my joke object to a JSON string a print it out to the console
    console.log(JSON.stringify(playlist));

    // Close the connection and make sure you do it BEFORE you redirect
    dbConnection.end();

    res.redirect('/');
  });

  router.post('/newSongAdded', function(req, res, next) {

  var dbConnection = mysql.createConnection(dbConnectionInfo);
  dbConnection.connect();

  dbConnection.on('error', function(err) {
    if (err.code == 'PROTOCOL_SEQUENCE_TIMEOUT') {
      // Let's just ignore this
      console.log('Got a DB PROTOCOL_SEQUENCE_TIMEOUT Error ... ignoring ');
    } else {
      // I really should do something better here
      console.log('Got a DB Error: ', err);
    }
  });

  var song = {
    text: req.body.theSong,
    url: req.body.theSongURL
  };

  dbConnection.query('INSERT INTO Songs (song_name, song_url) VALUES(?,?)',[song.text, song.url], function(err, results,fields) {
    // error will be an Error if one occurred during the query
    // results will contain the results of the query
    // fields will contain information about the returned results fields (if any)
    if (err) {
      throw err;
    }

    // notice that results.insertId will give you the value of the AI (auto-increment) field
    song.id = results.insertId;

    // Going to convert my joke object to a JSON string a print it out to the console
    console.log(JSON.stringify(song));

    // Close the connection and make sure you do it BEFORE you redirect
    dbConnection.end();

    res.redirect('/');
  });

 });
});

module.exports = router;

index.js

var express = require('express');
var mysql = require('mysql');
var router = express.Router();

var dbConnectionInfo = {
  host : '',
  user : '',
  password : '',
  database : 'audio_collections'
};

/* GET home page. */
router.get('/login', function(req, res, next) {
  res.render('login');
});

router.post('/login', function(req, res, next) {
  var username = req.body.username;

  username = username.trim();

  if (username.length == 0) {
    res.redirect('/login');
  }
  else {
    req.session.username = username;
    res.redirect('/');
  }
});

router.get('/', function(req, res, next) {
  var dbConnection = mysql.createConnection(dbConnectionInfo);
  dbConnection.connect();

  dbConnection.on('error', function(err) {
    if (err.code == 'PROTOCOL_SEQUENCE_TIMEOUT') {
      // Let's just ignore this
      console.log('Got a DB PROTOCOL_SEQUENCE_TIMEOUT Error ... ignoring ');
    } else {
      // I really should do something better here
      console.log('Got a DB Error: ', err);
    }
  });

  dbConnection.query('SELECT * FROM Playlists', function(err, results, fields){
    if (err) {
      throw err;
    }

    var allPlaylists = new Array();

    for (var i = 0; i < results.length; i++) {
      var playlist = {
        id: results[i].id,
        text: results[i].text
      };

      console.log(JSON.stringify(playlist));

      allPlaylists.push(playlist);
    }

    dbConnection.end();

    res.render('playlists', {playlists: allPlaylists});
  });

  router.get('/users/playlistCreated', function(req, res, next) {
    var dbConnection = mysql.createConnection(dbConnectionInfo);
    dbConnection.connect();

    dbConnection.on('error', function(err) {
      if (err.code == 'PROTOCOL_SEQUENCE_TIMEOUT') {
        // Let's just ignore this
        console.log('Got a DB PROTOCOL_SEQUENCE_TIMEOUT Error ... ignoring ');
      } else {
        // I really should do something better here
        console.log('Got a DB Error: ', err);
      }
    });

    dbConnection.query('SELECT * FROM Songs', function(err, results, fields){
      if (err) {
        throw err;
      }

      var allSongs = new Array();

      for (var i = 0; i < results.length; i++) {
        var song = {};
        song.id = results[i].id;
        song.text = results[i].text;
        song.url = results[i].url;

        console.log(JSON.stringify(song));

        allSongs.push(song);
      }

      dbConnection.end();

      res.render('name_of_created_playlist', {songs: allSongs});
    });
  });
});

module.exports = router;

new_playlist.jade

extends layout

block content

    form(method='POST', action='/users/newPlaylist')
      div
        label(for='thePlaylist') Name of Playlist
        div
          textarea(type='text', name='thePlaylist')
          br
          input(type='submit', name='Add new Playlist')

    a(href='/') Cancel

Here is the database and table setups

database and table setup

I would really appreciate the help and I have been stuck on this for a week now.


问:
How do I move a file into a compiled .jar file using Java?
I'm making a file import system, and I can't move files into the compiled .jar file the application is in.
Here's what I'm trying to do:</p>

```<code>Path FROM = Paths.get(filePath.getText());
Path TO = Paths.get("C:\\Users\\" + System.getProperty("user.name") +
"\\AppData\\Roaming\\.minecraft\\mods\\music_crafter-1.0\\src\\main\\resources\\assets\\music_crafter\\sounds\\block\\music_player");
                                       //jar file
Files.move(FROM, TO.resolve(FROM.getFileName()), StandardCopyOption.REPLACE_EXISTING);
</code>```

答:
You need to handle the jar file internally. A Jar is not a directory, it is a compressed container file (pretty much a ZIP file with a different extension).

To do this, given that you are on Java 6, you have 2 options:

Unzip the contents to a temporary working directory (there are built
in APIs for this, or use a library such as Apache Commons Compress)
do your work (copying, deleting, etc) and then re-zip.

Make external command line calls to the Jar utilities that come with
Java

Of those, only (1) makes any real sense.

A third option would be available if you could up your Java to 7+ which would be:
 3. Use a Zip File System Provider to to treat it as a file system in code

All that said, however:

As per comments on your question, you really might want to look at if this something you need to do at all?  Why do you need to insert into existing jars?    If this is 'external' data, it would be much better in a separate resource location/container, not the application jar.

Body:
I'm making a file import system, and I can't move files into the compiled .jar file the application is in.
Here's what I'm trying to do:

Path FROM = Paths.get(filePath.getText());
Path TO = Paths.get("C:\\Users\\" + System.getProperty("user.name") +
"\\AppData\\Roaming\\.minecraft\\mods\\music_crafter-1.0\\src\\main\\resources\\assets\\music_crafter\\sounds\\block\\music_player");
                                       //jar file
Files.move(FROM, TO.resolve(FROM.getFileName()), StandardCopyOption.REPLACE_EXISTING);


问:
Smart association of graphs where one is faceted - ggplot2
I want to combine these two graphs :

```<code>p1 <- ggplot(iris, aes(Sepal.Length)) +
  geom_density() +
  facet_wrap(~ Species)

p2 <- ggplot(iris, aes(Sepal.Length)) +
  geom_density()
</code>```

To combine, I do :

```<code>multiplot(p1, p2, cols = 2)
</code>```

But it is not the desired shape.

I would like the graph p2 has the same dimensions than others and is situated just next to the last faceted graph.

Thanks for help

答:
Not sure if this is applicable in you generic case, but with facet_grid instead of facet_wrap, you can use the margins argument:

```<code>library(ggplot2)

ggplot(iris, aes(Sepal.Length)) +
    geom_density() +
    facet_grid(. ~ Species, margins = T)
</code>```

If you question is more generic the answer probably lies in grid.arrange.

Something like this could be a start:

```<code>library(gridExtra)

grid.arrange(arrangeGrob(p1, p2,
                         widths = c(3,1),
                         heights = c(1,20),
                         layout_matrix = matrix(c(1,1,NA,2),2)))
</code>```

As you can see there are several problems (different axes, top strip), but working with grid could gets complicated quickly.

Body:
I want to combine these two graphs :

p1 <- ggplot(iris, aes(Sepal.Length)) +
  geom_density() +
  facet_wrap(~ Species)

p2 <- ggplot(iris, aes(Sepal.Length)) +
  geom_density()

To combine, I do :

multiplot(p1, p2, cols = 2)

But it is not the desired shape.

I would like the graph p2 has the same dimensions than others and is situated just next to the last faceted graph.

Thanks for help

Body:
Not sure if this is applicable in you generic case, but with facet_grid instead of facet_wrap, you can use the margins argument:

library(ggplot2)

ggplot(iris, aes(Sepal.Length)) +
    geom_density() +
    facet_grid(. ~ Species, margins = T)

If you question is more generic the answer probably lies in grid.arrange.

Something like this could be a start:

library(gridExtra)

grid.arrange(arrangeGrob(p1, p2,
                         widths = c(3,1),
                         heights = c(1,20),
                         layout_matrix = matrix(c(1,1,NA,2),2)))

As you can see there are several problems (different axes, top strip), but working with grid could gets complicated quickly.


问:
Transition matrix of absorbing higher order markov chain
I have a absorbing Markov chain, let say I have the states

s={START, S1, S2, END1, END2}

The state Start will always be the starting point of the chain, however it will not be possible to return to this states once you leave it.

I am curious of how the transition matrix will look like for a absorbing higher order markov chain.

Now imagine I set up the second order Markov chain transition matrix as follwing:

__________C1 C2 C3 START END1 END2

C1,C1

C1,C2

C1,START

C1, END1

C1, END2

.

.

.

How will it look like for instance on C1, START? This will be zero for all columns, but isnt the row required to sum to 1? Do I simply remove this from the matrix?

And also how will it be for C1, END1, this row will also have zero all across?
The state END1 and END2 on the other side will be impossible to leave once you are in it i.e. they are absorbing.

I wonder how the transistion matrix will look like for a second or kth order Markov chain.  I cannot find any good litterature on this problem, please contribute with som good litterature.

答:
well, If you think the Markov chain is second order, than your initial states should be like (C1,C1), (C1,C2), ..., and thus your matrix would be like

__________(C1,C1) (C1,C2) (C1,C3) (C1,START) ...

(C1,C1)

(C1,C2)

(C1,C3)

(C1,START)

(C1,END1)

(C1,END2)

...

with many zeros (e.g. the prob. of (C1,C2) to (C1,C1) is zero). In your case, it is a 25*25 matrix.

If you claim it is second order, than you have to have 2 consecutive states to estimate the next one.


问:
Problem with forcing SSL using .htaccess
I have the following .htaccess file:

```<code>Order deny,allow
Deny from all
Allow from XX.XXX.XXX.XXX

RewriteEngine  on
RewriteBase    /

RewriteCond    %{REQUEST_FILENAME} !-f
RewriteCond    %{REQUEST_FILENAME} !-d
RewriteRule    . /index.php

RewriteCond    %{HTTPS} !=on
RewriteRule    ^.*$ https://%{SERVER_NAME}%{REQUEST_URI} [R,L]
</code>```

Which is supposed to:

Only allow access from my IP (numbers changed to Xs to protect the innocent)

Send any request which is not a specific file through to /index.php

Force https for the entire domain

As far as I can see, it's identical to a previous project, which was admittedly on a different hosting provider, but that worked like a charm. This time it's resulting in a message saying "Firefox has detected that the server is redirecting the request for this address in a way that will never complete.".

Anybody know what's going on & what I need to change please?

答: Perhaps your new hosting provider is using some sort of setup (like a reverse proxy) that's preventing the HTTPS variable from being set. You may be able to use something else (like SERVER_PORT, or perhaps a header set by the remote proxy, assuming there is one) to determine if the request is HTTPS or HTTP.</p>

Body:
I have the following .htaccess file:

Order deny,allow
Deny from all
Allow from XX.XXX.XXX.XXX

RewriteEngine  on
RewriteBase    /

RewriteCond    %{REQUEST_FILENAME} !-f
RewriteCond    %{REQUEST_FILENAME} !-d
RewriteRule    . /index.php

RewriteCond    %{HTTPS} !=on
RewriteRule    ^.*$ https://%{SERVER_NAME}%{REQUEST_URI} [R,L]

Which is supposed to:

Only allow access from my IP (numbers changed to Xs to protect the innocent)

Send any request which is not a specific file through to /index.php

Force https for the entire domain

As far as I can see, it's identical to a previous project, which was admittedly on a different hosting provider, but that worked like a charm. This time it's resulting in a message saying "Firefox has detected that the server is redirecting the request for this address in a way that will never complete.".

Anybody know what's going on & what I need to change please?


问:
Link displays on two lines when adding style
Thank you all for your time.

I am trying to do something simple but it turns out to be so complicated.
I need a link to send an email but there's some issue with the style. It shows the content fractured (see jsfiddle). But when I right click several times, everything is back to normal. Any idea?

.sendAll {
    float: right;
    margin-right: 10%;
    margin-bottom: 3%;
    margin-top: 2%;
    display: inline-block;
}

#sendAll {
    color: white;
    padding: 7% 25%;
    background-color: #0080FF;
    display: inline-block;
}

#sendAll:hover {
    background-color: #0164c6;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code>HTML:

<div class="sendAll">

                <b id="sendAll">Send Email to All Selected</b>

</div></code>```

Here's the jsfiddle link

Thank you all !

答:
Try this:

```<code>.sendAll {
    float: right;
    margin-right: 10%;
    margin-bottom: 3%;
    margin-top: 2%;
    display: inline-block;
}

#sendAll {
    color: white;
    padding: 7% 25%;
    background-color: #0080FF;
    display: inline-block;
    white-space:nowrap;
}

#sendAll:hover {
    background-color: #0164c6;
}
</code>```

Explain
Add a property white-space:nowrap in #sendAll id

update code link

Body:
Thank you all for your time.

I am trying to do something simple but it turns out to be so complicated.
I need a link to send an email but there's some issue with the style. It shows the content fractured (see jsfiddle). But when I right click several times, everything is back to normal. Any idea?

.sendAll {
    float: right;
    margin-right: 10%;
    margin-bottom: 3%;
    margin-top: 2%;
    display: inline-block;
}

#sendAll {
    color: white;
    padding: 7% 25%;
    background-color: #0080FF;
    display: inline-block;
}

#sendAll:hover {
    background-color: #0164c6;
}

HTML:

                Send Email to All Selected

Here's the jsfiddle link

Thank you all !

Body:
Try this:

.sendAll {
    float: right;
    margin-right: 10%;
    margin-bottom: 3%;
    margin-top: 2%;
    display: inline-block;
}

#sendAll {
    color: white;
    padding: 7% 25%;
    background-color: #0080FF;
    display: inline-block;
    white-space:nowrap;
}

#sendAll:hover {
    background-color: #0164c6;
}

Explain
Add a property white-space:nowrap in #sendAll id

update code link


问:
How can I get data from different pages with javascripts buttons?
I have the following HTML:

            1

            2

            3

            4

            5

            6

            7

            8

            ...

            20

```
</div>
</div>
</p>

<p>When I click in this buttons I go to something like this www.example.com/something?page=X (x = number of the button)
I use this:</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code>Document doc = Jsoup.connect("www.example.com/something?page=5").get();</code>```

But I get always the first page HTML.
How I can "click" or extract information about this pages? I don't know so much about PHP but I think this page use it to change pages.

Edit:

I'm not using javascript. I'm using a java project that extract information from page using html.

答:
Only a single digit gets changed for every link, you can use for loop with a variable denoting your page number as follows:</p>

```<code>for (int i = 1; i <= 8; i++) {
    Document doc = Jsoup.connect("www.example.com/something?page=" + i).get();
              /* Your code for each page*/
        }
</code>```

Body:
I have the following HTML:

            1

            2

            3

            4

            5

            6

            7

            8

            ...

            20

When I click in this buttons I go to something like this www.example.com/something?page=X (x = number of the button)
I use this:

Document doc = Jsoup.connect("www.example.com/something?page=5").get();

But I get always the first page HTML.
How I can "click" or extract information about this pages? I don't know so much about PHP but I think this page use it to change pages.

Edit:

I'm not using javascript. I'm using a java project that extract information from page using html.

Body:
Only a single digit gets changed for every link, you can use for loop with a variable denoting your page number as follows:

for (int i = 1; i <= 8; i++) {
    Document doc = Jsoup.connect("www.example.com/something?page=" + i).get();
              /* Your code for each page*/
        }


问:
Accessing super class variables/methods in sub class
Since subclass can access super class's variables and methods defined as protected, why following code gives compile error?</p>

```<code>public class Animal {
    protected int var;

    public void eat() {
        System.out.println("Animal eating");
    }
}
class Dog extends Animal {
    Animal an = new Animal();
    an.var = 10;
}
</code>```

答:
The Problem is not caused by the fact that var is protected. It is because you need to wrap up that line in a method, like this

```<code>public Dog(){
    an.var = 10; //Compiles Correctly
}
</code>```

Body:
Since subclass can access super class's variables and methods defined as protected, why following code gives compile error?

public class Animal {
    protected int var;

    public void eat() {
        System.out.println("Animal eating");
    }
}
class Dog extends Animal {
    Animal an = new Animal();
    an.var = 10;
}

Body:
The Problem is not caused by the fact that var is protected. It is because you need to wrap up that line in a method, like this

public Dog(){
    an.var = 10; //Compiles Correctly
}


问:
How to replace duplicates in a text file with a #?
For my class project, I have to make a simple Username Inventor and store the Usernames in a file. This is what I have done and it is working.

An additional part to the project is, if a duplicate is added to the file, that duplicate needs to be deleted and replaced with a "#". But the "#" has to be next to the original Username that was the duplicate.

Please can someone show me how to do this, as a for reference this is my code below:

```<code>print("Hello, Welcome to the Username Inventor.")
Name = input("Please tell me, What is your name? ")
print(Name+"......")
print("I like....")
print("Anyway, lets get on shall we.")
with open("Interim.txt", "a") as file:
    true = True
    while true == True:
        choice = input("(1)Add a Pupil's Username to the file\n(2)Exit the program\n")
        if choice == "1":
            true = False
            print("Please identify the following:")
            FirstName = input("Pupil's First Name: ")
            Surname = input("Pupil's Surname: ")
            YearOfEntry = input("Pupil's Year of Entry: ")
            print("Thank you",FirstName, Surname, "from year joining at",YearOfEntry+".")
            Initial = FirstName[0]
            Username = YearOfEntry+Surname+Initial
            print("This Pupil's Username is",Username+".")
            file.write(Username)
            file.write("\n")
            true = True
        if choice == "2":
            print("Thank you", Name+". Goodbye!")
            true = False
</code>```

Help will be very much appreciated, thank you.

答:
You can use a list to check if new username is already in the list. Create a list and add the usernames to the list. Before writing username to the file, use 'if' statement to check if username is already in the list, if it is, then file.write("#\n") otherwise file.write("username").

Replace your following two lines:

```<code>file.write(Username)
file.write("\n")
</code>```

For:

```<code>username_list = [] #make empty list before your with open statement.
    ...
    if Username not in username_list:
        file.write('%s\n'%Username)
        username_list.append(Username)

    else:
        file.write('#\n')
        username_list.append("#")
</code>```

Body:
For my class project, I have to make a simple Username Inventor and store the Usernames in a file. This is what I have done and it is working.

An additional part to the project is, if a duplicate is added to the file, that duplicate needs to be deleted and replaced with a "#". But the "#" has to be next to the original Username that was the duplicate.

Please can someone show me how to do this, as a for reference this is my code below:

print("Hello, Welcome to the Username Inventor.")
Name = input("Please tell me, What is your name? ")
print(Name+"......")
print("I like....")
print("Anyway, lets get on shall we.")
with open("Interim.txt", "a") as file:
    true = True
    while true == True:
        choice = input("(1)Add a Pupil's Username to the file\n(2)Exit the program\n")
        if choice == "1":
            true = False
            print("Please identify the following:")
            FirstName = input("Pupil's First Name: ")
            Surname = input("Pupil's Surname: ")
            YearOfEntry = input("Pupil's Year of Entry: ")
            print("Thank you",FirstName, Surname, "from year joining at",YearOfEntry+".")
            Initial = FirstName[0]
            Username = YearOfEntry+Surname+Initial
            print("This Pupil's Username is",Username+".")
            file.write(Username)
            file.write("\n")
            true = True
        if choice == "2":
            print("Thank you", Name+". Goodbye!")
            true = False

Help will be very much appreciated, thank you.

Body:
You can use a list to check if new username is already in the list. Create a list and add the usernames to the list. Before writing username to the file, use 'if' statement to check if username is already in the list, if it is, then file.write("#\n") otherwise file.write("username").

Replace your following two lines:

file.write(Username)
file.write("\n")

For:

username_list = [] #make empty list before your with open statement.
    ...
    if Username not in username_list:
        file.write('%s\n'%Username)
        username_list.append(Username)

    else:
        file.write('#\n')
        username_list.append("#")


问:
Firebug css js order vs real load order
I want to know the order firebug shows in script , css.Is it the real order in which
the files are loaded or they are shown in sorted alphabetical order.

I want to know the sequence order how they are loaded instead of doing viewsource.

any inputs will be appreciated.

Thanks.

答: Are you talking about the net panel?  By default, it shows them in the order they are loaded.  However, you can click the different column headers to sort the lines.

Title: Firebug css js order vs real load order


答:
if you want your text on only one line, add the following to your #sendAll class

```<code>white-space: nowrap;
</code>```

Title: Link displays on two lines when adding style

Body:
if you want your text on only one line, add the following to your #sendAll class

white-space: nowrap;


问:
Date format not working correctly
Im submitting a form that has a date range picker in it.

I have the code to get the value of the picker from the form, which is in this format:

```<code>01/03/2017 - 01/03/2017
</code>```

I also have it so that it splits the date range into two variables.

```<code>$one = 20/01/2017
$two = 13/03/2017
</code>```

Im now trying to format the date of these variables into the one that MYSQL uses.

My problem is that the end date will fail and be displayed as 1970-01-01 all the time.

```<code>// Get the range from the form
$daterange = $_POST["daterange"];

// Split the range into a start and end date
list($one, $two) = explode("-", "$daterange", 2);

// Test the split worked
echo $one;
echo $two;

// Format the start date into MySQL style
$StartDate = date("Y-m-d", strtotime($one));

// Test date
echo $StartDate;

// Format the end date into MySQL style
$EndDate = date("Y-m-d", strtotime($two));

//Test date
echo $EndDate;
</code>```

答:
Try this:

```<code>$one = '20/01/2017';
$one = str_replace('/', '-', $one);
echo date('Y-m-d', strtotime($one));
</code>```

// Output: 2017-01-20

Working Code

For the reason, see The PHP Manual for strtotime() Specifically this note

Note:
  Dates in the m/d/y or d-m-y formats are disambiguated by looking at the separator between the various components: if the separator is a slash (/), then the American m/d/y is assumed; whereas if the separator is a dash (-) or a dot (.), then the European d-m-y format is assumed. If, however, the year is given in a two digit format and the separator is a dash (-, the date string is parsed as y-m-d.

To avoid potential ambiguity, it's best to use ISO 8601 (YYYY-MM-DD) dates or DateTime::createFromFormat() when possible.

Title: Date format not working correctly

Body:
Im submitting a form that has a date range picker in it.

I have the code to get the value of the picker from the form, which is in this format:

01/03/2017 - 01/03/2017

I also have it so that it splits the date range into two variables.

$one = 20/01/2017
$two = 13/03/2017

Im now trying to format the date of these variables into the one that MYSQL uses.

My problem is that the end date will fail and be displayed as 1970-01-01 all the time.

// Get the range from the form
$daterange = $_POST["daterange"];

// Split the range into a start and end date
list($one, $two) = explode("-", "$daterange", 2);

// Test the split worked
echo $one;
echo $two;

// Format the start date into MySQL style
$StartDate = date("Y-m-d", strtotime($one));

// Test date
echo $StartDate;

// Format the end date into MySQL style
$EndDate = date("Y-m-d", strtotime($two));

//Test date
echo $EndDate;

Body:
Try this:

$one = '20/01/2017';
$one = str_replace('/', '-', $one);
echo date('Y-m-d', strtotime($one));

// Output: 2017-01-20

Working Code

For the reason, see The PHP Manual for strtotime() Specifically this note

Note:
  Dates in the m/d/y or d-m-y formats are disambiguated by looking at the separator between the various components: if the separator is a slash (/), then the American m/d/y is assumed; whereas if the separator is a dash (-) or a dot (.), then the European d-m-y format is assumed. If, however, the year is given in a two digit format and the separator is a dash (-, the date string is parsed as y-m-d.

To avoid potential ambiguity, it's best to use ISO 8601 (YYYY-MM-DD) dates or DateTime::createFromFormat() when possible.