问:
Performing inheritance in JavaScript
Now while I know that you can not perform inheritance like you would in C#, I have seen it mentioned on the Internet that it is kind of possible. If it's not possible using plain JavaScript code then would it be possible using Ext JS and if so how?</p>

答:
Here is a simple example of inheritance. ClassA is a parent and ClassB is a child and common task is call a print method of ClassA through ClassB, therefore here the first initialized constructor then create prototype method for the parent class.    </p>

```<code>var ClassA = function() {
this.name = "class A";
 }
var a = new ClassA();
ClassA.prototype.print = function() {
alert(this.name);
}

var inheritsFrom = function (child, parent) {
 child.prototype = Object.create(parent.prototype);
 };
var ClassB = function() {
     this.name = "class B";
     this.surname = "I'm the child";
 }

 inheritsFrom(ClassB, ClassA);
 var b = new ClassB();
 b.print();
</code>```

Title: Performing inheritance in JavaScript

Body:
Here is a simple example of inheritance. ClassA is a parent and ClassB is a child and common task is call a print method of ClassA through ClassB, therefore here the first initialized constructor then create prototype method for the parent class.

var ClassA = function() {
this.name = "class A";
 }
var a = new ClassA();
ClassA.prototype.print = function() {
alert(this.name);
}

var inheritsFrom = function (child, parent) {
 child.prototype = Object.create(parent.prototype);
 };
var ClassB = function() {
     this.name = "class B";
     this.surname = "I'm the child";
 }

 inheritsFrom(ClassB, ClassA);
 var b = new ClassB();
 b.print();


来源: stackexchange

问:
Reading from a text file in java is returning some garbage value
I'm performing certain commands through command prompt and storing the values in a text file.

```<code> wmic logicaldisk where drivetype=3 get deviceid > drive.txt
</code>```

Now I want to read the string stored in the text file from my java file. When I try to do this:

```<code>            try {
            File file = new File("drive.txt");
            FileReader reader = new FileReader(file);
            BufferedReader in = new BufferedReader(reader);
            int i=0;
            while ((string[i] = in.readLine()) != null) {
                System.out.println(string[i]);
                    ++i;

            }
            in.close();
          } catch (IOException e) {
            e.printStackTrace();
          }
</code>```

I get the output as follows:

```<code> ÿþD[]E[]V[]I[]C[]E[]
</code>```

how to avoid this?

答: If you are using eclipse IDE, change the encoding type. Go to Edit->Set Encoding-> Others->UTF-8.</p>

ContentLicense: CC BY-SA 3.0

Body:
I'm performing certain commands through command prompt and storing the values in a text file.

 wmic logicaldisk where drivetype=3 get deviceid > drive.txt

Now I want to read the string stored in the text file from my java file. When I try to do this:

            try {
            File file = new File("drive.txt");
            FileReader reader = new FileReader(file);
            BufferedReader in = new BufferedReader(reader);
            int i=0;
            while ((string[i] = in.readLine()) != null) {
                System.out.println(string[i]);
                    ++i;

            }
            in.close();
          } catch (IOException e) {
            e.printStackTrace();
          }

I get the output as follows:

 ÿþD[]E[]V[]I[]C[]E[]

how to avoid this?


问:
How to deal with implicit dependency (e.g C++ include) for incremental build in custom Skylark rule

Problem

I wonder how to inform bazel about dependencies unknown at declaration time, but known at build time (a.k.a implicit dependencies, dynamic dependencies, ...). For instance when compiling C++ sources, the .cpp source file will depends on some header files and this information is not available when writing the BUILD file. It needs to be retrieve at build time. Whatever is the solution to get the information (dry-run, generating depfile, parsing stdout), it needs to be done at build time and the information need to be retrieved to bazel build graph.

Since skylark does not allow to do I/O, for instance to read a generated depfile or to parse stdout result containing a dependency list, I have no clue on how to deal with it.

Behind implicit dependencies, I am looking for correct incremental build.

Example

To experiment this problem I have created a simple tool, just_a_tool.exe which takes an input file, read a list of file from it, and concatenate the content of all these file to an output file.

command line example:

```<code>just_a_tool.exe --input input.txt --depfile dep.d output.txt
</code>```

dep.d contains the list of all the read files.

Issue

If I change the content of test1.txt, test2.txt, or test3.txt, bazel does not rebuild output.txt file. Of course, because it does not know there were dependencies.

Example files

just_a_tool.bzl

```<code>def _impl(ctx):
    exec_path = "C:/Code/JustATool/just_a_tool.exe"

    for f in ctx.attr.source.files:
        source_path = f.path
    output_path = ctx.outputs.out.path

    dep_file = ctx.actions.declare_file("dep.d")

    args = ["--input", source_path, "--dep_file", dep_file.path, output_path]

    ctx.actions.run(
        outputs=[ctx.outputs.out, dep_file],
        executable=exec_path,
        inputs=ctx.attr.source.files,
        arguments=args
    )

jat_convert = rule(
    implementation = _impl,
    attrs = {
        "source" : attr.label(mandatory=True, allow_files=True, single_file=True)
    },
    outputs = {"out": "%{name}.txt"}
)
</code>```

BUILD

```<code>load("//tool:just_a_tool.bzl", "jat_convert")

jat_convert(
    name="my_output",
    source=":input.txt"
)
</code>```

input.txt

```<code>test1.txt
test2.txt
test3.txt
</code>```

Goal

I want to do correct and fast incremental build for the following situation:

Generate reflection data from C++ sources, this custom tool execution depends on header file included in my source files.

Use a internal tool to build asset file which can include other files

Run a custom preprocessor on my shaders allowing a #include feature

Thanks!

答:
Bazel's extension language doesn't support creating actions with a dynamic set of inputs, where this set depends on the output of a previous action. In other words, custom rules cannot run an action, read the action's output, then create actions with those inputs or update (or prune the set of) inputs of already created actions.

Instead I suggest adding attribute(s) to your rule where the user can declare the set of files that the sources may include. I call this "the universe of headers". The actions you create depend on this user-defined universe, so the set of action inputs is completely defined. Of course this means these actions potentially depend on more files than the cpp files, which they process, include.

This approach is analogous to how the cc_* rules work: a file in cc_*.srcs can include other files in the srcs of the same rule and from hdrs of dependencies, but nothing else. Thus the union of srcs + hdrs of (direct & transitive) dependencies defines the universe of header files that a cpp file may include.

Body:
Problem

I wonder how to inform bazel about dependencies unknown at declaration time, but known at build time (a.k.a implicit dependencies, dynamic dependencies, ...). For instance when compiling C++ sources, the .cpp source file will depends on some header files and this information is not available when writing the BUILD file. It needs to be retrieve at build time. Whatever is the solution to get the information (dry-run, generating depfile, parsing stdout), it needs to be done at build time and the information need to be retrieved to bazel build graph.

Since skylark does not allow to do I/O, for instance to read a generated depfile or to parse stdout result containing a dependency list, I have no clue on how to deal with it.

Behind implicit dependencies, I am looking for correct incremental build.

Example

To experiment this problem I have created a simple tool, just_a_tool.exe which takes an input file, read a list of file from it, and concatenate the content of all these file to an output file.

command line example:

just_a_tool.exe --input input.txt --depfile dep.d output.txt

dep.d contains the list of all the read files.

Issue

If I change the content of test1.txt, test2.txt, or test3.txt, bazel does not rebuild output.txt file. Of course, because it does not know there were dependencies.

Example files

just_a_tool.bzl

def _impl(ctx):
    exec_path = "C:/Code/JustATool/just_a_tool.exe"

    for f in ctx.attr.source.files:
        source_path = f.path
    output_path = ctx.outputs.out.path

    dep_file = ctx.actions.declare_file("dep.d")

    args = ["--input", source_path, "--dep_file", dep_file.path, output_path]

    ctx.actions.run(
        outputs=[ctx.outputs.out, dep_file],
        executable=exec_path,
        inputs=ctx.attr.source.files,
        arguments=args
    )

jat_convert = rule(
    implementation = _impl,
    attrs = {
        "source" : attr.label(mandatory=True, allow_files=True, single_file=True)
    },
    outputs = {"out": "%{name}.txt"}
)

BUILD

load("//tool:just_a_tool.bzl", "jat_convert")

jat_convert(
    name="my_output",
    source=":input.txt"
)

input.txt

test1.txt
test2.txt
test3.txt

Goal

I want to do correct and fast incremental build for the following situation:

Generate reflection data from C++ sources, this custom tool execution depends on header file included in my source files.

Use a internal tool to build asset file which can include other files

Run a custom preprocessor on my shaders allowing a #include feature

Thanks!


问:
Asp.net core 2.0 Jwt doesn't ignore AllowAnonymous
I'm making a small new project using .net core 2.0 and jwt bearer authentication (https://github.com/aspnet/Security)

Here is my Startup.cs

