问:
Why doesn't Google Drive API work when called from java servlet?
This class works perfectly when I run it separately

```<code>public class MyDrive {

    private static String CLIENT_ID = "";
    private static String CLIENT_SECRET = "";
    private Drive service;

    public MyDrive() throws IOException {

        HttpTransport httpTransport = new NetHttpTransport();
        JsonFactory jsonFactory = new JacksonFactory();

        GoogleAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow.Builder(
            httpTransport, jsonFactory, CLIENT_ID, CLIENT_SECRET,
            Arrays.asList(new String[] { DriveScopes.DRIVE }))
            .setAccessType("online").setApprovalPrompt("auto").build();

        Credential credential = new AuthorizationCodeInstalledApp(
            flow, new LocalServerReceiver()).authorize("");

        // Create a new authorized API client
        Drive service = new Drive.Builder(httpTransport, jsonFactory,
                credential).build();

        this.service = service;
    }

    public Drive getDrive() {
        return service;
    }

    public static void main(String[] args) throws IOException {
        MyDrive drv = new MyDrive();
    }
}
</code>```

but when I try to create object of this class from Java servlet I get the following error

```<code>java.lang.ClassNotFoundException: com.google.api.client.json.JsonFactory
at org.apache.catalina.loader.WebappClassLoaderBase.loadClass(WebappClassLoaderBase.java:1285)
at org.apache.catalina.loader.WebappClassLoaderBase.loadClass(WebappClassLoaderBase.java:1119)
at WorkingServlets.CreateClassroomServlet.doPost(CreateClassroomServlet.java:60)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:661)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:742)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:231)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:198)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:96)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:478)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:140)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:80)
at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:624)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:87)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:342)
at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:799)
at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:66)
at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:861)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1455)
at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49)
at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
at java.lang.Thread.run(Unknown Source)
</code>```

I don't think it is problem of jar because that class runs separately correctly. What can be the problem?

答:
use these dependencies, and try to update project :

```<code><dependency>
  <groupId>com.google.http-client</groupId>
  <artifactId>google-http-client</artifactId>
  <version>1.22.0</version>
</dependency>

<dependency>
  <groupId>com.google.api-client</groupId>
  <artifactId>google-api-client</artifactId>
  <version>1.22.0</version>
</dependency>

<dependency>
  <groupId>com.google.oauth-client</groupId>
  <artifactId>google-oauth-client</artifactId>
  <version>1.22.0</version>
</code>```

Body:
This class works perfectly when I run it separately

public class MyDrive {

    private static String CLIENT_ID = "";
    private static String CLIENT_SECRET = "";
    private Drive service;

    public MyDrive() throws IOException {

        HttpTransport httpTransport = new NetHttpTransport();
        JsonFactory jsonFactory = new JacksonFactory();

        GoogleAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow.Builder(
            httpTransport, jsonFactory, CLIENT_ID, CLIENT_SECRET,
            Arrays.asList(new String[] { DriveScopes.DRIVE }))
            .setAccessType("online").setApprovalPrompt("auto").build();

        Credential credential = new AuthorizationCodeInstalledApp(
            flow, new LocalServerReceiver()).authorize("");

        // Create a new authorized API client
        Drive service = new Drive.Builder(httpTransport, jsonFactory,
                credential).build();

        this.service = service;
    }

    public Drive getDrive() {
        return service;
    }

    public static void main(String[] args) throws IOException {
        MyDrive drv = new MyDrive();
    }
}

but when I try to create object of this class from Java servlet I get the following error

java.lang.ClassNotFoundException: com.google.api.client.json.JsonFactory
at org.apache.catalina.loader.WebappClassLoaderBase.loadClass(WebappClassLoaderBase.java:1285)
at org.apache.catalina.loader.WebappClassLoaderBase.loadClass(WebappClassLoaderBase.java:1119)
at WorkingServlets.CreateClassroomServlet.doPost(CreateClassroomServlet.java:60)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:661)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:742)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:231)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:198)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:96)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:478)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:140)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:80)
at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:624)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:87)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:342)
at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:799)
at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:66)
at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:861)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1455)
at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49)
at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
at java.lang.Thread.run(Unknown Source)

I don't think it is problem of jar because that class runs separately correctly. What can be the problem?

Body:
use these dependencies, and try to update project :

<dependency>
  <groupId>com.google.http-client</groupId>
  <artifactId>google-http-client</artifactId>
  <version>1.22.0</version>
</dependency>

<dependency>
  <groupId>com.google.api-client</groupId>
  <artifactId>google-api-client</artifactId>
  <version>1.22.0</version>
</dependency>

<dependency>
  <groupId>com.google.oauth-client</groupId>
  <artifactId>google-oauth-client</artifactId>
  <version>1.22.0</version>


来源: stackexchange

问:
Angular 4 Refresh section of page only
Hi community I have a Plunker where I have implemented this flow:

Updated Plunker: I solved but header component gets called each time and I have to put my header component in each html is there a better way to do it?

Login

Show list of countries (User info on top)

Click on one of the  countries and show details about it (Problem is here)

Go back to list

I need to refresh only the section of the countries list, but in my plunker you can see the whole page is refreshing I want to keep the user info on top (static).

I have little experience.
Thanks a lot!

```<code>@Component({
selector : 'login',
template: `
<input type="text" value="james">
<input type="password" value="123">
<button (click)="logIn()">Login</button>
`
})
class LoginComponent {
constructor(private route: ActivatedRoute,
            private router: Router) { }

    logIn () {
        //LOGIN LOGIC
        this.router.navigate(['/base']);
    }
}
</code>```

答:
I finally managed to solve this! I had found the way to do it but it wasn't the correct aproach. Here is the solution: http://plnkr.co/edit/pNoGFP6fva4SYmcspoOj?p=preview

I used children components in the routing configuration and change the way navigations are done:

```<code> this.router.navigate(['/base',  { outlets: { mod : ['countrydetail', country_id ] } } ]);
</code>```

where:

/base is the origin component, where the navigation is starting.

mod is the outlet name (children in app.routing)

countrydetail the child component name

country_id: a parameter

ContentLicense: CC BY-SA 3.0

Title: Angular 4 Refresh section of page only

Body:
Hi community I have a Plunker where I have implemented this flow:

Updated Plunker: I solved but header component gets called each time and I have to put my header component in each html is there a better way to do it?

Login

Show list of countries (User info on top)

Click on one of the  countries and show details about it (Problem is here)

Go back to list

I need to refresh only the section of the countries list, but in my plunker you can see the whole page is refreshing I want to keep the user info on top (static).

I have little experience.
Thanks a lot!

@Component({
selector : 'login',
template: `
<input type="text" value="james">
<input type="password" value="123">
<button (click)="logIn()">Login</button>
`
})
class LoginComponent {
constructor(private route: ActivatedRoute,
            private router: Router) { }

    logIn () {
        //LOGIN LOGIC
        this.router.navigate(['/base']);
    }
}

Body:
I finally managed to solve this! I had found the way to do it but it wasn't the correct aproach. Here is the solution: http://plnkr.co/edit/pNoGFP6fva4SYmcspoOj?p=preview

I used children components in the routing configuration and change the way navigations are done:

 this.router.navigate(['/base',  { outlets: { mod : ['countrydetail', country_id ] } } ]);

where:

/base is the origin component, where the navigation is starting.

mod is the outlet name (children in app.routing)

countrydetail the child component name

country_id: a parameter


问:
trying to auto override JS and HTML files
i'm developning a system whit AngularJS, and as many knows the js and html files are storaged on browser's cache, sometimes making changes to the code, I've had to clear the cache to make the changes visible.. The problem is when the system is online there are no way to clear the client cache, unless he do it by himself, and as a consequence in some cases the system will not work correctly until he does.

Is there any way by means of the code to cause these cached files to be replaced by new ones?

PD: i know that the browsers have a function that replace old files but sometimes it not work.

答: You can add a time stamp at the end of your JavaScript and HTML file requests. For example, yourdomain.com/somescript.js?ts=1352627181 this will make sure that every time the client will make a different request. Therefore, it won't be cached by the browser. Also, you can add no-cache to the headers of the responses made by your server.


问:
Document library folder transfer from one site collection to other
I want to transfer the folder, which is under document library, from one site collection to other site collection. Please help me out!</p>

答: Open the document library in explorer mode copy it from one location open other library in explorer view paste it over their.</p>

ContentLicense: CC BY-SA 2.5


问:
How to properly put table record value to jquery function?
In my php code i have this stroke:

```<code>echo "<td><button id='pausebut_{$record['idTrack']}' name='StopButton'
type='Button' value='{$record['PreviewURL']}'>Stop</button>
</td>";
</code>```

I output a table and for each row I create a button with a unique ID. I want to create a simple Jquery function:

```<code>$('??????').hide();
</code>```

But instead of question marks there must be an ID (pausebut_{$record['idTrack']}). How should I put it in a proper way?

答:
Try this.

Note, it would be better to have a class assigned to each button. Such as 'pauseButtonClass' then your code looks like this:

$('.pauseButtonClass').click(function(){
  var id = $(this).id();
  //do with it what you want.
});

Body:
In my php code i have this stroke:

echo "<button id='pausebut_{$record['idTrack']}' name='StopButton'
type='Button' value='{$record['PreviewURL']}'>Stop</button>
	";

I output a table and for each row I create a button with a unique ID. I want to create a simple Jquery function:

$('??????').hide();

But instead of question marks there must be an ID (pausebut_{$record['idTrack']}). How should I put it in a proper way?


问:
Stripe Rails Cancel Subscription missing ID
I think I have a problem in my routes or in my controller. I tried so much but I can't figure out how to fix this code.

It says in ActionController:

No route matches {:action=>"destroy", :controller=>"payments",
  :order_id=>"sub_AzLXhqXdkvY0Z8"} missing required keys: [:id]

Dashboard show.html.erb

```<code><% @services.each do |service| %>
  <%= link_to service_path(service), class: "panel-row" do %>
    <span class="panel-cell panel-highlight"><%= service.title %></span>
    <span class="panel-cell"><%= service.student.full_name %></span>

    #ActionController tells me here is my problem

    <span><%= button_to "Cancel Subscription",
    order_payment_path(service.orders.last.subscription),
    :data => { :confirm => "Are you sure?" }, :method => :delete,
    class: "btn btn-danger" %></span>

    #

     <% end %>
  <% end %>
<% end %>
</code>```

The order_payment_path goes to the payment destroy controller

dashboard_controller.rb

```<code>def show
  @user = current_user
  if @user.profile_picture.nil?
    @user.profile_picture = "default.jpg"
  end
  @students = Student.all
  @orders = Order.all
  @order = Order.where(state: 'active') # gives me all the active orders
    @hash = @order.where(customer: @user.customer_id).map do |hash|
    hash.service #creates an array of service objects
  end
  @surveys = Survey.all

  if @user.admin == true
    @services = Service.all
  else
    @services = @hash
  end
end
</code>```

