问:
How to scroll down with sikuli
How to scroll down with Sikuli in Selenium Eebdriver with java?

I am using screen.wheel(1 , 8); in my code to scroll down in an open window.

Sometimes it works fine but after running my script 4-5 times it behaves differently. Instead of scrolling vertically it starts scrolling horizontally.

```<code>s.doubleClick("C:\\SikuliX\\Images\\C_Drive.png");
s.wheel( 1, 8);
s.doubleClick("C:\\SikuliX\\Images\\DestinFolder.png");
s.doubleClick("C:\\SikuliX\\Images\\CfgFolder.png")
</code>```

Please help and let me know how I can move the scrollbar vertically for specific steps and in particular window.

答:
Personally I like clicking the scrollbars Down Arrow in a For Loop until an image is found to indicate we've scrolled down far enough.

Ref: https://answers.launchpad.net/sikuli/+faq/1437

```<code># --- this loops forever
while True:
   if not exists(img, 0):
      break # but ends if img gets visible
   else:
      pass # we will see
   wait(5) # check every 5 seconds
print img, "finally came up"

# --- this loops as long as img is visible
</code>```

Title: How to scroll down with sikuli

Body:
How to scroll down with Sikuli in Selenium Eebdriver with java?

I am using screen.wheel(1 , 8); in my code to scroll down in an open window.

Sometimes it works fine but after running my script 4-5 times it behaves differently. Instead of scrolling vertically it starts scrolling horizontally.

s.doubleClick("C:\\SikuliX\\Images\\C_Drive.png");
s.wheel( 1, 8);
s.doubleClick("C:\\SikuliX\\Images\\DestinFolder.png");
s.doubleClick("C:\\SikuliX\\Images\\CfgFolder.png")

Please help and let me know how I can move the scrollbar vertically for specific steps and in particular window.

Body:
Personally I like clicking the scrollbars Down Arrow in a For Loop until an image is found to indicate we've scrolled down far enough.

Ref: https://answers.launchpad.net/sikuli/+faq/1437

# --- this loops forever
while True:
   if not exists(img, 0):
      break # but ends if img gets visible
   else:
      pass # we will see
   wait(5) # check every 5 seconds
print img, "finally came up"

# --- this loops as long as img is visible


来源: stackexchange

问:
Gradle issue with Android Studio 2.3.3
I am getting the following error:
"

The SDK platform tools version (25.0.6) is too old to check APIs
  compiled with API 26; please update This check scans through all
  ANDroid API calls in the application and  warns about any calls that
  are not available on all versions targeted by the application
  (according to its minimum SDK attribute in the manifest). If you
  really want to use this API and don’t need to support older devices
  just set the minSdkVersion in the build.gradle or AndroidManifest.xml
  files If your code is deliberately accessing newer APIs and you have
  ensured (e.g. with conditional execution) that this code will only
  ever be called on a supported platform, then you can annotate you
  class or method with the @TargetApi annotation specifying the local
  minimum SDK to Apply, such as @TargetApi(11), such that this check
  considers 11 rather than you manifest file’s minimum SDK as the
  required API level.   If you are deliberately setting android:
  attributes in style definitions, make sure you place this in
  values-xxx folder in order to avoid running into runtime conflicts on
  certain devices where manufacturers have added custom attributes whose
  ids conflict with new ones or later platforms. Similarly, you can use
  tooltargetApi=”11” in an XML file to indicate that the elements will
  only be inflated in an adequate context."

I also get the package name up top as an error, but I just created the new App and even though it indicates an error. The source code compiles and runs on the emulator on the targeted device.

答:
Go to your App Level Gradle file and enter the following:

apply plugin: 'com.android.application'

android {
  compileSdkVersion 26
  buildToolsVersion '26.0.0'

  defaultConfig {
    applicationId ">>>YOURPACKAGENAME<<<"
    minSdkVersion 16
    targetSdkVersion 26
    versionCode 1
    versionName "1.0"
  }
  buildTypes {
    release {
      minifyEnabled false
      proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
    }
  }
}```

ContentLicense: CC BY-SA 3.0

Title: Gradle issue with Android Studio 2.3.3


问:
c# string to class from which I can call functions
on initialize a class by string variable in c#? I already found out how to create an class using a string

so what I already have is:

```<code>Type type = Type.GetType("project.start");
var class = Activator.CreateInstance(type);
</code>```

what I want to do is call a function on this class for example:

```<code>class.foo();
</code>```

is this possible? and if it is how?

答:
If you can assume that the class implements an interface or base class that exposes a Foo method, then cast the class as appropriate.

```<code>public interface IFoo
{
   void Foo();
}
</code>```

then in your calling code you can do:

```<code>var yourType = Type.GetType("project.start");
var yourObject = (IFoo)Activator.CreateInstance(yourType);

yourType.Foo();
</code>```

ContentLicense: CC BY-SA 4.0

Body:
on initialize a class by string variable in c#? I already found out how to create an class using a string

so what I already have is:

Type type = Type.GetType("project.start");
var class = Activator.CreateInstance(type);

what I want to do is call a function on this class for example:

class.foo();

is this possible? and if it is how?

Body:
If you can assume that the class implements an interface or base class that exposes a Foo method, then cast the class as appropriate.

public interface IFoo
{
   void Foo();
}

then in your calling code you can do:

var yourType = Type.GetType("project.start");
var yourObject = (IFoo)Activator.CreateInstance(yourType);

yourType.Foo();

ContentLicense: CC BY-SA 2.5


问:
Scoring predictions in sklearn (Python machine learning)
I'm going through the following IPython Notebook which analyzes the Iris dataset

At one point in the notebook the author builds the following model:

At this point, I became very confused. What is going on in the last line?
From what I learned, you should create a prediction based on the model and then compare that prediction to the y_test values.

I would have done the following:

```<code>predictions = decision_tree_classifier.predict(X_test)
from sklearn.metrics import classification_report
print classification_report(y_test, predictions)
</code>```

What is going on when the author generates a score based on the testing_inputs and the testing_classes?

答:
Adding a bit of detail to @Coldspeed's answer, the score for DecisionTreeClassifier calls sklearn.metrics.accuracy_score.  This is the percentage of classifications made correctly.  Only pointing this out because I don't find "mean accuracy" all that intuitive.

```<code>from sklearn.metrics import accuracy_score
y_pred = [0, 2, 1, 3]
y_true = [0, 1, 2, 3]