```<code>        /// <summary>
        ///     This method gets called by the runtime. Use this method to add services to the container.
        /// </summary>
        /// <param name="services"></param>
        public void ConfigureServices(IServiceCollection services)
        {
            // Add entity framework to services collection.
            var sqlConnection = Configuration.GetConnectionString("SqlServerConnectionString");
            services.AddDbContext<RelationalDatabaseContext>(
                options => options.UseSqlServer(sqlConnection, b => b.MigrationsAssembly(nameof(Main))));

            // Injections configuration.
            services.AddScoped<IUnitOfWork, UnitOfWork>();
            services.AddScoped<DbContext, RelationalDatabaseContext>();
            services.AddScoped<IEncryptionService, EncryptionService>();
            services.AddScoped<IIdentityService, IdentityService>();
            services.AddScoped<ITimeService, TimeService>();
            services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();

            // Requirement handler.
            services.AddScoped<IAuthorizationHandler, SolidAccountRequirementHandler>();
            services.AddScoped<IAuthorizationHandler, RoleRequirementHandler>();

            // Load jwt configuration from setting files.
            services.Configure<JwtConfiguration>(Configuration.GetSection(nameof(JwtConfiguration)));
            services.Configure<ApplicationSetting>(Configuration.GetSection(nameof(ApplicationSetting)));

            // Build a service provider.
            var serviceProvider = services.BuildServiceProvider();
            var jwtBearerSettings = serviceProvider.GetService<IOptions<JwtConfiguration>>().Value;

            // Cors configuration.
            var corsBuilder = new CorsPolicyBuilder();
            corsBuilder.AllowAnyHeader();
            corsBuilder.AllowAnyMethod();
            corsBuilder.AllowAnyOrigin();
            corsBuilder.AllowCredentials();

            // Add cors configuration to service configuration.
            services.AddCors(options => { options.AddPolicy("AllowAll", corsBuilder.Build()); });
            services.AddOptions();

            // This can be removed after https://github.com/aspnet/IISIntegration/issues/371
            var authenticationBuilder = services.AddAuthentication(options =>
            {
                options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
                options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
            });

            authenticationBuilder.AddJwtBearer(o =>
            {
                // You also need to update /wwwroot/app/scripts/app.js
                o.Authority = jwtBearerSettings.Authority;
                o.Audience = jwtBearerSettings.Audience;
                o.RequireHttpsMetadata = false;

                o.SecurityTokenValidators.Clear();
                o.SecurityTokenValidators.Add(new JwtBearerValidator());

                o.Events = new JwtBearerEvents()
                {
                    OnAuthenticationFailed = c =>
                    {
                        c.NoResult();

                        c.Response.StatusCode = 500;
                        c.Response.ContentType = "text/plain";
                        if ("dev".Equals(Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT")))
                        {
                            // Debug only, in production do not share exceptions with the remote host.
                            return c.Response.WriteAsync(c.Exception.ToString());
                        }
                        return c.Response.WriteAsync("An error occurred processing your authentication.");
                    }
                };
            });

            #region Mvc builder

            // Construct mvc options.
            var mvcBuilder =
                services.AddMvc(mvcOptions =>
                {
                    //only allow authenticated users
                    var policy = new AuthorizationPolicyBuilder()
                        .RequireAuthenticatedUser()
                        .AddAuthenticationSchemes(JwtBearerDefaults.AuthenticationScheme)
                        .AddRequirements(new SolidAccountRequirement())
                        .Build();

                    mvcOptions.Filters.Add(new AuthorizeFilter(policy));
                });

            // Add json configuration/
            mvcBuilder.AddJsonOptions(options =>
            {
                options.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
            });

            #endregion
        }

        /// <summary>
        ///     This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        /// </summary>
        /// <param name="app"></param>
        /// <param name="env"></param>
        /// <param name="loggerFactory"></param>
        /// <param name="serviceProvider"></param>
        public void Configure(IApplicationBuilder app,
            IHostingEnvironment env,
            ILoggerFactory loggerFactory, IServiceProvider serviceProvider)
        {
            // Enable logging.
            loggerFactory.AddConsole(Configuration.GetSection("Logging"));
            loggerFactory.AddDebug();

            // Use JWT Bearer authentication in the system.
            app.UseAuthentication();

            // Enable cors.
            app.UseCors("AllowAll");

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

With these configurations, jwt has been enabled in my web application. But, there is one thing I'm currently facing with:

With API doesn't require authentication (placed under [AllowAnonymous] attribute), if I pass Authorization header in my request, OnAuthenticationFailed event will be raised (due to no token is detected).

My question is: How can I make my jwt authentication automatically ignore methods or controller which is marked as AllowAnonymous ?

Thank you,

答:
I think , it's because you are adding two authentication at the same time, one with jwt and other one with this code.

```<code> var mvcBuilder =
                services.AddMvc(mvcOptions =>
                {
                    //only allow authenticated users
                    var policy = new AuthorizationPolicyBuilder()
                        .RequireAuthenticatedUser()
                        .AddAuthenticationSchemes(JwtBearerDefaults.AuthenticationScheme)
                        .AddRequirements(new SolidAccountRequirement())
                        .Build();

                    mvcOptions.Filters.Add(new AuthorizeFilter(policy));
                });
</code>```

Keep just the jwt and if you want to add policies you can do it like this example

```<code>services.AddAuthorization(options =>
                {
                    options.AddPolicy("CreateUser", policy => policy.AddRequirements(
                    new UserLevelRequirement("Admin")
                ));
                })
</code>```

You don't to configure twice the authorization.

Body:
I'm making a small new project using .net core 2.0 and jwt bearer authentication (https://github.com/aspnet/Security)

Here is my Startup.cs

        ///
        ///     This method gets called by the runtime. Use this method to add services to the container.
        ///
        /// <param name="services"></param>
        public void ConfigureServices(IServiceCollection services)
        {
            // Add entity framework to services collection.
            var sqlConnection = Configuration.GetConnectionString("SqlServerConnectionString");
            services.AddDbContext<RelationalDatabaseContext>(
                options => options.UseSqlServer(sqlConnection, b => b.MigrationsAssembly(nameof(Main))));

            // Injections configuration.
            services.AddScoped<IUnitOfWork, UnitOfWork>();
            services.AddScoped<DbContext, RelationalDatabaseContext>();
            services.AddScoped<IEncryptionService, EncryptionService>();
            services.AddScoped<IIdentityService, IdentityService>();
            services.AddScoped<ITimeService, TimeService>();
            services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();

            // Requirement handler.
            services.AddScoped<IAuthorizationHandler, SolidAccountRequirementHandler>();
            services.AddScoped<IAuthorizationHandler, RoleRequirementHandler>();

            // Load jwt configuration from setting files.
            services.Configure<JwtConfiguration>(Configuration.GetSection(nameof(JwtConfiguration)));
            services.Configure<ApplicationSetting>(Configuration.GetSection(nameof(ApplicationSetting)));

            // Build a service provider.
            var serviceProvider = services.BuildServiceProvider();
            var jwtBearerSettings = serviceProvider.GetService<IOptions<JwtConfiguration>>().Value;

            // Cors configuration.
            var corsBuilder = new CorsPolicyBuilder();
            corsBuilder.AllowAnyHeader();
            corsBuilder.AllowAnyMethod();
            corsBuilder.AllowAnyOrigin();
            corsBuilder.AllowCredentials();

            // Add cors configuration to service configuration.
            services.AddCors(options => { options.AddPolicy("AllowAll", corsBuilder.Build()); });
            services.AddOptions();

            // This can be removed after https://github.com/aspnet/IISIntegration/issues/371
            var authenticationBuilder = services.AddAuthentication(options =>
            {
                options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
                options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
            });

            authenticationBuilder.AddJwtBearer(o =>
            {
                // You also need to update /wwwroot/app/scripts/app.js
                o.Authority = jwtBearerSettings.Authority;
                o.Audience = jwtBearerSettings.Audience;
                o.RequireHttpsMetadata = false;

                o.SecurityTokenValidators.Clear();
                o.SecurityTokenValidators.Add(new JwtBearerValidator());

                o.Events = new JwtBearerEvents()
                {
                    OnAuthenticationFailed = c =>
                    {
                        c.NoResult();

                        c.Response.StatusCode = 500;
                        c.Response.ContentType = "text/plain";
                        if ("dev".Equals(Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT")))
                        {
                            // Debug only, in production do not share exceptions with the remote host.
                            return c.Response.WriteAsync(c.Exception.ToString());
                        }
                        return c.Response.WriteAsync("An error occurred processing your authentication.");
                    }
                };
            });

            #region Mvc builder

            // Construct mvc options.
            var mvcBuilder =
                services.AddMvc(mvcOptions =>
                {
                    //only allow authenticated users
                    var policy = new AuthorizationPolicyBuilder()
                        .RequireAuthenticatedUser()
                        .AddAuthenticationSchemes(JwtBearerDefaults.AuthenticationScheme)
                        .AddRequirements(new SolidAccountRequirement())
                        .Build();

                    mvcOptions.Filters.Add(new AuthorizeFilter(policy));
                });

            // Add json configuration/
            mvcBuilder.AddJsonOptions(options =>
            {
                options.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
            });

            #endregion
        }

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

            // Use JWT Bearer authentication in the system.
            app.UseAuthentication();

            // Enable cors.
            app.UseCors("AllowAll");

            // Enable MVC features.
            app.UseMvc();
        }

With these configurations, jwt has been enabled in my web application. But, there is one thing I'm currently facing with:

With API doesn't require authentication (placed under [AllowAnonymous] attribute), if I pass Authorization header in my request, OnAuthenticationFailed event will be raised (due to no token is detected).

My question is: How can I make my jwt authentication automatically ignore methods or controller which is marked as AllowAnonymous ?

Thank you,

Body:
I think , it's because you are adding two authentication at the same time, one with jwt and other one with this code.

 var mvcBuilder =
                services.AddMvc(mvcOptions =>
                {
                    //only allow authenticated users
                    var policy = new AuthorizationPolicyBuilder()
                        .RequireAuthenticatedUser()
                        .AddAuthenticationSchemes(JwtBearerDefaults.AuthenticationScheme)
                        .AddRequirements(new SolidAccountRequirement())
                        .Build();

                    mvcOptions.Filters.Add(new AuthorizeFilter(policy));
                });

Keep just the jwt and if you want to add policies you can do it like this example

services.AddAuthorization(options =>
                {
                    options.AddPolicy("CreateUser", policy => policy.AddRequirements(
                    new UserLevelRequirement("Admin")
                ));
                })

You don't to configure twice the authorization.


问:
Tracing instantiation in a base class
Currently I trace number of instances of a base class this way:

```<code>private static int _instanceCount = 0;

protected BaseClass()
{
    Interlocked.Increment(ref _instanceCount);

    if (_instanceCount > 1)
        throw new Exception("multiple instances detected.");
}
</code>```

Then I have child classes with constructor like this:

```<code>public ChildClass(): base()
{
    // Empty Constructor
}
</code>```

and I get exceptions of course. I can move the code from BaseClass constructor to ChildClass constructor but it's a kind of redundancy (all children with the same code).

Is there any way to do it in the BaseClass?

Is getting exception means I really tried to create more than one instance of the ChildClass according to above code?

答: If you want a Singleton factory, you could consider using an IoC container instead of rolling your own. Many IoC containers support Singleton factory behaviour as a standard feature. For instance you could use Unity. </p>

ContentLicense: CC BY-SA 2.5

Title: Tracing instantiation in a base class

Body:
Currently I trace number of instances of a base class this way:

private static int _instanceCount = 0;

protected BaseClass()
{
    Interlocked.Increment(ref _instanceCount);

    if (_instanceCount > 1)
        throw new Exception("multiple instances detected.");
}

Then I have child classes with constructor like this:

public ChildClass(): base()
{
    // Empty Constructor
}

and I get exceptions of course. I can move the code from BaseClass constructor to ChildClass constructor but it's a kind of redundancy (all children with the same code).

Is there any way to do it in the BaseClass?

Is getting exception means I really tried to create more than one instance of the ChildClass according to above code?


问:
Where can I find the API documentation of the class Input?
Where can I find the API documentation of the class keras.layers.Input? I couldn't find it at https://keras.io/.

答:
Most of the things have been summarized by the above answer. But as mentioned in the comment, I think the tf.contrib.keras contains docs about keras. This link contains documentation for the same.

As mentioned in the accepted answer, Input can be used with model to denote the tensor. It, in fact, returns a tensor. The way I understand it is, it is somewhat similar to tf.placeholder as it allows us to define the model in terms of the Input object alone and fit the model later on. The following is the example from the tensorflow docs.

```<code># this is a logistic regression in Keras
x = Input(shape=(32,))
y = Dense(16, activation='softmax')(x)
model = Model(x, y)
</code>```

It can be seen here how the usage of Input is somewhat similar to that of tf.placeholder

ContentLicense: CC BY-SA 4.0

Body:
Most of the things have been summarized by the above answer. But as mentioned in the comment, I think the tf.contrib.keras contains docs about keras. This link contains documentation for the same.

As mentioned in the accepted answer, Input can be used with model to denote the tensor. It, in fact, returns a tensor. The way I understand it is, it is somewhat similar to tf.placeholder as it allows us to define the model in terms of the Input object alone and fit the model later on. The following is the example from the tensorflow docs.

# this is a logistic regression in Keras
x = Input(shape=(32,))
y = Dense(16, activation='softmax')(x)
model = Model(x, y)

It can be seen here how the usage of Input is somewhat similar to that of tf.placeholder


问:
Chrome canary headless mode does not work on windows10
Google Chrome Canary does not work with headless on Windows.

Chrome headless does not work on windows.
The Error happens like following when I tried to execute below code.
But it works on non-headless mode.

I know Canary is unstable but I want to using it to learning about web advanced spec.

This error caused by bug in canary?
Or caused by my code?

code:

```<code>from selenium import webdriver
from selenium.webdriver.chrome.options import Options

