问:
What measurement do you use in your development process to determine *Doneness* of your software?
I just finished listening to a very eye-opening podcast on Hanselminutes about the definition of "Done". So my question to everyone is "When do you consider a piece of software to be "Done"? Is it when it's fully unit tested? Is it when it's completely documented? What measurement do you use in your development process to determine Doneness of your software?

答:
A good measurement is code churn.  Using your source code control software, measure the rate of change.  How many lines of code are being removed/added/changed per day.  Graph this over time.  As you approach being ready to release, this should trend downwards and give an indication of stability and readiness to ship.  This assumes that you are actually testing well and making changes to fix bugs or respond to change requests.  If your user acceptance test users and integration/unit test activity are continuing to regress and test and you aren't having to make code changes (because they aren't finding anything necessitating a change) then you are probably ready to ship.

If big chunks of code are churning a few days before an arbitrary or externally driven ship date, look out!

OwnerDisplayName: Micah

OwnerDisplayName: Pat James


来源: stackexchange

问:
Find the number of connected objects in a given 2-D binary matrix
Find number of connected objects from a given 2d matrix<br>
 Sample Input & Output1: </p>

```<code>Enter number of rows:
5
Enter number of columns:
5
Enter the matrix:
0 0 0 0 0
1 0 0 1 0
1 0 0 0 1
0 1 0 1 0
0 0 0 0 0
Number of connected objects = 2
</code>```

答:
I found out what you want, here ya have it, this explains how to find the "islands", meaning the number of connected 1's

http://www.geeksforgeeks.org/find-number-of-islands/

ContentLicense: CC BY-SA 3.0

Body:
Find number of connected objects from a given 2d matrix

 Sample Input & Output1:

Enter number of rows:
5
Enter number of columns:
5
Enter the matrix:
0 0 0 0 0
1 0 0 1 0
1 0 0 0 1
0 1 0 1 0
0 0 0 0 0
Number of connected objects = 2


问:
Pass object between before and after advice
My question is the same as in Pass object between before and after advice?, however the accepted answer doesn't work in my case and I would like to ask for some clarification on this topic.

Actually, I'm using around advice, but I have to change it. Let's consider an example:

```<code>public Object registerLog( ProceedingJoinPoint jpoint)
{
    SomeObject so = getSomeData( jpoint.getArgs());
    Object result = jpoint.proceed();
    getMoreData( result, so);
    log( so);
}
</code>```

My proceed() method is inserting object into database. In this scenario I'm logging the result of INSERT before its transaction commits, which is not very good. That's why I want to split around advice into before and after, so I can log in after, when the record is already in database. However, I still need to get some data of the object before it's stored in database.

Of course the solution must be thread-safe, so I can't just add a SomeObject member to my aspect class. From the linked question I learned about ThreadLocal, and so far it's the best solution I found. However, I never used it before and I would like to ask if there are any other solutions. Maybe there's a way to force a transaction to commit while processing an aspect (I'm not sure right now if this is even a good idea)?

UPDATE with more details

I have two pointcuts:

```<code><aop:pointcut id="mngrPointcut" expression="execution(* com.mngr.Foo.*(..))"/>
<aop:pointcut id="savePointcut" expression="execution(* com.mngr.Foo.save(..))"/>
</code>```

First pointcut has advice

```<code><aop:advisor advice-ref="txAdvice" pointcut-ref="mngrPointcut"/>
</code>```

where advice is

```<code><tx:advice id="txAdvice" transaction-manager="txManager">
    <tx:attributes>
        <tx:method name="select*,search*,get*" propagation="REQUIRED" rollback-for="Exception" read-only="true"/>
        <tx:method name="*" propagation="REQUIRED" rollback-for="Exception"/>
    </tx:attributes>
</tx:advice>
</code>```

For second pointcut I have aspect

```<code><aop:aspect ref="logAspect">
    <aop:around method="registerLog" pointcut-ref="savePointcut"/>
</aop:aspect>
</code>```

When calling com.mngr.Foo.save() both pointcuts are valid. Probably because of declaration order, mngrPointcut is triggered first, starting a new transaction. Then savePointcut is triggered, starting an aspect. As I mentioned above, aspect is responsible for logging. Because of the order in which pointcuts are triggered, object is logged before it is stored in database, which is wrong. I thought that I have to use before and after advice instead of around, so I can call log() method in after part, when the transaction is already comitted.

答: If you have trouble with aspect precedence, changing the pointcut type from around to after will not help. Instead, you want to make your aspects implement the Ordered interface or alternatively annotate them by @Order, both as described in the Spring AOP manual. Please also search further down the chapter for the term "ordered" in order (no pun intended) to see some sample code.

Body:
My question is the same as in Pass object between before and after advice?, however the accepted answer doesn't work in my case and I would like to ask for some clarification on this topic.

Actually, I'm using around advice, but I have to change it. Let's consider an example:

public Object registerLog( ProceedingJoinPoint jpoint)
{
    SomeObject so = getSomeData( jpoint.getArgs());
    Object result = jpoint.proceed();
    getMoreData( result, so);
    log( so);
}

My proceed() method is inserting object into database. In this scenario I'm logging the result of INSERT before its transaction commits, which is not very good. That's why I want to split around advice into before and after, so I can log in after, when the record is already in database. However, I still need to get some data of the object before it's stored in database.

Of course the solution must be thread-safe, so I can't just add a SomeObject member to my aspect class. From the linked question I learned about ThreadLocal, and so far it's the best solution I found. However, I never used it before and I would like to ask if there are any other solutions. Maybe there's a way to force a transaction to commit while processing an aspect (I'm not sure right now if this is even a good idea)?

UPDATE with more details

I have two pointcuts:

<aop:pointcut id="mngrPointcut" expression="execution(* com.mngr.Foo.*(..))"/>
<aop:pointcut id="savePointcut" expression="execution(* com.mngr.Foo.save(..))"/>

First pointcut has advice

<aop:advisor advice-ref="txAdvice" pointcut-ref="mngrPointcut"/>

where advice is

<tx:advice id="txAdvice" transaction-manager="txManager">
    <tx:attributes>
        <tx:method name="select*,search*,get*" propagation="REQUIRED" rollback-for="Exception" read-only="true"/>
        <tx:method name="*" propagation="REQUIRED" rollback-for="Exception"/>
    </tx:attributes>
</tx:advice>

For second pointcut I have aspect

<aop:aspect ref="logAspect">
    <aop:around method="registerLog" pointcut-ref="savePointcut"/>
</aop:aspect>

When calling com.mngr.Foo.save() both pointcuts are valid. Probably because of declaration order, mngrPointcut is triggered first, starting a new transaction. Then savePointcut is triggered, starting an aspect. As I mentioned above, aspect is responsible for logging. Because of the order in which pointcuts are triggered, object is logged before it is stored in database, which is wrong. I thought that I have to use before and after advice instead of around, so I can call log() method in after part, when the transaction is already comitted.


问:
How can I refactor two functions into one function that takes a generic argument?
How can I refactor two functions into one function that has a generic parameter?

Example:

```<code>getVideo : Video -> Post
getVideo video =
    let
        (Video post) =
            video
    in
        post

getPodcast : Podcast -> Post
getPodcast podcast =
    let
        (Podcast post) =
            podcast
    in
        post
</code>```

I would like to do something like this:

```<code>getPodcast : 'a -> Post
getPodcast 'a =
    let
        ('a post) =
            'a
    in
        post
</code>```

Appendix:

```<code>type Video
    = Video Post

type Podcast
    = Podcast Post
</code>```

答:
You cannot have such an open-ended generic function in Elm. Here are two options:

Use a container type

You can create a container type that has a constructor for each of its valid types:

type PostContainer
    = VideoContainer Video
    | PodcastContainer Podcast
```

<p>Now your <code>getPost</code> function consists of a <code>case</code> statement which returns the appropriate post.</p>

<pre class="lang-elm prettyprint-override"><code>getPost : PostContainer -> Post
getPost container =
    case container of
        VideoContainer (Video post) ->
            post

        PodcastContainer (Podcast post) ->
            post
</code>```

Include the post type in the Post value

Let's say your Post object looks like this:

type alias Post =
    { name : String
    , body : String
    }
```

<p>You could create an enumeration of post types like this:</p>

<pre class="lang-elm prettyprint-override"><code>type PostType = Video | Podcast
</code>```

You could redefine Post to include the type:

type alias Post =
    { name : String
    , body : String
    , postType : PostType
    }
```

<p>Or, if you choose to keep the post body separate from the type, you could do something like this:</p>

<pre class="lang-elm prettyprint-override"><code>type alias PostContents =
    { name : String
    , body : String
    }

type Post = Post PostType PostContents
</code>```

and your getPostContents function would simply be

getPostContents : Post -> PostContents
getPostContents _ contents =
    contents
```

Body:
How can I refactor two functions into one function that has a generic parameter?

Example:

getVideo : Video -> Post
getVideo video =
    let
        (Video post) =
            video
    in
        post

getPodcast : Podcast -> Post
getPodcast podcast =
    let
        (Podcast post) =
            podcast
    in
        post

I would like to do something like this:

getPodcast : 'a -> Post
getPodcast 'a =
    let
        ('a post) =
            'a
    in
        post

Appendix:

type Video
    = Video Post

type Podcast
    = Podcast Post

Body:
You cannot have such an open-ended generic function in Elm. Here are two options:

Use a container type

You can create a container type that has a constructor for each of its valid types:

type PostContainer
    = VideoContainer Video
    | PodcastContainer Podcast

Now your getPost function consists of a case statement which returns the appropriate post.

getPost : PostContainer -> Post
getPost container =
    case container of
        VideoContainer (Video post) ->
            post

        PodcastContainer (Podcast post) ->
            post

Include the post type in the Post value

Let's say your Post object looks like this:

type alias Post =
    { name : String
    , body : String
    }

You could create an enumeration of post types like this:

type PostType = Video | Podcast

You could redefine Post to include the type:

type alias Post =
    { name : String
    , body : String
    , postType : PostType
    }

Or, if you choose to keep the post body separate from the type, you could do something like this:

type alias PostContents =
    { name : String
    , body : String
    }

type Post = Post PostType PostContents

and your getPostContents function would simply be

getPostContents : Post -> PostContents
getPostContents _ contents =
    contents


问:
Why can't we directly print the output of a lambda function/expression directly as a string,list, or tuple?
I am using Python 3. I am trying to write a lambda function/expression and generate a string type output. I am not sure what I am not understanding in this issue.

```<code>Cel = [39.5, 36.5, 37.3, 37.8]
Fer = lambda x: (float(9)/5*x for x in Cel + 32)
print(Fer)
</code>```

prints:

```<code><function <lambda> at 0x7fafc369eea0>
</code>```

But, I want the list of values as:

```<code>[103.1, 97.70, 99.14, 100.03]
</code>```

I then tried map with lambda

```<code>Fer2 = map(lambda x: (float(9)/5)*x + 32, Cel)
print(Fer2) # prints:
<map object at 0x7fafc36b5b38> # still no success

