问:
Use RegExp in Awk
I have CSV file:

```<code><iframe src="https://localhost/get/44bc40f3bc04f65b7a35"></iframe>|name_1
<iframe src="https://localhost/get/5db0d477d707121934ff"></iframe>|name_2
<iframe src="https://localhost/get/6c95bd2b32ed45989c61"></iframe>|name_3
<iframe src="https://localhost/get/0a9c4655800e8a7b9ea2"></iframe>|name_4
<iframe src="https://localhost/get/754953b57a32e2841bda"></iframe>|name_5
</code>```

and want use RegExp and Awk (or Gawk) to make this CSV file like this:

```<code>44bc40f3bc04f65b7a35|name_1
5db0d477d707121934ff|name_2
6c95bd2b32ed45989c61|name_3
0a9c4655800e8a7b9ea2|name_4
754953b57a32e2841bda|name_5
</code>```

I have worked RegExp in Grep

```<code>$ grep -Po "[A-Za-z]*+\d++\w++" example.txt
44bc40f3bc04f65b7a35
5db0d477d707121934ff
6c95bd2b32ed45989c61
0a9c4655800e8a7b9ea2
754953b57a32e2841bda
</code>```

but this RegExp not work in Awk. I think i'm not correct use regexp in Awk or this type of RegExp not worked in Awk.

```<code>$ awk -F "|" 'match($1, /[A-Za-z]*+\d++\w++/, a) {print a[0]"|"$2}' example.txt
db0d477d707121934ff|name_2
bd2b32ed45989c61|name_3
bda|name_5
</code>```

Just Awk work fine:

```<code>$ awk -F "|" '{print $1"|"$2}' example.txt
<iframe src="https://localhost/get/44bc40f3bc04f65b7a35"></iframe>|name_1
<iframe src="https://localhost/get/5db0d477d707121934ff"></iframe>|name_2
<iframe src="https://localhost/get/6c95bd2b32ed45989c61"></iframe>|name_3
<iframe src="https://localhost/get/0a9c4655800e8a7b9ea2"></iframe>|name_4
<iframe src="https://localhost/get/754953b57a32e2841bda"></iframe>|name_5
</code>```

答:
The difference between awk and grep invocations in your example is -P option in grep, which stands for "Use Perl regexp". If you replace it with -E, it will work just like your awk run. Awk does not support Perl extension.

Your regexp is better be fixed, I don't think you need these extra + signs, to begin with. If I can assume that you need all letters or digits after get/ then I'd rather write:

awk -F "|" 'match($1, /get/([A-Za-z0-9]+)/, a) {print a[1]"|"$2}' example.txt

Here we use [A-Za-z0-9]+ match any number of small or upper letters or digits that come after /get, use a[1] to print a matched group inside the parentheses instead of the whole matching pattern a[0] which includes get/

Title: Use RegExp in Awk

Body:
I have CSV file:

|name_1
|name_2
|name_3
|name_4
|name_5

and want use RegExp and Awk (or Gawk) to make this CSV file like this:

44bc40f3bc04f65b7a35|name_1
5db0d477d707121934ff|name_2
6c95bd2b32ed45989c61|name_3
0a9c4655800e8a7b9ea2|name_4
754953b57a32e2841bda|name_5

I have worked RegExp in Grep

$ grep -Po "[A-Za-z]*+\d++\w++" example.txt
44bc40f3bc04f65b7a35
5db0d477d707121934ff
6c95bd2b32ed45989c61
0a9c4655800e8a7b9ea2
754953b57a32e2841bda

but this RegExp not work in Awk. I think i'm not correct use regexp in Awk or this type of RegExp not worked in Awk.

$ awk -F "|" 'match($1, /[A-Za-z]*+\d++\w++/, a) {print a[0]"|"$2}' example.txt
db0d477d707121934ff|name_2
bd2b32ed45989c61|name_3
bda|name_5

Just Awk work fine:

$ awk -F "|" '{print $1"|"$2}' example.txt
|name_1
|name_2
|name_3
|name_4
|name_5


来源: stackexchange

问:
Laravel : Dependency injection vs Facades?
What, I had been doing previously was to inject only MY MODELS using the constructor and use Facades for the Laravel's provided classes i.e. Session, Auth, Validator etc, for example. Will it be a good idea if I inject each and every class (either mine or Laravel's) through construct and use it by $this->.. syntax or should I inject my own classes using constructor and use Facades for anything provided by Laravel?

To be more specific, here is what my controllers normally look like:

```<code>class MyController extends BaseController
{
    public function __construct( User $user, Bookmark $bookmark ) {
        $this->user = $user;
        $this->bookmark = $bookmark
    }

    public function foobar ( ) {
        $user_id = Input::get('bar');
        ...
        Session::get('someInfo');
        ...
        return Redirect::to('/');
    }
    ...
}
</code>```

Should I structure my methods like controller like following, instead?

```<code>class MyController extends BaseController
{
    public function __construct( User $user, Bookmark $bookmark, Input $input, Session $session, Redirect $redirect ) {
        $this->user = $user;
        $this->bookmark = $bookmark
        $this->input = $input;
        $this->session = $session;
        $this->redirect = $redirect;
    }

    public function foobar ( ) {
        $user_id = $this->input->get('bar');
        ...
        $this->session->get('someInfo');
        ...
        return $this->redirect->to('/');
    }
    ...
}
</code>```

答:
Laravel has replaced many of it's facade with helpers for example

```<code>use Auth;
</code>```

and

```<code>Auth::user()
</code>```

is now just

```<code>auth()->user()
</code>```

this makes thing simpler and neater (also prevents mistakes)

I would suggest using the helpers where possible and if no helper exists, use the facade because it is easier to mock than an injected instance.

ContentLicense: CC BY-SA 3.0

Body:
What, I had been doing previously was to inject only MY MODELS using the constructor and use Facades for the Laravel's provided classes i.e. Session, Auth, Validator etc, for example. Will it be a good idea if I inject each and every class (either mine or Laravel's) through construct and use it by $this->.. syntax or should I inject my own classes using constructor and use Facades for anything provided by Laravel?

To be more specific, here is what my controllers normally look like:

class MyController extends BaseController
{
    public function __construct( User $user, Bookmark $bookmark ) {
        $this->user = $user;
        $this->bookmark = $bookmark
    }

    public function foobar ( ) {
        $user_id = Input::get('bar');
        ...
        Session::get('someInfo');
        ...
        return Redirect::to('/');
    }
    ...
}

Should I structure my methods like controller like following, instead?

class MyController extends BaseController
{
    public function __construct( User $user, Bookmark $bookmark, Input $input, Session $session, Redirect $redirect ) {
        $this->user = $user;
        $this->bookmark = $bookmark
        $this->input = $input;
        $this->session = $session;
        $this->redirect = $redirect;
    }

    public function foobar ( ) {
        $user_id = $this->input->get('bar');
        ...
        $this->session->get('someInfo');
        ...
        return $this->redirect->to('/');
    }
    ...
}

Body:
Laravel has replaced many of it's facade with helpers for example

use Auth;

and

Auth::user()

is now just

auth()->user()

this makes thing simpler and neater (also prevents mistakes)

I would suggest using the helpers where possible and if no helper exists, use the facade because it is easier to mock than an injected instance.


问:
Access variable in Ember controller
how can I access a variable in Ember controller?
I've tried those methods, but it doesn't work:</p>

```<code>import ObjectController from '@ember/controller';
export default ObjectController.extend({

  currentPhase: 1,

  init: function () {
      var selfReference = this;
      this.set("currentPhase",1);
  },

  strings: {
      title: "Title",
      phase1: "Fase " + selfReference.get("currentPhase"),
      phase2: "Fase " + currentPhase
  }
});
</code>```

答: In your case, you have defined selfReference in your init function, but you tried to reach it from outside of the function which is forbidden. In order to reach it from outside the function, you need to set it to a variable by using set function. You can consider defining strings as computed property as well. Take a look at this twiddle.

Title: Access variable in Ember controller

Body:
how can I access a variable in Ember controller?
I've tried those methods, but it doesn't work:

import ObjectController from '@ember/controller';
export default ObjectController.extend({

  currentPhase: 1,

  init: function () {
      var selfReference = this;
      this.set("currentPhase",1);
  },

  strings: {
      title: "Title",
      phase1: "Fase " + selfReference.get("currentPhase"),
      phase2: "Fase " + currentPhase
  }
});


问:
Retain only two-dimensional components in sf data.frame
I have a similar setup as in this question. In my case, however, I've got an sf data.frame that contains a mix of different geometry types, some POLYGONs, some GEOMETRYCOLLECTIONs like so:

```<code>a <- st_polygon(list(cbind(c(0,0,7.5,7.5,0),c(0,-1,-1,0,0))))
b <- st_polygon(list(cbind(c(0,1,2,3,4,5,6,7,7,0),c(1,0,.5,0,0,0.5,-0.5,-0.5,1,1))))
i <- st_intersection(a,b)

a1 <- st_sf(a=1, geom = st_sfc(i))
a2 <- st_sf(a=2, geom = st_sfc(a))

ii <- rbind(a1, a2)
</code>```

As in the question referenced above, what I would like is to retain only those parts of the GEOMETRYCOLLECTION that are two-dimensional as ultimately I'm interested in the areas of these geometries and st_area() won't work on GEOMETRYCOLLECTIONs.

In the case of mixed geometries, however, the answer given

```<code>st_cast(ii)[which(st_is(st_cast(ii), c("POLYGON", "MULTIPOLYGON"))),]
</code>```

doesn't work as the st_cast() leaves the GEOMETRYCOLLECTION untouched.

答:
Did you try

```<code>st_collection_extract(ii)
</code>```

? And what did you mean by st_area not working on collections? I see

```<code> > st_area(ii)
[1] 0.625 7.500
</code>```

Body:
I have a similar setup as in this question. In my case, however, I've got an sf data.frame that contains a mix of different geometry types, some POLYGONs, some GEOMETRYCOLLECTIONs like so:

a <- st_polygon(list(cbind(c(0,0,7.5,7.5,0),c(0,-1,-1,0,0))))
b <- st_polygon(list(cbind(c(0,1,2,3,4,5,6,7,7,0),c(1,0,.5,0,0,0.5,-0.5,-0.5,1,1))))
i <- st_intersection(a,b)

a1 <- st_sf(a=1, geom = st_sfc(i))
a2 <- st_sf(a=2, geom = st_sfc(a))

ii <- rbind(a1, a2)

As in the question referenced above, what I would like is to retain only those parts of the GEOMETRYCOLLECTION that are two-dimensional as ultimately I'm interested in the areas of these geometries and st_area() won't work on GEOMETRYCOLLECTIONs.

In the case of mixed geometries, however, the answer given

st_cast(ii)[which(st_is(st_cast(ii), c("POLYGON", "MULTIPOLYGON"))),]

doesn't work as the st_cast() leaves the GEOMETRYCOLLECTION untouched.

Body:
Did you try

st_collection_extract(ii)

? And what did you mean by st_area not working on collections? I see

 > st_area(ii)
[1] 0.625 7.500


问:
Can not find docker container
I have asp core api project and i am using visual studio 2017 to run my project.
After i renamed the docker container that was previously created using visual studio using this command on command line,

```<code>docker rename CONTAINER NEW_NAME
</code>```

I receive the following message when i try to run the project again in visual studio.

Thanks for the help