op = Options()
op.binary_location = "C:\\Users\\username\\AppData\\Local\\Google\\Chrome SxS\\Application\\chrome.exe"
op.add_argument("--headless")
op.add_argument("--disable-gpu")

driver = webdriver.Chrome("chromedriver.exe", chrome_options=op)

driver.get("http://www.google.com")
</code>```

Error:

```<code>[1205/232511.644:ERROR:gpu_process_transport_factory.cc(1017)] Lost UI shared context.
[1205/232511.644:ERROR:instance.cc(49)] Unable to locate service manifest for metrics
[1205/232511.644:ERROR:service_manager.cc(890)] Failed to resolve service name: metrics

DevTools listening on ws://127.0.0.1:12022/devtools/browser/3d7c8ff8-625a-4326-b968-bbff
[1205/232511.714:ERROR:instance.cc(49)] Unable to locate service manifest for metrics
[1205/232511.714:ERROR:service_manager.cc(890)] Failed to resolve service name: metrics
[1205/232511.714:ERROR:instance.cc(49)] Unable to locate service manifest for metrics
[1205/232511.714:ERROR:service_manager.cc(890)] Failed to resolve service name: metrics
[1205/232513.037:ERROR:instance.cc(49)] Unable to locate service manifest for metrics
[1205/232513.037:ERROR:service_manager.cc(890)] Failed to resolve service name: metrics
</code>```

OS: windows 10 Home 1709

Chrome: 65.0.3285.0 (Official Build) canary 64bit

ChromeDriver: 2.33.506120

答:
As your error logs reports as follows :

```<code>[1205/232511.644:ERROR:gpu_process_transport_factory.cc(1017)] Lost UI shared context.
[1205/232511.644:ERROR:instance.cc(49)] Unable to locate service manifest for metrics
[1205/232511.644:ERROR:service_manager.cc(890)] Failed to resolve service name: metrics
</code>```

I will suggest the following steps :

Uninstall Google Chrome Canary from your system through Revo Uninstaller

Use CCleaner tool to wipe off all the OS chores.

Install fresh Google Chrome Canary

Use the following code block :

```<code>from selenium import webdriver
from selenium.webdriver.chrome.options import Options

op = Options()
op.binary_location = "C:\\Users\\username\\AppData\\Local\\Google\\Chrome SxS\\Application\\chrome.exe"
op.add_argument("--headless")
op.add_argument("--disable-gpu")
driver = webdriver.Chrome(chrome_options=op, executable_path=r'C:\path\to\chromedriver.exe')
driver.get("http://google.com/")
</code>```

You can find about multiple ways to work with multiple Chrome Browser Binaries in Set chrome browser binary to chrome webdriver in Python discussion.

Body:
Google Chrome Canary does not work with headless on Windows.

Chrome headless does not work on windows.
The Error happens like following when I tried to execute below code.
But it works on non-headless mode.

I know Canary is unstable but I want to using it to learning about web advanced spec.

This error caused by bug in canary?
Or caused by my code?

code:

from selenium import webdriver
from selenium.webdriver.chrome.options import Options

op = Options()
op.binary_location = "C:\\Users\\username\\AppData\\Local\\Google\\Chrome SxS\\Application\\chrome.exe"
op.add_argument("--headless")
op.add_argument("--disable-gpu")

driver = webdriver.Chrome("chromedriver.exe", chrome_options=op)

driver.get("http://www.google.com")

Error:

[1205/232511.644:ERROR:gpu_process_transport_factory.cc(1017)] Lost UI shared context.
[1205/232511.644:ERROR:instance.cc(49)] Unable to locate service manifest for metrics
[1205/232511.644:ERROR:service_manager.cc(890)] Failed to resolve service name: metrics

DevTools listening on ws://127.0.0.1:12022/devtools/browser/3d7c8ff8-625a-4326-b968-bbff
[1205/232511.714:ERROR:instance.cc(49)] Unable to locate service manifest for metrics
[1205/232511.714:ERROR:service_manager.cc(890)] Failed to resolve service name: metrics
[1205/232511.714:ERROR:instance.cc(49)] Unable to locate service manifest for metrics
[1205/232511.714:ERROR:service_manager.cc(890)] Failed to resolve service name: metrics
[1205/232513.037:ERROR:instance.cc(49)] Unable to locate service manifest for metrics
[1205/232513.037:ERROR:service_manager.cc(890)] Failed to resolve service name: metrics

OS: windows 10 Home 1709

Chrome: 65.0.3285.0 (Official Build) canary 64bit

ChromeDriver: 2.33.506120

Body:
As your error logs reports as follows :

[1205/232511.644:ERROR:gpu_process_transport_factory.cc(1017)] Lost UI shared context.
[1205/232511.644:ERROR:instance.cc(49)] Unable to locate service manifest for metrics
[1205/232511.644:ERROR:service_manager.cc(890)] Failed to resolve service name: metrics

I will suggest the following steps :

Uninstall Google Chrome Canary from your system through Revo Uninstaller

Use CCleaner tool to wipe off all the OS chores.

Install fresh Google Chrome Canary

Use the following code block :

from selenium import webdriver
from selenium.webdriver.chrome.options import Options

op = Options()
op.binary_location = "C:\\Users\\username\\AppData\\Local\\Google\\Chrome SxS\\Application\\chrome.exe"
op.add_argument("--headless")
op.add_argument("--disable-gpu")
driver = webdriver.Chrome(chrome_options=op, executable_path=r'C:\path\to\chromedriver.exe')
driver.get("http://google.com/")

You can find about multiple ways to work with multiple Chrome Browser Binaries in Set chrome browser binary to chrome webdriver in Python discussion.


问:
How to maintain session for a user until user is logged-in in spring mvc
I'm creating a project in spring mvc, hibernate. I'm stuck at maintaining sessions after a user is logged in. I want to maintain the session until the user is logged in.
Thanks.</p>

答:
Using the controller to log in your user you could create and store your session there...

```<code>    public ModelAndView yourMethod(HttpSession session){

    session.setAttribute("user", 1);
    return new ModelAndView("home");

}
</code>```

If you want to retrieve it you can do it like this

```<code>Long userId = (Long) session.getAttribute("user");
</code>```

Spring will maintain the session for you,

Body:
Using the controller to log in your user you could create and store your session there...

    public ModelAndView yourMethod(HttpSession session){

    session.setAttribute("user", 1);
    return new ModelAndView("home");

}

If you want to retrieve it you can do it like this

Long userId = (Long) session.getAttribute("user");

Spring will maintain the session for you,


问:
Encapsulate Spirit X3 parser in class
I tried to encapsulate a X3 parser in a class, where the rules (and their definitions) are members, i.e. similar to the structure of a Qi parser where one had to derive from boost::spirit::qi::grammar.

What would be the advantages of this approach:

better separation of code than the namespace approach used in the examples (e.g. to avoid namespace clash)

the parser is only instantiated when an object of this class is generated instead of the parser (the individual rules) being static

potential parameters (e.g. question Parser rule dependent on parameter) might be given to the constructor and integrated in a "direct" way instead of using the with<> directive

But this does not seem possible. Defining the rules (or rather rule definitions) in the form auto name = rule<class name, std::string>() = alpha >> *alnum; is not an option as auto is not possible for class members. On the other hand, stating the actual type does not seem practical either, apart from very small parsers.
A modeling alternative would be to have the rules as members and create the definitions in the constructor, but here the linking between them, usually done with BOOST_SPIRIT_DEFINE, is not possible and the rule alone is not enough to parse (static_assert failed "BOOST_SPIRIT_DEFINE undefined for this rule.").

Also, having the whole parser in a class method, e.g. ParseXYZ::parse(), which creates the parser - probably via another method such that it is created only once - and parses the input, is not really an option when it comes to code reuse (apart from copy&paste).

Do you know whether it is possible to encapsulate an X3 parser in a class? Besides that, what are your suggestions to build reusable parsers in X3?

答: Yes it is possible, Instead of auto name = rule<class name, std::string>() = alpha >> *alnum; you do decltype(rule<class name, std::string>() = alpha >> *alnum) name; in the definition, and name{rule<class name, std::string>() = alpha >> *alnum} in the constructor.

Title: Encapsulate Spirit X3 parser in class


问:
Define expected parameters for a controller action in Rails
I remember once seeing the ability to define at the top of a controller the parameters that an action requires to work. For the life of me I can't seem to find any mention of that capability anymore and it would be useful for the following:

```<code>def sort
  params[:links].each_with_index do |id, index|
    @link_set.links.in_context(context).update_all(['position=?', index+1], ['id=?', id])
  end
  render :nothing => true
end
</code>```

I'm expecting params[:links] so if some smarty decides to visit that action without giving me params then it fails with nil.each_with_index.

It'd be nice to gracefully give a 404 or something if the parameters are missing without having to code this into every method of this type.

Does this exist? :)

答:
Actually, stumbled across this article: http://rails.nuvvo.com/lesson/6376-action-controller-verification

The method is called verify and you can specify things like parameters to expect. :)

Body:
I remember once seeing the ability to define at the top of a controller the parameters that an action requires to work. For the life of me I can't seem to find any mention of that capability anymore and it would be useful for the following:

def sort
  params[:links].each_with_index do |id, index|
    @link_set.links.in_context(context).update_all(['position=?', index+1], ['id=?', id])
  end
  render :nothing => true
end

I'm expecting params[:links] so if some smarty decides to visit that action without giving me params then it fails with nil.each_with_index.

It'd be nice to gracefully give a 404 or something if the parameters are missing without having to code this into every method of this type.

Does this exist? :)


问:
How to perform nested sorting in sql?
I have following data:

id      name        score
1       sam               5
2       sam               1
3       jerry             6
4       jerry             2
5       sam               3

I want it like

id      name        score
3       jerry             6
4       jerry             2
1       sam               5
5       sam               3
2       sam               1

I want to perform nested sorting in this table I want result which is sorted by similar lastname and those last name is sorted by score

but it not working and giving me wrong result can anyone tell me how to do this??

答:
First of all, why do you join this table "ex" with itself? And why do you join on a non-unique column lastname?

Probably you need a query like

```<code>select id, lastname, monthly_sales_target
  from ex
 order by lastname, monthly_sales_target;
