问:
When to break up a function
Currently I am very new to python programming, been working on it for a while, I came across a little project task which was to make a program that takes all of the vowels out of a statement so I decided to try it out. I came up with a program but it seems that it only takes out the vowels sometimes, I find this very weird and I would like to ask for some assistance in solving it.

```<code>def anti_vowel(text):
   list = ['a', 'e', 'i', 'o', 'u']
   big_list = ['A', 'E', 'I', 'O', 'U']
   list_word = []

   for f in text:
      list_word.append(f)

   for vowel in list:
      for letter in list_word:
         if vowel == letter:
            list_word.remove(vowel)

   for vowel in big_list:
      for letter in list_word:
         if vowel == letter:
            list_word.remove(vowel)

   new_word = ''.join(list_word)
   return new_word

print anti_vowel("uuuUUUUUIIIIiiiIiIoOuuooouuUOUUuooouU")
</code>```

This statement as it sits prints out 'IiIuUUuoouU', but if I add more iterations over the lists using more for statements it decreases the amount of shown letters. Can someone tell me why this might be?

答:
Abend's solution with little edits that make it correct

```<code>vowels = ['a','e','i','o','u','A','E','I','O','U']

def no_vowels(str1):
    return ''.join([char for char in list(str1) if char not in vowels])

print no_vowels('finished')
</code>```

Gives

```<code>fnshd

Process finished with exit code 0
</code>```

Title: When to break up a function

Body:
Currently I am very new to python programming, been working on it for a while, I came across a little project task which was to make a program that takes all of the vowels out of a statement so I decided to try it out. I came up with a program but it seems that it only takes out the vowels sometimes, I find this very weird and I would like to ask for some assistance in solving it.

def anti_vowel(text):
   list = ['a', 'e', 'i', 'o', 'u']
   big_list = ['A', 'E', 'I', 'O', 'U']
   list_word = []

   for f in text:
      list_word.append(f)

   for vowel in list:
      for letter in list_word:
         if vowel == letter:
            list_word.remove(vowel)

   for vowel in big_list:
      for letter in list_word:
         if vowel == letter:
            list_word.remove(vowel)

   new_word = ''.join(list_word)
   return new_word

print anti_vowel("uuuUUUUUIIIIiiiIiIoOuuooouuUOUUuooouU")

This statement as it sits prints out 'IiIuUUuoouU', but if I add more iterations over the lists using more for statements it decreases the amount of shown letters. Can someone tell me why this might be?

Body:
Abend's solution with little edits that make it correct

vowels = ['a','e','i','o','u','A','E','I','O','U']

def no_vowels(str1):
    return ''.join([char for char in list(str1) if char not in vowels])

print no_vowels('finished')

Gives

fnshd

Process finished with exit code 0


来源: stackexchange

问:
Datacontract and servicecontract difference
As far as I knw -

ServiceContract can be used for interface/class whereas DataContract can b used only for Class, Struct and Enums

Apart from this - what are other differences b/w these 2 ?
When DataContract and ServiceContract should be used in an application ?

Any sample or link would also do.
Thanks in advance.

答:
The ServiceContract defines the service's contract - its shape and form. It defines the name of the service, its XML namespace etc., and it's typically an interface (but could also be applied to a class) that contains methods decorated with the [OperationContract] attribute - the service methods.

```<code>[ServiceContract]
public interface IMyService
{
    [OperationContract]
    Response GetData(int someKey);
}
</code>```

The DataContract is a totally different beast - it decorates a class to define it as a class that's being used as a parameter or return value from one of the service methods. It's labeling that class as a "thing" to serialize onto the wire to transmit it. It's an instruction for the WCF runtime (the data contract serializer) that this class is intended to be used in a WCF service.

```<code>[DataContract]
public class Response
{
    [DataMember]
    int Key { get; set; }

    [DataMember]
    string ProductName { get; set; }

    [DataMember]
    DateTime DateOfPurchase { get; set; }
}
</code>```

So the service contract and the data contract are two totally separate parts that play together to make a WCF service work - it's not like one could replace the other or something.

ContentLicense: CC BY-SA 2.5

Body:
The ServiceContract defines the service's contract - its shape and form. It defines the name of the service, its XML namespace etc., and it's typically an interface (but could also be applied to a class) that contains methods decorated with the [OperationContract] attribute - the service methods.

[ServiceContract]
public interface IMyService
{
    [OperationContract]
    Response GetData(int someKey);
}

The DataContract is a totally different beast - it decorates a class to define it as a class that's being used as a parameter or return value from one of the service methods. It's labeling that class as a "thing" to serialize onto the wire to transmit it. It's an instruction for the WCF runtime (the data contract serializer) that this class is intended to be used in a WCF service.

[DataContract]
public class Response
{
    [DataMember]
    int Key { get; set; }

    [DataMember]
    string ProductName { get; set; }

    [DataMember]
    DateTime DateOfPurchase { get; set; }
}

So the service contract and the data contract are two totally separate parts that play together to make a WCF service work - it's not like one could replace the other or something.

ContentLicense: CC BY-SA 3.0


问:
Dropdown menu in HTML/CSS doesn't actually "drop down"
I'm trying to add a drop-down menu for one of the options in my nav menu for a simple html page. However, when I hover over the nav menu option, the menu doesn't actually drop down. It just replaces the nav menu option with the first option in the drop-down whenever I hover over it. I'm not exactly sure why it isn't "dropping down".

Any help would be really appreciated... Here's the HTML for the nav and attempted drop-down.

```<code><nav>
    <ul>
        <li><a href="eiffel.shtml">Eiffel Tower</a></li>
        <li><a href="fashion.shtml">Fashion</a></li>
        <li><a href="food.shtml">Food</a></li>
        <li><a href="museums.shtml">Museums</a></li>
        <div class="dropDiv">
            <li class="dropdown"><a href="history.shtml">History</a></li>
                <div class="dropdownContent">
                    <a href=leaders.shtml>Leaders of Paris</a>
                    <a href=future.shtml>Future of Paris</a>
                </div>
        </div>
        <li><a href="language.shtml">Language</a></li>
        <li><a href="works.shtml">Works Cited</a></li>
    </ul>
</nav>
</code>```

and here is the CSS snippet for the Dropdown menu:

```<code>.dropdown {
    float: left;
    background-color: #FFF0F5;
    width: 100%;
}

.dropDiv {
    position: relative;
    display: inline-block;
    width: 100%;
}

.dropdownContent {
    display: none;
    position: absolute;
    background-color: #FFF0F5;
    height: 200px;
    width: 100%;
    z-index: 1;
}

.dropdownContent a {
    display: block;
    text-align: center;
    padding: 14px 16px;
    text-decoration: none;
}

.dropdownContent a:hover {background-color: #fff8dc;}

.dropDiv:hover .dropdownContent {
    display: block;
    z-index: 1;
    height: 200px;
}

.dropDiv:hover .dropdown {
    background-color: #fff8dc;
}
</code>```

I'm not really sure why the drop-down part isn't displaying, i'm sure it's some stupid mistake but it's eluded me for an hour and a half...

答:
The problem is in your HTML.

For the dropdown within an item of the 1st level you'll need a code block that looks like your 1st level. That is, another
 with a group of
s one for each 2nd level option.

Body:
I'm trying to add a drop-down menu for one of the options in my nav menu for a simple html page. However, when I hover over the nav menu option, the menu doesn't actually drop down. It just replaces the nav menu option with the first option in the drop-down whenever I hover over it. I'm not exactly sure why it isn't "dropping down".

Any help would be really appreciated... Here's the HTML for the nav and attempted drop-down.

Eiffel Tower

Fashion

Food

Museums

History

                    Leaders of Paris
                    Future of Paris

Language

Works Cited

and here is the CSS snippet for the Dropdown menu:

.dropdown {
    float: left;
    background-color: #FFF0F5;
    width: 100%;
}

.dropDiv {
    position: relative;
    display: inline-block;
    width: 100%;
}

.dropdownContent {
    display: none;
    position: absolute;
    background-color: #FFF0F5;
    height: 200px;
    width: 100%;
    z-index: 1;
}

.dropdownContent a {
    display: block;
    text-align: center;
    padding: 14px 16px;
    text-decoration: none;
}