accuracy_score(y_true, y_pred)
Out[106]: 0.5
</code>```

Body:
I'm going through the following IPython Notebook which analyzes the Iris dataset

At one point in the notebook the author builds the following model:

At this point, I became very confused. What is going on in the last line?
From what I learned, you should create a prediction based on the model and then compare that prediction to the y_test values.

I would have done the following:

predictions = decision_tree_classifier.predict(X_test)
from sklearn.metrics import classification_report
print classification_report(y_test, predictions)

What is going on when the author generates a score based on the testing_inputs and the testing_classes?

Body:
Adding a bit of detail to @Coldspeed's answer, the score for DecisionTreeClassifier calls sklearn.metrics.accuracy_score.  This is the percentage of classifications made correctly.  Only pointing this out because I don't find "mean accuracy" all that intuitive.

from sklearn.metrics import accuracy_score
y_pred = [0, 2, 1, 3]
y_true = [0, 1, 2, 3]

accuracy_score(y_true, y_pred)
Out[106]: 0.5


问:
JWT OpenIddict and ASP.Net Core 500 Internal Server Error
When I use Postman to try authentication I get an error. I trace it all the way through and it does the signin and succeeds but then fails returning the ticket.

The DEBUG log is as follows:

System.InvalidOperationException: No authentication handler is configured to handle the scheme: ASOS
   at Microsoft.AspNetCore.Http.Authentication.Internal.DefaultAuthenticationManager.<SignInAsync>d__14.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Microsoft.AspNetCore.Mvc.SignInResult.<ExecuteResultAsync>d__14.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.<InvokeResultAsync>d__30.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.<InvokeNextResultFilterAsync>d__28.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.Rethrow(ResultExecutedContext context)
   at Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.Next(State& next, Scope& scope, Object& state, Boolean& isCompleted)
   at Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.<InvokeNextResourceFilter>d__22.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.Rethrow(ResourceExecutedContext context)
   at Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.Next(State& next, Scope& scope, Object& state, Boolean& isCompleted)
   at Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.<InvokeAsync>d__20.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Microsoft.AspNetCore.Builder.RouterMiddleware.<Invoke>d__4.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Microsoft.AspNetCore.Authentication.AuthenticationMiddleware`1.<Invoke>d__18.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at Microsoft.AspNetCore.Authentication.AuthenticationMiddleware`1.<Invoke>d__18.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Microsoft.AspNetCore.Authentication.AuthenticationMiddleware`1.<Invoke>d__18.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at Microsoft.AspNetCore.Authentication.AuthenticationMiddleware`1.<Invoke>d__18.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Microsoft.AspNetCore.Authentication.AuthenticationMiddleware`1.<Invoke>d__18.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at Microsoft.AspNetCore.Authentication.AuthenticationMiddleware`1.<Invoke>d__18.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Microsoft.AspNetCore.Authentication.AuthenticationMiddleware`1.<Invoke>d__18.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at Microsoft.AspNetCore.Authentication.AuthenticationMiddleware`1.<Invoke>d__18.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Microsoft.AspNetCore.Authentication.AuthenticationMiddleware`1.<Invoke>d__18.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at Microsoft.AspNetCore.Authentication.AuthenticationMiddleware`1.<Invoke>d__18.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Microsoft.AspNetCore.Authentication.AuthenticationMiddleware`1.<Invoke>d__18.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at Microsoft.AspNetCore.Authentication.AuthenticationMiddleware`1.<Invoke>d__18.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Microsoft.AspNetCore.Cors.Infrastructure.CorsMiddleware.<Invoke>d__7.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.GetResult()
   at Angular2WebpackVisualStudio.Startup.<>c__DisplayClass5_0.<<Configure>b__0>d.MoveNext() in C:\Users\mhorton.NRH\Documents\Visual Studio 2017\Projects\AngularWebpackVisualStudio-master\src\AngularWebpackVisualStudio\Startup.cs:line 98
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Microsoft.AspNetCore.Server.IISIntegration.IISMiddleware.<Invoke>d__8.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Microsoft.AspNetCore.Hosting.Internal.RequestServicesContainerMiddleware.<Invoke>d__3.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Microsoft.AspNetCore.Server.Kestrel.Internal.Http.Frame`1.<RequestProcessingAsync>d__2.MoveNext()
Microsoft.AspNetCore.Hosting.Internal.WebHost:Information: Request finished in 1950.2099ms 500 ```
</div>
</div>
</p>

<p>And here is my Startup.cs. I think the error is in the Startup.cs and I freely admit I don't fully understand it all.</p>

<p>I am authenticating against an ASP.Net Identity Core SQL DB that is accessed via IdentityContext. During the trace the information from this DB is fine, so I am sure that part is working properly. I am intending to use OpenIddict to issue JWT Token using a self signed certificate and I want to use this token in an Angular4 app to access the API on the same server.</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code>using System;
using System.Linq;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Hosting;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Angular2WebpackVisualStudio.Repositories.Things;
using Angular2WebpackVisualStudio.Models;
using AngularWebpackVisualStudio.DBContexts;
using AngularWebpackVisualStudio.Models;
using Microsoft.AspNetCore.Identity.EntityFrameworkCore;
using System.Security.Cryptography.X509Certificates;
using Microsoft.AspNetCore.Identity;
using AngularWebpackVisualStudio.Shared;

namespace Angular2WebpackVisualStudio
{
    public class Startup
    {

        public Startup(IHostingEnvironment env)
        {
            var builder = new ConfigurationBuilder()
                .SetBasePath(env.ContentRootPath)
                .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
                .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true)
                .AddEnvironmentVariables();
            Configuration = builder.Build();
        }

        public IConfigurationRoot Configuration { get; }

        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddCors(options =>
            {
                options.AddPolicy("AllowAllOrigins",
                    builder =>
                    {
                        builder
                            .AllowAnyOrigin()
                            .AllowAnyHeader()
                            .AllowAnyMethod();
                    });
            });

            var jwtSigningCert = new X509Certificate2(@"C:\Program Files (x86)\Windows Kits\10\bin\10.0.15063.0\x64\SIWWW.pfx", "Test123");
            services.AddOpenIddict()
                .AllowAuthorizationCodeFlow()
                .AddEntityFrameworkCoreStores<IdentityContext>()
                .EnableTokenEndpoint("/oauth2/token")
                .EnableAuthorizationEndpoint("/connect/token")
                .UseJsonWebTokens()
                .AllowPasswordFlow()
                .DisableHttpsRequirement()
                .AddSigningCertificate(jwtSigningCert);

            services.AddMvc();

            services.AddDbContext<IdentityContext>(options =>
            {
                options.UseSqlServer(Configuration.GetSection("ConnectionStrings")["DefaultConnection"]);
                options.UseOpenIddict();
            });
            services.AddIdentity<ApplicationUser, IdentityRole>()
                .AddEntityFrameworkStores<IdentityContext>()
                .AddDefaultTokenProviders();

            services.AddScoped<IPasswordHasher<ApplicationUser>, SqlPasswordHasher>();

        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
        {
            loggerFactory.AddConsole(Configuration.GetSection("Logging"));
            loggerFactory.AddDebug();

            var angularRoutes = new[] {
                 "/home",
                 "/about",
                 "/contact",
                 "/login"
             };

            app.Use(async (context, next) =>
            {
                if (context.Request.Path.HasValue && null != angularRoutes.FirstOrDefault(
                    (ar) => context.Request.Path.Value.StartsWith(ar, StringComparison.OrdinalIgnoreCase)))
                {
                    context.Request.Path = new PathString("/");
                }

                await next();
            });

            app.UseCors("AllowAllOrigins");

            app.UseDefaultFiles();
            app.UseStaticFiles();
            app.UseIdentity();
            app.UseOAuthValidation();
            app.UseJwtBearerAuthentication(new JwtBearerOptions()
            {
                Audience = "414e1927a3884f68abc79f7283837fd1",
                Authority = "localhost:5000",
                AutomaticAuthenticate = true,
                RequireHttpsMetadata = false
            });

            app.UseMvc(routes =>
            {
                routes.MapRoute(
                    name: "default",
                    template: "{controller=Home}/{action=Index}/{id?}");
            });
        }
    }
}</code>```

Any help much appreciated.

答:
When I use Postman to try authentication I get an error. I trace it all the way through and it does the signin and succeeds but then fails returning the ticket.

You must add app.UseOpenIddict(); after app.UseIdentity(); (and necessarily before app.UseMvc();).

Body:
When I use Postman to try authentication I get an error. I trace it all the way through and it does the signin and succeeds but then fails returning the ticket.

The DEBUG log is as follows:

System.InvalidOperationException: No authentication handler is configured to handle the scheme: ASOS
   at Microsoft.AspNetCore.Http.Authentication.Internal.DefaultAuthenticationManager.<SignInAsync>d__14.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Microsoft.AspNetCore.Mvc.SignInResult.<ExecuteResultAsync>d__14.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.<InvokeResultAsync>d__30.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.<InvokeNextResultFilterAsync>d__28.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.Rethrow(ResultExecutedContext context)
   at Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.Next(State& next, Scope& scope, Object& state, Boolean& isCompleted)
   at Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.<InvokeNextResourceFilter>d__22.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.Rethrow(ResourceExecutedContext context)
   at Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.Next(State& next, Scope& scope, Object& state, Boolean& isCompleted)
   at Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.<InvokeAsync>d__20.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Microsoft.AspNetCore.Builder.RouterMiddleware.<Invoke>d__4.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Microsoft.AspNetCore.Authentication.AuthenticationMiddleware`1.<Invoke>d__18.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at Microsoft.AspNetCore.Authentication.AuthenticationMiddleware`1.<Invoke>d__18.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Microsoft.AspNetCore.Authentication.AuthenticationMiddleware`1.<Invoke>d__18.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at Microsoft.AspNetCore.Authentication.AuthenticationMiddleware`1.<Invoke>d__18.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Microsoft.AspNetCore.Authentication.AuthenticationMiddleware`1.<Invoke>d__18.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at Microsoft.AspNetCore.Authentication.AuthenticationMiddleware`1.<Invoke>d__18.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Microsoft.AspNetCore.Authentication.AuthenticationMiddleware`1.<Invoke>d__18.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at Microsoft.AspNetCore.Authentication.AuthenticationMiddleware`1.<Invoke>d__18.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Microsoft.AspNetCore.Authentication.AuthenticationMiddleware`1.<Invoke>d__18.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at Microsoft.AspNetCore.Authentication.AuthenticationMiddleware`1.<Invoke>d__18.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Microsoft.AspNetCore.Authentication.AuthenticationMiddleware`1.<Invoke>d__18.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at Microsoft.AspNetCore.Authentication.AuthenticationMiddleware`1.<Invoke>d__18.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Microsoft.AspNetCore.Cors.Infrastructure.CorsMiddleware.<Invoke>d__7.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.GetResult()
   at Angular2WebpackVisualStudio.Startup.<>c__DisplayClass5_0.<<Configure>b__0>d.MoveNext() in C:\Users\mhorton.NRH\Documents\Visual Studio 2017\Projects\AngularWebpackVisualStudio-master\src\AngularWebpackVisualStudio\Startup.cs:line 98
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Microsoft.AspNetCore.Server.IISIntegration.IISMiddleware.<Invoke>d__8.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Microsoft.AspNetCore.Hosting.Internal.RequestServicesContainerMiddleware.<Invoke>d__3.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Microsoft.AspNetCore.Server.Kestrel.Internal.Http.Frame`1.<RequestProcessingAsync>d__2.MoveNext()
Microsoft.AspNetCore.Hosting.Internal.WebHost:Information: Request finished in 1950.2099ms 500

And here is my Startup.cs. I think the error is in the Startup.cs and I freely admit I don't fully understand it all.

I am authenticating against an ASP.Net Identity Core SQL DB that is accessed via IdentityContext. During the trace the information from this DB is fine, so I am sure that part is working properly. I am intending to use OpenIddict to issue JWT Token using a self signed certificate and I want to use this token in an Angular4 app to access the API on the same server.

using System;
using System.Linq;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Hosting;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Angular2WebpackVisualStudio.Repositories.Things;
using Angular2WebpackVisualStudio.Models;
using AngularWebpackVisualStudio.DBContexts;
using AngularWebpackVisualStudio.Models;
using Microsoft.AspNetCore.Identity.EntityFrameworkCore;
using System.Security.Cryptography.X509Certificates;
using Microsoft.AspNetCore.Identity;
using AngularWebpackVisualStudio.Shared;

namespace Angular2WebpackVisualStudio
{
    public class Startup
    {

        public Startup(IHostingEnvironment env)
        {
            var builder = new ConfigurationBuilder()
                .SetBasePath(env.ContentRootPath)
                .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
                .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true)
                .AddEnvironmentVariables();
            Configuration = builder.Build();
        }

        public IConfigurationRoot Configuration { get; }

        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddCors(options =>
            {
                options.AddPolicy("AllowAllOrigins",
                    builder =>
                    {
                        builder
                            .AllowAnyOrigin()
                            .AllowAnyHeader()
                            .AllowAnyMethod();
                    });
            });

            var jwtSigningCert = new X509Certificate2(@"C:\Program Files (x86)\Windows Kits\10\bin\10.0.15063.0\x64\SIWWW.pfx", "Test123");
            services.AddOpenIddict()
                .AllowAuthorizationCodeFlow()
                .AddEntityFrameworkCoreStores<IdentityContext>()
                .EnableTokenEndpoint("/oauth2/token")
                .EnableAuthorizationEndpoint("/connect/token")
                .UseJsonWebTokens()
                .AllowPasswordFlow()
                .DisableHttpsRequirement()
                .AddSigningCertificate(jwtSigningCert);

            services.AddMvc();

            services.AddDbContext<IdentityContext>(options =>
            {
                options.UseSqlServer(Configuration.GetSection("ConnectionStrings")["DefaultConnection"]);
                options.UseOpenIddict();
            });
            services.AddIdentity<ApplicationUser, IdentityRole>()
                .AddEntityFrameworkStores<IdentityContext>()
                .AddDefaultTokenProviders();

            services.AddScoped<IPasswordHasher<ApplicationUser>, SqlPasswordHasher>();

        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
        {
            loggerFactory.AddConsole(Configuration.GetSection("Logging"));
            loggerFactory.AddDebug();

            var angularRoutes = new[] {
                 "/home",
                 "/about",
                 "/contact",
                 "/login"
             };

            app.Use(async (context, next) =>
            {
                if (context.Request.Path.HasValue && null != angularRoutes.FirstOrDefault(
                    (ar) => context.Request.Path.Value.StartsWith(ar, StringComparison.OrdinalIgnoreCase)))
                {
                    context.Request.Path = new PathString("/");
                }

                await next();
            });

            app.UseCors("AllowAllOrigins");

            app.UseDefaultFiles();
            app.UseStaticFiles();
            app.UseIdentity();
            app.UseOAuthValidation();
            app.UseJwtBearerAuthentication(new JwtBearerOptions()
            {
                Audience = "414e1927a3884f68abc79f7283837fd1",
                Authority = "localhost:5000",
                AutomaticAuthenticate = true,
                RequireHttpsMetadata = false
            });

            app.UseMvc(routes =>
            {
                routes.MapRoute(
                    name: "default",
                    template: "{controller=Home}/{action=Index}/{id?}");
            });
        }
    }
}

Any help much appreciated.


问:
Uploading a file from Google Cloud Storage to Bigquery using Python
I am having trouble writing a python script that loads or exports a file from google cloud storage to google bigquery.

```<code>#standardSQL
import json
import argparse
import time
import uuid