</code>```

This will sort your result by lastname and within lastname by monthly_sales_target.

Title: How to perform nested sorting in sql?

Body:
First of all, why do you join this table "ex" with itself? And why do you join on a non-unique column lastname?

Probably you need a query like

select id, lastname, monthly_sales_target
  from ex
 order by lastname, monthly_sales_target;

This will sort your result by lastname and within lastname by monthly_sales_target.


问:
Combining $("#myId").val() with $(this).val()
I would like to combine

```<code>$("#myId").val()
</code>```

and

```<code>$(this).val()
</code>```

so that I can use the same id and a name value connected to an array -- characters[x].name -- to store and display different names.

http://jsfiddle.net/ren1999/Fae95/

答:
Try this:

```<code>$.each([["#getName1", "#displayName1"], ["#getName2", "#displayName2"]],
function (i, names) {
    $(names[0]).blur(function () {
        var name=$(this).val();
        $(names[1]).text(name);
    });
})
</code>```

You can simply add more inputs by adding them too the array.

Body:
I would like to combine

$("#myId").val()

and

$(this).val()

so that I can use the same id and a name value connected to an array -- characters[x].name -- to store and display different names.

http://jsfiddle.net/ren1999/Fae95/

Body:
Try this:

$.each([["#getName1", "#displayName1"], ["#getName2", "#displayName2"]],
function (i, names) {
    $(names[0]).blur(function () {
        var name=$(this).val();
        $(names[1]).text(name);
    });
})

You can simply add more inputs by adding them too the array.


问:
Kivy - Editable RecycleView
I'm trying to create an editable table with the RecycleView widget using a TextInput widget as the individual element in Kivy. By looking at the examples and some posts on the web, I was able to write a table that takes input from the user.

Now I'm trying to get which row did the user edit. I could find events for on_text of the text input but that doesn't give information about the row number. Also I tried looking at the events available for the RecycleView but couldn't get much help from it.

Could anyone of you guide me in the right path. I'm fairly new to kivy. I have attached herewith, a simple example that I'm working on.

```<code>from kivy.app import App
from kivy.uix.recycleview import RecycleView
from kivy.lang import Builder

Builder.load_string('''
<Row@BoxLayout>:
    canvas.before:
        Color:
            rgba: 0.5, 0.5, 0.5, 1
        Rectangle:
            size: self.size
            pos: self.pos
    itemText: ''
    TextInput:
        id:CellText
        text:root.itemText

<RV>:
    id: rv
    viewclass: 'Row'
    scroll_type: ['bars', 'content']
    scroll_wheel_distance: dp(114)
    bar_width: dp(10)
    RecycleGridLayout:
        cols:3
        default_size: None, dp(30)
        default_size_hint: 1, None
        size_hint_y: None
        height: self.minimum_height
        orientation: 'vertical'
        spacing: dp(1)
''')

class RV(RecycleView):

    def __init__(self, **kwargs):
        super(RV, self).__init__(**kwargs)
        self.data = [{'itemText':'1'}, {'itemText':'John'}, {'itemText':'K'}, {'itemText':'2'}, {'itemText':'David'}, {'itemText':'P'}]

class rvTestApp(App):

    def build(self):
        return RV()

if __name__ == '__main__':
    rvTestApp().run()
</code>```

答:
SP SP's answer gets a way to work around this problem but I found another way (hoping this to be a better one) to get the row index.

Adding the below over-riding functions into the row class helped me get the row index when ever the user clicks on the textinput.

```<code>class Row(BoxLayout, RecycleDataViewBehavior):
index = None

def refresh_view_attrs(self, rv, index, data):
    ''' Catch and handle the view changes '''
    self.index = index
    return super(Row, self).refresh_view_attrs(
        rv, index, data)

def on_touch_down(self, touch):
    if super(Row, self).on_touch_down(touch):
        return True
    if self.collide_point(*touch.pos):
        global rowIndex
        rowIndex = self.index