PaymentsController.rb

```<code>before_action :set_active_order, only: [:destroy]
def destroy
  @user = current_user
  @subscription = Stripe::Subscription.retrieve(params[:subscription])
  @subscription.delete
  @order.destroy
  respond_to do |format|
    format.js do
      redirect_to dashboard_path, notice: "Successfully Deleted"
    end
    format.html do
      redirect_to dashboard_path
    end
  end
end

private

def set_active_order
  @order = Order.where(state: 'active').find(params[:order_id])
end
</code>```

routes.rb

```<code>devise_for :users
resources :students

resources :services do
  resources :reviews, only: [ :index, :new, :create ]
end
resources :reviews, only: [ :show, :edit, :update, :destroy ]

resources :surveys, only: [ :new, :create, :index, :show, :destroy ]

resources :users

resources :orders, only: [:show, :create] do
  resources :payments, only: [:new, :create, :destroy]
end

get 'dashboard' => 'dashboards#show'

root to: 'pages#home'
</code>```

Sorry if my code is messy because of the naming. I appreciate your effort!

答:
Issue is in this url helper
order_payment_path(service.orders.last.subscription)

Here you have two pass two arguments since it is nested path
the first argument will correspond to your order object and second will correspond to your payment object
something like this order_payment_path(service.orders.last, service.orders.last.subscription)

Body:
I think I have a problem in my routes or in my controller. I tried so much but I can't figure out how to fix this code.

It says in ActionController:

No route matches {:action=>"destroy", :controller=>"payments",
  :order_id=>"sub_AzLXhqXdkvY0Z8"} missing required keys: [:id]

Dashboard show.html.erb

<% @services.each do |service| %>
  <%= link_to service_path(service), class: "panel-row" do %>
    <%= service.title %>
    <%= service.student.full_name %>

    #ActionController tells me here is my problem

    <%= button_to "Cancel Subscription",
    order_payment_path(service.orders.last.subscription),
    :data => { :confirm => "Are you sure?" }, :method => :delete,
    class: "btn btn-danger" %>

    #

     <% end %>
  <% end %>
<% end %>

The order_payment_path goes to the payment destroy controller

dashboard_controller.rb

def show
  @user = current_user
  if @user.profile_picture.nil?
    @user.profile_picture = "default.jpg"
  end
  @students = Student.all
  @orders = Order.all
  @order = Order.where(state: 'active') # gives me all the active orders
    @hash = @order.where(customer: @user.customer_id).map do |hash|
    hash.service #creates an array of service objects
  end
  @surveys = Survey.all

  if @user.admin == true
    @services = Service.all
  else
    @services = @hash
  end
end

PaymentsController.rb

before_action :set_active_order, only: [:destroy]
def destroy
  @user = current_user
  @subscription = Stripe::Subscription.retrieve(params[:subscription])
  @subscription.delete
  @order.destroy
  respond_to do |format|
    format.js do
      redirect_to dashboard_path, notice: "Successfully Deleted"
    end
    format.html do
      redirect_to dashboard_path
    end
  end
end

private

def set_active_order
  @order = Order.where(state: 'active').find(params[:order_id])
end

routes.rb

devise_for :users
resources :students

resources :services do
  resources :reviews, only: [ :index, :new, :create ]
end
resources :reviews, only: [ :show, :edit, :update, :destroy ]

resources :surveys, only: [ :new, :create, :index, :show, :destroy ]

resources :users

resources :orders, only: [:show, :create] do
  resources :payments, only: [:new, :create, :destroy]
end

get 'dashboard' => 'dashboards#show'

root to: 'pages#home'

Sorry if my code is messy because of the naming. I appreciate your effort!


问:
Stop node.js program from command line
I have a simple TCP server that listens on a port.

```<code>var net = require("net");

var server = net.createServer(function(socket) {
    socket.end("Hello!\n");
});

server.listen(7777);
</code>```

I start it with node server.js and then close it with Ctrl + Z on Mac. When I try to run it again with node server.js I get this error message:

```<code>node.js:201
        throw e; // process.nextTick error, or 'error' event on first tick
          ^
Error: listen EADDRINUSE
at errnoException (net.js:670:11)
at Array.0 (net.js:771:26)
at EventEmitter._tickCallback (node.js:192:41)
</code>```

Am I closing the program the wrong way? How can I prevent this from happening?

答:
I'm adding this answer because for many projects with production deployments, we have scripts that stop these processes so we don't have to.

A clean way to manage your Node Server processes is using the forever package (from NPM).

Example:

Install Forever

npm install forever -g

Run Node Server

forever start -al ./logs/forever.log -ao ./logs/out.log -ae ./logs/err.log server.js

Result:

info:    Forever processing file: server.js

Shutdown Node Server

forever stop server.js

Result

info:    Forever stopped process:
    uid  command                            script                           forever pid   id logfile                           uptime
[0] sBSj "/usr/bin/nodejs/node" ~/path/to/your/project/server.js 23084   13176    ~/.forever/forever.log 0:0:0:0.247

This will cleanly shutdown your Server application.

Title: Stop node.js program from command line

Body:
I have a simple TCP server that listens on a port.

var net = require("net");

var server = net.createServer(function(socket) {
    socket.end("Hello!\n");
});

server.listen(7777);

I start it with node server.js and then close it with Ctrl + Z on Mac. When I try to run it again with node server.js I get this error message:

node.js:201
        throw e; // process.nextTick error, or 'error' event on first tick
          ^
Error: listen EADDRINUSE
at errnoException (net.js:670:11)
at Array.0 (net.js:771:26)
at EventEmitter._tickCallback (node.js:192:41)

Am I closing the program the wrong way? How can I prevent this from happening?


问:
Why my UI Grid cannot load the grid
Here is my runnable plunker

I followed the tutorial in UI Grid official tutorial.
I do not know why I cannot load the grid. I did not find any syntax error.

Here is part of errors from console:

URL visited /
  editor-1.2.0.js:2 URL visited /?p=catalogue
  emmet.js Failed to load resource: the server responded with a status of 404 (Not Found)
  editor-1.2.0.js:7 AUTH Object
  editor-1.2.0.js:2 Event tracked Plunk Beautify Toolbar undefined undefined
  editor-1.2.0.js:2 Event tracked Plunk Save Toolbar undefined undefined
  editor-1.2.0.js:2 URL visited /oXEt5IfdrpkkPSxysncy?p=catalogue
  editor-1.2.0.js:2 Event tracked Multipane Show Preview Toolbar undefined undefined
  editor-1.2.0.js:2 URL visited /oXEt5IfdrpkkPSxysncy?p=preview
  run.plnkr.co/:1 Mixed Content: The page at 'https://plnkr.co/edit/oXEt5IfdrpkkPSxysncy?p=preview' was loaded over HTTPS, but requested an insecure script 'http://ajax.googleapis.com/ajax/libs/angularjs/1.5.0/angular.min.js'. This request has been blocked; the content must be served over HTTPS.

```<code><!DOCTYPE html>
<html ng-app="app">

<head>
    <link rel="stylesheet" href="http://ui-grid.info/release/ui-grid.css" type="text/css">
    <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.5.0/angular.min.js"></script>
    <script src="http://ui-grid.info/release/ui-grid.js"></script>
</head>

<body>
    <h1>Hello Plunker!</h1>

    <div ng-controller="MainCtrl">
        <div ui-grid="{ data: myData }" class="myGrid"></div>
    </div>

    <script>
        var app = angular.module('app', ['ui.grid']);
        app.controller('MainCtrl', ['$scope', function($scope) {
            $scope.myData = [{
                    "firstName": "Cox",
                    "lastName": "Carney",
                    "company": "Enoromo",
                    "employed": true
                }, {
                    "firstName": "Lorraine",
                    "lastName": "Wise",
                    "company": "Comveyer",
                    "employed": false
                }, {
                    "firstName": "Nancy",
                    "lastName": "Waters",
                    "company": "Fuelton",
                    "employed": false
                }
            ];
        }])
    </script>

    <style>
        .myGrid {
            width: 500 px;
            height: 250 px;
        }
    </style>
</body>

</html>
</code>```

答:
Your cdn for ui-grid was not correct. And all your src should point to a secure url i.e with https. The reason is you are trying to access an unsecure script from a secure site. This will be blocked since content can be served over only HTTPS.

```<code>  <head>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/angular-ui-grid/4.0.6/ui-grid.css" type="text/css">
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.0/angular.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/angular-ui-grid/4.0.6/ui-grid.min.js"></script>
  </head>
</code>```

Working Plunkr:https://plnkr.co/edit/I87wgFzlqmtl6dcPem6F?p=preview

Title: Why my UI Grid cannot load the grid

Body:
Here is my runnable plunker

I followed the tutorial in UI Grid official tutorial.
I do not know why I cannot load the grid. I did not find any syntax error.

Here is part of errors from console:

URL visited /
  editor-1.2.0.js:2 URL visited /?p=catalogue
  emmet.js Failed to load resource: the server responded with a status of 404 (Not Found)
  editor-1.2.0.js:7 AUTH Object
  editor-1.2.0.js:2 Event tracked Plunk Beautify Toolbar undefined undefined
  editor-1.2.0.js:2 Event tracked Plunk Save Toolbar undefined undefined
  editor-1.2.0.js:2 URL visited /oXEt5IfdrpkkPSxysncy?p=catalogue
  editor-1.2.0.js:2 Event tracked Multipane Show Preview Toolbar undefined undefined
  editor-1.2.0.js:2 URL visited /oXEt5IfdrpkkPSxysncy?p=preview
  run.plnkr.co/:1 Mixed Content: The page at 'https://plnkr.co/edit/oXEt5IfdrpkkPSxysncy?p=preview' was loaded over HTTPS, but requested an insecure script 'http://ajax.googleapis.com/ajax/libs/angularjs/1.5.0/angular.min.js'. This request has been blocked; the content must be served over HTTPS.

<!DOCTYPE html>

    <link rel="stylesheet" href="http://ui-grid.info/release/ui-grid.css" type="text/css">

Hello Plunker!

Body:
Your cdn for ui-grid was not correct. And all your src should point to a secure url i.e with https. The reason is you are trying to access an unsecure script from a secure site. This will be blocked since content can be served over only HTTPS.

  <head>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/angular-ui-grid/4.0.6/ui-grid.css" type="text/css">
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.0/angular.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/angular-ui-grid/4.0.6/ui-grid.min.js"></script>
  </head>

Working Plunkr:https://plnkr.co/edit/I87wgFzlqmtl6dcPem6F?p=preview