from google.cloud import bigquery
from google.cloud import storage

dataset = 'dataworks-356fa'
source = 'gs://dataworks-356fa-backups/pullnupload.json'

# def load_data_from_gcs(dataset, source):
# #     load_data_from_gcs(dataworks-356fa, 'test10', gs://dataworks-356fa-backups/pullnupload.json):
#     bigquery_client = bigquery.Client('dataworks-356fa')
#     dataset = bigquery_client.dataset(FirebaseArchive)
#     table = dataset.table(test10)
#     job_name = str(uuid.uuid4())
#
#     job = bigquery_client.load_table_from_storage(
#         job_name, test10, 'gs://dataworks-356fa-backups/pullnupload.json')
#
#     job.source_format = 'NEWLINE_DELIMITED_JSON'
#     job.begin()

def load_data_from_gcs(dataset, test10, source ):
    bigquery_client = bigquery.Client(dataset)
    dataset = bigquery_client.dataset('FirebaseArchive')
    table = dataset.table(test10)
    job_name = str(uuid.uuid4())

    job = bigquery_client.load_table_from_storage(
        job_name, table, "gs://dataworks-356fa-backups/pullnupload.json")

    job.source_format = 'NEWLINE_DELIMITED_JSON'
    job.begin()
    job.errors
</code>```

So far this is my code. This file will run but it does not load anything into bigquery or come back with an error message. It runs then returns me to the normal terminal view.

答:
From your previous question, you have the wait_for_job function. You should use it before printing for errors, like so:

```<code>def load_data_from_gcs(dataset, test10, source ):
    bigquery_client = bigquery.Client(dataset)
    dataset = bigquery_client.dataset('FirebaseArchive')
    table = dataset.table(test10)
    job_name = str(uuid.uuid4())

    job = bigquery_client.load_table_from_storage(
        job_name, table, "gs://dataworks-356fa-backups/pullnupload.json")

    job.source_format = 'NEWLINE_DELIMITED_JSON'
    job.begin()
    wait_for_job(job)
    print("state of job is: " + job.state)
    print("errors: " + job.errors)
</code>```

You can also use IPython to run each step by hand and observe what results on each line.

Notice that job.state must reach 'DONE' status before looking for errors.

Body:
I am having trouble writing a python script that loads or exports a file from google cloud storage to google bigquery.

#standardSQL
import json
import argparse
import time
import uuid

from google.cloud import bigquery
from google.cloud import storage

dataset = 'dataworks-356fa'
source = 'gs://dataworks-356fa-backups/pullnupload.json'

# def load_data_from_gcs(dataset, source):
# #     load_data_from_gcs(dataworks-356fa, 'test10', gs://dataworks-356fa-backups/pullnupload.json):
#     bigquery_client = bigquery.Client('dataworks-356fa')
#     dataset = bigquery_client.dataset(FirebaseArchive)
#     table = dataset.table(test10)
#     job_name = str(uuid.uuid4())
#
#     job = bigquery_client.load_table_from_storage(
#         job_name, test10, 'gs://dataworks-356fa-backups/pullnupload.json')
#
#     job.source_format = 'NEWLINE_DELIMITED_JSON'
#     job.begin()

def load_data_from_gcs(dataset, test10, source ):
    bigquery_client = bigquery.Client(dataset)
    dataset = bigquery_client.dataset('FirebaseArchive')
    table = dataset.table(test10)
    job_name = str(uuid.uuid4())

    job = bigquery_client.load_table_from_storage(
        job_name, table, "gs://dataworks-356fa-backups/pullnupload.json")

    job.source_format = 'NEWLINE_DELIMITED_JSON'
    job.begin()
    job.errors

So far this is my code. This file will run but it does not load anything into bigquery or come back with an error message. It runs then returns me to the normal terminal view.

Body:
From your previous question, you have the wait_for_job function. You should use it before printing for errors, like so:

def load_data_from_gcs(dataset, test10, source ):
    bigquery_client = bigquery.Client(dataset)
    dataset = bigquery_client.dataset('FirebaseArchive')
    table = dataset.table(test10)
    job_name = str(uuid.uuid4())

    job = bigquery_client.load_table_from_storage(
        job_name, table, "gs://dataworks-356fa-backups/pullnupload.json")

    job.source_format = 'NEWLINE_DELIMITED_JSON'
    job.begin()
    wait_for_job(job)
    print("state of job is: " + job.state)
    print("errors: " + job.errors)

You can also use IPython to run each step by hand and observe what results on each line.

Notice that job.state must reach 'DONE' status before looking for errors.


问:
disabling children of a JPanel
Suppose I have a hierarchy like this:

```<code>JPanel panel1;
   JCheckBox cb1;
   JCheckBox cb2;
   JRadioButton rb1;
   JRadioButton rb2;
     ...
</code>```

I have a condition where I want to set individual groups of controls within the panel to be enabled/disabled. That works fine. (e.g. enable cb1 and cb2 when one condition is true, disable them when it is false.)

I would like to disable and re-enable the whole panel. If I call panel1.setEnabled(false) this does not work, it only disables the panel, but does not affect its children.

If I enumerate the panel's children, and call setEnabled(false) on each of them, that would work, but then I would have to store the child enabled state when I re-enable the panel.

Is there a simpler way?

答:
If I enumerate the panel's children, and call setEnabled(false) on each of them, that would work, but then I would have to store the child enabled state when I re-enable the panel.

The Disabled Panel entry has a solution for this approach as well as a "container level" glass pane approach.

Title: disabling children of a JPanel

Body:
Suppose I have a hierarchy like this:

JPanel panel1;
   JCheckBox cb1;
   JCheckBox cb2;
   JRadioButton rb1;
   JRadioButton rb2;
     ...

I have a condition where I want to set individual groups of controls within the panel to be enabled/disabled. That works fine. (e.g. enable cb1 and cb2 when one condition is true, disable them when it is false.)

I would like to disable and re-enable the whole panel. If I call panel1.setEnabled(false) this does not work, it only disables the panel, but does not affect its children.

If I enumerate the panel's children, and call setEnabled(false) on each of them, that would work, but then I would have to store the child enabled state when I re-enable the panel.

Is there a simpler way?


问:
C# Restart Console Application
This question has been asked before but I cannot find an answer that works.  I need to get a C# CONSOLE program to restart periodically. Each of the other answers use the Application.Restart or Application.ExecutablePath which are not supported in console apps.  What code or reference can I use to restart a C# application?

答:
Found it:</p>

```<code>var info = new System.Diagnostics.ProcessStartInfo(Environment.GetCommandLineArgs()[0]);
System.Diagnostics.Process.Start(info);
</code>```

Title: C# Restart Console Application

Body:
Found it:

var info = new System.Diagnostics.ProcessStartInfo(Environment.GetCommandLineArgs()[0]);
System.Diagnostics.Process.Start(info);


问:
Does not conform to protocol "UIPickerViewDataSource"
Why doesn't the view controller conform the UIPickerViewDataSource?

I have checked everything I could do to debug it from the web.

I have typed all the necessary functions for the protocols (Swift 3.1) but in vain.

Here is my code:

```<code>class SelectClassViewController: UIViewController, UIPickerViewDelegate, UIPickerViewDataSource {
    let grades = ["7", "8", "9", "10", "11", "12"]

    var selectCurrentGrade : String? = nil

    @IBOutlet weak var Grade: UIPickerView!

    @IBAction func Next(_ sender: Any) {
        if selectCurrentGrade != nil {
            performSegue(withIdentifier: "GradeToClass", sender: self)
        }
    }

    @IBAction func Back(_ sender: Any) {
        performSegue(withIdentifier: "GradeToMain", sender: self)
    }

    override func viewDidLoad() {
        super.viewDidLoad()

        func numberOfComponents(in pickerView: UIPickerView) -> Int {
            return 1
        }

        func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
            return grades[row]
        }

        func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
            return grades.count
        }

        func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
            selectCurrentGrade = grades[row]
        }
    }
}
</code>```

答: Your functions are inside viewDidLoad, move them outside and it'll work

Body:
Why doesn't the view controller conform the UIPickerViewDataSource?

I have checked everything I could do to debug it from the web.

I have typed all the necessary functions for the protocols (Swift 3.1) but in vain.

Here is my code:

class SelectClassViewController: UIViewController, UIPickerViewDelegate, UIPickerViewDataSource {
    let grades = ["7", "8", "9", "10", "11", "12"]

    var selectCurrentGrade : String? = nil

    @IBOutlet weak var Grade: UIPickerView!

    @IBAction func Next(_ sender: Any) {
        if selectCurrentGrade != nil {
            performSegue(withIdentifier: "GradeToClass", sender: self)
        }
    }

    @IBAction func Back(_ sender: Any) {
        performSegue(withIdentifier: "GradeToMain", sender: self)
    }

    override func viewDidLoad() {
        super.viewDidLoad()

        func numberOfComponents(in pickerView: UIPickerView) -> Int {
            return 1
        }

        func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
            return grades[row]
        }

        func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
            return grades.count
        }

        func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
            selectCurrentGrade = grades[row]
        }
    }
}


问:
Handling CodeIgniter form validation (rule keys and data types)
Okay, so I've been searching for a while this question, but couldn't find an answer (or at least some direct one) that explains this to me.

I've been using CodeIgniter 3.x Form Validation library, so I have some data like this:

```<code>// Just example data
$input_data = [
    'id'        => 1,
    'logged_in' => TRUE,
    'username'  => 'alejandroivan'
];
</code>```

Then, when I want to validate it, I use:

```<code>$this->form_validation->set_data($input_data);
$this->form_validation->set_rules([
    [
        'field'    => 'id',
        'label'    => 'The ID to work on',
        'rules'    => 'required|min_length[1]|is_natural_no_zero'
    ],
    [
        'field'    => 'username',
        'label'    => 'The username',
        'rules'    => 'required|min_length[1]|alpha_numeric|strtolower'
    ],
    [
        'field'    => 'logged_in',
        'label'    => 'The login status of the user',
        'rules'    => 'required|in_list[0,1]'
    ]
]);