</code>```

Thanks again for helping me with your suggestions. Posting my solution in case if any one else is facing the same problem.

Title: Kivy - Editable RecycleView

Body:
I'm trying to create an editable table with the RecycleView widget using a TextInput widget as the individual element in Kivy. By looking at the examples and some posts on the web, I was able to write a table that takes input from the user.

Now I'm trying to get which row did the user edit. I could find events for on_text of the text input but that doesn't give information about the row number. Also I tried looking at the events available for the RecycleView but couldn't get much help from it.

Could anyone of you guide me in the right path. I'm fairly new to kivy. I have attached herewith, a simple example that I'm working on.

from kivy.app import App
from kivy.uix.recycleview import RecycleView
from kivy.lang import Builder

Builder.load_string('''
<Row@BoxLayout>:
    canvas.before:
        Color:
            rgba: 0.5, 0.5, 0.5, 1
        Rectangle:
            size: self.size
            pos: self.pos
    itemText: ''
    TextInput:
        id:CellText
        text:root.itemText

<RV>:
    id: rv
    viewclass: 'Row'
    scroll_type: ['bars', 'content']
    scroll_wheel_distance: dp(114)
    bar_width: dp(10)
    RecycleGridLayout:
        cols:3
        default_size: None, dp(30)
        default_size_hint: 1, None
        size_hint_y: None
        height: self.minimum_height
        orientation: 'vertical'
        spacing: dp(1)
''')

class RV(RecycleView):

    def __init__(self, **kwargs):
        super(RV, self).__init__(**kwargs)
        self.data = [{'itemText':'1'}, {'itemText':'John'}, {'itemText':'K'}, {'itemText':'2'}, {'itemText':'David'}, {'itemText':'P'}]

class rvTestApp(App):

    def build(self):
        return RV()

if __name__ == '__main__':
    rvTestApp().run()

Body:
SP SP's answer gets a way to work around this problem but I found another way (hoping this to be a better one) to get the row index.

Adding the below over-riding functions into the row class helped me get the row index when ever the user clicks on the textinput.

class Row(BoxLayout, RecycleDataViewBehavior):
index = None

def refresh_view_attrs(self, rv, index, data):
    ''' Catch and handle the view changes '''
    self.index = index
    return super(Row, self).refresh_view_attrs(
        rv, index, data)

def on_touch_down(self, touch):
    if super(Row, self).on_touch_down(touch):
        return True
    if self.collide_point(*touch.pos):
        global rowIndex
        rowIndex = self.index

Thanks again for helping me with your suggestions. Posting my solution in case if any one else is facing the same problem.


问:
Does ng-init and ng-repeat bind properly?
```<code><tr data-ng-repeat="x in AList" data-ng-init="loopIndex=$index;">
<select data-ng-model='y.value' style="width:80%;margin-left:20px;" data-ng-change="filter()" data-ng-init="test123=x.name;">
<option data-ng-repeat="y in BList" value="{{y.test123}}">{{y.test123}}></option>
</code>```

The above code has 2 arrays

Alist which has field name, the value of name is a field in Blist, lets suppose value of field name  in Alist is text.

When I directly write y.text instead of y.test123, the value populates on the screen and also in option value, but when I try to fetch the value in test123 and then I write the above code, neither the value populates in option value nor it is displayed on the screen.

答:
If you call y.test123 you should have a attribute inside the BLits array.

ex: BLits = [test123:'sampletext']

data-ng-init="test123=x.name;" this code should work and if you use {{test123}} it will populate the x.name value.

so I assume you don't have a attribute called test123 inside BLits array and so it does not populate any value. instead it will give a error on your console.

Body:
<select data-ng-model='y.value' style="width:80%;margin-left:20px;" data-ng-change="filter()" data-ng-init="test123=x.name;">
<option data-ng-repeat="y in BList" value="{{y.test123}}">{{y.test123}}></option>

The above code has 2 arrays

Alist which has field name, the value of name is a field in Blist, lets suppose value of field name  in Alist is text.

When I directly write y.text instead of y.test123, the value populates on the screen and also in option value, but when I try to fetch the value in test123 and then I write the above code, neither the value populates in option value nor it is displayed on the screen.


问:
Fabric: How to edit file across machines?
Is there a way to use Fabric to open editor and set text?

I have to set new keys on 50+ servers and not willing to do it manually.

答:
okay create .aws directory in your local machine and put whatever contents you want to copy.

install sshpass

run this command over a loop changing hostname and password

```<code>sshpass -p abcpass rsync -arvce "ssh -o StrictHostKeyChecking=no" ./* user@ip:/home/user/.aws
</code>```

Body:
okay create .aws directory in your local machine and put whatever contents you want to copy.

install sshpass

run this command over a loop changing hostname and password

sshpass -p abcpass rsync -arvce "ssh -o StrictHostKeyChecking=no" ./* user@ip:/home/user/.aws


问:
Should you separate matrix data and math?
I am trying to make some simple classes to do the math necessary for OpenGL transformations. However, now that I am about halfway and while looking through different examples I find that most libraries keep the math separate of the matrix class itself (most of the times in math class with static methods). What exactly is the reason for this?

Is it when you're creating multiple of the matrix objects that the functions are also created multiple times, which impacts performance or something else entirely?

Example:
I find it much easier to add the math functions to the matrix class so I dont need to pass the matrix itself to the functions: e.g.

```<code>class Matrix4f {

    //constructor...

    public void rotate(double theta) {
        setValue(0, 0, (float) Math.cos(theta));
        setValue(1, 0, (float) Math.sin(theta));
        setValue(0, 1, (float) Math.sin(theta));
        setValue(1, 1, (float) Math.cos(theta));
    }

    //getters and setters...
}
</code>```

instead of

```<code>public class LinearAlgebraMath {
    public static Matrix4f rotate(Matrix4f target, double theta) {
        target.setValue(0, 0, (float) Math.cos(theta));
        target.setValue(1, 0, (float) Math.sin(theta));
        target.setValue(0, 1, (float) Math.sin(theta));
        target.setValue(1, 1, (float) Math.cos(theta));
        return target;
    }
}

public class Matrix4f {

    //constructor...

    //getters and setters...
}
</code>```

So, in the end I like adding the math functions to the matrix class because it's easier for me (especially when dealing with dealing with math operations that use multiple data structures) but I don't want to have my preferences lower performance, so my question is: Does example below outperform the example above and if yes, why?

答:
Is it when you're creating multiple of the matrix objects that the
  functions are also created multiple times, which impacts performance
  or something else entirely?

The functions are part of the Class object loaded into the VM. Multiple Matrix objects will only reference one copy of that function/method. So memory etc. will not be impacted by using instance methods as you're suggesting.

I'd normally attach the functionality to the instance of the class, as you're suggesting. Perhaps the references you're using were translated from a non-OO language (C?) where structures were used for the matrices and standalone functions were mandatory?

Body:
I am trying to make some simple classes to do the math necessary for OpenGL transformations. However, now that I am about halfway and while looking through different examples I find that most libraries keep the math separate of the matrix class itself (most of the times in math class with static methods). What exactly is the reason for this?

Is it when you're creating multiple of the matrix objects that the functions are also created multiple times, which impacts performance or something else entirely?

Example:
I find it much easier to add the math functions to the matrix class so I dont need to pass the matrix itself to the functions: e.g.

class Matrix4f {

    //constructor...

    public void rotate(double theta) {
        setValue(0, 0, (float) Math.cos(theta));
        setValue(1, 0, (float) Math.sin(theta));
        setValue(0, 1, (float) Math.sin(theta));
        setValue(1, 1, (float) Math.cos(theta));
    }

    //getters and setters...
}

instead of

public class LinearAlgebraMath {
    public static Matrix4f rotate(Matrix4f target, double theta) {
        target.setValue(0, 0, (float) Math.cos(theta));
        target.setValue(1, 0, (float) Math.sin(theta));
        target.setValue(0, 1, (float) Math.sin(theta));
        target.setValue(1, 1, (float) Math.cos(theta));
        return target;
    }
}

public class Matrix4f {

    //constructor...

    //getters and setters...
}

So, in the end I like adding the math functions to the matrix class because it's easier for me (especially when dealing with dealing with math operations that use multiple data structures) but I don't want to have my preferences lower performance, so my question is: Does example below outperform the example above and if yes, why?


问:
"Unknown command syncdb" running "python manage.py syncdb"
I want to create the tables of one database called "database1.sqlite", so I run the command:

python manage.py syncdb

but when I execute the command I receive the following error:

Unknown command: 'syncdb'
  Type 'manage.py help' for usage.

But when I run

manage.py help

I don`t see any command suspicious to substitute

python manage.py syncdb

Version of Python I use: 3.4.2    Version of Django I use:1.9

I would be very grateful if somebody could help me to solve this issue.

Regards and thanks in advance

答:
$python manage.py syncdb is deprecated and not supported now.
So instead of this follow below instructions..

Whatever model you have created:
First run:

```<code>$python manage.py makemigrations
</code>```

After running this command you model will be reflected in a migration.

Then you have to run:

```<code>$python manage.py migrate
</code>```

Then run server:

```<code>$python manage.py runserver
</code>```

Now, your project will run perfectly.

Body:
$python manage.py syncdb is deprecated and not supported now.
So instead of this follow below instructions..

Whatever model you have created:
First run:

$python manage.py makemigrations

After running this command you model will be reflected in a migration.

Then you have to run:

$python manage.py migrate

Then run server:

$python manage.py runserver

Now, your project will run perfectly.


问:
Not able to login after changing template file in backend
I wanted to add Google Analytics tracking code so I followed a tutorial on how to include its code inside some template file in backend. I am not sure how the file was called, template-something I believe.
At the end in editor I have placed the following code and after backend refresh I got fatal error.

```<code> page.wrap (
    // tracking code
 )
</code>```

How can I fix this issue? I have tried searching database for "googletagmanager", I have found code in sys_template and cache_pages, I have cleaned up my part but everthing is the same. I can also see there are some results in cache_hash and sys_history, but there are blobs inside and I can't find a way to search inside them? Is it safe to empty cache_hash table?

EDIT: I have manually edited blobs and uploaded cleaned from my insert, I have deleted rows fromo cache_hash, no change

It seems that problems is in temp_CACHED_ps20c1_ext_localconf file

答:
temp_CACHED_ps20c1_ext_localconf.php means a pre 6.0 version. So you need to update!

That file is a cache for the configuration. You should delete all files like typo3conf/temp_*.

So you have not specified your exact code, I only can guess.

The usual inclusion of google tracking starts with an include of javascript from google in the header (page.headerData. ....).

But even then you need to be careful if you include javascript in a multiline value. You start the multiline value with a ( after the initial property. This multiline will end on a line which starts with a ) (after whitespace). If your javascript includes such a line your typoscript gets confused. Such an error could be found in the TSOB or Template analyzer.

Body:
I wanted to add Google Analytics tracking code so I followed a tutorial on how to include its code inside some template file in backend. I am not sure how the file was called, template-something I believe.
At the end in editor I have placed the following code and after backend refresh I got fatal error.

 page.wrap (
    // tracking code
 )

How can I fix this issue? I have tried searching database for "googletagmanager", I have found code in sys_template and cache_pages, I have cleaned up my part but everthing is the same. I can also see there are some results in cache_hash and sys_history, but there are blobs inside and I can't find a way to search inside them? Is it safe to empty cache_hash table?

EDIT: I have manually edited blobs and uploaded cleaned from my insert, I have deleted rows fromo cache_hash, no change

It seems that problems is in temp_CACHED_ps20c1_ext_localconf file


问:
Node js & mongoDB - TypeError: db.collection is not a function
I am trying to post data from POSTMAN to an external database that I created on mLab but I am getting the error db.collection is not a function.

There is a similar question thread but the answer is incomplete and doesn't save  any keys/values I put into postman to mLab. The code that I am trying to make work is from this tutorial: https://medium.freecodecamp.com/building-a-simple-node-js-api-in-under-30-minutes-a07ea9e390d2

My Code:

Server.js

```<code>const express  = require('express'); // Load routes application
const MongoClient = require('mongodb').MongoClient; //Load database connection application
const db = require('./config/db');
const app  = express(); // Assign express app a variable
const port = 8000; //Set local port value for server
const bodyParser = require('body-parser'); // **This has to come BEFORE routes
var assert = require('assert'); // ?
var databaseURL ='mongodb://external:api@ds123312.mlab.com:23312/soundfactory';

app.listen(port, () => {
  console.log('')
  console.log('We are live on ' + port);
  console.log('')
});

MongoClient.connect(databaseURL, function(err, db) {
  assert.equal(null, err);
  console.log("API has succesfully connected to Sound Facotry mlab external database.");
  console.log('')
  db.close();
});

app.use(bodyParser.urlencoded({ extended: true }))
require('./app/routes')(app, {}); //Must come AFTER express w/ body parser
</code>```

db.js

```<code>module.exports = {
  url : 'mongodb://external:api@ds123312.mlab.com:23312/soundfactory'
};
</code>```

index.js

```<code>const noteroutes = require('./note_routes');
module.exports = function(app,db)
{
    noteroutes(app,db);
};
</code>```

note_routes.js

```<code>module.exports = function(app, db) {
  app.post('/notes', (req, res) => {
    const note = { text: req.body.body, title: req.body.title };
    db.collection('notes').insert(note, (err, result) => {
      if (err) {
        res.send({ 'error': 'An error has occurred' });
      } else {
        res.send(result.ops[0]);
      }
    });
  });
};
</code>```

partially correct code

server.js (code that partially works & doesn't throw the db.collections error like my original server.js file )

```<code>const express = require('express');
const MongoClient = require('mongodb').MongoClient;
const bodyParser = require('body-parser');
const db = require('./config/db');
const app = express();
const port = 8000;
app.use(bodyParser.urlencoded({extened:true}));
MongoClient.connect(db.url,(err,database) =>{
 if (err) return console.log(err)
//require('./app/routes')(app,{});
//check below line changed
 require('./app/routes')(app, database);
app.listen(port,() => {
    console.log("We are live on"+port);
});
})
</code>```

答:
Remove the node_modules folder and change mongodb version of your package.json

```<code>"mongodb": "^2.2.33"
</code>```

and run below code :

```<code>npm install
</code>```

Body:
I am trying to post data from POSTMAN to an external database that I created on mLab but I am getting the error db.collection is not a function.

There is a similar question thread but the answer is incomplete and doesn't save  any keys/values I put into postman to mLab. The code that I am trying to make work is from this tutorial: https://medium.freecodecamp.com/building-a-simple-node-js-api-in-under-30-minutes-a07ea9e390d2

My Code:

Server.js

const express  = require('express'); // Load routes application
const MongoClient = require('mongodb').MongoClient; //Load database connection application
const db = require('./config/db');
const app  = express(); // Assign express app a variable
const port = 8000; //Set local port value for server
const bodyParser = require('body-parser'); // **This has to come BEFORE routes
var assert = require('assert'); // ?
var databaseURL ='mongodb://external:api@ds123312.mlab.com:23312/soundfactory';

app.listen(port, () => {
  console.log('')
  console.log('We are live on ' + port);
  console.log('')
});

MongoClient.connect(databaseURL, function(err, db) {
  assert.equal(null, err);
  console.log("API has succesfully connected to Sound Facotry mlab external database.");
  console.log('')
  db.close();
});

app.use(bodyParser.urlencoded({ extended: true }))
require('./app/routes')(app, {}); //Must come AFTER express w/ body parser

db.js

module.exports = {
  url : 'mongodb://external:api@ds123312.mlab.com:23312/soundfactory'
};

index.js

const noteroutes = require('./note_routes');
module.exports = function(app,db)
{
    noteroutes(app,db);
};

note_routes.js

module.exports = function(app, db) {
  app.post('/notes', (req, res) => {
    const note = { text: req.body.body, title: req.body.title };
    db.collection('notes').insert(note, (err, result) => {
      if (err) {
        res.send({ 'error': 'An error has occurred' });
      } else {
        res.send(result.ops[0]);
      }
    });
  });
};

partially correct code

server.js (code that partially works & doesn't throw the db.collections error like my original server.js file )

const express = require('express');
const MongoClient = require('mongodb').MongoClient;
const bodyParser = require('body-parser');
const db = require('./config/db');
const app = express();
const port = 8000;
app.use(bodyParser.urlencoded({extened:true}));
MongoClient.connect(db.url,(err,database) =>{
 if (err) return console.log(err)
//require('./app/routes')(app,{});
//check below line changed
 require('./app/routes')(app, database);
app.listen(port,() => {
    console.log("We are live on"+port);
});
})

Body:
Remove the node_modules folder and change mongodb version of your package.json

"mongodb": "^2.2.33"

and run below code :

npm install


问:
Decrementing for loops
I want to have a for loop like so:

```<code>for counter in range(10,0):
       print counter,
</code>```

and the output should be 10 9 8 7 6 5 4 3 2 1

答:
Check out the range documentation, you have to define a negative step:

```<code>>>> range(10, 0, -1)
[10, 9, 8, 7, 6, 5, 4, 3, 2, 1]
</code>```

Title: Decrementing for loops

Body:
I want to have a for loop like so:

for counter in range(10,0):
       print counter,

and the output should be 10 9 8 7 6 5 4 3 2 1

Body:
Check out the range documentation, you have to define a negative step:

>>> range(10, 0, -1)
[10, 9, 8, 7, 6, 5, 4, 3, 2, 1]


问:
Quasar Framework: Method inside watcher is not recognized
I'm trying to use watchers in a Quasar-Framework application and the method inside the watcher is not recognized as a method.

```<code> data () {
   return {
     education: { degree:'test' },
     type: 2
   }
 },
 watch: {
   type: (newType) => {
     if (newType === 1) {
       this.removeDegree()
     }
   }
 },
 methods: {
   removeDegree () {
     this.education.degree = ''
   }
 }
</code>```

I expect the removeDegree to be called, however, Warning & Errors are thrown which says the removeDegree is not a function.

Reference: VueJS: Watchers

SOLUTION:
Using the shorthand es6 syntax as suggested by @docnoe

```<code>watch: {
  type (newType) {
    if (newType === 1) {
      this.removeDegree()
    }
  }
},
...
</code>```

答:
@Belmin Bedak already answered it in his comment: The arrow function used with the watch on "type" breaks the reference to "this". Use a normal function instead.

Fixed code:

```<code>new Vue({
  el: "#app",
  data() {
    return {
      education: { degree: "test" },
      type: 2,
      type2: 2,
      type3: 3
    };
  },
  watch: {
    // shorthand es6 syntax
    type(newType) {
      if (newType === 1) {
        this.removeDegree();
      }
    },
    // this is also valid
    type2: function(newType) {
      if (newType === 1) {
        this.removeDegree();
      }
    },
    // or using a handler
    type3: {
      handler(newType) {
        if (newType === 1) {
          this.removeDegree();
        }
      },
      // other watch options
      immediate: true
    }
  },
  methods: {
    removeDegree() {
      this.education.degree = "";
    }
  }
});
</code>```

Codepen

Body:
I'm trying to use watchers in a Quasar-Framework application and the method inside the watcher is not recognized as a method.

 data () {
   return {
     education: { degree:'test' },
     type: 2
   }
 },
 watch: {
   type: (newType) => {
     if (newType === 1) {
       this.removeDegree()
     }
   }
 },
 methods: {
   removeDegree () {
     this.education.degree = ''
   }
 }

I expect the removeDegree to be called, however, Warning & Errors are thrown which says the removeDegree is not a function.

Reference: VueJS: Watchers

SOLUTION:
Using the shorthand es6 syntax as suggested by @docnoe

watch: {
  type (newType) {
    if (newType === 1) {
      this.removeDegree()
    }
  }
},
...

Body:
@Belmin Bedak already answered it in his comment: The arrow function used with the watch on "type" breaks the reference to "this". Use a normal function instead.

Fixed code:

new Vue({
  el: "#app",
  data() {
    return {
      education: { degree: "test" },
      type: 2,
      type2: 2,
      type3: 3
    };
  },
  watch: {
    // shorthand es6 syntax
    type(newType) {
      if (newType === 1) {
        this.removeDegree();
      }
    },
    // this is also valid
    type2: function(newType) {
      if (newType === 1) {
        this.removeDegree();
      }
    },
    // or using a handler
    type3: {
      handler(newType) {
        if (newType === 1) {
          this.removeDegree();
        }
      },
      // other watch options
      immediate: true
    }
  },
  methods: {
    removeDegree() {
      this.education.degree = "";
    }
  }
});

Codepen


问:
Add submenu items from an MS Access DB file to a menustrip programmatically
I want to load programmatically some stored titles from an MS Access DB file and add them to a MenuStrip as subitems to existing submenus.

I am using this way to load my DB file, I just don't know how to add those titles into my Menustrip control as subitems...

```<code>Imports System.Data.OleDb

Public Class MainForm
    Public Provider As String = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source ="
    Public DataFile As String = "database.accdb"
    Public ConnString As String = Provider & DataFile
    Public MyConnection As OleDbConnection = New OleDbConnection
    Public DataReader As OleDbDataReader

    Public Sub ApplicationsMenu_Load()
        MyConnection.ConnectionString = ConnString
        MyConnection.Open()

        Dim str As String = "SELECT * FROM ApplicationsPaths"

        Dim cmd As OleDbCommand = New OleDbCommand(str, MyConnection)
        DataReader = cmd.ExecuteReader

        Try
            While DataReader.Read()
                'Add submenu items code here!!!
            End While
            MyConnection.Close()
        Catch ex As Exception
            MsgBox(ex.Message)
        End Try
    End Sub
End Class
</code>```

Into an other project I used this way below to add some labels into a FlowLayoutPanel control. I want to do something similar... I just missing the syntax!!!

```<code>While DataReader.Read()
            Dim lbl As New Label()
            Dim count As Integer = StandardPaths_HiddenFlowLayoutPanel.Controls.OfType(Of Label)().ToList().Count
            lbl.Name = "Path_" & DataReader("TagNum").ToString
            lbl.Tag = DataReader("TagNum").ToString
            lbl.Text = DataReader("Path").ToString
            lbl.AutoEllipsis = True
            lbl.AutoSize = True
            lbl.TextAlign = ContentAlignment.MiddleRight
            StandardPaths_HiddenFlowLayoutPanel.Controls.Add(lbl)
        End While
</code>```

EDIT:

I found this way below to add titles from DB file to MenuStrip but it loads them as top menus.

```<code>While DataReader.Read()
            Dim SubItems As New ToolStripMenuItem
            SubItems.Text = DataReader("AppName").ToString
            MainForm_MenuStrip.Items.Add(SubItems)
        End While
</code>```

How can I add them as items to an existing submenu? I am trying MainForm_MenuStrip.DropDownItems.Add(SubItems) and I get 'DropDownItems' is not a member of 'MenuStrip'.

答:
Okay, I found it!!! First I had to put the name of the submenu where I want to add those items and not the name of MenuStrip control. And then, I had to put DropDownItems.Add and not Items.Add probably because I want to add titles into a drop down item.

```<code>While DataReader.Read()
        Dim SubItems As New ToolStripMenuItem
        SubItems.Text = DataReader("AppName").ToString
        ApplicationsActions_MenuItem.DropDownItems.Add(SubItems)
    End While
</code>```

Body:
I want to load programmatically some stored titles from an MS Access DB file and add them to a MenuStrip as subitems to existing submenus.

I am using this way to load my DB file, I just don't know how to add those titles into my Menustrip control as subitems...

Imports System.Data.OleDb

Public Class MainForm
    Public Provider As String = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source ="
    Public DataFile As String = "database.accdb"
    Public ConnString As String = Provider & DataFile
    Public MyConnection As OleDbConnection = New OleDbConnection
    Public DataReader As OleDbDataReader

    Public Sub ApplicationsMenu_Load()
        MyConnection.ConnectionString = ConnString
        MyConnection.Open()

        Dim str As String = "SELECT * FROM ApplicationsPaths"

        Dim cmd As OleDbCommand = New OleDbCommand(str, MyConnection)
        DataReader = cmd.ExecuteReader

        Try
            While DataReader.Read()
                'Add submenu items code here!!!
            End While
            MyConnection.Close()
        Catch ex As Exception
            MsgBox(ex.Message)
        End Try
    End Sub
End Class

Into an other project I used this way below to add some labels into a FlowLayoutPanel control. I want to do something similar... I just missing the syntax!!!

While DataReader.Read()
            Dim lbl As New Label()
            Dim count As Integer = StandardPaths_HiddenFlowLayoutPanel.Controls.OfType(Of Label)().ToList().Count
            lbl.Name = "Path_" & DataReader("TagNum").ToString
            lbl.Tag = DataReader("TagNum").ToString
            lbl.Text = DataReader("Path").ToString
            lbl.AutoEllipsis = True
            lbl.AutoSize = True
            lbl.TextAlign = ContentAlignment.MiddleRight
            StandardPaths_HiddenFlowLayoutPanel.Controls.Add(lbl)
        End While

EDIT:

I found this way below to add titles from DB file to MenuStrip but it loads them as top menus.

While DataReader.Read()
            Dim SubItems As New ToolStripMenuItem
            SubItems.Text = DataReader("AppName").ToString
            MainForm_MenuStrip.Items.Add(SubItems)
        End While

How can I add them as items to an existing submenu? I am trying MainForm_MenuStrip.DropDownItems.Add(SubItems) and I get 'DropDownItems' is not a member of 'MenuStrip'.

Body:
Okay, I found it!!! First I had to put the name of the submenu where I want to add those items and not the name of MenuStrip control. And then, I had to put DropDownItems.Add and not Items.Add probably because I want to add titles into a drop down item.

While DataReader.Read()
        Dim SubItems As New ToolStripMenuItem
        SubItems.Text = DataReader("AppName").ToString
        ApplicationsActions_MenuItem.DropDownItems.Add(SubItems)
    End While


问:
Is it necessary to declare PHP array before adding values with []?
```<code>$arr = array(); // is this line needed?
$arr[] = 5;
</code>```

I know it works without the first line, but it's often included in practice.

What is the reason? Is it unsafe without it?

I know you can also do this:

```<code> $arr = array(5);
</code>```

but I'm talking about cases where you need to add items one by one.

答:
I strongly recommend to declare the array before adding values. Besides everything mentioned above, if the array is inside a loop you might unintentionally push elements into your array. I just observed this creating a costly bug.</p>

```<code>//Example code
foreach ($mailboxes as $mailbox){
       //loop creating email list to get
       foreach ($emails as $email){
          $arr[] = $email;
       }
       //loop to get emails
       foreach ($arr as $email){
       //oops now we're getting other peoples emails
       //in other mailboxes because we didn't initialize the array
       }
}
</code>```

Body:
$arr = array(); // is this line needed?
$arr[] = 5;

I know it works without the first line, but it's often included in practice.

What is the reason? Is it unsafe without it?

I know you can also do this:

 $arr = array(5);

but I'm talking about cases where you need to add items one by one.

Body:
I strongly recommend to declare the array before adding values. Besides everything mentioned above, if the array is inside a loop you might unintentionally push elements into your array. I just observed this creating a costly bug.

//Example code
foreach ($mailboxes as $mailbox){
       //loop creating email list to get
       foreach ($emails as $email){
          $arr[] = $email;
       }
       //loop to get emails
       foreach ($arr as $email){
       //oops now we're getting other peoples emails
       //in other mailboxes because we didn't initialize the array
       }
}


问:
SeekBarPreference with discrete values ()
I just wanted to include a SeekBarPreference in my project with only 3 values (level of emergency : low-Medium-high)

This can easily be done on a classic SeekBar (see example below) but I don't get how I could inlude that is a Preference.

If I use this code, it will work in a SeekBar (not Preference) but in Preferences it will still display a SeekBar without the thick marks.

CODE:

```<code><SeekBar
     android:id="@+id/sb"
     android:layout_width="match_parent"
     android:layout_height="wrap_content"
     android:max="10"
     android:thumb="@drawable/ic_location"
     android:theme="@style/Widget.AppCompat.SeekBar.Discrete" />
</code>```

Any idea, or suggestion?

答:
You need to use the support SeekbarPreference to customize the thumb and all. You can pass in your own custom layout for your seek bar preference. please check the example from below.

Your activity where you will add your preference fragment

```<code>public class MainActivity extends AppCompatActivity {

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

        BlankFragment mPrefsFragment = new BlankFragment();

        FragmentManager mFragmentManager = getSupportFragmentManager();
        FragmentTransaction mFragmentTransaction = mFragmentManager
                .beginTransaction();
        mFragmentTransaction.replace(android.R.id.content, mPrefsFragment);
        mFragmentTransaction.commit();

    }
}
</code>```

You have to add a specific theme in your manifest for this activity

```<code><activity
    android:name=".MainActivity"
    android:theme="@style/AppTheme.SettingsTheme" />
</code>```

styles.xml

```<code><style name="AppTheme.SettingsTheme" parent="AppTheme.NoActionBar">
    <item name="preferenceTheme">@style/PreferenceThemeOverlay</item>
</style>
</code>```

Your fragment where you load your preferences from xml

BlankFragment.java

```<code>public class BlankFragment extends PreferenceFragmentCompat {

    @Override
    public void onCreatePreferences(Bundle savedInstanceState, String rootKey) {
        setPreferencesFromResource(R.xml.preferences, rootKey);
    }
}
</code>```

And your preference file from xml res folder

```<code><?xml version="1.0" encoding="utf-8"?>
<android.support.v7.preference.PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android">

    <android.support.v7.preference.SeekBarPreference
        android:key="your_pref_key"
        android:max="3"
        android:thumb="@drawable/thumb_icon"
        android:summary="Summary"
        android:layout="@layout/my_custom_seekbar"
        android:title="Title" />
</android.support.v7.preference.PreferenceScreen>
</code>```

Here you can see that the android:layout attribute takes a resource layout file where you can supply your own custom seekbar and a textview-which shows the selected value from seekbar

my_custom_seekbar.xml

```<code><?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <SeekBar xmlns:android="http://schemas.android.com/apk/res/android"
        android:id="@+id/seekbar"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_toLeftOf="@+id/seekbar_value"
        android:max="10"
        android:theme="@style/Widget.AppCompat.SeekBar.Discrete"
        android:thumb="@drawable/ic_location" />

    <TextView
        android:id="@+id/seekbar_value"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentRight="true" />
</RelativeLayout>
</code>```

Note that you have to use the exact same identifier for your custom
SeekBar and TextView, otherwise it will throw a NullPointerException

```<code>    android:id="@+id/seekbar" for your custom Seekbar
    android:id="@+id/seekbar_value" for your custom TextView
</code>```

Body:
I just wanted to include a SeekBarPreference in my project with only 3 values (level of emergency : low-Medium-high)

This can easily be done on a classic SeekBar (see example below) but I don't get how I could inlude that is a Preference.

If I use this code, it will work in a SeekBar (not Preference) but in Preferences it will still display a SeekBar without the thick marks.

CODE:

<SeekBar
     android:id="@+id/sb"
     android:layout_width="match_parent"
     android:layout_height="wrap_content"
     android:max="10"
     android:thumb="@drawable/ic_location"
     android:theme="@style/Widget.AppCompat.SeekBar.Discrete" />

Any idea, or suggestion?

Body:
You need to use the support SeekbarPreference to customize the thumb and all. You can pass in your own custom layout for your seek bar preference. please check the example from below.

Your activity where you will add your preference fragment

public class MainActivity extends AppCompatActivity {

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

        BlankFragment mPrefsFragment = new BlankFragment();

        FragmentManager mFragmentManager = getSupportFragmentManager();
        FragmentTransaction mFragmentTransaction = mFragmentManager
                .beginTransaction();
        mFragmentTransaction.replace(android.R.id.content, mPrefsFragment);
        mFragmentTransaction.commit();

    }
}

You have to add a specific theme in your manifest for this activity

<activity
    android:name=".MainActivity"
    android:theme="@style/AppTheme.SettingsTheme" />

styles.xml

<style name="AppTheme.SettingsTheme" parent="AppTheme.NoActionBar">
    <item name="preferenceTheme">@style/PreferenceThemeOverlay</item>
</style>

Your fragment where you load your preferences from xml

BlankFragment.java

public class BlankFragment extends PreferenceFragmentCompat {

    @Override
    public void onCreatePreferences(Bundle savedInstanceState, String rootKey) {
        setPreferencesFromResource(R.xml.preferences, rootKey);
    }
}

And your preference file from xml res folder

<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.preference.PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android">

    <android.support.v7.preference.SeekBarPreference
        android:key="your_pref_key"
        android:max="3"
        android:thumb="@drawable/thumb_icon"
        android:summary="Summary"
        android:layout="@layout/my_custom_seekbar"
        android:title="Title" />
</android.support.v7.preference.PreferenceScreen>

Here you can see that the android:layout attribute takes a resource layout file where you can supply your own custom seekbar and a textview-which shows the selected value from seekbar

my_custom_seekbar.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <SeekBar xmlns:android="http://schemas.android.com/apk/res/android"
        android:id="@+id/seekbar"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_toLeftOf="@+id/seekbar_value"
        android:max="10"
        android:theme="@style/Widget.AppCompat.SeekBar.Discrete"
        android:thumb="@drawable/ic_location" />

    <TextView
        android:id="@+id/seekbar_value"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentRight="true" />
</RelativeLayout>

Note that you have to use the exact same identifier for your custom
SeekBar and TextView, otherwise it will throw a NullPointerException

    android:id="@+id/seekbar" for your custom Seekbar
    android:id="@+id/seekbar_value" for your custom TextView


问:
VBA - ADODB connect to remote Oracle db
I am developing an Excel VBA program that I want to connect to a remote Oracle 11g database, run a query, and return the data to Excel.

Connection strings and drivers are all OK as far as I know. (see below)

It was working perfectly for a while yesterday, connecting to db and returning with correct data. Then I saved and closed the workbook, opened it 20 minutes later (no changes made!) and when I ran the macro I got the following error:

Runtime error '-2147418113 (8000ffff)': Catastrophic failure

any ideas what could be causing the error?
Could it be something on the DB's side?

Thanks

```<code>Sub ExtractFromOracle(environment As String)

Dim cn As ADODB.connection
Dim recordSet As ADODB.recordSet
Set cn = CreateObject("ADODB.Connection")
Set recordSet = CreateObject("ADODB.recordset")

Dim SQLQuery As String
SQLQuery = "SELECT User_Id, Prof_Id FROM user_profile ORDER BY User_Id ASC"

Dim returnData As Variant
Dim returnedRowsCount As Integer

Dim connectionString As String
connectionString = ReturnConnectionString(environment)

cn.Open (connectionString) ------------> ERROR OCCURS HERE

Set recordSet = cn.Execute(SQLQuery)
returnData = Application.Transpose(recordSet.GetRows)
returnedRowsCount = UBound(returnData)

If Not SheetExist(environment) Then
CreateTab (environment)
End If

Worksheets(environment).Activate
ActiveSheet.Range("A1:B" & returnedRowsCount) = returnData

Set rs = Nothing
Set cn = Nothing

ConsolidateUsers (environment)

End Sub
</code>```

CONNECTION STRING :

```<code>"Provider=OraOLEDB.Oracle;Data Source=(DESCRIPTION=(CID=GTU_APP)(ADDRESS_LIST=(ADDRESS=(PROTOCOL=TCP)(HOST=xxxxxxx)(PORT=xxxx)))(CONNECT_DATA=(SID=xxxxx)(SERVER=DEDICATED)));User Id=xxxxxx;Password=xxxxxxx;"
</code>```

答:
Can you try to access the ADODB as below</p>

```<code>Dim strSQL  As String, conStr as String
Dim cnn As New ADODB.Connection
Dim rs As New ADODB.Recordset

conStr = "Provider=OraOLEDB.Oracle;Data Source=(DESCRIPTION=(CID=GTU_APP)(ADDRESS_LIST=(ADDRESS=(PROTOCOL=TCP)(HOST=xxxxxxx)(PORT=xxxx)))(CONNECT_DATA=(SID=xxxxx)(SERVER=DEDICATED)));User Id=xxxxxx;Password=xxxxxxx;"

Dim SQLQuery As String
SQLQuery = "SELECT User_Id, Prof_Id FROM user_profile ORDER BY User_Id ASC"

cnn.open conStr
rs.Open SQLQuery, cnn, adOpenStatic, adLockOptimistic, adCmdText
</code>```

Title: VBA - ADODB connect to remote Oracle db

Body:
I am developing an Excel VBA program that I want to connect to a remote Oracle 11g database, run a query, and return the data to Excel.

Connection strings and drivers are all OK as far as I know. (see below)

It was working perfectly for a while yesterday, connecting to db and returning with correct data. Then I saved and closed the workbook, opened it 20 minutes later (no changes made!) and when I ran the macro I got the following error:

Runtime error '-2147418113 (8000ffff)': Catastrophic failure

any ideas what could be causing the error?
Could it be something on the DB's side?

Thanks

Sub ExtractFromOracle(environment As String)

Dim cn As ADODB.connection
Dim recordSet As ADODB.recordSet
Set cn = CreateObject("ADODB.Connection")
Set recordSet = CreateObject("ADODB.recordset")

Dim SQLQuery As String
SQLQuery = "SELECT User_Id, Prof_Id FROM user_profile ORDER BY User_Id ASC"

Dim returnData As Variant
Dim returnedRowsCount As Integer

Dim connectionString As String
connectionString = ReturnConnectionString(environment)

cn.Open (connectionString) ------------> ERROR OCCURS HERE

Set recordSet = cn.Execute(SQLQuery)
returnData = Application.Transpose(recordSet.GetRows)
returnedRowsCount = UBound(returnData)

If Not SheetExist(environment) Then
CreateTab (environment)
End If

Worksheets(environment).Activate
ActiveSheet.Range("A1:B" & returnedRowsCount) = returnData

Set rs = Nothing
Set cn = Nothing

ConsolidateUsers (environment)

End Sub

CONNECTION STRING :

"Provider=OraOLEDB.Oracle;Data Source=(DESCRIPTION=(CID=GTU_APP)(ADDRESS_LIST=(ADDRESS=(PROTOCOL=TCP)(HOST=xxxxxxx)(PORT=xxxx)))(CONNECT_DATA=(SID=xxxxx)(SERVER=DEDICATED)));User Id=xxxxxx;Password=xxxxxxx;"

Body:
Can you try to access the ADODB as below

Dim strSQL  As String, conStr as String
Dim cnn As New ADODB.Connection
Dim rs As New ADODB.Recordset

conStr = "Provider=OraOLEDB.Oracle;Data Source=(DESCRIPTION=(CID=GTU_APP)(ADDRESS_LIST=(ADDRESS=(PROTOCOL=TCP)(HOST=xxxxxxx)(PORT=xxxx)))(CONNECT_DATA=(SID=xxxxx)(SERVER=DEDICATED)));User Id=xxxxxx;Password=xxxxxxx;"

Dim SQLQuery As String
SQLQuery = "SELECT User_Id, Prof_Id FROM user_profile ORDER BY User_Id ASC"

cnn.open conStr
rs.Open SQLQuery, cnn, adOpenStatic, adLockOptimistic, adCmdText


问:
Any plans for "do"/Action LINQ operator?
Here's a simple method with a foreach loop:

```<code>IEnumerable<XElement> FieldsToXElements(object instance)
{
    var fieldElements = new List<XElement>();

    foreach (var field in instance.GetType().GetFields(instance))
    {
        fieldElements.Add(new XElement(field.Name, field.GetValue(instance)));
    }

    return fieldElements;
}
</code>```

Kind of ugly. If there were some operator in LINQ that mean "do something" (e.g. perform an Action for each selected in the LINQ statement), it would look nicer, more terse:

```<code>IEnumerable<XElement> FieldsToXElements(object instance)
{
    var fieldElements = new List<XElement>();

    from field in instance.GetType().GetFields(instance))
    let name = field.Name
    let value = field.GetValue(instance)
    do fieldElements.Add(new XElement(name, value));

    return fieldElements;
}
</code>```

I realize that's subjective, and just my opinion. For a foreach loop that has one line that simply invokes a method, a "do" operator makes sense, in my opinion. But I'm wondering if anyone at MS has thought the same thing. Is such LINQ operator planned in any upcoming releases (e.g. alongside the C# 4.0 debut)?

Here's another example, with a predicate, where the fictitious do operator would really make the code look cleaner. This:

```<code>IEnumerable<XElement> FieldsToXElements
    (object instance, Func<FieldInfo, bool> predicate)
{
    var fieldElements = new List<XElement>();

    foreach (var field in instance.GetType().GetFields(instance).Where(predicate))
    {
        fieldElements.Add(new XElement(field.Name, field.GetValue(instance)));
    }

    return fieldElements;
}
</code>```

vs. this:

```<code>IEnumerable<XElement> FieldsToXElements
    (object instance, Func<FieldInfo, bool> predicate)
{
    var fieldElements = new List<XElement>();

    from field in instance.GetType().GetFields(instance))
    let name = field.Name
    let value = field.GetValue(instance)
    where predicate(field)
    do fieldElements.Add(new XElement(name, value));

    return fieldElements;
}
</code>```

答:
No, I don't expect any direct language suport (i.e. inside the query syntax) any time soon.

It sounds like you mean the mythical ForEach extension method; trivial to add, but Eric Lippert has commented numerous times about the cross between side-effect-free functional code and Action<T> with side-effects. In particular, C# 3.0 / .NET 3.5 expression trees are lousy at side-effecs (making full lambda support tricky). The runtime side is much better in .NET 4.0, but it is unclear at the moment how much of this will make it into the language (lambda compiler) in C# 4.0.

All you need (for delegate version) is:

```<code>public static void ForEach<T>(this IEnumerable<T> source, Action<T> action)
{   // note: omitted arg/null checks
    foreach(T item in source) { action(item); }
}
</code>```

Then from any query you can simply use .ForEach(x => /* do something */).