.dropdownContent a:hover {background-color: #fff8dc;}

.dropDiv:hover .dropdownContent {
    display: block;
    z-index: 1;
    height: 200px;
}

.dropDiv:hover .dropdown {
    background-color: #fff8dc;
}

I'm not really sure why the drop-down part isn't displaying, i'm sure it's some stupid mistake but it's eluded me for an hour and a half...

Body:
The problem is in your HTML.

For the dropdown within an item of the 1st level you'll need a code block that looks like your 1st level. That is, another <ul> with a group of <li>s one for each 2nd level option.


问:
How do i sum the Inputs for each value in javascript?
I would like to have the sum of the values of each checked checkbox input.
I tried my best and have problems with the following code:

```<code>$("#timediff").on("keyup", function() {

    var v_id = Number("0");

    $("input:checked").each(function () {
      v_id = Number(v_id) +Number($("input:checked").val());

    alert(v_id);
    });

    var s_id = $("#timediff").val();

    if (s_id<=v_id) {
       alert('The"' + s_id +' h" are smaller than "' + v_id + 'h"');
    }else{
          alert('The"' + s_id +' h" are bigger than "' + v_id + 'h"');
    }
  });
</code>```

My output is always the sum of the repeated value of the first "checked" checkbox.

For example, Checkbox1: Value="5", Checkbox2: Value="2", Checkbox3: Value="1".
The output is 15.
But I would like to have 8 as the result. Thank you very much for your help.

答:
Change this:

```<code>$("input:checked").val()
</code>```

to this:

```<code>$(this).val()
</code>```

And don't forget to convert s_id to a number before the <= comparison.

Body:
I would like to have the sum of the values of each checked checkbox input.
I tried my best and have problems with the following code:

$("#timediff").on("keyup", function() {

    var v_id = Number("0");

    $("input:checked").each(function () {
      v_id = Number(v_id) +Number($("input:checked").val());

    alert(v_id);
    });

    var s_id = $("#timediff").val();

    if (s_id<=v_id) {
       alert('The"' + s_id +' h" are smaller than "' + v_id + 'h"');
    }else{
          alert('The"' + s_id +' h" are bigger than "' + v_id + 'h"');
    }
  });

My output is always the sum of the repeated value of the first "checked" checkbox.

For example, Checkbox1: Value="5", Checkbox2: Value="2", Checkbox3: Value="1".
The output is 15.
But I would like to have 8 as the result. Thank you very much for your help.

Body:
Change this:

$("input:checked").val()

to this:

$(this).val()

And don't forget to convert s_id to a number before the <= comparison.


问:
Ruby FileList filtering
I have a FileList with *.js and *.tc extensions. How can I split it into two arrays of FileList, one with only *.js files and the other with *.tc files?

答:
You can use File.extname to get the extension of a file name, and Array#group_by to group array members with similarities:

```<code>result = [ "aaa.js", "bbb.js", "ccc.js",
           "xxx.tc", "yyy.tc", "zzz.tc" ].group_by { |fname| File.extname(fname) }

=> { ".js" => ["aaa.js", "bbb.js", "ccc.js"],
     ".tc" => ["xxx.tc", "yyy.tc", "zzz.tc"] }
</code>```

Now you have a Hash containing two arrays (result[".js"] and result[".tc"]) that contain the file names according to their extensions.

Title: Ruby FileList filtering

Body:
You can use File.extname to get the extension of a file name, and Array#group_by to group array members with similarities:

result = [ "aaa.js", "bbb.js", "ccc.js",
           "xxx.tc", "yyy.tc", "zzz.tc" ].group_by { |fname| File.extname(fname) }

=> { ".js" => ["aaa.js", "bbb.js", "ccc.js"],
     ".tc" => ["xxx.tc", "yyy.tc", "zzz.tc"] }

Now you have a Hash containing two arrays (result[".js"] and result[".tc"]) that contain the file names according to their extensions.


问:
Is it mandatory to have @PathParam argument and function argument same in a rest controller
I am writing a Controller in a Springboot aplictaion. Afunction call looks like

```<code>@GetMapping("/data/search")
    public ResponseEntity<Object> searchData(@PathParam("name") String dataName,
    ....
</code>```

When I run this in debug mode with the url as .../data/search?name=abc , I get a  null value for the variable dataName.
Whereas I get the value abc in case I update the variable name

 dataName->name

As per the docs, I should have used @QueryParam, but that makes no difference either.

So is it mandatory to have the variable name same as the param name?

答:
@PathParam is mandatory and must be passed via path in your case should be /data/search/{name} and then can be accessed. No defaults allowed for path parameters.

for ex: http://serverhost/data/search/test

On the other hand @RequestParam can have a default value and can be optional in your url

for ex: http://serverhost/data/search?name=test

Body:
I am writing a Controller in a Springboot aplictaion. Afunction call looks like

@GetMapping("/data/search")
    public ResponseEntity<Object> searchData(@PathParam("name") String dataName,
    ....

When I run this in debug mode with the url as .../data/search?name=abc , I get a  null value for the variable dataName.
Whereas I get the value abc in case I update the variable name

 dataName->name

As per the docs, I should have used @QueryParam, but that makes no difference either.

So is it mandatory to have the variable name same as the param name?


问:
GraphQL.NET interface using ResolveType
I am new to GraphQL and I'm currently trying to build an api for a existing library.

There I have Tags which have an unique alias, a value which can be of different types and some properties.

To take care of the different value types, I have defined an interface containing alias and properties as well as 4 implementations with a differently typed value field.

The GraphQL schema is as follows:

```<code>schema {
  query: Query
  mutation: Mutation
}

type Query {
    allTags: [Tag!]
    tags(aliases: [ID!]!): [Tag]
    tag(alias: ID!): Tag
}

interface Tag {
    alias: ID! @isUnique
    properties: [TagProperty]
}

type StringTag implements Tag {
    alias: ID! @isUnique
    properties: [TagProperty]
    value: String
}

type IntegerTag implements Tag {
    alias: ID! @isUnique
    properties: [TagProperty]
    value: Int
}

type FloatTag implements Tag {
    alias: ID! @isUnique
    properties: [TagProperty]
    value: Float
}

type BooleanTag implements Tag {
    alias: ID! @isUnique
    properties: [TagProperty]
    value: Boolean
}

type TagProperty {
    name: String!
    value: String!
}
</code>```

In the interface implementation in C#, I want to use ResolveType as suggested in the graphql-dotnet getting started docs.

The code for the interface implementation:

```<code>public TagInterface(
    BooleanTag booleanTag,
    IntegerTag integerTag,
    FloatTag floatTag,
    StringTag stringTag)
{
    Name = "Tag";
    Description = "A resource which points to a value";

    Field<IdGraphType>(
        "alias",
        "the unique alias of the tag"
    );
    Field<ListGraphType<TagPropertyType>>(
        "properties",
        "the properties of a tag defined in the config XML"
    );

    ResolveType = obj =>
    {
        if (obj is HtTag)
        {
            switch ((obj as HtTag).DataType) {
                case EDataType.Bool:

                    return booleanTag;

                case EDataType.Byte:
                case EDataType.Sbyte:
                case EDataType.Short:
                case EDataType.Ushort:
                case EDataType.Int:
                case EDataType.Uint:
                case EDataType.Long:
                case EDataType.Ulong:
                    return integerTag;

                case EDataType.Double:
                case EDataType.Float:
                case EDataType.Decimal:
                    return floatTag;

                default:
                    return stringTag;
            }
        }

        throw new ArgumentOutOfRangeException($"Could not resolve graph type for {obj.GetType().Name}");
    };
}
</code>```

}

When I run the following query

```<code>query {
    tags(aliases:["TagID_S1A02_IN","TagID_S1A03_IN"]) {
      __typename
      alias
      ... on StringTag {
        value
        }
      ... on IntegerTag {
        value
        }
      ... on BooleanTag {
        value
        }
      ... on FloatTag {
        value
        }
    }
}
</code>```

I get the following error:

```<code>{
    "errors": [
        {
            "message": "Für dieses Objekt wurde kein parameterloser Konstruktor definiert."
        }
    ]
}
</code>```

This seems to be because of the 4 constructor parameters in the interface definition (which is according to the example in the docs). If I remove them and return new StringTag() etc. in the ResolveType implementation, I get the correct number of results, but without content:

```<code>{
    "data": {
        "tags": [
            {
                "__typename": "StringTag",
                "alias": null,
                "value": null
            },
            {
                "__typename": "StringTag",
                "alias": null,
                "value": null
            }
        ]
    }
}
</code>```

Can anyone please point out to me what I'm doing wrong here?

Update

I got it working by using the parameterless constructor and returning the resolved object like this:

```<code>ResolveType = obj =>
    {
        if (obj is HtTag)
        {
            switch ((obj as HtTag).DataType) {
                case EDataType.Bool:
                    return (from t in PossibleTypes where t is BooleanTag select t).First();

                case EDataType.Byte:
                case EDataType.Sbyte:
                case EDataType.Short:
                case EDataType.Ushort:
                case EDataType.Int:
                case EDataType.Uint:
                case EDataType.Long:
                case EDataType.Ulong:
                    return (from t in PossibleTypes where t is IntegerTag select t).First();

                case EDataType.Double:
                case EDataType.Float:
                case EDataType.Decimal:
                    return (from t in PossibleTypes where t is FloatTag select t).First();

                default:
                    return (from t in PossibleTypes where t is StringTag select t).First();
            }
        }

        throw new ArgumentOutOfRangeException($"Could not resolve graph type for {obj.GetType().Name}");
    };
</code>```

Is this the way it is supposed to be used?

答:
To be able to resolve your TagInterface type you will need to use some form of Dependency Injection.  Your TagInterface and all of the other GraphType schema types will need to be registered with your DI container.

If using the 2.0 pre-release, use the following (.NET Core example):

```<code>services.AddSingleton<ISchema>(
  s => new StarWarsSchema(new FuncDependencyResolver(type => (IGraphType)s.GetRequiredService(type))));
</code>```

https://github.com/graphql-dotnet/graphql-dotnet/blob/master/src/GraphQL.GraphiQLCore/Startup.cs#L29

Older versions you can just use a func directly (.NET Core example):

```<code>services.AddSingleton<ISchema>(
  s => new StarWarsSchema(type => (IGraphType)s.GetRequiredService(type)));
</code>```

See these docs (not updated to the 2.0 alpha yet) for more info:

https://graphql-dotnet.github.io/docs/getting-started/dependency-injection

You may also need to register those Tag types using RegisterType on Schema if they are not publicly exposed somewhere else in your Schema.

When the Schema is built, it looks at the “root” types (Query,
  Mutation, Subscription) and gathers all of the GraphTypes they expose.
  Often when you are working with an interface type the concrete types
  are not exposed on the root types (or any of their children). Since
  those concrete types are never exposed in the type graph the Schema
  doesn’t know they exist. This is what the RegisterType<> method on the
  Schema is for. By using RegisterType<>, it tells the Schema about the
  specific type and it will properly add it to the PossibleTypes
  collection on the interface type when the Schema is initialized.

https://graphql-dotnet.github.io/docs/getting-started/interfaces#registertype

Title: GraphQL.NET interface using ResolveType

Body:
I am new to GraphQL and I'm currently trying to build an api for a existing library.

There I have Tags which have an unique alias, a value which can be of different types and some properties.

To take care of the different value types, I have defined an interface containing alias and properties as well as 4 implementations with a differently typed value field.

The GraphQL schema is as follows:

schema {
  query: Query
  mutation: Mutation
}

type Query {
    allTags: [Tag!]
    tags(aliases: [ID!]!): [Tag]
    tag(alias: ID!): Tag
}

interface Tag {
    alias: ID! @isUnique
    properties: [TagProperty]
}

type StringTag implements Tag {
    alias: ID! @isUnique
    properties: [TagProperty]
    value: String
}

type IntegerTag implements Tag {
    alias: ID! @isUnique
    properties: [TagProperty]
    value: Int
}

type FloatTag implements Tag {
    alias: ID! @isUnique
    properties: [TagProperty]
    value: Float
}

type BooleanTag implements Tag {
    alias: ID! @isUnique
    properties: [TagProperty]
    value: Boolean
}

type TagProperty {
    name: String!
    value: String!
}

In the interface implementation in C#, I want to use ResolveType as suggested in the graphql-dotnet getting started docs.

The code for the interface implementation:

public TagInterface(
    BooleanTag booleanTag,
    IntegerTag integerTag,
    FloatTag floatTag,
    StringTag stringTag)
{
    Name = "Tag";
    Description = "A resource which points to a value";

    Field<IdGraphType>(
        "alias",
        "the unique alias of the tag"
    );
    Field<ListGraphType<TagPropertyType>>(
        "properties",
        "the properties of a tag defined in the config XML"
    );

    ResolveType = obj =>
    {
        if (obj is HtTag)
        {
            switch ((obj as HtTag).DataType) {
                case EDataType.Bool:

                    return booleanTag;

                case EDataType.Byte:
                case EDataType.Sbyte:
                case EDataType.Short:
                case EDataType.Ushort:
                case EDataType.Int:
                case EDataType.Uint:
                case EDataType.Long:
                case EDataType.Ulong:
                    return integerTag;

                case EDataType.Double:
                case EDataType.Float:
                case EDataType.Decimal:
                    return floatTag;

                default:
                    return stringTag;
            }
        }

        throw new ArgumentOutOfRangeException($"Could not resolve graph type for {obj.GetType().Name}");
    };
}

}

When I run the following query

query {
    tags(aliases:["TagID_S1A02_IN","TagID_S1A03_IN"]) {
      __typename
      alias
      ... on StringTag {
        value
        }
      ... on IntegerTag {
        value
        }
      ... on BooleanTag {
        value
        }
      ... on FloatTag {
        value
        }
    }
}

I get the following error:

{
    "errors": [
        {
            "message": "Für dieses Objekt wurde kein parameterloser Konstruktor definiert."
        }
    ]
}

This seems to be because of the 4 constructor parameters in the interface definition (which is according to the example in the docs). If I remove them and return new StringTag() etc. in the ResolveType implementation, I get the correct number of results, but without content:

{
    "data": {
        "tags": [
            {
                "__typename": "StringTag",
                "alias": null,
                "value": null
            },
            {
                "__typename": "StringTag",
                "alias": null,
                "value": null
            }
        ]
    }
}

Can anyone please point out to me what I'm doing wrong here?

Update

I got it working by using the parameterless constructor and returning the resolved object like this:

ResolveType = obj =>
    {
        if (obj is HtTag)
        {
            switch ((obj as HtTag).DataType) {
                case EDataType.Bool:
                    return (from t in PossibleTypes where t is BooleanTag select t).First();

                case EDataType.Byte:
                case EDataType.Sbyte:
                case EDataType.Short:
                case EDataType.Ushort:
                case EDataType.Int:
                case EDataType.Uint:
                case EDataType.Long:
                case EDataType.Ulong:
                    return (from t in PossibleTypes where t is IntegerTag select t).First();

                case EDataType.Double:
                case EDataType.Float:
                case EDataType.Decimal:
                    return (from t in PossibleTypes where t is FloatTag select t).First();

                default:
                    return (from t in PossibleTypes where t is StringTag select t).First();
            }
        }

        throw new ArgumentOutOfRangeException($"Could not resolve graph type for {obj.GetType().Name}");
    };

Is this the way it is supposed to be used?

Body:
To be able to resolve your TagInterface type you will need to use some form of Dependency Injection.  Your TagInterface and all of the other GraphType schema types will need to be registered with your DI container.

If using the 2.0 pre-release, use the following (.NET Core example):

services.AddSingleton<ISchema>(
  s => new StarWarsSchema(new FuncDependencyResolver(type => (IGraphType)s.GetRequiredService(type))));

https://github.com/graphql-dotnet/graphql-dotnet/blob/master/src/GraphQL.GraphiQLCore/Startup.cs#L29

Older versions you can just use a func directly (.NET Core example):

services.AddSingleton<ISchema>(
  s => new StarWarsSchema(type => (IGraphType)s.GetRequiredService(type)));

See these docs (not updated to the 2.0 alpha yet) for more info:

https://graphql-dotnet.github.io/docs/getting-started/dependency-injection

You may also need to register those Tag types using RegisterType on Schema if they are not publicly exposed somewhere else in your Schema.

When the Schema is built, it looks at the “root” types (Query,
  Mutation, Subscription) and gathers all of the GraphTypes they expose.
  Often when you are working with an interface type the concrete types
  are not exposed on the root types (or any of their children). Since
  those concrete types are never exposed in the type graph the Schema
  doesn’t know they exist. This is what the RegisterType<> method on the
  Schema is for. By using RegisterType<>, it tells the Schema about the
  specific type and it will properly add it to the PossibleTypes
  collection on the interface type when the Schema is initialized.

https://graphql-dotnet.github.io/docs/getting-started/interfaces#registertype

ContentLicense: CC BY-SA 4.0


问:
How can I get the nearest points each other in a given list in python?
```<code>from math import hypot

p = [ (0,0),(1,1),(2,3),(4,5)]
def dist(p1,p2):
    x1,y1= p1
    x2,y2= p2
    return hypot(x2-x1,y2-y1)

from itertools import combinations

distances = [dist(*pair) for pair in combinations( p,2)]
</code>```

<p>After this step I don't know how to do further.. </p>

答:
One way to do it will be to introduce a little impurity in the function -

```<code>from math import hypot

p = [ (0,0),(1,1),(2,3),(4,5)]
distances = {}
def dist(p1,p2):
    x1,y1= p1
    x2,y2= p2
    distances[((x1,y1),(x2,y2))] = hypot(x2-x1,y2-y1)

from itertools import combinations

[dist(*pair) for pair in combinations( p,2)]
print(distances)

min_dist = min(distances, key=distances.get)
print("The minimum distance points are {} and {}".format(min_dist[0], min_dist[1]))
</code>```

I think this is what you're looking for.

Body:
from math import hypot

p = [ (0,0),(1,1),(2,3),(4,5)]
def dist(p1,p2):
    x1,y1= p1
    x2,y2= p2
    return hypot(x2-x1,y2-y1)

from itertools import combinations

distances = [dist(*pair) for pair in combinations( p,2)]

After this step I don't know how to do further..

Body:
One way to do it will be to introduce a little impurity in the function -

from math import hypot

p = [ (0,0),(1,1),(2,3),(4,5)]
distances = {}
def dist(p1,p2):
    x1,y1= p1
    x2,y2= p2
    distances[((x1,y1),(x2,y2))] = hypot(x2-x1,y2-y1)

from itertools import combinations

[dist(*pair) for pair in combinations( p,2)]
print(distances)

min_dist = min(distances, key=distances.get)
print("The minimum distance points are {} and {}".format(min_dist[0], min_dist[1]))

I think this is what you're looking for.


问:
What happens when i press the run button in visual studio
I only know html  and css.

And now I need to study c#

Can someone please explain what happens when i click the run button on my visual studio?

When does translating the souce code into machine code happens?

when does visual studio create an .exe?

Does this executable is already MSIL code already?

I already read some introduction of c#. But still i dont understand a thing.

I only need idea on how things works.

Thank you so much.

答:
When you press the run button, it compiles and build the assemblies and executable file from the source code.

You can find your exe in the bin folder.

Check this link


问:
Is it possible to create a category of the "Block" object in Objective-C
I would like to add functions by creating a category for Objective-C Blocks.

```<code>__block int (^aBlock)(int) = ^int( int n ){
    if( n <= 1 ) return n;
    return aBlock( n - 1 ) + aBlock( n - 2 );
};
</code>```

Instead of just allowing the normal [aBlock copy], [aBlock retain], [aBlock release], [aBlock autorelease]. I could do thing like:

```<code>[aBlock mapTo:anArray];
</code>```

Possible Category

```<code>@interface UnknownBlockClass (map)

- (NSArray *)mapTo:(NSArray *)array_;

@end
</code>```

答:
A block winds up being an instance of type __NSGlobalBlock__, as seen in the following snippet:

```
    void (^aBlock)(void) = ^(void) {
        NSLog(@"Hello world");
    };

    // prints "type = __NSGlobalBlock__"
    NSLog(@"type = %@", [aBlock class]);
```

In order to create a category of a class, the compiler needs to be able to see the original @interface declaration of the class. I can't find the declaration for __NSGlobalBlock__ and probably for good reason.

This article and this article contain some useful information about the implementation of blocks.

To your original point, why not just make a category of NSArray for your mapTo method?  It seems like a better place for that sort of functionality.

Updated

Let's say you can add a category to the Block object.  How would you invoke the block from the category's method?  To the best of my understanding, the only way to invoke a block is via the () operator (e.g., aBlock()).  I don't think there's a way to tell from the Block object the number and types of parameters.  So, what arguments would you pass in to the block invocation?

I'm not recommending you do this, but the following works...

```
@interface NSObject (BlockExtension)
- (void)foo;
@end

@implementation NSObject (BlockExtension)
- (void)foo
{
    // not sure how else to determine if self is a Block since neither
    // __NSGlobalBlock__ nor any of its superclasses (except NSObject)
    // are accessible to the compiler
    if ([[[self class] description] isEqual:@"__NSGlobalBlock__"])
    {
        NSLog(@"foo");
        // now what?
        // can't call self(), it doesn't compile
        // how else can I invoke this block?
    }
}
@end

...

void (^aBlock)(void) = ^(void) {
    NSLog(@"Hello world");
};

// prints "foo"
[aBlock foo];
```

Body:
I would like to add functions by creating a category for Objective-C Blocks.

__block int (^aBlock)(int) = ^int( int n ){
    if( n <= 1 ) return n;
    return aBlock( n - 1 ) + aBlock( n - 2 );
};

Instead of just allowing the normal [aBlock copy], [aBlock retain], [aBlock release], [aBlock autorelease]. I could do thing like:

[aBlock mapTo:anArray];

Possible Category

@interface UnknownBlockClass (map)

- (NSArray *)mapTo:(NSArray *)array_;

@end

Body:
A block winds up being an instance of type __NSGlobalBlock__, as seen in the following snippet:

    void (^aBlock)(void) = ^(void) {
        NSLog(@"Hello world");
    };

    // prints "type = __NSGlobalBlock__"
    NSLog(@"type = %@", [aBlock class]);

In order to create a category of a class, the compiler needs to be able to see the original @interface declaration of the class. I can't find the declaration for __NSGlobalBlock__ and probably for good reason.

This article and this article contain some useful information about the implementation of blocks.

To your original point, why not just make a category of NSArray for your mapTo method?  It seems like a better place for that sort of functionality.

Updated

Let's say you can add a category to the Block object.  How would you invoke the block from the category's method?  To the best of my understanding, the only way to invoke a block is via the () operator (e.g., aBlock()).  I don't think there's a way to tell from the Block object the number and types of parameters.  So, what arguments would you pass in to the block invocation?

I'm not recommending you do this, but the following works...

@interface NSObject (BlockExtension)
- (void)foo;
@end

@implementation NSObject (BlockExtension)
- (void)foo
{
    // not sure how else to determine if self is a Block since neither
    // __NSGlobalBlock__ nor any of its superclasses (except NSObject)
    // are accessible to the compiler
    if ([[[self class] description] isEqual:@"__NSGlobalBlock__"])
    {
        NSLog(@"foo");
        // now what?
        // can't call self(), it doesn't compile
        // how else can I invoke this block?
    }
}
@end

...

void (^aBlock)(void) = ^(void) {
    NSLog(@"Hello world");
};

// prints "foo"
[aBlock foo];


问:
How can i locate the Publish link of "orthoacapulco_30cm_cut ? Selenium webdriver using Java
Publish link

this is the HTML code

```<code><tbody>
  <tr id="id71" class="even">
  <!-- The select row checkbox -->
  <!-- This is a repeater, will generate one td for each property -->
  <td>
    <span></span>
  </td>
  <td>
    <span>orthoacapulco_30cm_cut</span>
  </td>
  <td>
    <span>
      <a id="id64" href="javascript:;"><span>Publish</span></a>
    </span>
  </td>
  </tr>
 </tbody>
</code>```

I tried everything. By XPath, CSS selector, by partialLinkName. I can´t use By.ID because never is the same id, and there may be more elements in the table.

答:
Hello You can try this one :</p>

```<code>driver.findElements(By.xpath(“.//tbody//tr[3]”)).get(0).click();
</code>```

Body:
Publish link

this is the HTML code

    orthoacapulco_30cm_cut

      Publish

I tried everything. By XPath, CSS selector, by partialLinkName. I can´t use By.ID because never is the same id, and there may be more elements in the table.

Body:
Hello You can try this one :