问:
Tap in UIWebView to Hide Keyboard
I'd lik to have the same behavior in my app as Safari has. In Safari when the keyboard is visible a tap in an area outside the editing field will cause the keyboard to hide.
But with a UIWebView in my own app that's not the case by default. So how can I get this behavior to my app?

I tried to add a UIGestureRecognizer but it fires never or always (depending on shouldRecognizeSimultaneouslyWithGestureRecognizer:). So I tried to override the sendEvent: in the UIWindow. But that also has the problem that I always get the tap. Even when tapping on e.g. the text that's being edited. So no text selection is possible.

--edit

I just discovered that this behaviour is not default in Safari. Only on the google search page it's this way. So there must be a JavaScript solution for this problem.

答:
Subclass the web view and override

-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event;
  Goog luck.

Title: Tap in UIWebView to Hide Keyboard


问:
How to properly use the HTML semantic elements in a blog?
I read a lot of information on w3schools. It defines
 as:

The
 element defines a section in a document. [...] A home page could normally be split into sections for introduction, content, and contact information.

So, basically, a
 can be a  (introduction) and  (contact information)?

The  element specifies a header for a document or section.

So I could put a  inside a
? But a
 can be used "for introduction", so it basically is a header? Same story with the  element.

Questions

How am I actually supposed to use the elements?

Should I use  for the title of an
 or for the part of my website containing the logo and navigation?

Should I use  for the data of an
 or for the part of my website containing the copyright and footer navigation?

Should I put a
 tag around my
 tags?

Let's say I have a simple website, containing a logo, navigation, several articles and some footer text. What would be the best way to do the markup?

<!DOCTYPE html>

    <title>My site</title>

Item 1

Item 2

Item 3

Article 1 title

            Posted on Foo.Bar.2017

Article 2 title

            Posted on Foo.Bar.2017

Article 3 title

            Posted on Foo.Bar.2017

Copyright

```

If I do that, the Nu HTML Checker says:

Warning: Section lacks heading. Consider using h2-h6 elements to add identifying headings to all sections.

I don't want an
 stating the
 contains
 tags. Should I just remove the
? It appears to be a flexible tag, yet I can't find a valid place to put it.

What would be the correct markup?

答:
A header is not the same as heading. You use the <header> tag for your header (page head) and <h1> to <h6> for you heading (titles, subtitles, etc.).
Thats the difference between header and headings. Other than that your markup seems logical enough, except for the header-heading issue and I wouldn't go using <footer> - the tag for page footers to display some data like dates or authors.

HTML5 semantics is very logical - <header>,<nav>,<main> content, content of main content, <aside> content etc...

But an <article> can be part of a <section>. And a section can also be part of an article. So my opinion is that if you follow the logic of HTML tags you don't have to worry about semantics much.

Oh, and to answer your question. I would do it like this:

```<code><section>
    <article>
        <h2>Article 1 title</h2>
        <p>Posted on Foo.Bar.2017</p>
    </article>

    <article>
        <h2>Article 2 title</h2>
        <p>Posted on Foo.Bar.2017</p>
    </article>
</section>
</code>```

If needed you could use the <time> tag with the <p> tag, but I would not (because of compatibility)

Body:
I read a lot of information on w3schools. It defines
 as:

The
 element defines a section in a document. [...] A home page could normally be split into sections for introduction, content, and contact information.

So, basically, a
 can be a  (introduction) and  (contact information)?

The  element specifies a header for a document or section.

So I could put a  inside a
? But a
 can be used "for introduction", so it basically is a header? Same story with the  element.

Questions

How am I actually supposed to use the elements?

Should I use  for the title of an
 or for the part of my website containing the logo and navigation?

Should I use  for the data of an
 or for the part of my website containing the copyright and footer navigation?

Should I put a
 tag around my
 tags?

Let's say I have a simple website, containing a logo, navigation, several articles and some footer text. What would be the best way to do the markup?

<!DOCTYPE html>

    <title>My site</title>

Item 1

Item 2

Item 3

Article 1 title

            Posted on Foo.Bar.2017

Article 2 title

            Posted on Foo.Bar.2017

Article 3 title

            Posted on Foo.Bar.2017

Copyright

If I do that, the Nu HTML Checker says:

Warning: Section lacks heading. Consider using h2-h6 elements to add identifying headings to all sections.

I don't want an
 stating the
 contains
 tags. Should I just remove the
? It appears to be a flexible tag, yet I can't find a valid place to put it.

What would be the correct markup?

Body:
A header is not the same as heading. You use the <header> tag for your header (page head) and <h1> to <h6> for you heading (titles, subtitles, etc.).
Thats the difference between header and headings. Other than that your markup seems logical enough, except for the header-heading issue and I wouldn't go using <footer> - the tag for page footers to display some data like dates or authors.

HTML5 semantics is very logical - <header>,<nav>,<main> content, content of main content, <aside> content etc...

But an <article> can be part of a <section>. And a section can also be part of an article. So my opinion is that if you follow the logic of HTML tags you don't have to worry about semantics much.

Oh, and to answer your question. I would do it like this:

<section>
    <article>
        <h2>Article 1 title</h2>
        <p>Posted on Foo.Bar.2017</p>
    </article>

    <article>
        <h2>Article 2 title</h2>
        <p>Posted on Foo.Bar.2017</p>
    </article>
</section>

If needed you could use the <time> tag with the <p> tag, but I would not (because of compatibility)


问:
React removing an element when onClick
I am trying to remove a div when onClick is pressed.  The div exists on my parent component where I have

```<code> render() {
    const listPlayers = players.map(player => (
      <Counter
        key={player.id}
        player={player}
        name={player.name}
        sortableGroupDecorator={this.sortableGroupDecorator}
        decrementCountTotal={this.decrementCountTotal}
        incrementCountTotal={this.incrementCountTotal}
        removePlayer={this.removePlayer}
        handleClick={player}
      />
    ));

    return (
      <ContainLeft style={{ alignItems: 'center' }}>
        <ProjectTitle>Score Keeper</ProjectTitle>
        <Copy>
          A sortable list of players that with adjustable scores.  Warning, don't go negative!
        </Copy>
        <div>
          <Stats totalScore={this.state.totalScore} players={players} />
          {listPlayers}
        </div>
      </ContainLeft>
    );
  }
