问:
Seeding admin database Role not adding
I am having some issues with getting my admin user have an admin role. Once I create a user and it succeeds I tried adding the admin role with AddToRoleAsync. But I am not sure why it's not being added. I then tried to have a check so that if the admin has no admin role it would add it. It looks like the command executes but I don't see it added to the database.

This is my code:

```<code>public async Task CreateAdmin()
{
       // Add roles
       string[] roles = new string[] {"Administrator", "User"};
       foreach(string role in roles)
       {
           bool result = await _roleManager.RoleExistsAsync(role);
           if(!result)
           {
               await _roleManager.CreateAsync(new IdentityRole(role));
           }
       }

       // Add admin user
       if (!_context.Users.Any(u => u.UserName == "Admin"))
       {
           var user = new Users
           {
               Email="admin@admin.com",
               NormalizedEmail="ADMIN@ADMIN.COM",
               UserName="admin@admin.com",
               NormalizedUserName="ADMIN",
               EmailConfirmed = true,
           };
           var result = await _userManager.CreateAsync(user, "Password123");
       }

       var adminuser = await _userManager.FindByEmailAsync("admin@admin.com");
       bool flag = await _userManager.IsInRoleAsync(adminuser, "Administrator");
       if(!flag)
       {
           var role = await _roleManager.FindByNameAsync("Administrator");
           await _userManager.AddToRoleAsync(adminuser, "Administrator");
            }
   }
</code>```

If you want the full DbIntilizer or more code let me know.

Anyone know what I am doing wrong?

Edit
Reworked it to follow this
http://www.locktar.nl/programming/net-core/seed-database-users-roles-dotnet-core-2-0-ef/
and now it works.

答:
This is how i do it.

```<code>public async Task InitializeDatabase(IApplicationBuilder app)
    {
        using (var serviceScope = app.ApplicationServices.GetService<IServiceScopeFactory>().CreateScope())
        {
            // Create DB
            serviceScope.ServiceProvider.GetRequiredService<ApplicationDbContext>().Database.Migrate();

            // Add roles
            var roleManager = serviceScope.ServiceProvider.GetRequiredService<RoleManager<IdentityRole<long>>>();
            if (!roleManager.Roles.Any())
            {
                foreach (var role in Config.GetTestRolls())
                {
                    await roleManager.CreateAsync(role);
                }
            }

            // Add users
            var userManager = serviceScope.ServiceProvider.GetRequiredService<UserManager<ApplicationUser>>();
            if (userManager.Users.Any()) return;
            foreach (var user in Config.GetTestUsers())
            {
                await userManager.CreateAsync(user, "Password123!");
            }

            // find first user add to first role (hack)
            var adminUser = await userManager.FindByEmailAsync(Config.GetTestUsers().FirstOrDefault()?.Email);
            if (adminUser != null)
            {
                await userManager.AddToRoleAsync(adminUser, Config.GetTestRolls().FirstOrDefault()?.Name);
            }

        }
</code>```

Code ripped from my GitHub Project found here

Title: Seeding admin database Role not adding

Body:
I am having some issues with getting my admin user have an admin role. Once I create a user and it succeeds I tried adding the admin role with AddToRoleAsync. But I am not sure why it's not being added. I then tried to have a check so that if the admin has no admin role it would add it. It looks like the command executes but I don't see it added to the database.

This is my code:

public async Task CreateAdmin()
{
       // Add roles
       string[] roles = new string[] {"Administrator", "User"};
       foreach(string role in roles)
       {
           bool result = await _roleManager.RoleExistsAsync(role);
           if(!result)
           {
               await _roleManager.CreateAsync(new IdentityRole(role));
           }
       }

       // Add admin user
       if (!_context.Users.Any(u => u.UserName == "Admin"))
       {
           var user = new Users
           {
               Email="admin@admin.com",
               NormalizedEmail="ADMIN@ADMIN.COM",
               UserName="admin@admin.com",
               NormalizedUserName="ADMIN",
               EmailConfirmed = true,
           };
           var result = await _userManager.CreateAsync(user, "Password123");
       }

       var adminuser = await _userManager.FindByEmailAsync("admin@admin.com");
       bool flag = await _userManager.IsInRoleAsync(adminuser, "Administrator");
       if(!flag)
       {
           var role = await _roleManager.FindByNameAsync("Administrator");
           await _userManager.AddToRoleAsync(adminuser, "Administrator");
            }
   }

If you want the full DbIntilizer or more code let me know.

Anyone know what I am doing wrong?

Edit
Reworked it to follow this
http://www.locktar.nl/programming/net-core/seed-database-users-roles-dotnet-core-2-0-ef/
and now it works.

Body:
This is how i do it.