for x in Fer:
    print(x)  # this doesn't work and gives following error
TypeError: 'function' object is not iterable

for x in Fer2:
    print(x) # but this works and prints
             103.10
             97.7
             99.14
             100.039
</code>```

Why can't I get print(Fer or Fer2) simply as a a list of values, like:
[103.1, 97.70, 99.14, 100.03]

How do I solve this within lambda, without writing another def function?

答:
not quite sure why you need the lambda at all this is a simple list comprehensions

```<code>Fer = [32+float(9)/5*x for x in Cel]
</code>```

or if you want to use lambda, you will have to use map

```<code>Fer = list(map(lambda x: (float(9)/5*x + 32),Cel))
</code>```

Since you are iterating through Fer you can leave out the list

```<code>Fer = map(lambda x: (float(9)/5*x + 32),Cel)
</code>```

Your current attempt is basically trying to mix map and list comprehensions. To elaborate further, what you are doing with the next line of code is to create a lambda function and assign it to a variable called Fer which is not what you want.

```<code>Fer = lambda x: (float(9)/5*x for x in Cel + 32)
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I am using Python 3. I am trying to write a lambda function/expression and generate a string type output. I am not sure what I am not understanding in this issue.

Cel = [39.5, 36.5, 37.3, 37.8]
Fer = lambda x: (float(9)/5*x for x in Cel + 32)
print(Fer)

prints:

<function <lambda> at 0x7fafc369eea0>

But, I want the list of values as:

[103.1, 97.70, 99.14, 100.03]

I then tried map with lambda

Fer2 = map(lambda x: (float(9)/5)*x + 32, Cel)
print(Fer2) # prints:
<map object at 0x7fafc36b5b38> # still no success

for x in Fer:
    print(x)  # this doesn't work and gives following error
TypeError: 'function' object is not iterable

for x in Fer2:
    print(x) # but this works and prints
             103.10
             97.7
             99.14
             100.039

Why can't I get print(Fer or Fer2) simply as a a list of values, like:
[103.1, 97.70, 99.14, 100.03]

How do I solve this within lambda, without writing another def function?

Body:
not quite sure why you need the lambda at all this is a simple list comprehensions

Fer = [32+float(9)/5*x for x in Cel]

or if you want to use lambda, you will have to use map

Fer = list(map(lambda x: (float(9)/5*x + 32),Cel))

Since you are iterating through Fer you can leave out the list

Fer = map(lambda x: (float(9)/5*x + 32),Cel)

Your current attempt is basically trying to mix map and list comprehensions. To elaborate further, what you are doing with the next line of code is to create a lambda function and assign it to a variable called Fer which is not what you want.

Fer = lambda x: (float(9)/5*x for x in Cel + 32)


问:
django - how to return two serializer in a response
I have two variable that i want to return: - serializer1.data and serializer2.data. I don't know how return 2 variable like : return Response(serializer1.data (and) serializer2.data, status=...). Any help is appreciated.</p>

答:
You can use the list comprehension of Python.

Like this:

```<code>    Serializer_list = [serializer1.data, serializer2.data]

    content = {
        'status': 1,
        'responseCode' : status.HTTP_200_OK,
        'data': Serializer_list,

        }
    return Response(content)
</code>```

And then use a for loop on data[0] variable.

Body:
You can use the list comprehension of Python.

Like this:

    Serializer_list = [serializer1.data, serializer2.data]

    content = {
        'status': 1,
        'responseCode' : status.HTTP_200_OK,
        'data': Serializer_list,

        }
    return Response(content)

And then use a for loop on data[0] variable.


答: You can use the UNIQUE constraint. For more information check here.</p>

ContentLicense: CC BY-SA 2.5

Title: MYSQL - how to a second unique string key?

Body:
Here is my goods table.

+----------------------+---------------+------+-----+---------+-------+
| Field                | Type          | Null | Key | Default | Extra |
+----------------------+---------------+------+-----+---------+-------+
| ID                   | decimal(18,0) | NO   | PRI |         |       |
| gkey                 | varchar(255)  | YES  | MUL | NULL    |       |
| GOODS                | decimal(18,0) | YES  | MUL | NULL    |       |

Column ID is auto-increment.
GOODS is the id of a goods category.
Here is the goods category table.

+-------+---------------------+
| ID    | NAME                |
+-------+---------------------+
| 1     | book                |
| 2     | phone               |
+-------+---------------------+

My question is in goods table I need the gkey is also an unique key with prefix-id(here id is started from 1.) Like BOOK-1,BOOK-2....PHONE-1,PHONE-2... when insert a new goods record into goods table.
Like that:

+--------------------+---------------+------+-----+---------+-------+
| ID                 | GKEY          |GOODS | PRI | COUNTRY | Extra |
+--------------------+---------------+------+-----+---------+-------+
| 1                  | BOOK-1        | 1    | 10  |         |       |
| 2                  | PHONE-1       | 2    | 12  |         |       |
| 3                  | BOOK-2        | 1    | 13  |         |       |
| 4                  | BOOK-3        | 1    | 10  |         |       |
| 5                  | PHONE-2       | 2    | 10  |         |       |
| 6                  | PHONE-3       | 2    | 20  |         |       |
+--------------------+---------------+------+-----+---------+-------+

How to get that GKEY in PHP+MYSQL?

thanks.


问:
Can't remove LFCR from text with the usual methods, Excel bug?
I have a list of strings littered with carriage return and line feed which I am trying to clean. I have tried the following methods:

find and replace of CTRL+J in excel

find and replace of ALT+0010/ALT+0013 in excel

find and replace of ALT+010/ALT+013 in excel

CLEAN in excel

copy list in excel, paste into notepad++, save as txt, reimport into excel ("Â" character was added on import) and finally replace "Â"

I've also tried the Text to Columns option with CTRL+J, absolutely no result whatsoever

EDIT: SUBSTITUTE CHAR(10) and CHAR(13) in excel didn't work either

None of the above worked, my list still contains line feeds and carriage returns. Is this a bug in excel?

Manually deleting these is out of the question due to the size of the list. I tried replacing these characters in notepad++ with pipe, and importing back into excel (choose delimited by pipe upon import and then copy/paste transpose), but again, the list is too long.

Anyone ideas?
Many thankZ

答:
The only thing I found working was pasting into Sublime, making everything visible, highlighting the characters, then CTRL+D highlight the same characters throughout the text, deleting them, then pressing space which added the spaces back to where the characters were between words and then copy back to excel and trim the lot.

Strangest thing I've ever seen...


问:
How to get the project path at Design Time
I use a component (System.ComponentModel.Component) and I want to get the application path of my project in order to create a file within it.

Thx

Florian

答:
If you are talking about WPF designer, please use "Context" property/type

Details:-
In Design time you have instance of modelItem (I assume it, you know it) if not then you can instantiate it in Override implementation of Activate method

// in  DesignAdorner class

```<code>public class DesignAdorner : PrimarySelectionAdornerProvider
{
      protected override void Activate(ModelItem item)
        {
                modelItem = item;
        }
}
</code>```

Now you can access the current application path using following single line code

```<code>string aplicationPathDir = System.IO.Directory.GetParent(modelItem.Context.ToString()).FullName;
</code>```

Let me know, if it does not help you.

Body:
If you are talking about WPF designer, please use "Context" property/type

Details:-
In Design time you have instance of modelItem (I assume it, you know it) if not then you can instantiate it in Override implementation of Activate method

// in  DesignAdorner class

public class DesignAdorner : PrimarySelectionAdornerProvider
{
      protected override void Activate(ModelItem item)
        {
                modelItem = item;
        }
}

Now you can access the current application path using following single line code

string aplicationPathDir = System.IO.Directory.GetParent(modelItem.Context.ToString()).FullName;

Let me know, if it does not help you.


问:
Add a firewall rule for Distributed Transaction Coordinator (msdtc.exe)
I tried to use firewallAPI.dll to add a rule. It works fine for calc.exe (or some other files) as described bellow but fails for msdtc.exe with the following exception:

System.IO.FileNotFoundException: 'The system cannot find the file
  specified. (Exception from HRESULT: 0x80070002)'

Example:

```<code>static void Main(string[] args)
{
    var manager = GetFirewallManager();
    if (manager.LocalPolicy.CurrentProfile.FirewallEnabled)
    {
        var path = @"C:\Windows\System32\calc.exe";
        //var path = @"C:\Windows\System32\msdtc.exe"; // System.IO.FileNotFoundException: 'The system cannot find the file specified.
        AuthorizeApplication("Test", path, NET_FW_SCOPE_.NET_FW_SCOPE_ALL, NET_FW_IP_VERSION_.NET_FW_IP_VERSION_ANY);
    }
}

private const string CLSID_FIREWALL_MANAGER =
    "{304CE942-6E39-40D8-943A-B913C40C9CD4}";

private static NetFwTypeLib.INetFwMgr GetFirewallManager()
{
    Type objectType = Type.GetTypeFromCLSID(
        new Guid(CLSID_FIREWALL_MANAGER));
    return Activator.CreateInstance(objectType)
        as NetFwTypeLib.INetFwMgr;
}

private const string PROGID_AUTHORIZED_APPLICATION =
    "HNetCfg.FwAuthorizedApplication";
public static bool AuthorizeApplication(string title, string applicationPath,
    NET_FW_SCOPE_ scope, NET_FW_IP_VERSION_ ipVersion)
{
    // Create the type from prog id
    Type type = Type.GetTypeFromProgID(PROGID_AUTHORIZED_APPLICATION);
    INetFwAuthorizedApplication auth = Activator.CreateInstance(type)
        as INetFwAuthorizedApplication;
    auth.Name = title;
    auth.ProcessImageFileName = applicationPath;
    auth.Scope = scope;
    auth.IpVersion = ipVersion;
    auth.Enabled = true;

    INetFwMgr manager = GetFirewallManager();
    manager.LocalPolicy.CurrentProfile.AuthorizedApplications.Add(auth);
    return true;
}
</code>```

Note: I checked the folder and see the file is located properly...
Could anybody help to add firewall rule for Distributed Transaction Coordinator? Maybe I should try to add another file to firewall (not msdtc.exe)?

答:
Project > Properties > Build tab, untick the "Prefer 32-bit" checkbox.  You don't prefer it, there is no 32-bit version of msdtc.exe.