```<code>Can not find docker container with the name starting with 'previous_container_name'.
</code>```

答: Delete the .vs folder in your solution directory (close the solution first), the Docker image name seems to be cached somewhere in there.

Title: Can not find docker container

Body:
I have asp core api project and i am using visual studio 2017 to run my project.
After i renamed the docker container that was previously created using visual studio using this command on command line,

docker rename CONTAINER NEW_NAME

I receive the following message when i try to run the project again in visual studio.

Thanks for the help

Can not find docker container with the name starting with 'previous_container_name'.


问:
IIS Express with VS2010 SP 1 beta problem
I have installed VS2010 SP1 and IIS Express Beta. Both are installed correctly, but I can't use them because the option does not appear in the context menu as Scott Guthrie describes on his blog here:
http://weblogs.asp.net/scottgu/archive/2011/01/03/vs-2010-sp1-beta-and-iis-developer-express.aspx

What am I doing wrong? What should I do to activate IIS Express?

答:
Final version of IIS Express has been released last week. You didn't mention which Beta are you using, but you would be better off with the final version.

Your Visual Studio 2010 SP1 version (as shown in the Help/About) should be 10.0.31118.1 SP1Rel.

You could check if IIS Express works on it's own by going to it's installation directory (in Program Files and trying to run iisexpress.exe (should start a sample site WebSite1 on port 8080).

ContentLicense: CC BY-SA 2.5


问:
How to convert a list of characters to ASCII in python?
Hi i’m sort of new to Python and i’m trying to convert a string of characters to ASCII in Python but I don’t know how to do that

So the relevant parts of my code are probably this

```<code>string = input(“Enter a line of text: “)
l = list(string)
return(l)
</code>```

So it puts the input in a list because then it’s separate characters instead of a whole string of them but then I don’t know how to convert it to ASCII. I know I have to use ord() but I don’t understand how to do that when it’s more than one character because I don’t know what the input will be so I can’t just do like ord(A).

How can I do it?

答:
Here's a time complexity efficient way of doing it. Assuming your list is of single characters as such:

l = ['a', 'b', 'c']
ascii_values = map(ord, l)

This will map each character to its specified ascii value.

Body:
Hi i’m sort of new to Python and i’m trying to convert a string of characters to ASCII in Python but I don’t know how to do that

So the relevant parts of my code are probably this

string = input(“Enter a line of text: “)
l = list(string)
return(l)

So it puts the input in a list because then it’s separate characters instead of a whole string of them but then I don’t know how to convert it to ASCII. I know I have to use ord() but I don’t understand how to do that when it’s more than one character because I don’t know what the input will be so I can’t just do like ord(A).

How can I do it?


问:
Upgrading to Swfit 3: cannot override 'init' which has been marked unavailable
I just inherited an iOS project which incorporates Apple's ResearchKit (RK).

I have upgraded to the most recent version of RK and also to Swift 3.  While I have worked in iOS and RK, I am still not very confident.  Anyways, There is a class called SurveyTask which implements an ORKOrderedTask from RK.

cannot override 'init' which has been marked unavailable

at the end this function, stepz already defined, we have:

```<code>super.init(identifier: "survey", steps: stepz)
</code>```

I checked the ORKOrderedTask class definition, which has an init function.

I have been reading about initializers but haven't found anything.  Using override or convenience before the init in SurveyTask doesn't change anything.  Same error.  Any help would be greatly appreciated.

XCode version 8.1.

答:
Here's how you can mimic a parameterless initializer and avoid the unavailable error:

class MyClass: ParentWithUnavailableInitializer {
    init(workaround _: Void = ()) {
        // Call a designated initializer
        super.init(param: "a very sensible value")
    }
}

// At a call site
let obj = MyClass()
```

Works in Swift 3.2 and Swift 4.

Body:
I just inherited an iOS project which incorporates Apple's ResearchKit (RK).

I have upgraded to the most recent version of RK and also to Swift 3.  While I have worked in iOS and RK, I am still not very confident.  Anyways, There is a class called SurveyTask which implements an ORKOrderedTask from RK.

cannot override 'init' which has been marked unavailable

at the end this function, stepz already defined, we have:

super.init(identifier: "survey", steps: stepz)

I checked the ORKOrderedTask class definition, which has an init function.

I have been reading about initializers but haven't found anything.  Using override or convenience before the init in SurveyTask doesn't change anything.  Same error.  Any help would be greatly appreciated.

XCode version 8.1.

Body:
Here's how you can mimic a parameterless initializer and avoid the unavailable error:

class MyClass: ParentWithUnavailableInitializer {
    init(workaround _: Void = ()) {
        // Call a designated initializer
        super.init(param: "a very sensible value")
    }
}

// At a call site
let obj = MyClass()

Works in Swift 3.2 and Swift 4.


问:
How to convert maximo SQL for Crystal Reporting
How do I change this to work in crystal?   </p>

```<code>SELECT jpnum in (select jpnum from jobplan minus select jpnum from jobtask where jptask = '1')
</code>```

答:
There are a few ways to structure this query and I'm not completely sure of the structure of your tables, but this query should get you on the way to a command.</p>

```<code>SELECT
    JOBPLAN.JPNUM,
    MIN(ISNULL(JOBTASK.JPTASK,0))
FROM
    JOBPLAN
LEFT OUTER JOIN
    JOBTASK
    ON JOBPLAN.JPNUM = JOBTASK.JPNUM
GROUP BY
    JOBPLAN.JPNUM
HAVING
    MIN(ISNULL(JOBTASK.JPTASK,0)) <> 1
</code>```

Body:
How do I change this to work in crystal?

SELECT jpnum in (select jpnum from jobplan minus select jpnum from jobtask where jptask = '1')

Body:
There are a few ways to structure this query and I'm not completely sure of the structure of your tables, but this query should get you on the way to a command.

SELECT
    JOBPLAN.JPNUM,
    MIN(ISNULL(JOBTASK.JPTASK,0))
FROM
    JOBPLAN
LEFT OUTER JOIN
    JOBTASK
    ON JOBPLAN.JPNUM = JOBTASK.JPNUM
GROUP BY
    JOBPLAN.JPNUM
HAVING
    MIN(ISNULL(JOBTASK.JPTASK,0)) <> 1


问:
Android - How to properly get a variable from a parent activity from a fragment
I read the official Android documentation on creating an interface to be able to communicate between a parent activity and a fragment. So I did but my app crashes when I call one of the methods to get a value from the parent activity.

if have an interface like this in my fragment

public interface InteractWithFragmentA {
    String getStringText();
}

In my calling activity I tested it out with a dummy text

```<code>@Override
public String getStringText(){ return "Some dummy text";}
</code>```

I have a variable in FragmentA.java that's a reference to the host activity and casted to InteractWithFragmentA, but when I call the method using

_hostActivity.getStringText()

the app crashes. Is there something that I'm missing? I've seen some suggested methods for getting the host activity's variables by making them public and static or some other method but I'm trying not to couple the fragment to that activity. Thanks in advance.

答:
Yo should do this:

Activity

```<code> public class YourActivity implements YourActivityInterface{
     @Override   public String getStringText(){ return "Some dummy text";}
 }
</code>```

Interface

```<code>    public interface YourActivityInterface {
    String getStringText();
}
</code>```

Fragment

```<code>  public class YourFragment extends Fragment {

    YourActivityInterface mListener;

     //your method...
     mListener.getStringText()

@Override
    public void onAttach(Context context) {
        super.onAttach(context);
        if (context instanceof YourActivityInterface) {
            mListener = (YourActivityInterface) context;
        } else {
            throw new RuntimeException(context.toString()
                    + " must implement YourActivityInterface");
        }
    }

    @Override
    public void onDetach() {
        super.onDetach();
        mListener = null;
    }
    }
</code>```

Body:
I read the official Android documentation on creating an interface to be able to communicate between a parent activity and a fragment. So I did but my app crashes when I call one of the methods to get a value from the parent activity.

if have an interface like this in my fragment

public interface InteractWithFragmentA {
    String getStringText();
}

In my calling activity I tested it out with a dummy text

@Override
public String getStringText(){ return "Some dummy text";}

I have a variable in FragmentA.java that's a reference to the host activity and casted to InteractWithFragmentA, but when I call the method using

_hostActivity.getStringText()

the app crashes. Is there something that I'm missing? I've seen some suggested methods for getting the host activity's variables by making them public and static or some other method but I'm trying not to couple the fragment to that activity. Thanks in advance.

Body:
Yo should do this:

Activity

 public class YourActivity implements YourActivityInterface{
     @Override   public String getStringText(){ return "Some dummy text";}
 }

Interface

    public interface YourActivityInterface {
    String getStringText();
}

Fragment

  public class YourFragment extends Fragment {

    YourActivityInterface mListener;

     //your method...
     mListener.getStringText()

@Override
    public void onAttach(Context context) {
        super.onAttach(context);
        if (context instanceof YourActivityInterface) {
            mListener = (YourActivityInterface) context;
        } else {
            throw new RuntimeException(context.toString()
                    + " must implement YourActivityInterface");
        }
    }

    @Override
    public void onDetach() {
        super.onDetach();
        mListener = null;
    }
    }


问:
How can I return the content of a variable by using match and regex?
I want to be able to return the content of these variables by using regular expressions.

```<code>'use strict'

const Telegraf = require('telegraf')
const fs = require('fs')

var ar1 = fs.readFileSync('folder/ar1.txt').toString()
var ar2 = fs.readFileSync('folder/ar2.txt').toString()
var ar3 = fs.readFileSync('folder/ar3.txt').toString()
</code>```

I tried using:

```<code>app.hears(/\bar\d/i, (ctx) => {
    ctx.reply(ctx.match[0])
    //Returns: "ar1"
})
</code>```

But this only returns the string, not the content of the variable.

答:
You could use eval here, but I don't suggest it. Instead, I suggest you map your variables.

```<code>const files = {
    "ar1" : fs.readFileSync('folder/ar1.txt').toString(),
    "ar2" : fs.readFileSync('folder/ar2.txt').toString(),
    "ar3" : fs.readFileSync('folder/ar3.txt').toString()
};
</code>```

Then, you can use your found string to reply with your object key (a Map can also be used here)

```<code>app.hears(/\b(a+)r\d/i, (ctx) => {
    ctx.reply(files[ctx.match[0]]);
    //now returns the file
});
</code>```

Body:
I want to be able to return the content of these variables by using regular expressions.

'use strict'

const Telegraf = require('telegraf')
const fs = require('fs')

var ar1 = fs.readFileSync('folder/ar1.txt').toString()
var ar2 = fs.readFileSync('folder/ar2.txt').toString()
var ar3 = fs.readFileSync('folder/ar3.txt').toString()

I tried using:

app.hears(/\bar\d/i, (ctx) => {
    ctx.reply(ctx.match[0])
    //Returns: "ar1"
})

But this only returns the string, not the content of the variable.

Body:
You could use eval here, but I don't suggest it. Instead, I suggest you map your variables.

const files = {
    "ar1" : fs.readFileSync('folder/ar1.txt').toString(),
    "ar2" : fs.readFileSync('folder/ar2.txt').toString(),
    "ar3" : fs.readFileSync('folder/ar3.txt').toString()
};

Then, you can use your found string to reply with your object key (a Map can also be used here)

app.hears(/\b(a+)r\d/i, (ctx) => {
    ctx.reply(files[ctx.match[0]]);
    //now returns the file
});


问:
ASP.NET Core C# Web API POST/PUT relational data
I'm building a simple app for entertainment with ASP.NET Core where I currently just have a Post model and a User model.

Post.cs:

```<code>using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Threading.Tasks;

namespace WebApplication1.Models
{
    public class Post
    {
        [Required]
        public int Id { get; set; }

        [Required]
        [MaxLength(16)]
        public string Title { get; set; }

        public string Body { get; set; }

        [Required]
        public Person Author { get; set; }
    }
}
</code>```

Person.cs:

```<code>using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Threading.Tasks;

namespace WebApplication1.Models
{
    public class Person
    {
        public int Id { get; set; }

        [Required]
        public string FirstName { get; set; }

        [Required]
        public string LastName { get; set; }

        [Required]
        public string Email { get; set; }

        [Required]
        public string Password { get; set; }

        public ICollection<Post> Posts = new List<Post>();
    }
}
</code>```

I used Visual Studio's scaffolding to generate controllers for those models.
When I'm trying to POST /api/posts in order to create a new post, I want also to specify the Author ID for that post.

I tried adding the attribute authorId, I tried "authorId": 1 and also "author": { "id": 1 }, but because the Author is required, I always get back either Author is missing or Email in author is missing etc.

How can I include the authorId for in the post body in order I would be able to successfully create a new post?

答:
Your controller will be expecting a valid whole Person class for the Author property (which means you would have to provide all the properties that are required for a Person) - try changing your Post class to include just the AuthorId as a required field. You can still include Author as a property, just dont make it required.

```<code>public class Post
{
    [Required]
    public int Id { get; set; }

    [Required]
    [MaxLength(16)]
    public string Title { get; set; }

    public string Body { get; set; }

    [Required]
    public int AuthorId { get; set; }

    public Person Author { get; set; }
}
</code>```

Body:
I'm building a simple app for entertainment with ASP.NET Core where I currently just have a Post model and a User model.

Post.cs:

using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Threading.Tasks;

namespace WebApplication1.Models
{
    public class Post
    {
        [Required]
        public int Id { get; set; }

        [Required]
        [MaxLength(16)]
        public string Title { get; set; }

        public string Body { get; set; }

        [Required]
        public Person Author { get; set; }
    }
}

Person.cs:

using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Threading.Tasks;

namespace WebApplication1.Models
{
    public class Person
    {
        public int Id { get; set; }

        [Required]
        public string FirstName { get; set; }

        [Required]
        public string LastName { get; set; }

        [Required]
        public string Email { get; set; }

        [Required]
        public string Password { get; set; }

        public ICollection<Post> Posts = new List<Post>();
    }
}

I used Visual Studio's scaffolding to generate controllers for those models.
When I'm trying to POST /api/posts in order to create a new post, I want also to specify the Author ID for that post.

I tried adding the attribute authorId, I tried "authorId": 1 and also "author": { "id": 1 }, but because the Author is required, I always get back either Author is missing or Email in author is missing etc.

How can I include the authorId for in the post body in order I would be able to successfully create a new post?

Body:
Your controller will be expecting a valid whole Person class for the Author property (which means you would have to provide all the properties that are required for a Person) - try changing your Post class to include just the AuthorId as a required field. You can still include Author as a property, just dont make it required.

public class Post
{
    [Required]
    public int Id { get; set; }

    [Required]
    [MaxLength(16)]
    public string Title { get; set; }

    public string Body { get; set; }

    [Required]
    public int AuthorId { get; set; }

    public Person Author { get; set; }
}


问:
How to use properly razor syntax inside script block?
I work on an ASP.NET MVC 5 project.

I try to use razor syntax in script area on the cshtml page:

```<code><script type="text/javascript">
    var url = '@Url.Content("~/Account/Login/")';

    @if (Request.IsAuthenticated)
     {
          url = '@Url.Content("~/Account/GetLayers/")';
     }
</script>
</code>```

But when I run the page I get on this row:

```<code>url = '@Url.Content("~/Account/GetLayers/")';
</code>```

This error:

CS1012: Too many characters in character literal

So I tried this:

```<code> url = "@Url.Content("~/Account/GetLayers/")";
</code>```

But now I get this error:

CS1002: ; expected

Any idea why my attempts above don't work?

答:
Because you are already in a C# code block, (opened by your if condition statement). If you want to mix  js/plain text with C# code in razor, use @: prefix

If you are trying to generate the relative url to an action method, you should consider using Url.Action method.

```<code><script type="text/javascript">
  var url = '@Url.Action("Login","Account")';
  @if (Request.IsAuthenticated)
  {
      @:url = '@Url.Action("GetLayers","Account")';
  }
</script>
</code>```

The @: tells razor that the following expression should be considered as not code, but plain text

It is same as using the <text> tag

```<code>@if (!Request.IsAuthenticated)
{
   <text>url = '@Url.Action("Index")'</text>;
}
</code>```

You can convert this to a one liner with ternary operator

```<code><script type="text/javascript">
    var url = '@(Request.IsAuthenticated ? Url.Action("GetLayers","Account")
                                                   :  Url.Action("Login","Account"))';
    console.log(url);