public async Task InitializeDatabase(IApplicationBuilder app)
    {
        using (var serviceScope = app.ApplicationServices.GetService<IServiceScopeFactory>().CreateScope())
        {
            // Create DB
            serviceScope.ServiceProvider.GetRequiredService<ApplicationDbContext>().Database.Migrate();

            // Add roles
            var roleManager = serviceScope.ServiceProvider.GetRequiredService<RoleManager<IdentityRole<long>>>();
            if (!roleManager.Roles.Any())
            {
                foreach (var role in Config.GetTestRolls())
                {
                    await roleManager.CreateAsync(role);
                }
            }

            // Add users
            var userManager = serviceScope.ServiceProvider.GetRequiredService<UserManager<ApplicationUser>>();
            if (userManager.Users.Any()) return;
            foreach (var user in Config.GetTestUsers())
            {
                await userManager.CreateAsync(user, "Password123!");
            }

            // find first user add to first role (hack)
            var adminUser = await userManager.FindByEmailAsync(Config.GetTestUsers().FirstOrDefault()?.Email);
            if (adminUser != null)
            {
                await userManager.AddToRoleAsync(adminUser, Config.GetTestRolls().FirstOrDefault()?.Name);
            }

        }

Code ripped from my GitHub Project found here


来源: stackexchange

问:
How can do I solve this? I want to inject a nhibernate session but the session is not created yet
Edit

I would like to try to do what Remo Gloor has recommended

Create a SessionFactoryProvider derived for Provider that retruns a SessionFactory using the code in OnApplicationStarted

Create a binding for SessionFactory using the new provider and put it in SingletonScope

Create a SessionProvider derived from Provider that gets the SessionFactory injected in the constructor and retuns a new session using GetCurrentSession of the factory.

Create a binding for ISession to the above provider with activation and deactivation actions that open, transmit, rollback, and close the session (basiclly the code from Application_BeginRequest, EndRequest). Decalre the binding as in request scope.

Remove Application_BeginRequest, EndRequest.

Bind the repo using Bind().To();

I am looking for a tutorial that hits on these points with a file that I can download and play around with. If it uses lots of generics you needs to be pretty detailed as generics still get me.

Hi

I am trying to do session per request with my nhibernate.

I done this in my global.aspx

```<code>using System;
using System.Web.Mvc;
using System.Web.Routing;
using Demo.WebUI.Models.NinjectModules;
using FluentNHibernate.Cfg;
using FluentNHibernate.Cfg.Db;
using NHibernate;
using NHibernate.Context;
using Ninject;
using Ninject.Modules;
using Ninject.Web.Mvc;

namespace Demo.WebUI
{
    // Note: For instructions on enabling IIS6 or IIS7 classic mode,
    // visit http://go.microsoft.com/?LinkId=9394801

    public class MvcApplication : NinjectHttpApplication
    {
        public static void RegisterRoutes(RouteCollection routes)
        {
            routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

            routes.MapRoute(
                "Default", // Route name
                "{controller}/{action}/{id}", // URL with parameters
                new {controller = "Account", action = "Login", id = UrlParameter.Optional} // Parameter defaults
                );
        }

        public static ISessionFactory SessionFactory { get; private set; }

        protected override void OnApplicationStarted()
        {
            AreaRegistration.RegisterAllAreas();
            RegisterRoutes(RouteTable.Routes);

            SessionFactory = Fluently.Configure()
                .Database(MsSqlConfiguration.MsSql2008.ConnectionString(c => c.FromConnectionStringWithKey("test")))
                .Mappings(m => m.FluentMappings.AddFromAssemblyOf<Demo.Framework.Data.NhibernateMapping.UserMap>())
                .ExposeConfiguration(x => x.SetProperty("current_session_context_class", "web"))
                .ExposeConfiguration(BuidSchema)
                .BuildSessionFactory();
        }

        protected void Application_BeginRequest(object sender, EventArgs e)
        {
            ISession session = SessionFactory.OpenSession();
            session.BeginTransaction();
            CurrentSessionContext.Bind(session);
        }

        protected void Application_EndRequest(object sender, EventArgs e)
        {
            ISession session = CurrentSessionContext.Unbind(SessionFactory);

            if (session != null)
            {
                try
                {
                    session.Transaction.Commit();
                }
                catch (Exception)
                {
                    session.Transaction.Rollback();
                }
                finally
                {
                    session.Close();
                    session.Dispose();
                }
            }
        }

        protected override IKernel CreateKernel()
        {
            var modules = new INinjectModule[]
                              {
                                  new ServiceModule(),
                                  new RepoModule()
                              };

            return new StandardKernel(modules);
        }

        private static void BuidSchema(NHibernate.Cfg.Configuration config)
        {
            new NHibernate.Tool.hbm2ddl.SchemaExport(config).Create(false, true);
        }
    }
}
</code>```

In my RepoModule I have

```<code>Bind<IUserRepo>().To<UserRepo>().WithConstructorArgument("session",MvcApplication.SessionFactory.GetCurrentSession());
</code>```

This will throw a error because ninject will create the kernal before OnApplicationStarted() gets started and before Application_Begin starts to bind it.

So what should I do?

Edit

This is what I found in some tutorial.

```<code>  public static ISessionFactory SessionFactory { get; private set; }

        public MvcApplication()
        {
            SessionFactory = CreateSessionFactory();
        }

        private static ISessionFactory CreateSessionFactory()
        {
            return Fluently.Configure()
            .Database(MsSqlConfiguration.MsSql2008.ConnectionString(c => c.FromConnectionStringWithKey("test")))
            .Mappings(m => m.FluentMappings.AddFromAssemblyOf<Demo.Framework.Data.NhibernateMapping.UserMap>())
            .ExposeConfiguration(x => x.SetProperty("current_session_context_class", "web"))
            .ExposeConfiguration(BuidSchema)
            .BuildSessionFactory();
        }
</code>```

My binding

```<code>  Bind<IUserRepo>().To<UserRepo>();
    Bind<ISession>().ToMethod(x => MvcApplication.SessionFactory.GetCurrentSession());
</code>```

So I first create the session factory on constructor load then I bind it to the Isession instead of passing it in as a parameter.

The only thing that I am not sure with the global aspx is if it will keep calling the constructor up everytime and recreating the SessionFactory what is bad. So I am not sure if I need to check if it exists first.

答:
I recently blogged about using nhibernate in an asp.net mvc application with a repository pattern. This project provides an example of using nhibernate & ninject. Here are a few links:

http://blog.bobcravens.com/2010/07/using-nhibernate-in-asp-net-mvc/

http://blog.bobcravens.com/2010/06/the-repository-pattern-with-linq-to-fluent-nhibernate-and-mysql/

http://blog.bobcravens.com/2010/09/the-repository-pattern-part-2/

http://blog.bobcravens.com/2010/11/using-ninject-to-manage-critical-resources/

I think that we have a similar architecture. Take a look at the posts and let me know if you have any questions.

BTW, you can download this project at http://gpsnerd.codeplex.com

Bob

ContentLicense: CC BY-SA 2.5

Body:
Edit

I would like to try to do what Remo Gloor has recommended

Create a SessionFactoryProvider derived for Provider that retruns a SessionFactory using the code in OnApplicationStarted

Create a binding for SessionFactory using the new provider and put it in SingletonScope

Create a SessionProvider derived from Provider that gets the SessionFactory injected in the constructor and retuns a new session using GetCurrentSession of the factory.

Create a binding for ISession to the above provider with activation and deactivation actions that open, transmit, rollback, and close the session (basiclly the code from Application_BeginRequest, EndRequest). Decalre the binding as in request scope.

Remove Application_BeginRequest, EndRequest.

Bind the repo using Bind().To();

I am looking for a tutorial that hits on these points with a file that I can download and play around with. If it uses lots of generics you needs to be pretty detailed as generics still get me.

Hi

I am trying to do session per request with my nhibernate.

I done this in my global.aspx

using System;
using System.Web.Mvc;
using System.Web.Routing;
using Demo.WebUI.Models.NinjectModules;
using FluentNHibernate.Cfg;
using FluentNHibernate.Cfg.Db;
using NHibernate;
using NHibernate.Context;
using Ninject;
using Ninject.Modules;
using Ninject.Web.Mvc;

namespace Demo.WebUI
{
    // Note: For instructions on enabling IIS6 or IIS7 classic mode,
    // visit http://go.microsoft.com/?LinkId=9394801

    public class MvcApplication : NinjectHttpApplication
    {
        public static void RegisterRoutes(RouteCollection routes)
        {
            routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

            routes.MapRoute(
                "Default", // Route name
                "{controller}/{action}/{id}", // URL with parameters
                new {controller = "Account", action = "Login", id = UrlParameter.Optional} // Parameter defaults
                );
        }

        public static ISessionFactory SessionFactory { get; private set; }

        protected override void OnApplicationStarted()
        {
            AreaRegistration.RegisterAllAreas();
            RegisterRoutes(RouteTable.Routes);

            SessionFactory = Fluently.Configure()
                .Database(MsSqlConfiguration.MsSql2008.ConnectionString(c => c.FromConnectionStringWithKey("test")))
                .Mappings(m => m.FluentMappings.AddFromAssemblyOf<Demo.Framework.Data.NhibernateMapping.UserMap>())
                .ExposeConfiguration(x => x.SetProperty("current_session_context_class", "web"))
                .ExposeConfiguration(BuidSchema)
                .BuildSessionFactory();
        }

        protected void Application_BeginRequest(object sender, EventArgs e)
        {
            ISession session = SessionFactory.OpenSession();
            session.BeginTransaction();
            CurrentSessionContext.Bind(session);
        }

        protected void Application_EndRequest(object sender, EventArgs e)
        {
            ISession session = CurrentSessionContext.Unbind(SessionFactory);

            if (session != null)
            {
                try
                {
                    session.Transaction.Commit();
                }
                catch (Exception)
                {
                    session.Transaction.Rollback();
                }
                finally
                {
                    session.Close();
                    session.Dispose();
                }
            }
        }

        protected override IKernel CreateKernel()
        {
            var modules = new INinjectModule[]
                              {
                                  new ServiceModule(),
                                  new RepoModule()
                              };

            return new StandardKernel(modules);
        }

        private static void BuidSchema(NHibernate.Cfg.Configuration config)
        {
            new NHibernate.Tool.hbm2ddl.SchemaExport(config).Create(false, true);
        }
    }
}

In my RepoModule I have

Bind<IUserRepo>().To<UserRepo>().WithConstructorArgument("session",MvcApplication.SessionFactory.GetCurrentSession());

This will throw a error because ninject will create the kernal before OnApplicationStarted() gets started and before Application_Begin starts to bind it.

So what should I do?

Edit

This is what I found in some tutorial.

  public static ISessionFactory SessionFactory { get; private set; }

        public MvcApplication()
        {
            SessionFactory = CreateSessionFactory();
        }

        private static ISessionFactory CreateSessionFactory()
        {
            return Fluently.Configure()
            .Database(MsSqlConfiguration.MsSql2008.ConnectionString(c => c.FromConnectionStringWithKey("test")))
            .Mappings(m => m.FluentMappings.AddFromAssemblyOf<Demo.Framework.Data.NhibernateMapping.UserMap>())
            .ExposeConfiguration(x => x.SetProperty("current_session_context_class", "web"))
            .ExposeConfiguration(BuidSchema)
            .BuildSessionFactory();
        }

My binding

  Bind<IUserRepo>().To<UserRepo>();
    Bind<ISession>().ToMethod(x => MvcApplication.SessionFactory.GetCurrentSession());

So I first create the session factory on constructor load then I bind it to the Isession instead of passing it in as a parameter.

The only thing that I am not sure with the global aspx is if it will keep calling the constructor up everytime and recreating the SessionFactory what is bad. So I am not sure if I need to check if it exists first.


问:
CKeditor 4 plugin button doesn't appear
I have a working extention plugin (myplugin) which extends the drupalimagecaption plugin, which extends drupalimage which extend the original image plugin. Now I want to add an additional toolbar button to myplugin plugin. Here is how I try to add:

```<code>(function (CKEDITOR) {

  'use strict';

  CKEDITOR.plugins.add('myplugin', {
    icons: 'drupalimage,DoubleImage',
    requires: 'drupalimagecaption',
    hidpi: true,

    beforeInit: function (editor) {
      // [...] Here are some overwrites

      var imageSaveCallback = function (data) {
        editor.fire('saveSnapshot');
        var content = data.image_render;
        editor.insertHtml(content);
        editor.fire('saveSnapshot');
      };

      // Implementation before initializing plugin.
      editor.addCommand('InsertDoubleImage', {
        canUndo: true,
        exec: function (editor, data) {
          Drupal.ckeditor.openDialog(editor,
            Drupal.url('mydrupalmodule/dialog/double_image/' + editor.config.drupal.format),
            {},
            imageSaveCallback,
            {}
          );
        }
      });

      // Register the toolbar button.
      if (editor.ui.addButton) {
        editor.ui.addButton('DoubleImage', {
          label: Drupal.t('Upload Double Image'),
          command: 'InsertDoubleImage'
        });
      }
    }
  });

})(CKEDITOR);
</code>```

My main problem is, some why this button doesn't appear on the drupal's admin UI, so I'm not able to add to the CKeditor's toolbar. I also has a PHP class which loads this file (where this script lives) and I define there too the new and the current button:

```<code>public function getButtons() {
  return [
    'DrupalImage' => array(
      'label' => t('Single Image Popup'),
      'image' => drupal_get_path('module', 'mydrupalmodule') . '/js/plugins/elevation/icons/drupalimage.png',
    ),
    'DoubleImage' => array(
      'label' => t('Double Image Popup'),
      'image' => drupal_get_path('module', 'mydrupalmodule') . '/js/plugins/elevation/icons/DoubleImage.png',
    ),
  ];
}
</code>```

Actually I don't know what am I missing and I can't find why doesn't want to work... (only the overwrite work, but the button doesn't appear...) It's not possible to add new button if you overwrite an existing plugin?

答: Ok, I fount the problem. If I want to create a plugin for CKeditor in Drupal 8 I need to extend the CKEditorPluginBase not the PluginBase class. They extend the PluginBase in the DrupalImageCaption class (which I used as the base), but this won't work in my case.

ContentLicense: CC BY-SA 3.0

Title: CKeditor 4 plugin button doesn't appear

Body:
I have a working extention plugin (myplugin) which extends the drupalimagecaption plugin, which extends drupalimage which extend the original image plugin. Now I want to add an additional toolbar button to myplugin plugin. Here is how I try to add:

(function (CKEDITOR) {

  'use strict';

  CKEDITOR.plugins.add('myplugin', {
    icons: 'drupalimage,DoubleImage',
    requires: 'drupalimagecaption',
    hidpi: true,

    beforeInit: function (editor) {
      // [...] Here are some overwrites

      var imageSaveCallback = function (data) {
        editor.fire('saveSnapshot');
        var content = data.image_render;
        editor.insertHtml(content);
        editor.fire('saveSnapshot');
      };

      // Implementation before initializing plugin.
      editor.addCommand('InsertDoubleImage', {
        canUndo: true,
        exec: function (editor, data) {
          Drupal.ckeditor.openDialog(editor,
            Drupal.url('mydrupalmodule/dialog/double_image/' + editor.config.drupal.format),
            {},
            imageSaveCallback,
            {}
          );
        }
      });

      // Register the toolbar button.
      if (editor.ui.addButton) {
        editor.ui.addButton('DoubleImage', {
          label: Drupal.t('Upload Double Image'),
          command: 'InsertDoubleImage'
        });
      }
    }
  });

})(CKEDITOR);

My main problem is, some why this button doesn't appear on the drupal's admin UI, so I'm not able to add to the CKeditor's toolbar. I also has a PHP class which loads this file (where this script lives) and I define there too the new and the current button:

public function getButtons() {
  return [
    'DrupalImage' => array(
      'label' => t('Single Image Popup'),
      'image' => drupal_get_path('module', 'mydrupalmodule') . '/js/plugins/elevation/icons/drupalimage.png',
    ),
    'DoubleImage' => array(
      'label' => t('Double Image Popup'),
      'image' => drupal_get_path('module', 'mydrupalmodule') . '/js/plugins/elevation/icons/DoubleImage.png',
    ),
  ];
}

Actually I don't know what am I missing and I can't find why doesn't want to work... (only the overwrite work, but the button doesn't appear...) It's not possible to add new button if you overwrite an existing plugin?


问:
JMeter: While sending post request data value with quote Jmeter is adding escape character during sending request to server
We want to post some data value with quotes, which is being captured using correlation

String:
Request_UserKey="==paddas"

correlation regex used to extract value
UserKey="(.*?)"

we capture value without quotes with this regexp, captured value is ==paddas

but we need to pass value with quotes so we concatenate quote with correlated value and stored in temp variable.
temp value is "==paddas"

Now when when we are sending temp value in post request then value is going like UserKey="\"==paddas"\" but we want to send data like this UserKey="==paddas"

JMeter adding extra \" before quote so please help how to send correct value

答:
Assuming your speaking of HTTP POST request, quotes are not allowed.
You have to urlencode the data.