OwnerDisplayName: Chris

Body:
Here's a simple method with a foreach loop:

IEnumerable<XElement> FieldsToXElements(object instance)
{
    var fieldElements = new List<XElement>();

    foreach (var field in instance.GetType().GetFields(instance))
    {
        fieldElements.Add(new XElement(field.Name, field.GetValue(instance)));
    }

    return fieldElements;
}

Kind of ugly. If there were some operator in LINQ that mean "do something" (e.g. perform an Action for each selected in the LINQ statement), it would look nicer, more terse:

IEnumerable<XElement> FieldsToXElements(object instance)
{
    var fieldElements = new List<XElement>();

    from field in instance.GetType().GetFields(instance))
    let name = field.Name
    let value = field.GetValue(instance)
    do fieldElements.Add(new XElement(name, value));

    return fieldElements;
}

I realize that's subjective, and just my opinion. For a foreach loop that has one line that simply invokes a method, a "do" operator makes sense, in my opinion. But I'm wondering if anyone at MS has thought the same thing. Is such LINQ operator planned in any upcoming releases (e.g. alongside the C# 4.0 debut)?

Here's another example, with a predicate, where the fictitious do operator would really make the code look cleaner. This:

IEnumerable<XElement> FieldsToXElements
    (object instance, Func<FieldInfo, bool> predicate)
{
    var fieldElements = new List<XElement>();

    foreach (var field in instance.GetType().GetFields(instance).Where(predicate))
    {
        fieldElements.Add(new XElement(field.Name, field.GetValue(instance)));
    }

    return fieldElements;
}

vs. this:

IEnumerable<XElement> FieldsToXElements
    (object instance, Func<FieldInfo, bool> predicate)
{
    var fieldElements = new List<XElement>();

    from field in instance.GetType().GetFields(instance))
    let name = field.Name
    let value = field.GetValue(instance)
    where predicate(field)
    do fieldElements.Add(new XElement(name, value));

    return fieldElements;
}