</script>
</code>```

Body:
I work on an ASP.NET MVC 5 project.

I try to use razor syntax in script area on the cshtml page:

But when I run the page I get on this row:

url = '@Url.Content("~/Account/GetLayers/")';

This error:

CS1012: Too many characters in character literal

So I tried this:

 url = "@Url.Content("~/Account/GetLayers/")";

But now I get this error:

CS1002: ; expected

Any idea why my attempts above don't work?

Body:
Because you are already in a C# code block, (opened by your if condition statement). If you want to mix  js/plain text with C# code in razor, use @: prefix

If you are trying to generate the relative url to an action method, you should consider using Url.Action method.

<script type="text/javascript">
  var url = '@Url.Action("Login","Account")';
  @if (Request.IsAuthenticated)
  {
      @:url = '@Url.Action("GetLayers","Account")';
  }
</script>

The @: tells razor that the following expression should be considered as not code, but plain text

It is same as using the <text> tag

@if (!Request.IsAuthenticated)
{
   <text>url = '@Url.Action("Index")'</text>;
}

You can convert this to a one liner with ternary operator

<script type="text/javascript">
    var url = '@(Request.IsAuthenticated ? Url.Action("GetLayers","Account")
                                                   :  Url.Action("Login","Account"))';
    console.log(url);
</script>


问:
A program that prints even and odd characters from a string
This is for Homework

I have to write a program that asks the user to enter a string, then my program would separate the even and odd values from the entered string. Here is my program.

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

int main(void) {
    char *str[41];
    char odd[21];
    char even[21];
    int i = 0;
    int j = 0;
    int k = 0;

    printf("Enter a string (40 characters maximum): ");
    scanf("%s", &str);

    while (&str[i] < 41) {
        if (i % 2 == 0) {
            odd[j++] = *str[i];
        } else {
            even[k++] = *str[i];
        }
        i++;
    }

    printf("The even string is:%s\n ", even);
    printf("The odd string is:%s\n ", odd);

    return 0;
}
</code>```

When I try and compile my program I get two warnings:

For my scanf I get "format '%s' expects arguments of type char but argument has 'char * (*)[41]". I'm not sure what this means but I assume it's because of the array initialization.

On the while loop it gives me the warning that says comparison between pointer and integer. I'm not sure what that means either and I thought it was legal in C to make that comparison.

When I compile the program, I get random characters for both the even and odd string.

Any help would be appreciated!

答:
There are multiple problems in your code:

You define an array of pointers char *str[41], not an array of char.

You should pass the array to scanf instead of its address: When passed to a function, an array decays into a pointer to its first element.

You should limit the number of characters read by scanf.

You should iterate until the end of the string, not on all elements of the array, especially with (&str[i] < 41) that compares the address of the ith element with the value 41, which is meaningless.  The end of the string is the null terminator which can be tested with (str[i] != '\0').

You should read the characters from str with str[i].

You should null terminate the even and odd arrays.

Here is a modified version:

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