For example, "blah" is gonna be encoded %22blah%22.

Look for "urlencode online" in your favorite search engine.


问:
How do we generate stack trace in TOMCAT?
How do we generate stack trace in TOMCAT?
My real problem is TOMCAT just stops after doing some function call defined in some library.
It would be easy to debug with a stacktrace.</p>

答:
There's multiple things you can do.  I'm assuming below you are talking about a Java stack trace.

In linux, you can generate a stack trace at any time by doing a kill -3 command

ps aux | grep tomcat
 --> gives you the process number

kill -3 1000
  --> where 1000 is the process number

In Windows, right click on the Tomcat service icon in the system task tray and choose "Thread dump".

If you want to generate a stack trace at a particular point in the code

```<code>Throwable t = new RuntimeException();
t.printStackTrace();
</code>```

All of the above will send a stack trace to standard out.

Finally, you can run a profiling program like VisualVM and see the stack trace for any given thread while the program is running.

Body:
There's multiple things you can do.  I'm assuming below you are talking about a Java stack trace.

In linux, you can generate a stack trace at any time by doing a kill -3 command

ps aux | grep tomcat
 --> gives you the process number

kill -3 1000
  --> where 1000 is the process number

In Windows, right click on the Tomcat service icon in the system task tray and choose "Thread dump".

If you want to generate a stack trace at a particular point in the code

Throwable t = new RuntimeException();
t.printStackTrace();

All of the above will send a stack trace to standard out.

Finally, you can run a profiling program like VisualVM and see the stack trace for any given thread while the program is running.


问:
'dependsOn' property error in data factory
I am getting following error in azure data factory pipeline activity

I am using following code:

```<code>...
"dependsOn": [
        {
            "activity": "MyFirstActivity",
            "dependencyConditions": [
                "Succeeded"
            ]
        }
      ]
...
</code>```

"Input is malformed. Reason: batchPipelineRequest.dependsOn : Could not find member 'dependsOn' on object of type 'Activity'. Path 'dependsOn'..
  OK"

Is there any other property we need to put in pipeline or in datasets?

答:
This feature is available only in v2 preview version of ADF. To link and activity to another activity, you will need to use the output of previous activity as the input to the new activity. You can find details here-
https://learn.microsoft.com/en-us/azure/data-factory/v1/data-factory-create-pipelines</p>

Body:
I am getting following error in azure data factory pipeline activity

I am using following code:

...
"dependsOn": [
        {
            "activity": "MyFirstActivity",
            "dependencyConditions": [
                "Succeeded"
            ]
        }
      ]
...

"Input is malformed. Reason: batchPipelineRequest.dependsOn : Could not find member 'dependsOn' on object of type 'Activity'. Path 'dependsOn'..
  OK"

Is there any other property we need to put in pipeline or in datasets?


问:
Picking up a Sequence out of a matrix
I would like to find a way to pick the correct "11" out of my matrix.
You start from upper-left end, by [1, 1], and move to the direction from left to right rowwise.

Each time you see the combination "01" or "00", you should keep on moving from left to right till you find some "11".

In the example 1 the correct solution would be the "11" on the position [1, 3].

```<code># Example 1:
(R)

#       [,1] [,2] [,3]
# [1,]   01   01   11
# [2,]   11   01   11
# [3,]   01   11   10
</code>```

Once you have a "10" you must change the line and start from the second line.
In the example 2 the code must end up with the result "11" on the [2, 1] position.

```<code># Example 2:
(R1)

#       [,1] [,2] [,3]
# [1,]   01   10   11
# [2,]   11   01   11
# [3,]   01   11   10
</code>```

The command below would work for the second example, but not for the first one.

```<code>which(R == "11",  arr.ind = T)
</code>```

I am looking for the position of the correct "11" in the matrix. Any idea would be highly appreciated!

p.s.
For replication of R and R1:

```<code>R <- structure(c("01", "11", "01", "01", "01", "11", "11", "11", "10"), .Dim = c(3L, 3L))
R1 <- structure(c("01", "11", "01", "10", "01", "11", "11", "11", "10"), .Dim = c(3L, 3L))
</code>```

答:
Below is a simple function that does what you want. Parameters are the matrix m, the string you are searching for strSearch (here "11") and the string that stops the search on a given row strStop (here "10").

The loops work through each row and column, breaking when the stop string is found, and returning at the first instance of the search string. The returned vector of length two contains the row and column indices.

If the search string is not found, NA is returned.

```<code>R <- structure(c("01", "11", "01", "01", "01", "11", "11", "11", "10"), .Dim = c(3L, 3L))
R1 <- structure(c("01", "11", "01", "10", "01", "11", "11", "11", "10"), .Dim = c(3L, 3L))

getPosition <- function(m, strSearch, strStop) {

  for (i in seq_len(nrow(m))) {
    for (j in seq_len(ncol(m))) {
      if (m[i, j] == strStop) break
      if (m[i, j] == strSearch) return(c(i, j))
    }
  }

  return(NA)
}
</code>```

Sample output:

```<code>> getPosition(R, "11", "10")
[1] 1 3
> getPosition(R1, "11", "10")
[1] 2 1
</code>```

Title: Picking up a Sequence out of a matrix

Body:
I would like to find a way to pick the correct "11" out of my matrix.
You start from upper-left end, by [1, 1], and move to the direction from left to right rowwise.

Each time you see the combination "01" or "00", you should keep on moving from left to right till you find some "11".

In the example 1 the correct solution would be the "11" on the position [1, 3].

# Example 1:
(R)

#       [,1] [,2] [,3]
# [1,]   01   01   11
# [2,]   11   01   11
# [3,]   01   11   10

Once you have a "10" you must change the line and start from the second line.
In the example 2 the code must end up with the result "11" on the [2, 1] position.

# Example 2:
(R1)

#       [,1] [,2] [,3]
# [1,]   01   10   11
# [2,]   11   01   11
# [3,]   01   11   10

The command below would work for the second example, but not for the first one.

which(R == "11",  arr.ind = T)

I am looking for the position of the correct "11" in the matrix. Any idea would be highly appreciated!

p.s.
For replication of R and R1:

R <- structure(c("01", "11", "01", "01", "01", "11", "11", "11", "10"), .Dim = c(3L, 3L))
R1 <- structure(c("01", "11", "01", "10", "01", "11", "11", "11", "10"), .Dim = c(3L, 3L))

Body:
Below is a simple function that does what you want. Parameters are the matrix m, the string you are searching for strSearch (here "11") and the string that stops the search on a given row strStop (here "10").

The loops work through each row and column, breaking when the stop string is found, and returning at the first instance of the search string. The returned vector of length two contains the row and column indices.

If the search string is not found, NA is returned.

R <- structure(c("01", "11", "01", "01", "01", "11", "11", "11", "10"), .Dim = c(3L, 3L))
R1 <- structure(c("01", "11", "01", "10", "01", "11", "11", "11", "10"), .Dim = c(3L, 3L))

getPosition <- function(m, strSearch, strStop) {

  for (i in seq_len(nrow(m))) {
    for (j in seq_len(ncol(m))) {
      if (m[i, j] == strStop) break
      if (m[i, j] == strSearch) return(c(i, j))
    }
  }

  return(NA)
}

Sample output:

> getPosition(R, "11", "10")
[1] 1 3
> getPosition(R1, "11", "10")
[1] 2 1


答:
This works:

```<code>find_index <- function(matr) {
  # find the col index of first "10" in each row
  ind10 <- apply(matr, 1, function(x) ifelse(sum(x == "10") == 0,
                 length(x) + 1, min(seq_len(length(x))[x == "10"])))
  # find the col index of first "11" in each row
  ind11 <- apply(matr, 1, function(x) ifelse(sum(x == "11") == 0,
                 length(x) + 1, min(seq_len(length(x))[x == "11"])))

  # check if 11 is before 10
  ind <- ifelse(ind10 < ind11, NA, ind11)

  # select the first row where "11" is before "10"
  rownumber <- which(!is.na(ind))[1]
  # and its colnumber
  colnumber <- ind[rownumber]
  return(c(rownumber, colnumber))
}
find_index(R)
find_index(R1)
</code>```

Then the output is like this.

```<code>> find_index(R)
[1] 1 3
> find_index(R1)
[1] 2 1
>
</code>```

Since you didn't specify that what happens if there is an entry other than "11", "01", "10", "00" I ignore the possibility.

EDIT
Since it was complicated to read, I created a bit more readable version with text concatenation.

```<code>library(stringi)
library(dplyr)

find_11_before_10 <- function(x){
  text <- x %>% paste(collapse = "|")
  if(stri_detect_fixed(text, "11") &
     stri_detect_regex(text, "10.+11", negate = T)){
    return(which(x == "11") %>% min)
  } else {
    return(NA)
  }
}

find_index2 <- function(matr){
  ind <- apply(matr, 1, find_11_before_10)
  rownumber <- which(!is.na(ind))[1]
  colnumber <- ind[rownumber]
  return(c(rownumber, colnumber))
}

find_index2(R)
find_index2(R1)
</code>```

Title: Picking up a Sequence out of a matrix

Body:
This works:

find_index <- function(matr) {
  # find the col index of first "10" in each row
  ind10 <- apply(matr, 1, function(x) ifelse(sum(x == "10") == 0,
                 length(x) + 1, min(seq_len(length(x))[x == "10"])))
  # find the col index of first "11" in each row
  ind11 <- apply(matr, 1, function(x) ifelse(sum(x == "11") == 0,
                 length(x) + 1, min(seq_len(length(x))[x == "11"])))

  # check if 11 is before 10
  ind <- ifelse(ind10 < ind11, NA, ind11)

  # select the first row where "11" is before "10"
  rownumber <- which(!is.na(ind))[1]
  # and its colnumber
  colnumber <- ind[rownumber]
  return(c(rownumber, colnumber))
}
find_index(R)
find_index(R1)

Then the output is like this.

> find_index(R)
[1] 1 3
> find_index(R1)
[1] 2 1
>

Since you didn't specify that what happens if there is an entry other than "11", "01", "10", "00" I ignore the possibility.

EDIT
Since it was complicated to read, I created a bit more readable version with text concatenation.

library(stringi)
library(dplyr)

find_11_before_10 <- function(x){
  text <- x %>% paste(collapse = "|")
  if(stri_detect_fixed(text, "11") &
     stri_detect_regex(text, "10.+11", negate = T)){
    return(which(x == "11") %>% min)
  } else {
    return(NA)
  }
}

find_index2 <- function(matr){
  ind <- apply(matr, 1, find_11_before_10)
  rownumber <- which(!is.na(ind))[1]
  colnumber <- ind[rownumber]
  return(c(rownumber, colnumber))
}

find_index2(R)
find_index2(R1)


问:
Junit spring boot unable to autowire jdbc template
I have a Spring Boot application and worked fine with the application and previously with my JUNIT tests.