driver.findElements(By.xpath(“.//tbody//tr[3]”)).get(0).click();


问:
SVG Won't Vertically Center
I've been desperately trying to find some way to center my logo svg within a
 tag. I've scoured what felt like all of stack overflow, but to no avail. I hope someone... anyone can help me out with this!
Here is my code:

.site-nav__list {
        display: flex;
        list-style: none;
        align-items: center;
        padding: 0;
        margin: 0;
    }
    .nav-logo {
        cursor: pointer;
        text-align: center;
        width: 3.7em;
        height: 3.7em;
        border: 1px solid red;
    }
    .nav-logo svg {
        display: block;
        width: 100%;
        height: 100%;
        border: 1px solid green;
    }
    .nav-logo svg g {
        border: 1px solid blue;
    }```
<pre class="snippet-code-html lang-html prettyprint-override"><code><ul class="site-nav__list">
          <li>
            <div class="nav-logo">
              <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 100 100" preserveAspectRatio="none">
                <g data-name="Layer 1">
                  <path d="M26.25 0v27.1H0a26.67 26.67 0 0 0 53.34 0V0H26.25z" />
                  <path d="M100 8.25a26.67 26.67 0 1 0-.41 37.3L81.14 27.11z" />
                </g>
              </svg>
            </div>
          </li>
        </ul></code>```

Every solution I've found has not worked :/
And no, table cells and absolute positioning are stupid on a simple svg.

答:
There are several changes that you need to make to solve this problem:

The SVG has a display:block that will prevent some movement, change it to inline-block so things like line-height will affect it.

Add a line-height to .nav-logo of the same size as the height (3.7em) so the elements will be shown in the centered vertically.

Make the image align vertically to the middle of the line by adding a vertical-align: middle.

Remove the width:100% and height:100%, as you don't specify size for the SVG, it will automatically expand to the size of its container.

With all those changes, the image is already centered... but it doesn't look like it. Why? Because there's one change left: the viewBox. Right now the SVG is two letters with a big blank space below. This happens because the viewBox, the canvas in which the image is drawn, is 100x100, but the "lowest" point of the image is at 53.34, leaving all the space underneath it blank.

So one last change: modify the viewBox so it limits the image to the content inside: the width is ok (100), but the height should be 53.34. After fixing that last part, the logo centers vertically:

.site-nav__list {
  display: flex;
  list-style: none;
  align-items: center;
  padding: 0;
  margin: 0;
}

.nav-logo {
  cursor: pointer;
  text-align: center;
  width: 3.7em;
  height: 3.7em;
  border: 1px solid red;
  line-height: 3.7em;
}

.nav-logo svg {
  display: inline-block;
  border: 1px solid green;
  vertical-align:middle;
}

.nav-logo svg g {
  border: 1px solid blue;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><ul class="site-nav__list">
  <li>
    <div class="nav-logo">
      <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 100 53.34" preserveAspectRatio="none">
        <g data-name="Layer 1">
          <path d="M26.25 0v27.1H0a26.67 26.67 0 0 0 53.34 0V0H26.25z" />
          <path d="M100 8.25a26.67 26.67 0 1 0-.41 37.3L81.14 27.11z" />
        </g>
      </svg>
    </div>
  </li>
</ul></code>```

If you want to limit the changes to a minimum, you would only need one simple step: translate the g tag to center it within the svg, so instead of leaving all the white space at the bottom, you put it above and underneath the letters.

You need to translate it vertically (100 - height of letters) / 2, as states previously, the height is 53.34, so the translation would need to be 23.33:

.site-nav__list {
  display: flex;
  list-style: none;
  align-items: center;
  padding: 0;
  margin: 0;
}

.nav-logo {
  cursor: pointer;
  text-align: center;
  width: 3.7em;
  height: 3.7em;
  border: 1px solid red;
}

.nav-logo svg {
  display: block;
  width: 100%;
  height: 100%;
  border: 1px solid green;
}

.nav-logo svg g {
  border: 1px solid blue;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><ul class="site-nav__list">
  <li>
    <div class="nav-logo">
      <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 100 100" preserveAspectRatio="none">
          <g data-name="Layer 1" transform="translate(0, 23.33)">
            <path d="M26.25 0v27.1H0a26.67 26.67 0 0 0 53.34 0V0H26.25z" />
            <path d="M100 8.25a26.67 26.67 0 1 0-.41 37.3L81.14 27.11z" />
          </g>
      </svg>
    </div>
  </li>
</ul></code>```

Title: SVG Won't Vertically Center

Body:
I've been desperately trying to find some way to center my logo svg within a
 tag. I've scoured what felt like all of stack overflow, but to no avail. I hope someone... anyone can help me out with this!
Here is my code:

.site-nav__list {
        display: flex;
        list-style: none;
        align-items: center;
        padding: 0;
        margin: 0;
    }
    .nav-logo {
        cursor: pointer;
        text-align: center;
        width: 3.7em;
        height: 3.7em;
        border: 1px solid red;
    }
    .nav-logo svg {
        display: block;
        width: 100%;
        height: 100%;
        border: 1px solid green;
    }
    .nav-logo svg g {
        border: 1px solid blue;
    }

              <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 100 100" preserveAspectRatio="none">
                <g data-name="Layer 1">
                  <path d="M26.25 0v27.1H0a26.67 26.67 0 0 0 53.34 0V0H26.25z" />
                  <path d="M100 8.25a26.67 26.67 0 1 0-.41 37.3L81.14 27.11z" />
                </g>
              </svg>

Every solution I've found has not worked :/
And no, table cells and absolute positioning are stupid on a simple svg.

Body:
There are several changes that you need to make to solve this problem:

The SVG has a display:block that will prevent some movement, change it to inline-block so things like line-height will affect it.

Add a line-height to .nav-logo of the same size as the height (3.7em) so the elements will be shown in the centered vertically.

Make the image align vertically to the middle of the line by adding a vertical-align: middle.

Remove the width:100% and height:100%, as you don't specify size for the SVG, it will automatically expand to the size of its container.

With all those changes, the image is already centered... but it doesn't look like it. Why? Because there's one change left: the viewBox. Right now the SVG is two letters with a big blank space below. This happens because the viewBox, the canvas in which the image is drawn, is 100x100, but the "lowest" point of the image is at 53.34, leaving all the space underneath it blank.

So one last change: modify the viewBox so it limits the image to the content inside: the width is ok (100), but the height should be 53.34. After fixing that last part, the logo centers vertically:

.site-nav__list {
  display: flex;
  list-style: none;
  align-items: center;
  padding: 0;
  margin: 0;
}

.nav-logo {
  cursor: pointer;
  text-align: center;
  width: 3.7em;
  height: 3.7em;
  border: 1px solid red;
  line-height: 3.7em;
}

.nav-logo svg {
  display: inline-block;
  border: 1px solid green;
  vertical-align:middle;
}

.nav-logo svg g {
  border: 1px solid blue;
}

<ul class="site-nav__list">
  <li>
    <div class="nav-logo">
      <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 100 53.34" preserveAspectRatio="none">
        <g data-name="Layer 1">
          <path d="M26.25 0v27.1H0a26.67 26.67 0 0 0 53.34 0V0H26.25z" />
          <path d="M100 8.25a26.67 26.67 0 1 0-.41 37.3L81.14 27.11z" />
        </g>
      </svg>
    </div>
  </li>
</ul>

If you want to limit the changes to a minimum, you would only need one simple step: translate the g tag to center it within the svg, so instead of leaving all the white space at the bottom, you put it above and underneath the letters.

You need to translate it vertically (100 - height of letters) / 2, as states previously, the height is 53.34, so the translation would need to be 23.33:

.site-nav__list {
  display: flex;
  list-style: none;
  align-items: center;
  padding: 0;
  margin: 0;
}

.nav-logo {
  cursor: pointer;
  text-align: center;
  width: 3.7em;
  height: 3.7em;
  border: 1px solid red;
}

.nav-logo svg {
  display: block;
  width: 100%;
  height: 100%;
  border: 1px solid green;
}

.nav-logo svg g {
  border: 1px solid blue;
}

<ul class="site-nav__list">
  <li>
    <div class="nav-logo">
      <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 100 100" preserveAspectRatio="none">
          <g data-name="Layer 1" transform="translate(0, 23.33)">
            <path d="M26.25 0v27.1H0a26.67 26.67 0 0 0 53.34 0V0H26.25z" />
            <path d="M100 8.25a26.67 26.67 0 1 0-.41 37.3L81.14 27.11z" />
          </g>
      </svg>
    </div>
  </li>
</ul>


问:
for loop in matrix using R
I have to put 54 matrices in a list of vector called A. I want the first 25 matrices in this list to be zero matrices except the (i,j)th element of the matrix, which should be equal to one. All my matrices are 5x5. I am using a for loop, but I dont understand how to create the first 25 matrices.

Now I am trying to make 16 matrices of 0 with (i:(i-1),j:(j-1))th element = 1, so that there is a square of 1s of size 2 by 2. For this I have used the following code, but I want to make sure that 'i' is greater that or equal to 2. how can I do this?

```<code>    t<-26
for(i in 1:5){
   for(j in 1:5){
     A <- matrix(0, nrow = 5, ncol = 5)
    A[i:(i-1), j:(j-1)] <- 1
    M[[l]] <- A
    t <- t+1
   }
}
A
</code>```

Title: for loop in matrix using R

Body:
I have to put 54 matrices in a list of vector called A. I want the first 25 matrices in this list to be zero matrices except the (i,j)th element of the matrix, which should be equal to one. All my matrices are 5x5. I am using a for loop, but I dont understand how to create the first 25 matrices.

Now I am trying to make 16 matrices of 0 with (i:(i-1),j:(j-1))th element = 1, so that there is a square of 1s of size 2 by 2. For this I have used the following code, but I want to make sure that 'i' is greater that or equal to 2. how can I do this?

    t<-26
for(i in 1:5){
   for(j in 1:5){
     A <- matrix(0, nrow = 5, ncol = 5)
    A[i:(i-1), j:(j-1)] <- 1
    M[[l]] <- A
    t <- t+1
   }
}
A

Body:
Just a guess as to what you want. Let me know if this is not what you want, then either I can edit or remove it.

A <- vector("list", 54)
mat <- matrix(0, nrow = 5, ncol = 5)

# assign mat to A and the 1 to the ith element of mat (column wise)
for (i in 1:25) {
  A[[i]] <- mat
  A[[i]][i] <- 1
}

A[[1]]
# [,1] [,2] [,3] [,4] [,5]
# [1,]    1    0    0    0    0
# [2,]    0    0    0    0    0
# [3,]    0    0    0    0    0
# [4,]    0    0    0    0    0
# [5,]    0    0    0    0    0

A[[2]]
# [,1] [,2] [,3] [,4] [,5]
# [1,]    0    0    0    0    0
# [2,]    1    0    0    0    0
# [3,]    0    0    0    0    0
# [4,]    0    0    0    0    0
# [5,]    0    0    0    0    0

A[[25]]
# [,1] [,2] [,3] [,4] [,5]
# [1,]    0    0    0    0    0
# [2,]    0    0    0    0    0
# [3,]    0    0    0    0    0
# [4,]    0    0    0    0    0
# [5,]    0    0    0    0    1

Insert 1 row wise (not the most elegant way to do it)

# assing 1 the ith element of mat (column wise)
for (i in 1:25) {
  mat_1 <- mat
  mat_1[i] <- 1
  A[[i]] <- t(mat_1)
}


问:
Calling methods of actual object instead of parent class
I have the following dummy code:

```<code> #include <iostream>
 #include <vector>

 using namespace std;

 class Parent {
 public:
     void printHello() {
         cout << "Hello Parent" << endl;
     }
 };

 class Child : public Parent {
 public:
     void printHello() {
         cout << "Hello Child" << endl;
     }
 };

 int main() {
     vector<Parent*> list;
     Child child;
     list.push_back(&child);

     list[0]->printHello();
  }

  Output: Hello Parent
</code>```

I am trying to create a list of objects of classes derived from the parent class. Iterating over them and running a method they all inherit and override.

I had assumed the method in the child class would have overridden the method in the parent class.

I have also tried the approach of using vector<Parent> instead of vector<Parent*>.

The result has been the same. How can I call the methods of the derived classes instead of the parent class?

答:
In C++ you have to use virtual in the parent class method definition to specify that you are going to use a polymophic method. The default behavior in C++ is not polymorfic.

```<code>#include <iostream>
#include <vector>

using namespace std;

class Parent {
public:
    virtual void printHello() {
        cout << "Hello Parent" << endl;
    }
};

class Child : public Parent {
public:
    void printHello() {
        cout << "Hello Child" << endl;
    }
};
</code>```

Check this out for more info: Polymorphism in C++

Body:
I have the following dummy code:

 #include <iostream>
 #include <vector>

 using namespace std;

 class Parent {
 public:
     void printHello() {
         cout << "Hello Parent" << endl;
     }
 };

 class Child : public Parent {
 public:
     void printHello() {
         cout << "Hello Child" << endl;
     }
 };

 int main() {
     vector<Parent*> list;
     Child child;
     list.push_back(&child);

     list[0]->printHello();
  }

  Output: Hello Parent

I am trying to create a list of objects of classes derived from the parent class. Iterating over them and running a method they all inherit and override.

I had assumed the method in the child class would have overridden the method in the parent class.

I have also tried the approach of using vector<Parent> instead of vector<Parent*>.

The result has been the same. How can I call the methods of the derived classes instead of the parent class?

Body:
In C++ you have to use virtual in the parent class method definition to specify that you are going to use a polymophic method. The default behavior in C++ is not polymorfic.

#include <iostream>
#include <vector>

using namespace std;

class Parent {
public:
    virtual void printHello() {
        cout << "Hello Parent" << endl;
    }
};

class Child : public Parent {
public:
    void printHello() {
        cout << "Hello Child" << endl;
    }
};

Check this out for more info: Polymorphism in C++


答: I see you have mentioned position: absolute in dropdownContent class. This is causing to overlap. Just remove it and try. By default it sets to static, which mean Elements render in order, as they appear in the document flow. Where as absolute means element is positioned relative to its first positioned ancestor element.</p>

Title: Dropdown menu in HTML/CSS doesn't actually "drop down"

Body:
I'm trying to add a drop-down menu for one of the options in my nav menu for a simple html page. However, when I hover over the nav menu option, the menu doesn't actually drop down. It just replaces the nav menu option with the first option in the drop-down whenever I hover over it. I'm not exactly sure why it isn't "dropping down".

Any help would be really appreciated... Here's the HTML for the nav and attempted drop-down.

Eiffel Tower

Fashion

Food

Museums

History

                    Leaders of Paris
                    Future of Paris

Language

Works Cited

and here is the CSS snippet for the Dropdown menu:

.dropdown {
    float: left;
    background-color: #FFF0F5;
    width: 100%;
}

.dropDiv {
    position: relative;
    display: inline-block;
    width: 100%;
}

.dropdownContent {
    display: none;
    position: absolute;
    background-color: #FFF0F5;
    height: 200px;
    width: 100%;
    z-index: 1;
}

.dropdownContent a {
    display: block;
    text-align: center;
    padding: 14px 16px;
    text-decoration: none;
}

.dropdownContent a:hover {background-color: #fff8dc;}

.dropDiv:hover .dropdownContent {
    display: block;
    z-index: 1;
    height: 200px;
}

.dropDiv:hover .dropdown {
    background-color: #fff8dc;
}

I'm not really sure why the drop-down part isn't displaying, i'm sure it's some stupid mistake but it's eluded me for an hour and a half...


问:
Azure AD B2C Authentication Firewall Issues
I have implemented a website that uses Azure AD B2C as its authentication mechanism.

Everything works great except I recently ran into a firewall issue with one of my clients.  When the client redirects to either *.onmicrosoft.com and/or login.microsoftonline.com my client's corporate firewall blocks the routes.  And to further complicate my situation my client's corporate firewall restrictions can not be changed.

Is there any work around that anyone can suggest such using a headless login workflow that is orchestrated within the web server that hosts my website or possibly using custom domains that my client trusts such as login.mycompany.com?

答:
Both of the approaches have outlined would be the ideal ways to deal with this restriction, unfortunately neither are currently available in Azure AD B2C.

Both of them are listed in the Azure AD B2C feedback forum for you to support and keep track of their progress:

Customer-owned domains

Add support for Resource Owner Password Credentials flow in Azure AD B2C and headless authentication in Microsoft Authentication Library

I can't think of any other approach, which is a good thing otherwise, it would mean someone could easily spoof Azure AD B2C.

Ultimately, the right thing to do is to work with your client to ensure these and all the endpoints your applications needs, are allowed through the firewall.


问:
docker run hello-world results in "Incorrect Usage" error: "flag provided but not defined: -console"
When running docker run hello-world I get an "Incorrect Usage" error (full output pasted below).  I'm running the following:

Docker 17.05.0-ce, build 89658be

docker-containerd 0.2.3 (commit 9048e5e)

runc v1.0.0-rc4

Linux kernel 4.1.15

Using buildroot 2017.11 (commit 1f1a242) to generate custom toolchain/rootfs

systemd 234

Seems as though I can pull the hello-world image down properly, as it is included in docker images output.  Wondering if there is an incompatibility between docker/containerd/runc?  Or maybe something obvious?  First time working with docker.

Additionally, I've run a docker check-config.sh script I found that states the only kernel configuration features I'm missing are optional.  They are CONFIG_CGROUP_PIDS, CONFIG_CGROUP_HUGETLB, CONFIG_AUFS_FS, /dev/zfs, zfs command, and zpool command.  Everything else, including all required, are enabled.

Output:

```<code># docker run hello-world
[  429.332968] device vethc0d83d1 entered promiscuous mode
[  429.359681] IPv6: ADDRCONF(NETDEV_UP): vethc0d83d1: link is not ready
Incorrect Usage.

NAME:
   docker-runc create - create a container

USAGE:
   docker-runc create [command options] <container-id>

Where "<container-id>" is your name for the instance of the container that you
are starting. The name you provide for the container instance must be unique on
your host.

DESCRIPTION:
   The create command creates an instance of a container for a bundle. The bundle
is a directory with a specification file named "config.json" and a root
filesystem.

The specification file includes an args parameter. The args parameter is used
to specify command(s) that get run when the container is started. To change the
command(s) that get executed on start, edit the args parameter of the spec. See
"runc spec --help" for more explanation.

OPTIONS:
   --bundle value, -b value  path to the root of the bundle directory, defaults to the current directory
   --console-socket value    path to an AF_UNIX socket which will receive a file descriptor referencing the master end of the console's pseudoterminal
   --pid-file value          specify the file to write the process id to
   --no-pivot                do not use pivot root to jail process inside rootfs.  This should be used whenever the rootfs is on top of a ramdisk
   --no-new-keyring          do not create a new session keyring for the container.  This will cause the container to inherit the calling processes session key
   --preserve-fds value      Pass N additional file descriptors to the container (stdio + $LISTEN_FDS + N in total) (default: 0)

flag provided but not defined: -console
[  429.832198] docker0: port 1(vethc0d83d1) entered disabled state
[  429.849301] device vethc0d83d1 left promiscuous mode
[  429.859317] docker0: port 1(vethc0d83d1) entered disabled state
docker: Error response from daemon: oci runtime error: flag provided but not defined: -console.
</code>```

答:
The -console option was replaced with --console-socket in runc Dec 2016 for v1.0.0-rc4.

So I would guess you need an older version of runc or a newer version of Docker.

If you are building Docker yourself, use Docker 17.09.0-ce or an older release of runc. I'm not sure if that's v0.1.1 or just an earlier 1.0 like v1.0.0-rc2

If you were upgrading packages, something has gone wrong with the install. Probably purge everything and reinstall Docker.

Body:
When running docker run hello-world I get an "Incorrect Usage" error (full output pasted below).  I'm running the following:

Docker 17.05.0-ce, build 89658be

docker-containerd 0.2.3 (commit 9048e5e)

runc v1.0.0-rc4

Linux kernel 4.1.15

Using buildroot 2017.11 (commit 1f1a242) to generate custom toolchain/rootfs

systemd 234

Seems as though I can pull the hello-world image down properly, as it is included in docker images output.  Wondering if there is an incompatibility between docker/containerd/runc?  Or maybe something obvious?  First time working with docker.

Additionally, I've run a docker check-config.sh script I found that states the only kernel configuration features I'm missing are optional.  They are CONFIG_CGROUP_PIDS, CONFIG_CGROUP_HUGETLB, CONFIG_AUFS_FS, /dev/zfs, zfs command, and zpool command.  Everything else, including all required, are enabled.

Output:

# docker run hello-world
[  429.332968] device vethc0d83d1 entered promiscuous mode
[  429.359681] IPv6: ADDRCONF(NETDEV_UP): vethc0d83d1: link is not ready
Incorrect Usage.

NAME:
   docker-runc create - create a container

USAGE:
   docker-runc create [command options] <container-id>

Where "<container-id>" is your name for the instance of the container that you
are starting. The name you provide for the container instance must be unique on
your host.

DESCRIPTION:
   The create command creates an instance of a container for a bundle. The bundle
is a directory with a specification file named "config.json" and a root
filesystem.

The specification file includes an args parameter. The args parameter is used
to specify command(s) that get run when the container is started. To change the
command(s) that get executed on start, edit the args parameter of the spec. See
"runc spec --help" for more explanation.

OPTIONS:
   --bundle value, -b value  path to the root of the bundle directory, defaults to the current directory
   --console-socket value    path to an AF_UNIX socket which will receive a file descriptor referencing the master end of the console's pseudoterminal
   --pid-file value          specify the file to write the process id to
   --no-pivot                do not use pivot root to jail process inside rootfs.  This should be used whenever the rootfs is on top of a ramdisk
   --no-new-keyring          do not create a new session keyring for the container.  This will cause the container to inherit the calling processes session key
   --preserve-fds value      Pass N additional file descriptors to the container (stdio + $LISTEN_FDS + N in total) (default: 0)

flag provided but not defined: -console
[  429.832198] docker0: port 1(vethc0d83d1) entered disabled state
[  429.849301] device vethc0d83d1 left promiscuous mode
[  429.859317] docker0: port 1(vethc0d83d1) entered disabled state
docker: Error response from daemon: oci runtime error: flag provided but not defined: -console.


问:
@HostBinding disabling class from child component Angular 4
I have an angular app which has user login and logout. I am showing up a welcome page as the home page before a user logs in. I want to enable a background image only on the welcome page. Once the user logs in, the background image must disappear. When the user logs out, he will be redirected to welcome page which must show up the background image again.

I have tried using @HostBinding in the app.component.ts by renaming the selector to 'body'.

```<code>app.component.ts

import {Component, HostBinding, Input} from '@angular/core';
import {InputMask} from "primeng/primeng";

@Component({
  selector: 'body',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  path = '../assets/img/AvayaHome.jpg';
  title = 'app';
  toggleClass = true;
  @HostBinding('class.bodyClass') isWelcomePage = this.toggleClass;
}
</code>```

Here is my CSS.

```<code>app.component.css

.bodyClass  {
    background-image: url("../assets/img/AvayaHome.jpg");
}
</code>```

Here is my index.html

```<code><!doctype html>
<html lang="en">
<head>
 <title> Something </title>
</head>
<body class="bodyClass">

    <app-welcome-page></app-welcome-page>

</body>
</html>
</code>```

I am enabling the css style for bodyClass by assigning toggleClass as true. Once the user logs in, I am changing the value of toggleClass (which is in the app.component.ts) from the child component.

Here is my login.component.ts

```<code>onLogin() {
    console.log('onLogin() invoked:', this._email, ':' , this.password);
    if (this._email == null || this.password == null) {
      this.errorMessage = 'All fields are required';
      return;
    }
    this.errorMessage = null;
    this.loginservice.authenticate(this._email, this.password);
    this.appComponent.toggleClass = true;
    this.router.navigate(['/dashboard']);
  }
</code>```

The value of the toggleClass changes when the user logs in to FALSE. But I am still seeing the background image. Not sure what I am doing wrong. Any help will be appreciated.

答:
As an example, let's take a look at this code:

```<code>var toggleClass = false;
var isWelcomePage = toggleClass;

console.log(isWelcomePage); // prints true
</code>```

Cool, all works as expected.

Ten seconds later....

Some user logins:

```<code>toggleClass = true;

console.log(isWelcomePage); // prints false
</code>```

Why it has not changed???

If you open any documentation or any book about javascript you can read one main rule:

Primitives are always immutable.

When we assign toggleClass variable to isWelcomePage variable using =, we copy the value to the new variable because primitives are copied by value.

Solution 1:

Change isWelcomePage property directly

```<code>onLogin() {
  ...
  this.appComponent.isWelcomePage = true;
  ...
}
</code>```

Solution 2

Define getter

```<code>@HostBinding('class.bodyClass')
get isWelcomePage() {
  return this.toggleClass;
}
</code>```

Body:
I have an angular app which has user login and logout. I am showing up a welcome page as the home page before a user logs in. I want to enable a background image only on the welcome page. Once the user logs in, the background image must disappear. When the user logs out, he will be redirected to welcome page which must show up the background image again.

I have tried using @HostBinding in the app.component.ts by renaming the selector to 'body'.

app.component.ts

import {Component, HostBinding, Input} from '@angular/core';
import {InputMask} from "primeng/primeng";

@Component({
  selector: 'body',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  path = '../assets/img/AvayaHome.jpg';
  title = 'app';
  toggleClass = true;
  @HostBinding('class.bodyClass') isWelcomePage = this.toggleClass;
}

Here is my CSS.

app.component.css

.bodyClass  {
    background-image: url("../assets/img/AvayaHome.jpg");
}

Here is my index.html

<!doctype html>

 <title> Something </title>

    <app-welcome-page></app-welcome-page>

I am enabling the css style for bodyClass by assigning toggleClass as true. Once the user logs in, I am changing the value of toggleClass (which is in the app.component.ts) from the child component.

Here is my login.component.ts

onLogin() {
    console.log('onLogin() invoked:', this._email, ':' , this.password);
    if (this._email == null || this.password == null) {
      this.errorMessage = 'All fields are required';
      return;
    }
    this.errorMessage = null;
    this.loginservice.authenticate(this._email, this.password);
    this.appComponent.toggleClass = true;
    this.router.navigate(['/dashboard']);
  }

The value of the toggleClass changes when the user logs in to FALSE. But I am still seeing the background image. Not sure what I am doing wrong. Any help will be appreciated.

Body:
As an example, let's take a look at this code:

var toggleClass = false;
var isWelcomePage = toggleClass;

console.log(isWelcomePage); // prints true

Cool, all works as expected.

Ten seconds later....

Some user logins:

toggleClass = true;

console.log(isWelcomePage); // prints false

Why it has not changed???

If you open any documentation or any book about javascript you can read one main rule:

Primitives are always immutable.

When we assign toggleClass variable to isWelcomePage variable using =, we copy the value to the new variable because primitives are copied by value.

Solution 1:

Change isWelcomePage property directly

onLogin() {
  ...
  this.appComponent.isWelcomePage = true;
  ...
}

Solution 2

Define getter

@HostBinding('class.bodyClass')
get isWelcomePage() {
  return this.toggleClass;
}


问:
camel cxf on wildfly
I'v created a SOAP webservice and I'd like to expose it with camel-cxf on wildfly.

When I want to deploy it I get the following error:

Apache CXF library (cxf-core-3.2.0.jar) detected in ws endpoint deployment; either provide a proper deployment replacing embedded libraries with container module dependencies or disable the webservices subsystem for the current deployment adding a proper jboss-deployment-structure.xml descriptor to it. The former approach is recommended, as the latter approach causes most of the webservices Java EE and any JBossWS specific functionality to be disabled.

Tried what was suggested here but didn't work. Tried to exclude the cxf dependencies from the caml-cxf include in my pom.xml:

```<code><dependency>
   <groupId>org.apache.camel</groupId>
   <artifactId>camel-cxf</artifactId>
   <version>2.20.0</version>
   <exclusions>
     <exclusion>
         <groupId>org.apache.cxf</groupId>
          <artifactId>*</artifactId>
     </exclusion>
   </exclusions>
</dependency>
</code>```

That solved the error but produces new ones:

```<code>Failed to define class org.apache.camel.component.cxf.spring.AbstractCxfBeanDefinitionParser in Module "deployment.CamelCXF-1.0.war" from Service Module Loader: java.lang.NoClassDefFoundError: Failed to link org/apache/camel/component/cxf/spring/AbstractCxfBeanDefinitionParser

Failed to define class org.apache.camel.component.cxf.spring.CxfEndpointBeanDefinitionParser in Module "deployment.CamelCXF-1.0.war" from Service Module Loader: java.lang.NoClassDefFoundError: Failed to link org/apache/camel/component/cxf/spring/CxfEndpointBeanDefinitionParser

Context initialization failed: org.springframework.beans.factory.BeanDefinitionStoreException: Unexpected exception parsing XML document from ServletContext resource [/WEB-INF/camel.xml]; nested exception is org.springframework.beans.FatalBeanException: Invalid NamespaceHandler class [org.apache.camel.component.cxf.spring.NamespaceHandler] for namespace [http://camel.apache.org/schema/cxf]: problem with handler class file or dependent class; nested exception is java.lang.NoClassDefFoundError: Failed to link org/apache/camel/component/cxf/spring/CxfEndpointBeanDefinitionParser
</code>```

Could you help me resolve these errors or provide a small working example that I can deploy on wildfly and extend? Much appreciated.

Defined these dependencies in my pom.xml:

```<code><dependencies>
    <dependency>
        <groupId>org.apache.camel</groupId>
        <artifactId>camel-core</artifactId>
        <version>2.20.0</version>
    </dependency>
    <dependency>
        <groupId>org.apache.camel</groupId>
        <artifactId>camel-cxf</artifactId>
        <version>2.20.0</version>
        <exclusions>
            <exclusion>
                <groupId>org.apache.cxf</groupId>
                <artifactId>*</artifactId>
            </exclusion>
        </exclusions>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-web</artifactId>
        <version>5.0.1.RELEASE</version>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-context</artifactId>
        <version>5.0.1.RELEASE</version>
    </dependency>
    <dependency>
        <groupId>javax</groupId>
        <artifactId>javaee-web-api</artifactId>
        <version>8.0</version>
        <scope>provided</scope>
    </dependency>
</dependencies>
</code>```

And here's my camel.xml:

```<code><?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
   xmlns:camel="http://camel.apache.org/schema/spring"
   xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
   xmlns:cxf="http://camel.apache.org/schema/cxf"
   xsi:schemaLocation="
   http://camel.apache.org/schema/spring
    http://camel.apache.org/schema/spring/camel-spring.xsd
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://camel.apache.org/schema/cxf
http://camel.apache.org/schema/cxf/camel-cxf.xsd">

<cxf:cxfEndpoint id="customerEndpoint"
                 address="http://localhost:8080/TestService/"
                 serviceClass="my.package.TestService"
                 wsdlURL="WEB-INF/CustomerService.wsdl"/>

<bean id="logBean" class="my.package.LogBean"/>

<camel:camelContext xmlns="http://camel.apache.org/schema/spring">
    <route>
        <from uri="cxf:bean:customerEndpoint" />
        <to uri="bean:logBean" />
    </route>
</camel:camelContext>
</code>```

Follow-up question

I could set up a webservice with the links provided by @Tadayoshi Sato. The examples, however, only use one simple function with one processor. How do I know which function was called when I have several operations in a port definition?
Is it possible to have camel call the implementation of the provided interface that was called or do I have to map that myself?

答:
As Claus pointed out, the most recommended approach to use Camel on WildFly is using WildFly Camel. You can find in the link below how to install the WildFly Camel subsystem to WildFly:

http://wildfly-extras.github.io/wildfly-camel/index.html

Once you've installed WildFly Camel, let's see this link, where you can find how to develop code using camel-cxf on WildFly:

http://wildfly-extras.github.io/wildfly-camel/index.html#_jax_ws

The point is that WildFly already has its own CXF libraries as a subsystem and you are required to use the built-in libraries as much as possible; otherwise, you may encounter awkward problems like those in the question. It's the WildFly Camel subsystem that lets you to use the underlying WildFly subsystems for your Camel applications.

UPDATE:

For camel-cxf consumers, the operation name which is called is available via CxfConstants.OPERATION_NAME message header. According to:

https://github.com/apache/camel/blob/master/components/camel-cxf/src/main/docs/cxf-component.adoc

The camel-cxf endpoint consumer POJO data format is based on the CXF invoker, so the message header has a property with the name of CxfConstants.OPERATION_NAME and the message body is a list of the SEI method parameters.

You may route a message based on this message header and change the implementations accordingly.

Title: camel cxf on wildfly

Body:
I'v created a SOAP webservice and I'd like to expose it with camel-cxf on wildfly.

When I want to deploy it I get the following error:

Apache CXF library (cxf-core-3.2.0.jar) detected in ws endpoint deployment; either provide a proper deployment replacing embedded libraries with container module dependencies or disable the webservices subsystem for the current deployment adding a proper jboss-deployment-structure.xml descriptor to it. The former approach is recommended, as the latter approach causes most of the webservices Java EE and any JBossWS specific functionality to be disabled.

Tried what was suggested here but didn't work. Tried to exclude the cxf dependencies from the caml-cxf include in my pom.xml:

<dependency>
   <groupId>org.apache.camel</groupId>
   <artifactId>camel-cxf</artifactId>
   <version>2.20.0</version>
   <exclusions>
     <exclusion>
         <groupId>org.apache.cxf</groupId>
          <artifactId>*</artifactId>
     </exclusion>
   </exclusions>
</dependency>

That solved the error but produces new ones:

Failed to define class org.apache.camel.component.cxf.spring.AbstractCxfBeanDefinitionParser in Module "deployment.CamelCXF-1.0.war" from Service Module Loader: java.lang.NoClassDefFoundError: Failed to link org/apache/camel/component/cxf/spring/AbstractCxfBeanDefinitionParser

Failed to define class org.apache.camel.component.cxf.spring.CxfEndpointBeanDefinitionParser in Module "deployment.CamelCXF-1.0.war" from Service Module Loader: java.lang.NoClassDefFoundError: Failed to link org/apache/camel/component/cxf/spring/CxfEndpointBeanDefinitionParser

Context initialization failed: org.springframework.beans.factory.BeanDefinitionStoreException: Unexpected exception parsing XML document from ServletContext resource [/WEB-INF/camel.xml]; nested exception is org.springframework.beans.FatalBeanException: Invalid NamespaceHandler class [org.apache.camel.component.cxf.spring.NamespaceHandler] for namespace [http://camel.apache.org/schema/cxf]: problem with handler class file or dependent class; nested exception is java.lang.NoClassDefFoundError: Failed to link org/apache/camel/component/cxf/spring/CxfEndpointBeanDefinitionParser

Could you help me resolve these errors or provide a small working example that I can deploy on wildfly and extend? Much appreciated.

Defined these dependencies in my pom.xml:

<dependencies>
    <dependency>
        <groupId>org.apache.camel</groupId>
        <artifactId>camel-core</artifactId>
        <version>2.20.0</version>
    </dependency>
    <dependency>
        <groupId>org.apache.camel</groupId>
        <artifactId>camel-cxf</artifactId>
        <version>2.20.0</version>
        <exclusions>
            <exclusion>
                <groupId>org.apache.cxf</groupId>
                <artifactId>*</artifactId>
            </exclusion>
        </exclusions>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-web</artifactId>
        <version>5.0.1.RELEASE</version>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-context</artifactId>
        <version>5.0.1.RELEASE</version>
    </dependency>
    <dependency>
        <groupId>javax</groupId>
        <artifactId>javaee-web-api</artifactId>
        <version>8.0</version>
        <scope>provided</scope>
    </dependency>
</dependencies>

And here's my camel.xml:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
   xmlns:camel="http://camel.apache.org/schema/spring"
   xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
   xmlns:cxf="http://camel.apache.org/schema/cxf"
   xsi:schemaLocation="
   http://camel.apache.org/schema/spring
    http://camel.apache.org/schema/spring/camel-spring.xsd
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://camel.apache.org/schema/cxf
http://camel.apache.org/schema/cxf/camel-cxf.xsd">

<cxf:cxfEndpoint id="customerEndpoint"
                 address="http://localhost:8080/TestService/"
                 serviceClass="my.package.TestService"
                 wsdlURL="WEB-INF/CustomerService.wsdl"/>

<bean id="logBean" class="my.package.LogBean"/>

<camel:camelContext xmlns="http://camel.apache.org/schema/spring">
    <route>
        <from uri="cxf:bean:customerEndpoint" />
        <to uri="bean:logBean" />
    </route>
</camel:camelContext>

Follow-up question

I could set up a webservice with the links provided by @Tadayoshi Sato. The examples, however, only use one simple function with one processor. How do I know which function was called when I have several operations in a port definition?
Is it possible to have camel call the implementation of the provided interface that was called or do I have to map that myself?


问:
Do periods count as numerics (COBOL)
I am working on a bit of code at home and that is suppose to find and identify errors is a input file. I got it just about right, but two little errors are hitting me. The major problem though is this. I have to make a code that identifies "3077.B22" as an error because the first 5 columns are suppose to be numeric, but my current code is letting it pass. It hits every thing else though so I have to believe that it is seeing the period as a decimal point. Here is what I got that concerns to this part.

```<code>   01  PART-NUMBER-CHECK.
       05 P-N-NUM-1                PIC X(5).
       05 P-N-LETTER               PIC X.
       05 P-N-NUM-2                PIC XX.

   300-VALIDATE-PART-NUMBER.
       MOVE 'NO' TO FIELD-ERROR-SWITCH
       MOVE PART-NUMBER TO PART-NUMBER-CHECK
       EVALUATE P-N-NUM-1
           WHEN 00001 THRU 99999  CONTINUE

           WHEN OTHER              MOVE 'YES' TO FIELD-ERROR-SWITCH
       END-EVALUATE
       IF P-N-LETTER IS NUMERIC
           MOVE 'YES' TO FIELD-ERROR-SWITCH
       END-IF
       IF P-N-LETTER IS ALPHABETIC-LOWER
           MOVE 'YES' TO FIELD-ERROR-SWITCH
       END-IF
       IF P-N-NUM-2 IS ALPHABETIC
           MOVE 'YES' TO FIELD-ERROR-SWITCH
       END-IF
       IF (P-N-NUM-2 > 00 AND < 69)
           OR (P-N-NUM-2 >77 AND < 100)
               CONTINUE
       ELSE
           MOVE 'YES' TO FIELD-ERROR-SWITCH
       END-IF
       IF FIELD-ERROR-SWITCH = 'YES'
           MOVE 'YES' TO RECORD-ERROR-SWITCH
           MOVE 'Part Number' TO FIELD-NAME
           MOVE PART-NUMBER TO FIELD-VALUE
           PERFORM 400-WRITE-DETAIL-LINE
       END-IF.
</code>```

My second problem is similar cause it is seeing an * in another field as a alphabetic.
Here is the paragraph to that:

```<code>   340-VALIDATE-INITIAL.
       MOVE 'NO' TO FIELD-ERROR-SWITCH
       INSPECT INITIALS
           TALLYING I-CHECK FOR ALL SPACES
       IF I-CHECK > 0
           MOVE 'YES' TO FIELD-ERROR-SWITCH
           MOVE 0 TO I-CHECK
       END-IF
       IF INITIALS IS NUMERIC
           MOVE 'YES' TO FIELD-ERROR-SWITCH
       END-IF
       IF FIELD-ERROR-SWITCH = 'YES'
           MOVE 'YES' TO RECORD-ERROR-SWITCH
           MOVE 'Initials' TO FIELD-NAME
           MOVE INITIALS TO FIELD-VALUE
           PERFORM 400-WRITE-DETAIL-LINE
       END-IF.
</code>```

Please help, I am done as soon as I get over this little bump in the road.

答:
A long time since I wrote my last COBOL, and I don't have a compiler at hand, so expect some sintax checks in the code, but you'll get the idea ...</p>

```<code>01  PART-NUMBER-CHECK.
   05 P-N-NUM-1                .
      07 p-x-occ occurs 5      pic X.
   05 P-N-NUM-1-N    redefines P-N-NUM-1.           .
      07 p-n-occ occurs 5      pic 9.
   05 P-N-LETTER               PIC X.
   05 P-N-NUM-2                PIC XX.

01 FIELD-ERROR-SWITCH pic x(3).
   88 no-error value 'NO'.

300-VALIDATE-PART-NUMBER.
   MOVE 'NO' TO FIELD-ERROR-SWITCH
   MOVE PART-NUMBER TO PART-NUMBER-CHECK.
   perform validate-p-n-occurs varying I from 1 to 5.
   if no-error
      IF ( P-N-LETTER IS NUMERIC or P-N-LETTER IS ALPHABETIC-LOWER or
           P-N-NUM-2 IS ALPHABETIC)
         MOVE 'YES' TO FIELD-ERROR-SWITCH
      ELSE
          IF (P-N-NUM-2 < 0) OR (P-N-NUM-20 > 68 AND < 79) OR (P-N-NUM-2 >99)
             MOVE 'YES' TO FIELD-ERROR-SWITCH
          END-IF
      END-IF
   END-IF

   IF FIELD-ERROR-SWITCH = 'YES'
       MOVE 'YES' TO RECORD-ERROR-SWITCH
       MOVE 'Part Number' TO FIELD-NAME
       MOVE PART-NUMBER TO FIELD-VALUE
       PERFORM 400-WRITE-DETAIL-LINE
   END-IF.

validate-p-n-occurs.
   IF p-x-occ(I) is not NUMERIC or (p-n-occ(I) < 0 or  > 10)
         MOVE 'YES' TO FIELD-ERROR-SWITCH
   END-IF.
</code>```

Title: Do periods count as numerics (COBOL)

Body:
I am working on a bit of code at home and that is suppose to find and identify errors is a input file. I got it just about right, but two little errors are hitting me. The major problem though is this. I have to make a code that identifies "3077.B22" as an error because the first 5 columns are suppose to be numeric, but my current code is letting it pass. It hits every thing else though so I have to believe that it is seeing the period as a decimal point. Here is what I got that concerns to this part.

   01  PART-NUMBER-CHECK.
       05 P-N-NUM-1                PIC X(5).
       05 P-N-LETTER               PIC X.
       05 P-N-NUM-2                PIC XX.

   300-VALIDATE-PART-NUMBER.
       MOVE 'NO' TO FIELD-ERROR-SWITCH
       MOVE PART-NUMBER TO PART-NUMBER-CHECK
       EVALUATE P-N-NUM-1
           WHEN 00001 THRU 99999  CONTINUE

           WHEN OTHER              MOVE 'YES' TO FIELD-ERROR-SWITCH
       END-EVALUATE
       IF P-N-LETTER IS NUMERIC
           MOVE 'YES' TO FIELD-ERROR-SWITCH
       END-IF
       IF P-N-LETTER IS ALPHABETIC-LOWER
           MOVE 'YES' TO FIELD-ERROR-SWITCH
       END-IF
       IF P-N-NUM-2 IS ALPHABETIC
           MOVE 'YES' TO FIELD-ERROR-SWITCH
       END-IF
       IF (P-N-NUM-2 > 00 AND < 69)
           OR (P-N-NUM-2 >77 AND < 100)
               CONTINUE
       ELSE
           MOVE 'YES' TO FIELD-ERROR-SWITCH
       END-IF
       IF FIELD-ERROR-SWITCH = 'YES'
           MOVE 'YES' TO RECORD-ERROR-SWITCH
           MOVE 'Part Number' TO FIELD-NAME
           MOVE PART-NUMBER TO FIELD-VALUE
           PERFORM 400-WRITE-DETAIL-LINE
       END-IF.

My second problem is similar cause it is seeing an * in another field as a alphabetic.
Here is the paragraph to that:

   340-VALIDATE-INITIAL.
       MOVE 'NO' TO FIELD-ERROR-SWITCH
       INSPECT INITIALS
           TALLYING I-CHECK FOR ALL SPACES
       IF I-CHECK > 0
           MOVE 'YES' TO FIELD-ERROR-SWITCH
           MOVE 0 TO I-CHECK
       END-IF
       IF INITIALS IS NUMERIC
           MOVE 'YES' TO FIELD-ERROR-SWITCH
       END-IF
       IF FIELD-ERROR-SWITCH = 'YES'
           MOVE 'YES' TO RECORD-ERROR-SWITCH
           MOVE 'Initials' TO FIELD-NAME
           MOVE INITIALS TO FIELD-VALUE
           PERFORM 400-WRITE-DETAIL-LINE
       END-IF.

Please help, I am done as soon as I get over this little bump in the road.

Body:
A long time since I wrote my last COBOL, and I don't have a compiler at hand, so expect some sintax checks in the code, but you'll get the idea ...

01  PART-NUMBER-CHECK.
   05 P-N-NUM-1                .
      07 p-x-occ occurs 5      pic X.
   05 P-N-NUM-1-N    redefines P-N-NUM-1.           .
      07 p-n-occ occurs 5      pic 9.
   05 P-N-LETTER               PIC X.
   05 P-N-NUM-2                PIC XX.

01 FIELD-ERROR-SWITCH pic x(3).
   88 no-error value 'NO'.

300-VALIDATE-PART-NUMBER.
   MOVE 'NO' TO FIELD-ERROR-SWITCH
   MOVE PART-NUMBER TO PART-NUMBER-CHECK.
   perform validate-p-n-occurs varying I from 1 to 5.
   if no-error
      IF ( P-N-LETTER IS NUMERIC or P-N-LETTER IS ALPHABETIC-LOWER or
           P-N-NUM-2 IS ALPHABETIC)
         MOVE 'YES' TO FIELD-ERROR-SWITCH
      ELSE
          IF (P-N-NUM-2 < 0) OR (P-N-NUM-20 > 68 AND < 79) OR (P-N-NUM-2 >99)
             MOVE 'YES' TO FIELD-ERROR-SWITCH
          END-IF
      END-IF
   END-IF

   IF FIELD-ERROR-SWITCH = 'YES'
       MOVE 'YES' TO RECORD-ERROR-SWITCH
       MOVE 'Part Number' TO FIELD-NAME
       MOVE PART-NUMBER TO FIELD-VALUE
       PERFORM 400-WRITE-DETAIL-LINE
   END-IF.

validate-p-n-occurs.
   IF p-x-occ(I) is not NUMERIC or (p-n-occ(I) < 0 or  > 10)
         MOVE 'YES' TO FIELD-ERROR-SWITCH
   END-IF.


问:
Find partial keywords in python list
```<code>x = 'a'
list = ['ab','cd','a']
if x in list:
    print(list.index(x))
</code>```

Here I try to find all the values in list which contains 'a'. But with the 'in' method I can only find the value which is 'a' rather than contain 'a',like 'ab'. Are there any efficient ways to do so? Thanks

答:
Requires a list comprehension to get it done - </p>

```<code>x = 'a'
list_ = ['ab','cd','a']
filtered_list = [elem for elem in list_ if x in elem]
print(filtered_list)
</code>```

<p>Output - </p>

```<code>['ab', 'a']
</code>```

Title: Find partial keywords in python list

Body:
x = 'a'
list = ['ab','cd','a']
if x in list:
    print(list.index(x))

Here I try to find all the values in list which contains 'a'. But with the 'in' method I can only find the value which is 'a' rather than contain 'a',like 'ab'. Are there any efficient ways to do so? Thanks

Body:
Requires a list comprehension to get it done -

x = 'a'
list_ = ['ab','cd','a']
filtered_list = [elem for elem in list_ if x in elem]
print(filtered_list)

Output -

['ab', 'a']


问:
Use NumberFormat.getCurrency in Kotlin Android
I need call this

```<code>{private static final NumberFormat currencyFormat = NumberFormat.getCurrencyInstance();}
</code>```

in Android Application, but I using Kotlin and I don't know how to do that in Kotlin. How can I do this in Kotlin?

答:
use below method it will return currency format of the current default format locale:</p>

```<code> fun currencyFormat() : NumberFormat = NumberFormat.getCurrencyInstance()
</code>```

Body:
I need call this

{private static final NumberFormat currencyFormat = NumberFormat.getCurrencyInstance();}

in Android Application, but I using Kotlin and I don't know how to do that in Kotlin. How can I do this in Kotlin?

Body:
use below method it will return currency format of the current default format locale:

 fun currencyFormat() : NumberFormat = NumberFormat.getCurrencyInstance()


问:
TWILIO - why the actual response returned does not match with documented
I have integrated Twilio and it works fine. Now I want to capture all the intermediate message statuses. I referred to Sending Messages.

My code looks like -

```<code>require __DIR__ . '/vendor/autoload.php';
      // Use the REST API Client to make requests to the Twilio REST API
      use Twilio\Rest\Client;

// Your Account SID and Auth Token from twilio.com/console
$sid = '****************';
$token = '*****************';
$client = new Client($sid, $token);

// send message
$message = $client->messages->create(
    // the number you'd like to send the message to
    '+1xxxxxxxxx',
    array(
        'from' => '+1xxxxxxxx',
        'body' => 'Test web hook message '.date('h:i'),
        'statusCallback' => "https://xxxxxx/xxxx.php",
    )
);
</code>```

But the output/response returned to statusCallback is different as -

```<code>"{\"SmsSid\":\"SM72478c1ea61f467dbc33338123c0ad0\",\"SmsStatus\":\"sent\",\"MessageStatus\":\"sent\",\"To\":\"+1xxxxxxxx\",\"MessageSid\":\"SM72478c1ea612222dbc3b7858123c0ad0\",\"AccountSid\":\"ACb655a10c1c2222e4af158c5395d64beb\",\"From\":\"+1xxxxxxx\",\"ApiVersion\":\"2010-04-01\"}"
</code>```

But I need the response as it is defined at Sending Messages

EDIT

If checked at Sending Messages, we can see the fields returned in the output are - account_sid, api_version, body, num_segments, num_media, date_created, date_sent, date_updated, direction, error_code, error_message, from, price, sid, status, to and uri.
But I receive fields as - SmsSid, SmsStatus, MessageStatus, To, MessageSid, AccountSid, From and ApiVersion.

For me, the fields - num_segments, date_sent, direction, error_code, error_message are important which I am not receiving. Do I need to use another API of TWILIO to retrieve this information ?

Why am I getting different response ?

答:
Twilio developer evangelist here.

When you send a message and set a statusCallback URL the sending messages documentation says:

Twilio will POST the MessageSid along with the other standard request parameters as well as MessageStatus and ErrorCode.

The standard request parameters are:

MessageSid

SmsSid

AccountSid

MessagingServiceSid

From

To

Body

NumMedia

as well as some others specifically about media or geographic data based on the two numbers.

If you need to find out those other attributes of the message, you will need to look up the message using the REST API.

Let me know if that helps at all.

Body:
I have integrated Twilio and it works fine. Now I want to capture all the intermediate message statuses. I referred to Sending Messages.

My code looks like -

require __DIR__ . '/vendor/autoload.php';
      // Use the REST API Client to make requests to the Twilio REST API
      use Twilio\Rest\Client;

// Your Account SID and Auth Token from twilio.com/console
$sid = '****************';
$token = '*****************';
$client = new Client($sid, $token);

// send message
$message = $client->messages->create(
    // the number you'd like to send the message to
    '+1xxxxxxxxx',
    array(
        'from' => '+1xxxxxxxx',
        'body' => 'Test web hook message '.date('h:i'),
        'statusCallback' => "https://xxxxxx/xxxx.php",
    )
);

But the output/response returned to statusCallback is different as -

"{\"SmsSid\":\"SM72478c1ea61f467dbc33338123c0ad0\",\"SmsStatus\":\"sent\",\"MessageStatus\":\"sent\",\"To\":\"+1xxxxxxxx\",\"MessageSid\":\"SM72478c1ea612222dbc3b7858123c0ad0\",\"AccountSid\":\"ACb655a10c1c2222e4af158c5395d64beb\",\"From\":\"+1xxxxxxx\",\"ApiVersion\":\"2010-04-01\"}"

But I need the response as it is defined at Sending Messages

EDIT

If checked at Sending Messages, we can see the fields returned in the output are - account_sid, api_version, body, num_segments, num_media, date_created, date_sent, date_updated, direction, error_code, error_message, from, price, sid, status, to and uri.
But I receive fields as - SmsSid, SmsStatus, MessageStatus, To, MessageSid, AccountSid, From and ApiVersion.

For me, the fields - num_segments, date_sent, direction, error_code, error_message are important which I am not receiving. Do I need to use another API of TWILIO to retrieve this information ?

Why am I getting different response ?


问:
Springfox Java Bean Validations not displaying in Swagger Output
I'm trying to follow the documentation for Springfox Swagger to get Java Bean Validation to work (http://springfox.github.io/springfox/docs/current/#springfox-support-for-jsr-303), but they are not showing up in the Swagger UI.

This is my Spring Configuration:

```<code>import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;

@EnableSwagger2
@Import({springfox.bean.validators.configuration.BeanValidatorPluginsConfiguration.class})
@Configuration
public class SwaggerConfig {
    @Bean
    public Docket docket() {
        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo())
                .select()
                .build();
    }

    private ApiInfo apiInfo() {
        return new ApiInfoBuilder()
                .title("My API")
                .build();
    }
}
</code>```

This is my request mapping:

```<code>@ApiOperation(value = "Use to get token for internal applications")
@PostMapping(value = AuthUris.TOKEN)
public AuthResponse token(@Valid @RequestBody AuthRequest authRequest) {
// implementation omitted
}
</code>```

This is my POJO:

```<code>@ApiModel
public class AuthRequest {
    @ApiModelProperty
    @NotNull
    @Size(min = 4, max = 50)
    private String username;
    @NotNull
    private String password;

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }
}
</code>```

I expected the NotNull and Size annotations to be captured in the Swagger UI but they are not. Please help me understand how this should work.  Thank you.

.

So thanks to https://stackoverflow.com/users/8012379/indra-basak I do see that they were working.  However, I have to hover over the field to thinks like @Size.  See the screenshot below.

答:
If you are using springfox version 2.7.0, both @NotNull and @Size annotations should work.

Your @NotNull annotation is already working in the password field.

If @ApiModelProperty annotation is present for a field, it takes precedence over @NotNull annotation. It is the case with the username field. It shows up as optional because the required attribute of @ApiModelProperty annotation is set to false by default.

If you use springfox version 2.7.0 and don't use @ApiModelProperty annotation, the model will show up as:

Validation

For example, if you enter a username less than the minimum size of 4, you will get the following exception:

```<code>{
  "timestamp": 1511550365198,
  "status": 400,
  "error": "Bad Request",
  "exception": "org.springframework.web.bind.MethodArgumentNotValidException",
  "errors": [
    {
      "codes": [
        "Size.authRequest.username",
        "Size.username",
        "Size.java.lang.String",
        "Size"
      ],
      "arguments": [
        {
          "codes": [
            "authRequest.username",
            "username"
          ],
          "arguments": null,
          "defaultMessage": "username",
          "code": "username"
        },
        50,
        4
      ],
      "defaultMessage": "size must be between 4 and 50",
      "objectName": "authRequest",
      "field": "username",
      "rejectedValue": "s",
      "bindingFailure": false,
      "code": "Size"
    }
  ],
  "message": "Validation failed for object='authRequest'. Error count: 1",
  "path": "/tokens"
}
</code>```

Body:
I'm trying to follow the documentation for Springfox Swagger to get Java Bean Validation to work (http://springfox.github.io/springfox/docs/current/#springfox-support-for-jsr-303), but they are not showing up in the Swagger UI.

This is my Spring Configuration:

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;

@EnableSwagger2
@Import({springfox.bean.validators.configuration.BeanValidatorPluginsConfiguration.class})
@Configuration
public class SwaggerConfig {
    @Bean
    public Docket docket() {
        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo())
                .select()
                .build();
    }

    private ApiInfo apiInfo() {
        return new ApiInfoBuilder()
                .title("My API")
                .build();
    }
}

This is my request mapping:

@ApiOperation(value = "Use to get token for internal applications")
@PostMapping(value = AuthUris.TOKEN)
public AuthResponse token(@Valid @RequestBody AuthRequest authRequest) {
// implementation omitted
}

This is my POJO:

@ApiModel
public class AuthRequest {
    @ApiModelProperty
    @NotNull
    @Size(min = 4, max = 50)
    private String username;
    @NotNull
    private String password;

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }
}

I expected the NotNull and Size annotations to be captured in the Swagger UI but they are not. Please help me understand how this should work.  Thank you.

.

So thanks to https://stackoverflow.com/users/8012379/indra-basak I do see that they were working.  However, I have to hover over the field to thinks like @Size.  See the screenshot below.

Body:
If you are using springfox version 2.7.0, both @NotNull and @Size annotations should work.

Your @NotNull annotation is already working in the password field.

If @ApiModelProperty annotation is present for a field, it takes precedence over @NotNull annotation. It is the case with the username field. It shows up as optional because the required attribute of @ApiModelProperty annotation is set to false by default.

If you use springfox version 2.7.0 and don't use @ApiModelProperty annotation, the model will show up as:

Validation

For example, if you enter a username less than the minimum size of 4, you will get the following exception:

{
  "timestamp": 1511550365198,
  "status": 400,
  "error": "Bad Request",
  "exception": "org.springframework.web.bind.MethodArgumentNotValidException",
  "errors": [
    {
      "codes": [
        "Size.authRequest.username",
        "Size.username",
        "Size.java.lang.String",
        "Size"
      ],
      "arguments": [
        {
          "codes": [
            "authRequest.username",
            "username"
          ],
          "arguments": null,
          "defaultMessage": "username",
          "code": "username"
        },
        50,
        4
      ],
      "defaultMessage": "size must be between 4 and 50",
      "objectName": "authRequest",
      "field": "username",
      "rejectedValue": "s",
      "bindingFailure": false,
      "code": "Size"
    }
  ],
  "message": "Validation failed for object='authRequest'. Error count: 1",
  "path": "/tokens"
}