if ( $this->form_validation->run() === FALSE ) { /* failed */ }
</code>```

So I have some questions here:

Is the label key really necessary? I'm not using the Form Validation auto-generated error messages in any way, I just want to know if the data passed validation or not. Will something else fail if I just omit it? As this will be a JSON API, I don't really want to print the description of the field, just a static error that I have already defined.

In the username field of my example, will the required rule check length? In other words, is min_length optional in this case? The same question for alpha_numeric... is the empty string considered alpha numeric?

In the logged_in field (which is boolean), how do I check for TRUE or FALSE? Would in_list[0,1] be sufficient? Should I include required too? Is there something like is_boolean?

Thank you in advance.

答:
The "label" key is necessary, but it can be empty.

The "required" rule does not check length, nor does the "alpha_numeric". It checks that a value is present, it does not check the length of said value. For that, there is min_length[] and max_length[].

If you're only passing a 0 or 1, then this is probably the easiest and shortest route.

Body:
Okay, so I've been searching for a while this question, but couldn't find an answer (or at least some direct one) that explains this to me.

I've been using CodeIgniter 3.x Form Validation library, so I have some data like this:

// Just example data
$input_data = [
    'id'        => 1,
    'logged_in' => TRUE,
    'username'  => 'alejandroivan'
];

Then, when I want to validate it, I use:

$this->form_validation->set_data($input_data);
$this->form_validation->set_rules([
    [
        'field'    => 'id',
        'label'    => 'The ID to work on',
        'rules'    => 'required|min_length[1]|is_natural_no_zero'
    ],
    [
        'field'    => 'username',
        'label'    => 'The username',
        'rules'    => 'required|min_length[1]|alpha_numeric|strtolower'
    ],
    [
        'field'    => 'logged_in',
        'label'    => 'The login status of the user',
        'rules'    => 'required|in_list[0,1]'
    ]
]);

if ( $this->form_validation->run() === FALSE ) { /* failed */ }

So I have some questions here:

Is the label key really necessary? I'm not using the Form Validation auto-generated error messages in any way, I just want to know if the data passed validation or not. Will something else fail if I just omit it? As this will be a JSON API, I don't really want to print the description of the field, just a static error that I have already defined.

In the username field of my example, will the required rule check length? In other words, is min_length optional in this case? The same question for alpha_numeric... is the empty string considered alpha numeric?

In the logged_in field (which is boolean), how do I check for TRUE or FALSE? Would in_list[0,1] be sufficient? Should I include required too? Is there something like is_boolean?

Thank you in advance.


问:
Jquery-ui select menu with icon - select not working
I created a jquery-ui select menu containing icons, however when clicked the select function is not called.

Items which have text respond to click correctly see below:

Thx!

$(function() {
  $("#menu").menu({
    select: function(event, ui) {
      alert('click');
    }
  });
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>#menu li {
  height: auto;
  margin: 0;
}</code>```

<link rel="stylesheet" href="https://code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css" type="text/css" />

hello

```
</div>
</div>
</p>

<p>EDIT:</p>

<p>I found that for some reason jqueryUI is giving the images a divider class instead of a menu item class.</p>

<p>I can solve my issue by adding an extra div like this</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>$(function() {
  $("#menu").menu({
    select: function(event, ui) {
      alert('click');
    }
  });
});</code>```

#menu li {
  height: auto;
  margin: 0;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><link rel="stylesheet" href="https://code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css" type="text/css" />

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.min.js"></script>

<ul id="menu">
  <li>hello</li>
  <li>
    <div class="ui-menu-item">
      <img src="https://cdn2.iconfinder.com/data/icons/pittogrammi/142/24-128.png" height=20 width=20 />
    </div>
  </li>
  <li>
    <div class="ui-menu-item">
      <img src="https://cdn1.iconfinder.com/data/icons/material-core/24/cloud-download-128.png" height=20 width=20>
    </div>
  </li>
</ul></code>```

I still hope a better solution/explanation is possible

答:
Based on jQuery UI Menu Widget documentation, it treats all list items with space or dash as a menu divider (read here).

In your case, I think because you have nothing on the menu item except an image, the item is treated as a divider.

But the widget uses functional CSS classes which you can use to tell the widget that the image is in fact a menu item rather than a divider. You can give your menu item img tag a class named ui-menu-item. So you can have:

```<code><ul id="menu">
  <li>hello</li>
  <li>
    <img class="ui-menu-item" src="https://cdn2.iconfinder.com/data/icons/pittogrammi/142/24-128.png" height=20 width=20 />
  </li>
  <li>
    <img class="ui-menu-item" src="https://cdn1.iconfinder.com/data/icons/material-core/24/cloud-download-128.png" height=20 width=20>
  </li>
</ul>
</code>```

Or as you did, you wrapped your img within a div with the said class.

Another option is to override the widget's _isDivider function. But this is less efficient in your case.

Body:
I created a jquery-ui select menu containing icons, however when clicked the select function is not called.

Items which have text respond to click correctly see below:

Thx!

$(function() {
  $("#menu").menu({
    select: function(event, ui) {
      alert('click');
    }
  });
});

#menu li {
  height: auto;
  margin: 0;
}

<link rel="stylesheet" href="https://code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css" type="text/css" />

hello

EDIT:

I found that for some reason jqueryUI is giving the images a divider class instead of a menu item class.

I can solve my issue by adding an extra div like this

$(function() {
  $("#menu").menu({
    select: function(event, ui) {
      alert('click');
    }
  });
});

#menu li {
  height: auto;
  margin: 0;
}

<link rel="stylesheet" href="https://code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css" type="text/css" />

hello

I still hope a better solution/explanation is possible

Body:
Based on jQuery UI Menu Widget documentation, it treats all list items with space or dash as a menu divider (read here).

In your case, I think because you have nothing on the menu item except an image, the item is treated as a divider.

But the widget uses functional CSS classes which you can use to tell the widget that the image is in fact a menu item rather than a divider. You can give your menu item img tag a class named ui-menu-item. So you can have:

<ul id="menu">
  <li>hello</li>
  <li>
    <img class="ui-menu-item" src="https://cdn2.iconfinder.com/data/icons/pittogrammi/142/24-128.png" height=20 width=20 />
  </li>
  <li>
    <img class="ui-menu-item" src="https://cdn1.iconfinder.com/data/icons/material-core/24/cloud-download-128.png" height=20 width=20>
  </li>
</ul>

Or as you did, you wrapped your img within a div with the said class.

Another option is to override the widget's _isDivider function. But this is less efficient in your case.


问:
ARKit hide objects behind walls
How can I use the horizontal and vertical planes tracked by ARKit to hide objects behind walls/ behind real objects? Currently the 3D added objects can be seen through walls when you leave a room and/ or in front of objects that they should be behind. So is it possible to use the data ARKit gives me to provide a more natural AR experience without the objects appearing through walls?</p>

答:
You have two issues here.

(And you didn't even use regular expressions!)

How to create occlusion geometry for ARKit/SceneKit?

If you set a SceneKit material's colorBufferWriteMask to an empty value ([] in Swift), any objects using that material won't appear in the view, but they'll still write to the z-buffer during rendering, which affects the rendering of other objects. In effect, you'll get a "hole" shaped like your object, through which the background shows (the camera feed, in the case of ARSCNView), but which can still obscure other SceneKit objects.

You'll also need to make sure that an occluded renders before any other nodes it's supposed to obscure. You can do this using node hierarchy ( I can't remember offhand whether parent nodes render before their children or the other way around, but it's easy enough to test). Nodes that are peers in the hierarchy don't have a deterministic order, but you can force an order regardless of hierarchy with the renderingOrder property. That property defaults to zero, so setting it to -1 will render before everything. (Or for finer control, set the renderingOrders for several nodes to a sequence of values.)

How to detect walls/etc so you know where to put occlusion geometry?

In iOS 11.3 and later (aka "ARKit 1.5"), you can turn on vertical plane detection. (Note that when you get vertical plane anchors back from that, they're automatically rotated. So if you attach models to the anchor, their local "up" direction is normal to the plane.) Also new in iOS 11.3, you can get a more detailed shape estimate for each detected plane (see ARSCNPlaneGeometry), regardless of its orientation.

However, even if you have the horizontal and the vertical, the outer limits of a plane are just estimates that change over time. That is, ARKit can quickly detect where part of a wall is, but it doesn't know where the edges of the wall are without the user spending some time waving the device around to map out the space. And even then, the mapped edges might not line up precisely with those of the real wall.

So... if you use detected vertical planes to occlude virtual geometry, you might find places where virtual objects that are supposed to be hidden show through, either by being not quite hiding right at the edge of the wall, or being visible through places where ARKit hasn't mapped the entire real wall. (The latter issue you might be able to solve by assuming a larger extent than ARKit does.)

Title: ARKit hide objects behind walls


问:
setCharAt method not working as expected inside for loop (Java)
I am trying to develop a method to reverse the vowels in a string. For this, I have developed my own small stack. I am iterating backwards through the string twice, once to populate the stack with each vowel I locate, the second time to replace the vowel with the vowel stored at the top of the stack. I have added a bunch of print statements to determine where this is failing and it seems to be failing at the setCharAt method. For testing purposes, I provide a string aeiou and I am expecting to get back uoiea. The chars are getting replaced during each iteration, but unfortunately, they don't stay that way. As of the next iteration, the chars that were replaced on the previous iteration return to what they were before. As a result, I am getting back ueiou, where only the first character in the string is as expected (and the third which is a noop). Here is my code. Any tips are appreciated.

```<code>import java.util.*;