I have recently started using a JDBCTemplate and DataSource all of the tests fail to even start.

The main problem from the stacktrace is that once it tries to Autowire either the datasource or jdbc template it seems it cannot find the datasource properties

```<code>org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'directoryLoader': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: org.springframework.jdbc.core.JdbcTemplate com.millerhare.winfsapi.fsloader.DirectoryLoader.jdbcTemplate; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration$JdbcTemplateConfiguration': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private javax.sql.DataSource org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration$JdbcTemplateConfiguration.dataSource; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'dataSource' defined in class path resource [org/springframework/boot/autoconfigure/jdbc/DataSourceAutoConfiguration$NonEmbeddedConfiguration.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [javax.sql.DataSource]: Factory method 'dataSource' threw exception; nested exception is org.springframework.boot.autoconfigure.jdbc.DataSourceProperties$DataSourceBeanCreationException: Cannot determine embedded database driver class for database type NONE. If you want an embedded database please put a supported one on the classpath. If you have database settings to be loaded from a particular profile you may need to active it (no profiles are currently active).

at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:334)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1214)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:543)
...
</code>```

This is the Autowire class

```<code>@Component
public class DirectoryLoader {

@Autowired
JdbcTemplate jdbcTemplate;

@Autowired
DataSource ds;
</code>```

However in the application.properties for both the application and test, all of the datasource properties are set

```<code>spring.datasource.url=jdbc\:oracle\:thin\:@xxxx
spring.datasource.username=xxxx
spring.datasource.driver-class-name=oracle.jdbc.OracleDriver
</code>```

I have tried changing other properties like the server.port and those are picked up so it is clearly finding the application.properties file fine.

My original configuration for the test was

```<code> @RunWith(SpringJUnit4ClassRunner.class)
 @SpringApplicationConfiguration(classes = WinFsapiApplication.class)
 @WebIntegrationTest
</code>```

I have also tried setting the properties via @TestPropertiesSource but this also does not find them.
What am I missing?

答:
I faced a similar issue where the spring boot application was running fine and I could test it from Postman but the JUnit tests were failing. Adding application.properties to src/test/resources resolved it for me.

I know spring boot should pick it up from src/main/resources but just wouldn't. Even if I asked it to look for it specifically using @PropertySource("classpath:application.properties") on my configuration file.

Body:
I have a Spring Boot application and worked fine with the application and previously with my JUNIT tests.

I have recently started using a JDBCTemplate and DataSource all of the tests fail to even start.

The main problem from the stacktrace is that once it tries to Autowire either the datasource or jdbc template it seems it cannot find the datasource properties

org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'directoryLoader': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: org.springframework.jdbc.core.JdbcTemplate com.millerhare.winfsapi.fsloader.DirectoryLoader.jdbcTemplate; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration$JdbcTemplateConfiguration': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private javax.sql.DataSource org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration$JdbcTemplateConfiguration.dataSource; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'dataSource' defined in class path resource [org/springframework/boot/autoconfigure/jdbc/DataSourceAutoConfiguration$NonEmbeddedConfiguration.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [javax.sql.DataSource]: Factory method 'dataSource' threw exception; nested exception is org.springframework.boot.autoconfigure.jdbc.DataSourceProperties$DataSourceBeanCreationException: Cannot determine embedded database driver class for database type NONE. If you want an embedded database please put a supported one on the classpath. If you have database settings to be loaded from a particular profile you may need to active it (no profiles are currently active).

at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:334)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1214)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:543)
...

This is the Autowire class

@Component
public class DirectoryLoader {

@Autowired
JdbcTemplate jdbcTemplate;

@Autowired
DataSource ds;

However in the application.properties for both the application and test, all of the datasource properties are set

spring.datasource.url=jdbc\:oracle\:thin\:@xxxx
spring.datasource.username=xxxx
spring.datasource.driver-class-name=oracle.jdbc.OracleDriver

I have tried changing other properties like the server.port and those are picked up so it is clearly finding the application.properties file fine.

My original configuration for the test was

 @RunWith(SpringJUnit4ClassRunner.class)
 @SpringApplicationConfiguration(classes = WinFsapiApplication.class)
 @WebIntegrationTest

I have also tried setting the properties via @TestPropertiesSource but this also does not find them.
What am I missing?

ContentLicense: CC BY-SA 4.0


问:
monitoring cassandra with prometheus monitoring tool
My prometheus tool is on centos 7 machine and cassandra is on centos 6. I am trying to monitor cassandra JMX port 7199 with prometheus. I keep getting error with my yml file. Not sure why I am not able to connect to the centos 6 (cassandra machine) Is my YAML file wrong or does it have something to do with JMX port 7199?
here is my YAML file:

my global config

```<code>global:
  scrape_interval: 15s

scrape_configs:
   - job_name: cassandra
     static_configs:
       - targets: ['10.1.0.22:7199']
</code>```

Here is my prometheus log:

```<code>level=info ts=2017-12-08T04:30:53.92549611Z caller=main.go:215 msg="Starting Prometheus" version="(version=2.0.0, branch=HEAD, revision=0a74f98628a0463dddc90528220c94de5032d1a0)"
level=info ts=2017-12-08T04:30:53.925623847Z caller=main.go:216 build_context="(go=go1.9.2, user=root@615b82cb36b6, date=20171108-07:11:59)"
level=info ts=2017-12-08T04:30:53.92566228Z caller=main.go:217 host_details="(Linux 3.10.0-693.5.2.el7.x86_64 #1 SMP Fri Oct 20 20:32:50 UTC 2017 x86_64 localhost.localdomain (none))"
level=info ts=2017-12-08T04:30:53.932807536Z caller=web.go:380 component=web msg="Start listening for connections" address=0.0.0.0:9090
level=info ts=2017-12-08T04:30:53.93303681Z caller=targetmanager.go:71 component="target manager" msg="Starting target manager..."
level=info ts=2017-12-08T04:30:53.932905473Z caller=main.go:314 msg="Starting TSDB"
level=info ts=2017-12-08T04:30:53.987468942Z caller=main.go:326 msg="TSDB started"
level=info ts=2017-12-08T04:30:53.987582063Z caller=main.go:394 msg="Loading configuration file" filename=prometheus.yml
level=info ts=2017-12-08T04:30:53.988366778Z caller=main.go:371 msg="Server is ready to receive requests."
level=warn ts=2017-12-08T04:31:00.561007282Z caller=main.go:377 msg="Received SIGTERM, exiting gracefully..."
level=info ts=2017-12-08T04:31:00.563191668Z caller=main.go:384 msg="See you next time!"
level=info ts=2017-12-08T04:31:00.566231211Z caller=targetmanager.go:87 component="target manager" msg="Stopping target manager..."
level=info ts=2017-12-08T04:31:00.567070099Z caller=targetmanager.go:99 component="target manager" msg="Target manager stopped"
level=info ts=2017-12-08T04:31:00.567136027Z caller=manager.go:455 component="rule manager" msg="Stopping rule manager..."
level=info ts=2017-12-08T04:31:00.567162215Z caller=manager.go:461 component="rule manager" msg="Rule manager stopped"
level=info ts=2017-12-08T04:31:00.567186356Z caller=notifier.go:483 component=notifier msg="Stopping notification handler..."
</code>```

If anyone has instruction on how to connect prometheus to cassandra , both being on two different machines, that would be helpful too.

答:
This is not a problem with your config, prometheus received a TERM signal and terminated gracefully.

If you are not getting metrics, check whether 10.1.0.22:7199/metrics loads and returns metrics. You can also check the prometheus server's /targets endpoint for scraping status.

If you're not getting anything on your cassandra server's /metrics endpoint, it could be because you did not configure the cassandra prometheus exporter properly.

Body:
My prometheus tool is on centos 7 machine and cassandra is on centos 6. I am trying to monitor cassandra JMX port 7199 with prometheus. I keep getting error with my yml file. Not sure why I am not able to connect to the centos 6 (cassandra machine) Is my YAML file wrong or does it have something to do with JMX port 7199?
here is my YAML file:

my global config

global:
  scrape_interval: 15s

scrape_configs:
   - job_name: cassandra
     static_configs:
       - targets: ['10.1.0.22:7199']

Here is my prometheus log:

level=info ts=2017-12-08T04:30:53.92549611Z caller=main.go:215 msg="Starting Prometheus" version="(version=2.0.0, branch=HEAD, revision=0a74f98628a0463dddc90528220c94de5032d1a0)"
level=info ts=2017-12-08T04:30:53.925623847Z caller=main.go:216 build_context="(go=go1.9.2, user=root@615b82cb36b6, date=20171108-07:11:59)"
level=info ts=2017-12-08T04:30:53.92566228Z caller=main.go:217 host_details="(Linux 3.10.0-693.5.2.el7.x86_64 #1 SMP Fri Oct 20 20:32:50 UTC 2017 x86_64 localhost.localdomain (none))"
level=info ts=2017-12-08T04:30:53.932807536Z caller=web.go:380 component=web msg="Start listening for connections" address=0.0.0.0:9090
level=info ts=2017-12-08T04:30:53.93303681Z caller=targetmanager.go:71 component="target manager" msg="Starting target manager..."
level=info ts=2017-12-08T04:30:53.932905473Z caller=main.go:314 msg="Starting TSDB"
level=info ts=2017-12-08T04:30:53.987468942Z caller=main.go:326 msg="TSDB started"
level=info ts=2017-12-08T04:30:53.987582063Z caller=main.go:394 msg="Loading configuration file" filename=prometheus.yml
level=info ts=2017-12-08T04:30:53.988366778Z caller=main.go:371 msg="Server is ready to receive requests."
level=warn ts=2017-12-08T04:31:00.561007282Z caller=main.go:377 msg="Received SIGTERM, exiting gracefully..."
level=info ts=2017-12-08T04:31:00.563191668Z caller=main.go:384 msg="See you next time!"
level=info ts=2017-12-08T04:31:00.566231211Z caller=targetmanager.go:87 component="target manager" msg="Stopping target manager..."
level=info ts=2017-12-08T04:31:00.567070099Z caller=targetmanager.go:99 component="target manager" msg="Target manager stopped"
level=info ts=2017-12-08T04:31:00.567136027Z caller=manager.go:455 component="rule manager" msg="Stopping rule manager..."
level=info ts=2017-12-08T04:31:00.567162215Z caller=manager.go:461 component="rule manager" msg="Rule manager stopped"
level=info ts=2017-12-08T04:31:00.567186356Z caller=notifier.go:483 component=notifier msg="Stopping notification handler..."

If anyone has instruction on how to connect prometheus to cassandra , both being on two different machines, that would be helpful too.


问:
Does Junit reinitialize the class with each test method invocation?
When i run the below code, both test cases come true:

```<code>import static junit.framework.Assert.assertEquals;

import org.junit.Test;

public class MyTest{
    private int count;

    @Before
    public void before(){
        count=1;
    }

    @Test
    public void test1(){
        count++;
        assertEquals(2, count);
    }

    @Test
    public void test2(){
        count++;
        assertEquals(2, count);
    }
}
</code>```

EXPECTED BEHAVIOUR

test1 - success

test2 - fail(as expected that count will become 3)

ACTUAL BEHAVIOUR

test1 - success

test2 - success

Why junit is reinitializing class/variable with each test method invocation.
It is a bug in junit or is provided intentionally.

答: If you want to use test class's member variable for all tests , without it being reinitialised to null, then make it static.

Body:
When i run the below code, both test cases come true:

import static junit.framework.Assert.assertEquals;

import org.junit.Test;

public class MyTest{
    private int count;