Body:
No, I don't expect any direct language suport (i.e. inside the query syntax) any time soon.

It sounds like you mean the mythical ForEach extension method; trivial to add, but Eric Lippert has commented numerous times about the cross between side-effect-free functional code and Action<T> with side-effects. In particular, C# 3.0 / .NET 3.5 expression trees are lousy at side-effecs (making full lambda support tricky). The runtime side is much better in .NET 4.0, but it is unclear at the moment how much of this will make it into the language (lambda compiler) in C# 4.0.

All you need (for delegate version) is:

public static void ForEach<T>(this IEnumerable<T> source, Action<T> action)
{   // note: omitted arg/null checks
    foreach(T item in source) { action(item); }
}

Then from any query you can simply use .ForEach(x => /* do something */).

OwnerDisplayName: Marc Gravell

LastEditorDisplayName: Marc Gravell


问:
How to create DataFrame from a Counter of tuples
I am kind of green at pandas and other scipy libraries, so I am not sure how to do this. I have a list of two-element tuples and I am counting the number of times the same tuple is found, or the reversed counterpart, hence the sorting:

```<code>In [24]: tuples
Out[24]:
[(1, 2),
 (1, 3),
 (1, 4),
 (2, 3),
 (2, 4),
 (3, 4),
 (2, 1),
 (3, 1),
 (4, 1),
 (3, 2),
 (4, 2),
 (4, 3)]

In [30]: count = Counter([tuple(sorted(t)) for t in tuples])

In [31]: count
Out[31]: Counter({(1, 2): 2, (1, 3): 2, (1, 4): 2, (2, 3): 2, (2, 4): 2, (3, 4): 2})
</code>```