public class Solution {

    static String result;

    static class StackOfVowels {
        static Node top;

        public StackOfVowels() {
            Node top = null;
        }

        static class Node {
            Node next = null;
            char vowel = '\0';
            Node(char value) {
                this.vowel = value;
            }
        }

        public void push(char item) {
            Node node = new Node(item);
            if (top == null) {
                top = node;
            }
            else {
                node.next = top;
                top = node;
            }
        }

        public char top() {
            if (top == null) throw new EmptyStackException();
            return top.vowel;
        }

        public void pop() {
            int result = -1;
            if (top != null) {
                result = top.vowel;
                top = top.next;
            }
        }
    }

    public static String reverseVowels(String s) {

        StackOfVowels stackOfVowels = new StackOfVowels();

        for(int i = s.length()-1; i >= 0; i--) {
            char c = s.charAt(i);
            if ((c == 'a') || (c == 'e') || (c == 'i') || (c == 'o') || (c == 'u')) {
                System.out.println("Initial sequence of iterations identified vowel: " + c);
                stackOfVowels.push(c);
                System.out.println("Pushed to stack, current top is: " + stackOfVowels.top());
            }
        }

        for(int j = s.length()-1; j >= 0; j--) {
            char b = s.charAt(j);
            if ((b == 'a') || (b == 'e') || (b == 'i') || (b == 'o') || (b == 'u')) {
                System.out.println("Second sequence of iterations identified vowel: " + b);
                StringBuilder newstr = new StringBuilder(s);
                char d = stackOfVowels.top();
                System.out.println("Variable d set to top of: " + stackOfVowels.top());
                newstr.setCharAt(j, d);
                result = newstr.toString();
                System.out.println("Here is the new string: " + result);
                stackOfVowels.pop();
                System.out.println("Stack was popped");
            }
        }
        return result;
    }

    public static void main(String[] args) {
        String s = "aeiou";
        reverseVowels(s);
        System.out.println("Final result: " + result);
    }
}
</code>```

答:
A slight improvement (debatable) on @Elliot answer is to create the StringBuilder with the original String and only replace when necessary

```<code>    String vowels = new StringBuilder(s.replaceAll("[^AEIOUaeiou]", ""))
            .reverse().toString();
    StringBuilder sb = new StringBuilder(s);
    for (int i = 0, p = 0; i < s.length(); i++) {
        switch (Character.toLowerCase(s.charAt(i))) {
        // Note that these fall-through...
        case 'a': case 'e': case 'i': case 'o': case 'u':
            sb.setCharAt(i, vowels.charAt(p++));
            break;
        default:
            break;
        }
    }
    return sb.toString();
</code>```

Body:
I am trying to develop a method to reverse the vowels in a string. For this, I have developed my own small stack. I am iterating backwards through the string twice, once to populate the stack with each vowel I locate, the second time to replace the vowel with the vowel stored at the top of the stack. I have added a bunch of print statements to determine where this is failing and it seems to be failing at the setCharAt method. For testing purposes, I provide a string aeiou and I am expecting to get back uoiea. The chars are getting replaced during each iteration, but unfortunately, they don't stay that way. As of the next iteration, the chars that were replaced on the previous iteration return to what they were before. As a result, I am getting back ueiou, where only the first character in the string is as expected (and the third which is a noop). Here is my code. Any tips are appreciated.

import java.util.*;

public class Solution {

    static String result;

    static class StackOfVowels {
        static Node top;

        public StackOfVowels() {
            Node top = null;
        }

        static class Node {
            Node next = null;
            char vowel = '\0';
            Node(char value) {
                this.vowel = value;
            }
        }

        public void push(char item) {
            Node node = new Node(item);
            if (top == null) {
                top = node;
            }
            else {
                node.next = top;
                top = node;
            }
        }

        public char top() {
            if (top == null) throw new EmptyStackException();
            return top.vowel;
        }

        public void pop() {
            int result = -1;
            if (top != null) {
                result = top.vowel;
                top = top.next;
            }
        }
    }

    public static String reverseVowels(String s) {

        StackOfVowels stackOfVowels = new StackOfVowels();

        for(int i = s.length()-1; i >= 0; i--) {
            char c = s.charAt(i);
            if ((c == 'a') || (c == 'e') || (c == 'i') || (c == 'o') || (c == 'u')) {
                System.out.println("Initial sequence of iterations identified vowel: " + c);
                stackOfVowels.push(c);
                System.out.println("Pushed to stack, current top is: " + stackOfVowels.top());
            }
        }

        for(int j = s.length()-1; j >= 0; j--) {
            char b = s.charAt(j);
            if ((b == 'a') || (b == 'e') || (b == 'i') || (b == 'o') || (b == 'u')) {
                System.out.println("Second sequence of iterations identified vowel: " + b);
                StringBuilder newstr = new StringBuilder(s);
                char d = stackOfVowels.top();
                System.out.println("Variable d set to top of: " + stackOfVowels.top());
                newstr.setCharAt(j, d);
                result = newstr.toString();
                System.out.println("Here is the new string: " + result);
                stackOfVowels.pop();
                System.out.println("Stack was popped");
            }
        }
        return result;
    }

    public static void main(String[] args) {
        String s = "aeiou";
        reverseVowels(s);
        System.out.println("Final result: " + result);
    }
}

Body:
A slight improvement (debatable) on @Elliot answer is to create the StringBuilder with the original String and only replace when necessary

    String vowels = new StringBuilder(s.replaceAll("[^AEIOUaeiou]", ""))
            .reverse().toString();
    StringBuilder sb = new StringBuilder(s);
    for (int i = 0, p = 0; i < s.length(); i++) {
        switch (Character.toLowerCase(s.charAt(i))) {
        // Note that these fall-through...
        case 'a': case 'e': case 'i': case 'o': case 'u':
            sb.setCharAt(i, vowels.charAt(p++));
            break;
        default:
            break;
        }
    }
    return sb.toString();


问:
Calculate the penny double after each day of working
I'm trying to make a table, which the pay of day 2 is double from day 1, day 3 is double from day 2 and keep doubling. There are 5 days to display and then calculate the total pay of 5 days.

But the result was just 0.02 from day 1 to day 5. What did I miss?

```<code>#include <iostream>
#include <iomanip>
using namespace std;

int main()
{
    int entries;
    double pay = 0.010000;
    double sum = 0;
    int day;

    cout << "Enter number of days";
    cin >> entries; //Number of day

    cout << "Day   Pay\n";
    cout << "=========\n";

    for (day = 1; day <= entries; day++)
    {
       cout << day << "\t\t" << (pay * 2);
    }
return 0;
}
</code>```

答:
You have to update the pay variable in each iteration:</p>

```<code>for (day = 1; day <= entries; day++)
{
   cout << day << "\t\t" << pay<<endl;
   sum += pay;
   pay *= 2;
}

cout << "Total is\t\t" << sum <<endl;
</code>```

Body:
I'm trying to make a table, which the pay of day 2 is double from day 1, day 3 is double from day 2 and keep doubling. There are 5 days to display and then calculate the total pay of 5 days.

But the result was just 0.02 from day 1 to day 5. What did I miss?

#include <iostream>
#include <iomanip>
using namespace std;

int main()
{
    int entries;
    double pay = 0.010000;
    double sum = 0;
    int day;

    cout << "Enter number of days";
    cin >> entries; //Number of day

    cout << "Day   Pay\n";
    cout << "=========\n";

    for (day = 1; day <= entries; day++)
    {
       cout << day << "\t\t" << (pay * 2);
    }
return 0;
}

Body:
You have to update the pay variable in each iteration:

for (day = 1; day <= entries; day++)
{
   cout << day << "\t\t" << pay<<endl;
   sum += pay;
   pay *= 2;
}

cout << "Total is\t\t" << sum <<endl;


问:
setPersistenceEnabled(true) crashes app
I’m creating my first Firebase App. One of its requirements is that it run when the network is not available. The Firebase guide states:

Enabling disk persistence allows our app to also keep all of its state even after an app restart. We can enable disk persistence with just one line of code.
  FirebaseDatabase.getInstance().setPersistenceEnabled(true);
  With disk persistence enabled, our synced data and writes will be persisted to disk across app restarts and our app should work seamlessly in offline situations.

Another requirement is to use Google Sign In. So in my MainActivity I check if the User is signed in, if not, I launch the SignInActivity. (The  SignInActivity is from the Firebase examples.)  The SignInActivity works, the user gets logged in, and MainActivity is launched for a second time.  Now my app crashes on the code line FirebaseDatabase.getInstance().setPersistenceEnabled(true);  with the following message:

Calls to setPersistenceEnabled() must be made before any other usage of FirebaseDatabase instance.

Now if I restart my app, the User is signed in, the SignInActivity is not launched, my app runs fine.

Any suggestions of how I avoid this crash after the User signs in?

As I was posting this question, I received a suggestion to relocate FirebaseDatabase.getInstance().setPersistenceEnabled(true);
to my “Application class”. I get exactly the same result … SignInActivity starts, completes, and I get a crash on the setPersistenceEnabled.

Below is my MainActivity onCreate:

```<code>@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    // Calls to setPersistenceEnabled() must be made before any other usage of FirebaseDatabase instance.
    // Crash here upon returning from SignInActivity.
    FirebaseDatabase.getInstance().setPersistenceEnabled(true);
    mFirebaseDbReference = FirebaseDatabase.getInstance().getReference();

    // Initialize Firebase Auth
    mFirebaseAuth = FirebaseAuth.getInstance();
    mFirebaseUser = mFirebaseAuth.getCurrentUser();
    if (mFirebaseUser == null) {
        // Not signed in, launch the Sign In activity
        Timber.tag("MainActivity").i("onCreate(): User not signed in, launching SignInActivity");
        startActivity(new Intent(this, SignInActivity.class));
        finish();

    } else {
        mUsername = mFirebaseUser.getDisplayName();
        Timber.tag("MainActivity").i("onCreate(): User \"%s\" signed in.", mUsername);
        if (mFirebaseUser.getPhotoUrl() != null) {
            mPhotoUrl = mFirebaseUser.getPhotoUrl().toString();
        }
    }