    @Before
    public void before(){
        count=1;
    }

    @Test
    public void test1(){
        count++;
        assertEquals(2, count);
    }

    @Test
    public void test2(){
        count++;
        assertEquals(2, count);
    }
}

EXPECTED BEHAVIOUR

test1 - success

test2 - fail(as expected that count will become 3)

ACTUAL BEHAVIOUR

test1 - success

test2 - success

Why junit is reinitializing class/variable with each test method invocation.
It is a bug in junit or is provided intentionally.


问:
Find the list of inactive users in Bitbucket?
How can I find the list of those users who never logged in to their Bitbucket account? Is there any query or macro, or will I have to do it manually ?</p>

答:
You can do this with SQL query to database:</p>

```<code>    SELECT cu.lower_user_name
      ,cu.display_name
      ,cu.lower_display_name
      ,cu.lower_email_address
      ,cu.is_active
      ,dateadd(second,cast(cast(cua.attribute_value AS nvarchar(255)) AS bigint)/1000,'19700101 00:00:00:000') AS LAST_LOGIN
  FROM [BitBucketDB].[dbo].[cwd_user] As cu
      LEFT JOIN [BitBucketDB].[dbo].cwd_membership AS cm
        ON cu.directory_id=cm.directory_id
        AND cu.lower_user_name=cm.lower_child_name
        AND cm.membership_type='GROUP_USER'

      LEFT JOIN [BitBucketDB].[dbo].cwd_user_attribute As cua
      ON cu.ID = cua.user_id and cua.attribute_name='lastAuthenticationTimestamp'
      WHERE cm.lower_parent_name='stash-users'
</code>```

Body:
You can do this with SQL query to database:

    SELECT cu.lower_user_name
      ,cu.display_name
      ,cu.lower_display_name
      ,cu.lower_email_address
      ,cu.is_active
      ,dateadd(second,cast(cast(cua.attribute_value AS nvarchar(255)) AS bigint)/1000,'19700101 00:00:00:000') AS LAST_LOGIN
  FROM [BitBucketDB].[dbo].[cwd_user] As cu
      LEFT JOIN [BitBucketDB].[dbo].cwd_membership AS cm
        ON cu.directory_id=cm.directory_id
        AND cu.lower_user_name=cm.lower_child_name
        AND cm.membership_type='GROUP_USER'

