问:
Highlight first character of every line using css or JS
I have requirement to highlight first character in each and every line, as example image below, all the content is in single paragraph, based on resolution change also it should behave same,

I have tried with flex box, and first child using script also, I could not able to find solution

Any help will be appreciated.

答:
Easy way

An easy way to achieve this results is to split("\n") to get all lines, then replace the first letter of each line with itself, wrapped in a  with an appropriate class and finally join("
") the lines and place them inside their original parent element.

var lines = document.querySelector("p").innerHTML.split("\n");
for(var key in lines)
 lines[key] = "" + lines[key].substr(0, 1) + "" + lines[key].substr(1);
document.querySelector("p").innerHTML = lines.join("
");```
<pre class="snippet-code-css lang-css prettyprint-override"><code>span.first-letter {
  font-weight: bold;
  color: red;
}</code>```

This is a line
This is another line
This is yet another line
```
</div>
</div>
</p>

<h2>Alternate (semantically correct) way</h2>

<p>Another option is to <code>split("\n")</code> as before, but actually replace each line with itself wrapped in a <code><p></code> tag. Then <code>join()</code> the lines and replace the original parent with the lines themselves. This makes use of the <code>::first-letter</code> CSS pseudo-element to style these classes and is more semantically correct than the previous one.</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>var lines = document.querySelector("p").innerHTML.split("\n");
for(var key in lines)
 lines[key] = "<p>" + lines[key] + "</p>";
document.querySelector("p").outerHTML = lines.join("");</code>```

p::first-letter {
  font-weight: bold;
  color: red;
}
/* This is a quick fix to make paragraphs display same as if the were all part of the same one, alter this based on your page's style and your needs. */
p + p {
  margin-top: -16px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><p>This is a line
This is another line
This is yet another line</p></code>```

Body:
Easy way

An easy way to achieve this results is to split("\n") to get all lines, then replace the first letter of each line with itself, wrapped in a <span> with an appropriate class and finally join("<br/>") the lines and place them inside their original parent element.

var lines = document.querySelector("p").innerHTML.split("\n");
for(var key in lines)
 lines[key] = "<span class='first-letter'>" + lines[key].substr(0, 1) + "</span>" + lines[key].substr(1);
document.querySelector("p").innerHTML = lines.join("<br/>");

span.first-letter {
  font-weight: bold;
  color: red;
}

<p>This is a line
This is another line
This is yet another line</p>

Alternate (semantically correct) way

Another option is to split("\n") as before, but actually replace each line with itself wrapped in a <p> tag. Then join() the lines and replace the original parent with the lines themselves. This makes use of the ::first-letter CSS pseudo-element to style these classes and is more semantically correct than the previous one.

var lines = document.querySelector("p").innerHTML.split("\n");
for(var key in lines)
 lines[key] = "<p>" + lines[key] + "</p>";
document.querySelector("p").outerHTML = lines.join("");

p::first-letter {
  font-weight: bold;
  color: red;
}
/* This is a quick fix to make paragraphs display same as if the were all part of the same one, alter this based on your page's style and your needs. */
p + p {
  margin-top: -16px;
}

<p>This is a line
This is another line
This is yet another line</p>


来源: stackexchange

问:
ASP.Net Core Identity - Unable to stay logged in for more than 20 mintues - IIS 7.5
After deploying an ASP.Net Core app using Identity to Windows 2008 R2 (IIS 7.5) I cannot stay logged in after about 20 minutes of inactivity. I'm only using simple username / password authentication, no third party stuff.

This is not an issue on my Dev machine running VS 2017.

AccountController.cs

```<code>    public async Task<IActionResult> Login(LoginViewModel model, string returnUrl = null)
    {
        ViewData["ReturnUrl"] = returnUrl;
        if (ModelState.IsValid)
        {
            var result = await _signInManager.PasswordSignInAsync(model.Email, model.Password, true, lockoutOnFailure: false);
            if (result.Succeeded)
            {
                _logger.LogInformation(1, "User logged in.");
                return RedirectToLocal(returnUrl);
            }
            if (result.RequiresTwoFactor)
            {
                return RedirectToAction(nameof(SendCode), new { ReturnUrl = returnUrl, RememberMe = model.RememberMe });
            }
            if (result.IsLockedOut)
            {
                _logger.LogWarning(2, "User account locked out.");
                return View("Lockout");
            }
            else
            {
                ModelState.AddModelError(string.Empty, "Invalid login attempt.");
                return View(model);
            }
        }

        return View(model);
    }
</code>```

Any help kindly appreciated.

EDIT
Here is my ConfigureServices method in it's entirety. It has an authorization policy which could be relevant.

```<code>        public void ConfigureServices(IServiceCollection services)
    {
        // Add framework services.
        services.AddDbContext<ApplicationDbContext>(options =>
            options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));

        services.AddIdentity<ApplicationUser, ApplicationRole>()
            .AddEntityFrameworkStores<ApplicationDbContext>()
            .AddDefaultTokenProviders();

        services.AddAuthorization(options =>
        {
            options.AddPolicy("UserOnly", policy => policy.RequireRole("User"));
            options.AddPolicy("InstructorOnly", policy => policy.RequireRole("Instructor"));
            options.AddPolicy("AdminOnly", policy => policy.RequireRole("Admin"));
            options.AddPolicy("SystemManagerOnly", policy => policy.RequireRole("Manager"));

        });

        services.AddMvc(config =>
        {
            var policy = new AuthorizationPolicyBuilder()
                             .RequireAuthenticatedUser()
                             .Build();
            config.Filters.Add(new AuthorizeFilter(policy));
        });

        // Add application services.
        services.AddTransient<IEmailSender, AuthMessageSender>();
        services.AddTransient<ISmsSender, AuthMessageSender>();

        // Configure Identity
        services.Configure<IdentityOptions>(options =>
        {
            // Password settings
            options.Password.RequireDigit = true;
            options.Password.RequiredLength = 8;
            options.Password.RequireNonAlphanumeric = false;
            options.Password.RequireUppercase = false;
            options.Password.RequireLowercase = false;

            // Lockout settings
            options.Lockout.DefaultLockoutTimeSpan = TimeSpan.FromMinutes(240);
            options.Lockout.MaxFailedAccessAttempts = 10;

            // Cookie settings
            options.Cookies.ApplicationCookie.ExpireTimeSpan = TimeSpan.FromDays(15);
            options.Cookies.ApplicationCookie.LoginPath = "/Account/LogIn";
            options.Cookies.ApplicationCookie.LogoutPath = "/Account/LogOff";
            options.Cookies.ApplicationCookie.SlidingExpiration = true;

            // User settings
            options.User.RequireUniqueEmail = true;

        });

        var appSettings = Configuration.GetSection("AppSettings");
        services.Configure<AppSettings>(appSettings);

        // Inject the ability to get current user
        services.AddTransient<IHttpContextAccessor, HttpContextAccessor>();
        // Inject the User access class
        services.AddTransient<UserResolverService>();

    }
</code>```

Here is a screenshot of Chrome Dev Tools showing the response/request cookie. The Login page seems to send the correct cookie with a an expiration 15 days into the future. Subsequent pages are called using this cookie.

答:
For some very strange reason I'm not seeing this problem anymore.

The only change I made to either config or code was configuring the IIS version log to enable cs(Cookie).

Thank for your assistance @Rohith Rajan

ContentLicense: CC BY-SA 3.0

Body:
After deploying an ASP.Net Core app using Identity to Windows 2008 R2 (IIS 7.5) I cannot stay logged in after about 20 minutes of inactivity. I'm only using simple username / password authentication, no third party stuff.

This is not an issue on my Dev machine running VS 2017.

AccountController.cs

    public async Task<IActionResult> Login(LoginViewModel model, string returnUrl = null)
    {
        ViewData["ReturnUrl"] = returnUrl;
        if (ModelState.IsValid)
        {
            var result = await _signInManager.PasswordSignInAsync(model.Email, model.Password, true, lockoutOnFailure: false);
            if (result.Succeeded)
            {
                _logger.LogInformation(1, "User logged in.");
                return RedirectToLocal(returnUrl);
            }
            if (result.RequiresTwoFactor)
            {
                return RedirectToAction(nameof(SendCode), new { ReturnUrl = returnUrl, RememberMe = model.RememberMe });
            }
            if (result.IsLockedOut)
            {
                _logger.LogWarning(2, "User account locked out.");
                return View("Lockout");
            }
            else
            {
                ModelState.AddModelError(string.Empty, "Invalid login attempt.");
                return View(model);
            }
        }

        return View(model);
    }

Any help kindly appreciated.

EDIT
Here is my ConfigureServices method in it's entirety. It has an authorization policy which could be relevant.

        public void ConfigureServices(IServiceCollection services)
    {
        // Add framework services.
        services.AddDbContext<ApplicationDbContext>(options =>
            options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));

        services.AddIdentity<ApplicationUser, ApplicationRole>()
            .AddEntityFrameworkStores<ApplicationDbContext>()
            .AddDefaultTokenProviders();

        services.AddAuthorization(options =>
        {
            options.AddPolicy("UserOnly", policy => policy.RequireRole("User"));
            options.AddPolicy("InstructorOnly", policy => policy.RequireRole("Instructor"));
            options.AddPolicy("AdminOnly", policy => policy.RequireRole("Admin"));
            options.AddPolicy("SystemManagerOnly", policy => policy.RequireRole("Manager"));

        });

        services.AddMvc(config =>
        {
            var policy = new AuthorizationPolicyBuilder()
                             .RequireAuthenticatedUser()
                             .Build();
            config.Filters.Add(new AuthorizeFilter(policy));
        });

        // Add application services.
        services.AddTransient<IEmailSender, AuthMessageSender>();
        services.AddTransient<ISmsSender, AuthMessageSender>();

        // Configure Identity
        services.Configure<IdentityOptions>(options =>
        {
            // Password settings
            options.Password.RequireDigit = true;
            options.Password.RequiredLength = 8;
            options.Password.RequireNonAlphanumeric = false;
            options.Password.RequireUppercase = false;
            options.Password.RequireLowercase = false;

            // Lockout settings
            options.Lockout.DefaultLockoutTimeSpan = TimeSpan.FromMinutes(240);
            options.Lockout.MaxFailedAccessAttempts = 10;

            // Cookie settings
            options.Cookies.ApplicationCookie.ExpireTimeSpan = TimeSpan.FromDays(15);
            options.Cookies.ApplicationCookie.LoginPath = "/Account/LogIn";
            options.Cookies.ApplicationCookie.LogoutPath = "/Account/LogOff";
            options.Cookies.ApplicationCookie.SlidingExpiration = true;

            // User settings
            options.User.RequireUniqueEmail = true;

        });

        var appSettings = Configuration.GetSection("AppSettings");
        services.Configure<AppSettings>(appSettings);

        // Inject the ability to get current user
        services.AddTransient<IHttpContextAccessor, HttpContextAccessor>();
        // Inject the User access class
        services.AddTransient<UserResolverService>();

    }

Here is a screenshot of Chrome Dev Tools showing the response/request cookie. The Login page seems to send the correct cookie with a an expiration 15 days into the future. Subsequent pages are called using this cookie.


问:
Easy to use graph system for python, to post results on a web page
I would like to generate a pretty graph to show it at meetings; since most of the time, we have people that are not necessarily able to get the picture just looking at numbers.

I did create a simple website where to post these results, and I am saving the output from my tool, as CSV. Posting it on a web page is easy, since the output is read directly from the web server, and it display it as text.

But I would like to make a graph, and so far I did find solutions that require to create a web app; which is not necessarily something that I would like to pursue at this time (not much time available).

Is there an easy way to generate graphs from CSV files, and post it in a way that a simple apache server can read it and display it? I was thinking to use excel, since there are tools for Python that allow worksheet to be read, so I assume there is a way to do the opposite (create worksheet from data and make a graph). In the worst case, I was planning to make PNG of the graphs and post them as images; although it does not feel like something that is sustainable.

答: I have just released a wrapper library pyexcel-pygal, with which you can plot csv in svg format easily. I believe you will be interested in these examples.</p>


问:
CKEditor and ASP.Net MVC 3 RequiredAttribute
I've integrated CKEditor 3 (formerly FCKEditor) into my asp.net MVC (v3 to be specific) application. I have a RequiredAttribute in my model for the field that needs the editor but the client side validation doesn't work correctly with CKEditor. When I try to submit and I've entered data into CKEditor the required validation doesn't see the data. If I try resubmitting again, then it works. I've looked around online and can't find a solution. I am also using Jquery and using the Jquery adapter

http://docs.cksource.com/CKEditor_3.x/Developers_Guide/jQuery_Adapter

答:
I also tried to use CKEditor but with no luck. I've been using CLEditor instead (along with the required attribute) and it works fine for me.

Ever thought of trying this instead?

ContentLicense: CC BY-SA 2.5


问:
Difference between ByteBuffer.allocateDirect() and glGenBuffers()
What is difference between ByteBuffer.allocateDirect() and glGenBuffers()? Why we use on android ByteBuffer.allocateDirect() instead of glGenBuffers() like in classic OpenGL?

答:
But why in every basic OpenGL Tutorial for rendering triangle is used OpenGL object and in every Android OpenGL ES tutorial for rendering triangle is used java object instead of OpenGL object?

Because they can.

ByteBuffer represents a CPU memory allocation. An OpenGL buffer object represents a GPU-accessible memory allocation.

OpenGL ES 2.0 allows users to specify vertex data from either CPU memory or buffer objects. Desktop core OpenGL removed this ability since 2009. So modern desktop OpenGL tutorials use buffer objects for vertex data.

Note that ES 3.0 explicitly says that "client-side vertex arrays":

are  present  to  maintain  backward  compatibility  with OpenGL ES 2.0, but their use in not recommended as it is likely for these features to be removed in a future version.

They haven't been removed yet. But they do interfere with a number of features. For example, they make gl_VertexID undefined.

So you should never use ByteBuffer directly for vertex arrays. And you should avoid learning materials that do so, as they may teach you other bad practices.


问:
how to retrieve the bill list from xero api
I am working on xero-api and have successfully retrieved the invoice, contact and payment from the api. But am unable to list out the list out bills from the api.</p>

答:
Bills are also retrieved from the Invoices endpoint so you might be already retrieving them. Bills have a Type of ACCPAY and sales invoices have a type of ACCREC.

So you could make a request like GET /Invoices?where=Type=="ACCPAY" to retrieve only the Bills.


问:
How do I make my application using Mongodb and nodejs HIPAA compliant?
I am writing an application to be used potentially by doctors to keep in notes about patients (my app is not targeted for doctors but other professions don't need such strict rules).

My app is written in nodejs and only the backend can access the database with an authenticated user account and following all common security practices such as firewall rules etc.

I read about HIPAA compliance but most of them don't apply because no user specifically has access to the database unless it's coming from the API of the backend for which of course you need to authenticate against my app with SSL.

How can I be confident that doctors can use my app? Is there any authentication test/certificate etc?

答:
The mongodb website has a great example of Hippa compliance standard,I think the following will help you:
https://www.mongodb.com/blog/post/making-hipaa-compliant-applications-mongodb</p>


问:
excel vba copy value from a column and paste value in a cell
I have data like below. First column belongs to column A and second column belongs to column B.

```<code>1   q
1   q
2   q
2   q
2   q
3   q
</code>```

I would like to insert empty rows whenever values in column A change. To insert rows I am using the macro from this site.

```<code>'select column a before running the macro
Sub InsertRowsAtValueChange()
'Update 20140716
Dim Rng As Range
Dim WorkRng As Range
On Error Resume Next
xTitleId = "KutoolsforExcel"
Set WorkRng = Application.Selection
Set WorkRng = Application.InputBox("Range", xTitleId, WorkRng.Address, Type:=8)

Application.ScreenUpdating = False
For i = WorkRng.Rows.Count To 2 Step -1
    If WorkRng.Cells(i, 1).Value <> WorkRng.Cells(i - 1, 1).Value Then
        WorkRng.Cells(i, 1).EntireRow.Insert
    End If
Next
Application.ScreenUpdating = True
End Sub
</code>```

After that I would like to copy each set of values from column A and paste in a cell in column C. While pasting them, I would like to paste values in a cell in a row format (by concatenating them) and separating them by a space. In below case, cells c1 should have 1 1, cell c4 should have 2 2 2 and cell c8 should have 3

How to do this? I tried to record macro using first copying each set of values then pasting them after transposing into a row. But I am having hard time copying values again and pasting them within a single cell

答:
I have this function that works like the built-in Concatenate(), but gives you filtering abilities. I doesn't seem to fully help you might give you another approach to your ultimate goal.

```<code>Function ConcatenateIf(CriteriaRange As Range, Condition As Variant, _
        ConcatenateRange As Range, Optional Separator As String = ",") As Variant
    Dim i As Long
    Dim strResult As String
    On Error GoTo ErrHandler
    If CriteriaRange.Count <> ConcatenateRange.Count Then
        ConcatenateIf = CVErr(xlErrRef)
        Exit Function
    End If
    For i = 1 To CriteriaRange.Count
        If CriteriaRange.Cells(i).Value = Condition Then
            strResult = strResult & Separator & ConcatenateRange.Cells(i).Value
        End If
    Next i
    If strResult <> "" Then
        strResult = Mid(strResult, Len(Separator) + 1)
    End If
    ConcatenateIf = strResult
    Exit Function
ErrHandler:
    ConcatenateIf = CVErr(xlErrValue)
End Function
</code>```

Body:
I have data like below. First column belongs to column A and second column belongs to column B.

1   q
1   q
2   q
2   q
2   q
3   q

I would like to insert empty rows whenever values in column A change. To insert rows I am using the macro from this site.

'select column a before running the macro
Sub InsertRowsAtValueChange()
'Update 20140716
Dim Rng As Range
Dim WorkRng As Range
On Error Resume Next
xTitleId = "KutoolsforExcel"
Set WorkRng = Application.Selection
Set WorkRng = Application.InputBox("Range", xTitleId, WorkRng.Address, Type:=8)

Application.ScreenUpdating = False
For i = WorkRng.Rows.Count To 2 Step -1
    If WorkRng.Cells(i, 1).Value <> WorkRng.Cells(i - 1, 1).Value Then
        WorkRng.Cells(i, 1).EntireRow.Insert
    End If
Next
Application.ScreenUpdating = True
End Sub

After that I would like to copy each set of values from column A and paste in a cell in column C. While pasting them, I would like to paste values in a cell in a row format (by concatenating them) and separating them by a space. In below case, cells c1 should have 1 1, cell c4 should have 2 2 2 and cell c8 should have 3

How to do this? I tried to record macro using first copying each set of values then pasting them after transposing into a row. But I am having hard time copying values again and pasting them within a single cell

Body:
I have this function that works like the built-in Concatenate(), but gives you filtering abilities. I doesn't seem to fully help you might give you another approach to your ultimate goal.

Function ConcatenateIf(CriteriaRange As Range, Condition As Variant, _
        ConcatenateRange As Range, Optional Separator As String = ",") As Variant
    Dim i As Long
    Dim strResult As String
    On Error GoTo ErrHandler
    If CriteriaRange.Count <> ConcatenateRange.Count Then
        ConcatenateIf = CVErr(xlErrRef)
        Exit Function
    End If
    For i = 1 To CriteriaRange.Count
        If CriteriaRange.Cells(i).Value = Condition Then
            strResult = strResult & Separator & ConcatenateRange.Cells(i).Value
        End If
    Next i
    If strResult <> "" Then
        strResult = Mid(strResult, Len(Separator) + 1)
    End If
    ConcatenateIf = strResult
    Exit Function
ErrHandler:
    ConcatenateIf = CVErr(xlErrValue)
End Function


问:
Validate input inside a ngFor using template driven forms
In our Angular form (we are using template driven forms) we have a list of input fields which are rendered dynamically, as so, we need to validate then. Following this: Using template driven form with dynamic input list (ngFor) I didn't come any further as it seems to be outdated, as the plunkr sample is not working.

that is our tbody which renders our list:

```<code>  <tbody>
    <tr *ngFor="let item of items; let i=index">
      <td><span>{{ item.categoryName }}</span></td>
      <td class="text-right">
        <input *ngIf="editMode"
          type="number"
          tabindex="1"
          autocomplete="off"
          [(ngModel)]="item.value" name="value-{{item.categoryId}}" #value="ngModel"
          required
        />
        {{value.valid}} <!--As I'm using ngForm I was expecting to receive false or true here-->
        <span *ngIf="!editMode">{{ item.value }}</span>
      </td>
      <td>
        <app-status [status]="item.status"></app-status>
      </td>
    </tr>
  </tbody>
</code>```

This works fine, the list  can be seen, but the validation does not work.

if I try: {{value.valid}} I get the following error:

ERROR TypeError: Cannot read property 'valid' of undefined

Means, my instance of ngModel did't work.

What am I missing?

答:
Where are you trying to do {{value.valid}}? I don't see that here so I don't know what would be causing a null definition of value.

Rather than using an attribute of value, you could have a function in your component that does the validation check for you.

```<code><tr *ngFor="let item of items; let i = index">
  <!-- somewhere in your code -->
  <div *ngIf="myValidationFunction(value)">
    <!-- stuff -->
  </div>
</code>```

Then in your ts file, you could have something that does a check on it. If it is always required, it's pretty simple to do.

```<code>myValidationFunction(value) {
    if (value) {
        // results to 'true' if value isn't null
        return value.valid; // where valid is some field in value
    }
    else { // if value is null, you can say that it is wrong
        return false; // this means that it will not be valid until it's defined
    }
</code>```

Body:
In our Angular form (we are using template driven forms) we have a list of input fields which are rendered dynamically, as so, we need to validate then. Following this: Using template driven form with dynamic input list (ngFor) I didn't come any further as it seems to be outdated, as the plunkr sample is not working.

that is our tbody which renders our list:

      {{ item.categoryName }}

        <input *ngIf="editMode"
          type="number"
          tabindex="1"
          autocomplete="off"
          [(ngModel)]="item.value" name="value-{{item.categoryId}}" #value="ngModel"
          required
        />
        {{value.valid}}
        {{ item.value }}

        <app-status [status]="item.status"></app-status>

This works fine, the list  can be seen, but the validation does not work.

if I try: {{value.valid}} I get the following error:

ERROR TypeError: Cannot read property 'valid' of undefined

Means, my instance of ngModel did't work.

What am I missing?

Body:
Where are you trying to do {{value.valid}}? I don't see that here so I don't know what would be causing a null definition of value.

Rather than using an attribute of value, you could have a function in your component that does the validation check for you.

<tr *ngFor="let item of items; let i = index">
  <!-- somewhere in your code -->
  <div *ngIf="myValidationFunction(value)">
    <!-- stuff -->
  </div>

Then in your ts file, you could have something that does a check on it. If it is always required, it's pretty simple to do.

myValidationFunction(value) {
    if (value) {
        // results to 'true' if value isn't null
        return value.valid; // where valid is some field in value
    }
    else { // if value is null, you can say that it is wrong
        return false; // this means that it will not be valid until it's defined
    }


问:
Spring Data JPA CrudRepository Method name to compare columns?
How do I name a method to find all rows with a condition based on comparing two columns?
For example:

```<code>public class Example {
    Integer num1;
    Integer num2;
}
</code>```

I want to query for all Examples where num1 is less than num2.
What would be the method name?

```<code>public class ExampleDao extends CrudRepository<Example, Integer> {
    List<Example> ???();
}
</code>```

答:
You can't. Use a query like this:</p>

```<code>@Query("SELECT t FROM Example t where t.num1 < t.num2")
List<Example> findNum1IsLessThanNum2();
</code>```

Body:
How do I name a method to find all rows with a condition based on comparing two columns?
For example:

public class Example {
    Integer num1;
    Integer num2;
}

I want to query for all Examples where num1 is less than num2.
What would be the method name?

public class ExampleDao extends CrudRepository<Example, Integer> {
    List<Example> ???();
}

Body:
You can't. Use a query like this:

@Query("SELECT t FROM Example t where t.num1 < t.num2")
List<Example> findNum1IsLessThanNum2();


问:
How can I validate a copy constructor's parameter?
```<code>public class Rectangle {

  int width, height;

  public Rectangle(int width, int height) {
    this.width = width;
    this.height = height;
  }

  public Rectangle(Rectangle source) {
    this(source.width, source.height);
  }
}
</code>```

Let's say I have a class with multiple constructors, one of which is a copy-constructor (to copy an object).

Is there any way I can make check if source is null in the copy-constructor and throw an IllegalArgumentException if it is? Because the other constructor call has to be the first statement in my constructor.

答:
If you're open to alternatives to a copy constructor, a static copy factory would buy you more flexibility:

[...] you are usually better off providing an alternative means [to Cloneable] of object copying. A better approach to object copying is to provide a copy constructor or copy factory. A copy constructor is simply a constructor that takes a single argument whose type is the class containing the constructor [...]

(source: Josh Bloch's Effective Java, 3nd ed., item 13, p65)

```<code>public final class Rectangle {

  private final int width
  private final int height;

  public Rectangle(int width, int height) {
    this.width = width;
    this.height = height;
  }

  public static Rectangle newInstance(Rectangle source) {// <-- copy factory
    if (source == null) {
      throw new IllegalArgumentException("null source");
    }

    return new Rectangle(source.width, source.height);
  }

}
</code>```

Arguably, throwing a NullPointerException would be more idiomatic than throwing an IllegalArgumentException, though.

Body:
public class Rectangle {

  int width, height;

  public Rectangle(int width, int height) {
    this.width = width;
    this.height = height;
  }

  public Rectangle(Rectangle source) {
    this(source.width, source.height);
  }
}

Let's say I have a class with multiple constructors, one of which is a copy-constructor (to copy an object).

Is there any way I can make check if source is null in the copy-constructor and throw an IllegalArgumentException if it is? Because the other constructor call has to be the first statement in my constructor.

Body:
If you're open to alternatives to a copy constructor, a static copy factory would buy you more flexibility:

[...] you are usually better off providing an alternative means [to Cloneable] of object copying. A better approach to object copying is to provide a copy constructor or copy factory. A copy constructor is simply a constructor that takes a single argument whose type is the class containing the constructor [...]

(source: Josh Bloch's Effective Java, 3nd ed., item 13, p65)

public final class Rectangle {

  private final int width
  private final int height;

  public Rectangle(int width, int height) {
    this.width = width;
    this.height = height;
  }

  public static Rectangle newInstance(Rectangle source) {// <-- copy factory
    if (source == null) {
      throw new IllegalArgumentException("null source");
    }

    return new Rectangle(source.width, source.height);
  }

}

Arguably, throwing a NullPointerException would be more idiomatic than throwing an IllegalArgumentException, though.

ContentLicense: CC BY-SA 4.0


问:
How to sort a string using custom compare function in C++?
I need to sort characters of a string and need to have lower letters appear first. For example, "acDbA" would become "abcAD" after sorting.

The code below is what I came up with:

```<code>bool compare(const char& c1, const char& c2) {
    if (c1 >= 'A' && c1 <= 'Z' && c2 >= 'a' && c2 <= 'z') return false;
    if (c2 >= 'A' && c2 <= 'Z' && c1 >= 'a' && c1 <= 'z') return true;
    return c1<c2;
}
void sortLetters(string &letters) {
    sort(letters.begin(), letters.end(), compare);
}
</code>```

However in Visual Studio I got:

```<code>'sort': no matching overloaded function found
'SortLetters::compare': non-standard syntax; use '&' to create a pointer to member
'void std::sort(_RanIt,_RanIt)': expects 2 arguments - 3 provided
</code>```

How should I create custom compare function for sorting a string, I couldn't seem to find examples online with string sorting.

答:
The code below works, only change is the compare member function is now marked "static":   </p>

```<code>class SortLetters {
public:
    static bool compare(const char& c1, const char& c2) {
        if (c1 >= 'A' && c1 <= 'Z' && c2 >= 'a' && c2 <= 'z') return false;
        if (c2 >= 'A' && c2 <= 'Z' && c1 >= 'a' && c1 <= 'z') return true;
        return c1<c2;
    }
    void sortLetters(string &letters) {
        sort(letters.begin(), letters.end(), compare);
    }
};
</code>```

Body:
I need to sort characters of a string and need to have lower letters appear first. For example, "acDbA" would become "abcAD" after sorting.

The code below is what I came up with:

bool compare(const char& c1, const char& c2) {
    if (c1 >= 'A' && c1 <= 'Z' && c2 >= 'a' && c2 <= 'z') return false;
    if (c2 >= 'A' && c2 <= 'Z' && c1 >= 'a' && c1 <= 'z') return true;
    return c1<c2;
}
void sortLetters(string &letters) {
    sort(letters.begin(), letters.end(), compare);
}

However in Visual Studio I got:

'sort': no matching overloaded function found
'SortLetters::compare': non-standard syntax; use '&' to create a pointer to member
'void std::sort(_RanIt,_RanIt)': expects 2 arguments - 3 provided

How should I create custom compare function for sorting a string, I couldn't seem to find examples online with string sorting.

Body:
The code below works, only change is the compare member function is now marked "static":

class SortLetters {
public:
    static bool compare(const char& c1, const char& c2) {
        if (c1 >= 'A' && c1 <= 'Z' && c2 >= 'a' && c2 <= 'z') return false;
        if (c2 >= 'A' && c2 <= 'Z' && c1 >= 'a' && c1 <= 'z') return true;
        return c1<c2;
    }
    void sortLetters(string &letters) {
        sort(letters.begin(), letters.end(), compare);
    }
};


问:
Trouble with parsing PHP in HTML
I have a html page that I'm trying to use php on. I've got
AddType application/x-httpd-php .html  in the .htaccess file like I read I should have. When I try to access the page in a browser, a dialog box appears that asks whether I would like to save the file or open it in a browser. If I choose to open it in a browser, the page comes up without any css, just very basic html. What am I doing wrong?</p>

答:
You need to run apache. And save the files in the server folder made for it.
And then you need to go to localhost/your-file

Apache documentation is your friend here:
https://httpd.apache.org/docs/

Title: Trouble with parsing PHP in HTML


问:
Redshift query to combine result if the data are continous within a table
I have a requirement in redshift where I need to combine result if the data are continuous. I have the following table, where user_id, product_id are varchar and login_time, log_out_time are timestamp.

```<code>user_id    product_id   login_time                log_out_time
----------------------------------------------------------------------
ashok      facebook     1/1/2017 1:00:00 AM       1/1/2017 2:00:00 AM
ashok      facebook     1/1/2017 2:00:00 AM       1/1/2017 3:00:00 AM
ashok      facebook     1/1/2017 3:00:00 AM       1/1/2017 4:00:00 AM
ashok      linked_in    1/1/2017 5:00:00 AM       1/1/2017 6:00:00 AM
ashok      linked_in    1/1/2017 6:00:00 AM       1/1/2017 7:00:00 AM
ashok      facebook     1/1/2017 8:00:00 AM       1/1/2017 9:00:00 AM
ram        facebook     1/1/2017 9:00:00 AM       1/1/2017 10:00:00 AM
ashok      linked_in    1/1/2017 7:00:00 AM       1/1/2017 8:00:00 AM
</code>```

I need to combine the result if the data are continuous for a given user_id for each product. So my output should looks like,

```<code>user_id    product_id   login_time                log_out_time
----------------------------------------------------------------------
ashok      facebook     1/1/2017 1:00:00 AM       1/1/2017 4:00:00 AM
ashok      facebook     1/1/2017 8:00:00 AM       1/1/2017 9:00:00 AM
ashok      linked_in    1/1/2017 5:00:00 AM       1/1/2017 8:00:00 AM
ram        facebook     1/1/2017 9:00:00 AM       1/1/2017 10:00:00 AM
</code>```

I tried with the following query but it doesn't helped me,

```<code>SELECT user_id, product_id, MIN(login_time), MAX(log_out_time) FROM TABLE_NAME GROUP BY user_id, product_id
</code>```

Above query fails to give my required output since it doesn't have the logic to check the data are in continuous time. I need to have a query for this without using any custom function, but I am allowed to use any redshift in-built function.

答:
You can use lag() to identify where groups start, then cumulative sum to identify the groups, then group by to aggregate the results:

```<code>select user_id, product_id, min(login_time), max(log_out_time)
from (select t.*,
             sum(case when prev_lt = login_time then 0 else 1 end) over
                 (partition by user_id, product_id
                  order by login_time
                  rows between unbounded preceding and current row
                 ) as grp
      from (select t.*,
                   lag(log_out_time) over (partition by user_id, product_id order by login_time) as prev_lt
            from t
           ) t
     ) t
group by user_id, product_id, grp;
</code>```

Body:
I have a requirement in redshift where I need to combine result if the data are continuous. I have the following table, where user_id, product_id are varchar and login_time, log_out_time are timestamp.

user_id    product_id   login_time                log_out_time
----------------------------------------------------------------------
ashok      facebook     1/1/2017 1:00:00 AM       1/1/2017 2:00:00 AM
ashok      facebook     1/1/2017 2:00:00 AM       1/1/2017 3:00:00 AM
ashok      facebook     1/1/2017 3:00:00 AM       1/1/2017 4:00:00 AM
ashok      linked_in    1/1/2017 5:00:00 AM       1/1/2017 6:00:00 AM
ashok      linked_in    1/1/2017 6:00:00 AM       1/1/2017 7:00:00 AM
ashok      facebook     1/1/2017 8:00:00 AM       1/1/2017 9:00:00 AM
ram        facebook     1/1/2017 9:00:00 AM       1/1/2017 10:00:00 AM
ashok      linked_in    1/1/2017 7:00:00 AM       1/1/2017 8:00:00 AM

I need to combine the result if the data are continuous for a given user_id for each product. So my output should looks like,

user_id    product_id   login_time                log_out_time
----------------------------------------------------------------------
ashok      facebook     1/1/2017 1:00:00 AM       1/1/2017 4:00:00 AM
ashok      facebook     1/1/2017 8:00:00 AM       1/1/2017 9:00:00 AM
ashok      linked_in    1/1/2017 5:00:00 AM       1/1/2017 8:00:00 AM
ram        facebook     1/1/2017 9:00:00 AM       1/1/2017 10:00:00 AM

I tried with the following query but it doesn't helped me,

SELECT user_id, product_id, MIN(login_time), MAX(log_out_time) FROM TABLE_NAME GROUP BY user_id, product_id

Above query fails to give my required output since it doesn't have the logic to check the data are in continuous time. I need to have a query for this without using any custom function, but I am allowed to use any redshift in-built function.

Body:
You can use lag() to identify where groups start, then cumulative sum to identify the groups, then group by to aggregate the results:

select user_id, product_id, min(login_time), max(log_out_time)
from (select t.*,
             sum(case when prev_lt = login_time then 0 else 1 end) over
                 (partition by user_id, product_id
                  order by login_time
                  rows between unbounded preceding and current row
                 ) as grp
      from (select t.*,
                   lag(log_out_time) over (partition by user_id, product_id order by login_time) as prev_lt
            from t
           ) t
     ) t
group by user_id, product_id, grp;


问:
Blender rescaling rendered images issue
I recently rendered an image in blender. Now, the issue is, when I down scale the image the quality seems to lower as I can identify individual pixels. I'm not entirely sure if this is aliasing (and if it is, it would be nice if someone could explain how this is caused by aliasing) and whether setting anti-aliasing in blender would work. See below:

Before

After

Any help would be appreciated, thanks.

答: Your answer isn't directly related to blender, since you're resizing the image inside microsoft paint, this program manage how the pixels are stored/rendered over screen and in most of the cases, shrinking or increase the resolution of an image, also mean that you're going to lose detail/quality, try another image manipulation program and check the results, there are some algorithms that perform the resampling of an image, each of them performs some mathematical operation over pixel, approximation, multiplication between neighbors pixels and so on. different programs have their different features for this.</p>

Title: Blender rescaling rendered images issue


问:
Retrieving original images after blending two images together
Alright, say I have two images, img1 and img2. Now I create a new image, img3, by blending img1 and img2 one on top of the other. Is it possible to retrieve either img1 or img2 from img3?

I was able to create img3 by blending two uiimages together but I'm at a lost when it comes to separating the original two images from the newly created image. I've tried searching for information on how to achieve this but have hit a wall as I am not quite sure what's the proper term for this process.

I'll appreciate any guidance here as I am completely stumped.

答:
If you are drawing two image using drawInRect and then get image by UIGraphicsGetImageFromCurrentImageContext then the answer is no.

drawInRect:

This method draws the entire image in the current graphics
context, respecting the image’s orientation setting.

This method is drawing the image on top of another by pixel, not creating two layer so that you can get a specific layer later.


问:
Grails additional columns in table or list
I'm trying for several days to receive a list from my Data. The Domain looks like this:

```<code>class Alpha {
    String a
    String b
    etc.
    static hasMany = [beta:Beta]

}

class Beta {
    String a
    Integer foo
    String status
    static belongsTo = [alpha:Alpha]
    static constraints = {
        status(nullable:false, inList:["val1","val2","val3", "val4"])
    }
}
</code>```

I'd like to have in Alpha the sum of all Beta.foo and of all Beta.foo in a certain status. Best would be something like an additional row ( Integer sumVal1 ... ).

I tried named queries:

```<code>static namedQueries = {
        erledigterProbeAufwend {
            createAlias ('Beta', 'b')
            eq ('b.status', 'val1')
            projections {
                groupProperty('b.alpha')
                sum('b.foo', 'sumFooVal1')
            }
        }
}
</code>```

But this just give me one sum at a time.

I'm looking forward to get some help on that.

Greetings
Bas

答:
This could be calculated formula field, but with a subquery trick:</p>

```<code>static mapping = {
    betaCount formula: "(SELECT count(*) FROM Beta b WHERE b.alpha_id = id and b.status in('a', 'b'))"
}
</code>```

Body:
I'm trying for several days to receive a list from my Data. The Domain looks like this:

class Alpha {
    String a
    String b
    etc.
    static hasMany = [beta:Beta]

}

class Beta {
    String a
    Integer foo
    String status
    static belongsTo = [alpha:Alpha]
    static constraints = {
        status(nullable:false, inList:["val1","val2","val3", "val4"])
    }
}

I'd like to have in Alpha the sum of all Beta.foo and of all Beta.foo in a certain status. Best would be something like an additional row ( Integer sumVal1 ... ).

I tried named queries:

static namedQueries = {
        erledigterProbeAufwend {
            createAlias ('Beta', 'b')
            eq ('b.status', 'val1')
            projections {
                groupProperty('b.alpha')
                sum('b.foo', 'sumFooVal1')
            }
        }
}

But this just give me one sum at a time.

I'm looking forward to get some help on that.

Greetings
Bas

Body:
This could be calculated formula field, but with a subquery trick:

static mapping = {
    betaCount formula: "(SELECT count(*) FROM Beta b WHERE b.alpha_id = id and b.status in('a', 'b'))"
}


问:
Why do the functions in std::io::Read take a buffer?
Why do the methods in std::io::Read, namely read_to_end, read_to_string, and read_exact take a buffer rather than returning the result? The current return value is a Result<usize> (or Result<()>), but could that not be made into a tuple instead, also containing the result?

答:
RFC 517 discusses these functions and describes two reasons for why the functions take buffers over returning values:

Performance. When it is known that reading will involve some large number of bytes, the buffer can be preallocated in advance.

"Atomicity" concerns. For read_to_end, it's possible to use this API to retain data collected so far even when a read fails in the middle. For read_to_string, this is not the case, because UTF-8 validity cannot be ensured in such cases; but if intermediate results are wanted, one can use read_to_end and convert to a String only at the end.

For the first point, a string can be pre-allocated using the associated function String::with_capacity. A very similar function exists for vectors: Vec::with_capacity.


问:
how to customise plot title in spatstat
How may I change the plot titles and subtitles when using plot command on linnet object. For example

```<code>library(spatstat)
first = runiflpp(10, as.linnet(chicago), nsim = 2)
plot(first)
</code>```

This code above gives two realisations of a a point process and a plot with the plot command because we requested for nsim=2. But it plots the two realisations with plot title 'simulation 1' and 'simulation 2'.

How can I change the subplot titles for example from simulation 1 to experiment 1?

thank you

答:
The simplest way would be to change the names of the items in the list:

```<code>names(first) <- paste("experiment", 1:2)
</code>```

Alternatively you can change the argument main.panel in plot.solist (see ?plot.solist for all the options):

```<code>plot(first, main.panel = paste("experiment", 1:2))
</code>```

Title: how to customise plot title in spatstat

Body:
How may I change the plot titles and subtitles when using plot command on linnet object. For example

library(spatstat)
first = runiflpp(10, as.linnet(chicago), nsim = 2)
plot(first)

This code above gives two realisations of a a point process and a plot with the plot command because we requested for nsim=2. But it plots the two realisations with plot title 'simulation 1' and 'simulation 2'.

How can I change the subplot titles for example from simulation 1 to experiment 1?

thank you

Body:
The simplest way would be to change the names of the items in the list:

names(first) <- paste("experiment", 1:2)

Alternatively you can change the argument main.panel in plot.solist (see ?plot.solist for all the options):

plot(first, main.panel = paste("experiment", 1:2))


问:
Connect to SQlite (Spiceworks) database from ireports (Jaspersoft)
I'm trying to connect to SQLite db from Jaspersoft ireports. I was able to create a datasource successfully but when I create a report using the datasource it gives me below error message.

java.sql.SQLException: file is encrypted or is not a database

I'm using below JDBC drivers:

```<code>JDBC Driver: org.sqlite.JDBC
JDBC URL: jdbc:sqlite:C:\\Users\\IT\\Desktop\\sqllitejdbc\\spiceworks_prod.sqlite
</code>```

Any help is greatly appreciated.

Thanks.

答:
JDBC Driver: org.sqlite.JDBC
JDBC URL: jdbc:sqlite:C:\Users\IT\Desktop\sqllitejdbc\wwe.sqlite

this is how i gave the Driver and URL but it does not work before that i gave jre file(sqlitejdbc-v056) to the classpath

Body:
I'm trying to connect to SQLite db from Jaspersoft ireports. I was able to create a datasource successfully but when I create a report using the datasource it gives me below error message.

java.sql.SQLException: file is encrypted or is not a database

I'm using below JDBC drivers:

JDBC Driver: org.sqlite.JDBC
JDBC URL: jdbc:sqlite:C:\\Users\\IT\\Desktop\\sqllitejdbc\\spiceworks_prod.sqlite

Any help is greatly appreciated.

Thanks.


问:
Use of max command inside quicksum - gurobi with python
I am trying to include a python "max" command inside a quicksum command using gurobi with python. There is obviously an error with doing so, under LinExpr limitations as it is not accepted.

```<code>shutdowncost = quicksum(quicksum(shutdown_cost[i] * max((v[hour -1, i] - v[hour, i]),0) for i in num_gen) for hour in hour_range)
</code>```

V is a binary variable in the model, while the remainder are fixed variables. The issue is around shutdowncost being negative in the scenario where v[hour - 1, i] is 0, and v[hour, i] is 1.

Is there another command that can be used to replace the max command inside the quicksum?

答:
Here is a paper that talks about startup and shutdown constraints: MIPFormulation.  They use the notation:

u[t] 1 for online, 0 for offline, binary (state)

v[t] 1 for turned on that time period, binary (turn_on)

w[t] 1 for turned off that period, binary (turn_off)

These gurobi binary variables are defined with the constraints:

u[t] - u[t-1] == v[t] - w[t]

v[t] + w[t] <= 1

Then your shutdowncost can be defined:

shutdowncost = quicksum([shutdown_cost[i] * w[hour, i] for i in num_gen for hour in hour_range])

(No need for 2 quicksums!)
This shutdowncost can then be used in your objective function or another constraint. And it is easier to see what is happening.

Body:
I am trying to include a python "max" command inside a quicksum command using gurobi with python. There is obviously an error with doing so, under LinExpr limitations as it is not accepted.

shutdowncost = quicksum(quicksum(shutdown_cost[i] * max((v[hour -1, i] - v[hour, i]),0) for i in num_gen) for hour in hour_range)

V is a binary variable in the model, while the remainder are fixed variables. The issue is around shutdowncost being negative in the scenario where v[hour - 1, i] is 0, and v[hour, i] is 1.

Is there another command that can be used to replace the max command inside the quicksum?


问:
Web.config settings for ASP.NET Core web app as a sub-app within a ASP.NET Core web app?
Have "WebsiteA" trying to host another application "API" within it. Using a folder called "services". From what I've read in order for the sub-app to work I have to move my handlers up to the parent config. So being new to .NET Core I'm sure I'm missing something straightforward but set up the handlers in the parent something like this:

```<code>    <system.webServer>
    <handlers>
      <add name="aspNetCoreAPI" path="services\*" verb="*" modules="AspNetCoreModule" resourceType="Unspecified" />
      <add name="aspNetCore" path="*" verb="*" modules="AspNetCoreModule" resourceType="Unspecified" />

    </handlers>
    <aspNetCore processPath="dotnet" arguments=".\websiteA.dll" stdoutLogEnabled="true" stdoutLogFile=".\logs\stdout" />

    <aspNetCoreAPI processPath="dotnet" arguments=".\services\api.dll" stdoutLogEnabled="true" stdoutLogFile=".\logs\stdout" />

  </system.webServer>
</code>```

Seems that the aspNetCoreAPI tag is a no-no as the application rejects the configuration as malformed.

Ideally how should the web.config be setup in a the sub-application scenario for such an api application?

答:
Yeah so the config approach is completely not right. Keeping the config vanilla in the parent app and making a simple handler exclusion (commented out) in the child application makes the magic happen for configuration issues.

Parent:

```<code><system.webServer>
    <handlers>
      <add name="aspNetCore" path="*" verb="*" modules="AspNetCoreModule" resourceType="Unspecified" />
    </handlers>
    <aspNetCore processPath="dotnet" arguments=".\websiteA.dll" stdoutLogEnabled="true" stdoutLogFile=".\logs\stdout" />
  </system.webServer>
</code>```

Child:

```<code><system.webServer>
    <handlers>
      <!--<add name="aspNetCore" path="*" verb="*" modules="AspNetCoreModule" resourceType="Unspecified" />-->

    </handlers>
    <aspNetCore processPath="dotnet" arguments=".\api.dll" stdoutLogEnabled="true" stdoutLogFile=".\logs\stdout" />
  </system.webServer>
</code>```

They real key is that you need to make a really gross addition to the parent Configure method in the Startup.cs. (https://github.com/aspnet/Hosting/issues/416#issuecomment-149046552)

So I added this at the bottom of the existing logic in the method:

```<code>app.Map("/services", (app1) => this.Configure1(app1, env, loggerFactory));
</code>```

and in the new Configure1 method created I copied the Configure method from my child application:

```<code>public void Configure1(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
        {
            loggerFactory.AddConsole(Configuration.GetSection("Logging"));
            loggerFactory.AddDebug();

            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseExceptionHandler("/Home/Error");
            }

            app.UseStaticFiles();

            app.UseMvc();
        }
</code>```

I don't prefer the child app directory path and sub-application logic in my parent app as it is a tightly leashed coupling that just feels wrong. But that is where things stand right now as I understand.

Body:
Have "WebsiteA" trying to host another application "API" within it. Using a folder called "services". From what I've read in order for the sub-app to work I have to move my handlers up to the parent config. So being new to .NET Core I'm sure I'm missing something straightforward but set up the handlers in the parent something like this:

    <system.webServer>
    <handlers>
      <add name="aspNetCoreAPI" path="services\*" verb="*" modules="AspNetCoreModule" resourceType="Unspecified" />
      <add name="aspNetCore" path="*" verb="*" modules="AspNetCoreModule" resourceType="Unspecified" />

    </handlers>
    <aspNetCore processPath="dotnet" arguments=".\websiteA.dll" stdoutLogEnabled="true" stdoutLogFile=".\logs\stdout" />

    <aspNetCoreAPI processPath="dotnet" arguments=".\services\api.dll" stdoutLogEnabled="true" stdoutLogFile=".\logs\stdout" />

  </system.webServer>

Seems that the aspNetCoreAPI tag is a no-no as the application rejects the configuration as malformed.

Ideally how should the web.config be setup in a the sub-application scenario for such an api application?

Body:
Yeah so the config approach is completely not right. Keeping the config vanilla in the parent app and making a simple handler exclusion (commented out) in the child application makes the magic happen for configuration issues.

Parent:

<system.webServer>
    <handlers>
      <add name="aspNetCore" path="*" verb="*" modules="AspNetCoreModule" resourceType="Unspecified" />
    </handlers>
    <aspNetCore processPath="dotnet" arguments=".\websiteA.dll" stdoutLogEnabled="true" stdoutLogFile=".\logs\stdout" />
  </system.webServer>

Child:

<system.webServer>
    <handlers>
      <!--<add name="aspNetCore" path="*" verb="*" modules="AspNetCoreModule" resourceType="Unspecified" />-->

    </handlers>
    <aspNetCore processPath="dotnet" arguments=".\api.dll" stdoutLogEnabled="true" stdoutLogFile=".\logs\stdout" />
  </system.webServer>

They real key is that you need to make a really gross addition to the parent Configure method in the Startup.cs. (https://github.com/aspnet/Hosting/issues/416#issuecomment-149046552)

So I added this at the bottom of the existing logic in the method:

app.Map("/services", (app1) => this.Configure1(app1, env, loggerFactory));

and in the new Configure1 method created I copied the Configure method from my child application:

public void Configure1(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
        {
            loggerFactory.AddConsole(Configuration.GetSection("Logging"));
            loggerFactory.AddDebug();

            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseExceptionHandler("/Home/Error");
            }

            app.UseStaticFiles();

            app.UseMvc();
        }

I don't prefer the child app directory path and sub-application logic in my parent app as it is a tightly leashed coupling that just feels wrong. But that is where things stand right now as I understand.


问:
Can I debug (step through) code without a main() function?
Assume I want to understand a larger project by just stepping through the code with a debugger. Is it possible to just jump in at an arbitrary point (given I define the correct variables)? How do I debug libraries that don't have a main?</p>

答:
The best way would be to run the application as it is and set a breakpoint whenever you want to look. The thing is that the program might do lot of initialization and other stuff, that you wouldn't be able to figure out.

Another approach would be to look out for unit tests. They are like small programs itself targeting just specific parts of the program.


问:
How to mock an import
Module A includes import B at its top. However under test conditions I'd like to mock B in A (mock A.B) and completely refrain from importing B.

In fact, B isn't installed in the test environment on purpose.

A is the unit under test. I have to import A with all its functionality. B is the module I need to mock. But how can I mock B within A and stop A from importing the real B, if the first thing A does is import B?

(The reason B isn't installed is that I use pypy for quick testing and unfortunately B isn't compatible with pypy yet.)

How could this be done?

答:
I found fine way to mock the imports in Python. It's Eric's Zaadi solution found here which I just use inside my Django application.

I've got class SeatInterface which is interface to Seat model class.
So inside my seat_interface module I have such an import:

```<code>from ..models import Seat

class SeatInterface(object):
    (...)
</code>```

I wanted to create isolated tests for SeatInterface class with mocked Seat class as FakeSeat. The problem was - how tu run tests offline, where Django application is down. I had below error:

ImproperlyConfigured: Requested setting BASE_DIR, but settings are not
  configured. You must either define the environment variable
  DJANGO_SETTINGS_MODULE or call settings.configure() before accessing
  settings.

Ran 1 test in 0.078s

FAILED (errors=1)

The solution was:

```<code>import unittest
from mock import MagicMock, patch

class FakeSeat(object):
    pass

class TestSeatInterface(unittest.TestCase):

    def setUp(self):
        models_mock = MagicMock()
        models_mock.Seat.return_value = FakeSeat
        modules = {'app.app.models': models_mock}
        patch.dict('sys.modules', modules).start()

    def test1(self):
        from app.app.models_interface.seat_interface import SeatInterface
</code>```

And then test magically runs OK :)

.

  Ran 1 test in 0.002s

OK

Title: How to mock an import

Body:
I found fine way to mock the imports in Python. It's Eric's Zaadi solution found here which I just use inside my Django application.

I've got class SeatInterface which is interface to Seat model class.
So inside my seat_interface module I have such an import:

from ..models import Seat

class SeatInterface(object):
    (...)

I wanted to create isolated tests for SeatInterface class with mocked Seat class as FakeSeat. The problem was - how tu run tests offline, where Django application is down. I had below error:

ImproperlyConfigured: Requested setting BASE_DIR, but settings are not
  configured. You must either define the environment variable
  DJANGO_SETTINGS_MODULE or call settings.configure() before accessing
  settings.

Ran 1 test in 0.078s

FAILED (errors=1)

The solution was:

import unittest
from mock import MagicMock, patch

class FakeSeat(object):
    pass

class TestSeatInterface(unittest.TestCase):

    def setUp(self):
        models_mock = MagicMock()
        models_mock.Seat.return_value = FakeSeat
        modules = {'app.app.models': models_mock}
        patch.dict('sys.modules', modules).start()

    def test1(self):
        from app.app.models_interface.seat_interface import SeatInterface

And then test magically runs OK :)

.

  Ran 1 test in 0.002s

OK


问:
a simple person class in objective c
I'm starting to learn objective c, I made a simple person class, i get 6 errors,
expected specifier-qualifier-list before '-' token

just wondering if someone can explain to me what I'm doing wrong,

thanks

```<code>#import <Foundation/Foundation.h>
#import <Foundation/NSObject.h>
#import <Foundation/NSString.h>

@interface Person:NSObject
{
    NSString *firstName;
    NSString *lastName;

    -(void) setFName:(NSString *) theFirstName;
    -(void) setLName:(NSString *) theLastName;
    -(void) printName;
}
@end

@implementation Person
{

    -(void) setFName:(NSString *) theFirstName
    {
        firstName = [[NSString alloc]initWithString: theFirstName];
    }

    -(void) setLName:(NSString *) theLastName
    {
        lastName = [[NSString alloc]initWithString: theLastName];
    }

    -(void) printName
    {
        NSLog(@"The person's full name is",firstName,lastName);
    }

}

@end

int main (int argc, const char * argv[]) {
    NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];

    Person *person = [[Person alloc] init];

    [person setFName:@"Amir"];
    [person setLName:@"Karimian"];
    [person printName];

    [person release];
    [pool drain];
    return 0;
}
</code>```

答:
Or even simpler:</p>

```<code>@interface Person : NSObject

@property (nonatomic, copy) NSString * firstName;
@property (nonatomic, copy) NSString * lastName;

- (NSString *) fullName;

@end

@implementation Person
@synthesize firstName, lastName;

- (NSString *) fullName {
  return [NSString stringWithFormat:@"%@ %@", [self firstName], [self lastName]];
}

- (void) dealloc {
  [self setFirstName:nil];
  [self setLastName:nil];
  [super dealloc];
}

@end
</code>```

Title: a simple person class in objective c

Body:
I'm starting to learn objective c, I made a simple person class, i get 6 errors,
expected specifier-qualifier-list before '-' token

just wondering if someone can explain to me what I'm doing wrong,

thanks

#import <Foundation/Foundation.h>
#import <Foundation/NSObject.h>
#import <Foundation/NSString.h>

@interface Person:NSObject
{
    NSString *firstName;
    NSString *lastName;

    -(void) setFName:(NSString *) theFirstName;
    -(void) setLName:(NSString *) theLastName;
    -(void) printName;
}
@end

@implementation Person
{

    -(void) setFName:(NSString *) theFirstName
    {
        firstName = [[NSString alloc]initWithString: theFirstName];
    }

    -(void) setLName:(NSString *) theLastName
    {
        lastName = [[NSString alloc]initWithString: theLastName];
    }

    -(void) printName
    {
        NSLog(@"The person's full name is",firstName,lastName);
    }

}

@end

int main (int argc, const char * argv[]) {
    NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];

    Person *person = [[Person alloc] init];

    [person setFName:@"Amir"];
    [person setLName:@"Karimian"];
    [person printName];

    [person release];
    [pool drain];
    return 0;
}

Body:
Or even simpler:

@interface Person : NSObject

@property (nonatomic, copy) NSString * firstName;
@property (nonatomic, copy) NSString * lastName;

- (NSString *) fullName;

@end

@implementation Person
@synthesize firstName, lastName;

- (NSString *) fullName {
  return [NSString stringWithFormat:@"%@ %@", [self firstName], [self lastName]];
}

- (void) dealloc {
  [self setFirstName:nil];
  [self setLastName:nil];
  [super dealloc];
}

@end


问:
Remove white space at the top and the bottom in h3
h3 with white space at the top and the bottom

I have some white space around my h3. To align it the same as some pictures I want to delete the white space at the top and the bottom of the h3. The margin is 0, but there is still space between the top and the bottom of the text. How do I solve this?

this is my code:

```<code><html>
 <head>
 </head>
 <body>
  <h3>title</h3>
 </body>
</html>
</code>```

答:
You're confused about what the whitespace is. It's the full line height of the text, which accounts for potential above and below text characters, like accents and dangling letters. If you want to squish this whitespace (not recommended), set the line height to something smaller than the default, like</p>

```<code>line-height: 0.8em;
</code>```

Body:
h3 with white space at the top and the bottom

I have some white space around my h3. To align it the same as some pictures I want to delete the white space at the top and the bottom of the h3. The margin is 0, but there is still space between the top and the bottom of the text. How do I solve this?

this is my code:

title

Body:
You're confused about what the whitespace is. It's the full line height of the text, which accounts for potential above and below text characters, like accents and dangling letters. If you want to squish this whitespace (not recommended), set the line height to something smaller than the default, like

line-height: 0.8em;


答:
Remove the padding of the container element (in your example, the  tag):

```<code>body { padding: 0 }
</code>```

Title: Remove white space at the top and the bottom in h3

Body:
Remove the padding of the container element (in your example, the <body> tag):

body { padding: 0 }


问:
angular 1 compile in angular 2
In angular 1 what we can do is

```<code>var elem = document.getElementById('#someid');
$compile(elem)($scope);
</code>```

and this works like charm. But i'm unable to find equivalent of above in angular 2. I'm really stuck.

To give you overview, i m using a library handsontable which is a javascript library and adds different elements to dom. Now i have element out of angular scope which i now want to include in angular scope

答:
I would suggest you can upgrade to Angular 4 which is most stable version and it have backward compatability.You can use  ComponentFactoryResolver  as an alternative for $compile in Angular 4

https://fromjami.com/2017/06/26/load-components-dynamically-at-runtime-in-angular-4/

https://angular.io/guide/dynamic-component-loader

In your case you can create a component with an html that you want to compile at runtime

Title: angular 1 compile in angular 2

Body:
In angular 1 what we can do is

var elem = document.getElementById('#someid');
$compile(elem)($scope);

and this works like charm. But i'm unable to find equivalent of above in angular 2. I'm really stuck.

To give you overview, i m using a library handsontable which is a javascript library and adds different elements to dom. Now i have element out of angular scope which i now want to include in angular scope


问:
GCloud Compute Engine won't delete or stop. Keeps respawing
I have a google compute VM instance that will not stop or be killed.

I don't know where it came from and I can't delete it or pause it. I don't have anything running on it nor is has anything scheduled with it.

'gke-cluster-1-default-pool-....`

答:
That is a VM from Google Container Engine. In the left menu, navigate to Container Engine and check if you have any clusters created. If a cluster was created and then removed it is possible that the VM did not get cleaned up properly.

In you dashboard, there should be an Activity tab. You can use this to filter the activity on the account to see if someone created a Google Container Engine cluster.


问:
CPP - strlen is not outputting entire length for multiple words [C-Strings Only]
the code below is only outputting the length of the first word that I typed. I thought strlen would give me the length of multiple words, but it doesn't.

For example, the string "hello sir" gives me the output of 5 and not 8. Why is that?

```<code>#include <iostream>
#include <string>

void ReadString(char * c, int maxLength);
void GetStringLength(char * c, int * length);

int main()
{

    int length = 0;
    const int SIZE = 20;
    char cpoint[SIZE];
    char *refC = cpoint;

    ReadString(refC, SIZE);
    GetStringLength(refC, &length);
    system("pause");

}

void ReadString(char * c, int maxLength)
{
    std::cout << "Enter a string " << maxLength << " characters." << std::endl;
    std::cin >> c;

}

void GetStringLength(char * c, int * length)
{
    int sizeOfArray = std::strlen(c);
    *length = sizeOfArray;
    std::cout << sizeOfArray;
}
</code>```

答:
The operator >> after std::cin only gives you the char array that can be found in std::cin until it hits whitespace, use std::getline() instead. This requires you to use std::string instead of a char array.

```<code>std::string input;
std::getline(std::cin, input);
</code>```

Also: "Hello sir" has a length of 9 and is an array with 10 elements.

Body:
the code below is only outputting the length of the first word that I typed. I thought strlen would give me the length of multiple words, but it doesn't.

For example, the string "hello sir" gives me the output of 5 and not 8. Why is that?

#include <iostream>
#include <string>

void ReadString(char * c, int maxLength);
void GetStringLength(char * c, int * length);

int main()
{

    int length = 0;
    const int SIZE = 20;
    char cpoint[SIZE];
    char *refC = cpoint;

    ReadString(refC, SIZE);
    GetStringLength(refC, &length);
    system("pause");

}

void ReadString(char * c, int maxLength)
{
    std::cout << "Enter a string " << maxLength << " characters." << std::endl;
    std::cin >> c;

}

void GetStringLength(char * c, int * length)
{
    int sizeOfArray = std::strlen(c);
    *length = sizeOfArray;
    std::cout << sizeOfArray;
}

Body:
The operator >> after std::cin only gives you the char array that can be found in std::cin until it hits whitespace, use std::getline() instead. This requires you to use std::string instead of a char array.

std::string input;
std::getline(std::cin, input);

Also: "Hello sir" has a length of 9 and is an array with 10 elements.


问:
Constructing a Regular Expression from a Finite Automata
I'm trying to construct a regular expression from a Finite Automaton but found my self completely stuck with this one. The regex to use is like this:

? = 0 or 1

* = 0 or more

+= 1 or more

| = or

_ = empty string

@ = empty set

() = parentheses

As I understand the strings must either be "b*" end with "a*" or end with "a+bb+"

What i have now is ((b*(a+(bb))*)*)
but that doesn't take into account a string ending with 'a'.

As said, I'm 100% stuck with this and just can't get my head around how I am supposed to work with this.

image: http://img593.imageshack.us/img593/2563/28438387.jpg

CODE:

Type of the automaton

FA

States

q1

q2

q3

q4

Alphabet

a

b

Initial state

q3

Final states

q3

q4

Transitions

q1 a q2

q1 b q3

q2 a q2

q2 b q2

q3 a q4

q3 b q3

q4 a q4

q4 b q1

Any solutions or tips appreciated!

答:
It isn't possible to get from q2 to a final state. Remove it and the resulting DFA should be easier to convert.

As I understand the strings must either be "b*" end with "a*" or end with "a+bb+"
  What i have now is ((b*(a+(bb)))) but that doesn't take into account a string ending with 'a'.

Imagine q3 was not a final state, and q4 was the initial state. What would the regex look like then? Changing that into what you want shouldn't be too hard, just don't be afraid to have the same state and/or transitions described by more than one part of the regex.

One more hint: I'm pretty sure you're going to need to use either ? or | at least once.


问:
Error: Can't open display: (null) when using Xclip to copy ssh public key
I’m following in Generating SSH Keys, it says

sudo apt-get install xclip

Downloads and installs xclip. If you don't have apt-get, you might need to use another installer (like yum)

xclip -sel clip < ~/.ssh/id_rsa.pub

Copies the contents of the id_rsa.pub file to your clipboard

But after I runxclip -sel clip < ~/.ssh/id_rsa.pub I get Error: Can't open display: (null)
What is the problem? I googled around but found nothing about it

答:
Based on the date of this question the original poster wouldn't have been using Windows Subsystem for Linux. But if you are, and you get the same error, the following alternative works:

```<code>clip.exe < ~/.ssh/id_rsa.pub
</code>```

Thanks to this page for pointing out Windows' clip.exe (and you have to type the ".exe") can be run from the bash shell.

Body:
Based on the date of this question the original poster wouldn't have been using Windows Subsystem for Linux. But if you are, and you get the same error, the following alternative works:

clip.exe < ~/.ssh/id_rsa.pub

Thanks to this page for pointing out Windows' clip.exe (and you have to type the ".exe") can be run from the bash shell.


问:
Highlight first character of every line using css or JS
I have requirement to highlight first character in each and every line, as example image below, all the content is in single paragraph, based on resolution change also it should behave same,

I have tried with flex box, and first child using script also, I could not able to find solution

Any help will be appreciated.

答:
CSS only responsive solution that uses mix-blend-mode, which is not supported by IE and Edge.

The idea is to use a colored overlay with a fixed width (the largest letter width) and mix-blend-mode: screen; to color only the 1st letter of each line.

You need to use a monospace font, so the color won't spill to the next letter if the 1st letter is narrow.

p {
  position: relative;
  font-family: monospace; /** to have constant character width **/
  font-size: 28px;
  background: white;
}

p::before {
  position: absolute;
  top: 0;
  bottom: 0;
  left: 0;
  z-index: 1;
  background: red;
  mix-blend-mode: screen;
  pointer-events: none; /** to enable selected of the text under the pseudo element **/
  color: transparent; /** to hide the character **/
  content: 'W'; /** a character in your font to use as width **/
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Duis quis euismod orci. Morbi ullamcorper augue ipsum, at consectetur turpis dictum sed. Phasellus bibendum tellus eu aliquet congue. Morbi ultrices aliquam purus, id semper diam aliquet eget. Nulla
  at tellus lacus. Curabitur massa lectus, auctor et lobortis vel, sodales non diam. Pellentesque gravida tortor ac ex porta congue. Ut vestibulum arcu ex, ac lacinia tortor pulvinar id. Nulla sagittis, lectus at luctus dignissim, orci nulla interdum
  ex, at euismod nibh ipsum et lacus. Suspendisse potenti. Quisque ac eros nunc. Suspendisse sit amet dolor diam. Phasellus blandit commodo mi, at aliquam mi facilisis ut. Vestibulum lacinia enim tempor nunc elementum suscipit. Praesent ligula ipsum,
  venenatis et tellus at, imperdiet tempus lectus. Pellentesque consequat magna augue, at vestibulum sem facilisis nec.</p></code>```

Body:
CSS only responsive solution that uses mix-blend-mode, which is not supported by IE and Edge.

The idea is to use a colored overlay with a fixed width (the largest letter width) and mix-blend-mode: screen; to color only the 1st letter of each line.

You need to use a monospace font, so the color won't spill to the next letter if the 1st letter is narrow.

p {
  position: relative;
  font-family: monospace; /** to have constant character width **/
  font-size: 28px;
  background: white;
}

p::before {
  position: absolute;
  top: 0;
  bottom: 0;
  left: 0;
  z-index: 1;
  background: red;
  mix-blend-mode: screen;
  pointer-events: none; /** to enable selected of the text under the pseudo element **/
  color: transparent; /** to hide the character **/
  content: 'W'; /** a character in your font to use as width **/
}

<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Duis quis euismod orci. Morbi ullamcorper augue ipsum, at consectetur turpis dictum sed. Phasellus bibendum tellus eu aliquet congue. Morbi ultrices aliquam purus, id semper diam aliquet eget. Nulla
  at tellus lacus. Curabitur massa lectus, auctor et lobortis vel, sodales non diam. Pellentesque gravida tortor ac ex porta congue. Ut vestibulum arcu ex, ac lacinia tortor pulvinar id. Nulla sagittis, lectus at luctus dignissim, orci nulla interdum
  ex, at euismod nibh ipsum et lacus. Suspendisse potenti. Quisque ac eros nunc. Suspendisse sit amet dolor diam. Phasellus blandit commodo mi, at aliquam mi facilisis ut. Vestibulum lacinia enim tempor nunc elementum suscipit. Praesent ligula ipsum,
  venenatis et tellus at, imperdiet tempus lectus. Pellentesque consequat magna augue, at vestibulum sem facilisis nec.</p>


问:
Why this code is not running in emulator even if i have given all the permission in the code?

TelephonyManagerActivity.java

```<code>package com.lovepurohit.project15;

/**
* Program for telephony manager that means to access the details related
* to sim and phone number like IMEI number, Device type and many more
* <p/>
* For this we use TelephonyManagerActivity class which is in the package
* android.telephony.TelephonyManagerActivity;
*/

import android.content.Context;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;

//importing our new package
import android.telephony.TelephonyManager;

import android.widget.TextView;

/**
* Created by Love on 04-07-2017.
*/
public class TelephonyManagerActivity extends AppCompatActivity {
TextView textView;

@Override

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_manager_telephony);

    //Getting id
    textView = (TextView) findViewById(R.id.textView);

    //Accessing the service for performing operation related to telephony
    TelephonyManager tm = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);

    /**
     * Getting the phone Type
     * whether phone is cdma or gsm
     */
    int type = tm.getPhoneType();

    //Getting other details like IMEI number and device id and etc
    String IMEINumber = tm.getDeviceId();

    //getting subscriber ID
    String subscriberID = tm.getDeviceId();

    //Getting Sim serial number
    String SIMSerialNumber = tm.getSimSerialNumber();

    //Getting network details
    String networkCountryISO = tm.getNetworkCountryIso();

    //Getting sim country info
    String SIMCountryISO = tm.getSimCountryIso();

    //Getting the software on which app is running
    String softwareVersion = tm.getDeviceSoftwareVersion();

    //Getting the voice mail number on which app is running
    String voiceMailNumber = tm.getVoiceMailNumber();

    String strPhoneType = "";
    switch (type) {
        case (TelephonyManager.PHONE_TYPE_CDMA):
            strPhoneType = "CDMA";
            break;

        case (TelephonyManager.PHONE_TYPE_GSM):
            strPhoneType = "GSM";
            break;

        case (TelephonyManager.PHONE_TYPE_NONE):
            strPhoneType = "NONE";
            break;

    }

    boolean isRoaming = tm.isNetworkRoaming();

    String phoneInfo = "Phone Details: \n";
    phoneInfo += "\n IMEI Number: " + IMEINumber;
    phoneInfo += "\n SubscriberID: " + subscriberID;
    phoneInfo += "\n SIM Serial Number: " + SIMSerialNumber;
    phoneInfo += "\n Network Country ISO: " + networkCountryISO;
    phoneInfo += "\n SIMCountryISO: " + SIMCountryISO;
    phoneInfo += "\n SoftwreVersion: " + softwareVersion;
    phoneInfo += "\n VoiceMailNumber: " + voiceMailNumber;
    phoneInfo += "\n Phone Type: " + strPhoneType;
    phoneInfo += "\n Is Roaming? : " + isRoaming;

    textView.setText(phoneInfo);
}
}
</code>```

AndroidManifest.xml

```<code><?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.lovepurohit.project15">

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="adndroid.permission.READ_INTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_PHONE_STATE"/>

<application
    android:allowBackup="true"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:supportsRtl="true"
    android:theme="@style/AppTheme">

    <!-- Activity 25th our project -->
    <activity android:name=".SharedPreferences">
        <!-- <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter> -->
    </activity>

    <!-- Activity 26th of our project -->
    <activity android:name=".InternalStorage">
       <!-- <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter> -->
    </activity>

    <!-- Activity 27th of our project -->
    <activity android:name=".TelephonyManagerActivity">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
</application>

</manifest>
</code>```

Do I have to run it on the real device? I have added all the permission but it is not working in the emulator. And I'm using API 23 that is Marshmallow

答:
You have to ask for  runtime permissons for real devices(see https://developer.android.com/training/permissions/requesting.html?hl=en).
Emulated device haven't got some of things your asking for and might return null, but other things should give you values. For example in my case the emulated device ID return 00000000000 when I run something like:

```<code>TelephonyManager telephonyManager = (TelephonyManager) this.getSystemService(Context.TELEPHONY_SERVICE);
        int duration = Toast.LENGTH_SHORT;

DeviceId = telephonyManager.getDeviceId() ;
String testToastInfo = DeviceId + "\n";

Toast.makeText(this,testToastInfo , duration).show();
</code>```

Hope this help!

Body:
TelephonyManagerActivity.java

package com.lovepurohit.project15;

/**
* Program for telephony manager that means to access the details related
* to sim and phone number like IMEI number, Device type and many more
*

* For this we use TelephonyManagerActivity class which is in the package
* android.telephony.TelephonyManagerActivity;
*/

import android.content.Context;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;

//importing our new package
import android.telephony.TelephonyManager;

import android.widget.TextView;

/**
* Created by Love on 04-07-2017.
*/
public class TelephonyManagerActivity extends AppCompatActivity {
TextView textView;

@Override

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_manager_telephony);

    //Getting id
    textView = (TextView) findViewById(R.id.textView);

    //Accessing the service for performing operation related to telephony
    TelephonyManager tm = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);

    /**
     * Getting the phone Type
     * whether phone is cdma or gsm
     */
    int type = tm.getPhoneType();

    //Getting other details like IMEI number and device id and etc
    String IMEINumber = tm.getDeviceId();

    //getting subscriber ID
    String subscriberID = tm.getDeviceId();

    //Getting Sim serial number
    String SIMSerialNumber = tm.getSimSerialNumber();

    //Getting network details
    String networkCountryISO = tm.getNetworkCountryIso();

    //Getting sim country info
    String SIMCountryISO = tm.getSimCountryIso();

    //Getting the software on which app is running
    String softwareVersion = tm.getDeviceSoftwareVersion();

    //Getting the voice mail number on which app is running
    String voiceMailNumber = tm.getVoiceMailNumber();

    String strPhoneType = "";
    switch (type) {
        case (TelephonyManager.PHONE_TYPE_CDMA):
            strPhoneType = "CDMA";
            break;

        case (TelephonyManager.PHONE_TYPE_GSM):
            strPhoneType = "GSM";
            break;

        case (TelephonyManager.PHONE_TYPE_NONE):
            strPhoneType = "NONE";
            break;

    }

    boolean isRoaming = tm.isNetworkRoaming();

    String phoneInfo = "Phone Details: \n";
    phoneInfo += "\n IMEI Number: " + IMEINumber;
    phoneInfo += "\n SubscriberID: " + subscriberID;
    phoneInfo += "\n SIM Serial Number: " + SIMSerialNumber;
    phoneInfo += "\n Network Country ISO: " + networkCountryISO;
    phoneInfo += "\n SIMCountryISO: " + SIMCountryISO;
    phoneInfo += "\n SoftwreVersion: " + softwareVersion;
    phoneInfo += "\n VoiceMailNumber: " + voiceMailNumber;
    phoneInfo += "\n Phone Type: " + strPhoneType;
    phoneInfo += "\n Is Roaming? : " + isRoaming;

    textView.setText(phoneInfo);
}
}

AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.lovepurohit.project15">

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="adndroid.permission.READ_INTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_PHONE_STATE"/>

<application
    android:allowBackup="true"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:supportsRtl="true"
    android:theme="@style/AppTheme">

    <activity android:name=".SharedPreferences">

    </activity>

    <activity android:name=".InternalStorage">

    </activity>

    <activity android:name=".TelephonyManagerActivity">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
</application>

</manifest>

Do I have to run it on the real device? I have added all the permission but it is not working in the emulator. And I'm using API 23 that is Marshmallow

Body:
You have to ask for  runtime permissons for real devices(see https://developer.android.com/training/permissions/requesting.html?hl=en).
Emulated device haven't got some of things your asking for and might return null, but other things should give you values. For example in my case the emulated device ID return 00000000000 when I run something like:

TelephonyManager telephonyManager = (TelephonyManager) this.getSystemService(Context.TELEPHONY_SERVICE);
        int duration = Toast.LENGTH_SHORT;

DeviceId = telephonyManager.getDeviceId() ;
String testToastInfo = DeviceId + "\n";

Toast.makeText(this,testToastInfo , duration).show();

Hope this help!


问:
ctx.passport undefined when trying to generate a jsonwebtoken when using passport with koa?
I'm trying to create a simple user register/login api using Koa 2 and passport.

The trouble comes when trying to login.

Here is the code for the route;

```<code>import {
    authEmail,
    generateToken
} from '../../auth';

import User from '../../models/user';

export default (router) => {
    router.post('/auth/email', authEmail(), generateToken());
    router.post('/auth/register', register, generateToken());
};

async function register(ctx, next) {
    const { name, email, password } = ctx.request.body;

    // TODO - improve validation
    if (name && email && password) {
        let user = await User.findOne({ email });

        if (!user) {
            user = new User({
                name,
                email
            });
            user.password = user.generateHash(password);
            await user.save();

            ctx.passport = {
                user: user._id,
            };

            console.log(ctx.passport)

            await next();

        } else {
            ctx.status = 400;
            ctx.body = { status: 'error', message: 'E-mail already registered' };
        }
    } else {
        ctx.status = 400;
        ctx.body = { status: 'error', message: 'Invalid email or password' };
    }
}
</code>```

Here is the authEmail() + GenerateToken functions;

```<code>export function authEmail() {
    return passport.authenticate('email');
}

/** After autentication using one of the strategies, generate a JWT token */
export function generateToken() {
    return async ctx => {
        console.log('generating token....')
        console.log(ctx.passport)
        const { user } = ctx.passport;
        if (user === false) {
            ctx.status = 401;
        } else {
            const _token = jwt.sign({id: user}, config.secret);
            const token = `JWT ${_token}`;

            const currentUser = await User.findOne({_id: user});

            ctx.status = 200;
            ctx.body = {
                token,
                user: currentUser,
            };
        }
    };
}
</code>```

and finally the passport email strategy:

```<code>import User from '../../models/user';
import { Strategy as CustomStrategy } from 'passport-custom';

export default new CustomStrategy(async(ctx, done) => {
    console.log('Email Strategy: ', ctx.body);
    try {
        /** Test whether is a login using email and password */
        if (ctx.body.email && ctx.body.password) {
            const user = await User.findOne({ email: ctx.body.email.toLowerCase() });

            if (!user) { done(null, false, {'message': 'User not found.'}); }
            const password = ctx.body.password;
            if (!user.validPassword(password))
                return done(null, false, {'message': 'Password not correct.'});

            done(null, user);

        } else {
            done(null, false, {'message': 'Email and Password are required.'});
        }
    } catch (error) {
        done(error);
    }
});
</code>```

When trying to run a post request to /auth/email I get the following error;

generating token....
  undefined
 xxx POST /api/auth/email 500 124ms

  TypeError: Cannot read property 'user' of undefined...

This is the first time I'm using koa and passport, so I've been trying to clean up a github repo I found. (https://github.com/zombiQWERTY/koa2-starter-kit) and the code is mostly adapted from here.

Any advice on what the problem could be is much appreciated, and if you need any more information / want me to share more parts of the server code please let me know.

EDIT:

Here is the stack trace:

```<code>   TypeError: Cannot read property 'user' of undefined
      at _callee2$ (C:\api/app/auth/index.js:45:12)
      at tryCatch (C:\api\node_modules\regenerator-runtime\runtime.js:65:40)
      at Generator.invoke [as _invoke] (C:\api\node_modules\regenerator-runtime\runtime.js:303:22)
      at Generator.prototype.(anonymous function) [as next] (C:\api\node_modules\regenerator-runtime\runtime.js:117:21)
      at step (C:\api\app\auth\index.js:39:191)
      at C:\api\app\auth\index.js:39:437
      at Promise (<anonymous>)
      at C:\api\app\auth\index.js:39:99
      at C:\api/app/auth/index.js:45:5
      at dispatch (C:\api\node_modules\koa-router\node_modules\koa-compose\index.js:44:32)
      at next (C:\api\node_modules\koa-router\node_modules\koa-compose\index.js:45:18)
      at p.then.cont (C:\api\node_modules\koa-passport\lib\framework\koa.js:144:16)
      at <anonymous>
      at process._tickDomainCallback (internal/process/next_tick.js:208:7)
</code>```

Uploaded current code to repo: https://github.com/alexc101/koa-api

答:
According to the koa-passport docs, with v3, you should be saving your user to ctx.state.user instead of ctx.passport.user.

https://github.com/rkusa/koa-passport

I pulled down your repo and changed all references of ctx.passport to ctx.state and the /email route gives a 200 now.

Body:
I'm trying to create a simple user register/login api using Koa 2 and passport.

The trouble comes when trying to login.

Here is the code for the route;

import {
    authEmail,
    generateToken
} from '../../auth';

import User from '../../models/user';

export default (router) => {
    router.post('/auth/email', authEmail(), generateToken());
    router.post('/auth/register', register, generateToken());
};

async function register(ctx, next) {
    const { name, email, password } = ctx.request.body;

    // TODO - improve validation
    if (name && email && password) {
        let user = await User.findOne({ email });

        if (!user) {
            user = new User({
                name,
                email
            });
            user.password = user.generateHash(password);
            await user.save();

            ctx.passport = {
                user: user._id,
            };

            console.log(ctx.passport)

            await next();

        } else {
            ctx.status = 400;
            ctx.body = { status: 'error', message: 'E-mail already registered' };
        }
    } else {
        ctx.status = 400;
        ctx.body = { status: 'error', message: 'Invalid email or password' };
    }
}

Here is the authEmail() + GenerateToken functions;

export function authEmail() {
    return passport.authenticate('email');
}

/** After autentication using one of the strategies, generate a JWT token */
export function generateToken() {
    return async ctx => {
        console.log('generating token....')
        console.log(ctx.passport)
        const { user } = ctx.passport;
        if (user === false) {
            ctx.status = 401;
        } else {
            const _token = jwt.sign({id: user}, config.secret);
            const token = `JWT ${_token}`;

            const currentUser = await User.findOne({_id: user});

            ctx.status = 200;
            ctx.body = {
                token,
                user: currentUser,
            };
        }
    };
}

and finally the passport email strategy:

import User from '../../models/user';
import { Strategy as CustomStrategy } from 'passport-custom';

export default new CustomStrategy(async(ctx, done) => {
    console.log('Email Strategy: ', ctx.body);
    try {
        /** Test whether is a login using email and password */
        if (ctx.body.email && ctx.body.password) {
            const user = await User.findOne({ email: ctx.body.email.toLowerCase() });

            if (!user) { done(null, false, {'message': 'User not found.'}); }
            const password = ctx.body.password;
            if (!user.validPassword(password))
                return done(null, false, {'message': 'Password not correct.'});

            done(null, user);

        } else {
            done(null, false, {'message': 'Email and Password are required.'});
        }
    } catch (error) {
        done(error);
    }
});

When trying to run a post request to /auth/email I get the following error;

generating token....
  undefined
 xxx POST /api/auth/email 500 124ms

  TypeError: Cannot read property 'user' of undefined...

This is the first time I'm using koa and passport, so I've been trying to clean up a github repo I found. (https://github.com/zombiQWERTY/koa2-starter-kit) and the code is mostly adapted from here.

Any advice on what the problem could be is much appreciated, and if you need any more information / want me to share more parts of the server code please let me know.

EDIT:

Here is the stack trace:

   TypeError: Cannot read property 'user' of undefined
      at _callee2$ (C:\api/app/auth/index.js:45:12)
      at tryCatch (C:\api\node_modules\regenerator-runtime\runtime.js:65:40)
      at Generator.invoke [as _invoke] (C:\api\node_modules\regenerator-runtime\runtime.js:303:22)
      at Generator.prototype.(anonymous function) [as next] (C:\api\node_modules\regenerator-runtime\runtime.js:117:21)
      at step (C:\api\app\auth\index.js:39:191)
      at C:\api\app\auth\index.js:39:437
      at Promise (<anonymous>)
      at C:\api\app\auth\index.js:39:99
      at C:\api/app/auth/index.js:45:5
      at dispatch (C:\api\node_modules\koa-router\node_modules\koa-compose\index.js:44:32)
      at next (C:\api\node_modules\koa-router\node_modules\koa-compose\index.js:45:18)
      at p.then.cont (C:\api\node_modules\koa-passport\lib\framework\koa.js:144:16)
      at <anonymous>
      at process._tickDomainCallback (internal/process/next_tick.js:208:7)

Uploaded current code to repo: https://github.com/alexc101/koa-api


问:
How to find project dependencies in eclipse? how eclipse builds the class path?
There is a project that in some way other project indirectly depends on. I'm trying to find the path of dependencies or the dependencies graph in eclipse but can't find a way.

any way to do that ?

答:
There is command based option as well.
Go to the root folder of your project(you will see pom file in there)
On your command prompt type "mvn dependency:tree", this should print all the dependency your project has on your console.

You can redirect console output to a file, in case dependency tree is too big to fit in console; it is always easy to review this in a file.


问:
Unable to compile jitsi android source code in android studio
When i am import the jitsi-meet android source code in android studio. then there is compiler error.

Failed to resolve: Could not resolve project :react-native-immersive. Required by: project :app > project :sdk Open File

答:
You need to install all dependencies with npm install first. That module is downloaded as part of that process.

In addition, you will need Android Studio 3.0 Preview.