</code>```

答:
I wouldn't recommend using Application to store the data because like its written in CodePath

There is always data and information that is needed in many places within your app. This might be a session token, the result of an expensive computation, etc. It might be tempting to use the application instance in order to avoid the overhead of passing objects between activities or keeping those in persistent storage.

However, you should never store mutable instance data inside the Application object because if you assume that your data will stay there, your application will inevitably crash at some point with a NullPointerException. The application object is not guaranteed to stay in memory forever, it will get killed. Contrary to popular belief, the app won’t be restarted from scratch. Android will create a new Application object and start the activity where the user was before to give the illusion that the application was never killed in the first place.

Thats the reason I would recommend using a Singleton like this:

```<code>public class DataBaseUtil {

private static FirebaseDatabase mDatabase;

public static FirebaseDatabase getDatabase() {
    if (mDatabase == null) {
        mDatabase = FirebaseDatabase.getInstance();
        mDatabase.setPersistenceEnabled(true);
    }
    return mDatabase;
}}
</code>```

just use it in your code then like

```<code>private FirebaseDatabase fdb = DataBaseUtil.getDatabase();
</code>```

Title: setPersistenceEnabled(true) crashes app

Body:
I’m creating my first Firebase App. One of its requirements is that it run when the network is not available. The Firebase guide states:

Enabling disk persistence allows our app to also keep all of its state even after an app restart. We can enable disk persistence with just one line of code.
  FirebaseDatabase.getInstance().setPersistenceEnabled(true);
  With disk persistence enabled, our synced data and writes will be persisted to disk across app restarts and our app should work seamlessly in offline situations.

Another requirement is to use Google Sign In. So in my MainActivity I check if the User is signed in, if not, I launch the SignInActivity. (The  SignInActivity is from the Firebase examples.)  The SignInActivity works, the user gets logged in, and MainActivity is launched for a second time.  Now my app crashes on the code line FirebaseDatabase.getInstance().setPersistenceEnabled(true);  with the following message:

Calls to setPersistenceEnabled() must be made before any other usage of FirebaseDatabase instance.

Now if I restart my app, the User is signed in, the SignInActivity is not launched, my app runs fine.

Any suggestions of how I avoid this crash after the User signs in?

As I was posting this question, I received a suggestion to relocate FirebaseDatabase.getInstance().setPersistenceEnabled(true);
to my “Application class”. I get exactly the same result … SignInActivity starts, completes, and I get a crash on the setPersistenceEnabled.

Below is my MainActivity onCreate:

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    // Calls to setPersistenceEnabled() must be made before any other usage of FirebaseDatabase instance.
    // Crash here upon returning from SignInActivity.
    FirebaseDatabase.getInstance().setPersistenceEnabled(true);
    mFirebaseDbReference = FirebaseDatabase.getInstance().getReference();

    // Initialize Firebase Auth
    mFirebaseAuth = FirebaseAuth.getInstance();
    mFirebaseUser = mFirebaseAuth.getCurrentUser();
    if (mFirebaseUser == null) {
        // Not signed in, launch the Sign In activity
        Timber.tag("MainActivity").i("onCreate(): User not signed in, launching SignInActivity");
        startActivity(new Intent(this, SignInActivity.class));
        finish();

    } else {
        mUsername = mFirebaseUser.getDisplayName();
        Timber.tag("MainActivity").i("onCreate(): User \"%s\" signed in.", mUsername);
        if (mFirebaseUser.getPhotoUrl() != null) {
            mPhotoUrl = mFirebaseUser.getPhotoUrl().toString();
        }
    }

Body:
I wouldn't recommend using Application to store the data because like its written in CodePath

There is always data and information that is needed in many places within your app. This might be a session token, the result of an expensive computation, etc. It might be tempting to use the application instance in order to avoid the overhead of passing objects between activities or keeping those in persistent storage.

However, you should never store mutable instance data inside the Application object because if you assume that your data will stay there, your application will inevitably crash at some point with a NullPointerException. The application object is not guaranteed to stay in memory forever, it will get killed. Contrary to popular belief, the app won’t be restarted from scratch. Android will create a new Application object and start the activity where the user was before to give the illusion that the application was never killed in the first place.

Thats the reason I would recommend using a Singleton like this:

public class DataBaseUtil {

private static FirebaseDatabase mDatabase;

public static FirebaseDatabase getDatabase() {
    if (mDatabase == null) {
        mDatabase = FirebaseDatabase.getInstance();
        mDatabase.setPersistenceEnabled(true);
    }
    return mDatabase;
}}

just use it in your code then like

private FirebaseDatabase fdb = DataBaseUtil.getDatabase();


问:
Reactstrap is causing a critical dependency warning about tether.js
I am using reactstrap in my React app which was originally created by create-react-app.

The problem I'm having is with reactstrap, I'm getting the following console warnings:

```<code>./~/reactstrap-tether/dist/js/tether.js
Critical dependencies:
2:479-486 This seems to be a pre-built javascript file. Though this is possible, it's not recommended. Try to require the original source to get better results.
 @ ./~/reactstrap-tether/dist/js/tether.js 2:479-486