int main(void) {
    char str[41];
    char odd[21];
    char even[21];
    int i = 0;
    int j = 0;
    int k = 0;

    printf("Enter a string (40 characters maximum): ");
    if (scanf("%40s", str) != 1)
        return 1;

    while (str[i] != '\0') {
        if (i % 2 == 0) {
            odd[j++] = str[i];
        } else {
            even[k++] = str[i];
        }
        i++;
    }
    odd[j] = even[k] = '\0';

    printf("The even string is: %s\n", even);
    printf("The odd string is: %s\n", odd);

    return 0;
}
</code>```

Note that your interpretation of even and odd characters assumes 1-based offsets, ie: the first character is an odd character. This is not consistent with the C approach where an even characters would be interpreted as having en even offset from the beginning of the string, starting at 0.

Body:
This is for Homework

I have to write a program that asks the user to enter a string, then my program would separate the even and odd values from the entered string. Here is my program.

#include <stdio.h>
#include <string.h>

int main(void) {
    char *str[41];
    char odd[21];
    char even[21];
    int i = 0;
    int j = 0;
    int k = 0;

    printf("Enter a string (40 characters maximum): ");
    scanf("%s", &str);

    while (&str[i] < 41) {
        if (i % 2 == 0) {
            odd[j++] = *str[i];
        } else {
            even[k++] = *str[i];
        }
        i++;
    }

    printf("The even string is:%s\n ", even);
    printf("The odd string is:%s\n ", odd);

    return 0;
}

When I try and compile my program I get two warnings:

For my scanf I get "format '%s' expects arguments of type char but argument has 'char * (*)[41]". I'm not sure what this means but I assume it's because of the array initialization.

On the while loop it gives me the warning that says comparison between pointer and integer. I'm not sure what that means either and I thought it was legal in C to make that comparison.

When I compile the program, I get random characters for both the even and odd string.

Any help would be appreciated!

Body:
There are multiple problems in your code:

You define an array of pointers char *str[41], not an array of char.

You should pass the array to scanf instead of its address: When passed to a function, an array decays into a pointer to its first element.

You should limit the number of characters read by scanf.

You should iterate until the end of the string, not on all elements of the array, especially with (&str[i] < 41) that compares the address of the ith element with the value 41, which is meaningless.  The end of the string is the null terminator which can be tested with (str[i] != '\0').

You should read the characters from str with str[i].

You should null terminate the even and odd arrays.

Here is a modified version:

#include <stdio.h>

int main(void) {
    char str[41];
    char odd[21];
    char even[21];
    int i = 0;
    int j = 0;
    int k = 0;

    printf("Enter a string (40 characters maximum): ");
    if (scanf("%40s", str) != 1)
        return 1;

    while (str[i] != '\0') {
        if (i % 2 == 0) {
            odd[j++] = str[i];
        } else {
            even[k++] = str[i];
        }
        i++;
    }
    odd[j] = even[k] = '\0';

    printf("The even string is: %s\n", even);
    printf("The odd string is: %s\n", odd);

    return 0;
}

Note that your interpretation of even and odd characters assumes 1-based offsets, ie: the first character is an odd character. This is not consistent with the C approach where an even characters would be interpreted as having en even offset from the beginning of the string, starting at 0.


问:
groovy replaceAll with \n
I'm working with jobDsl in Jenkins 2

I have a script.dsl with patterns to replace

I'm triying to replace rDEST with desa\ntest

Here my example

```<code>example="choiceListText('rDEST')"
print ("example is ")
println (example)
exreplace = example.replaceAll("rDEST","desa\ntest")
print ("exreplace is ")
println (exreplace)
</code>```

The code result is

```<code>example is choiceListText('rDEST')
exreplace is choiceListText('desa
test')
</code>```

I'm expecting to get

```<code>exreplace is choiceListText('desa\ntest')
</code>```

I've tried Single quoted, Triple single quoted, Double quoted, Triple double quoted but stil cant get it done!

答:
Fixed code

```<code>example="choiceListText('rDEST')"
print ("example is ")
println (example)
exreplace = example.replaceAll("rDEST","desa \\\\n test")
print ("exreplace is ")
println (exreplace)
</code>```

Because
This "\\" is for the slash
This "\\" other one is for \n which also is a reserved character

And i also had to write 3 slashes to post my answer!!!

Thanks to Marcelo Gaston Rebasti Peralta!!!

Title: groovy replaceAll with \n

Body:
I'm working with jobDsl in Jenkins 2

I have a script.dsl with patterns to replace

I'm triying to replace rDEST with desa\ntest

Here my example

example="choiceListText('rDEST')"
print ("example is ")
println (example)
exreplace = example.replaceAll("rDEST","desa\ntest")
print ("exreplace is ")
println (exreplace)

The code result is

example is choiceListText('rDEST')
exreplace is choiceListText('desa
test')

I'm expecting to get

exreplace is choiceListText('desa\ntest')

I've tried Single quoted, Triple single quoted, Double quoted, Triple double quoted but stil cant get it done!

Body:
Fixed code

example="choiceListText('rDEST')"
print ("example is ")
println (example)
exreplace = example.replaceAll("rDEST","desa \\\\n test")
print ("exreplace is ")
println (exreplace)

Because
This "\\" is for the slash
This "\\" other one is for \n which also is a reserved character

And i also had to write 3 slashes to post my answer!!!

Thanks to Marcelo Gaston Rebasti Peralta!!!


问:
rxjs - delay function return until a stream value meets a condition and is unsubscribed
I have a method that is triggering a server request. It has access to a stream from the redux-store and should execute a callback as soon as the result of the request is found in the mentioned stream. So basically:

```<code>private resultStream$: Observable<boolean>;
doFetch(args, callback) {
    store.dispatchHttpRequest(args);
    // this should only be executed when resultStream$ emits true
    callback();
}
</code>```

How do I make callback(); to be called only when resultStream$ emits true AND I have unsubscribed from the stream, so there is no memory leak?

I have tried takeWhile(), putting the dispatchHttpRequest the setter of a conditional (for takeWhile) and the callback itself in the subscription() but it seems I am doing something wrong because I get bugs in my app. To be precise, the callback is only executed when doFetch() is called more than once, so the first request receives no callback-response.

答:
You can use finally which is called when the chain is disposed. This means when all observers unsubscribed or when the chain completed/errored.

```<code>private resultStream$: Observable<boolean>;

doFetch(args, callback) {
    store.dispatchHttpRequest(args);

    return this.resultStream
      // be aware that `takeWhile` completes when the predicate function returns false
      .takeWhile(val => !Boolean(val) /* or whatever ... */)
      .finally(() => callback());
}
</code>```

If you know the chain is going to complete you don't need to unsubscribe yourself.

Body:
I have a method that is triggering a server request. It has access to a stream from the redux-store and should execute a callback as soon as the result of the request is found in the mentioned stream. So basically:

private resultStream$: Observable<boolean>;
doFetch(args, callback) {
    store.dispatchHttpRequest(args);
    // this should only be executed when resultStream$ emits true
    callback();
}

How do I make callback(); to be called only when resultStream$ emits true AND I have unsubscribed from the stream, so there is no memory leak?

I have tried takeWhile(), putting the dispatchHttpRequest the setter of a conditional (for takeWhile) and the callback itself in the subscription() but it seems I am doing something wrong because I get bugs in my app. To be precise, the callback is only executed when doFetch() is called more than once, so the first request receives no callback-response.

Body:
You can use finally which is called when the chain is disposed. This means when all observers unsubscribed or when the chain completed/errored.

private resultStream$: Observable<boolean>;

doFetch(args, callback) {
    store.dispatchHttpRequest(args);

    return this.resultStream
      // be aware that `takeWhile` completes when the predicate function returns false
      .takeWhile(val => !Boolean(val) /* or whatever ... */)
      .finally(() => callback());
}

If you know the chain is going to complete you don't need to unsubscribe yourself.


问:
How to avoid the bug of transition opacity for vertical svg line in Chrome
I created a very simple vertical line with stroke-width: 1px and shape-rendering: crispEdges. When I tried to animate its opacity, it turned out that Google Chrome v62.0.3202.89 (64 bit) failed to render it properly, while other browsers (such as IE11, Edge, current versions of Firefox and Opera) do it correctly.

How do we avoid this erratic behavior before it is fixed in Chrome?

答:
I created this simple example https://codepen.io/ch3rn0v/pen/ZaypbW?editors=0110 to demonstrate three options for work-arounds, even though none of them if perfect.

Personally I think the one that makes the line not absolutely vertical is the best in terms of visual appearance, yet the knowledge that it is not purely vertical bothers me.

```<code>const notSoVerticalLineCoords = {
    x1: lineOffsetX + 2 * lineHorizontalOffset + 0.01,
    x2: lineOffsetX + 2 * lineHorizontalOffset,
    y1: lineTopOffsetY,
    y2: lineLength + lineTopOffsetY
};
</code>```

Body:
I created this simple example https://codepen.io/ch3rn0v/pen/ZaypbW?editors=0110 to demonstrate three options for work-arounds, even though none of them if perfect.

Personally I think the one that makes the line not absolutely vertical is the best in terms of visual appearance, yet the knowledge that it is not purely vertical bothers me.

const notSoVerticalLineCoords = {
    x1: lineOffsetX + 2 * lineHorizontalOffset + 0.01,
    x2: lineOffsetX + 2 * lineHorizontalOffset,
    y1: lineTopOffsetY,
    y2: lineLength + lineTopOffsetY
};


问:
How to changing layout based on screen size with react
I want to be able to change my layout when i hit a given screen size so i can change the way my site looks when it hits a mobile view.

Currently my react site scrolls horizontally using the package Horitzontal Scroll Package

I've tried implementing this with the react-responsive package which allows me to run media queries but there seems to be a conflict between the two packages.

So i want my site to scroll horizontal when in full screen (Desktop and table) and then scroll top to bottom in mobile view. How would i do this?

```<code>class Home extends React.Component{
constructor(props) {
    super(props);
    this.state = {};
}

componentWillMount() {
    this.setState({
        home: projectsData.filter( p => p.name === "homepage" ),
        galleryImages: [
            ImgOne,
            ImgTwo,
            ImgThree,
            ImgFour,
            ImgFive,
            ImgSix
        ]
    });
}

render(){

    const test = { color: "black", position: "fixed" }
    return(
        <div className="row">
            <Responsive minWidth={992}>
                <HorizontalScroll reverseScroll={true}>
                    <Header />
                    <SplashScreen />
                    <CopyText />
                </HorizontalScroll>
            </Responsive>
        </div>
    );
  }
}
</code>```

NOTE: I know that the horizontal-scroll package doesn't support sizing with percentages.

答:
I recommend looking into Media Queries. Here is a short video to show you the basics.

You can set a threshold that will trigger separate styles under those conditions. It can be very useful when you want your UI to do something different at different sizes.

```<code>@media only screen
and (*Your threshold criteria goes here* EXAMPLE:  max-width : 1000px) {
  //css goes here with whatever css you want to fire at this threshold
}
</code>```

Body:
I want to be able to change my layout when i hit a given screen size so i can change the way my site looks when it hits a mobile view.

Currently my react site scrolls horizontally using the package Horitzontal Scroll Package

I've tried implementing this with the react-responsive package which allows me to run media queries but there seems to be a conflict between the two packages.

So i want my site to scroll horizontal when in full screen (Desktop and table) and then scroll top to bottom in mobile view. How would i do this?

class Home extends React.Component{
constructor(props) {
    super(props);
    this.state = {};
}

componentWillMount() {
    this.setState({
        home: projectsData.filter( p => p.name === "homepage" ),
        galleryImages: [
            ImgOne,
            ImgTwo,
            ImgThree,
            ImgFour,
            ImgFive,
            ImgSix
        ]
    });
}

render(){

    const test = { color: "black", position: "fixed" }
    return(

            <Responsive minWidth={992}>
                <HorizontalScroll reverseScroll={true}>

                    <SplashScreen />
                    <CopyText />
                </HorizontalScroll>
            </Responsive>

    );
  }
}

NOTE: I know that the horizontal-scroll package doesn't support sizing with percentages.

Body:
I recommend looking into Media Queries. Here is a short video to show you the basics.

You can set a threshold that will trigger separate styles under those conditions. It can be very useful when you want your UI to do something different at different sizes.

@media only screen
and (*Your threshold criteria goes here* EXAMPLE:  max-width : 1000px) {
  //css goes here with whatever css you want to fire at this threshold
}


答:
For such cases you would make use of a computed property:</p>

```<code>import Controller from '@ember/controller';
import { computed } from '@ember/object';

export default Controller.extend({
  currentPhase: 1,

  strings: computed('currentPhase', function() {
    let currentPhase = this.get('currentPhase');
    return {
      title: "Title",
      phase1: `Phase ${currentPhase}`,
      phase2: `Phase ${currentPhase}`
    }
  }
});
</code>```

Title: Access variable in Ember controller

Body:
how can I access a variable in Ember controller?
I've tried those methods, but it doesn't work:

import ObjectController from '@ember/controller';
export default ObjectController.extend({

  currentPhase: 1,

  init: function () {
      var selfReference = this;
      this.set("currentPhase",1);
  },

  strings: {
      title: "Title",
      phase1: "Fase " + selfReference.get("currentPhase"),
      phase2: "Fase " + currentPhase
  }
});

Body:
For such cases you would make use of a computed property:

import Controller from '@ember/controller';
import { computed } from '@ember/object';

export default Controller.extend({
  currentPhase: 1,

  strings: computed('currentPhase', function() {
    let currentPhase = this.get('currentPhase');
    return {
      title: "Title",
      phase1: `Phase ${currentPhase}`,
      phase2: `Phase ${currentPhase}`
    }
  }
});


问:
Bind array values to dropdown in AngularJs
I have an Edit Page there I have an drop down called Role, while inserting I sent a value (like 1 instead "Role Name") to db, while retrieving to edit page I couldn't able to initialize the selected text in drop down

below is my html code

```<code><label class="adjust1-label-right">Role</label>
<select id="role" class="adjust-select-combo" ng-options="r.role_name for r in Role_Name track by r.roleid" ng-model="role">
      <option ng-repeat="rol.roleid for rol in Role_Name" value="{{rol.roleid}}">{{rol.role_name}}</option>
</select>
</code>```

I tried this but no luck

```<code>$scope.role = $scope.Role_Name[0];
</code>```

My data looks like

```<code>[{"Role_Id":1,"User_Id":10001}]
</code>```

答:
Have you tried with just using the ng-options

```<code><select id="role"
        class="adjust-select-combo"
        ng-options="r.Role_Id as r.User_Id for r in Role_Name"
        ng-model="role"></select>
</code>```

To set the selected role

```<code>$scope.role = $scope.Role_Name[0].Role_Id;
</code>```

Body:
I have an Edit Page there I have an drop down called Role, while inserting I sent a value (like 1 instead "Role Name") to db, while retrieving to edit page I couldn't able to initialize the selected text in drop down

below is my html code

Role
<select id="role" class="adjust-select-combo" ng-options="r.role_name for r in Role_Name track by r.roleid" ng-model="role">
      <option ng-repeat="rol.roleid for rol in Role_Name" value="{{rol.roleid}}">{{rol.role_name}}</option>
</select>

I tried this but no luck

$scope.role = $scope.Role_Name[0];

My data looks like

[{"Role_Id":1,"User_Id":10001}]

Body:
Have you tried with just using the ng-options

<select id="role"
        class="adjust-select-combo"
        ng-options="r.Role_Id as r.User_Id for r in Role_Name"
        ng-model="role"></select>

To set the selected role

$scope.role = $scope.Role_Name[0].Role_Id;


问:
How to get the Name and DeptId of the employees whose salary is greater than average of his department?
I am newbie to Hadoop and pig.As per the question i able to drill down till the below script but how can i compare salary of person to his average salary of his dept. Following is the script written to get average salary of each department

```<code>A = LOAD 'Assignment_1_Input.log' USING PigStorage('\t') as (id:int,name:chararray,age:int,salary:int,deptid:int);
B = GROUP A by deptid;
STORE B INTO 'Assign1GrpByNew';
C = FOREACH B GENERATE group as grpId,AVG(A.salary) as grpAvgSal;
DUMP C;
</code>```

Input File:

```<code>15878   mohan   24      8000    1
19173   ramya   27      10000   1
9527    krishna 35      40000   2
9528    raj     36      60000   2
16884   ravi    50      70000   2
</code>```

Expected Output

```<code>ramya   1
raj 2
ravi    2
</code>```

Help me out,Thanks

答:
GROUP BY dept_id and compute the avg salary for each employee record and select those employees who salary is greater than avg.

Snippet :

```<code>inp_data = LOAD 'Assignment_1_Input.log' USING PigStorage('\t') as (id:int,name:chararray,age:int,salary:int,deptid:int);
inp_data_fmt = FOREACH(GROUP inp_data BY deptid) GENERATE FLATTEN(inp_data), AVG(inp_data.salary) AS avg_salary;
req_data = FILTER inp_data_fmt BY salary > avg_salary;
DUMP req_data;
</code>```

Body:
I am newbie to Hadoop and pig.As per the question i able to drill down till the below script but how can i compare salary of person to his average salary of his dept. Following is the script written to get average salary of each department

A = LOAD 'Assignment_1_Input.log' USING PigStorage('\t') as (id:int,name:chararray,age:int,salary:int,deptid:int);
B = GROUP A by deptid;
STORE B INTO 'Assign1GrpByNew';
C = FOREACH B GENERATE group as grpId,AVG(A.salary) as grpAvgSal;
DUMP C;

Input File:

15878   mohan   24      8000    1
19173   ramya   27      10000   1
9527    krishna 35      40000   2
9528    raj     36      60000   2
16884   ravi    50      70000   2

Expected Output

ramya   1
raj 2
ravi    2

Help me out,Thanks

Body:
GROUP BY dept_id and compute the avg salary for each employee record and select those employees who salary is greater than avg.

Snippet :

inp_data = LOAD 'Assignment_1_Input.log' USING PigStorage('\t') as (id:int,name:chararray,age:int,salary:int,deptid:int);
inp_data_fmt = FOREACH(GROUP inp_data BY deptid) GENERATE FLATTEN(inp_data), AVG(inp_data.salary) AS avg_salary;
req_data = FILTER inp_data_fmt BY salary > avg_salary;
DUMP req_data;


问:
Creating a graph based on specific conditions
I have a question that asks me to make a graph such that the BFS and DFS trees from the graph is not a minimum spanning tree and the order of the adjacency list does not matter, I know the properties of BFS DFS and MST but I'm a confused by the question. How should I be approaching the problem? (not looking for the solution)</p>

答:
Imagine a complete graph on k vertices. For k > 3, a DFS tree will always look different from a BFS tree. For k > 4, you can have a MST that is different from both the BFS and DFS trees. You can choose the shape of the MST to be different from the DFS tree by ensuring one vertex needs three edges coming out of it. You can choose the shape of the MST to be different from the BFS tree by ensuring no vertex has more than three edges coming out of it. You choose the shape of the MST by assigning weights to make the edges you choose, and only those edges, part of the MST.

```<code>DFS Tree

1-----2----3
           |
           |
     4-----5

BFS Tree

      1
  ____|____
 /   / \   \
2   3   4   5

MST

2
|
1---3---5
|
4
</code>```

The complete graph on five vertices has 5 * 4 / 2 = 10 edges, of which only four are needed in any tree.

Body:
Imagine a complete graph on k vertices. For k > 3, a DFS tree will always look different from a BFS tree. For k > 4, you can have a MST that is different from both the BFS and DFS trees. You can choose the shape of the MST to be different from the DFS tree by ensuring one vertex needs three edges coming out of it. You can choose the shape of the MST to be different from the BFS tree by ensuring no vertex has more than three edges coming out of it. You choose the shape of the MST by assigning weights to make the edges you choose, and only those edges, part of the MST.

DFS Tree

1-----2----3
           |
           |
     4-----5

BFS Tree

      1
  ____|____
 /   / \   \
2   3   4   5

MST

2
|
1---3---5
|
4

The complete graph on five vertices has 5 * 4 / 2 = 10 edges, of which only four are needed in any tree.


问:
Get the Worksheet Name of all the .xlsx Workbooks inside a directory
I have a textbox where I am getting an Input Directory and calculating the number of .xlsx reports and the total number of worksheets in those report.

I would like to get the report name and sheetname of each of those report.

What could be the quickest way to get that.

As there are cases where it could be 100 workbooks and total of 1000 worksheets inside them.

Here goes my code which Just gets the number of reports and worksheets in those reports.

```<code>Private Sub FL_TextBox_Change()

Dim FolderPath As String
Dim path As String
Dim count As Integer
Dim Wk As Workbook

Dim Ws As Workbook
Set Ws = ActiveWorkbook

FolderPath = NewTask.FL_TextBox.Value

MsgBox ("Click Ok & Wait for the Total Number of Reports and Worksheets" & vbNewLine & vbNewLine & "to be calculated.")

If FolderPath = "" Then

     NewTask.Num_Rpt_TextBox.Value = ""

     Ws.Sheets("Config").Range("I1").Value = ""

Else

    path = FolderPath & "\*.xlsx"
    Filename = Dir(path)
    File = (FolderPath & "\" & Filename)
    wkcount = 0
    Shcount = 0
    shtcount = 0
    RptSheets = ""
    Do While Filename <> ""
        wkcount = wkcount + 1
        File = FolderPath & "\" & Filename
        Set Wk = Workbooks.Open(File, ReadOnly:=True)
        Shcount = Wk.Sheets.count
        If RptSheets <> "" Then
           RptSheets = RptSheets & "," & Shcount
        Else
           RptSheets = Shcount
        End If
        Wk.Close
        shtcount = shtcount + Shcount
        Filename = Dir()
    Loop

Ws.Sheets("Config").Range("I1").Value = RptSheets
XlsxFilesPresent = wkcount & " / " & shtcount
NewTask.Num_Rpt_TextBox.Value = XlsxFilesPresent
End If

End Sub
</code>```

So, in short - I want to get the number of .xlsx reports and those report names and number of worksheets inside those report and the worksheet names in a structured way.

Something like

```<code>Number of workbooks = 3

Number of Worksheets = 100

ReportNames = TestFile1, TestFile2, TestFile3.
</code>```

SheetNames = TestFile1:TestSheet1, TestFile1:TestSheet2, TestFile1:TestSheet3, TestFile1:TestSheet4 etc.,

Kindly share your thoughts in getting this process running faster.

答:
It seems you have everything you need, you just need to add some lines to make an object that contains all of the data you need and then you can use that object to extract anything you want and I cannot think of anything better than a dictionary object.

All of the information of the sheets are stored in a collection object called worksheets so you can simply store that object and iterate through it to access worksheet names and possibly any other information you want. So first create a collection object and a dictionary object like this:

```<code>Dim coll As Object
Dim dict As Object

Set dict = CreateObject("scripting.dictionary")
</code>```

Inside your do while loop use workbook names as keys and the worksheets object of that workbook as the item. Note that the keys should be unique and I assume that you will run this in one directory so file names must be unique forced by your OS.

To add keys and items inside the loop after you opened the workbook use this:

```<code>set coll=wk.Worksheets
dict.add Wk,coll
</code>```

once the execution gets out of the loop you have a dictionary of all workbooks and their worksheets object. Now you can loop through the dictionary and form the data however you want. for example, let's say you want to print the workbook name and then the worksheets:

```<code>dim i as integer
dim key as variant
Dim sht As Worksheet

for each key in dict.keys
    set coll=dict(key) 'sets the item of the dict=worksheets
    For i = 1 To coll.Count 'loop through worksheets object and print their names
        Set sht = coll(i)
        Debug.Print key & ":" & sht.Name
    Next
next key
</code>```

Body:
I have a textbox where I am getting an Input Directory and calculating the number of .xlsx reports and the total number of worksheets in those report.

I would like to get the report name and sheetname of each of those report.

What could be the quickest way to get that.

As there are cases where it could be 100 workbooks and total of 1000 worksheets inside them.

Here goes my code which Just gets the number of reports and worksheets in those reports.

Private Sub FL_TextBox_Change()

Dim FolderPath As String
Dim path As String
Dim count As Integer
Dim Wk As Workbook

Dim Ws As Workbook
Set Ws = ActiveWorkbook

FolderPath = NewTask.FL_TextBox.Value

MsgBox ("Click Ok & Wait for the Total Number of Reports and Worksheets" & vbNewLine & vbNewLine & "to be calculated.")

If FolderPath = "" Then

     NewTask.Num_Rpt_TextBox.Value = ""

     Ws.Sheets("Config").Range("I1").Value = ""

Else

    path = FolderPath & "\*.xlsx"
    Filename = Dir(path)
    File = (FolderPath & "\" & Filename)
    wkcount = 0
    Shcount = 0
    shtcount = 0
    RptSheets = ""
    Do While Filename <> ""
        wkcount = wkcount + 1
        File = FolderPath & "\" & Filename
        Set Wk = Workbooks.Open(File, ReadOnly:=True)
        Shcount = Wk.Sheets.count
        If RptSheets <> "" Then
           RptSheets = RptSheets & "," & Shcount
        Else
           RptSheets = Shcount
        End If
        Wk.Close
        shtcount = shtcount + Shcount
        Filename = Dir()
    Loop

Ws.Sheets("Config").Range("I1").Value = RptSheets
XlsxFilesPresent = wkcount & " / " & shtcount
NewTask.Num_Rpt_TextBox.Value = XlsxFilesPresent
End If

End Sub

So, in short - I want to get the number of .xlsx reports and those report names and number of worksheets inside those report and the worksheet names in a structured way.

Something like

Number of workbooks = 3

Number of Worksheets = 100

ReportNames = TestFile1, TestFile2, TestFile3.

SheetNames = TestFile1:TestSheet1, TestFile1:TestSheet2, TestFile1:TestSheet3, TestFile1:TestSheet4 etc.,

Kindly share your thoughts in getting this process running faster.

Body:
It seems you have everything you need, you just need to add some lines to make an object that contains all of the data you need and then you can use that object to extract anything you want and I cannot think of anything better than a dictionary object.

All of the information of the sheets are stored in a collection object called worksheets so you can simply store that object and iterate through it to access worksheet names and possibly any other information you want. So first create a collection object and a dictionary object like this:

Dim coll As Object
Dim dict As Object

Set dict = CreateObject("scripting.dictionary")

Inside your do while loop use workbook names as keys and the worksheets object of that workbook as the item. Note that the keys should be unique and I assume that you will run this in one directory so file names must be unique forced by your OS.

To add keys and items inside the loop after you opened the workbook use this:

set coll=wk.Worksheets
dict.add Wk,coll

once the execution gets out of the loop you have a dictionary of all workbooks and their worksheets object. Now you can loop through the dictionary and form the data however you want. for example, let's say you want to print the workbook name and then the worksheets:

dim i as integer
dim key as variant
Dim sht As Worksheet

for each key in dict.keys
    set coll=dict(key) 'sets the item of the dict=worksheets
    For i = 1 To coll.Count 'loop through worksheets object and print their names
        Set sht = coll(i)
        Debug.Print key & ":" & sht.Name
    Next
next key


问:
Overloading for forward iterators
While looking at libc++ I've found two different ways of overloading a function when template arguments are forward iterators.

First way is using std::iterator_traits::iterator_category

```<code>template <class ForwardIter1, class ForwardIter2>
inline
bool
__some_function(ForwardIter1 first1, ForwardIter1 last1,
                ForwardIter2 first2, ForwardIter2 last2,
                std::forward_iterator_tag, std::forward_iterator_tag)
{
    // do stuff ...

    return true;
}

template <class InputIter1, class InputIter2>
inline
bool
__some_function(InputIter1 first1, InputIter1 last1,
                InputIter2 first2, InputIter2 last2,
                std::input_iterator_tag, std::input_iterator_tag)
{
    // do stuff ...

    return true;
}

template <class InputIter1, class InputIter2>
inline
bool
some_function(InputIter1 first1, InputIter1 last1,
              InputIter2 first2, InputIter2 last2)
{
    return __some_function(first1, last1, first2, last2,
                           typename std::iterator_traits<InputIter1>::iterator_category(),
                           typename std::iterator_traits<InputIter2>::iterator_category());
}
</code>```

But I've also seen uses of std::enable_if

```<code>template <class ForwardIter1, class ForwardIter2>
inline
bool
some_function(ForwardIter1 first1, ForwardIter1 last1,
              ForwardIter2 first2, ForwardIter2 last2,
              typename std::enable_if<
                  __is_forward_iterator<ForwardIter1>::value &&
                  __is_forward_iterator<ForwardIter2>::value
              >::type* = 0)
{
    // do stuff ...

    return true;
}

template <class InputIter1, class InputIter2>
inline
bool
some_function(InputIter1 first1, InputIter1 last1,
              InputIter2 first2, InputIter2 last2,
              typename std::enable_if<
                  __is_exactly_input_iterator<InputIter1>::value &&
                  __is_exactly_input_iterator<InputIter2>::value
              >::type* = 0)
{
    // do stuff ...

    return true;
}
</code>```

Which of these two are the "prefered" way of solving the problem or does that depend on the situation. In that case, when would one solution be better than the other?

答:
The better way would be to use enable if as a return type so there is no need to pass any extra parameters (with defaulted value) to function:

```<code>template <class ForwardIter1, class ForwardIter2>
typename std::enable_if
<
    __is_forward_iterator<ForwardIter1>::value
    &&
    __is_forward_iterator<ForwardIter2>::value
,   bool
>::type
some_function
(
    ForwardIter1 first1, ForwardIter1 last1
,   ForwardIter2 first2, ForwardIter2 last2
)
{
    // do stuff ...
    return(true);
}
</code>```

Also identifiers with double underscore are reserved, but let's assume that __is_forward_iterator template is valid and exist somewhere.

Title: Overloading for forward iterators

Body:
While looking at libc++ I've found two different ways of overloading a function when template arguments are forward iterators.

First way is using std::iterator_traits::iterator_category

template <class ForwardIter1, class ForwardIter2>
inline
bool
__some_function(ForwardIter1 first1, ForwardIter1 last1,
                ForwardIter2 first2, ForwardIter2 last2,
                std::forward_iterator_tag, std::forward_iterator_tag)
{
    // do stuff ...

    return true;
}

template <class InputIter1, class InputIter2>
inline
bool
__some_function(InputIter1 first1, InputIter1 last1,
                InputIter2 first2, InputIter2 last2,
                std::input_iterator_tag, std::input_iterator_tag)
{
    // do stuff ...

    return true;
}

template <class InputIter1, class InputIter2>
inline
bool
some_function(InputIter1 first1, InputIter1 last1,
              InputIter2 first2, InputIter2 last2)
{
    return __some_function(first1, last1, first2, last2,
                           typename std::iterator_traits<InputIter1>::iterator_category(),
                           typename std::iterator_traits<InputIter2>::iterator_category());
}

But I've also seen uses of std::enable_if

template <class ForwardIter1, class ForwardIter2>
inline
bool
some_function(ForwardIter1 first1, ForwardIter1 last1,
              ForwardIter2 first2, ForwardIter2 last2,
              typename std::enable_if<
                  __is_forward_iterator<ForwardIter1>::value &&
                  __is_forward_iterator<ForwardIter2>::value
              >::type* = 0)
{
    // do stuff ...

    return true;
}

template <class InputIter1, class InputIter2>
inline
bool
some_function(InputIter1 first1, InputIter1 last1,
              InputIter2 first2, InputIter2 last2,
              typename std::enable_if<
                  __is_exactly_input_iterator<InputIter1>::value &&
                  __is_exactly_input_iterator<InputIter2>::value
              >::type* = 0)
{
    // do stuff ...

    return true;
}

Which of these two are the "prefered" way of solving the problem or does that depend on the situation. In that case, when would one solution be better than the other?

Body:
The better way would be to use enable if as a return type so there is no need to pass any extra parameters (with defaulted value) to function:

template <class ForwardIter1, class ForwardIter2>
typename std::enable_if
<
    __is_forward_iterator<ForwardIter1>::value
    &&
    __is_forward_iterator<ForwardIter2>::value
,   bool
>::type
some_function
(
    ForwardIter1 first1, ForwardIter1 last1
,   ForwardIter2 first2, ForwardIter2 last2
)
{
    // do stuff ...
    return(true);
}

Also identifiers with double underscore are reserved, but let's assume that __is_forward_iterator template is valid and exist somewhere.


问:
convert WPF WebBrowser to WinForms
I am trying to convert a WPF WebBrowser control to a WinForms WebBrowser control using this code:

```<code>System.Windows.Forms.WebBrowser wb = myWebBrowser as System.Windows.Forms.WebBrowser();
</code>```

I am getting this error:

"Cannot convert type 'System.Windows.Controls.WebBrowser' to 'System.Windows.Forms.WebBrowser' via a reference conversion, boxing conversion, unboxing conversion, wrapping conversion, or null type conversion"

Any help would be appreciated.

Thanks!

答:
You cannot convert between these two classes.  They are completely separate implementations, one for WPF, and one for Windows Forms.

If you must use a Windows Forms WebBrowser, you'll need to instance one from scratch, and copy individual settings across as required.

Title: convert WPF WebBrowser to WinForms

Body:
I am trying to convert a WPF WebBrowser control to a WinForms WebBrowser control using this code:

System.Windows.Forms.WebBrowser wb = myWebBrowser as System.Windows.Forms.WebBrowser();

I am getting this error:

"Cannot convert type 'System.Windows.Controls.WebBrowser' to 'System.Windows.Forms.WebBrowser' via a reference conversion, boxing conversion, unboxing conversion, wrapping conversion, or null type conversion"

Any help would be appreciated.

Thanks!


问:
Extending express.Request in project
I am new to Typescript, so bear with me.

I am working on an Express-based web service. I want to let a piece of early middleware set a logging object on the request object, and use it later in the request handler flow.

The middleware and the final request handler are organized in different files.

What would be the best way to centrally extend the express.Request-object to allow using this logging object without having type warnings?

Just to show what I have and want:

The file that instantiates express and sets my log object:

```<code>const app = express();
const log = console;

app.use((req: express.Request, res: express.Response, next: express.NextFunction) => {
    req.log = log;
    next();
});
</code>```

A request handler:

```<code>(req: express.Request, res: express.Response): void => {
    req.log("request was made");
    res.send();
}
</code>```

答:
You can extend the express.Request object like this:

```<code>declare global {
  namespace Express {
    interface Request {
      log(...params: any[]): void
    }
  }
}
</code>```

Or, if you want to make a clearer distinction between the vanilla Request type and your augmented version, you could do something like this:

```<code>interface RequestWithLogging extends express.Request {
  log(...params: any[]): void
}

app.get('/', (req: RequestWithLogging, res: express.Response) => {
  req.log('Log something')
  res.send('Hello World!')
})
</code>```

Title: Extending express.Request in project

Body:
I am new to Typescript, so bear with me.

I am working on an Express-based web service. I want to let a piece of early middleware set a logging object on the request object, and use it later in the request handler flow.

The middleware and the final request handler are organized in different files.

What would be the best way to centrally extend the express.Request-object to allow using this logging object without having type warnings?

Just to show what I have and want:

The file that instantiates express and sets my log object:

const app = express();
const log = console;

app.use((req: express.Request, res: express.Response, next: express.NextFunction) => {
    req.log = log;
    next();
});

A request handler:

(req: express.Request, res: express.Response): void => {
    req.log("request was made");
    res.send();
}

Body:
You can extend the express.Request object like this:

declare global {
  namespace Express {
    interface Request {
      log(...params: any[]): void
    }
  }
}

Or, if you want to make a clearer distinction between the vanilla Request type and your augmented version, you could do something like this:

interface RequestWithLogging extends express.Request {
  log(...params: any[]): void
}

app.get('/', (req: RequestWithLogging, res: express.Response) => {
  req.log('Log something')
  res.send('Hello World!')
})


问:
wxPython background image disturbance
wxPython background code is distrubing other sizers. How do I fix it so that it won't influence other objects in the frame?</p>

```<code>backgroundfile = wx.Image(backgroundfilepath, wx.BITMAP_TYPE_ANY).ConvertToBitmap()
self.bitmap1 = wx.StaticBitmap(self, -1, backgroundfile, (0, 0))
</code>```

答: wx.StaticBitmap is a distinct widget, and the behavior of overlapping sibling widgets is undefined in wx. A better approach would be to bind a handler for the parent's EVT_PAINT event and draw the background bitmap in that handler.

Title: wxPython background image disturbance

Body:
wxPython background code is distrubing other sizers. How do I fix it so that it won't influence other objects in the frame?

backgroundfile = wx.Image(backgroundfilepath, wx.BITMAP_TYPE_ANY).ConvertToBitmap()
self.bitmap1 = wx.StaticBitmap(self, -1, backgroundfile, (0, 0))


问:
Wildfly domain mode debug
I have tried to configure widfly for remote debugging in domain mode, using Eclipse, but it's not successful. Does anyone know the detail configuration for Wildfly domain mode debugging with Eclipse. Thank you!</p>

答:
To debug the server instance, you need to setup the JVM Configuration of the server group.

For this, using Wildfly Management (like http://{ip}:9990/console/App.html):

Access Wildfly Management from your Wildfly

Click on Runtime

Choose the server group from the list and click on View

Choose the JVM Configuration tab and click on Edit

On JVM Options put this line: -agentlib:jdwp=transport=dt_socket,address=8787,server=y,suspend=n

Save the modifications and reload the server group.

To connect to the server, use the port 8787.

Title: Wildfly domain mode debug


问:
Fragment BroadCast receiver not working
I'm making an app where I need to get constant location updates from a Service on a fragment, the problem is that the fragment is not getting the updates and I'm not sure what is the problem, here is the service:

```<code>public class GPService extends Service
{
 private LocationManager locMan;
 private Boolean locationChanged;
 private Handler handler = new Handler();
 static final int REQUEST_LOCATION = 1;

public static Location curLocation;
public static boolean isService = true;
public LocalBroadcastManager broadcast;

LocationListener gpsListener = new LocationListener() {
    public void onLocationChanged(Location location) {
        if (curLocation == null) {
            curLocation = location;
            locationChanged = true;
            Intent intent= new Intent("GPSLocationUpdates");
            intent.putExtra("latitud",curLocation.getLatitude());
            intent.putExtra("latitud",curLocation.getLongitude());
            LocalBroadcastManager.getInstance(getApplicationContext()).sendBroadcast(intent);

        }else if (curLocation.getLatitude() == location.getLatitude() && curLocation.getLongitude() == location.getLongitude()){
            locationChanged = false;
            return;
        }else
            locationChanged = true;

        curLocation = location;

        if (locationChanged)
            locMan.removeUpdates(gpsListener);

    }
    public void onProviderDisabled(String provider) {
    }

    public void onProviderEnabled(String provider) {
    }

    public void onStatusChanged(String provider, int status,Bundle extras) {

    }

};

@Override
public void onCreate() {
    super.onCreate();

    curLocation = getBestLocation();

    if (curLocation == null)
        Toast.makeText(getBaseContext(),"Unable to get your location", Toast.LENGTH_SHORT).show();
    else{
        //Toast.makeText(getBaseContext(), curLocation.toString(), Toast.LENGTH_LONG).show();
    }

    isService =  true;
    broadcast= LocalBroadcastManager.getInstance(this);

}
final String TAG="LocationService";
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    return super.onStartCommand(intent, flags, startId);
}
@Override
public void onLowMemory() {
    super.onLowMemory();
}

@Override
public void onStart(Intent i, int startId){
    handler.postDelayed(GpsFinder,1);
}

@Override
public void onDestroy() {
    handler.removeCallbacks(GpsFinder);
    handler = null;
    Toast.makeText(this, "Stop services", Toast.LENGTH_SHORT).show();
    isService = false;
}

public IBinder onBind(Intent arg0) {
    return null;
}

public Runnable GpsFinder = new Runnable(){
    public void run(){

        Location tempLoc = getBestLocation();
        if(tempLoc!=null)
            curLocation = tempLoc;
        tempLoc = null;
        handler.postDelayed(GpsFinder,1000);
    }
};

private Location getBestLocation() {
    Location gpslocation = null;
    Location networkLocation = null;

    if(locMan==null){
        locMan = (LocationManager) getApplicationContext() .getSystemService(Context.LOCATION_SERVICE);
    }
    try {
        if ( ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION)
                != PackageManager.PERMISSION_GRANTED &&
                ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_COARSE_LOCATION)
                        != PackageManager.PERMISSION_GRANTED) {

            //ActivityCompat.requestPermissions(this, new String[]{android.Manifest.permission.ACCESS_FINE_LOCATION}, REQUEST_LOCATION);
        }
        else {
            if(locMan.isProviderEnabled(LocationManager.GPS_PROVIDER)){

                locMan.requestLocationUpdates(LocationManager.GPS_PROVIDER,1000, 1, gpsListener);
                gpslocation = locMan.getLastKnownLocation(LocationManager.GPS_PROVIDER);
                Intent intent= new Intent("GPSLocationUpdates");
                intent.putExtra("latitud",gpslocation.getLatitude());
                intent.putExtra("longitud",gpslocation.getLongitude());
                Log.wtf("COORDENATES TO SEND",gpslocation.getLatitude()+" "+gpslocation.getLongitude());
                LocalBroadcastManager.getInstance(getApplicationContext()).sendBroadcast(intent);

            }
            if(locMan.isProviderEnabled(LocationManager.NETWORK_PROVIDER)){
                locMan.requestLocationUpdates(LocationManager.NETWORK_PROVIDER,1000, 1, gpsListener);
                networkLocation = locMan.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
                Intent intent= new Intent("GPSLocationUpdates");
                Log.wtf("LAS COORDENADAS a enviar SON",networkLocation.getLatitude()+" "+networkLocation.getLongitude());

                intent.putExtra("latitud",networkLocation.getLatitude());
                intent.putExtra("longitud",networkLocation.getLongitude());
                LocalBroadcastManager.getInstance(getApplicationContext()).sendBroadcast(intent);
            }
        }
</code>```

The service is initiated in the activity like this

```<code> startService(new Intent(this, GPService.class));
</code>```

In the fragment this is how I create it and register it

```<code>public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    receiver= new GPSReceiver();
    //this.getActivity().registerReceiver(receiver, new IntentFilter());

    db=Database.getInstance(this.getContext());

}
@Override
public void onResume() {
    super.onResume();
    IntentFilter filter = new IntentFilter("GPSLocationUpdates");
    getActivity().registerReceiver(receiver,filter);
}

@Override
public void onPause() {
    getActivity().unregisterReceiver(receiver);
    super.onPause();
}
</code>```

Finally this is the reciever in the Fragment, I can't get it to get the info from the service, any ideas? I don't know what I'm doing wrong.

```<code>private class GPSReceiver extends BroadcastReceiver {

    private LatLng changed;

    public GPSReceiver()
    {
        changed= new LatLng(0,0);
    }
    @Override
    public void onReceive(Context context, Intent intent) {
        Log.wtf("RECIEVE", "IT IS IN BROADCAST");
        if (intent.getAction().equals("GPSLocationUpdates"))
        {
            Log.wtf("RECIEVE1", "INTENT ARRIVES");
            double lat= intent.getDoubleExtra("latitud",1);
            double longi= intent.getDoubleExtra("longitud",1);
            changed= new LatLng(lat,longi);

        }
       // String text = intent.getStringExtra("position");

    }
    public LatLng getChanged()
    {
        return changed;
    }
}
</code>```

The service seems to be working fine, I can see the coordinates in the console being send.

答:
You're not registering you BroadcastReceiver to the LocalBroadcastManager.  You're registering it to the global broadcast manager, but sending on the local.

Change:

```<code>@Override
public void onResume() {
    super.onResume();
    IntentFilter filter = new IntentFilter("GPSLocationUpdates");
    LocalBroadcastManager.getInstance(getActivity()).registerReceiver(receiver,filter);
}

@Override
public void onPause() {
    LocalBroadcastManager.getInstance(getActivity()).unregisterReceiver(receiver);
    super.onPause();
}
</code>```

Title: Fragment BroadCast receiver not working

Body:
I'm making an app where I need to get constant location updates from a Service on a fragment, the problem is that the fragment is not getting the updates and I'm not sure what is the problem, here is the service:

public class GPService extends Service
{
 private LocationManager locMan;
 private Boolean locationChanged;
 private Handler handler = new Handler();
 static final int REQUEST_LOCATION = 1;

public static Location curLocation;
public static boolean isService = true;
public LocalBroadcastManager broadcast;

LocationListener gpsListener = new LocationListener() {
    public void onLocationChanged(Location location) {
        if (curLocation == null) {
            curLocation = location;
            locationChanged = true;
            Intent intent= new Intent("GPSLocationUpdates");
            intent.putExtra("latitud",curLocation.getLatitude());
            intent.putExtra("latitud",curLocation.getLongitude());
            LocalBroadcastManager.getInstance(getApplicationContext()).sendBroadcast(intent);

        }else if (curLocation.getLatitude() == location.getLatitude() && curLocation.getLongitude() == location.getLongitude()){
            locationChanged = false;
            return;
        }else
            locationChanged = true;

        curLocation = location;

        if (locationChanged)
            locMan.removeUpdates(gpsListener);

    }
    public void onProviderDisabled(String provider) {
    }

    public void onProviderEnabled(String provider) {
    }

    public void onStatusChanged(String provider, int status,Bundle extras) {

    }

};

@Override
public void onCreate() {
    super.onCreate();

    curLocation = getBestLocation();

    if (curLocation == null)
        Toast.makeText(getBaseContext(),"Unable to get your location", Toast.LENGTH_SHORT).show();
    else{
        //Toast.makeText(getBaseContext(), curLocation.toString(), Toast.LENGTH_LONG).show();
    }

    isService =  true;
    broadcast= LocalBroadcastManager.getInstance(this);

}
final String TAG="LocationService";
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    return super.onStartCommand(intent, flags, startId);
}
@Override
public void onLowMemory() {
    super.onLowMemory();
}

@Override
public void onStart(Intent i, int startId){
    handler.postDelayed(GpsFinder,1);
}

@Override
public void onDestroy() {
    handler.removeCallbacks(GpsFinder);
    handler = null;
    Toast.makeText(this, "Stop services", Toast.LENGTH_SHORT).show();
    isService = false;
}

public IBinder onBind(Intent arg0) {
    return null;
}

public Runnable GpsFinder = new Runnable(){
    public void run(){

        Location tempLoc = getBestLocation();
        if(tempLoc!=null)
            curLocation = tempLoc;
        tempLoc = null;
        handler.postDelayed(GpsFinder,1000);
    }
};

private Location getBestLocation() {
    Location gpslocation = null;
    Location networkLocation = null;

    if(locMan==null){
        locMan = (LocationManager) getApplicationContext() .getSystemService(Context.LOCATION_SERVICE);
    }
    try {
        if ( ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION)
                != PackageManager.PERMISSION_GRANTED &&
                ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_COARSE_LOCATION)
                        != PackageManager.PERMISSION_GRANTED) {

            //ActivityCompat.requestPermissions(this, new String[]{android.Manifest.permission.ACCESS_FINE_LOCATION}, REQUEST_LOCATION);
        }
        else {
            if(locMan.isProviderEnabled(LocationManager.GPS_PROVIDER)){

                locMan.requestLocationUpdates(LocationManager.GPS_PROVIDER,1000, 1, gpsListener);
                gpslocation = locMan.getLastKnownLocation(LocationManager.GPS_PROVIDER);
                Intent intent= new Intent("GPSLocationUpdates");
                intent.putExtra("latitud",gpslocation.getLatitude());
                intent.putExtra("longitud",gpslocation.getLongitude());
                Log.wtf("COORDENATES TO SEND",gpslocation.getLatitude()+" "+gpslocation.getLongitude());
                LocalBroadcastManager.getInstance(getApplicationContext()).sendBroadcast(intent);

            }
            if(locMan.isProviderEnabled(LocationManager.NETWORK_PROVIDER)){
                locMan.requestLocationUpdates(LocationManager.NETWORK_PROVIDER,1000, 1, gpsListener);
                networkLocation = locMan.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
                Intent intent= new Intent("GPSLocationUpdates");
                Log.wtf("LAS COORDENADAS a enviar SON",networkLocation.getLatitude()+" "+networkLocation.getLongitude());

                intent.putExtra("latitud",networkLocation.getLatitude());
                intent.putExtra("longitud",networkLocation.getLongitude());
                LocalBroadcastManager.getInstance(getApplicationContext()).sendBroadcast(intent);
            }
        }

The service is initiated in the activity like this

 startService(new Intent(this, GPService.class));

In the fragment this is how I create it and register it

public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    receiver= new GPSReceiver();
    //this.getActivity().registerReceiver(receiver, new IntentFilter());

    db=Database.getInstance(this.getContext());

}
@Override
public void onResume() {
    super.onResume();
    IntentFilter filter = new IntentFilter("GPSLocationUpdates");
    getActivity().registerReceiver(receiver,filter);
}

@Override
public void onPause() {
    getActivity().unregisterReceiver(receiver);
    super.onPause();
}

Finally this is the reciever in the Fragment, I can't get it to get the info from the service, any ideas? I don't know what I'm doing wrong.

private class GPSReceiver extends BroadcastReceiver {

    private LatLng changed;

    public GPSReceiver()
    {
        changed= new LatLng(0,0);
    }
    @Override
    public void onReceive(Context context, Intent intent) {
        Log.wtf("RECIEVE", "IT IS IN BROADCAST");
        if (intent.getAction().equals("GPSLocationUpdates"))
        {
            Log.wtf("RECIEVE1", "INTENT ARRIVES");
            double lat= intent.getDoubleExtra("latitud",1);
            double longi= intent.getDoubleExtra("longitud",1);
            changed= new LatLng(lat,longi);

        }
       // String text = intent.getStringExtra("position");

    }
    public LatLng getChanged()
    {
        return changed;
    }
}

The service seems to be working fine, I can see the coordinates in the console being send.

Body:
You're not registering you BroadcastReceiver to the LocalBroadcastManager.  You're registering it to the global broadcast manager, but sending on the local.

Change:

@Override
public void onResume() {
    super.onResume();
    IntentFilter filter = new IntentFilter("GPSLocationUpdates");
    LocalBroadcastManager.getInstance(getActivity()).registerReceiver(receiver,filter);
}

@Override
public void onPause() {
    LocalBroadcastManager.getInstance(getActivity()).unregisterReceiver(receiver);
    super.onPause();
}


问:
Conditionally delete line suffix and add prefix
I have 4 lines:

```<code>812.12 135.14 646.17 1
812.12 135.14 646.18 1
812.12 135.14 646.19 2
812.12 135.14 646.20 2
</code>```

I want to remove the last character of each line. Moreover, if the last character changes from previous line, S will be added in the front. For example, given the input above, the third line's last character is 2 which is different from 1 that terminates the second line. Therefore, S will be added in the front as shown below.

Desired output:

```<code>812.12 135.14 646.17
812.12 135.14 646.18
S 812.12 135.14 646.19
812.12 135.14 646.20
</code>```

I have this piece of code to start:

```<code>while(lines[0].charAt(lines[0].length()-1)==lines[1].charAt(lines[1].length()-1)){
    continue;
}
</code>```

答:
This code would work:

```<code>public static void main(String[] args) {
    String[] lines = new String[4];
    lines[0] = "812.12 135.14 646.17 1";
    lines[1] = "812.12 135.14 646.18 1";
    lines[2] = "812.12 135.14 646.19 2";
    lines[3] = "812.12 135.14 646.20 2";

    // first one is done separately to extract last character
    // for comparisons (for next iterations)
    char lastChar = lines[0].charAt(lines[0].length()-1);
    lines[0] = lines[0].substring(0, lines[0].length()-2);

    // start from index 1 since index 0 was already processed
    for(int i=1;i<lines.length; i++){
        // get last character
        char tmp = lines[i].charAt(lines[i].length()-1);

        // remove last character
        lines[i] = lines[i].substring(0, lines[i].length()-2);

        // if last character from this line isn't the same like
        // the last character from previous line, add S
        if(tmp != lastChar)
            lines[i] = "S " + lines[i];

        // update lastChar for comparison
        lastChar = tmp;
    }

    for(int i=0;i<lines.length;i++)
        System.out.println(lines[i]);
}
</code>```

Output:

```<code>812.12 135.14 646.17
812.12 135.14 646.18
S 812.12 135.14 646.19
812.12 135.14 646.20
</code>```

Or if you wish to have a function that takes String[] and modifies it:

```<code>static void updateLines(String[] lines){
    // first one is done separately to extract last character
    // for comparisons (for next iterations)
    char lastChar = lines[0].charAt(lines[0].length()-1);
    lines[0] = lines[0].substring(0, lines[0].length()-2);

    // start from index 1 since index 0 was already processed
    for(int i=1;i<lines.length; i++){
        // get last character
        char tmp = lines[i].charAt(lines[i].length()-1);

        // remove last character
        lines[i] = lines[i].substring(0, lines[i].length()-2);

        // if last character from this line isn't the same like
        // the last character from previous line, add S
        if(tmp != lastChar)
            lines[i] = "S " + lines[i];

        // update lastChar for comparison
        lastChar = tmp;
    }
}

public static void main(String[] args) {
    String[] lines = new String[4];
    lines[0] = "812.12 135.14 646.17 1";
    lines[1] = "812.12 135.14 646.18 1";
    lines[2] = "812.12 135.14 646.19 2";
    lines[3] = "812.12 135.14 646.20 2";

    updateLines(lines);

    for(int i=0;i<lines.length;i++)
        System.out.println(lines[i]);
}
</code>```

Output:

```<code>812.12 135.14 646.17
812.12 135.14 646.18
S 812.12 135.14 646.19
812.12 135.14 646.20
</code>```

Body:
I have 4 lines:

812.12 135.14 646.17 1
812.12 135.14 646.18 1
812.12 135.14 646.19 2
812.12 135.14 646.20 2

I want to remove the last character of each line. Moreover, if the last character changes from previous line, S will be added in the front. For example, given the input above, the third line's last character is 2 which is different from 1 that terminates the second line. Therefore, S will be added in the front as shown below.

Desired output:

812.12 135.14 646.17
812.12 135.14 646.18
S 812.12 135.14 646.19
812.12 135.14 646.20

I have this piece of code to start:

while(lines[0].charAt(lines[0].length()-1)==lines[1].charAt(lines[1].length()-1)){
    continue;
}

Body:
This code would work:

public static void main(String[] args) {
    String[] lines = new String[4];
    lines[0] = "812.12 135.14 646.17 1";
    lines[1] = "812.12 135.14 646.18 1";
    lines[2] = "812.12 135.14 646.19 2";
    lines[3] = "812.12 135.14 646.20 2";

    // first one is done separately to extract last character
    // for comparisons (for next iterations)
    char lastChar = lines[0].charAt(lines[0].length()-1);
    lines[0] = lines[0].substring(0, lines[0].length()-2);

    // start from index 1 since index 0 was already processed
    for(int i=1;i<lines.length; i++){
        // get last character
        char tmp = lines[i].charAt(lines[i].length()-1);

        // remove last character
        lines[i] = lines[i].substring(0, lines[i].length()-2);

        // if last character from this line isn't the same like
        // the last character from previous line, add S
        if(tmp != lastChar)
            lines[i] = "S " + lines[i];

        // update lastChar for comparison
        lastChar = tmp;
    }

    for(int i=0;i<lines.length;i++)
        System.out.println(lines[i]);
}

Output:

812.12 135.14 646.17
812.12 135.14 646.18
S 812.12 135.14 646.19
812.12 135.14 646.20

Or if you wish to have a function that takes String[] and modifies it:

static void updateLines(String[] lines){
    // first one is done separately to extract last character
    // for comparisons (for next iterations)
    char lastChar = lines[0].charAt(lines[0].length()-1);
    lines[0] = lines[0].substring(0, lines[0].length()-2);

    // start from index 1 since index 0 was already processed
    for(int i=1;i<lines.length; i++){
        // get last character
        char tmp = lines[i].charAt(lines[i].length()-1);

        // remove last character
        lines[i] = lines[i].substring(0, lines[i].length()-2);

        // if last character from this line isn't the same like
        // the last character from previous line, add S
        if(tmp != lastChar)
            lines[i] = "S " + lines[i];

        // update lastChar for comparison
        lastChar = tmp;
    }
}

public static void main(String[] args) {
    String[] lines = new String[4];
    lines[0] = "812.12 135.14 646.17 1";
    lines[1] = "812.12 135.14 646.18 1";
    lines[2] = "812.12 135.14 646.19 2";
    lines[3] = "812.12 135.14 646.20 2";

    updateLines(lines);

    for(int i=0;i<lines.length;i++)
        System.out.println(lines[i]);
}

Output:

812.12 135.14 646.17
812.12 135.14 646.18
S 812.12 135.14 646.19
812.12 135.14 646.20


问:
How to convert BGRA to RGBA in Xamarin.iOS?
I am using AVFoundation to get real-time frames from camera and display to the UrhoSharp.

However, seems the Texture2D in UrhoSharp is not support the BGRA from AVVideoOutput. So I want to convert the "CVPixelBuffer" to RGB format.

I found there is an API in vImage "vImagePermuteChannels_ARGB8888", which can convert the BGRA to ARGB but this is not provided by Xamarin.

So how to solve this problem?

答:
The Accelerate.framework consists of C functions, so:

```<code>vImage_Error vImagePermuteChannels_ARGB8888(    const vImage_Buffer *src,
                                                const vImage_Buffer *dest,
                                                const uint8_t       permuteMap[4],
                                                vImage_Flags        flags )     VIMAGE_NON_NULL(1,2,3)  __OSX_AVAILABLE_STARTING( __MAC_10_4, __IPHONE_5_0 );
</code>```

Can be used via:

```<code>[DllImport("/System/Library/Frameworks/Accelerate.framework/Frameworks/vImage.framework/vImage")]
public unsafe static extern vImageError vImagePermuteChannels_ARGB8888(ref vImageBuffer src, ref vImageBuffer dest, [MarshalAs(UnmanagedType.LPArray)]uint[] permuteMap, vImageFlags flags);
</code>```

Ref: https://developer.apple.com/documentation/accelerate/1533241-vimagepermutechannels_argb8888

Ref: Conversion.h

/Applications/Xcode9.1.app/Contents/Developer/Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS.sdk/System/Library/Frameworks/Accelerate.framework/Frameworks/vImage.framework/Headers

Body:
The Accelerate.framework consists of C functions, so:

vImage_Error vImagePermuteChannels_ARGB8888(    const vImage_Buffer *src,
                                                const vImage_Buffer *dest,
                                                const uint8_t       permuteMap[4],
                                                vImage_Flags        flags )     VIMAGE_NON_NULL(1,2,3)  __OSX_AVAILABLE_STARTING( __MAC_10_4, __IPHONE_5_0 );

Can be used via:

[DllImport("/System/Library/Frameworks/Accelerate.framework/Frameworks/vImage.framework/vImage")]
public unsafe static extern vImageError vImagePermuteChannels_ARGB8888(ref vImageBuffer src, ref vImageBuffer dest, [MarshalAs(UnmanagedType.LPArray)]uint[] permuteMap, vImageFlags flags);

Ref: https://developer.apple.com/documentation/accelerate/1533241-vimagepermutechannels_argb8888

Ref: Conversion.h

/Applications/Xcode9.1.app/Contents/Developer/Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS.sdk/System/Library/Frameworks/Accelerate.framework/Frameworks/vImage.framework/Headers