Why the file system redirector caused the FileNotFoundException is explained well in this MSDN article.

Body:
I tried to use firewallAPI.dll to add a rule. It works fine for calc.exe (or some other files) as described bellow but fails for msdtc.exe with the following exception:

System.IO.FileNotFoundException: 'The system cannot find the file
  specified. (Exception from HRESULT: 0x80070002)'

Example:

static void Main(string[] args)
{
    var manager = GetFirewallManager();
    if (manager.LocalPolicy.CurrentProfile.FirewallEnabled)
    {
        var path = @"C:\Windows\System32\calc.exe";
        //var path = @"C:\Windows\System32\msdtc.exe"; // System.IO.FileNotFoundException: 'The system cannot find the file specified.
        AuthorizeApplication("Test", path, NET_FW_SCOPE_.NET_FW_SCOPE_ALL, NET_FW_IP_VERSION_.NET_FW_IP_VERSION_ANY);
    }
}

private const string CLSID_FIREWALL_MANAGER =
    "{304CE942-6E39-40D8-943A-B913C40C9CD4}";

private static NetFwTypeLib.INetFwMgr GetFirewallManager()
{
    Type objectType = Type.GetTypeFromCLSID(
        new Guid(CLSID_FIREWALL_MANAGER));
    return Activator.CreateInstance(objectType)
        as NetFwTypeLib.INetFwMgr;
}

private const string PROGID_AUTHORIZED_APPLICATION =
    "HNetCfg.FwAuthorizedApplication";
public static bool AuthorizeApplication(string title, string applicationPath,
    NET_FW_SCOPE_ scope, NET_FW_IP_VERSION_ ipVersion)
{
    // Create the type from prog id
    Type type = Type.GetTypeFromProgID(PROGID_AUTHORIZED_APPLICATION);
    INetFwAuthorizedApplication auth = Activator.CreateInstance(type)
        as INetFwAuthorizedApplication;
    auth.Name = title;
    auth.ProcessImageFileName = applicationPath;
    auth.Scope = scope;
    auth.IpVersion = ipVersion;
    auth.Enabled = true;

    INetFwMgr manager = GetFirewallManager();
    manager.LocalPolicy.CurrentProfile.AuthorizedApplications.Add(auth);
    return true;
}

Note: I checked the folder and see the file is located properly...
Could anybody help to add firewall rule for Distributed Transaction Coordinator? Maybe I should try to add another file to firewall (not msdtc.exe)?


问:
Storm-Kafka-client from Storm 1.0.1
Based on the Storm documentation supported implementation of  KafkaSpout is based on the old consumer API. I noticed the external package has another implementation named storm-kafka-client.

https://github.com/apache/storm/tree/master/external/storm-kafka-client

It is unclear if the new client release in 1.0.1 is production ready. Does anyone have experience running it?

答:
You can use following maven dependency for storm 1.1.0

```<code>  <dependency>
        <groupId>org.apache.storm</groupId>
        <artifactId>storm-core</artifactId>
         <version>1.1.0</version>
        <scope>provided</scope>
        <exclusions>
            <exclusion>
                <groupId>org.slf4j</groupId>
                <artifactId>log4j-over-slf4j</artifactId>
            </exclusion>
        </exclusions>
    </dependency>

 <dependency>
        <groupId>org.apache.kafka</groupId>
        <artifactId>kafka-clients</artifactId>
        <version>0.10.0.0</version>
    </dependency>
    <dependency>
    <groupId>org.apache.storm</groupId>
    <artifactId>storm-kafka</artifactId>
    <version>1.0.0</version>
</dependency>
    <dependency>
        <groupId>org.apache.kafka</groupId>
        <artifactId>kafka_2.10</artifactId>
         <version>0.9.0.0</version>
        <exclusions>
            <exclusion>
                <groupId>org.apache.zookeeper</groupId>
                <artifactId>zookeeper</artifactId>
            </exclusion>
            <exclusion>
                <groupId>log4j</groupId>
                <artifactId>log4j</artifactId>
            </exclusion>
        </exclusions>
    </dependency>
</code>```

You may face some more dependency issue which you can resolve by adding the required jars.

Also the dependency in java code will change from org.backtype.storm.XXXXX to org.apache.storm.XXXXX

Title: Storm-Kafka-client from Storm 1.0.1

Body:
You can use following maven dependency for storm 1.1.0

  <dependency>
        <groupId>org.apache.storm</groupId>
        <artifactId>storm-core</artifactId>
         <version>1.1.0</version>
        <scope>provided</scope>
        <exclusions>
            <exclusion>
                <groupId>org.slf4j</groupId>
                <artifactId>log4j-over-slf4j</artifactId>
            </exclusion>
        </exclusions>
    </dependency>

 <dependency>
        <groupId>org.apache.kafka</groupId>
        <artifactId>kafka-clients</artifactId>
        <version>0.10.0.0</version>
    </dependency>
    <dependency>
    <groupId>org.apache.storm</groupId>
    <artifactId>storm-kafka</artifactId>
    <version>1.0.0</version>
</dependency>
    <dependency>
        <groupId>org.apache.kafka</groupId>
        <artifactId>kafka_2.10</artifactId>
         <version>0.9.0.0</version>
        <exclusions>
            <exclusion>
                <groupId>org.apache.zookeeper</groupId>
                <artifactId>zookeeper</artifactId>
            </exclusion>
            <exclusion>
                <groupId>log4j</groupId>
                <artifactId>log4j</artifactId>
            </exclusion>
        </exclusions>
    </dependency>

You may face some more dependency issue which you can resolve by adding the required jars.

Also the dependency in java code will change from org.backtype.storm.XXXXX to org.apache.storm.XXXXX


问:
ImageTk and PIL do not display png image correctly
I am currently trying to write some kind of mapping tool in python using both the PIL and Tkinter module. So far almost everything works quite fine. During the setup process of the ui a virtual image is created (based upon several input png files), which also seems to have worked well. However, when trying to display this picture inside a canvas using ImageTk.Photo the display shows something that is definitly not the picture. For debugging reasons I had my picture be output by using the show method on the PIL.Image itself.

However what the show method shows and the canvas displays somehow differ - I could not figure out the solution and would appreciate help.

First of all the code excerts (I only show the initialization of the canvas and the displaying of the picture, since the whole code would be extremly long and not provide any more inside I guess).

This is the code excert of the initialization of the canvas (I display a completly black picture until the user loaded all resources neccessary for displaying the picture):

```<code>    self.tileset_canvas = tkinter.Canvas(root, width=1024, height=1024)
    self.tileset_canvas.create_line(0, 0, 80, 80)
    self.tileset_raw_image = ImageTk.PhotoImage(PImage.new("RGB", (1024, 1024), "black"))
    self.tileset_canvas_image = self.tileset_canvas.create_image(0, 0, image=self.tileset_raw_image)
    self.tileset_canvas.grid(row=4, column=6, sticky=tkinter.W)
</code>```

Furthermore inside another method I change the display of the image:

```<code>        merged_img = PImage.new("RGB", (128, 512))
        merged_img.paste(tsp_img, (0, 0))
        merged_img.paste(tss_img, (0, 320))
        merged_img = merged_img.resize((1024, 1024)) #Double the view for a better mapping expierience
        merged_img = merged_img.convert(mode="RGB")
        self.tileset_raw_image = ImageTk.PhotoImage(merged_img)
        merged_img.show()
        self.tileset_canvas.itemconfig(self.tileset_canvas_image, image=self.tileset_raw_image)
</code>```

As you can see I also call the show method to see what the picture actually looks like.

This is what the show method outputs, when called on the picture:

However this is what is shown inside the ui:

答: For anyone that cares, it seems that the image was not just correctly anchored but instead fixed in the middle of the canvas.</p>

Body:
I am currently trying to write some kind of mapping tool in python using both the PIL and Tkinter module. So far almost everything works quite fine. During the setup process of the ui a virtual image is created (based upon several input png files), which also seems to have worked well. However, when trying to display this picture inside a canvas using ImageTk.Photo the display shows something that is definitly not the picture. For debugging reasons I had my picture be output by using the show method on the PIL.Image itself.

However what the show method shows and the canvas displays somehow differ - I could not figure out the solution and would appreciate help.

First of all the code excerts (I only show the initialization of the canvas and the displaying of the picture, since the whole code would be extremly long and not provide any more inside I guess).

This is the code excert of the initialization of the canvas (I display a completly black picture until the user loaded all resources neccessary for displaying the picture):

    self.tileset_canvas = tkinter.Canvas(root, width=1024, height=1024)
    self.tileset_canvas.create_line(0, 0, 80, 80)
    self.tileset_raw_image = ImageTk.PhotoImage(PImage.new("RGB", (1024, 1024), "black"))
    self.tileset_canvas_image = self.tileset_canvas.create_image(0, 0, image=self.tileset_raw_image)
    self.tileset_canvas.grid(row=4, column=6, sticky=tkinter.W)

Furthermore inside another method I change the display of the image:

        merged_img = PImage.new("RGB", (128, 512))
        merged_img.paste(tsp_img, (0, 0))
        merged_img.paste(tss_img, (0, 320))
        merged_img = merged_img.resize((1024, 1024)) #Double the view for a better mapping expierience
        merged_img = merged_img.convert(mode="RGB")
        self.tileset_raw_image = ImageTk.PhotoImage(merged_img)
        merged_img.show()
        self.tileset_canvas.itemconfig(self.tileset_canvas_image, image=self.tileset_raw_image)

As you can see I also call the show method to see what the picture actually looks like.

This is what the show method outputs, when called on the picture:

However this is what is shown inside the ui:


问:
Relay Modern: Connecting websocket to network layer
I’m having issues figuring out how to connect the Relay Modern network layer with my websocket instance.

I’m currently instantiating a websocket instance as:

```<code>const subscriptionWebSocket = new ReconnectingWebSocket('ws://url.url/ws/subscriptions/', null, options);
</code>```

I'm specifying the subscription and creating a new instance of requestSubscription:

```<code>const subscription = graphql`
  subscription mainSubscription {
    testData {
      anotherNode {
        data
      }
    }
  }
`;

requestSubscription(
  environment,
  {
    subscription,
    variables: {},
    onComplete: () => {...},
    onError: (error) => {...},
    onNext: (response) => {...},
    updater: (updaterStoreConfig) => {...},
  },
);
</code>```

Which then allows me to send any subscription requests:

```<code>function subscriptionHandler(subscriptionConfig, variables, cacheConfig, observer) {
  subscriptionWebSocket.send(JSON.stringify(subscriptionConfig.text));

  return {
    dispose: () => {
      console.log('subscriptionHandler: Disposing subscription');
    },
  };
}

const network = Network.create(fetchQuery, subscriptionHandler);
</code>```