      LEFT JOIN [BitBucketDB].[dbo].cwd_user_attribute As cua
      ON cu.ID = cua.user_id and cua.attribute_name='lastAuthenticationTimestamp'
      WHERE cm.lower_parent_name='stash-users'


问:
Override Views that OnFling hasn't Shown Yet
Is there a way I can get a reference to the Views that onFling has not yet revealed? I'm extending Gallery, and in my onFling method, of course I can get the current View (the one that is showing already). But I haven't found a way to get the views that are about to be flung by. I need to change properties like backgroundColor (it's a Gallery of TextViews).</p>

答:
There's a nifty method for handling each onFocus event in a gallery fling. As each item comes into focus, this will get fired.</p>

```<code>thisGallery.setOnItemSelectedListener(new OnItemSelectedListener() {
   @Override
   public void onItemSelected(AdapterView<?> parentView,
                              View selectedItemView,
                              int position,
                              long id) { }
</code>```

Body:
There's a nifty method for handling each onFocus event in a gallery fling. As each item comes into focus, this will get fired.

thisGallery.setOnItemSelectedListener(new OnItemSelectedListener() {
   @Override
   public void onItemSelected(AdapterView<?> parentView,
                              View selectedItemView,
                              int position,
                              long id) { }


问:
Regex using the AND NOT operator
I'm looking for a regular expression that I find in the text, the words "ata de audiência" OR "termo de audiência", and find "inconcilia" AND "reclamante" AND "reclamada", and do NOT find the word "sentença"

```<code>if(re.search(r'ata de audiência' or r'termo de audiência') and r'inconcilia' and r'reclamada' and r'reclamante' and not r'sentença', content.read())):
            key_content = True
</code>```

I tried to do it this way.. i can find the words, but when I use the  "AND NOT" operator, the regular expression does not work

ps: there are words in portuguese

答:
Try this:</p>

```<code>if(
0 <= re.search('((ata de audiência){1}||(termo de audiência){1})&&(inconcilia){1}&&(reclamada){1}&&(reclamante){1}&&(sentença){0}', content.read())
){
 key_content = True
}
</code>```

Title: Regex using the AND NOT operator

Body:
I'm looking for a regular expression that I find in the text, the words "ata de audiência" OR "termo de audiência", and find "inconcilia" AND "reclamante" AND "reclamada", and do NOT find the word "sentença"

if(re.search(r'ata de audiência' or r'termo de audiência') and r'inconcilia' and r'reclamada' and r'reclamante' and not r'sentença', content.read())):
            key_content = True

I tried to do it this way.. i can find the words, but when I use the  "AND NOT" operator, the regular expression does not work

ps: there are words in portuguese

Body:
Try this:

if(
0 <= re.search('((ata de audiência){1}||(termo de audiência){1})&&(inconcilia){1}&&(reclamada){1}&&(reclamante){1}&&(sentença){0}', content.read())
){
 key_content = True
}


问:
Google analytics - difference between analytics data and the data from the core platform
We use Google analytics with Google Tag manager for our ecommerce platform based to track the conversion, etc.,
In the thank you page, its used to track the order value and the revenues.

Consistently we see a difference of about 15 to 20 % difference between GA data and the data from the core platform.

Tried to find a pattern among the missed orders but couldn´t ascertain one easily. The GA recorded orders include devices like Desktop, tablet and mobile and we see different browsers too.

Need inputs to analyze this better.

Note: Thank you page is loaded by a redirect from the payment gateway system

答:
15-20% difference is not good at all.  Google says you should expect better than 95% accuracy, and to keep at it if you're not getting those numbers.

Note: The more "techy" crowd that your website has, the more folks you'll run into "Do not track" or with Ad-Blocking tech in their browser.  Normally, you'd want to try to baseline that difference using device category filters to see if the gap is bigger for desktop (most phones/tablets don't use ad-blocking).

First, question. If the user lands on the thankyou page, and hits the refresh button,  does it send another "conversion" to GA?  IF so, you want to make sure that you build in logic that prevents duplicate conversions to be sent if the user was not making duplicate purchases. A browser refresh is not a purchase, don't record it as such.

Second, if the page takes forever to load, or you have users that have bad internet, then that could increase the difference. They might be closing the browser or exiting site before GA client has a chance to send the final conversion to the server.  So how is the performance of your thankyou page?

Are you sure you're looking at the correct business data? I've been told GA numbers are off by the business before and it turned out they messed up their own query in the transaction system (and they had been doing so for years!). It is a long shot,  but if you feel super confident about your GA measurement setup, then run it by the folks giving you the transaction numbers.

Finally, if you can't get the difference down then move to the Measurement Protocol server-side implementation of GA.  You simply need to record the IP address of the user and their GA client id, and then construct an HTTPS GET request using the Measurement Protocol fields for a valid hit. Server side measurement is the most accurate way to do this, but requires code updates in the ecommerce platform itself.


问:
SQLServer Issue with view on another database
SQLServer 2008R2, we have the following architecture:

Table A (on Database A)  <-- View A (on Database B, same server)

Users should be able to select View A but not Table A. The Scenario works fine, if table and view reside on the same database. But with the given architekture, View A can only be selected, if Table A can be selected as well.

Can we solve that without changing the "concept of different databases"?

答: One method is to turn on the DB_CHAINING database option in both databases. This will allow normal ownership chaining to extend to both databases as long as the referenced table owners map to the same login. In the case of dbo-owned objects, the implication is that both databases must be owned by the same login (AUTOORIZATION). Users must exist in both databases and have permissions on the view. Permissions on the tables referenced by the view are not necessary.


问:
Rails getting routes name in Route.rb with controller actions
I'm a real beginner of rails.

Can I get multiple routes from one controller + many actions?

For example,

```<code>resources :something
</code>```

get "something#index", "something#show", "something#update"...etc.

I'm just curious if there is a command to get route name from the actions.

For example, in a controller named "pledges",

```<code>class PledgesController < ApplicationController
    def home
    end

    def abc
    end

    def defg
    end

    def hijk
    end
end
</code>```

Can any commands get "pledges#home", "pledges#abc", "pledges#defg","pledges#hijk" ?

答:
To add custom, "non-RESTful" routes to a resource, you could do the following:

```<code>resources :pledges do
  collection do
    get :foo
  end

  member do
    put :bar
  end
end
</code>```

collection-defined routes will produce results against Pledge as a whole – think the index route.

member-defined routes will produce results against an instance of Pledge – think the show route.

This would produce the following routes for you:

```<code>foo_pledges  GET       /pledges/foo(.:format          pledges#foo
bar_pledge   PUT       /pledges/:id/bar(.:format)     pledges#bar
pledges      GET       /pledges(.:format)             pledges#index
             POST      /pledges(.:format)             pledges#create
new_pledge   GET       /pledges/new(.:format)         pledges#new
edit_pledge  GET       /pledges/:id/edit(.:format)    pledges#edit
pledge       GET       /pledges/:id(.:format)         pledges#show
             PATCH     /pledges/:id(.:format)         pledges#update
             PUT       /pledges/:id(.:format)         pledges#update
             DELETE    /pledges/:id(.:format)         pledges#destroy
</code>```

Body:
I'm a real beginner of rails.

Can I get multiple routes from one controller + many actions?

For example,

resources :something

get "something#index", "something#show", "something#update"...etc.

I'm just curious if there is a command to get route name from the actions.

For example, in a controller named "pledges",

class PledgesController < ApplicationController
    def home
    end

    def abc
    end

    def defg
    end

    def hijk
    end
end

Can any commands get "pledges#home", "pledges#abc", "pledges#defg","pledges#hijk" ?

Body:
To add custom, "non-RESTful" routes to a resource, you could do the following:

resources :pledges do
  collection do
    get :foo
  end

  member do
    put :bar
  end
end

collection-defined routes will produce results against Pledge as a whole – think the index route.

member-defined routes will produce results against an instance of Pledge – think the show route.

This would produce the following routes for you:

foo_pledges  GET       /pledges/foo(.:format          pledges#foo
bar_pledge   PUT       /pledges/:id/bar(.:format)     pledges#bar
pledges      GET       /pledges(.:format)             pledges#index
             POST      /pledges(.:format)             pledges#create
new_pledge   GET       /pledges/new(.:format)         pledges#new
edit_pledge  GET       /pledges/:id/edit(.:format)    pledges#edit
pledge       GET       /pledges/:id(.:format)         pledges#show
             PATCH     /pledges/:id(.:format)         pledges#update
             PUT       /pledges/:id(.:format)         pledges#update
             DELETE    /pledges/:id(.:format)         pledges#destroy


问:
Animate button inside custom adapter for listview
I made a ListView with a custom adapter with my own layout, and on this layout there is a text view, a button and three image buttons that are at first with setVisibility.GONE
I am trying to animate this button for when the user clicks on it, it changes its position from right to left to give space for the three image buttons.

The problem is, the only item in which the animation is working is the last item on the list. I want the animation to work in all of the items.

Here's the code for my adapter:

```<code>public class ListaAdapter extends BaseAdapter implements ListAdapter {

private ArrayList<String> list = new ArrayList<String>();
private Context context;
private ListView lista;
private Button btnAbrir;
private RelativeLayout relativeLayout;
private ObjectAnimator animation;

public ListaAdapter (ArrayList<String> list, Context context, ListView a) {
    this.list = list;
    this.context = context;
    this.lista = a;

}

@Override
public int getCount() {
    return list.size();
}

@Override
public Object getItem(int pos) {
    return list.get(pos);
}

@Override
public long getItemId(int pos) {
    return 0;
    //just return 0 if your list items do not have an Id variable.
}

@Override
public View getView(final int position, View convertView, ViewGroup
parent)
{
    View view = convertView;
    if (view == null) {
        LayoutInflater inflater = (LayoutInflater)
    context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        view = inflater.inflate(R.layout.custom_list, null);
}

TextView listItemText = (TextView)view.findViewById(R.id.textoItem);
listItemText.setText(list.get(position));

final LinearLayout btnLayout = (LinearLayout)
 view.findViewById(R.id.btnLayout);

relativeLayout = (RelativeLayout) view.findViewById(R.id.layout);

btnAbrir = (Button)view.findViewById(R.id.btnAbrir);

ImageButton btnNaoSei = (ImageButton)view.findViewById(R.id.btnNaoSei);

ImageButton btnAceitar =
(ImageButton)view.findViewById(R.id.btnAceitar);

ImageButton btnNegar = (ImageButton)view.findViewById(R.id.btnNegar);

animation = ObjectAnimator.ofFloat(btnAbrir,"x",200);

btnLayout.setVisibility(View.GONE);

btnAbrir.setOnClickListener(new View.OnClickListener() {

@Override
        public void onClick(View view) {

            btnLayout.setVisibility(View.VISIBLE);

           animate();
        }
    });

    return view;
}

private void animate()
{
    animation.setDuration(500);
    animation.start();
}
}
</code>```

And this is my custom_list.xml layout:

```<code><?xml version="1.0" encoding="utf-8"?>

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical"
android:animateLayoutChanges="true">

<RelativeLayout
    android:id="@+id/layout"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_alignParentLeft="true"
    android:layout_alignParentStart="true"
    android:layout_alignParentTop="true"
    android:background="@color/white">

    <LinearLayout
        android:id="@+id/btnLayout"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentEnd="true"
        android:layout_alignParentRight="true"
        android:layout_alignParentTop="true"
        android:orientation="horizontal">

        <RelativeLayout
            android:layout_width="@dimen/_32sdp"
            android:layout_height="@dimen/_50sdp"
            android:background="@color/compras_barra">

            <ImageButton
                android:id="@+id/btnNaoSei"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_alignParentLeft="false"
                android:layout_alignParentStart="false"
                android:layout_alignParentTop="false"
                android:backgroundTint="@color/compras_barra"
                android:contextClickable="false"
                app:srcCompat="@drawable/a12" />

            <TextView
                android:id="@+id/textView11"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_below="@+id/btnNaoSei"
                android:layout_centerHorizontal="true"
                android:text="NÃO SEI"
                android:textColor="@color/white"
                android:textSize="8sp" />

        </RelativeLayout>

        <RelativeLayout
            android:layout_width="@dimen/_32sdp"
            android:layout_height="@dimen/_50sdp"
            android:background="@color/compras">

            <ImageButton
                android:id="@+id/btnAceitar"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_alignParentTop="true"
                android:layout_centerHorizontal="true"
                android:layout_marginTop="11dp"
                android:background="@color/compras"
                app:srcCompat="@drawable/a11" />

            <TextView
                android:id="@+id/textView12"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_alignParentEnd="true"
                android:layout_alignParentRight="true"
                android:layout_below="@+id/btnAceitar"
                android:paddingEnd="@dimen/_3sdp"
                android:paddingTop="@dimen/_8sdp"
                android:text="ACEITAR"
                android:textColor="@color/white"
                android:textSize="8sp" />

        </RelativeLayout>

        <RelativeLayout
            android:layout_width="@dimen/_32sdp"
            android:layout_height="@dimen/_50sdp"
            android:background="@color/compras_texto2">

            <ImageButton
                android:id="@+id/btnNegar"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_alignParentTop="true"
                android:layout_centerHorizontal="true"
                android:layout_marginTop="10dp"
                android:background="@color/compras_texto2"
                app:srcCompat="@drawable/a10" />

            <TextView
                android:id="@+id/textView13"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_alignParentBottom="true"
                android:layout_centerHorizontal="true"
                android:layout_marginBottom="12dp"
                android:paddingBottom="@dimen/_1sdp"
                android:text="NEGAR"
                android:textColor="@color/white"
                android:textSize="8sp" />

        </RelativeLayout>

    </LinearLayout>

    <Button
        android:id="@+id/btnAbrir"
        android:layout_width="30dp"
        android:layout_height="30dp"
        android:background="@drawable/a09"
        android:layout_alignTop="@+id/textoItem"
        android:layout_alignParentRight="true"
        android:layout_alignParentEnd="true" />

    <TextView
        android:id="@+id/textoItem"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginStart="@dimen/_10sdp"
        android:layout_marginTop="@dimen/_10sdp"
        android:maxWidth="200dp"
        android:text="TextView"
        android:textColor="@color/compras_texto2" />
</RelativeLayout>
</code>```

Any idea on how to accomplish this? Thanks in advance.

答:
The things you need to adopt the following method and create a ViewHolder so that your adapter will know each element of each row in the List

The last UI element of the row only animates because this the only last known id of components for your Adapater when he was creating the Views in your List. So it will animates for the last row elements

You have to add ViewHolder nested class inside your Adapter and declare your UI components. Use setTag and getTag methods inside the getView

Overall you have to create your adapter things like this in getView

```<code>public class SListAdapter extends ArrayAdapter<String> {

    private Context context;
    private String[] seCtnColors;
    private List<Subscription> item;
    private ViewHolder mainViewHolder = null;
    private ViewHolder viewHolder;
    private LayoutInflater inflater;
    private View row;

    public SListAdapter(Context c, List<Subscription> subscriptions)
    {
        super(c, R.layout.row,R.id.rowNameTV);
        this.context=c;
        this.item = subscriptions;
    }

    @Override
    public int getCount() {
        return this.item.size();
    }

    @Override
    public View getView(final int position, final View convertView, ViewGroup parent) {
        row = null;
        inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        row = inflater.inflate(R.layout.row,parent,false);
        viewHolder = new ViewHolder();
        initAdapterUI();
        setAdapterDataset(position);

        return row;
    }

    private void initAdapterUI() {

        viewHolder.animatedGifViewHol = row.findViewById(R.id.row_animated_gif);
        viewHolder.alertBarVerticalViewHol = row.findViewById(R.id.alertBarVerticalView);
        viewHolder.firstNameTVHol = (TextView) row.findViewById(R.id.rowNameTV);
        viewHolder.phoneNumberTVHol = (TextView) row.findViewById(R.id.rowNumberTV);
        viewHolder.switchStateTVHol = (TextView) row.findViewById(R.id.switchStateTV);
        row.setTag(viewHolder);
    }

    private void setAdapterDataset(int position) {
        mainViewHolder = (ViewHolder) row.getTag();
        mainViewHolder.alertBarVerticalViewHol.setBackgroundColor(Color.RED);
        mainViewHolder.switchStateTVHol.setTextColor(Color.RED);
        mainViewHolder.firstNameTVHol.setText(item.get(position).getFirstName());
        mainViewHolder.phoneNumberTVHol.setText(item.get(position).getNumber());
    }

    public class ViewHolder{
        View animatedGifViewHol;
        View alertBarVerticalViewHol;
        TextView firstNameTVHol;
        TextView switchStateTVHol;
        TextView phoneNumberTVHol;
    }
}
</code>```

Body:
I made a ListView with a custom adapter with my own layout, and on this layout there is a text view, a button and three image buttons that are at first with setVisibility.GONE
I am trying to animate this button for when the user clicks on it, it changes its position from right to left to give space for the three image buttons.

The problem is, the only item in which the animation is working is the last item on the list. I want the animation to work in all of the items.

Here's the code for my adapter:

public class ListaAdapter extends BaseAdapter implements ListAdapter {

private ArrayList<String> list = new ArrayList<String>();
private Context context;
private ListView lista;
private Button btnAbrir;
private RelativeLayout relativeLayout;
private ObjectAnimator animation;

public ListaAdapter (ArrayList<String> list, Context context, ListView a) {
    this.list = list;
    this.context = context;
    this.lista = a;

}

@Override
public int getCount() {
    return list.size();
}

@Override
public Object getItem(int pos) {
    return list.get(pos);
}

@Override
public long getItemId(int pos) {
    return 0;
    //just return 0 if your list items do not have an Id variable.
}

@Override
public View getView(final int position, View convertView, ViewGroup
parent)
{
    View view = convertView;
    if (view == null) {
        LayoutInflater inflater = (LayoutInflater)
    context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        view = inflater.inflate(R.layout.custom_list, null);
}

TextView listItemText = (TextView)view.findViewById(R.id.textoItem);
listItemText.setText(list.get(position));

final LinearLayout btnLayout = (LinearLayout)
 view.findViewById(R.id.btnLayout);

relativeLayout = (RelativeLayout) view.findViewById(R.id.layout);

btnAbrir = (Button)view.findViewById(R.id.btnAbrir);

ImageButton btnNaoSei = (ImageButton)view.findViewById(R.id.btnNaoSei);

ImageButton btnAceitar =
(ImageButton)view.findViewById(R.id.btnAceitar);

ImageButton btnNegar = (ImageButton)view.findViewById(R.id.btnNegar);

animation = ObjectAnimator.ofFloat(btnAbrir,"x",200);

btnLayout.setVisibility(View.GONE);

btnAbrir.setOnClickListener(new View.OnClickListener() {

@Override
        public void onClick(View view) {

            btnLayout.setVisibility(View.VISIBLE);

           animate();
        }
    });

    return view;
}

private void animate()
{
    animation.setDuration(500);
    animation.start();
}
}

And this is my custom_list.xml layout:

<?xml version="1.0" encoding="utf-8"?>

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical"
android:animateLayoutChanges="true">

<RelativeLayout
    android:id="@+id/layout"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_alignParentLeft="true"
    android:layout_alignParentStart="true"
    android:layout_alignParentTop="true"
    android:background="@color/white">

    <LinearLayout
        android:id="@+id/btnLayout"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentEnd="true"
        android:layout_alignParentRight="true"
        android:layout_alignParentTop="true"
        android:orientation="horizontal">

        <RelativeLayout
            android:layout_width="@dimen/_32sdp"
            android:layout_height="@dimen/_50sdp"
            android:background="@color/compras_barra">

            <ImageButton
                android:id="@+id/btnNaoSei"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_alignParentLeft="false"
                android:layout_alignParentStart="false"
                android:layout_alignParentTop="false"
                android:backgroundTint="@color/compras_barra"
                android:contextClickable="false"
                app:srcCompat="@drawable/a12" />

            <TextView
                android:id="@+id/textView11"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_below="@+id/btnNaoSei"
                android:layout_centerHorizontal="true"
                android:text="NÃO SEI"
                android:textColor="@color/white"
                android:textSize="8sp" />

        </RelativeLayout>

        <RelativeLayout
            android:layout_width="@dimen/_32sdp"
            android:layout_height="@dimen/_50sdp"
            android:background="@color/compras">

            <ImageButton
                android:id="@+id/btnAceitar"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_alignParentTop="true"
                android:layout_centerHorizontal="true"
                android:layout_marginTop="11dp"
                android:background="@color/compras"
                app:srcCompat="@drawable/a11" />

            <TextView
                android:id="@+id/textView12"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_alignParentEnd="true"
                android:layout_alignParentRight="true"
                android:layout_below="@+id/btnAceitar"
                android:paddingEnd="@dimen/_3sdp"
                android:paddingTop="@dimen/_8sdp"
                android:text="ACEITAR"
                android:textColor="@color/white"
                android:textSize="8sp" />

        </RelativeLayout>

        <RelativeLayout
            android:layout_width="@dimen/_32sdp"
            android:layout_height="@dimen/_50sdp"
            android:background="@color/compras_texto2">

            <ImageButton
                android:id="@+id/btnNegar"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_alignParentTop="true"
                android:layout_centerHorizontal="true"
                android:layout_marginTop="10dp"
                android:background="@color/compras_texto2"
                app:srcCompat="@drawable/a10" />

            <TextView
                android:id="@+id/textView13"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_alignParentBottom="true"
                android:layout_centerHorizontal="true"
                android:layout_marginBottom="12dp"
                android:paddingBottom="@dimen/_1sdp"
                android:text="NEGAR"
                android:textColor="@color/white"
                android:textSize="8sp" />

        </RelativeLayout>

    </LinearLayout>

    <Button
        android:id="@+id/btnAbrir"
        android:layout_width="30dp"
        android:layout_height="30dp"
        android:background="@drawable/a09"
        android:layout_alignTop="@+id/textoItem"
        android:layout_alignParentRight="true"
        android:layout_alignParentEnd="true" />

    <TextView
        android:id="@+id/textoItem"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginStart="@dimen/_10sdp"
        android:layout_marginTop="@dimen/_10sdp"
        android:maxWidth="200dp"
        android:text="TextView"
        android:textColor="@color/compras_texto2" />
</RelativeLayout>

Any idea on how to accomplish this? Thanks in advance.

Body:
The things you need to adopt the following method and create a ViewHolder so that your adapter will know each element of each row in the List

The last UI element of the row only animates because this the only last known id of components for your Adapater when he was creating the Views in your List. So it will animates for the last row elements

You have to add ViewHolder nested class inside your Adapter and declare your UI components. Use setTag and getTag methods inside the getView

Overall you have to create your adapter things like this in getView

public class SListAdapter extends ArrayAdapter<String> {

    private Context context;
    private String[] seCtnColors;
    private List<Subscription> item;
    private ViewHolder mainViewHolder = null;
    private ViewHolder viewHolder;
    private LayoutInflater inflater;
    private View row;

    public SListAdapter(Context c, List<Subscription> subscriptions)
    {
        super(c, R.layout.row,R.id.rowNameTV);
        this.context=c;
        this.item = subscriptions;
    }

    @Override
    public int getCount() {
        return this.item.size();
    }

    @Override
    public View getView(final int position, final View convertView, ViewGroup parent) {
        row = null;
        inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        row = inflater.inflate(R.layout.row,parent,false);
        viewHolder = new ViewHolder();
        initAdapterUI();
        setAdapterDataset(position);

        return row;
    }

    private void initAdapterUI() {

        viewHolder.animatedGifViewHol = row.findViewById(R.id.row_animated_gif);
        viewHolder.alertBarVerticalViewHol = row.findViewById(R.id.alertBarVerticalView);
        viewHolder.firstNameTVHol = (TextView) row.findViewById(R.id.rowNameTV);
        viewHolder.phoneNumberTVHol = (TextView) row.findViewById(R.id.rowNumberTV);
        viewHolder.switchStateTVHol = (TextView) row.findViewById(R.id.switchStateTV);
        row.setTag(viewHolder);
    }

    private void setAdapterDataset(int position) {
        mainViewHolder = (ViewHolder) row.getTag();
        mainViewHolder.alertBarVerticalViewHol.setBackgroundColor(Color.RED);
        mainViewHolder.switchStateTVHol.setTextColor(Color.RED);
        mainViewHolder.firstNameTVHol.setText(item.get(position).getFirstName());
        mainViewHolder.phoneNumberTVHol.setText(item.get(position).getNumber());
    }

    public class ViewHolder{
        View animatedGifViewHol;
        View alertBarVerticalViewHol;
        TextView firstNameTVHol;
        TextView switchStateTVHol;
        TextView phoneNumberTVHol;
    }
}


问:
Cannot get image (ASP.NET)
I have View where I need to get src value for pic from db.

Here is View code

```<code>   <tbody id="findings" style="overflow-y: scroll;">
                @foreach (var item in Model)
                {
                    <tr>
                        <td class="point">
                            @(rowNo += 1)
                        </td>
                        <td style="display:none" id="patientId" class="title">
                            @Html.DisplayFor(modelItem => item.Patient_id)
                        </td>

                        <td class="title">
                            @Html.DisplayFor(modelItem => item.Patient.Date_of_Birthday)
                        </td>
                        <td id="nameVal" class="title">
                            @Html.DisplayFor(modelItem => item.Patient.Name)
                        </td>
                        <td class="title">
                            @Html.DisplayFor(modelItem => item.Start_appointment)
                        </td>
                        <td class="title">
                            <img src="@item.Calculation.CalculationStatus" />
                        </td>
                        <td class="title"></td>
                        <td class="title"></td>
                    </tr>
                 }
            </tbody>
</code>```

But when I run I have error

Failed to load resource: the server responded with a status of 404
  (Not Found)

In page source I have this

I don't understand why page not showing.

答: Problem was at ~ symbol. Without it, all will be working.

Title: Cannot get image (ASP.NET)

Body:
I have View where I need to get src value for pic from db.

Here is View code

                @foreach (var item in Model)
                {

                            @(rowNo += 1)

                            @Html.DisplayFor(modelItem => item.Patient_id)

                            @Html.DisplayFor(modelItem => item.Patient.Date_of_Birthday)

                            @Html.DisplayFor(modelItem => item.Patient.Name)

                            @Html.DisplayFor(modelItem => item.Start_appointment)

                 }

But when I run I have error

Failed to load resource: the server responded with a status of 404
  (Not Found)

In page source I have this

I don't understand why page not showing.


答:
Here are two approaches.

1) regular expression Collapse t(m) into a single space-separated string and use strapply with the indicated regular expression to pick out everything from the beginning of that string to the first 11 that follows a 00 or 01.  The number of spaces plus 1 in the extracted string is the position of the 11. Convert that to row and column numbers.

```<code>library(gsubfn)

v <- paste(t(m), collapse = " ")
ix <- head(strapply(v, ".*?0[01].*?11", ~ nchar(gsub("\\S", "", x)), simplify = c), 1) + 1
c(t(row(m))[ix], t(col(m))[ix])
## [1] 1 3
</code>```

2) Position/Find A different approach calculates the position of the first 00 or 01, w0, and ix, the position of the first 11 greater than w0. Finally
compute the row and column numbers.

```<code>w0 <- Position(isTRUE, grepl("0[01]", t(m)))
ix <- Find(function(x) x > w0, which(t(m) == 11))
c(t(row(m))[ix], t(col(m))[ix])
    ## [1] 1 3
</code>```

3) state machine Using switch and Reduce we could implement a state machine.  We are in state 1 starting out.  As soon as we find a 00 or 01 we transition to state 2 and when in state 2 upon finding a 11 we transition into state 3.  If we are in state 3 or 4 we transition into state 4.  State 3 is the position of the first 11 after a 00 or 01.

```<code>transition <- function(state, x)
  switch(state,
    if (x == "00" || x == "01") 2 else 1,
    if (x == "11") 3 else 2,
    4,
    4)
r <- Reduce(transition, init = 1, c(t(m)), accumulate = TRUE)[-1]
ix <- which(r == 3)
c(t(row(m))[ix], t(col(m))[ix])
## [1] 1 3
</code>```

Note: We used this as the input:

```<code>m <- structure(c("01", "11", "01", "01", "01", "11", "11", "11", "10"
), .Dim = c(3L, 3L), .Dimnames = list(NULL, NULL))
</code>```

Title: Picking up a Sequence out of a matrix

Body:
Here are two approaches.

1) regular expression Collapse t(m) into a single space-separated string and use strapply with the indicated regular expression to pick out everything from the beginning of that string to the first 11 that follows a 00 or 01.  The number of spaces plus 1 in the extracted string is the position of the 11. Convert that to row and column numbers.

library(gsubfn)

v <- paste(t(m), collapse = " ")
ix <- head(strapply(v, ".*?0[01].*?11", ~ nchar(gsub("\\S", "", x)), simplify = c), 1) + 1
c(t(row(m))[ix], t(col(m))[ix])
## [1] 1 3

2) Position/Find A different approach calculates the position of the first 00 or 01, w0, and ix, the position of the first 11 greater than w0. Finally
compute the row and column numbers.