I am trying to create a DataFrame that essentially produces this output:

```<code>   1  2  3  4
1  0  2  2  2
2  2  0  2  2
3  2  2  0  2
4  2  2  2  0
</code>```

答:
What about slightly different approach?

first let's create a DF from the sortedlist of tuples:

```<code>In [272]: df = pd.DataFrame(np.sort(np.array(tuples), axis=1), columns=['c1','c2'])

In [273]: df
Out[273]:
    c1  c2
0    1   2
1    1   3
2    1   4
3    2   3
4    2   4
5    3   4
6    1   2
7    1   3
8    1   4
9    2   3
10   2   4
11   3   4
</code>```

now we can count pairs using Pandas technique:

```<code>In [274]: res = df.groupby(['c1','c2']).size()

In [275]: res
Out[275]:
c1  c2
1   2     2
    3     2
    4     2
2   3     2
    4     2
3   4     2
dtype: int64
</code>```

Accessing data in multi-index DF:

```<code>In [277]: res.loc[(1,2)]
Out[277]: 2

In [278]: res.loc[(2,4)]
Out[278]: 2
</code>```

we can also unstack the resulting DF, which will give us:

```<code>In [279]: res.unstack(fill_value=0)
Out[279]:
c2  2  3  4
c1
1   2  2  2
2   0  2  2
3   0  0  2
</code>```

Or as proposed by @Dark:

```<code>In [280]: pd.Series(count).unstack(fill_value=0)
Out[280]:
   2  3  4
1  2  2  2
2  0  2  2
3  0  0  2
</code>```

Body:
I am kind of green at pandas and other scipy libraries, so I am not sure how to do this. I have a list of two-element tuples and I am counting the number of times the same tuple is found, or the reversed counterpart, hence the sorting:

In [24]: tuples
Out[24]:
[(1, 2),
 (1, 3),
 (1, 4),
 (2, 3),
 (2, 4),
 (3, 4),
 (2, 1),
 (3, 1),
 (4, 1),
 (3, 2),
 (4, 2),
 (4, 3)]

In [30]: count = Counter([tuple(sorted(t)) for t in tuples])

In [31]: count
Out[31]: Counter({(1, 2): 2, (1, 3): 2, (1, 4): 2, (2, 3): 2, (2, 4): 2, (3, 4): 2})

I am trying to create a DataFrame that essentially produces this output:

   1  2  3  4
1  0  2  2  2
2  2  0  2  2
3  2  2  0  2
4  2  2  2  0

Body:
What about slightly different approach?

first let's create a DF from the sortedlist of tuples:

In [272]: df = pd.DataFrame(np.sort(np.array(tuples), axis=1), columns=['c1','c2'])

In [273]: df
Out[273]:
    c1  c2
0    1   2
1    1   3
2    1   4
3    2   3
4    2   4
5    3   4
6    1   2
7    1   3
8    1   4
9    2   3
10   2   4
11   3   4

now we can count pairs using Pandas technique:

In [274]: res = df.groupby(['c1','c2']).size()

In [275]: res
Out[275]:
c1  c2
1   2     2
    3     2
    4     2
2   3     2
    4     2
3   4     2
dtype: int64

Accessing data in multi-index DF:

In [277]: res.loc[(1,2)]
Out[277]: 2

In [278]: res.loc[(2,4)]
Out[278]: 2

we can also unstack the resulting DF, which will give us:

In [279]: res.unstack(fill_value=0)
Out[279]:
c2  2  3  4
c1
1   2  2  2
2   0  2  2
3   0  0  2

Or as proposed by @Dark:

In [280]: pd.Series(count).unstack(fill_value=0)
Out[280]:
   2  3  4
1  2  2  2
2  0  2  2
3  0  0  2


问:
On select change, get data attribute value
The following code returns 'undefined'...</p>

```<code>$('select').change(function(){
    alert($(this).data('id'));
});

<select>
    <option data-id="1">one</option>
    <option data-id="2">two</option>
    <option data-id="3">three</option>
</select>
</code>```

答:
this works for me

```<code><select class="form-control" id="foo">
    <option value="first" data-id="1">first</option>
    <option value="second" data-id="2">second</option>
</select>
</code>```

and the script

```<code>$('#foo').on("change",function(){
    var dataid = $("#foo option:selected").attr('data-id');
    alert(dataid)
});
</code>```

Body:
The following code returns 'undefined'...

$('select').change(function(){
    alert($(this).data('id'));
});

<select>
    <option data-id="1">one</option>
    <option data-id="2">two</option>
    <option data-id="3">three</option>
</select>

Body:
this works for me

<select class="form-control" id="foo">
    <option value="first" data-id="1">first</option>
    <option value="second" data-id="2">second</option>
</select>

and the script

$('#foo').on("change",function(){
    var dataid = $("#foo option:selected").attr('data-id');
    alert(dataid)
});


问:
Refresh angularjs (content in AWS S3 ) application is landing on the main page
I configured an angularjs application in AWS S3. I need to remove hash(#) from URL So, followed the rules mentioned here
Angular on Aws S3 everything works fine but when a refresh on any page it is landing into the base/root/main page.

Could anyone help me to solve the issue.

FYI: Am using Apache to serve my S3 content.

答:
This happens because when the browser is reloaded when the angular app is in a route(Not with #) it request it from S3 where there isn't a file on that path. The Angular development handles this which is why its not appear locally. As a workaround you can do the following.

Setup AWS CloudFront Distribution in-front of S3.

Create an error handler if a different path is called and its not found in S3 to return the index.html.

For more details and automate the setup use the AWS Cloudformation in the article Deploying Angular/React Apps in AWS

Note: You can directly serve your S3 content using this approach using the Apache server only for the backend logic which can also be routed through CloudFront while in the same origin.