through to my server (currently using Graphene-python), and I’m able to interpret the received message on the server.

However, what I’m having issues figuring out is how to respond to a subscription; for example, when something changes in my DB, I want to generate a response and return to any potential subscribers.

The question being, how do I connect the onMessage event from my websocket instance into my Relay Modern Network Layer? I've browsed through the source for relay but can't seem to figure out what callback, or what method should be implementing an onreceive.

Any tips are appreciated.

答:
I’ll just write down how I’ve approached this issue after the assistance found in this thread. It might be usable for someone else. This is very dependent on the server-side solution that you've chosen.

My approach:

Firstly I built a SubscriptionHandler that will handle the requestStream#subscribeFunction through SubscriptionHandler#setupSubscription.

The SubscriptionHandler instantiates a WebSocket (using a custom version of ReconnectingWebSockets) and attaches the onmessage event to an internal method (SubscriptionHandler#receiveSubscriptionPayload) which will add the payload to the corresponding request.

We create new subscriptions through SubscriptionHandler#newSubscription which will use the internal attribute SubscriptionHandler.subscriptions to add a keyed entry of this subscription (we use an MD5-hash util over the query and variables); meaning the object will come out as:

```<code>SubscriptionHandler.subscriptions = {
  [md5hash]: {
    query: QueryObject,
    variables: SubscriptionVariables,
    observer: Observer (contains OnNext method)
}
</code>```

Whenever the server sends a subscription response the SubscriptionHandler#receiveSubscriptionPayload method will be called and it will identify what subscription the payload belongs to by using the query/variables md5 hash, then use the SubscriptionHandler.subscriptions observer onNext method.

This approach requires the server to return a message such as:

```<code>export type ServerResponseMessageParsed = {
  payload: QueryPayload,
  request: {
    query: string,
    variables: Object,
  }
}
</code>```

I do not know if this is a great way of handling subscriptions, but it works for now with my current setup.

SubscriptionHandler.js

```<code>class SubscriptionHandler {
  subscriptions: Object;
  subscriptionEnvironment: RelayModernEnvironment;
  websocket: Object;

  /**
   * The SubscriptionHandler constructor. Will setup a new websocket and bind
   * it to internal method to handle receving messages from the ws server.
   *
   * @param  {string} websocketUrl      - The WebSocket URL to listen to.
   * @param  {Object} webSocketSettings - The options object.
   *                                      See ReconnectingWebSocket.
   */
  constructor(websocketUrl: string, webSocketSettings: WebSocketSettings) {
    // All subscription hashes and objects will be stored in the
    // this.subscriptions attribute on the subscription handler.
    this.subscriptions = {};

    // Store the given environment internally to be reused when registering new
    // subscriptions. This is required as per the requestRelaySubscription spec
    // (method requestSubscription).
    this.subscriptionEnvironment = null;

    // Create a new WebSocket instance to be able to receive messages on the
    // given URL. Always opt for default protocol for the RWS, second arg.
    this.websocket = new ReconnectingWebSocket(
      websocketUrl,
      null,  // Protocol.
      webSocketSettings,
    );

    // Bind an internal method to handle incoming messages from the websocket.
    this.websocket.onmessage = this.receiveSubscriptionPayload;
  }

  /**
   * Method to attach the Relay Environment to the subscription handler.
   * This is required as the Network needs to be instantiated with the
   * SubscriptionHandler's methods, and the Environment needs the Network Layer.
   *
   * @param  {Object} environment - The apps environment.
   */
  attachEnvironment = (environment: RelayModernEnvironment) => {
    this.subscriptionEnvironment = environment;
  }

  /**
   * Generates a hash from a given query and variable pair. The method
   * used is a recreatable MD5 hash, which is used as a 'key' for the given
   * subscription. Using the MD5 hash we can identify what subscription is valid
   * based on the query/variable given from the server.
   *
   * @param  {string} query     - A string representation of the subscription.
   * @param  {Object} variables - An object containing all variables used
   *                              in the query.
   * @return {string}             The MD5 hash of the query and variables.
   */
  getHash = (query: string, variables: HashVariables) => {
    const queryString = query.replace(/\s+/gm, '');
    const variablesString = JSON.stringify(variables);
    const hash = md5(queryString + variablesString).toString();
    return hash;
  }

  /**
   * Method to be bound to the class websocket instance. The method will be
   * called each time the WebSocket receives a message on the subscribed URL
   * (see this.websocket options).
   *
   * @param  {string} message - The message received from the websocket.
   */
  receiveSubscriptionPayload = (message: ServerResponseMessage) => {
    const response: ServerResponseMessageParsed = JSON.parse(message.data);
    const { query, variables } = response.request;
    const hash = this.getHash(query, variables);

    // Fetch the subscription instance from the subscription handlers stored
    // subscriptions.
    const subscription = this.subscriptions[hash];

    if (subscription) {
      // Execute the onNext method with the received payload after validating
      // that the received hash is currently stored. If a diff occurs, meaning
      // no hash is stored for the received response, ignore the execution.
      subscription.observer.onNext(response.payload);
    } else {
      console.warn(Received payload for unregistered hash: ${hash});
    }
  }

  /**
   * Method to generate new subscriptions that will be bound to the
   * SubscriptionHandler's environment and will be stored internally in the
   * instantiated handler object.
   *
   * @param {string} subscriptionQuery - The query to subscribe to. Needs to
   *                                     be a validated subscription type.
   * @param {Object} variables         - The variables for the passed query.
   * @param {Object} configs           - A subscription configuration. If
   *                                     override is required.
   */
  newSubscription = (
      subscriptionQuery: GraphQLTaggedNode,
      variables: Variables,
      configs: GraphQLSubscriptionConfig,
  ) => {
    const config = configs || DEFAULT_CONFIG;

    requestSubscription(
      this.subscriptionEnvironment,
      {
        subscription: subscriptionQuery,
        variables: {},
        ...config,
      },
    );
  }

  setupSubscription = (
    config: ConcreteBatch,
    variables: Variables,
    cacheConfig: ?CacheConfig,
    observer: Observer,
  ) => {
    const query = config.text;

    // Get the hash from the given subscriptionQuery and variables. Used to
    // identify this specific subscription.
    const hash = this.getHash(query, variables);

    // Store the newly created subscription request internally to be re-used
    // upon message receival or local data updates.
    this.subscriptions[hash] = { query, variables };

    const subscription = this.subscriptions[hash];
    subscription.observer = observer;

    // Temp fix to avoid WS Connection state.
    setTimeout(() => {
      this.websocket.send(JSON.stringify({ query, variables }));
    }, 100);
  }
}

const subscriptionHandler = new SubscriptionHandler(WS_URL, WS_OPTIONS);

export default subscriptionHandler;
</code>```

Body:
I’m having issues figuring out how to connect the Relay Modern network layer with my websocket instance.

I’m currently instantiating a websocket instance as:

const subscriptionWebSocket = new ReconnectingWebSocket('ws://url.url/ws/subscriptions/', null, options);

I'm specifying the subscription and creating a new instance of requestSubscription:

const subscription = graphql`
  subscription mainSubscription {
    testData {
      anotherNode {
        data
      }
    }
  }
`;

requestSubscription(
  environment,
  {
    subscription,
    variables: {},
    onComplete: () => {...},
    onError: (error) => {...},
    onNext: (response) => {...},
    updater: (updaterStoreConfig) => {...},
  },
);

Which then allows me to send any subscription requests:

function subscriptionHandler(subscriptionConfig, variables, cacheConfig, observer) {
  subscriptionWebSocket.send(JSON.stringify(subscriptionConfig.text));

  return {
    dispose: () => {
      console.log('subscriptionHandler: Disposing subscription');
    },
  };
}

const network = Network.create(fetchQuery, subscriptionHandler);

through to my server (currently using Graphene-python), and I’m able to interpret the received message on the server.

However, what I’m having issues figuring out is how to respond to a subscription; for example, when something changes in my DB, I want to generate a response and return to any potential subscribers.

The question being, how do I connect the onMessage event from my websocket instance into my Relay Modern Network Layer? I've browsed through the source for relay but can't seem to figure out what callback, or what method should be implementing an onreceive.

Any tips are appreciated.

Body:
I’ll just write down how I’ve approached this issue after the assistance found in this thread. It might be usable for someone else. This is very dependent on the server-side solution that you've chosen.

My approach:

Firstly I built a SubscriptionHandler that will handle the requestStream#subscribeFunction through SubscriptionHandler#setupSubscription.

The SubscriptionHandler instantiates a WebSocket (using a custom version of ReconnectingWebSockets) and attaches the onmessage event to an internal method (SubscriptionHandler#receiveSubscriptionPayload) which will add the payload to the corresponding request.

We create new subscriptions through SubscriptionHandler#newSubscription which will use the internal attribute SubscriptionHandler.subscriptions to add a keyed entry of this subscription (we use an MD5-hash util over the query and variables); meaning the object will come out as:

SubscriptionHandler.subscriptions = {
  [md5hash]: {
    query: QueryObject,
    variables: SubscriptionVariables,
    observer: Observer (contains OnNext method)
}

Whenever the server sends a subscription response the SubscriptionHandler#receiveSubscriptionPayload method will be called and it will identify what subscription the payload belongs to by using the query/variables md5 hash, then use the SubscriptionHandler.subscriptions observer onNext method.

This approach requires the server to return a message such as:

export type ServerResponseMessageParsed = {
  payload: QueryPayload,
  request: {
    query: string,
    variables: Object,
  }
}

I do not know if this is a great way of handling subscriptions, but it works for now with my current setup.

SubscriptionHandler.js

class SubscriptionHandler {
  subscriptions: Object;
  subscriptionEnvironment: RelayModernEnvironment;
  websocket: Object;

  /**
   * The SubscriptionHandler constructor. Will setup a new websocket and bind
   * it to internal method to handle receving messages from the ws server.
   *
   * @param  {string} websocketUrl      - The WebSocket URL to listen to.
   * @param  {Object} webSocketSettings - The options object.
   *                                      See ReconnectingWebSocket.
   */
  constructor(websocketUrl: string, webSocketSettings: WebSocketSettings) {
    // All subscription hashes and objects will be stored in the
    // this.subscriptions attribute on the subscription handler.
    this.subscriptions = {};

    // Store the given environment internally to be reused when registering new
    // subscriptions. This is required as per the requestRelaySubscription spec
    // (method requestSubscription).
    this.subscriptionEnvironment = null;

    // Create a new WebSocket instance to be able to receive messages on the
    // given URL. Always opt for default protocol for the RWS, second arg.
    this.websocket = new ReconnectingWebSocket(
      websocketUrl,
      null,  // Protocol.
      webSocketSettings,
    );

    // Bind an internal method to handle incoming messages from the websocket.
    this.websocket.onmessage = this.receiveSubscriptionPayload;
  }

  /**
   * Method to attach the Relay Environment to the subscription handler.
   * This is required as the Network needs to be instantiated with the
   * SubscriptionHandler's methods, and the Environment needs the Network Layer.
   *
   * @param  {Object} environment - The apps environment.
   */
  attachEnvironment = (environment: RelayModernEnvironment) => {
    this.subscriptionEnvironment = environment;
  }

  /**
   * Generates a hash from a given query and variable pair. The method
   * used is a recreatable MD5 hash, which is used as a 'key' for the given
   * subscription. Using the MD5 hash we can identify what subscription is valid
   * based on the query/variable given from the server.
   *
   * @param  {string} query     - A string representation of the subscription.
   * @param  {Object} variables - An object containing all variables used
   *                              in the query.
   * @return {string}             The MD5 hash of the query and variables.
   */
  getHash = (query: string, variables: HashVariables) => {
    const queryString = query.replace(/\s+/gm, '');
    const variablesString = JSON.stringify(variables);
    const hash = md5(queryString + variablesString).toString();
    return hash;
  }

  /**
   * Method to be bound to the class websocket instance. The method will be
   * called each time the WebSocket receives a message on the subscribed URL
   * (see this.websocket options).
   *
   * @param  {string} message - The message received from the websocket.
   */
  receiveSubscriptionPayload = (message: ServerResponseMessage) => {
    const response: ServerResponseMessageParsed = JSON.parse(message.data);
    const { query, variables } = response.request;
    const hash = this.getHash(query, variables);

    // Fetch the subscription instance from the subscription handlers stored
    // subscriptions.
    const subscription = this.subscriptions[hash];

    if (subscription) {
      // Execute the onNext method with the received payload after validating
      // that the received hash is currently stored. If a diff occurs, meaning
      // no hash is stored for the received response, ignore the execution.
      subscription.observer.onNext(response.payload);
    } else {
      console.warn(Received payload for unregistered hash: ${hash});
    }
  }

  /**
   * Method to generate new subscriptions that will be bound to the
   * SubscriptionHandler's environment and will be stored internally in the
   * instantiated handler object.
   *
   * @param {string} subscriptionQuery - The query to subscribe to. Needs to
   *                                     be a validated subscription type.
   * @param {Object} variables         - The variables for the passed query.
   * @param {Object} configs           - A subscription configuration. If
   *                                     override is required.
   */
  newSubscription = (
      subscriptionQuery: GraphQLTaggedNode,
      variables: Variables,
      configs: GraphQLSubscriptionConfig,
  ) => {
    const config = configs || DEFAULT_CONFIG;

    requestSubscription(
      this.subscriptionEnvironment,
      {
        subscription: subscriptionQuery,
        variables: {},
        ...config,
      },
    );
  }

  setupSubscription = (
    config: ConcreteBatch,
    variables: Variables,
    cacheConfig: ?CacheConfig,
    observer: Observer,
  ) => {
    const query = config.text;

    // Get the hash from the given subscriptionQuery and variables. Used to
    // identify this specific subscription.
    const hash = this.getHash(query, variables);

    // Store the newly created subscription request internally to be re-used
    // upon message receival or local data updates.
    this.subscriptions[hash] = { query, variables };

    const subscription = this.subscriptions[hash];
    subscription.observer = observer;

    // Temp fix to avoid WS Connection state.
    setTimeout(() => {
      this.websocket.send(JSON.stringify({ query, variables }));
    }, 100);
  }
}

const subscriptionHandler = new SubscriptionHandler(WS_URL, WS_OPTIONS);

export default subscriptionHandler;


问:
Awk Command not working as it should, output is wrong, sed command?
I tried this little script on my dataset and for some reason I am not getting the desired output? can someone have a look ? Maybe you can figure it out? Also if you could offer a SED command solution.

Script

```<code>awk -v RS= -F '<connection name="|<hostPort>' '
{
sub(/".*/, "", $2)
split($3, tokens, /[:<]/)
printf "%-6s %s %s\n", $2, tokens[1], tokens[2]
}
'
</code>```

input

```<code><hostPort>srv1:33333</hostPort>
<hostPort>srv2:33333</hostPort>
<connection name="boing_ny__Primary__" transport="tcp">
<hostPort>srv1:33333</hostPort>
<connection name="boing_ny__Backup__" transport="tcp">
<hostPort>srv2:33333</hostPort>
<connection name="boy_ny__Primary__" transport="tcp">
<hostPort>srv1:6666</hostPort>
<connection name="boy_ny__Backup__" transport="tcp">
<hostPort>srv2:6666</hostPort>
<connection name="song_ny__Primary__" transport="tcp">
<hostPort>srv1:55555</hostPort>
<connection name="song_ny__Backup__" transport="tcp">
<hostPort>srv2:55555</hostPort>
<connection name="bob_ny__Primary__" transport="tcp">
<hostPort>srv3:33333</hostPort>
<connection name="bob_ny__Backup__" transport="tcp">
<hostPort>srv4:33333</hostPort>
<hostPort>srv1:4444</hostPort>
<hostPort>srv2:4444</hostPort>
<hostPort>srv1:4444</hostPort>
</code>```

Current output

```<code>srv1:33333</hostPort>
srv2 33333
</code>```

desired output

```<code>boing_ny__Primary__  srv1 33333
boing_ny__Backup__   srv2 33333
boy_ny__Primary__     srv1 6666
boy_ny__Backup__   srv2 6666
song_ny__Primary__ srv1 55555
song_ny__Backup__ srv2 55555
bob_ny__Primary__ srv3 33333
bob_ny__Backup__ srv4 33333
</code>```

答:
robust:
cat input | awk -F'\"|>' '{print $2}' | awk -F'<' '{print $1}' | sed -z 's/_\n/_ /g' | grep -v ^srv | tr ":" " "

Body:
I tried this little script on my dataset and for some reason I am not getting the desired output? can someone have a look ? Maybe you can figure it out? Also if you could offer a SED command solution.

Script

awk -v RS= -F '<connection name="|<hostPort>' '
{
sub(/".*/, "", $2)
split($3, tokens, /[:<]/)
printf "%-6s %s %s\n", $2, tokens[1], tokens[2]
}
'

input

<hostPort>srv1:33333</hostPort>
<hostPort>srv2:33333</hostPort>
<connection name="boing_ny__Primary__" transport="tcp">
<hostPort>srv1:33333</hostPort>
<connection name="boing_ny__Backup__" transport="tcp">
<hostPort>srv2:33333</hostPort>
<connection name="boy_ny__Primary__" transport="tcp">
<hostPort>srv1:6666</hostPort>
<connection name="boy_ny__Backup__" transport="tcp">
<hostPort>srv2:6666</hostPort>
<connection name="song_ny__Primary__" transport="tcp">
<hostPort>srv1:55555</hostPort>
<connection name="song_ny__Backup__" transport="tcp">
<hostPort>srv2:55555</hostPort>
<connection name="bob_ny__Primary__" transport="tcp">
<hostPort>srv3:33333</hostPort>
<connection name="bob_ny__Backup__" transport="tcp">
<hostPort>srv4:33333</hostPort>
<hostPort>srv1:4444</hostPort>
<hostPort>srv2:4444</hostPort>
<hostPort>srv1:4444</hostPort>

Current output

srv1:33333</hostPort>
srv2 33333

desired output

boing_ny__Primary__  srv1 33333
boing_ny__Backup__   srv2 33333
boy_ny__Primary__     srv1 6666
boy_ny__Backup__   srv2 6666
song_ny__Primary__ srv1 55555
song_ny__Backup__ srv2 55555
bob_ny__Primary__ srv3 33333
bob_ny__Backup__ srv4 33333


问:
PHP add elements to array using foreach()
How to add elements to the array using the foreach loop?

```<code>    $list = [
        ['User-ID', 'Payout-ID', 'Amount', 'Withdraw address', 'Date'],
    ];

    //generate CSV
    foreach ($open_payouts as $open_payout) {
        $list .= [
            (string)$open_payout->user_id,
            (string)$open_payout->id,
            (string)number_format($open_payout->amount / 100000000, 8, '.', ''),
            (string)$open_payout->user->withdraw_address,
            (string)$open_payout->created_at,
        ];
    }

    $fp = fopen(app_path() . '/CSV/file.csv', 'w');
    //write whole list
    foreach ($list as $fields) {
        fputcsv($fp, $fields);
    }
</code>```

It seems like my problem is located at $list .=. How to insert another array into this array, so I can generate a .CSV file from the arrays?

答:
.= is used to concatenate strings - not arrays.

You simply need to use;

```<code>$list[] = [
        (string)$open_payout->user_id,
        (string)$open_payout->id,
        (string)number_format($open_payout->amount / 100000000, 8, '.', ''),
        (string)$open_payout->user->withdraw_address,
        (string)$open_payout->created_at,
    ];
</code>```

That will add your new array onto the end of your $list array.

You could also use array_push();

```<code>array_push($list, [
    (string)$open_payout->user_id,
    (string)$open_payout->id,
    (string)number_format($open_payout->amount / 100000000, 8, '.', ''),
    (string)$open_payout->user->withdraw_address,
    (string)$open_payout->created_at,
]);
</code>```

Body:
How to add elements to the array using the foreach loop?

    $list = [
        ['User-ID', 'Payout-ID', 'Amount', 'Withdraw address', 'Date'],
    ];

    //generate CSV
    foreach ($open_payouts as $open_payout) {
        $list .= [
            (string)$open_payout->user_id,
            (string)$open_payout->id,
            (string)number_format($open_payout->amount / 100000000, 8, '.', ''),
            (string)$open_payout->user->withdraw_address,
            (string)$open_payout->created_at,
        ];
    }

    $fp = fopen(app_path() . '/CSV/file.csv', 'w');
    //write whole list
    foreach ($list as $fields) {
        fputcsv($fp, $fields);
    }

It seems like my problem is located at $list .=. How to insert another array into this array, so I can generate a .CSV file from the arrays?

Body:
.= is used to concatenate strings - not arrays.

You simply need to use;

$list[] = [
        (string)$open_payout->user_id,
        (string)$open_payout->id,
        (string)number_format($open_payout->amount / 100000000, 8, '.', ''),
        (string)$open_payout->user->withdraw_address,
        (string)$open_payout->created_at,
    ];

That will add your new array onto the end of your $list array.

You could also use array_push();

array_push($list, [
    (string)$open_payout->user_id,
    (string)$open_payout->id,
    (string)number_format($open_payout->amount / 100000000, 8, '.', ''),
    (string)$open_payout->user->withdraw_address,
    (string)$open_payout->created_at,
]);


问:
It doesn't render when I use *ngFor (Angular 4)

I'm new with angular 4. I have 2 components apart app.components : home.component and product.component. I initialized array elements of product in app.component.ts. and I want to display list of products on home.component.html by using *ngFor. It does not render where I set  in home.component.html but it does render if only I call . Where is the problem ?

app.module.ts

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { HttpModule } from '@angular/http';
import { RouterModule } from '@angular/router';

import { AppComponent } from './app.component';
import { ProductComponent } from './product/product.component';
import { DetailsComponent } from './details/details.component';
import { HomeComponent } from './home/home.component';

@NgModule({
  declarations: [
    AppComponent,
    ProductComponent,
    DetailsComponent,
    HomeComponent
  ],
  imports: [
    BrowserModule,
    FormsModule,
    HttpModule,
    RouterModule.forRoot([
      {
        path: '',
        pathMatch: 'full',
        component: HomeComponent
      },
      {
        path: 'product',
        component: ProductComponent
      },
      {
        path: 'details',
        component: DetailsComponent
      }
    ])
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }
```

<p>app.component.ts</p>

<pre class="lang-js prettyprint-override"><code>import { Component } from '@angular/core';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  title = 'app works!';

  products = [{
    titre:"titre1",
    desc:"desc1"
  },{
    titre:"titre2",
    desc:"desc2"
  },{
    titre:"titre3",
    desc:"desc3"
  }];
}
</code>```

app.component.html

<router-outlet></router-outlet>
```

<p>product.component.ts </p>

<pre class="lang-js prettyprint-override"><code>import {Component, OnInit, Input} from '@angular/core';

@Component({
  selector: 'product',
  templateUrl: './product.component.html',
  styleUrls: ['./product.component.css']
})
export class ProductComponent implements OnInit {

  @Input() titre:string;
  @Input() description:string;
  constructor() { }

  ngOnInit() {
  }

}
</code>```

product.component.html

{{titre}}

{{desc}}

```

<p>home.component.html</p>

<pre class="lang-html prettyprint-override"><code><div class="home">

  <div class="album text-muted">
  <div class="container">

    <div class="row">

      <product
    class="col-md-4"
    *ngFor="let p of products"
    [description]="p.desc"
    [titre]="p.titre">
      </product>

      <!--<product></product>-->

    </div>

  </div>
</div>

</div>
</code>```

答:
Is products defined in your home.component.ts?
HomeComponent should look like this:

```<code>export class HomeComponent{
  products = [{
    titre:"titre1",
    desc:"desc1"
  },{
    titre:"titre2",
    desc:"desc2"
  },{
    titre:"titre3",
    desc:"desc3"
  }];
}
</code>```

Body:
I'm new with angular 4. I have 2 components apart app.components : home.component and product.component. I initialized array elements of product in app.component.ts. and I want to display list of products on home.component.html by using *ngFor. It does not render where I set  in home.component.html but it does render if only I call . Where is the problem ?

app.module.ts

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { HttpModule } from '@angular/http';
import { RouterModule } from '@angular/router';

import { AppComponent } from './app.component';
import { ProductComponent } from './product/product.component';
import { DetailsComponent } from './details/details.component';
import { HomeComponent } from './home/home.component';

@NgModule({
  declarations: [
    AppComponent,
    ProductComponent,
    DetailsComponent,
    HomeComponent
  ],
  imports: [
    BrowserModule,
    FormsModule,
    HttpModule,
    RouterModule.forRoot([
      {
        path: '',
        pathMatch: 'full',
        component: HomeComponent
      },
      {
        path: 'product',
        component: ProductComponent
      },
      {
        path: 'details',
        component: DetailsComponent
      }
    ])
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

app.component.ts

import { Component } from '@angular/core';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  title = 'app works!';

  products = [{
    titre:"titre1",
    desc:"desc1"
  },{
    titre:"titre2",
    desc:"desc2"
  },{
    titre:"titre3",
    desc:"desc3"
  }];
}

app.component.html

<router-outlet></router-outlet>

product.component.ts

import {Component, OnInit, Input} from '@angular/core';

@Component({
  selector: 'product',
  templateUrl: './product.component.html',
  styleUrls: ['./product.component.css']
})
export class ProductComponent implements OnInit {

  @Input() titre:string;
  @Input() description:string;
  constructor() { }

  ngOnInit() {
  }

}

product.component.html

{{titre}}

{{desc}}

home.component.html

      <product
    class="col-md-4"
    *ngFor="let p of products"
    [description]="p.desc"
    [titre]="p.titre">
      </product>

Body:
Is products defined in your home.component.ts?
HomeComponent should look like this:

export class HomeComponent{
  products = [{
    titre:"titre1",
    desc:"desc1"
  },{
    titre:"titre2",
    desc:"desc2"
  },{
    titre:"titre3",
    desc:"desc3"
  }];
}


问:
getSupportFragmentManager().getFragments() NPE
I tried to post the Activity's onActivityResult() to its sub-Fragments and got a NPE. I have no idea why the fragment is null.

```<code>@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);

    for (Fragment fragment : getSupportFragmentManager().getFragments()) {
        if (fragment != null) {
            fragment.onActivityResult(requestCode, resultCode, data);
        }
    }
}
</code>```

Excpetion:

java.lang.NullPointerException: Attempt to invoke virtual method 'void android.support.v4.app.Fragment.onActivityResult(int, int, android.content.Intent)' on a null object reference

答: There is a method "makeInactive(Fragment f)" in FragmentManager which use "mActive.set(f.mIndex, null);" to set the fragment null. I should have thought it just remove the fragment from the list instead of setting a null to it.</p>

Body:
I tried to post the Activity's onActivityResult() to its sub-Fragments and got a NPE. I have no idea why the fragment is null.

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);

    for (Fragment fragment : getSupportFragmentManager().getFragments()) {
        if (fragment != null) {
            fragment.onActivityResult(requestCode, resultCode, data);
        }
    }
}

Excpetion:

java.lang.NullPointerException: Attempt to invoke virtual method 'void android.support.v4.app.Fragment.onActivityResult(int, int, android.content.Intent)' on a null object reference


问:
Convert JSONObject to JSONArray in Android JAVA?
I am trying to prepare JSON data for an ArrayAdapter to add to a listView.

A breakdown of the JSON I am digesting from a server is such:

```<code>{
"friends": {
            "mufasa3": "false",
            "jenkins": "false"
           }
}
</code>```

I convert this JSON to a java JSONObject like:

```<code>try {
                JSONObject obj = new JSONObject(jsonDigest);

                Object thelist = obj.get("friends");

                }

            }catch(JSONException e){
                throw new RuntimeException(e);
            }
</code>```

How do I convert Object thelist to an Array so that I can use it with a my custom ArrayAdapter?
I've tried JSONArray arr = obj.toJSONArray("friends"); but errors because there is no existing array in the JSONObject.

答:
You can iterate though all the keys in JSONObject and add it to a list</p>

```<code>List<String> friends=new ArrayList<>();

for(Iterator<String> iter = json.keys();iter.hasNext();) {
    String key = iter.next();
    friends.add(key);
    ...
}
</code>```

Body:
I am trying to prepare JSON data for an ArrayAdapter to add to a listView.

A breakdown of the JSON I am digesting from a server is such:

{
"friends": {
            "mufasa3": "false",
            "jenkins": "false"
           }
}

I convert this JSON to a java JSONObject like:

try {
                JSONObject obj = new JSONObject(jsonDigest);

                Object thelist = obj.get("friends");

                }

            }catch(JSONException e){
                throw new RuntimeException(e);
            }

How do I convert Object thelist to an Array so that I can use it with a my custom ArrayAdapter?
I've tried JSONArray arr = obj.toJSONArray("friends"); but errors because there is no existing array in the JSONObject.

Body:
You can iterate though all the keys in JSONObject and add it to a list

List<String> friends=new ArrayList<>();

for(Iterator<String> iter = json.keys();iter.hasNext();) {
    String key = iter.next();
    friends.add(key);
    ...
}


问:
How to increase slider values in whole numbers when starting value is 2 decimals
I have a price slider that submits and works as it should. The only thing it doesn't do is increase the values of the slider in whole numbers when the starting value is a 2 decimal number.
It also doesn't display the initial 2 decimal number. Just to show what I mean here is the code:

```<code> $Deposit= '12.85';
<script>
   Deposit_increase = <?php echo (isset($_GET['Deposit_increase'])) ?
   $_GET['Deposit_increase'] : 0 ?>;

   $(document).ready(function() {
   $( "#slider-range-min" ).slider({
      range: "min",
      value: <?php echo $Deposit ?>,
      min: <?php echo $Deposit ?>,
      max: 3000,

      values : [Deposit_increase],
                slide : function(event, ui) {
                    $("#Deposit_increase").val(ui.values[0]);
                },
        change: function() {
            $("#increase_form").submit();
        }
    });
    $("#Deposit_increase").val($("#slider-range-min").slider("values", 0));
});
  </script>
</code>```

The form:

```<code> <form action="" id="increase_form" method="get">

           <p  style="margin-left:12%; color:#2872bd; font-weight:bold; text-align:left">
  Change your Depost<br><br>
Deposit: £
  <input type="text" id="Deposit_increase" name="Deposit_increase"  style="border:0; color:#2872bd; font-weight:bold; text-align:left"  value="<?php echo $_GET['Deposit_increase']; ?>">

</p>
        <div id="slider-range-min"></div></form>
</code>```

Here it displays as follows:
Deposit: £12.9  (instead of £12.85)

The slider uses increments of 1 so all values will be shown as 13.9, 14.9. 15.9 etc.

What I want the slider to show is:
14, 15, 16 etc.

Is there a way to achieve this? Any help welcome

答:
You must use either Math.round() for this situation

Math.round will round your value to the nearest whole number

Body:
I have a price slider that submits and works as it should. The only thing it doesn't do is increase the values of the slider in whole numbers when the starting value is a 2 decimal number.
It also doesn't display the initial 2 decimal number. Just to show what I mean here is the code:

 $Deposit= '12.85';

The form:

 <form action="" id="increase_form" method="get">

  Change your Depost

Deposit: £
  <input type="text" id="Deposit_increase" name="Deposit_increase"  style="border:0; color:#2872bd; font-weight:bold; text-align:left"  value="<?php echo $_GET['Deposit_increase']; ?>">

</form>

Here it displays as follows:
Deposit: £12.9  (instead of £12.85)

The slider uses increments of 1 so all values will be shown as 13.9, 14.9. 15.9 etc.

What I want the slider to show is:
14, 15, 16 etc.

Is there a way to achieve this? Any help welcome


问:
Angularjs: How to get value of input without ng-model
I need to make some inputs by ng-repeat, and in my json file I have in object where is a property called name, like this:

```<code>"url":"find_company",
    "values":[
      {
        "name":"company name",
        "type":"input_search"
      },{
        "name":"company_phone",
        "type":"input_search"
      }
    ]
</code>```

I want to make search in DB, in search you can find by any field or by two or more field. Field called the same as property of object. So by ng-keyup I need to send to my function

```<code>search(field, value)
</code>```

two arguments. I want to do something like this

```<code><div ng-repeat="value in param.values">
    <input ng-if="value.type == 'input_search'"
           ng-keyup="search(value.name, this.text)"
           type="text">
</code>```

How can a send to function text of this input without using ng-model? Where this.text is value of input.

答:
I know the question said without using ng-model. But I suspect you may want this because you want to customize when data-binding occurs. If that's the case, you can use ng-model-options with ng-change:

```<code><input type="text" ng-model="yourModel" ng-model-options="{ updateOn: 'keyup' }" ng-change="search()" />
</code>```

ng-change fires when the model has been updated, which is after keyup in this case. So the value of yourModel will be up to date when search() executes.

Body:
I need to make some inputs by ng-repeat, and in my json file I have in object where is a property called name, like this:

"url":"find_company",
    "values":[
      {
        "name":"company name",
        "type":"input_search"
      },{
        "name":"company_phone",
        "type":"input_search"
      }
    ]

I want to make search in DB, in search you can find by any field or by two or more field. Field called the same as property of object. So by ng-keyup I need to send to my function

search(field, value)

two arguments. I want to do something like this

    <input ng-if="value.type == 'input_search'"
           ng-keyup="search(value.name, this.text)"
           type="text">

How can a send to function text of this input without using ng-model? Where this.text is value of input.

Body:
I know the question said without using ng-model. But I suspect you may want this because you want to customize when data-binding occurs. If that's the case, you can use ng-model-options with ng-change:

<input type="text" ng-model="yourModel" ng-model-options="{ updateOn: 'keyup' }" ng-change="search()" />

ng-change fires when the model has been updated, which is after keyup in this case. So the value of yourModel will be up to date when search() executes.


答:
Your problem has nothing to do with lambda, if you used a function you would run into the same problem - map returns an object, which is an
iterable, ie. it can be converted to a list of values, but it is not a list of values. To print such a list, you must explicitly require its creation:

```<code>print(list(map(lambda x: (float(9)/5)*x + 32, Cel)))
</code>```

Title: Why can't we directly print the output of a lambda function/expression directly as a string,list, or tuple?

Body:
I am using Python 3. I am trying to write a lambda function/expression and generate a string type output. I am not sure what I am not understanding in this issue.

Cel = [39.5, 36.5, 37.3, 37.8]
Fer = lambda x: (float(9)/5*x for x in Cel + 32)
print(Fer)

prints:

<function <lambda> at 0x7fafc369eea0>

But, I want the list of values as:

[103.1, 97.70, 99.14, 100.03]

I then tried map with lambda

Fer2 = map(lambda x: (float(9)/5)*x + 32, Cel)
print(Fer2) # prints:
<map object at 0x7fafc36b5b38> # still no success

for x in Fer:
    print(x)  # this doesn't work and gives following error
TypeError: 'function' object is not iterable

for x in Fer2:
    print(x) # but this works and prints
             103.10
             97.7
             99.14
             100.039

Why can't I get print(Fer or Fer2) simply as a a list of values, like:
[103.1, 97.70, 99.14, 100.03]

How do I solve this within lambda, without writing another def function?

Body:
Your problem has nothing to do with lambda, if you used a function you would run into the same problem - map returns an object, which is an
iterable, ie. it can be converted to a list of values, but it is not a list of values. To print such a list, you must explicitly require its creation:

print(list(map(lambda x: (float(9)/5)*x + 32, Cel)))


问:
Spring Data REST - RepositoryEventHandler methods not getting invoked for POST method?
I have the following domain object and DTO defined.

Country.java

```<code>@Data
@Entity
public class Country extends ResourceSupport {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private long countryID;

    @NotBlank(message = "Country name is a required field")
    private String countryName;

    private String countryNationality;
}
</code>```

CountryDTO.java

```<code>@Data

public class CountryDTO {

    private List<Country> countries;
}
</code>```

I have overridden the POST method in the RepositoryRestController for the country class.

```<code>@RepositoryRestController
public class CountryController {

    @Autowired
    private CountryRepository repo;

    @RequestMapping(method = POST, value = "countries")
    public @ResponseBody ResponseEntity<?> createCountry(@RequestBody Resource<CountryDTO> dto,
            Pageable page, PersistentEntityResourceAssembler resourceAssembler) {

        Country savedCountry = repo.save(dto.getContent().getCountries());
        return new ResponseEntity<>(resourceAssembler.toResource(savedCountry), HttpStatus.OK);
    }

}
</code>```

Now I have defined a RepositoryEventHandler to handle validations.

```<code>@Component
@RepositoryEventHandler
public class CountryHandler {

    @HandleBeforeCreate
    public void handleBeforeCreate(Country country) {

        System.out.println("testing");

}
</code>```

But when I send a POST request to the endpoint http://localhost:8080/countries, the eventhandler does not get invoked. Is there anything I am doing wrong?

UPDATE 1:
I am sending the following JSON to the endpoint using Postman.

```<code>"countries":[{
    "countryName":"Australia",
    "countryNationality":"Australian"

}]
</code>```

答:
Define a Bean in AppConfigration as

```<code>@Configuration
@EnableAsync
public class AppConfig {

  @Bean
    CountryHandler countryHandler (){
        return new CountryHandler ();
    }

}
</code>```

It will work then.

Body:
I have the following domain object and DTO defined.

Country.java

@Data
@Entity
public class Country extends ResourceSupport {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private long countryID;

    @NotBlank(message = "Country name is a required field")
    private String countryName;

    private String countryNationality;
}

CountryDTO.java

@Data

public class CountryDTO {

    private List<Country> countries;
}

I have overridden the POST method in the RepositoryRestController for the country class.

@RepositoryRestController
public class CountryController {

    @Autowired
    private CountryRepository repo;

    @RequestMapping(method = POST, value = "countries")
    public @ResponseBody ResponseEntity<?> createCountry(@RequestBody Resource<CountryDTO> dto,
            Pageable page, PersistentEntityResourceAssembler resourceAssembler) {

        Country savedCountry = repo.save(dto.getContent().getCountries());
        return new ResponseEntity<>(resourceAssembler.toResource(savedCountry), HttpStatus.OK);
    }

}

Now I have defined a RepositoryEventHandler to handle validations.

@Component
@RepositoryEventHandler
public class CountryHandler {

    @HandleBeforeCreate
    public void handleBeforeCreate(Country country) {

        System.out.println("testing");

}

But when I send a POST request to the endpoint http://localhost:8080/countries, the eventhandler does not get invoked. Is there anything I am doing wrong?

UPDATE 1:
I am sending the following JSON to the endpoint using Postman.

"countries":[{
    "countryName":"Australia",
    "countryNationality":"Australian"

}]

Body:
Define a Bean in AppConfigration as

@Configuration
@EnableAsync
public class AppConfig {

  @Bean
    CountryHandler countryHandler (){
        return new CountryHandler ();
    }

}

It will work then.


问:
Floating Action Button Unwanted Behavior with Recycle view android
The behavior of FAB is unexpected. The images are in the link below

Can not find any help.. It does work sometime and sometime does not.
Not being able to find actual problem
even tried to add dynamically  like

```<code>CoordinatorLayout.LayoutParams params = (CoordinatorLayout.LayoutParams) btnSubmitConfirm.getLayoutParams();
   params.setAnchorId(R.id.listWorkData);
params.anchorGravity = Gravity.BOTTOM | GravityCompat.END | Gravity.RIGHT;
btnSubmitConfirm.setLayoutParams(params);
</code>```

but dosen't work at allHere's the xml codeneed a solution guys

```<code><?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="@+id/parentView"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:animateLayoutChanges="true"
android:background="@color/background"
android:clickable="true">

<android.support.v7.widget.RecyclerView
    android:id="@+id/listWorkData"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:padding="@dimen/ten" />

<android.support.design.widget.FloatingActionButton
    android:id="@+id/btnConfirmSubmitReport"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentBottom="true"
    android:layout_alignParentEnd="true"
    android:layout_alignParentRight="true"
    android:layout_margin="@dimen/thirty"
    android:src="@drawable/ic_tick"
    android:tint="@android:color/white"
    app:layout_anchor="@id/listWorkData"
    app:layout_anchorGravity="bottom|right|end" />
</code>```

[OK Condition Image][1]
[Not OK Condition Image][2]  [1]: https://i.stack.imgur.com/7D0XD.png  [2]: https://i.stack.imgur.com/ds2Gi.png

答:
Remove this,

```<code>app:layout_anchor="@id/listWorkData"
app:layout_anchorGravity="bottom|right|end"
</code>```

And check.

Body:
The behavior of FAB is unexpected. The images are in the link below

Can not find any help.. It does work sometime and sometime does not.
Not being able to find actual problem
even tried to add dynamically  like

CoordinatorLayout.LayoutParams params = (CoordinatorLayout.LayoutParams) btnSubmitConfirm.getLayoutParams();
   params.setAnchorId(R.id.listWorkData);
params.anchorGravity = Gravity.BOTTOM | GravityCompat.END | Gravity.RIGHT;
btnSubmitConfirm.setLayoutParams(params);

but dosen't work at allHere's the xml codeneed a solution guys

<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="@+id/parentView"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:animateLayoutChanges="true"
android:background="@color/background"
android:clickable="true">

<android.support.v7.widget.RecyclerView
    android:id="@+id/listWorkData"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:padding="@dimen/ten" />

<android.support.design.widget.FloatingActionButton
    android:id="@+id/btnConfirmSubmitReport"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentBottom="true"
    android:layout_alignParentEnd="true"
    android:layout_alignParentRight="true"
    android:layout_margin="@dimen/thirty"
    android:src="@drawable/ic_tick"
    android:tint="@android:color/white"
    app:layout_anchor="@id/listWorkData"
    app:layout_anchorGravity="bottom|right|end" />

[OK Condition Image][1]
[Not OK Condition Image][2]  [1]: https://i.stack.imgur.com/7D0XD.png  [2]: https://i.stack.imgur.com/ds2Gi.png

Body:
Remove this,

app:layout_anchor="@id/listWorkData"
app:layout_anchorGravity="bottom|right|end"

And check.


问:
GDB Cannot insert breakpoint, Cannot access memory at address XXX?
I wrote a really simple program:

```<code>ebrahim@ebrahim:~/test$ cat main.c
int main() {
    int i = 0;
    return i;
}
</code>```

And the I compiled it with -s for stripped mode:

ebrahim@ebrahim:~/test$ gcc -s main.c -o f3
ebrahim@ebrahim:~/test$ file f3
f3: ELF 64-bit LSB shared object, x86-64, version 1 (SYSV), dynamically linked, interpreter /lib64/ld-linux-x86-64.so.2, for GNU/Linux 2.6.32, BuildID[sha1]=4dc6b893fbae8b418ca41ddeef948df1fcb26d3d, stripped
```

<p>Now, I'm trying to find out the main function start address using GDB:</p>

<pre class="lang-none prettyprint-override"><code>ebrahim@ebrahim:~/test$ gdb -nh f3
GNU gdb (Ubuntu 7.11.90.20161005-0ubuntu2) 7.11.90.20161005-git
Copyright (C) 2016 Free Software Foundation, Inc.
License GPLv3+: GNU GPL version 3 or later <http://gnu.org/licenses/gpl.html>
This is free software: you are free to change and redistribute it.
There is NO WARRANTY, to the extent permitted by law.  Type "show copying"
and "show warranty" for details.
This GDB was configured as "x86_64-linux-gnu".
Type "show configuration" for configuration details.
For bug reporting instructions, please see:
<http://www.gnu.org/software/gdb/bugs/>.
Find the GDB manual and other documentation resources online at:
<http://www.gnu.org/software/gdb/documentation/>.
For help, type "help".
Type "apropos word" to search for commands related to "word"...
Reading symbols from f3...(no debugging symbols found)...done.
</code>```

As there is no Symbol info inside the file, I need to put a break at the file entry point and the disassemble it and find the start address of main function. So I used info file command to find the file entry point address:

(gdb) info file
Symbols from "/home/ebrahim/test/f3".
Local exec file:
    `/home/ebrahim/test/f3', file type elf64-x86-64.
    Entry point: 0x530     <<<<=============
    0x0000000000000238 - 0x0000000000000254 is .interp
    0x0000000000000254 - 0x0000000000000274 is .note.ABI-tag
    0x0000000000000274 - 0x0000000000000298 is .note.gnu.build-id
    0x0000000000000298 - 0x00000000000002b4 is .gnu.hash
    0x00000000000002b8 - 0x0000000000000360 is .dynsym
    0x0000000000000360 - 0x00000000000003f1 is .dynstr
    0x00000000000003f2 - 0x0000000000000400 is .gnu.version
    0x0000000000000400 - 0x0000000000000420 is .gnu.version_r
    0x0000000000000420 - 0x00000000000004f8 is .rela.dyn
    0x00000000000004f8 - 0x000000000000050f is .init
    0x0000000000000510 - 0x0000000000000520 is .plt
    0x0000000000000520 - 0x0000000000000528 is .plt.got
    0x0000000000000530 - 0x00000000000006e2 is .text
    0x00000000000006e4 - 0x00000000000006ed is .fini
    0x00000000000006f0 - 0x00000000000006f4 is .rodata
    0x00000000000006f4 - 0x0000000000000728 is .eh_frame_hdr
    0x0000000000000728 - 0x000000000000081c is .eh_frame
    0x0000000000200de0 - 0x0000000000200de8 is .init_array
    0x0000000000200de8 - 0x0000000000200df0 is .fini_array
    0x0000000000200df0 - 0x0000000000200df8 is .jcr
    0x0000000000200df8 - 0x0000000000200fb8 is .dynamic
    0x0000000000200fb8 - 0x0000000000201000 is .got
    0x0000000000201000 - 0x0000000000201010 is .data
    0x0000000000201010 - 0x0000000000201018 is .bss
```

<p>As we expected the entry point is the start of <code>.text</code> section. So I put a breakpoint on this address:</p>

<pre class="lang-none prettyprint-override"><code>(gdb) b *0x0000000000000530
Breakpoint 1 at 0x530
(gdb) r
Starting program: /home/ebrahim/test/f3
Warning:
Cannot insert breakpoint 1.
Cannot access memory at address 0x530

(gdb)
</code>```

The question is why GDB cannot insert this breakpoint?

答:
Debugging stripped code is probably very much useless (except for reverse engineering), but you can cause gdb to stop at the very first instruction, and you are already doing this accidentally. If the address of a breakpoint cannot be mapped, gdb stops and tells you the error. As a side effect, your program is stopped at its first instruction. An address that's guaranteed to be unmappable is 0, so just do the following:

(gdb) b *0
Breakpoint 1 at 0x0
(gdb) r
Starting program: [...]
Warning:
Cannot insert breakpoint 1.
Cannot access memory at address 0x0

(gdb) disas
Dump of assembler code for function _start:
=> 0x00007ffff7ddd190 <+0>: mov    %rsp,%rdi
   0x00007ffff7ddd193 <+3>: callq  0x7ffff7de0750 <_dl_start>
```

<p>Here you see the <code>PC</code> sits at <code>0x00007ffff7ddd190</code>. So this is your entry point at runtime.</p>

<p>In order to be able to continue  (or: single-step for example), you have to delete the offending breakpoint:</p>

<pre class="lang-none prettyprint-override"><code>(gdb) delete
Delete all breakpoints? (y or n) y
(gdb) c
Continuing.
</code>```

Credits for this answer go to this answer on reverse engineering

Body:
I wrote a really simple program:

ebrahim@ebrahim:~/test$ cat main.c
int main() {
    int i = 0;
    return i;
}

And the I compiled it with -s for stripped mode:

ebrahim@ebrahim:~/test$ gcc -s main.c -o f3
ebrahim@ebrahim:~/test$ file f3
f3: ELF 64-bit LSB shared object, x86-64, version 1 (SYSV), dynamically linked, interpreter /lib64/ld-linux-x86-64.so.2, for GNU/Linux 2.6.32, BuildID[sha1]=4dc6b893fbae8b418ca41ddeef948df1fcb26d3d, stripped

Now, I'm trying to find out the main function start address using GDB:

ebrahim@ebrahim:~/test$ gdb -nh f3
GNU gdb (Ubuntu 7.11.90.20161005-0ubuntu2) 7.11.90.20161005-git
Copyright (C) 2016 Free Software Foundation, Inc.
License GPLv3+: GNU GPL version 3 or later <http://gnu.org/licenses/gpl.html>
This is free software: you are free to change and redistribute it.
There is NO WARRANTY, to the extent permitted by law.  Type "show copying"
and "show warranty" for details.
This GDB was configured as "x86_64-linux-gnu".
Type "show configuration" for configuration details.
For bug reporting instructions, please see:
<http://www.gnu.org/software/gdb/bugs/>.
Find the GDB manual and other documentation resources online at:
<http://www.gnu.org/software/gdb/documentation/>.
For help, type "help".
Type "apropos word" to search for commands related to "word"...
Reading symbols from f3...(no debugging symbols found)...done.

As there is no Symbol info inside the file, I need to put a break at the file entry point and the disassemble it and find the start address of main function. So I used info file command to find the file entry point address:

(gdb) info file
Symbols from "/home/ebrahim/test/f3".
Local exec file:
    `/home/ebrahim/test/f3', file type elf64-x86-64.
    Entry point: 0x530     <<<<=============
    0x0000000000000238 - 0x0000000000000254 is .interp
    0x0000000000000254 - 0x0000000000000274 is .note.ABI-tag
    0x0000000000000274 - 0x0000000000000298 is .note.gnu.build-id
    0x0000000000000298 - 0x00000000000002b4 is .gnu.hash
    0x00000000000002b8 - 0x0000000000000360 is .dynsym
    0x0000000000000360 - 0x00000000000003f1 is .dynstr
    0x00000000000003f2 - 0x0000000000000400 is .gnu.version
    0x0000000000000400 - 0x0000000000000420 is .gnu.version_r
    0x0000000000000420 - 0x00000000000004f8 is .rela.dyn
    0x00000000000004f8 - 0x000000000000050f is .init
    0x0000000000000510 - 0x0000000000000520 is .plt
    0x0000000000000520 - 0x0000000000000528 is .plt.got
    0x0000000000000530 - 0x00000000000006e2 is .text
    0x00000000000006e4 - 0x00000000000006ed is .fini
    0x00000000000006f0 - 0x00000000000006f4 is .rodata
    0x00000000000006f4 - 0x0000000000000728 is .eh_frame_hdr
    0x0000000000000728 - 0x000000000000081c is .eh_frame
    0x0000000000200de0 - 0x0000000000200de8 is .init_array
    0x0000000000200de8 - 0x0000000000200df0 is .fini_array
    0x0000000000200df0 - 0x0000000000200df8 is .jcr
    0x0000000000200df8 - 0x0000000000200fb8 is .dynamic
    0x0000000000200fb8 - 0x0000000000201000 is .got
    0x0000000000201000 - 0x0000000000201010 is .data
    0x0000000000201010 - 0x0000000000201018 is .bss

As we expected the entry point is the start of .text section. So I put a breakpoint on this address:

(gdb) b *0x0000000000000530
Breakpoint 1 at 0x530
(gdb) r
Starting program: /home/ebrahim/test/f3
Warning:
Cannot insert breakpoint 1.
Cannot access memory at address 0x530

(gdb)

The question is why GDB cannot insert this breakpoint?

Body:
Debugging stripped code is probably very much useless (except for reverse engineering), but you can cause gdb to stop at the very first instruction, and you are already doing this accidentally. If the address of a breakpoint cannot be mapped, gdb stops and tells you the error. As a side effect, your program is stopped at its first instruction. An address that's guaranteed to be unmappable is 0, so just do the following:

(gdb) b *0
Breakpoint 1 at 0x0
(gdb) r
Starting program: [...]
Warning:
Cannot insert breakpoint 1.
Cannot access memory at address 0x0

(gdb) disas
Dump of assembler code for function _start:
=> 0x00007ffff7ddd190 <+0>: mov    %rsp,%rdi
   0x00007ffff7ddd193 <+3>: callq  0x7ffff7de0750 <_dl_start>

Here you see the PC sits at 0x00007ffff7ddd190. So this is your entry point at runtime.

In order to be able to continue  (or: single-step for example), you have to delete the offending breakpoint:

(gdb) delete
Delete all breakpoints? (y or n) y
(gdb) c
Continuing.

Credits for this answer go to this answer on reverse engineering