w0 <- Position(isTRUE, grepl("0[01]", t(m)))
ix <- Find(function(x) x > w0, which(t(m) == 11))
c(t(row(m))[ix], t(col(m))[ix])
    ## [1] 1 3

3) state machine Using switch and Reduce we could implement a state machine.  We are in state 1 starting out.  As soon as we find a 00 or 01 we transition to state 2 and when in state 2 upon finding a 11 we transition into state 3.  If we are in state 3 or 4 we transition into state 4.  State 3 is the position of the first 11 after a 00 or 01.

transition <- function(state, x)
  switch(state,
    if (x == "00" || x == "01") 2 else 1,
    if (x == "11") 3 else 2,
    4,
    4)
r <- Reduce(transition, init = 1, c(t(m)), accumulate = TRUE)[-1]
ix <- which(r == 3)
c(t(row(m))[ix], t(col(m))[ix])
## [1] 1 3

Note: We used this as the input:

m <- structure(c("01", "11", "01", "01", "01", "11", "11", "11", "10"
), .Dim = c(3L, 3L), .Dimnames = list(NULL, NULL))


问:
Error when installing NUnit 3.9 in Visual Studio 13 with NuGet
I am trying to install NUnit 3.9 in Visual Studio 13 Professional, but I am facing the below mentioned error while installing:

```<code>'NUnit' already has a dependency defined for 'NETStandard.Library'.
</code>```

How do I solve this issue?

答:
If you cannot upgrade Visual Studio to a newer version that includes newer versions of NuGet, you can install NUnit 3.5.0 which doesn't include .NET Standard. You can select the older versions from a dropdown in the user interface, or install from the Package Manager Console.</p>

```<code>Install-Package NUnit -Version 3.5.0
</code>```

Body:
I am trying to install NUnit 3.9 in Visual Studio 13 Professional, but I am facing the below mentioned error while installing:

'NUnit' already has a dependency defined for 'NETStandard.Library'.

How do I solve this issue?

Body:
If you cannot upgrade Visual Studio to a newer version that includes newer versions of NuGet, you can install NUnit 3.5.0 which doesn't include .NET Standard. You can select the older versions from a dropdown in the user interface, or install from the Package Manager Console.

Install-Package NUnit -Version 3.5.0


问:
How do I access my iPhone 4's UDID?
I have just bought an iPhone 4 for development.

Unfortunately, I forgot to register my phone to my development account before I tried installing the iOS 4.3 beta 2 software.

Now I can't restore my iPhone because I haven't got my UDID in my developer account, and I cannot get the UDID in iTunes because my phone is stuck in recovery mode.

Does anyone know how to restore my phone, or how to get the UDID into the developer account so it can be restored?

Thank you

答:
You should be able to just click "Restore" in recovery mode in iTunes and it'll restore the current 4.2.1 firmware.

Perhaps you need to put it in DFU mode first.

Title: How do I access my iPhone 4's UDID?


问:
Why is compiling with CGO_ENABLED=0 slower?
When writing programs which utilize network, you can see quite noticeable slowdown of compilation with CGO_ENABLED=0.

For example, the simplest HTTP server:

```<code>package main

import (
    "flag"
    "fmt"
    "log"
    "net/http"
)

func handler(w http.ResponseWriter, r *http.Request) {
    fmt.Fprintf(w, "Hi! glad you requested %s.\n", r.URL.Path[1:])
}

func main() {
    port := flag.Int("port", 9000, "")
    flag.Parse()

    http.HandleFunc("/", handler)
    err := http.ListenAndServe(fmt.Sprintf(":%d", *port), nil)
    if err != nil {
        log.Fatal(err)
    }
}
</code>```

the timings are:

```<code>% time go build
go build  0.46s user 0.06s system 131% cpu 0.396 total
% time CGO_ENABLED=0 go build
CGO_ENABLED=0 go build  3.93s user 0.15s system 143% cpu 2.849 total
</code>```

So far I'm not using bindings to C so CGo handling or not seems irrelevant, what I'd like to do is to compile 100% static binary, but not if there's such slowdown.

What is the cause of such behavior?

答:
The problem is that the standard library packages are built without flags. CGO_ENABLED changes build flags and therefore it can't use the pre-built packages so most of the standard library needs to be rebuilt.

As the other answer mentioned, go build -i will install the packages built with the new flags, but that won't really solve much because if you install packages built with CGO_ENABLED=0, it will speed up all future builds with CGO_ENABLED=0, but it will slow down all the builds without it.

Unfortunately the way pre-built packages are installed by default today is pretty inefficient because everything goes into the same directory under the same names regardless of how it's built. If you want to be able to have fast builds of go programs with different flags, besides doing go build -i you also need to use the the -installsuffix and/or the -pkgdir flags. In the system I work in, we have a handful of different compilation modes, each mode has different flags (because of a lot of old C code we interface with) and each mode also has its own -pkgdir.

Body:
When writing programs which utilize network, you can see quite noticeable slowdown of compilation with CGO_ENABLED=0.

For example, the simplest HTTP server:

package main

import (
    "flag"
    "fmt"
    "log"
    "net/http"
)

func handler(w http.ResponseWriter, r *http.Request) {
    fmt.Fprintf(w, "Hi! glad you requested %s.\n", r.URL.Path[1:])
}

func main() {
    port := flag.Int("port", 9000, "")
    flag.Parse()

    http.HandleFunc("/", handler)
    err := http.ListenAndServe(fmt.Sprintf(":%d", *port), nil)
    if err != nil {
        log.Fatal(err)
    }
}

the timings are:

% time go build
go build  0.46s user 0.06s system 131% cpu 0.396 total
% time CGO_ENABLED=0 go build
CGO_ENABLED=0 go build  3.93s user 0.15s system 143% cpu 2.849 total

So far I'm not using bindings to C so CGo handling or not seems irrelevant, what I'd like to do is to compile 100% static binary, but not if there's such slowdown.

What is the cause of such behavior?


问:
Issues when creating using oracle_fdw extension in windows
I'm trying to install and use oracle_fdw in postgresql 9.6, however I keep receiving the same issue every time that I run the following command:

```<code>create extension oracle_fdw;
ERROR:  could not load library "D:/PostgreSQL/pg96/../pg96/lib/postgresql/oracle_fdw.dll":
    The specified module could not be found.
</code>```

Two things are very strange here:

the folder that it's looking for the dll, has a ".." in the middle, so it seems it should look into D:\PostgreSQL\pg96\lib only, but I do have the folder D:\PostgreSQL\pg96\lib\postgresql as well.

I set the following variables in the system, but it seems not to reflect in the command:

```<code>Path: D:\PostgreSQL\pg96\lib\;C:\Program Files\Oracle Instant Client\instantclient_12_2;
    D:\PostgreSQL\pg96\lib\postgresql
</code>```

Are you guys able to help me? I really need specific instructions on how to make it work.

Tks!

答:
Many are running into this issue and I got it resoved in most cases.
Oracle Client libraries are compiled using specific version of Visual C++. So we need to have Visual C++ redistributable package of that particular version of Visual Studio is required in the system.
Second dependancy is coming from oracle_fdw.dll. Lastest community version of oracle_fdw.dll is prepared using Visual C++ 2013. So we need to have Visual C++ 2013 Redistributable package to be present in the system.
Once all such dependanices are solved, it works.

Alaternatively, you can use oracle_fdw.dll prepared by BigSQL project. Since the project is built using MSYS2, there is no dependancies to Visual C++. However the dependancy created by Oracle client libraries cannot be avoided.

Body:
I'm trying to install and use oracle_fdw in postgresql 9.6, however I keep receiving the same issue every time that I run the following command:

create extension oracle_fdw;
ERROR:  could not load library "D:/PostgreSQL/pg96/../pg96/lib/postgresql/oracle_fdw.dll":
    The specified module could not be found.

Two things are very strange here:

the folder that it's looking for the dll, has a ".." in the middle, so it seems it should look into D:\PostgreSQL\pg96\lib only, but I do have the folder D:\PostgreSQL\pg96\lib\postgresql as well.

I set the following variables in the system, but it seems not to reflect in the command:

Path: D:\PostgreSQL\pg96\lib\;C:\Program Files\Oracle Instant Client\instantclient_12_2;
    D:\PostgreSQL\pg96\lib\postgresql

Are you guys able to help me? I really need specific instructions on how to make it work.

Tks!


问:
perform data-toggle with jquery
I have a button that toggles a bootstrap modal.

```<code><button class="btn btn-primary btn-lg" data-toggle="modal" data-target="#myModal">
</code>```

I want to do the same thing with a jquery function. Is this possible?

答: Just a simple $("#myModal").modal() in any function of your choice

Title: perform data-toggle with jquery

Body:
I have a button that toggles a bootstrap modal.

<button class="btn btn-primary btn-lg" data-toggle="modal" data-target="#myModal">

I want to do the same thing with a jquery function. Is this possible?


问:
Attempt to perform arithmetic on global 't1' (a table value)
Trying to add tables, using metatables, I get this error, I have really complicated here and there is no way to solve (I am learning Lua)
)

```<code>mt = { ___add = function (a,b)
                local s = {}
                for k,v in ipairs( a ) do s[#s + 1] = v end
                for k,v in ipairs( b ) do s[#s + 1] = v end
               end
    }

t1 = {1,2,3}
t2 = {4,5}
setmetatable( t1, mt )
print(table.concat(t1+t2, ", "))
</code>```

It gives me this result when trying to "compile" with the interpreter

```<code>main.lua:15: attempt to perform arithmetic on global 't1' (a table value)
main.lua:15: in main chunk
</code>```

答:
Two problems in your code:

The name of the metamethod is __add, with two underscores, not  three.

You need to return s in the metamethod.

After you fix these, the code works as expected.

Body:
Trying to add tables, using metatables, I get this error, I have really complicated here and there is no way to solve (I am learning Lua)
)

mt = { ___add = function (a,b)
                local s = {}
                for k,v in ipairs( a ) do s[#s + 1] = v end
                for k,v in ipairs( b ) do s[#s + 1] = v end
               end
    }

t1 = {1,2,3}
t2 = {4,5}
setmetatable( t1, mt )
print(table.concat(t1+t2, ", "))

It gives me this result when trying to "compile" with the interpreter

main.lua:15: attempt to perform arithmetic on global 't1' (a table value)
main.lua:15: in main chunk


问:
How to show different Views on different Drupal Themes
Say I have a default theme for my drupal site. Here I have created views, blocks, etc and styled everything the way I want for the public. Now, as the admin I would like to have an entirely separate theme. No problem, I create a second theme in the themes directory and switch my admin user theme configuration to the second theme. But, what if in my second theme I want to show entirely different content (i.e. Views, blocks, etc).
Let's use my front page as an example (front).
Right now my front page has a slideshow using Views. This view obviously shows up on the front page no matter what theme I'm using. So for my front page, how could I show an entirely different View (say a list of blog posts) for the second theme than the slideshow View I'm using for the first theme?</p>

答:
If the question is about the admin theme that fires on different paths and blocks have path visibility settings. Views do not just appear on a page, if they are in a block, that's handled if not -- how do they appear on the page?

As for front, if you say have two themes and user can switch then you need your own "routing code". There is no support for this. Ie you need your own blocks that call out to the relevant blocks depending on the theme.