</code>```

It passes props to the child component where the button to delete the div, here

```<code>    return (
      <div
        style={{ display: this.state.displayInfo }}
        className="group-list"
        ref={sortableGroupDecorator}
        id="cell"
      >
        <CountCell style={{ background: this.state.color }}>
          <Row style={{ alignItems: 'center', marginLeft: '-42px' }}>
            <Col>
              <DeleteButton onClick={removePlayer}>
                <Icon name="delete" className="delete-adjust fa-minus-circle" />
              </DeleteButton>
            </Col>
</code>```

(I snipped the rest of the code because it was long and not useful here)

The array (a separate file) is imported into the Parent component and it reads like this

```<code>const players = [
  {
    name: 'Jabba',
    score: 10,
    id: 11
  },
  {
    name: 'Han',
    score: 10,
    id: 1
  },
  {
    name: 'Rey',
    score: 30,
    id: 10
  }
];

export default players;
</code>```

So what I'm trying to do is write a function on the main parent that when it is clicked inside the child, the div is removed, deleted, gone (whatever the best term is) sort of like "remove player, add player"

On my parent component, I've written a function where the console.log works when it is clicked in the child, but whatever I write in the function doesn't seem to want to work.

The function I'm building (in progress, I'm still a little lost here) is:

```<code>  removePlayer() {
    console.log('this was removed');
    players.splice(2, 0, 'Luke', 'Vader');
  }
</code>```

which is mapped over here as a prop

```<code>const listPlayers = players.map(player => (
  <Counter
    key={player.id}
    player={player}
    name={player.name}
    sortableGroupDecorator={this.sortableGroupDecorator}
    decrementCountTotal={this.decrementCountTotal}
    incrementCountTotal={this.incrementCountTotal}
    removePlayer={this.removePlayer}
    handleClick={player}
  />
));
</code>```

And passed into the child here:

```<code>render() {
const {
  name,
  sortableGroupDecorator,
  decrementCountTotal,
  incrementCountTotal,
  removePlayer
} = this.props;

return (
  <div
    style={{ display: this.state.displayInfo }}
    className="group-list"
    ref={sortableGroupDecorator}
    id="cell"
  >
    <CountCell style={{ background: this.state.color }}>
      <Row style={{ alignItems: 'center', marginLeft: '-42px' }}>
        <Col>
          <DeleteButton onClick={removePlayer}>
            <Icon name="delete" className="delete-adjust fa-minus-circle" />
          </DeleteButton>
</code>```

I know all this is lengthy and I wanted to provide as much detail as I could because React is still new to me and I get confused with some of the verbiages.  Thanks for helping out in advance

答:
We sorted it out in chat. Like expected, it was a problem with the state.

I made a small semi-pseudo snippet with comments as explanation:

```<code>import React, { Component } from 'react';

// Your player constant, outside the scope of any React component
// This pretty much just lives in your browser as a plain object.
const players = [
  {
    name: 'Jabba',
    score: 10,
    id: 11
  },
  {
    name: 'Han',
    score: 10,
    id: 1
  },
  {
    name: 'Rey',
    score: 30,
    id: 10
  }
];

class App extends Component {

  constructor() {
    super();

    this.state = {
      players, // ES6 Syntax, same as players: players
      // Add all your other stuff here
    };
  }

  removePlayer(id) {
    const newState = this.state;
    const index = newState.players.findIndex(a => a.id === id);

    if (index === -1) return;
    newState.players.splice(index, 1);

    this.setState(newState); // This will update the state and trigger a rerender of the components
  }

  render() {

   const listPlayers = this.state.players.map(player => { // Note the this.state, this is important for React to see changes in the data and thus rerender the Component
      <Counter
        ..

        removePlayer={this.removePlayer.bind(this)} //bind this to stay in the context of the parent component
      />
    });

    return (
      <div>
        {listPlayers}
      </div>
    );
  }
}

//////////////////////////////////////// Child component

....

<DeleteButton onClick={() => this.props.removePlayer(this.props.player.id)}>

....
</code>```

Title: React removing an element when onClick

Body:
I am trying to remove a div when onClick is pressed.  The div exists on my parent component where I have

 render() {
    const listPlayers = players.map(player => (
      <Counter
        key={player.id}
        player={player}
        name={player.name}
        sortableGroupDecorator={this.sortableGroupDecorator}
        decrementCountTotal={this.decrementCountTotal}
        incrementCountTotal={this.incrementCountTotal}
        removePlayer={this.removePlayer}
        handleClick={player}
      />
    ));

    return (
      <ContainLeft style={{ alignItems: 'center' }}>
        <ProjectTitle>Score Keeper</ProjectTitle>
        <Copy>
          A sortable list of players that with adjustable scores.  Warning, don't go negative!
        </Copy>

          <Stats totalScore={this.state.totalScore} players={players} />
          {listPlayers}

      </ContainLeft>
    );
  }

It passes props to the child component where the button to delete the div, here

    return (

        <CountCell style={{ background: this.state.color }}>
          <Row style={{ alignItems: 'center', marginLeft: '-42px' }}>
            <Col>
              <DeleteButton onClick={removePlayer}>
                <Icon name="delete" className="delete-adjust fa-minus-circle" />
              </DeleteButton>
            </Col>

(I snipped the rest of the code because it was long and not useful here)

The array (a separate file) is imported into the Parent component and it reads like this

const players = [
  {
    name: 'Jabba',
    score: 10,
    id: 11
  },
  {
    name: 'Han',
    score: 10,
    id: 1
  },
  {
    name: 'Rey',
    score: 30,
    id: 10
  }
];

export default players;

So what I'm trying to do is write a function on the main parent that when it is clicked inside the child, the div is removed, deleted, gone (whatever the best term is) sort of like "remove player, add player"

On my parent component, I've written a function where the console.log works when it is clicked in the child, but whatever I write in the function doesn't seem to want to work.

The function I'm building (in progress, I'm still a little lost here) is:

  removePlayer() {
    console.log('this was removed');
    players.splice(2, 0, 'Luke', 'Vader');
  }

which is mapped over here as a prop

const listPlayers = players.map(player => (
  <Counter
    key={player.id}
    player={player}
    name={player.name}
    sortableGroupDecorator={this.sortableGroupDecorator}
    decrementCountTotal={this.decrementCountTotal}
    incrementCountTotal={this.incrementCountTotal}
    removePlayer={this.removePlayer}
    handleClick={player}
  />
));

And passed into the child here:

render() {
const {
  name,
  sortableGroupDecorator,
  decrementCountTotal,
  incrementCountTotal,
  removePlayer
} = this.props;

return (

    <CountCell style={{ background: this.state.color }}>
      <Row style={{ alignItems: 'center', marginLeft: '-42px' }}>
        <Col>
          <DeleteButton onClick={removePlayer}>
            <Icon name="delete" className="delete-adjust fa-minus-circle" />
          </DeleteButton>

I know all this is lengthy and I wanted to provide as much detail as I could because React is still new to me and I get confused with some of the verbiages.  Thanks for helping out in advance

Body:
We sorted it out in chat. Like expected, it was a problem with the state.

I made a small semi-pseudo snippet with comments as explanation:

import React, { Component } from 'react';

// Your player constant, outside the scope of any React component
// This pretty much just lives in your browser as a plain object.
const players = [
  {
    name: 'Jabba',
    score: 10,
    id: 11
  },
  {
    name: 'Han',
    score: 10,
    id: 1
  },
  {
    name: 'Rey',
    score: 30,
    id: 10
  }
];

class App extends Component {

  constructor() {
    super();

    this.state = {
      players, // ES6 Syntax, same as players: players
      // Add all your other stuff here
    };
  }

  removePlayer(id) {
    const newState = this.state;
    const index = newState.players.findIndex(a => a.id === id);

    if (index === -1) return;
    newState.players.splice(index, 1);

    this.setState(newState); // This will update the state and trigger a rerender of the components
  }

  render() {

   const listPlayers = this.state.players.map(player => { // Note the this.state, this is important for React to see changes in the data and thus rerender the Component
      <Counter
        ..

        removePlayer={this.removePlayer.bind(this)} //bind this to stay in the context of the parent component
      />
    });

    return (
      <div>
        {listPlayers}
      </div>
    );
  }
}

//////////////////////////////////////// Child component

....

<DeleteButton onClick={() => this.props.removePlayer(this.props.player.id)}>

....


问:
How to correctly query list in firebase/angularfire?
I have this structure:

I found this: https://github.com/angular/angularfire2/blob/master/docs/4-querying-lists.md and also I read firebase docs.

I try this:

```<code>return this.db.list(`${this.API_EVENTS_PATH}`, {
  query: {
    equalTo: {
      value: 'sharikov.vladislav@gmail.com',
      key: 'from'
    }
  }
});
</code>```

This gives nothing: empty array. Why?

And another question is: how to I can filter items by 2 fields? I need from=sharikov.vladislav@gmail.com&status=ACCEPTED for example.

How it is possible to do it with FB?

答:
For your first question.

Before you use the EqualTo filter there should first be an OrderBy filter... This OrderBy filter tells the query which field should EqualTo refer to... So your query should look like this.

```<code>let path = this.API_EVENTS_PATH;
return db.list(path , {
  query: {
    orderByChild: 'from',
    equalTo: 'sharikov.vladislav@gmail.com',
  }
});
</code>```

For your second question

How to filter items by 2 fields

In Nosql database like firebase you are normally allowed to filter by only 1 field. Every other manipulations are done considering on how you organise your database. Check out this firebase video which shows you how to do your normal SQL queries on firebase database. Enjoy

Body:
I have this structure:

I found this: https://github.com/angular/angularfire2/blob/master/docs/4-querying-lists.md and also I read firebase docs.

I try this:

return this.db.list(`${this.API_EVENTS_PATH}`, {
  query: {
    equalTo: {
      value: 'sharikov.vladislav@gmail.com',
      key: 'from'
    }
  }
});

This gives nothing: empty array. Why?

And another question is: how to I can filter items by 2 fields? I need from=sharikov.vladislav@gmail.com&status=ACCEPTED for example.

How it is possible to do it with FB?

Body:
For your first question.

Before you use the EqualTo filter there should first be an OrderBy filter... This OrderBy filter tells the query which field should EqualTo refer to... So your query should look like this.

let path = this.API_EVENTS_PATH;
return db.list(path , {
  query: {
    orderByChild: 'from',
    equalTo: 'sharikov.vladislav@gmail.com',
  }
});

For your second question

How to filter items by 2 fields

In Nosql database like firebase you are normally allowed to filter by only 1 field. Every other manipulations are done considering on how you organise your database. Check out this firebase video which shows you how to do your normal SQL queries on firebase database. Enjoy


问:
Virtual functions and performance - C++
In my class design, I use abstract classes and virtual functions extensively. I had a  feeling that virtual functions affects the performance. Is this true? But I think this performance difference is not noticeable and looks like I am doing premature optimization. Right?</p>

答: When Objective-C (where all methods are virtual) is the primary language for the iPhone and freakin' Java is the main language for Android, I think it's pretty safe to use C++ virtual functions on our 3 GHz dual-core towers.

OwnerDisplayName: Appu

Title: Virtual functions and performance - C++

LastEditorDisplayName: Serge

OwnerDisplayName: Chuck


问:
How to make a site in malayalam language?
I want to create a website. Its contents must be displayed in malayalam language. In admin panel I can edit that malayalam contents of the site also.

How can I do that? Please share your ideas with me. Also help me on this, how to create that kind of a content editor?

答:
Creating a system like the one you mention is really complex, and takes years of practice to do properly. If you still want to go ahead and code it yourself, you need to learn PHP, MySql, and HTML.

I would recommend, however, that you use a Content Managing System ( CMS ) such as Wordpress or drupal. Wordpress is really easy to install and use.

Regards,
Pedro


问:
Tail multiple directories
How do I print only the last (n) file(s) inside nested directories matching a certain pattern?

Doing

```<code>ls -l dir*/history/ | tail
</code>```

gives only the content of the last directory.

I suspect it has to do with xargs but can't really figure out how.

答:
Try that:

```<code>find . -type d -name "dir*" | while read dir; do find "$dir" | tail -n 5; done
</code>```

Not very laconic, but if you need to match all the levels of nested directories and pick N files from each subdirectory...

Also add 2>/dev/null before each pipe to supress 'permission denied' messages. Or use sudo.

An equivalent with process substitution, if you need to change global variables within the while loop:

```<code>while read dir; do find "$dir" | tail -n 5; done < <(find . -type d -name "dir*")
</code>```

Title: Tail multiple directories

Body:
How do I print only the last (n) file(s) inside nested directories matching a certain pattern?

Doing

ls -l dir*/history/ | tail

gives only the content of the last directory.

I suspect it has to do with xargs but can't really figure out how.

Body:
Try that:

find . -type d -name "dir*" | while read dir; do find "$dir" | tail -n 5; done

Not very laconic, but if you need to match all the levels of nested directories and pick N files from each subdirectory...

Also add 2>/dev/null before each pipe to supress 'permission denied' messages. Or use sudo.

An equivalent with process substitution, if you need to change global variables within the while loop:

while read dir; do find "$dir" | tail -n 5; done < <(find . -type d -name "dir*")


问:
angular validation .error not defined
I'm trying to use a template driven form and I can't seem to get the errors property to correctly work to validate the minlength as per the tutorial Here.  The error I'm getting on page load in the dev tools is:

ContactFormComponent.html:8 ERROR TypeError: Cannot read property
  'minlength' of null

So the problem is that there is no .error property on the ngModel.  I'm not sure if I've misinterpreted something or incorrectly set up the form.  Without the validation everything works as intended.

HTML

```<code><form (ngSubmit)="onSubmit()" #contactForm="ngForm">
    <div class="form-group">
        <label for="email">Email</label>
        <input minlength="6" maxlength="50" name="email" class="form-control" id="email" placeholder="Email" required email [(ngModel)]="contactForm.email" #email="ngModel">
        <div *ngIf="email.dirty || email.touched" class="alert alert-danger">
            <div [hidden]="!email.errors.minlength">
                <span>Email is too short</span>
            </div>
        </div>
    </div>
</form>
</code>```

Component

```<code>import { Component, Input } from '@angular/core';
import { Contact } from './contact';
import { AppService } from '../app.service';

@Component({
  selector: 'selected-page',
  template: require('./contact-form.html'),
  providers: [AppService]
})

export class ContactFormComponent {
    contactForm = new Contact();
    submitted: boolean = false;

    constructor (private appService: AppService) {}

    onSubmit() {
        this.appService.emailContact(contactForm).then(data => {
            this.submitted = true;
        });
    }
}
</code>```

Module

```<code>import { NgModule }      from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { RouterModule, Routes }   from '@angular/router';
import { FormsModule } from '@angular/forms';

import { AppComponent }  from './app.component';
import { ContactFormComponent } from './contact/contact-form.component';
import { HttpModule } from '@angular/http';
import { AppService } from './app.service';

const appRoutes: Routes = [
    {
        path: 'contact',
        component: ContactFormComponent
    }
]

@NgModule({
    imports: [
        BrowserModule,
        RouterModule.forRoot(appRoutes),
        FormsModule,
        HttpModule
    ],
    declarations: [
        AppComponent,
        ContactFormComponent,
    ],
    bootstrap: [ AppComponent ],
    providers: [ AppService ]
})

export class AppModule { }
</code>```

答:
The problem is that I was using *ngIf in my code incorrectly and made assumptions about how it worked.  I updated my original post to correctly reflect this.

The *ngIf on email.errors stops the child html elements from being evaluated which stops the error from happening.

As per TheUnreals comment you can also not use *ngIf all together by doing !email.errors?.minlength.

What I had

```<code><div *ngIf="email.dirty || email.touched" class="alert alert-danger">
    <div [hidden]="!email.errors.minlength">
        <span>Email is too short</span>
    </div>
</div>
</code>```

Correct Answer

```<code><div *ngIf="email.errors && (email.dirty || email.touched)" class="alert alert-danger">
    <div [hidden]="!email.errors.minlength">
        <span>Email is too short</span>
    </div>
</div>
</code>```

Title: angular validation .error not defined

Body:
I'm trying to use a template driven form and I can't seem to get the errors property to correctly work to validate the minlength as per the tutorial Here.  The error I'm getting on page load in the dev tools is:

ContactFormComponent.html:8 ERROR TypeError: Cannot read property
  'minlength' of null

So the problem is that there is no .error property on the ngModel.  I'm not sure if I've misinterpreted something or incorrectly set up the form.  Without the validation everything works as intended.

HTML

<form (ngSubmit)="onSubmit()" #contactForm="ngForm">

        Email
        <input minlength="6" maxlength="50" name="email" class="form-control" id="email" placeholder="Email" required email [(ngModel)]="contactForm.email" #email="ngModel">

                Email is too short

</form>

Component

import { Component, Input } from '@angular/core';
import { Contact } from './contact';
import { AppService } from '../app.service';

@Component({
  selector: 'selected-page',
  template: require('./contact-form.html'),
  providers: [AppService]
})

export class ContactFormComponent {
    contactForm = new Contact();
    submitted: boolean = false;

    constructor (private appService: AppService) {}

    onSubmit() {
        this.appService.emailContact(contactForm).then(data => {
            this.submitted = true;
        });
    }
}

Module

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

import { AppComponent }  from './app.component';
import { ContactFormComponent } from './contact/contact-form.component';
import { HttpModule } from '@angular/http';
import { AppService } from './app.service';

const appRoutes: Routes = [
    {
        path: 'contact',
        component: ContactFormComponent
    }
]

@NgModule({
    imports: [
        BrowserModule,
        RouterModule.forRoot(appRoutes),
        FormsModule,
        HttpModule
    ],
    declarations: [
        AppComponent,
        ContactFormComponent,
    ],
    bootstrap: [ AppComponent ],
    providers: [ AppService ]
})

export class AppModule { }

Body:
The problem is that I was using *ngIf in my code incorrectly and made assumptions about how it worked.  I updated my original post to correctly reflect this.

The *ngIf on email.errors stops the child html elements from being evaluated which stops the error from happening.

As per TheUnreals comment you can also not use *ngIf all together by doing !email.errors?.minlength.

What I had

<div *ngIf="email.dirty || email.touched" class="alert alert-danger">
    <div [hidden]="!email.errors.minlength">
        <span>Email is too short</span>
    </div>
</div>

Correct Answer

<div *ngIf="email.errors && (email.dirty || email.touched)" class="alert alert-danger">
    <div [hidden]="!email.errors.minlength">
        <span>Email is too short</span>
    </div>
</div>


答:
```<code>$("button[name='StopButton']").click(function(){
    var id = $(this).attr('id');
    $('#' + id).hide();
});
</code>```

Title: How to properly put table record value to jquery function?


问:
How to change all view text size in android
I want to add an item on menu to adjust the application font size. and if font size be changed by user with this feature all the font sizes of texts in views of application be changed.</p>

答:
I use this method to adjust the font size of my application but here i am keeping it stable at scale 1 which you can change accordingly.

```<code>    public void adjustFontScale(Configuration configuration) {
    configuration.fontScale = (float) 1;
    DisplayMetrics metrics = getResources().getDisplayMetrics();
    WindowManager wm = (WindowManager) getSystemService(WINDOW_SERVICE);
    wm.getDefaultDisplay().getMetrics(metrics);
    metrics.scaledDensity = configuration.fontScale * metrics.density;
    getBaseContext().getResources().updateConfiguration(configuration, metrics);
}
</code>```

Just change the configuration.fontScale to any value you like and call it in onCreate. Hope this helps.

Body:
I use this method to adjust the font size of my application but here i am keeping it stable at scale 1 which you can change accordingly.

    public void adjustFontScale(Configuration configuration) {
    configuration.fontScale = (float) 1;
    DisplayMetrics metrics = getResources().getDisplayMetrics();
    WindowManager wm = (WindowManager) getSystemService(WINDOW_SERVICE);
    wm.getDefaultDisplay().getMetrics(metrics);
    metrics.scaledDensity = configuration.fontScale * metrics.density;
    getBaseContext().getResources().updateConfiguration(configuration, metrics);
}

Just change the configuration.fontScale to any value you like and call it in onCreate. Hope this helps.


问:
Developing speedometer in Android?
I want to develop speedometer in Android which will display the speed of the user. For that I have one image which has speed readings like 5, 10, 15 and so on. Now, I want to move the arrow on that. If the speed is 5 then that arrow should move from 0 to 5. Can someone help me out as how that can be done?</p>

答: I'd start with an arrow image with a transparent background, and draw it over the dial image, rotating it to match the right speed.</p>

Title: Developing speedometer in Android?


问:
How to return prevent entity escapes from returning in Play?
I'm using play 2.6 with Scala and have this bit in my view template:

```<code>@isActive( liText: String ) = @{
        if ( liText.equals(activeTab) ) "class=\"active\""  else ""
    }
</code>```

But it's rendering this:
class="active"

But I want it to render this:

"class="active""

I feel like I'm close but can't quite get it to not use &quot in the final HTML. Any suggestions?

答:
You can use @Html to make it print raw html instead of escaping the content:

```<code>@isActive( liText: String ) = @{
    if ( liText.equals(activeTab) ) @Html("class='active'")  else ""
}
</code>```

Source: https://www.playframework.com/documentation/2.6.x/ScalaTemplates#Escaping

Body:
I'm using play 2.6 with Scala and have this bit in my view template:

@isActive( liText: String ) = @{
        if ( liText.equals(activeTab) ) "class=\"active\""  else ""
    }

But it's rendering this:
class="active"

But I want it to render this:

"class="active""

I feel like I'm close but can't quite get it to not use &quot in the final HTML. Any suggestions?

Body:
You can use @Html to make it print raw html instead of escaping the content:

@isActive( liText: String ) = @{
    if ( liText.equals(activeTab) ) @Html("class='active'")  else ""
}

Source: https://www.playframework.com/documentation/2.6.x/ScalaTemplates#Escaping


问:
Handling different errors for different versions of python
I am having issues with catching errors by the json module for different versions of Python. The json module throws a JSONDecodeError for Python 3.5.2 and ValueError for Python 2.7.12. What is the best practice for doing this?

For example, this works for Python 2.7.12

```<code>a = '{"a": [5 8]}'
try:
    d = json.loads(a)
except ValueError:
    # do something
</code>```

and this works for Python 3.5.2

```<code>a = '{"a": [5 8]}'
try:
    d = json.loads(a)
except json.JSONDecodeError:
    # do something
</code>```

I have seen the answer here but I want to find a more elegant way.

答:
JSONDecodeError is a subclass of ValueError:

```<code>>>> from json import JSONDecodeError
>>> issubclass(JSONDecodeError, ValueError)
True
</code>```

Just stick to catching ValueError; it should suffice if you need to support both versions. All JSONDecodeError adds is a few additional fields, giving you easy access to the parsed document, and the exact position of the error.

If you need access to those attributes (provided they are present), just use hasattr() to test first:

```<code>try:
    d = json.loads(a)
except ValueError as err:
    pos = (None, None)
    if hasattr(err, lineno):
        # JSONDecodeError subclass
        pos = err.lineno, err.colno
</code>```

Body:
I am having issues with catching errors by the json module for different versions of Python. The json module throws a JSONDecodeError for Python 3.5.2 and ValueError for Python 2.7.12. What is the best practice for doing this?

For example, this works for Python 2.7.12

a = '{"a": [5 8]}'
try:
    d = json.loads(a)
except ValueError:
    # do something

and this works for Python 3.5.2

a = '{"a": [5 8]}'
try:
    d = json.loads(a)
except json.JSONDecodeError:
    # do something

I have seen the answer here but I want to find a more elegant way.

Body:
JSONDecodeError is a subclass of ValueError:

>>> from json import JSONDecodeError
>>> issubclass(JSONDecodeError, ValueError)
True

Just stick to catching ValueError; it should suffice if you need to support both versions. All JSONDecodeError adds is a few additional fields, giving you easy access to the parsed document, and the exact position of the error.

If you need access to those attributes (provided they are present), just use hasattr() to test first:

try:
    d = json.loads(a)
except ValueError as err:
    pos = (None, None)
    if hasattr(err, lineno):
        # JSONDecodeError subclass
        pos = err.lineno, err.colno


问:
Pandas Error Matching String
I have data like the SampleDf data below.  I'm trying to check values in one column in my dataframe to see if they contain 'sum' or 'count' or 'Avg' and then create a new column with the value 'sum', 'count', or 'Avg'.  When I run the code below on my real dataframe I'm getting the error below.  When I run dtypes on my real dataframe it says all the columns are objects.  The code below is related to the post below.  Unfortunately I don't get the same errors when I run the code on the SampleDf I've provided, but I couldn't post my whole dataframe.

post:
Pandas and apply function to match a string

```<code>Code:

SampleDf=pd.DataFrame([['tom',"Avg(case when Value1 in ('Value2') and [DateType] in ('Value3') then LOS end)"],['bob',"isnull(Avg(case when XferToValue2 in (1) and DateType in ('Value3') and  [Value1] in ('HM') then  LOS end),0)"]],columns=['ReportField','OtherField'])

search1='Sum'
search2='Count'
search3='Avg'

def Agg_type(x):
    if search1 in x:
        return 'sum'
    elif search2 in x:
        return 'count'
    elif search3 in x:
        return 'Avg'
    else:
        return 'Other'

SampleDf['AggType'] = SampleDf['OtherField'].apply(Agg_type)

SampleDf.head()

Error:

---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-17-a2b4920246a7> in <module>()
     17         return 'Other'
     18
---> 19 SampleDf['AggType'] = SampleDf['OtherField'].apply(Agg_type)
     20
     21 #SampleDf.head()

C:\Users\Name\AppData\Local\Continuum\Anaconda3\lib\site-packages\pandas\core\series.py in apply(self, func, convert_dtype, args, **kwds)
   2292             else:
   2293                 values = self.asobject
-> 2294                 mapped = lib.map_infer(values, f, convert=convert_dtype)
   2295
   2296         if len(mapped) and isinstance(mapped[0], Series):

pandas\src\inference.pyx in pandas.lib.map_infer (pandas\lib.c:66124)()

<ipython-input-17-a2b4920246a7> in Agg_type(x)
      8
      9 def Agg_type(x):
---> 10     if search1 in x:
     11         return 'sum'
     12     elif search2 in x:

TypeError: argument of type 'float' is not iterable
</code>```

答:
You can try this:

```<code>SampleDf['new_col'] = np.where(SampleDf.OtherField.str.contains("Avg"),"Avg",
                          np.where(SampleDf.OtherField.str.contains("Count"),"Count",
                                  np.where(SampleDf.OtherField.str.contains("Sum"),"Sum","Nothing")))
</code>```

please notice that this will work properly if you don't have both Avg and Count or Sum in the same string.

If you do, please notice me i'll look for a better approach.

Of course if something doesn't suit your needs also report it back.

Hope this was helpful

explanation:

what's happening is that you're looking for indexes where Avg is in the string inside OtherField column and fill new_col with "Avg" in these indexes. for the remaining fields( where there isn't "Avg", you look for Count and do the same and last you do the same for Sum.

documentation:

np.where

pandas.series.str.contains

Title: Pandas Error Matching String

Body:
I have data like the SampleDf data below.  I'm trying to check values in one column in my dataframe to see if they contain 'sum' or 'count' or 'Avg' and then create a new column with the value 'sum', 'count', or 'Avg'.  When I run the code below on my real dataframe I'm getting the error below.  When I run dtypes on my real dataframe it says all the columns are objects.  The code below is related to the post below.  Unfortunately I don't get the same errors when I run the code on the SampleDf I've provided, but I couldn't post my whole dataframe.

post:
Pandas and apply function to match a string

Code:

SampleDf=pd.DataFrame([['tom',"Avg(case when Value1 in ('Value2') and [DateType] in ('Value3') then LOS end)"],['bob',"isnull(Avg(case when XferToValue2 in (1) and DateType in ('Value3') and  [Value1] in ('HM') then  LOS end),0)"]],columns=['ReportField','OtherField'])

search1='Sum'
search2='Count'
search3='Avg'

def Agg_type(x):
    if search1 in x:
        return 'sum'
    elif search2 in x:
        return 'count'
    elif search3 in x:
        return 'Avg'
    else:
        return 'Other'

SampleDf['AggType'] = SampleDf['OtherField'].apply(Agg_type)

SampleDf.head()

Error:

---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-17-a2b4920246a7> in <module>()
     17         return 'Other'
     18
---> 19 SampleDf['AggType'] = SampleDf['OtherField'].apply(Agg_type)
     20
     21 #SampleDf.head()

C:\Users\Name\AppData\Local\Continuum\Anaconda3\lib\site-packages\pandas\core\series.py in apply(self, func, convert_dtype, args, **kwds)
   2292             else:
   2293                 values = self.asobject
-> 2294                 mapped = lib.map_infer(values, f, convert=convert_dtype)
   2295
   2296         if len(mapped) and isinstance(mapped[0], Series):

pandas\src\inference.pyx in pandas.lib.map_infer (pandas\lib.c:66124)()

<ipython-input-17-a2b4920246a7> in Agg_type(x)
      8
      9 def Agg_type(x):
---> 10     if search1 in x:
     11         return 'sum'
     12     elif search2 in x:

TypeError: argument of type 'float' is not iterable

Body:
You can try this:

SampleDf['new_col'] = np.where(SampleDf.OtherField.str.contains("Avg"),"Avg",
                          np.where(SampleDf.OtherField.str.contains("Count"),"Count",
                                  np.where(SampleDf.OtherField.str.contains("Sum"),"Sum","Nothing")))

please notice that this will work properly if you don't have both Avg and Count or Sum in the same string.

If you do, please notice me i'll look for a better approach.

Of course if something doesn't suit your needs also report it back.

Hope this was helpful

explanation:

what's happening is that you're looking for indexes where Avg is in the string inside OtherField column and fill new_col with "Avg" in these indexes. for the remaining fields( where there isn't "Avg", you look for Count and do the same and last you do the same for Sum.

documentation:

np.where

pandas.series.str.contains


问:
moving items of list up and down
Let's say we have a list of items. And, we want to allow users to control their order by clicking (down-arrow) to lower the order of item one level. And, doing the same to set the order one level higher.

views.py

```<code>def item_up(request, item_id):
    item = get_object_or_404(Item, id=item_id)
    swap_order = item.order - 1
    swap = get_object_or_404(Item, order=swap_order)
    item.order += 1000
    item.save()
    swap.order += 1
    item.order -= 1001
    swap.save()
    item.save()
    return redirect(request.META['HTTP_REFERER'])

def item_down(request, item_id):
    item = get_object_or_404(Item, id=item_id)
    swap_order = item.order + 1
    swap = get_object_or_404(Item, order=swap_order)
    item.order -= 1000
    item.save()
    swap.order -= 1
    item.order += 1001
    swap.save()
    item.save()
    return redirect(request.META['HTTP_REFERER'])
</code>```

this way is working except when I have only two items it shows me an error.

```<code>No Item matches the given query.
</code>```

Any Idea?

答:
You are probably passing an ID, which does not exist in the database, or the logic of the swap_order was wrong.

This message error is raised when the object does not exist (or not found).

https://docs.djangoproject.com/en/1.11/_modules/django/shortcuts/#get_object_or_404

Title: moving items of list up and down

Body:
Let's say we have a list of items. And, we want to allow users to control their order by clicking (down-arrow) to lower the order of item one level. And, doing the same to set the order one level higher.

views.py

def item_up(request, item_id):
    item = get_object_or_404(Item, id=item_id)
    swap_order = item.order - 1
    swap = get_object_or_404(Item, order=swap_order)
    item.order += 1000
    item.save()
    swap.order += 1
    item.order -= 1001
    swap.save()
    item.save()
    return redirect(request.META['HTTP_REFERER'])

def item_down(request, item_id):
    item = get_object_or_404(Item, id=item_id)
    swap_order = item.order + 1
    swap = get_object_or_404(Item, order=swap_order)
    item.order -= 1000
    item.save()
    swap.order -= 1
    item.order += 1001
    swap.save()
    item.save()
    return redirect(request.META['HTTP_REFERER'])

this way is working except when I have only two items it shows me an error.

No Item matches the given query.

Any Idea?


问:
access firebase data id within push
complete noob here.

Trying to retrieve the firebase unique id from the first data push to use in the second so that I can reference the data between the two data sets. I used stackoverflow answers to retrieve the key, but my code didnt work.

(If you have a better way of referencing the two items other than utilizing firebase unique id, Im all for it!)  thanks!!

```<code>export const GROUP_CREATE = 'group_create';
export const groupCreate = ({ name, course, members }) => {
  const { currentUser } = firebase.auth();

  return (dispatch) => {
    var pushedRef = firebase.database().ref(`/groups`).push({ name })
    var dataId = pushedRef.key
      .then(
        firebase.database().ref('/groups')
          .push({ name, dataId, course, members }))
      .then(() => {
        dispatch({ type: GROUP_CREATE });
        Actions.groupMain({ type: 'reset' });
      });
  };
};
</code>```

答:
I figured it out!</p>

```<code>export const GROUP_CREATE = 'group_create';
export const groupCreate = ({ name, course, members }) => {
  const { currentUser } = firebase.auth();
  var myRef = firebase.database().ref('/groups').push();
  var groupId = myRef.key;

  return (dispatch) => {
    myRef.push({ name, course, members })
      .then(
        firebase.database().ref(`/users/${currentUser.uid}/groups`)
          .push({ name, groupId }))
      .then(() => {
        dispatch({ type: GROUP_CREATE });
        Actions.groupMain({ type: 'reset' });
      });
  };
};
</code>```

Title: access firebase data id within push

Body:
complete noob here.

Trying to retrieve the firebase unique id from the first data push to use in the second so that I can reference the data between the two data sets. I used stackoverflow answers to retrieve the key, but my code didnt work.

(If you have a better way of referencing the two items other than utilizing firebase unique id, Im all for it!)  thanks!!

export const GROUP_CREATE = 'group_create';
export const groupCreate = ({ name, course, members }) => {
  const { currentUser } = firebase.auth();

  return (dispatch) => {
    var pushedRef = firebase.database().ref(`/groups`).push({ name })
    var dataId = pushedRef.key
      .then(
        firebase.database().ref('/groups')
          .push({ name, dataId, course, members }))
      .then(() => {
        dispatch({ type: GROUP_CREATE });
        Actions.groupMain({ type: 'reset' });
      });
  };
};

Body:
I figured it out!

export const GROUP_CREATE = 'group_create';
export const groupCreate = ({ name, course, members }) => {
  const { currentUser } = firebase.auth();
  var myRef = firebase.database().ref('/groups').push();
  var groupId = myRef.key;

  return (dispatch) => {
    myRef.push({ name, course, members })
      .then(
        firebase.database().ref(`/users/${currentUser.uid}/groups`)
          .push({ name, groupId }))
      .then(() => {
        dispatch({ type: GROUP_CREATE });
        Actions.groupMain({ type: 'reset' });
      });
  };
};


问:
Method validation Hibernate
I am using Spring Boot + Hibernate + Kotlin.

What I am trying to do is the following:

I have a Question object with a questionTime and an answerTime (see code below). I want to constraint that the answerTime is always longer than or equal to the questionTime. I want this constrainted at the database level. How can I do this? The only thing I would want is database independent.

```<code>@Entity
@Table(name = "question")
class Question(
        @Id @GeneratedValue(strategy = GenerationType.AUTO)
        @Column(updatable = false, nullable = false)
        var id: Long,
        @Column(name = "question_time")
        @ColumnDefault(value = "-1")
        var questionTime: Int = -1,
        @Column(name = "answer_time")
        @ColumnDefault(value = "-1")
        var answerTime: Int = -1

)
</code>```

答:
If you need support db constraints for entity you can use @Check annotation.

```<code>    @Check("name_db_constraint")
    @Column(name = "answer_time")
    @ColumnDefault(value = "-1")
    var answerTime: Int = -1
</code>```

If you need to have same constraint from server side use Validation framework, you can create constraint with extension

Title: Method validation Hibernate

Body:
I am using Spring Boot + Hibernate + Kotlin.

What I am trying to do is the following:

I have a Question object with a questionTime and an answerTime (see code below). I want to constraint that the answerTime is always longer than or equal to the questionTime. I want this constrainted at the database level. How can I do this? The only thing I would want is database independent.

@Entity
@Table(name = "question")
class Question(
        @Id @GeneratedValue(strategy = GenerationType.AUTO)
        @Column(updatable = false, nullable = false)
        var id: Long,
        @Column(name = "question_time")
        @ColumnDefault(value = "-1")
        var questionTime: Int = -1,
        @Column(name = "answer_time")
        @ColumnDefault(value = "-1")
        var answerTime: Int = -1

)

Body:
If you need support db constraints for entity you can use @Check annotation.

    @Check("name_db_constraint")
    @Column(name = "answer_time")
    @ColumnDefault(value = "-1")
    var answerTime: Int = -1

If you need to have same constraint from server side use Validation framework, you can create constraint with extension


问:
404 Error on azure website
We have setup a AppService based website in Azure (using Node.js) in the "F1 Free" Tier. Very often when we browse to a JSON file in the site, we get a 404 not found error. But, when we hit refresh in the browser, it loads.

Why is this happening and how to fix this?

Is this a symptom of a larger issue we should be aware of?

答:
Not much to go on, in your question, but... from a "happens very often" perspective:

App Service Free tier is going to have frequent app pool recycling after inactivity. So, after (I believe) 20 minutes, your app is being recycled, and your first hit will likely be delayed (or hit a timeout).

You'd have to use a paid tier to enable "always on."

Title: 404 Error on azure website


问:
Port 465 cannot send email
I set up account in google compute engine, and I use go daddy smtp
smtpout.asia.secureserver.net , this works fine in my localhost but in GCE it will threw error Connection could not be established with host smtpout.asia.secureserver.net [Connection timed out #110] ...is port 465 with option 'ssl' is block ? ...how to enable this 465 'ssl' in GCE ?

EDIT
465 works fine if I use gmail account...but why using other smtp is not working ?

Thank you in advance.

答:
TL;DR - Google Compute Engine blocks all outbound connections on ports 25, 465 and 587.

Using standard outbound email ports on Google Compute Engine

Yattin's answer is incorrect regarding Google Compute Engine (it only answers how to send mail using gmail).

Google Compute Engine blocks all outbound connections on ports 25, 465 and 587 for the sake of protection against spam and abuse. The only exceptions are for outbound connections to Google's mail services like GMail or Google Apps.

Options for outbound email on Google Compute Engine

Use a trusted third-party mail provider like SendGrid, Mailgun or Mailjet.

Use GMail account to send the messages. This is what you tried already based on what you have mentioned in your question.

Use Google Apps SMTP relay service if you have a Google Apps account.

If you already have a corporate email server and you have a VPN connection to that from your Google Compute Engine instances, you can tunnel the mail traffic to your corporate email server and let it handle the mail delivery.

Title: Port 465 cannot send email


问:
Which type of path to store in MySQL database?
When I come to build a simple site using PHP and MySQL, what is the best method for storing paths of files and images?

Inserting paths to Mysql as (system path C:/----)

Inserting paths to Mysql as (HTTP path http://----)

答:
Always save file paths relative to your web sites directory. Consider your website's address is "foo.com" and you want to store images in "foo.com/images". It better to store images address without "http" and without "foo.com".

Therefore just save the filename and its subfolder if exists.


答:
For the json module in particular, which is basically simplejson packaged as json module and distributed with Python, you can use the latest (or at least the same) version of simplejson.

That way the exception in all versions of Python will be the same: JSONDecodeError.

Title: Handling different errors for different versions of python


问:
android InstantRun - Norton Security finds Trojan
A week ago Norton Security started to find Trojan horse (Trojan.Gen.NPE.2) in file R.class located:

app\build\intermediates\transforms\instantrun\debug\folders\1\5\main\android\support\v4\ r.class

and

app\build\intermediates\transforms\instantrunslicer\debug\folders\1\5\slice_2\android\support\v4\ r.class

Link to virustotal.com scan: https://www.virustotal.com/pl/file/282f4e09c102cd93c2f849c9fe9ed570188f5a03395ab84d2457a7c64d7acb1c/analysis/1499458308/

And the code:

```<code>package android.support.v4;

import com.android.tools.fd.runtime.IncrementalChange;
import com.android.tools.fd.runtime.InstantReloadException;

public final class R {
    public static final long serialVersionUID = 830508538663712626L;

    public R() {
        IncrementalChange var1 = $change;
        if(var1 != null) {
            Object[] var10001 = (Object[])var1.access$dispatch("init$args.([Landroid/support/v4/R;[Ljava/lang/Object;)Ljava/lang/Object;", new Object[]{null, new Object[0]});
            Object[] var2 = (Object[])var10001[0];
            this(var10001, (InstantReloadException)null);
            var2[0] = this;
            var1.access$dispatch("init$body.(Landroid/support/v4/R;[Ljava/lang/Object;)V", var2);
        } else {
            super();
        }
    }

    R(Object[] var1, InstantReloadException var2) {
        String var3 = (String)var1[1];
        switch(var3.hashCode()) {
        case -1968665286:
            super();
            return;
        case -71951640:
            this();
            return;
        default:
            throw new InstantReloadException(String.format("String switch could not find \'%s\' with hashcode %s in %s", new Object[]{var3, Integer.valueOf(var3.hashCode()), "android/support/v4/R"}));
        }
    }
}
</code>```

Is it false alarm?

答:
You can report this false positive to Symantec and have them fix it.

https://submit.symantec.com/false_positive/

Body:
A week ago Norton Security started to find Trojan horse (Trojan.Gen.NPE.2) in file R.class located:

app\build\intermediates\transforms\instantrun\debug\folders\1\5\main\android\support\v4\ r.class

and

app\build\intermediates\transforms\instantrunslicer\debug\folders\1\5\slice_2\android\support\v4\ r.class

Link to virustotal.com scan: https://www.virustotal.com/pl/file/282f4e09c102cd93c2f849c9fe9ed570188f5a03395ab84d2457a7c64d7acb1c/analysis/1499458308/

And the code:

package android.support.v4;

import com.android.tools.fd.runtime.IncrementalChange;
import com.android.tools.fd.runtime.InstantReloadException;

public final class R {
    public static final long serialVersionUID = 830508538663712626L;

    public R() {
        IncrementalChange var1 = $change;
        if(var1 != null) {
            Object[] var10001 = (Object[])var1.access$dispatch("init$args.([Landroid/support/v4/R;[Ljava/lang/Object;)Ljava/lang/Object;", new Object[]{null, new Object[0]});
            Object[] var2 = (Object[])var10001[0];
            this(var10001, (InstantReloadException)null);
            var2[0] = this;
            var1.access$dispatch("init$body.(Landroid/support/v4/R;[Ljava/lang/Object;)V", var2);
        } else {
            super();
        }
    }

    R(Object[] var1, InstantReloadException var2) {
        String var3 = (String)var1[1];
        switch(var3.hashCode()) {
        case -1968665286:
            super();
            return;
        case -71951640:
            this();
            return;
        default:
            throw new InstantReloadException(String.format("String switch could not find \'%s\' with hashcode %s in %s", new Object[]{var3, Integer.valueOf(var3.hashCode()), "android/support/v4/R"}));
        }
    }
}

Is it false alarm?


问:
JavaScript error when function called in JavaScript, not when called in HTML
So I had an idea to let the computer guess the number with JavaScript as code language. I know exactly what it must do, but it isn't doing it. The idea is (to see if it works) to get a random number between 1 and 100, when you open the webpage. Weird thing, is that if I call the function in the same JavaScript file it gives an error, but if I call the function with a HTML button, it's working totally fine! The F12-console gives the following error:

Unable to set property 'innerHTML' of undefined or null reference

I have the following code:

var guessTheNumber = function() {

// var number = prompt("Tell me a number between 1 and 100.");
var x = document.getElementById("JS1");

x.innerHTML = Math.floor((Math.random() * 100) + 1);
}

guessTheNumber();```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html>
<head>
 <title>JS test</title>

 <script type="text/javascript" src="JavaScript.js"></script>
</head>
<body>
 <button onclick="guessTheNumber()"></button>
 <p class="test">test</p>
 <p id="JS1"></p>
</body>
</html></code>```

I tried Microsoft Edge and Google Chrome as browsers, no results. I do not know what I am doing wrong, so any help is appreciated!

答:
```<code><script>
// self executing function here
var guessTheNumber = function() {

    // var number = prompt("Tell me a number between 1 and 100.");
    var x = document.getElementById("JS1");

    x.innerHTML = Math.floor((Math.random() * 100) + 1);
}
(function() {

   // your page initialization code here
   // the DOM will be available here
   guessTheNumber();
})();
</script>
</code>```

You have to wait until the dom is ready.

Also never declare your script in the head move your script tag below body.

Body:
So I had an idea to let the computer guess the number with JavaScript as code language. I know exactly what it must do, but it isn't doing it. The idea is (to see if it works) to get a random number between 1 and 100, when you open the webpage. Weird thing, is that if I call the function in the same JavaScript file it gives an error, but if I call the function with a HTML button, it's working totally fine! The F12-console gives the following error:

Unable to set property 'innerHTML' of undefined or null reference

I have the following code:

var guessTheNumber = function() {

// var number = prompt("Tell me a number between 1 and 100.");
var x = document.getElementById("JS1");

x.innerHTML = Math.floor((Math.random() * 100) + 1);
}

guessTheNumber();

<!DOCTYPE html>

 <title>JS test</title>

 <button onclick="guessTheNumber()"></button>

test

I tried Microsoft Edge and Google Chrome as browsers, no results. I do not know what I am doing wrong, so any help is appreciated!

Body:
<script>
// self executing function here
var guessTheNumber = function() {

    // var number = prompt("Tell me a number between 1 and 100.");
    var x = document.getElementById("JS1");

    x.innerHTML = Math.floor((Math.random() * 100) + 1);
}
(function() {

   // your page initialization code here
   // the DOM will be available here
   guessTheNumber();
})();
</script>

You have to wait until the dom is ready.

Also never declare your script in the head move your script tag below body.


问:
Is it a solvable problem to generate a regular expression that matches some input set?
I provide some input set which contains known separated number of text blocks.

I want to make a program that automatically generate 1 or more regular expressions each of which matches every text block in the input set.

I see some relatively easy ways to implement a brute-force search. But I'm not an expert in compilers theory. That's why I'm curious:

1) is this problem solvable? or there are some principle impossibility to make such algorithm?

2) is it possible to achieve polynomial complexity for this algorithm and avoid brute forcing?

答: http://txt2re.com/ might be what you want.</p>


问:
How to make an Approval step in Azure Logic app calling my own APIs similar to office365 approval connector?
I wanna build a small workflow using Azure Logic Apps that contains an "Approval" step, which is simply an API call in my own system, similar to office 365 approval connector.

However, from what I found on the internet, the only way to make a long running task in Azure Logic Apps is to use Webhooks.

In Webhooks, I could not set a value to the parameter I created "Bool-Approved".. so, How can I check it later in a condition step?

The other possible solution maybe is to use Swagger to have an "Bool-Approved" parameter. However, it does not support long running action!

What's the possible solution for me?

答: make you api return HTTP code 200 if the response if "ok" and 400 if the response is "not ok". This way you can force logic app to behave the way you need it to behave..</p>


问:
Volatile keyword in multicore vs single processor?
I have heard many people saying that volatile keyword makes more sense in multicore processor
than single core processor but don't know the reason. I tried to google but did not help in
this aspect. Any reason for it?

As per my understanding volatile keyword should have equal importance whether it is multicore vs single processor.
Reason is with volatile , its guaranteed that value will be updated in main memory (heap) instead of keeping
it in thread local memory(stack) which can be seen by all threads. So whether its multicore or single processor,
how does it makes difference?

答:
As per my understanding volatile is not relevant in single core. Volatile variable updates are pushed/read from main memory which is important in a multi-core architecture where each core can have its own cache, hence an update in a particular core's cache may not be visible for other threads running on a different core.

However if you have a single core, then when you update a variable which is not volatile, if it gets updated in the core's cache without being pushed to main memory this may be fine because all the other threads run on the same core hence will see the latest value available in the cache that they all share. So you dont need a volatile there.


问:
Using DEFAULT_GUI_FONT in high DPI Windows application
I have a Windows application which I want to look good at high DPI monitors. The application is using DEFAULT_GUI_FONT in lots of places, and the font created this way doesn't scale correctly.

Is there any simple way to fix this problem with not too much pain?

答:
The recommended fonts for different purposes can be obtained from the NONCLIENTMETRICS structure.

For automatically DPI-scaled fonts (Windows 10 1607+, must be per-monitor DPI-aware):

```<code>// Your window's handle
HWND window;

// Get the DPI for which your window should scale to
UINT dpi = GetDpiForWindow(window);

// Obtain the recommended fonts, which are already correctly scaled for the current DPI
NONCLIENTMETRICSW non_client_metrics;

if (!SystemParametersInfoForDpi(SPI_GETNONCLIENTMETRICS, sizeof(non_client_metrics), &non_client_metrics, 0, dpi)
{
    // Error handling
}

// Create an appropriate font(s)
HFONT message_font = CreateFontIndirectW(&non_client_metrics.lfMessageFont);

if (!message_font)
{
    // Error handling
}
</code>```

For older Windows versions you can use the system-wide DPI and scale the font manually (Windows 7+, must be system DPI-aware):

```<code>// Your window's handle
HWND window;

// Obtain the recommended fonts, which are already correctly scaled for the current DPI
NONCLIENTMETRICSW non_client_metrics;

if (!SystemParametersInfoW(SPI_GETNONCLIENTMETRICS, sizeof(non_client_metrics), &non_client_metrics, 0)
{
    // Error handling
}

// Get the system-wide DPI
HDC hdc = GetDC(nullptr);

if (!hdc)
{
    // Error handling
}

UINT dpi = GetDeviceCaps(hdc, LOGPIXELSY);

ReleaseDC(nullptr, hdc);

// Scale the font(s)
constexpr UINT font_size = 12;

non_client_metrics.lfMessageFont.lfHeight = -((font_size * dpi) / 72);

// Create the appropriate font(s)
HFONT message_font = CreateFontIndirectW(&non_client_metrics.lfMessageFont);

if (!message_font)
{
    // Error handling
}
</code>```

NONCLIENTMETRICS has also many other fonts in it. Make sure to choose the right one for your purpose.

You should set the DPI-awareness level in your application manifest as described here for best compatibility.

Body:
The recommended fonts for different purposes can be obtained from the NONCLIENTMETRICS structure.

For automatically DPI-scaled fonts (Windows 10 1607+, must be per-monitor DPI-aware):

// Your window's handle
HWND window;

// Get the DPI for which your window should scale to
UINT dpi = GetDpiForWindow(window);

// Obtain the recommended fonts, which are already correctly scaled for the current DPI
NONCLIENTMETRICSW non_client_metrics;

if (!SystemParametersInfoForDpi(SPI_GETNONCLIENTMETRICS, sizeof(non_client_metrics), &non_client_metrics, 0, dpi)
{
    // Error handling
}

// Create an appropriate font(s)
HFONT message_font = CreateFontIndirectW(&non_client_metrics.lfMessageFont);

if (!message_font)
{
    // Error handling
}

For older Windows versions you can use the system-wide DPI and scale the font manually (Windows 7+, must be system DPI-aware):

// Your window's handle
HWND window;

// Obtain the recommended fonts, which are already correctly scaled for the current DPI
NONCLIENTMETRICSW non_client_metrics;

if (!SystemParametersInfoW(SPI_GETNONCLIENTMETRICS, sizeof(non_client_metrics), &non_client_metrics, 0)
{
    // Error handling
}

// Get the system-wide DPI
HDC hdc = GetDC(nullptr);

if (!hdc)
{
    // Error handling
}

UINT dpi = GetDeviceCaps(hdc, LOGPIXELSY);

ReleaseDC(nullptr, hdc);

// Scale the font(s)
constexpr UINT font_size = 12;

non_client_metrics.lfMessageFont.lfHeight = -((font_size * dpi) / 72);

// Create the appropriate font(s)
HFONT message_font = CreateFontIndirectW(&non_client_metrics.lfMessageFont);

if (!message_font)
{
    // Error handling
}

NONCLIENTMETRICS has also many other fonts in it. Make sure to choose the right one for your purpose.

You should set the DPI-awareness level in your application manifest as described here for best compatibility.


问:
Do I need to duplicate code on every EC2 instance running behind an ELB?
Hi this is a very noob question, but I am trying to deply my Node JS API server on AWS.
Everything is working fine with one m1.large instance that my Front End running on S3 connects to.
Now I want to Scale and put my EC2 instance and possibly many more behing and ELB and an Auto Scaling Group.
Do I need to duplicate my server code on every EC2 instance?
If so , I assume I'll have to create a seperate DB server which all of the EC2 instances will connect to.
Am I right,anyone experienced in Amazon AWS can answer this, I tried googling but most of the links point to detailed tutorials which however don't answer my question.
Any help would be much appreciated. Thanks </p>

答:
Of course NOT.. But sure you can do..
That's why there are EFS volumes, which are shared volumes to more than one EC2 instance, but you have to choose a region that support them since they are available on certain regions. As a candidate AWS certified architect I would recommend you more than two options.

You can follow your first approach and create an EC2 instance put your code inside and then create an AMI and use this AMI to launch your upcoming EC2s through autoscaling group. In my opinion bad decision since on any code change you have to go on each one and put the new code and then create a new AMI and a new Auto scaling configuration..Lot's of stuff to do, but it will work.

Second approach, following the first approach but do not create an AMI, instead upload your code on a private (I suppose) Repo like github, bitbucket, install SSM and the appropriate roles for managing EC2 and on every code changes push them to repo and pull them on your EC2, using SSM. Of course you may write a webhook to bitbucket to call an api and run the git pull command on each EC2. Probably the last sentence could be a third approach but needs more coding!!!

Last but not least!! Use an EFS volume put your code there, mount this volume on your EC2, add a auto mount command on every boot, alter your apache httpd main document to point on this EFS/folder and create an AMI with this configuration. Voila! every new EC2 will use the same code which located on this shared/network volume. Whenever you need to change something you have to log in on a third instance outside of your autoscaling group for a certain amount of time upload your changes and then turn it off and all of your EC2 will take immediately the new code. Of course you may pull the changes from a repo following the third approach.

Maybe there are more approaches, I'm using the third one with private repos of course and until now I haven't faced any problem (Fingers crossed)!


问:
Difference between is X and is X _
Before C# 7.0, the following code was valid:

```<code>if(x is X)
{
    //...
}
</code>```

Now, the following is also valid:

```<code>if(x is X _)
{
    //...
}
</code>```

Accoding to TryRoslyn, those code sections generates the same IL. My question is: what's the purpose of the discard operator in pattern matching, if it is not necessary neither useful? Am I missing something here?

This question is not the same as that one, since I'm asking the purpose of the discard operator (wildcard) specifically for the pattern matching (is operator).

答:
This is not useful yet. But when recursive pattern matching is introduced (hopefully in C# 8.0), it will be useful to have discards in part of the pattern.

The details are not finalized, but imagine something like is (1, (_, 3)) or possibly is X (1, Y (_, 3)).

Title: Difference between is X and is X _

Body:
Before C# 7.0, the following code was valid:

if(x is X)
{
    //...
}

Now, the following is also valid:

if(x is X _)
{
    //...
}

Accoding to TryRoslyn, those code sections generates the same IL. My question is: what's the purpose of the discard operator in pattern matching, if it is not necessary neither useful? Am I missing something here?

This question is not the same as that one, since I'm asking the purpose of the discard operator (wildcard) specifically for the pattern matching (is operator).


答:
The problem is that the javascript file is loaded BEFORE the DOM, so the document.getElementById("JS1"); would be undefined.

To easily fix this, load the

```

Title: JavaScript error when function called in JavaScript, not when called in HTML

Body:
The problem is that the javascript file is loaded BEFORE the DOM, so the document.getElementById("JS1"); would be undefined.

To easily fix this, load the <script> at the BOTTOM of the <body> tag:

<!DOCTYPE html>
<html>
<head>
    <title>JS test</title>

</head>
<body>
    <button onclick="guessTheNumber()"></button>
    <p class="test">test</p>
    <p id="JS1"></p>

<script type="text/javascript" src="JavaScript.js"></script>
</body>
</html>


问:
Was the "Developer pack" originally called SDK?
Quick question - is what Microsoft now calls the "Microsoft .NET Framework 4.5.2 Developer Pack" what was historically called the SDK?</p>

答:
Just a piece of history for reference.

When .NET Framework was 1.0 and 1.1, you need to have the .NET Framework SDK installed, so as to perform most command line tasks. That was how things got started.

.NET Framework 2.0 followed that tradition, has an SDK of its own. Later, Microsoft decided to merge .NET Framework SDK into Windows SDK.

You can find out such information by reading SharpDevelop's documentation on what are the dependencies. As a third party IDE, it always tells which are needed to build a project by assembling Microsoft's installers.

Recently .NET Framework has been updated more frequently, so Microsoft decided to ship Developer Pack as separate downloads. Like Hans Passant explained, this design is more closely related to Visual Studio compilation (referenced assemblies). It is more like a reorganization of different tools and utilities,

Compilers, are now part of the .NET Framework installation (and also individual downloads from GitHub Roslyn repo).

MSBuild, is now separate downloads (MSBuild from VS2015/2017).

Developer Packs, provides referenced assemblies and others.