</code>```

In the project's GitHub issues, I see possible solutions listed like so: "To suppress the warning (for now), add this to your webpack config file...". The problem is, with Facebook's create-react-app I do not have a Webpack configuration file to configure. How can I go about fixing this warning

答: Looks like this has raised concern for people with create-react-app and a feature request has been put in and is currently being worked on. It should be fixed in the near future so there you shouldn't really worry about it. But to answer the other part of the question, it's possible to get the Webpack, Babel and other configuration files from create-react-app by running npm run eject but since this is an irreversible action and will separate you from future updates, I would highly suggest just waiting for the fix to happen.

Body:
I am using reactstrap in my React app which was originally created by create-react-app.

The problem I'm having is with reactstrap, I'm getting the following console warnings:

./~/reactstrap-tether/dist/js/tether.js
Critical dependencies:
2:479-486 This seems to be a pre-built javascript file. Though this is possible, it's not recommended. Try to require the original source to get better results.
 @ ./~/reactstrap-tether/dist/js/tether.js 2:479-486

In the project's GitHub issues, I see possible solutions listed like so: "To suppress the warning (for now), add this to your webpack config file...". The problem is, with Facebook's create-react-app I do not have a Webpack configuration file to configure. How can I go about fixing this warning


问:
Move a node to a certain position withou dragging
I use D3.js and i want that a node move to a certain position ( 1; 1000) after i clicked a button.

The onclick function looks like this:

```<code>var node = svg.append("g")
          .attr("class", "nodes")
          .selectAll("circle")
          .data(nodes)
          .enter().append("circle")
           .attr("r", 8)
         .attr("fill", (d, i) => colours[i % 2])
            .style("stroke", "#000")

     button.on("click", function(d) {
            nodes[1].x = 1;
            nodes[1].y = 1000;
            nodes[1].px = 1;
            nodes[1].py = 1000;
            nodes[1].fixed = true; };
</code>```

My problem is that this does not work right. Can someone help me maybe?

Thanks a lot!

答:
You have to reheat the simulation. In v4:

```<code>simulation.alpha(0.8).restart();
//value here------^
//between 0 and 1
</code>```

Here is a demo, click the button to set the position of the first node to the top left corner (again, I'm using v4):

var width = 400;
var height = 300;

var svg = d3.select("body")
  .append("svg")
  .attr("width", width)
  .attr("height", height);

var nodes = [{
  name: "foo",
  color: "blue"
}, {
  name: "bar",
  color: "green"
}, {
  name: "baz",
  color: "red"
}, {
  name: "foofoo",
  color: "yellow"
}, {
  name: "foobar",
  color: "blue"
}, {
  name: "foobaz",
  color: "green"
}, {
  name: "barfoo",
  color: "red"
}, {
  name: "barbar",
  color: "yellow"
}, {
  name: "barbaz",
  color: "blue"
}];

var links = [{
  "source": 0,
  "target": 1
}, {
  "source": 0,
  "target": 2
}, {
  "source": 0,
  "target": 3
}, {
  "source": 1,
  "target": 3
}, {
  "source": 1,
  "target": 4
}, {
  "source": 2,
  "target": 5
}, {
  "source": 3,
  "target": 6
}, {
  "source": 1,
  "target": 7
}, {
  "source": 6,
  "target": 8
}, {
  "source": 0,
  "target": 7
}, {
  "source": 2,
  "target": 6
}, {
  "source": 3,
  "target": 8
}];

var simulation = d3.forceSimulation()
  .force("link", d3.forceLink())
  .force("charge", d3.forceManyBody().strength(-50))
  .force("center", d3.forceCenter(width / 2, height / 2))
  .force("collide", d3.forceCollide(function(d) {
    return d.r + 1;
  }));

var link = svg.selectAll(null)
  .data(links)
  .enter()
  .append("line")
  .style("stroke", "#ccc")
  .style("stroke-width", 1);

var node = svg.selectAll(null)
  .data(nodes)
  .enter()
  .append("circle")
  .attr("r", function(d) {
    return d.r = 10;
  })
  .attr("stroke", "gray")
  .attr("stroke-width", "2px")
  .attr("fill", function(d) {
    return d.color
  })
  .call(d3.drag()
    .on("start", dragstarted)
    .on("drag", dragged)
    .on("end", dragended));;

var text = svg.selectAll(null)
  .data(nodes)
  .enter()
  .append("text")
  .attr("pointer-events", "none")
  .style("fill", "black")
  .attr("dy", "-1em")
  .attr("dx", "-1em")
  .text(function(d) {
    return d.name;
  });

simulation.nodes(nodes);
simulation.force("link")
  .links(links);

simulation.on("tick", function() {

  link.attr("x1", function(d) {
      return d.source.x;
    })
    .attr("y1", function(d) {
      return d.source.y;
    })
    .attr("x2", function(d) {
      return d.target.x;
    })
    .attr("y2", function(d) {
      return d.target.y;
    })

  node.attr("cx", function(d) {
    return d.x
  }).attr("cy", function(d) {
    return d.y
  });

  text.attr("x", function(d) {
    return d.x
  }).attr("y", function(d) {
    return d.y
  });

});

function dragstarted(d) {
  if (!d3.event.active) simulation.alphaTarget(0.3).restart();
  d.fx = d.x;
  d.fy = d.y;
}

function dragged(d) {
  d.fx = d3.event.x;
  d.fy = d3.event.y;
}

function dragended(d) {
  if (!d3.event.active) simulation.alphaTarget(0);
  d.fx = null;
  d.fy = null;
}

d3.select("button").on("click", function(d) {
  nodes[1].fx = 20;
  nodes[1].fy = 30;
  simulation.alpha(0.8).restart();
})```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://d3js.org/d3.v4.js"></script>
<button>Click me</button>
<br></code>```

Body:
I use D3.js and i want that a node move to a certain position ( 1; 1000) after i clicked a button.

The onclick function looks like this:

var node = svg.append("g")
          .attr("class", "nodes")
          .selectAll("circle")
          .data(nodes)
          .enter().append("circle")
           .attr("r", 8)
         .attr("fill", (d, i) => colours[i % 2])
            .style("stroke", "#000")

     button.on("click", function(d) {
            nodes[1].x = 1;
            nodes[1].y = 1000;
            nodes[1].px = 1;
            nodes[1].py = 1000;
            nodes[1].fixed = true; };

My problem is that this does not work right. Can someone help me maybe?

Thanks a lot!

Body:
You have to reheat the simulation. In v4:

simulation.alpha(0.8).restart();
//value here------^
//between 0 and 1

Here is a demo, click the button to set the position of the first node to the top left corner (again, I'm using v4):

var width = 400;
var height = 300;

var svg = d3.select("body")
  .append("svg")
  .attr("width", width)
  .attr("height", height);

var nodes = [{
  name: "foo",
  color: "blue"
}, {
  name: "bar",
  color: "green"
}, {
  name: "baz",
  color: "red"
}, {
  name: "foofoo",
  color: "yellow"
}, {
  name: "foobar",
  color: "blue"
}, {
  name: "foobaz",
  color: "green"
}, {
  name: "barfoo",
  color: "red"
}, {
  name: "barbar",
  color: "yellow"
}, {
  name: "barbaz",
  color: "blue"
}];

var links = [{
  "source": 0,
  "target": 1
}, {
  "source": 0,
  "target": 2
}, {
  "source": 0,
  "target": 3
}, {
  "source": 1,
  "target": 3
}, {
  "source": 1,
  "target": 4
}, {
  "source": 2,
  "target": 5
}, {
  "source": 3,
  "target": 6
}, {
  "source": 1,
  "target": 7
}, {
  "source": 6,
  "target": 8
}, {
  "source": 0,
  "target": 7
}, {
  "source": 2,
  "target": 6
}, {
  "source": 3,
  "target": 8
}];

var simulation = d3.forceSimulation()
  .force("link", d3.forceLink())
  .force("charge", d3.forceManyBody().strength(-50))
  .force("center", d3.forceCenter(width / 2, height / 2))
  .force("collide", d3.forceCollide(function(d) {
    return d.r + 1;
  }));

var link = svg.selectAll(null)
  .data(links)
  .enter()
  .append("line")
  .style("stroke", "#ccc")
  .style("stroke-width", 1);

var node = svg.selectAll(null)
  .data(nodes)
  .enter()
  .append("circle")
  .attr("r", function(d) {
    return d.r = 10;
  })
  .attr("stroke", "gray")
  .attr("stroke-width", "2px")
  .attr("fill", function(d) {
    return d.color
  })
  .call(d3.drag()
    .on("start", dragstarted)
    .on("drag", dragged)
    .on("end", dragended));;

var text = svg.selectAll(null)
  .data(nodes)
  .enter()
  .append("text")
  .attr("pointer-events", "none")
  .style("fill", "black")
  .attr("dy", "-1em")
  .attr("dx", "-1em")
  .text(function(d) {
    return d.name;
  });

simulation.nodes(nodes);
simulation.force("link")
  .links(links);

simulation.on("tick", function() {

  link.attr("x1", function(d) {
      return d.source.x;
    })
    .attr("y1", function(d) {
      return d.source.y;
    })
    .attr("x2", function(d) {
      return d.target.x;
    })
    .attr("y2", function(d) {
      return d.target.y;
    })

  node.attr("cx", function(d) {
    return d.x
  }).attr("cy", function(d) {
    return d.y
  });

  text.attr("x", function(d) {
    return d.x
  }).attr("y", function(d) {
    return d.y
  });

});

function dragstarted(d) {
  if (!d3.event.active) simulation.alphaTarget(0.3).restart();
  d.fx = d.x;
  d.fy = d.y;
}

function dragged(d) {
  d.fx = d3.event.x;
  d.fy = d3.event.y;
}

function dragended(d) {
  if (!d3.event.active) simulation.alphaTarget(0);
  d.fx = null;
  d.fy = null;
}

d3.select("button").on("click", function(d) {
  nodes[1].fx = 20;
  nodes[1].fy = 30;
  simulation.alpha(0.8).restart();
})

<script src="https://d3js.org/d3.v4.js"></script>
<button>Click me</button>
<br>


问:
GCloud: Copying Files from Local Machine into a Docker Container
Is there a straightforward way to copy files from a local machine into a docker container within a VM instance on Google Compute Engine?

I know gcloud compute ssh --container=XX is an easy way to execute commands on a container, but there's no analogous gcloud compute scp --container=XX. Note: I created this VM and docker container with the command gcloud alpha compute instances create-from-container ...

Note, better than just being able to transfer files, it would be nice to have an rsync type functionality.

答:
I generally use an approach where I use object storage in-between local machines and a cloud VMs.  On AWS I use s3 sync, on Google you can use gsutil rsync

First the data on a 'local' development machine gets pushed into object storage when I'm ready to deploy it.

(The data in question is a snapshot of a git repository + some binary
files).

(Sometimes the development machine in question is a laptop, sometimes
my desktop, sometimes a cloud IDE.  They all run git).

Then the VM pulls content from object storage using s3 sync.  I think you can do the same with gsutil to pull data from Google object storage into a Google container.  (In fact it seems you can even rsync between clouds using gsutil).

This is my shoestring dev-ops environment.  It's a little bit more work, but using object storage as a middleman for syncing snapshots of data between machines provides a bit of flexibility, a reproducible environment and peace of mind.


问:
How to Scrape Dynamic Website in Go?
With NodeJS I can use PhantomJS to help me to scrape dynamic website, with Python I can use Selenium to do this job.

How about in GoLang?

答:
Give it a try on Go lang selenium web drivers

https://github.com/knq/chromedp : Package chromedp is a faster, simpler way to drive browsers (Chrome, Edge, Safari, Android, etc) without external dependencies (ie, Selenium, PhantomJS, etc) using the Chrome Debugging Protocol.

https://github.com/sourcegraph/go-selenium : Selenium WebDriver client for Go

https://github.com/tebeka/selenium : Selenium/Webdriver client for Go

Static Crawler Reference

You can use github.com/PuerkitoBio/gocrawl library or built your custom crawler, basic idea is here https://tour.golang.org/concurrency/10.

Title: How to Scrape Dynamic Website in Go?


问:
Override users `remember_me` token in Laravel
I want same remember_token to be generated when we use generator ==> php artisan make:auth.
Here is what I'm creating new user.

```<code> $user = User::create(['name' => $request->name,'email' => $request->email,'password' => bcrypt($request->password),'phone' => $request->phone,'address' => $request->address]);
</code>```

but I don't know how to generate remember_token.

```<code> $user = User::create(['...'=>'...','remember_token' => what()]);
</code>```

I already have created remember_token in my database.

答:
If you're using the default User.php model that ships with Laravel, then you can override the method setRememberToken($token):

```<code>use Illuminate\Foundation\Auth\User as Authenticatable;

class User extends Authenticatable
{
    public function setRememberToken($token)
    {
        // Set the remember token your own way...

        $this->remember_token = 'my random token';
    }
}
</code>```

This is called in the EloquentUserProvider here:

https://github.com/laravel/framework/blob/5.4/src/Illuminate/Auth/EloquentUserProvider.php#L71-L89

```<code>/**
 * Update the "remember me" token for the given user in storage.
 *
 * @param  \Illuminate\Contracts\Auth\Authenticatable  $user
 * @param  string  $token
 * @return void
 */
public function updateRememberToken(UserContract $user, $token)
{
    $user->setRememberToken($token);

    $timestamps = $user->timestamps;

    $user->timestamps = false;

    $user->save();

    $user->timestamps = $timestamps;
}
</code>```

Body:
I want same remember_token to be generated when we use generator ==> php artisan make:auth.
Here is what I'm creating new user.

 $user = User::create(['name' => $request->name,'email' => $request->email,'password' => bcrypt($request->password),'phone' => $request->phone,'address' => $request->address]);

but I don't know how to generate remember_token.

 $user = User::create(['...'=>'...','remember_token' => what()]);

I already have created remember_token in my database.

Body:
If you're using the default User.php model that ships with Laravel, then you can override the method setRememberToken($token):

use Illuminate\Foundation\Auth\User as Authenticatable;

class User extends Authenticatable
{
    public function setRememberToken($token)
    {
        // Set the remember token your own way...

        $this->remember_token = 'my random token';
    }
}

This is called in the EloquentUserProvider here:

https://github.com/laravel/framework/blob/5.4/src/Illuminate/Auth/EloquentUserProvider.php#L71-L89

/**
 * Update the "remember me" token for the given user in storage.
 *
 * @param  \Illuminate\Contracts\Auth\Authenticatable  $user
 * @param  string  $token
 * @return void
 */
public function updateRememberToken(UserContract $user, $token)
{
    $user->setRememberToken($token);

    $timestamps = $user->timestamps;

    $user->timestamps = false;

    $user->save();

    $user->timestamps = $timestamps;
}


问:
Typescript- Creating member function outside of a Class definition with return types
How do you define a member function, outside the definition of a class in Typescript?

To quote an example from c++:

```<code>class A
{
   void runThis();
  //Member variables and constructors here
}

A::runThis()
{
  //code goes here
}
</code>```

How do you achieve the same in typescript? By searching in google I found something like:

```<code>class A
{
  runThis: () => void;
}

A.prototype.runThis = function(){
 //Anonymous function code goes here
}
</code>```

However, I have not found the syntax, to do the same with functions that have a return type (such as a number or a string).

How can this be achieved?

答:
In TypeScript you can use static method for your problem.

Sample:

```<code>export class Person {

   private static birthday : Date;

   public static getBirthDay() : Date {
     return this.birthday;
   }
}

Person.getBirthDay();
</code>```

Body:
How do you define a member function, outside the definition of a class in Typescript?

To quote an example from c++:

class A
{
   void runThis();
  //Member variables and constructors here
}

A::runThis()
{
  //code goes here
}

How do you achieve the same in typescript? By searching in google I found something like:

class A
{
  runThis: () => void;
}

A.prototype.runThis = function(){
 //Anonymous function code goes here
}

However, I have not found the syntax, to do the same with functions that have a return type (such as a number or a string).

How can this be achieved?

Body:
In TypeScript you can use static method for your problem.

Sample:

export class Person {

   private static birthday : Date;

   public static getBirthDay() : Date {
     return this.birthday;
   }
}

Person.getBirthDay();


问:
Cocoa Pods error with pod install
[!] Unable to satisfy the following requirements:

Google/SignIn required by Podfile

Google/SignIn required by Podfile

Google/SignIn required by Podfile

Google/SignIn required by Podfile

Google/SignIn (= 1.3.2) required by Podfile.lock

Specs satisfying the Google/SignIn dependency were found, but they required a higher minimum deployment target.

Specs satisfying the Google/SignIn dependency were found, but they required a higher minimum deployment target.

Specs satisfying the Google/SignIn dependency were found, but they required a higher minimum deployment target.

Specs satisfying the Google/SignIn dependency were found, but they required a higher minimum deployment target.

Specs satisfying the Google/SignIn (= 1.3.2) dependency were found, but they required a higher minimum deployment target.

答: I solved the problem. I selected my project at the top of my project navigator   -> General -> Deployment info -> Deployment Target -> (Set the the most current)</p>

Title: Cocoa Pods error with pod install


问:
#define function with variable name
I am continually writing something akin to

```<code>std::vector< std::vector< double > > A(N, std::vector< double >(M));
</code>```

and I would like to replace this with something like

```<code>matrix A(N,M);
</code>```

by using a #define directive. I've looked at #define directives and think I can create a function like matrix(A,N,M) that would declare a vector of vectors as follows:

```<code>#define matrix(A, N, M) std::vector< std::vector< double > > A(N, std::vector< double >(M))
</code>```

but I would rather not declare my matrices as matrix(A,N,M), but rather matrix A(N,M). My question is - how do I use the #define directives to account for changing a variable name?

答:
You can use typedef and define type, something like that:

```<code>#include <vector>
using namespace std;

int main()
{
    int N = 10;
    typedef std::vector< std::vector<double> matrix;
    matrix  A(N, std::vector< double >(N));
    return 0;

}
</code>```

or more safety (if you don't know, that matrix will be right)

```<code>int main()
{
    int N = 10;

    typedef std::vector< std::array<double, 5> > matrix;
    matrix  A(N, std::array< double , 5 >());
    return 0;
}
</code>```

my wrapper for matrix with vectors

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

template< typename T >
class WrapperMatrix
{
public:
    WrapperMatrix(const int& weight, const int& length);
    void pushLine(const std::vector<T>&&);
    void pushColumn(const std::vector<T>&&);
    void display();
private:
    std::vector<std::vector<T>> matrix;
};
template<typename T>
WrapperMatrix<T>::WrapperMatrix(const int& weight, const int& length)
{
    this->matrix = std::vector<std::vector<T>>(weight, std::vector<T>(length));
}

template <typename T>
void WrapperMatrix<T>::pushLine(const std::vector<T>&& newLine)
{
    if (newLine.size() == this->matrix.at(0).size())
        matrix.emplace_back(std::move(newLine));
    else
        throw std::invalid_argument("Invalis syntax");
}
template <typename T>
void WrapperMatrix<T>::pushColumn(const std::vector<T>&& newColumn)
{
    if (newColumn.size() == this->matrix.size())
    {
        for (int i = 0; i < matrix.size(); ++i)
            matrix.at(i).emplace_back(std::move(newColumn.at(i)));
    }
    else
        throw std::invalid_argument("Invalid syntax");
}
template<typename T>
void WrapperMatrix<T>::display()
{
    for (int i = 0; i < matrix.size(); ++i)
    {
        for (int j = 0; j < matrix.at(0).size(); ++j)
            std::cout << matrix.at(i).at(j);
        std::cout << std::endl;
    }
}
int main()
{
    std::vector<int> v1{ 1,2,3,4,5 };
    std::vector<int> v2{ 1,2,3,4,5,6 };
    std::vector<int> v3{ 2,3,4,5,6 };

    WrapperMatrix<int> vw(5,5);
    try {
        vw.pushLine(std::move(v1));
        vw.pushColumn(std::move(v2));
        //vw.pushLine(std::move(v3));
    }
    catch (const std::exception& e)
    {
        std::cout << e.what() << std::endl;
    }

    vw.display();
    return 0;
}
</code>```

Title: #define function with variable name

Body:
I am continually writing something akin to

std::vector< std::vector< double > > A(N, std::vector< double >(M));

and I would like to replace this with something like

matrix A(N,M);

by using a #define directive. I've looked at #define directives and think I can create a function like matrix(A,N,M) that would declare a vector of vectors as follows:

#define matrix(A, N, M) std::vector< std::vector< double > > A(N, std::vector< double >(M))

but I would rather not declare my matrices as matrix(A,N,M), but rather matrix A(N,M). My question is - how do I use the #define directives to account for changing a variable name?

Body:
You can use typedef and define type, something like that:

#include <vector>
using namespace std;

int main()
{
    int N = 10;
    typedef std::vector< std::vector<double> matrix;
    matrix  A(N, std::vector< double >(N));
    return 0;

}

or more safety (if you don't know, that matrix will be right)

int main()
{
    int N = 10;

    typedef std::vector< std::array<double, 5> > matrix;
    matrix  A(N, std::array< double , 5 >());
    return 0;
}

my wrapper for matrix with vectors

#include <iostream>
#include <vector>
#include <exception>
#include <algorithm>

template< typename T >
class WrapperMatrix
{
public:
    WrapperMatrix(const int& weight, const int& length);
    void pushLine(const std::vector<T>&&);
    void pushColumn(const std::vector<T>&&);
    void display();
private:
    std::vector<std::vector<T>> matrix;
};
template<typename T>
WrapperMatrix<T>::WrapperMatrix(const int& weight, const int& length)
{
    this->matrix = std::vector<std::vector<T>>(weight, std::vector<T>(length));
}

template <typename T>
void WrapperMatrix<T>::pushLine(const std::vector<T>&& newLine)
{
    if (newLine.size() == this->matrix.at(0).size())
        matrix.emplace_back(std::move(newLine));
    else
        throw std::invalid_argument("Invalis syntax");
}
template <typename T>
void WrapperMatrix<T>::pushColumn(const std::vector<T>&& newColumn)
{
    if (newColumn.size() == this->matrix.size())
    {
        for (int i = 0; i < matrix.size(); ++i)
            matrix.at(i).emplace_back(std::move(newColumn.at(i)));
    }
    else
        throw std::invalid_argument("Invalid syntax");
}
template<typename T>
void WrapperMatrix<T>::display()
{
    for (int i = 0; i < matrix.size(); ++i)
    {
        for (int j = 0; j < matrix.at(0).size(); ++j)
            std::cout << matrix.at(i).at(j);
        std::cout << std::endl;
    }
}
int main()
{
    std::vector<int> v1{ 1,2,3,4,5 };
    std::vector<int> v2{ 1,2,3,4,5,6 };
    std::vector<int> v3{ 2,3,4,5,6 };

    WrapperMatrix<int> vw(5,5);
    try {
        vw.pushLine(std::move(v1));
        vw.pushColumn(std::move(v2));
        //vw.pushLine(std::move(v3));
    }
    catch (const std::exception& e)
    {
        std::cout << e.what() << std::endl;
    }

    vw.display();
    return 0;
}