问:
How to call shell commands from Ruby
How do I call shell commands from inside of a Ruby program? How do I then get output from these commands back into Ruby?</p>

答:
The easiest way is, for example:</p>

```<code>reboot = `init 6`
puts reboot
</code>```

Title: How to call shell commands from Ruby

LastEditorDisplayName: dreftymac

Body:
The easiest way is, for example:

reboot = `init 6`
puts reboot


来源: stackexchange

问:
GLScissors: what is faster/better?
I'm having a small dilemma.

I'm working with Android (not that it is relevant) and I noticed one thing on some phones and not others: the scissor prevents the call glClear(GL_COLOR_BUFFER_BIT) from working correctly.

Therefore I'm wondering if it is better to do:

```<code>gl.glDisable(GL10.GL_SCISSOR_TEST);
gl.glClear(GL10.GL_COLOR_BUFFER_BIT);
gl.glEnable(GL10.GL_SCISSOR_TEST);
</code>```

or

```<code>gl.glScissors(0,0,800,480);
gl.glClear(GL10.GL_COLOR_BUFFER_BIT);
</code>```

Basically, is it better to change to scissors test zone before the clear or is it better to disable/enable?

答:
This is the specification of glScissors, since a glClear is considered in OpenGL as a drawing command. So the behavior you see is perfectly normal (D3D works similarly) but buggy on the other phones where funnily it seems for you to work!

About which solution to choose, I don't know, both are valid. It's a matter of taste I would say. I prefer the first one because it's more easy to figure out what happens.

Now if on your OpenGL implementation the second solution turns out to be faster than the first one, I would picked the second one. Benchmark!

Under the glHood:

Let me share of what I know on desktop GPUs and speculate a bit (don't take it too seriously!). A glClear command actually results in a draw of a full-screen quad, since drawing triangles is the "fast path" on GPUs. This is probably more efficient than DMAs or fixed hardware, since it's parallel (all shader cores clear its portion of the screen, color, z and stencil) and if you do that you can avoid the cost of fixed hardware.

About glScissor, I heard it's implemented via stencil buffering (the same mechanism than usual OpenGL stencil buffer), so only fragments that fall into the scissor zone can participate to depth dest, fragment shading, blending, etc (this is done for same reason than glClear, avoid dedicated hardware). It could be also implemented as a fragment discard+dynamic branching on modern GPUs.

Now you can see why it works that way. Only fragments of the full screen quad that lies within the scissor zone can "shade" the color buffer and clear it!

ContentLicense: CC BY-SA 4.0

Title: GLScissors: what is faster/better?

Body:
I'm having a small dilemma.

I'm working with Android (not that it is relevant) and I noticed one thing on some phones and not others: the scissor prevents the call glClear(GL_COLOR_BUFFER_BIT) from working correctly.

Therefore I'm wondering if it is better to do:

gl.glDisable(GL10.GL_SCISSOR_TEST);
gl.glClear(GL10.GL_COLOR_BUFFER_BIT);
gl.glEnable(GL10.GL_SCISSOR_TEST);

or

gl.glScissors(0,0,800,480);
gl.glClear(GL10.GL_COLOR_BUFFER_BIT);

Basically, is it better to change to scissors test zone before the clear or is it better to disable/enable?

ContentLicense: CC BY-SA 2.5


问:
How to archive an RSS feed?
I need to take a few RSS feeds, and archive all the items that get added to them. I've never consumed or created RSS before, but I know xml, so the format seems pretty intuitive.

I know how to parse the feed: How can I get started making a C# RSS Reader?

I know I can't rely on the feed server to provide a complete history: Is it possible to get RSS archive

I know I'll have to have some custom logic around duplicates: how to check uniqueness (non duplication) of a post in an rss feed

My question is, how can I ensure I don't miss any items? My initial plan is to write a parser, where for each item in the feed:
    1) Check to see if it's already in the archive database
    2) If not, add it to the database
If I schedule this to run once a day, can I be confident I won't be missing any items?

答:
If you're open to relying on a service for this... I built my own RSS archival service (https://app.pub.center). You can access an RSS feed's data via our API.

Page 1 of The Atlantic
https://pub.center/feed/02702624d8a4c825dde21af94e9169773454e0c3/articles?limit=10&page=1

Page 2 of The Atlantic
https://pub.center/feed/02702624d8a4c825dde21af94e9169773454e0c3/articles?limit=10&page=2

The REST API is free. We have pricing plans for push notifications (email, SMS, your custom API endpoint)

ContentLicense: CC BY-SA 3.0

Title: How to archive an RSS feed?


问:
Calculate mean of serial pairs of values by group
Objective: calculate the mean of each pair of values by group in a dataframe

Example data:

```<code>mtcars[1:10, 1:2] %>%
   arrange(cyl)

 mpg cyl
22.8   4
24.4   4
22.8   4
21.0   6
21.0   6
21.4   6
18.1   6
19.2   6
18.7   8
14.3   8
</code>```

Expected Output:

```<code>mpg   cyl   avg
22.8   4     -
24.4   4     23.6
22.8   4     23.6
21.0   6     -
21.0   6     21.0
21.4   6     21.2
18.1   6     19.75
19.2   6     18.65
18.7   8     -
14.3   8     16.5
</code>```

Thought I could use dplyr::lag or dplyr::slice to do this, but haven't got it working.  Not married to dplyr, any solution would be appreciated...

Attempt:

```<code>group_by(mtcars, gear) %>%
   summarise(pairmean=mean(c(mpg, lag(mpg))))
</code>```

答:
Here is a base R method with ave.

```<code># get data
temp <- mtcars[order(mtcars$cyl), c("mpg", "cyl")]

# calculate value pairwise means
temp$avg <- ave(temp$mpg, temp$cyl, FUN=function(i) (i + c(NA, head(i, -1))) / 2)
</code>```

Here, mpg is added to a lagged value and divided by 2. The lagged value is constructed using head with the final element removed (-1) and an NA concatenated to the initial position.

This returns

```<code>head(temp)
                mpg cyl   avg
Datsun 710     22.8   4    NA
Merc 240D      24.4   4 23.60
Merc 230       22.8   4 23.60
Fiat 128       32.4   4 27.60
Honda Civic    30.4   4 31.40
Toyota Corolla 33.9   4 32.15
</code>```

Body:
Objective: calculate the mean of each pair of values by group in a dataframe

Example data:

mtcars[1:10, 1:2] %>%
   arrange(cyl)

 mpg cyl
22.8   4
24.4   4
22.8   4
21.0   6
21.0   6
21.4   6
18.1   6
19.2   6
18.7   8
14.3   8

Expected Output:

mpg   cyl   avg
22.8   4     -
24.4   4     23.6
22.8   4     23.6
21.0   6     -
21.0   6     21.0
21.4   6     21.2
18.1   6     19.75
19.2   6     18.65
18.7   8     -
14.3   8     16.5

Thought I could use dplyr::lag or dplyr::slice to do this, but haven't got it working.  Not married to dplyr, any solution would be appreciated...

Attempt:

group_by(mtcars, gear) %>%
   summarise(pairmean=mean(c(mpg, lag(mpg))))

Body:
Here is a base R method with ave.

# get data
temp <- mtcars[order(mtcars$cyl), c("mpg", "cyl")]

# calculate value pairwise means
temp$avg <- ave(temp$mpg, temp$cyl, FUN=function(i) (i + c(NA, head(i, -1))) / 2)

Here, mpg is added to a lagged value and divided by 2. The lagged value is constructed using head with the final element removed (-1) and an NA concatenated to the initial position.

This returns

head(temp)
                mpg cyl   avg
Datsun 710     22.8   4    NA
Merc 240D      24.4   4 23.60
Merc 230       22.8   4 23.60
Fiat 128       32.4   4 27.60
Honda Civic    30.4   4 31.40
Toyota Corolla 33.9   4 32.15


问:
Is it bad to make a cookie every second or less?
I am currently making a timer in javascript and I want to make sure that if you close the browser that its not just lost...so as my clock is ticking away I am storing a cookie every 100ms.

It's every 100ms as I am using the system time instead of just a system interval so I am basically just calculating the difference in time between the start and now and just want to update that as nicely as possible.

I could reduce it to 500ms I guess but its still basically doing the same thing...

I'm just wondering if storing cookies this way is a bad thing in any way and if it is a bad thing is there a better way to be doing this?

Cheers!

答:
I am not sure what the "big picture" is, but here is my take on it.

If your web page is showing a count-down to a certain event, I would split the responsibility between server side code and client side.

On page-load get data from the server on time-remaining and start the timer. No need to store anything in cookies. On page-load, you can get the data from the server again, so nothing is lost.


问:
Double sum computation in R
I'm having problem writing the following double sum into a function in r:

where the I function is an indicator function and we have n observations x_1...x_n.

I tried something like this

```<code>sum( (x <= t) / (sum((x<=x)))^2)
</code>```

答:
You can do:</p>

```<code>sumiI <- function(xi, x) sum(xi<=x)
sum(1/sapply(x[x<=t], FUN=sumI, x=x))
</code>```

Title: Double sum computation in R

Body:
I'm having problem writing the following double sum into a function in r:

where the I function is an indicator function and we have n observations x_1...x_n.

I tried something like this

sum( (x <= t) / (sum((x<=x)))^2)

Body:
You can do:

sumiI <- function(xi, x) sum(xi<=x)
sum(1/sapply(x[x<=t], FUN=sumI, x=x))


问:
C# Sql Command for Insering into a database
I am new to Visual C# programming language and recently i was trying to make a application that is supposed to insert into a local database of users some data but every times my code runs and the insertion works fine the database does not update.This is the code that i am using

```<code>try
{
    cn.Open();
    SqlCommand insert = new SqlCommand();
    insert.CommandText = "insert into Clienti (Nume,Prenume,Parola,Email) values(@Nume,@Prenume,@Parola,@Email)";
    insert.Connection = cn;
    insert.Parameters.AddWithValue("@Nume", register_nume.Text);
    insert.Parameters.AddWithValue("@Prenume", register_prenume.Text);
    insert.Parameters.AddWithValue("@Parola", register_password.Text);
    insert.Parameters.AddWithValue("@Email", register_email.Text);
    insert.ExecuteNonQuery();
    SqlDataReader reader = insert.ExecuteReader();
    while (reader.Read()) { }

    MessageBox.Show("Added succesfully");
}
catch (Exception ex)
{
    MessageBox.Show(""+ex);
}
</code>```

I already tried the property Copy to output and it doesn't seems to work.
I am sorry for any grammar mistakes that i made,I would be grateful for any help.

答:
Its because you have to now read the database using a select statement, you cant use an INSERT SQL statement to read.

You could add the following immediately after your insert.

```<code>using(var selectCmd = new SqlCommand("SELECT Nume,Prenume,Parola,Email FROM Clienti WHERE Nume = @Nume", cn))
{
    selectCmd.Parameters.AddWithValue("@Nume", register_nume.Text);
    using(SqlDataReader reader = selectCmd.ExecuteReader())
    {
        while (reader.Read()) { }
    }
}
</code>```

That said if you want to know IF the row was inserted or how many records were inserted ExecuteNonQuery returns the number of rows affected. You could change that part of the code like this:

```<code>var recordsAffected = insert.ExecuteNonQuery();

if(recordsAffected > 0)
    MessageBox.Show("Added succesfully");
else
    MessageBox.Show("Nothing happened");
</code>```

Although in this particular case it would not make sense because if nothing was inserted it would probably be caused by an Exception.

Some side notes

Always wrap types that implement IDisposable in using blocks (see code above as example). It ensures that resources are always released as soon as you are done with them even if an Exception is thrown.

Never swallow Exceptions! Either recover from one and log it or do not catch it at all. If you swallow it you will never know if/why your code broke.

Body:
I am new to Visual C# programming language and recently i was trying to make a application that is supposed to insert into a local database of users some data but every times my code runs and the insertion works fine the database does not update.This is the code that i am using

try
{
    cn.Open();
    SqlCommand insert = new SqlCommand();
    insert.CommandText = "insert into Clienti (Nume,Prenume,Parola,Email) values(@Nume,@Prenume,@Parola,@Email)";
    insert.Connection = cn;
    insert.Parameters.AddWithValue("@Nume", register_nume.Text);
    insert.Parameters.AddWithValue("@Prenume", register_prenume.Text);
    insert.Parameters.AddWithValue("@Parola", register_password.Text);
    insert.Parameters.AddWithValue("@Email", register_email.Text);
    insert.ExecuteNonQuery();
    SqlDataReader reader = insert.ExecuteReader();
    while (reader.Read()) { }

    MessageBox.Show("Added succesfully");
}
catch (Exception ex)
{
    MessageBox.Show(""+ex);
}

I already tried the property Copy to output and it doesn't seems to work.
I am sorry for any grammar mistakes that i made,I would be grateful for any help.

Body:
Its because you have to now read the database using a select statement, you cant use an INSERT SQL statement to read.

You could add the following immediately after your insert.

using(var selectCmd = new SqlCommand("SELECT Nume,Prenume,Parola,Email FROM Clienti WHERE Nume = @Nume", cn))
{
    selectCmd.Parameters.AddWithValue("@Nume", register_nume.Text);
    using(SqlDataReader reader = selectCmd.ExecuteReader())
    {
        while (reader.Read()) { }
    }
}

That said if you want to know IF the row was inserted or how many records were inserted ExecuteNonQuery returns the number of rows affected. You could change that part of the code like this:

var recordsAffected = insert.ExecuteNonQuery();

if(recordsAffected > 0)
    MessageBox.Show("Added succesfully");
else
    MessageBox.Show("Nothing happened");

Although in this particular case it would not make sense because if nothing was inserted it would probably be caused by an Exception.

Some side notes

Always wrap types that implement IDisposable in using blocks (see code above as example). It ensures that resources are always released as soon as you are done with them even if an Exception is thrown.

Never swallow Exceptions! Either recover from one and log it or do not catch it at all. If you swallow it you will never know if/why your code broke.


问:
Rhino.Security and IEntityInformationExtractor
I've recently downloaded Rhino.Security and I am trying to implement permissions on a entity.
Since I like Ninject (v2) I would like to put together a simple example to start with.
In my NinjectModule I've bound the repository and the services:

```<code>Bind<ISessionFactory>()
    .ToProvider(new SessionFactoryProvider())
    .InSingletonScope();
Bind<ISession>().ToProvider(new SessionProvider())
    .InSingletonScope();
Bind<IAuthorizationRepository>()
     .To<AuthorizationRepository>()
     .InSingletonScope();
Bind<IPermissionsService>()
    .To<PermissionsService>()
    .InSingletonScope();
Bind<IAuthorizationService>()
    .To<AuthorizationService>()
    .InSingletonScope();
Bind<IPermissionsBuilderService>()
    .To<PermissionsBuilderService>()
    .InSingletonScope();
</code>```

I am testing everything in a console app and everything works fine.
I can run this test with no problem:

```<code>public void RunTest()
{
Model.User user1;
Rhino.Security.Model.UsersGroup grp1;

    using (session)
    {
        session.BeginTransaction();

        user1 = new Model.User { Name = "xxx xxx" };
        session.Save(user1);
        session.Flush();

        grp1 = authorizationRepository.CreateUsersGroup("Administrators");
        session.Flush();

        authorizationRepository.AssociateUserWith(user1, grp1);
        session.Flush();

        var OpAccountEdit = authorizationRepository.CreateOperation("/Account/Edit");
        session.Flush();

        permissionsBuilderService
        .Allow(OpAccountEdit)
        .For(grp1)
        .OnEverything()
        .Level(10)
        .Save();

        permissionsBuilderService
        .Deny(OpAccountEdit)
        .For(user1)
        .OnEverything()
        .Level(10)
        .Save();

        Console.WriteLine(authorizationService.IsAllowed(user1, "/Account/Edit"));

        session.Transaction.Rollback();

        Console.ReadLine();
       }
    }
</code>```

Now, I would like to define a permission for an account; something like this:

```<code>account1 = new Model.Account() { Name = "My Account", SecurityKey = new Guid(), Id = 1 };
session.Save(account1);
session.Flush();

permissionsBuilderService
   .Allow("/Account/Delete")
   .For(user1)
   .On(account1)
   .Level(20)
   .Save();
</code>```

I've defined my class, as Ayende did in the sample code found in the solution:

```<code>public class AccountInfromationExtractor : IEntityInformationExtractor<Model.Account>
{
...
}
</code>```

and I've tried to bind (in my ninject module) the interface IEntityInformationExtractor to the class

```<code> Bind<IEntityInformationExtractor<Model.Account>>()
   .To<AccountInfromationExtractor>();
</code>```

but when I run my app I get an "Object reference not set to an instance of an object." in the Security class.
The service locator cannot resolve the instance and it generates and exception right here:

```<code>var extractor = ServiceLocator.Current.GetInstance<IEntityInformationExtractor<TEntity>>();
</code>```

Is there anyone who tried to use Ninject with Rhino.Security and would be able to help me?

Thanks

答:
At the end I couldn't manage to make it work with Ninject so I switched to StructureMap.

Rhino.Security works with MS ServiceLocator to resolve IEntityInformationExtractor.
I've found a ServiceLocator adapter for StructureMap

So I've referenced in my project the following assemblies:

Microsoft.Practices.ServiceLocation

StructureMap

StructureMapAdapter

changed my code to use StructureMap:

```<code>public static class Bootstrapper
    {
        public static void Initialize()
        {
            ObjectFactory.Initialize(cfg =>
            {
                cfg.AddRegistry<StructureMapRegistry>();
            });
            ServiceLocator.SetLocatorProvider(() => new StructureMapServiceLocator(ObjectFactory.Container));
        }
    }
</code>```

and my StructureMapRegistry class:

```<code>public class StructureMapRegistry : Registry
{
    public StructureMapRegistry()
    {
        string ConnDb = "Data Source=(local); Initial Catalog=RhinoSecurity_Test; Trusted_Connection=true;";

        For<ISessionFactory>()
            .Singleton()
            .TheDefault.Is.ConstructedBy(() => new NHSessionFactory(ConnDb, false).SessionFactory);
        For<ISession>()
            .Singleton()
            .TheDefault.Is.ConstructedBy(x => x.GetInstance<ISessionFactory>().OpenSession());
        For<IAuthorizationRepository>()
             .Use<AuthorizationRepository>();
        For<IPermissionsService>()
            .Use<PermissionsService>();
        For<IAuthorizationService>()
            .Use<AuthorizationService>();
        For<IPermissionsBuilderService>()
            .Use<PermissionsBuilderService>();
        For<IEntityInformationExtractor<Model.Account>>()
            .Use(p =>
                {
                return (new AccountInfromationExtractor(p.GetInstance<ISession>()));
                });
    }
}
</code>```

I hope this might help someone.

Body:
I've recently downloaded Rhino.Security and I am trying to implement permissions on a entity.
Since I like Ninject (v2) I would like to put together a simple example to start with.
In my NinjectModule I've bound the repository and the services:

Bind<ISessionFactory>()
    .ToProvider(new SessionFactoryProvider())
    .InSingletonScope();
Bind<ISession>().ToProvider(new SessionProvider())
    .InSingletonScope();
Bind<IAuthorizationRepository>()
     .To<AuthorizationRepository>()
     .InSingletonScope();
Bind<IPermissionsService>()
    .To<PermissionsService>()
    .InSingletonScope();
Bind<IAuthorizationService>()
    .To<AuthorizationService>()
    .InSingletonScope();
Bind<IPermissionsBuilderService>()
    .To<PermissionsBuilderService>()
    .InSingletonScope();

I am testing everything in a console app and everything works fine.
I can run this test with no problem:

public void RunTest()
{
Model.User user1;
Rhino.Security.Model.UsersGroup grp1;

    using (session)
    {
        session.BeginTransaction();

        user1 = new Model.User { Name = "xxx xxx" };
        session.Save(user1);
        session.Flush();

        grp1 = authorizationRepository.CreateUsersGroup("Administrators");
        session.Flush();

        authorizationRepository.AssociateUserWith(user1, grp1);
        session.Flush();

        var OpAccountEdit = authorizationRepository.CreateOperation("/Account/Edit");
        session.Flush();

        permissionsBuilderService
        .Allow(OpAccountEdit)
        .For(grp1)
        .OnEverything()
        .Level(10)
        .Save();

        permissionsBuilderService
        .Deny(OpAccountEdit)
        .For(user1)
        .OnEverything()
        .Level(10)
        .Save();

        Console.WriteLine(authorizationService.IsAllowed(user1, "/Account/Edit"));

        session.Transaction.Rollback();

        Console.ReadLine();
       }
    }

Now, I would like to define a permission for an account; something like this:

account1 = new Model.Account() { Name = "My Account", SecurityKey = new Guid(), Id = 1 };
session.Save(account1);
session.Flush();

permissionsBuilderService
   .Allow("/Account/Delete")
   .For(user1)
   .On(account1)
   .Level(20)
   .Save();

I've defined my class, as Ayende did in the sample code found in the solution:

public class AccountInfromationExtractor : IEntityInformationExtractor<Model.Account>
{
...
}

and I've tried to bind (in my ninject module) the interface IEntityInformationExtractor to the class

 Bind<IEntityInformationExtractor<Model.Account>>()
   .To<AccountInfromationExtractor>();

but when I run my app I get an "Object reference not set to an instance of an object." in the Security class.
The service locator cannot resolve the instance and it generates and exception right here:

var extractor = ServiceLocator.Current.GetInstance<IEntityInformationExtractor<TEntity>>();

Is there anyone who tried to use Ninject with Rhino.Security and would be able to help me?

Thanks

Body:
At the end I couldn't manage to make it work with Ninject so I switched to StructureMap.

Rhino.Security works with MS ServiceLocator to resolve IEntityInformationExtractor.
I've found a ServiceLocator adapter for StructureMap

So I've referenced in my project the following assemblies:

Microsoft.Practices.ServiceLocation

StructureMap

StructureMapAdapter

changed my code to use StructureMap:

public static class Bootstrapper
    {
        public static void Initialize()
        {
            ObjectFactory.Initialize(cfg =>
            {
                cfg.AddRegistry<StructureMapRegistry>();
            });
            ServiceLocator.SetLocatorProvider(() => new StructureMapServiceLocator(ObjectFactory.Container));
        }
    }

and my StructureMapRegistry class:

public class StructureMapRegistry : Registry
{
    public StructureMapRegistry()
    {
        string ConnDb = "Data Source=(local); Initial Catalog=RhinoSecurity_Test; Trusted_Connection=true;";

        For<ISessionFactory>()
            .Singleton()
            .TheDefault.Is.ConstructedBy(() => new NHSessionFactory(ConnDb, false).SessionFactory);
        For<ISession>()
            .Singleton()
            .TheDefault.Is.ConstructedBy(x => x.GetInstance<ISessionFactory>().OpenSession());
        For<IAuthorizationRepository>()
             .Use<AuthorizationRepository>();
        For<IPermissionsService>()
            .Use<PermissionsService>();
        For<IAuthorizationService>()
            .Use<AuthorizationService>();
        For<IPermissionsBuilderService>()
            .Use<PermissionsBuilderService>();
        For<IEntityInformationExtractor<Model.Account>>()
            .Use(p =>
                {
                return (new AccountInfromationExtractor(p.GetInstance<ISession>()));
                });
    }
}

I hope this might help someone.


问:
call popupwindow from recyclerview
I am trying to call pop up window from my recyclerView adapter, I am getting a android.view.WindowManager$BadTokenException: Unable to add window -- token null is not valid; is your activity running?

here is the code which creates the popupwindow.

```<code> private void initiatePopupWindow() {
        try {
        final View popupView =

LayoutInflater.from(context).inflate(R.layout.times_popup, null);
        final PopupWindow pwindo = new PopupWindow(popupView, WindowManager.LayoutParams.MATCH_PARENT, WindowManager.LayoutParams.MATCH_PARENT);
        popupView.post(new Runnable() {
            public void run() {
                pwindo.showAtLocation(popupView, Gravity.CENTER, 0, 0);
            }
        });

        btnClosePopup = (Button) popupView.findViewById(R.id.btn_close_popup);
        btnClosePopup.setOnClickListener(cancel_button_click_listener);

    } catch (Exception e) {
        e.printStackTrace();
    }
}
private View.OnClickListener cancel_button_click_listener = new View.OnClickListener() {
    public void onClick(View v) {
        pwindo.dismiss();

    }
};
</code>```

and here is my RecyclerView class

public class DetailsAdapter extends RecyclerView.Adapter {

```<code>private List<Restaurant> restaurant;
private List<Time> times;
private int rowLayout;
private Context context;
private PopupWindow pwindo;
private Button btnClosePopup;
private CoordinatorLayout rootLayout;
private LinearLayout root;

public class DetailViewholder extends RecyclerView.ViewHolder{
    LinearLayout restaurantLayout;
   // TextView RestaurantTitle;
    TextView address1;
    TextView phone;
    TextView price;
    TextView menu_type;
    TextView rate;
    TextView open;
    RatingBar ratingBar;
    ImageView check;
    TextView offer;
    ImageButton info;

    public DetailViewholder(View v) {
        super(v);

        restaurantLayout = (LinearLayout) v.findViewById(R.id.general_information);
        ratingBar = (RatingBar) v.findViewById(R.id.ratingBar);
        check = (ImageView) v.findViewById(R.id.tick);
        info = (ImageButton) v.findViewById(R.id.info);
        address1 = (TextView) v.findViewById(R.id.address);
        phone = (TextView) v.findViewById(R.id.phone);
        price = (TextView) v.findViewById(R.id.price);
        menu_type = (TextView) v.findViewById(R.id.menu_type);
        rate = (TextView) v.findViewById(R.id.rate);
        open = (TextView) v.findViewById(R.id.hours);
        offer = (TextView) v.findViewById(R.id.offer);
        root =(LinearLayout) v.findViewById(R.id.linear);
        rootLayout = (CoordinatorLayout) v.findViewById(R.id.coordinatorLayout);
        info.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
               //onclick listener for the popup window
                initiatePopupWindow();
            }
        });
    }

    public void callplace(View view){
        String val = phone.getText().toString();
        Intent intent = new Intent(Intent.ACTION_DIAL);
        intent.setData(Uri.parse("tel:"+val));
        context.startActivity(intent);
        Log.v("Calling", "Calling..."+val);
    }

}

public DetailsAdapter(List<Restaurant> restaurant,List<Time> times,int rowLayout,Context context) {
    this.restaurant = restaurant;
    this.times=times;
    this.rowLayout = rowLayout;
    this.context = context;
}

@Override
public DetailsAdapter.DetailViewholder onCreateViewHolder(ViewGroup parent,int viewType) {
    View view = LayoutInflater.from(parent.getContext()).inflate(rowLayout, parent, false);
    return new DetailViewholder(view);

}

@Override
public void onBindViewHolder(DetailViewholder holder, final int position) {
    String Sadd = context.getResources().getString(R.string.addr);
    String Smen = context.getResources().getString(R.string.menu);
    String Spho = context.getResources().getString(R.string.phone);
    String Srat = context.getResources().getString(R.string.rate);
    String Scos = context.getResources().getString(R.string.cost);
    String Shou = context.getResources().getString(R.string.hours);
    String Stil = context.getResources().getString(R.string.till);
    String Soff = context.getResources().getString(R.string.offer);

    SimpleDateFormat dateFormat = new SimpleDateFormat("HH:mm");
    try {
        Date StartTime = dateFormat.parse(times.get(position).getStartTime());
        Date FinishTime = dateFormat.parse(times.get(position).getFinishTime());
        Date CurrentTime = dateFormat.parse(dateFormat.format(new Date()));
        if (CurrentTime.after(FinishTime) || CurrentTime.before(StartTime))
        {
            Log.d(TAG,"Restaurant is currently closed");
            holder.check.setImageResource(R.drawable.ic_check_circle_red_500_18dp);
            holder.check.setVisibility(View.VISIBLE);

        }
        else
        {
            Log.d(TAG,"Its open! yey!");
            holder.check.setVisibility(View.VISIBLE);
            holder.check.setImageResource(R.drawable.ic_check_circle_teal_600_18dp);

        }
    } catch (ParseException e)
    {
        e.printStackTrace();
    }

    holder.ratingBar.setRating(1);
    holder.address1.setText(Sadd+restaurant.get(position).getAddress1().substring(0,20));
    holder.menu_type.setText(Smen+restaurant.get(position).getMenuType());
    holder.phone.setText(Spho+restaurant.get(position).getPhone());
    holder.rate.setText(Srat+restaurant.get(position).getRate());
    holder.price.setText(Scos+restaurant.get(position).getCost() +"€");
    holder.open.setText(Shou + times.get(position).getStartTime().substring(0,5)
            + Stil +times.get(position).getFinishTime().substring(0,5));
    holder.offer.setText(Soff+restaurant.get(position).getOffer());
    Picasso.with(context).load(R.drawable.ic_info_blue_900_18dp)
            .fit()
            .into(holder.info);

}
@Override
public int getItemCount() {
    return restaurant.size();
}
</code>```

答:
I have Fixed the issue by referring the inflator to my parent.getContext() instead of the "context" variable,</p>

```<code> LayoutInflater inflater = (LayoutInflater)parent.getContext()
                .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
</code>```

Title: call popupwindow from recyclerview

Body:
I am trying to call pop up window from my recyclerView adapter, I am getting a android.view.WindowManager$BadTokenException: Unable to add window -- token null is not valid; is your activity running?

here is the code which creates the popupwindow.

 private void initiatePopupWindow() {
        try {
        final View popupView =

LayoutInflater.from(context).inflate(R.layout.times_popup, null);
        final PopupWindow pwindo = new PopupWindow(popupView, WindowManager.LayoutParams.MATCH_PARENT, WindowManager.LayoutParams.MATCH_PARENT);
        popupView.post(new Runnable() {
            public void run() {
                pwindo.showAtLocation(popupView, Gravity.CENTER, 0, 0);
            }
        });

        btnClosePopup = (Button) popupView.findViewById(R.id.btn_close_popup);
        btnClosePopup.setOnClickListener(cancel_button_click_listener);

    } catch (Exception e) {
        e.printStackTrace();
    }
}
private View.OnClickListener cancel_button_click_listener = new View.OnClickListener() {
    public void onClick(View v) {
        pwindo.dismiss();

    }
};

and here is my RecyclerView class

public class DetailsAdapter extends RecyclerView.Adapter {

private List<Restaurant> restaurant;
private List<Time> times;
private int rowLayout;
private Context context;
private PopupWindow pwindo;
private Button btnClosePopup;
private CoordinatorLayout rootLayout;
private LinearLayout root;

public class DetailViewholder extends RecyclerView.ViewHolder{
    LinearLayout restaurantLayout;
   // TextView RestaurantTitle;
    TextView address1;
    TextView phone;
    TextView price;
    TextView menu_type;
    TextView rate;
    TextView open;
    RatingBar ratingBar;
    ImageView check;
    TextView offer;
    ImageButton info;

    public DetailViewholder(View v) {
        super(v);

        restaurantLayout = (LinearLayout) v.findViewById(R.id.general_information);
        ratingBar = (RatingBar) v.findViewById(R.id.ratingBar);
        check = (ImageView) v.findViewById(R.id.tick);
        info = (ImageButton) v.findViewById(R.id.info);
        address1 = (TextView) v.findViewById(R.id.address);
        phone = (TextView) v.findViewById(R.id.phone);
        price = (TextView) v.findViewById(R.id.price);
        menu_type = (TextView) v.findViewById(R.id.menu_type);
        rate = (TextView) v.findViewById(R.id.rate);
        open = (TextView) v.findViewById(R.id.hours);
        offer = (TextView) v.findViewById(R.id.offer);
        root =(LinearLayout) v.findViewById(R.id.linear);
        rootLayout = (CoordinatorLayout) v.findViewById(R.id.coordinatorLayout);
        info.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
               //onclick listener for the popup window
                initiatePopupWindow();
            }
        });
    }

    public void callplace(View view){
        String val = phone.getText().toString();
        Intent intent = new Intent(Intent.ACTION_DIAL);
        intent.setData(Uri.parse("tel:"+val));
        context.startActivity(intent);
        Log.v("Calling", "Calling..."+val);
    }

}

public DetailsAdapter(List<Restaurant> restaurant,List<Time> times,int rowLayout,Context context) {
    this.restaurant = restaurant;
    this.times=times;
    this.rowLayout = rowLayout;
    this.context = context;
}

@Override
public DetailsAdapter.DetailViewholder onCreateViewHolder(ViewGroup parent,int viewType) {
    View view = LayoutInflater.from(parent.getContext()).inflate(rowLayout, parent, false);
    return new DetailViewholder(view);

}

@Override
public void onBindViewHolder(DetailViewholder holder, final int position) {
    String Sadd = context.getResources().getString(R.string.addr);
    String Smen = context.getResources().getString(R.string.menu);
    String Spho = context.getResources().getString(R.string.phone);
    String Srat = context.getResources().getString(R.string.rate);
    String Scos = context.getResources().getString(R.string.cost);
    String Shou = context.getResources().getString(R.string.hours);
    String Stil = context.getResources().getString(R.string.till);
    String Soff = context.getResources().getString(R.string.offer);

    SimpleDateFormat dateFormat = new SimpleDateFormat("HH:mm");
    try {
        Date StartTime = dateFormat.parse(times.get(position).getStartTime());
        Date FinishTime = dateFormat.parse(times.get(position).getFinishTime());
        Date CurrentTime = dateFormat.parse(dateFormat.format(new Date()));
        if (CurrentTime.after(FinishTime) || CurrentTime.before(StartTime))
        {
            Log.d(TAG,"Restaurant is currently closed");
            holder.check.setImageResource(R.drawable.ic_check_circle_red_500_18dp);
            holder.check.setVisibility(View.VISIBLE);

        }
        else
        {
            Log.d(TAG,"Its open! yey!");
            holder.check.setVisibility(View.VISIBLE);
            holder.check.setImageResource(R.drawable.ic_check_circle_teal_600_18dp);

        }
    } catch (ParseException e)
    {
        e.printStackTrace();
    }

    holder.ratingBar.setRating(1);
    holder.address1.setText(Sadd+restaurant.get(position).getAddress1().substring(0,20));
    holder.menu_type.setText(Smen+restaurant.get(position).getMenuType());
    holder.phone.setText(Spho+restaurant.get(position).getPhone());
    holder.rate.setText(Srat+restaurant.get(position).getRate());
    holder.price.setText(Scos+restaurant.get(position).getCost() +"€");
    holder.open.setText(Shou + times.get(position).getStartTime().substring(0,5)
            + Stil +times.get(position).getFinishTime().substring(0,5));
    holder.offer.setText(Soff+restaurant.get(position).getOffer());
    Picasso.with(context).load(R.drawable.ic_info_blue_900_18dp)
            .fit()
            .into(holder.info);

}
@Override
public int getItemCount() {
    return restaurant.size();
}

Body:
I have Fixed the issue by referring the inflator to my parent.getContext() instead of the "context" variable,

 LayoutInflater inflater = (LayoutInflater)parent.getContext()
                .getSystemService(Context.LAYOUT_INFLATER_SERVICE);


问:
Merging two json (deep nested)
I tried to merge two json both with $.extend and $.merge but no success. I also tried to attach it like this:

```<code>data: JSON.stringify({"data" : [
    {term: request.term},
    jsontag
]}),
</code>```

Here's my setup:

```<code>autocomplete: ({
    source: function (request, response) {
        var tags = $('#input-newsearch-2').val();
        var jsonfied = {
            tags: tags.replace(/,$/, "").split(",").map(function (tag) {
                return { tag: tag };
            })
        };
        var jsontag = JSON.stringify(jsonfied);
        var jsonterm = JSON.stringify({ term: request.term });
    //console.log(jsontag);
    //console.log(jsonterm);
    //var mergedObj = $.extend(jsontag, jsonterm);
    //console.log(mergedObj);
    $.ajax({
        url: "/source",
        type: "POST",
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        data: [jsontag, jsonterm],
        success: function (data) {
            response(data);
        }
    });
},
});
</code>```

Console:

```<code>{"tags":[{"tag":"value01"},{"tag":"value02"},{"tag":"value03"}]}
{"term":"value04"}
</code>```

I was hoping to get sth like:

```<code>[{"term":"value04"},{"tags":[{"tag":"value01"},{"tag":"value02"},{"tag":"value03"}]}]
</code>```

Or even better:

```<code>{"data":[{"term":"value04"},{"tags":[{"tag":"value01"},{"tag":"value02"},{"tag":"value03"}]}]}
</code>```

答:
So what seems to work is if I first merge the arrays and then JSON.stringify() it ... like ..

```<code>        var jsontag = { data };

        var jsonterm = {};
        jsonterm['terms'] = { term: request.term };

        console.log(jsontag);
        console.log(jsonterm);
        var mergedJSON = JSON.stringify($.extend(true, jsontag, jsonterm));
        console.log(mergedJSON);
</code>```

JSON result:

```<code>{"data":{"tags":[{"tag":"value04"},{"tag":"value03"},{"tag":"value02"}]},"terms":{"term":"value01"}}
</code>```

Title: Merging two json (deep nested)

Body:
I tried to merge two json both with $.extend and $.merge but no success. I also tried to attach it like this:

data: JSON.stringify({"data" : [
    {term: request.term},
    jsontag
]}),

Here's my setup:

autocomplete: ({
    source: function (request, response) {
        var tags = $('#input-newsearch-2').val();
        var jsonfied = {
            tags: tags.replace(/,$/, "").split(",").map(function (tag) {
                return { tag: tag };
            })
        };
        var jsontag = JSON.stringify(jsonfied);
        var jsonterm = JSON.stringify({ term: request.term });
    //console.log(jsontag);
    //console.log(jsonterm);
    //var mergedObj = $.extend(jsontag, jsonterm);
    //console.log(mergedObj);
    $.ajax({
        url: "/source",
        type: "POST",
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        data: [jsontag, jsonterm],
        success: function (data) {
            response(data);
        }
    });
},
});

Console:

{"tags":[{"tag":"value01"},{"tag":"value02"},{"tag":"value03"}]}
{"term":"value04"}

I was hoping to get sth like:

[{"term":"value04"},{"tags":[{"tag":"value01"},{"tag":"value02"},{"tag":"value03"}]}]

Or even better:

{"data":[{"term":"value04"},{"tags":[{"tag":"value01"},{"tag":"value02"},{"tag":"value03"}]}]}

Body:
So what seems to work is if I first merge the arrays and then JSON.stringify() it ... like ..

        var jsontag = { data };

        var jsonterm = {};
        jsonterm['terms'] = { term: request.term };

        console.log(jsontag);
        console.log(jsonterm);
        var mergedJSON = JSON.stringify($.extend(true, jsontag, jsonterm));
        console.log(mergedJSON);

JSON result:

{"data":{"tags":[{"tag":"value04"},{"tag":"value03"},{"tag":"value02"}]},"terms":{"term":"value01"}}


问:
Initializing the applicationhost.config file failed. Cannot find IIS Express
I recently installed the Visual Studio 2017 RC and created AngularJS SPA application. I had to uninstall the VS 2017 RC as it was hanging multiple times. Now, Whenever I try to open this SPA application using VS 2015 I get this error. Any help to resolve this would be helpful. Thank you.

Initializing the applicationhost.config file failed. Cannot find IIS
  Express

答:
Follow this link :

https://drive.google.com/open?id=0B9Q8e7mRZ7_oaXRHX01yMUNPbUE

You need to modify the visual studio web services. The video shows how to modify VS. Modification depends on which type of template you are using that shows error.
If its WCF, then you make web service updates during modification of VS.


问:
Angular2 CLI error "@angular/compiler-cli" package was not properly installed
I'm working an Angular 2 project. Now trying to install Angular CLI within the current project with the following

```<code>npm install --save-dev @angular/cli@latest
npm install
</code>```

Problem is when running ng serve I receive error

```<code>The "@angular/compiler-cli" package was not properly installed.
Error: The "@angular/compiler-cli" package was not properly installed.
    at Object.<anonymous> (/myng2project/node_modules/@ngtools/webpack/src/index.js:14:11)
    at Module._compile (module.js:570:32)
    at Object.Module._extensions..js (module.js:579:10)
    at Module.load (module.js:487:32)
    at tryModuleLoad (module.js:446:12)
    at Function.Module._load (module.js:438:3)
    at Module.require (module.js:497:17)
    at require (internal/module.js:20:19)
    at Object.<anonymous> (/myng2project/node_modules/@angular/cli/tasks/eject.js:10:19)
    at Module._compile (module.js:570:32)
    at Object.Module._extensions..js (module.js:579:10)
    at Module.load (module.js:487:32)
    at tryModuleLoad (module.js:446:12)
    at Function.Module._load (module.js:438:3)
    at Module.require (module.js:497:17)
    at require (internal/module.js:20:19)
</code>```

答:
This absolutely sucked to work through. In order for me to fix it I had to do a few things...

To get around the @angular/compiler-cli was not installed correctly error, I had to take @Ruzenhack's solution, which was to remove both the global and local @angular/cli packages:

```<code>rm -rf node_modules dist
npm uninstall -g @angular/cli
npm cache clean
</code>```

But taking his advice further to install @angular/cli@latest left me with the same problem, which led me to @SergeyV's suggestion that I downgrade to an older version of the cli. Personally, I had another project that was working with @angular/cli@1.0.0-rc.1 so I decided to use that and install it globally as well as in my package.json.

Success.

BUT...

I was then given another error....
Cannot read property 'Private' of undefined

Dammit.

So I took this suggestion from the angular-cli github issues, which was to upgrade my typescript. So, throwing my typescript version to ^2.0.0 in package.json, I was greeted with the familiar and frustration-free green ng serve output. Finally.

I hope this helps someone out.

Body:
I'm working an Angular 2 project. Now trying to install Angular CLI within the current project with the following

npm install --save-dev @angular/cli@latest
npm install

Problem is when running ng serve I receive error

The "@angular/compiler-cli" package was not properly installed.
Error: The "@angular/compiler-cli" package was not properly installed.
    at Object.<anonymous> (/myng2project/node_modules/@ngtools/webpack/src/index.js:14:11)
    at Module._compile (module.js:570:32)
    at Object.Module._extensions..js (module.js:579:10)
    at Module.load (module.js:487:32)
    at tryModuleLoad (module.js:446:12)
    at Function.Module._load (module.js:438:3)
    at Module.require (module.js:497:17)
    at require (internal/module.js:20:19)
    at Object.<anonymous> (/myng2project/node_modules/@angular/cli/tasks/eject.js:10:19)
    at Module._compile (module.js:570:32)
    at Object.Module._extensions..js (module.js:579:10)
    at Module.load (module.js:487:32)
    at tryModuleLoad (module.js:446:12)
    at Function.Module._load (module.js:438:3)
    at Module.require (module.js:497:17)
    at require (internal/module.js:20:19)

Body:
This absolutely sucked to work through. In order for me to fix it I had to do a few things...

To get around the @angular/compiler-cli was not installed correctly error, I had to take @Ruzenhack's solution, which was to remove both the global and local @angular/cli packages:

rm -rf node_modules dist
npm uninstall -g @angular/cli
npm cache clean

But taking his advice further to install @angular/cli@latest left me with the same problem, which led me to @SergeyV's suggestion that I downgrade to an older version of the cli. Personally, I had another project that was working with @angular/cli@1.0.0-rc.1 so I decided to use that and install it globally as well as in my package.json.

Success.

BUT...

I was then given another error....
Cannot read property 'Private' of undefined

Dammit.

So I took this suggestion from the angular-cli github issues, which was to upgrade my typescript. So, throwing my typescript version to ^2.0.0 in package.json, I was greeted with the familiar and frustration-free green ng serve output. Finally.

I hope this helps someone out.


问:
Oracle: Need help on a parent-child scenario
Need help on the below scenario.

Table Structure:

ACCT_XREF

```<code>CREATE TABLE ACCT_XREF
(
 ACCT_NO VARCHAR2(10),
 PRNT_ACCT_NO VARCHAR2(10),
 PRTY_ROWID VARCHAR2(10),
 ACCT_ROWID VARCHAR2(10)
);
</code>```

INPUT_ACCTROWID

```<code>CREATE TABLE INPUT_ACCTROWID
(
 ACCT_ROWID VARCHAR2(10)
);
</code>```

Sample Data:

```<code>INSERT INTO ACCT_XREF VALUES('1000',NULL,'100','1');
INSERT INTO ACCT_XREF VALUES('1001','1003','NULL','2');
INSERT INTO ACCT_XREF VALUES('1003',NULL,'102','3');

INSERT INTO INPUT_ACCTROWID VALUES('1');
INSERT INTO INPUT_ACCTROWID VALUES('2');
</code>```

ACCT_XREF

i/p data:

```<code>ACCT_NO    PRNT_ACCT_NO    PRTY_ROWID      ACCT_ROWID
-----------------------------------------------------
1000       NULL            100             1
1001       1003            NULL            2
1003       NULL            102             3
</code>```

INPUT_ACCTROWID

```<code> ACCT_ROWID
 ----------
 1
 2
</code>```

EXPECTED OUTPUT

```<code>ACCT_NO   PRTY_ROWID
--------------------
1000      100
1001      102
</code>```

The issue here is:

ACCT_XREF is hierarchy based,

So, When PRNT_ACCT_NO is NOT NULL,PRTY_ROWID will be NULL,

In such cases, Pick the PRNT_ACCT_NO and    query the same table with
ACCT_NO as a match conditon and fetch the    Party linked to that
account i.e PRTY_ROWID

I have made an effort to achieve the same and below is my query:

```<code>SELECT ALL_INP.ACCT_NO,COALESCE(ALL_INP.PRTY_ROWID,C.PRTY_ROWID)
FROM
(
 SELECT A.*
 FROM
 ACCT_XREF A
 JOIN
 INPUT_ACCTROWID B
 ON A.ACCT_ROWID=B.ACCT_ROWID
)ALL_INP
LEFT OUTER JOIN
ACCT_XREF C
ON ALL_INP.PRNT_ACCT_NO=C.ACCT_NO;
</code>```

Not sure this is the best way, So wanted to know if there are better options.Thanks in Advance.

答:
I see what you mean. You have recursive table which has primarily 2 types of data components. Either they are PARENT type (where PRNT_ACCT_NO is NULL) or CHILD type (where PRNT_ACCT_NO is NOT NULL). And if the CHILD is requested then it should navigate to parent first before fetching the data as output

Here is how to breakdown such a problem

Find out Father nodes and get the required data for CHILD nodes only

Find out Father nodes and get the required data for CHILD nodes only

Get node data for SOLO nodes (who are already PARENTS - no child)

Merge these 2 data sets

Bump it with final driving table INPUT_ACCTROWID for fetching required selective data only.

```<code> SELECT XREF.ACCT_NO, XREF.PRTY_ROWID
    FROM    (SELECT CHILD.ACCT_NO AS ACCT_NO,
                    FATHER.PRTY_ROWID AS PRTY_ROWID,
                    CHILD.ACCT_ROWID AS ACCT_ROWID
               FROM    ACCT_XREF FATHER
                    JOIN
                       ACCT_XREF CHILD
                    ON FATHER.ACCT_NO = CHILD.PRNT_ACCT_NO
              WHERE CHILD.PRNT_ACCT_NO IS NOT NULL --**CHILD NODES ONLY**
             UNION ALL
             SELECT SOLO.ACCT_NO AS ACCT_NO,
                    SOLO.PRTY_ROWID AS PRTY_ROWID,
                    SOLO.ACCT_ROWID AS ACCT_ROWID
               FROM ACCT_XREF SOLO
              WHERE SOLO.PRNT_ACCT_NO IS NULL --**PARENT/SOLO NODES ONLY**
            ) XREF
         JOIN
            INPUT_ACCTROWID INPUT1 --**DRIVING TABLE JOIN**
         ON XREF.ACCT_ROWID = INPUT1.ACCT_ROWID
ORDER BY 1 ASC
</code>```

Here is the output

```<code>    ACCT_NO    PRTY_ROWID
    1000       100
    1001       102
</code>```

Here is an explain plan for easier understanding of execution plan:

```<code>SELECT STATEMENT  ALL_ROWSCost: 74  Bytes: 84  Cardinality: 3
    9 SORT ORDER BY  Cost: 74  Bytes: 84  Cardinality: 3
        8 HASH JOIN  Cost: 73  Bytes: 84  Cardinality: 3
            1 TABLE ACCESS FULL TABLE CONTACTDBA.INPUT_ACCTROWID Cost: 18  Bytes: 14  Cardinality: 2
            7 VIEW CONTACTDBA. Cost: 55  Bytes: 63  Cardinality: 3
                6 UNION-ALL
                    4 HASH JOIN  Cost: 37  Bytes: 35  Cardinality: 1
                        2 TABLE ACCESS FULL TABLE CONTACTDBA.ACCT_XREF Cost: 18  Bytes: 21  Cardinality: 1
                        3 TABLE ACCESS FULL TABLE CONTACTDBA.ACCT_XREF Cost: 18  Bytes: 42  Cardinality: 3
                    5 TABLE ACCESS FULL TABLE CONTACTDBA.ACCT_XREF Cost: 18  Bytes: 56  Cardinality: 2
</code>```

I hope this helps.

Body:
Need help on the below scenario.

Table Structure:

ACCT_XREF

CREATE TABLE ACCT_XREF
(
 ACCT_NO VARCHAR2(10),
 PRNT_ACCT_NO VARCHAR2(10),
 PRTY_ROWID VARCHAR2(10),
 ACCT_ROWID VARCHAR2(10)
);

INPUT_ACCTROWID

CREATE TABLE INPUT_ACCTROWID
(
 ACCT_ROWID VARCHAR2(10)
);

Sample Data:

INSERT INTO ACCT_XREF VALUES('1000',NULL,'100','1');
INSERT INTO ACCT_XREF VALUES('1001','1003','NULL','2');
INSERT INTO ACCT_XREF VALUES('1003',NULL,'102','3');

INSERT INTO INPUT_ACCTROWID VALUES('1');
INSERT INTO INPUT_ACCTROWID VALUES('2');

ACCT_XREF

i/p data:

ACCT_NO    PRNT_ACCT_NO    PRTY_ROWID      ACCT_ROWID
-----------------------------------------------------
1000       NULL            100             1
1001       1003            NULL            2
1003       NULL            102             3

INPUT_ACCTROWID

 ACCT_ROWID
 ----------
 1
 2

EXPECTED OUTPUT

ACCT_NO   PRTY_ROWID
--------------------
1000      100
1001      102

The issue here is:

ACCT_XREF is hierarchy based,

So, When PRNT_ACCT_NO is NOT NULL,PRTY_ROWID will be NULL,

In such cases, Pick the PRNT_ACCT_NO and    query the same table with
ACCT_NO as a match conditon and fetch the    Party linked to that
account i.e PRTY_ROWID

I have made an effort to achieve the same and below is my query:

SELECT ALL_INP.ACCT_NO,COALESCE(ALL_INP.PRTY_ROWID,C.PRTY_ROWID)
FROM
(
 SELECT A.*
 FROM
 ACCT_XREF A
 JOIN
 INPUT_ACCTROWID B
 ON A.ACCT_ROWID=B.ACCT_ROWID
)ALL_INP
LEFT OUTER JOIN
ACCT_XREF C
ON ALL_INP.PRNT_ACCT_NO=C.ACCT_NO;

Not sure this is the best way, So wanted to know if there are better options.Thanks in Advance.

Body:
I see what you mean. You have recursive table which has primarily 2 types of data components. Either they are PARENT type (where PRNT_ACCT_NO is NULL) or CHILD type (where PRNT_ACCT_NO is NOT NULL). And if the CHILD is requested then it should navigate to parent first before fetching the data as output

Here is how to breakdown such a problem

Find out Father nodes and get the required data for CHILD nodes only

Find out Father nodes and get the required data for CHILD nodes only

Get node data for SOLO nodes (who are already PARENTS - no child)

Merge these 2 data sets

Bump it with final driving table INPUT_ACCTROWID for fetching required selective data only.

 SELECT XREF.ACCT_NO, XREF.PRTY_ROWID
    FROM    (SELECT CHILD.ACCT_NO AS ACCT_NO,
                    FATHER.PRTY_ROWID AS PRTY_ROWID,
                    CHILD.ACCT_ROWID AS ACCT_ROWID
               FROM    ACCT_XREF FATHER
                    JOIN
                       ACCT_XREF CHILD
                    ON FATHER.ACCT_NO = CHILD.PRNT_ACCT_NO
              WHERE CHILD.PRNT_ACCT_NO IS NOT NULL --**CHILD NODES ONLY**
             UNION ALL
             SELECT SOLO.ACCT_NO AS ACCT_NO,
                    SOLO.PRTY_ROWID AS PRTY_ROWID,
                    SOLO.ACCT_ROWID AS ACCT_ROWID
               FROM ACCT_XREF SOLO
              WHERE SOLO.PRNT_ACCT_NO IS NULL --**PARENT/SOLO NODES ONLY**
            ) XREF
         JOIN
            INPUT_ACCTROWID INPUT1 --**DRIVING TABLE JOIN**
         ON XREF.ACCT_ROWID = INPUT1.ACCT_ROWID
ORDER BY 1 ASC

Here is the output

    ACCT_NO    PRTY_ROWID
    1000       100
    1001       102

Here is an explain plan for easier understanding of execution plan:

SELECT STATEMENT  ALL_ROWSCost: 74  Bytes: 84  Cardinality: 3
    9 SORT ORDER BY  Cost: 74  Bytes: 84  Cardinality: 3
        8 HASH JOIN  Cost: 73  Bytes: 84  Cardinality: 3
            1 TABLE ACCESS FULL TABLE CONTACTDBA.INPUT_ACCTROWID Cost: 18  Bytes: 14  Cardinality: 2
            7 VIEW CONTACTDBA. Cost: 55  Bytes: 63  Cardinality: 3
                6 UNION-ALL
                    4 HASH JOIN  Cost: 37  Bytes: 35  Cardinality: 1
                        2 TABLE ACCESS FULL TABLE CONTACTDBA.ACCT_XREF Cost: 18  Bytes: 21  Cardinality: 1
                        3 TABLE ACCESS FULL TABLE CONTACTDBA.ACCT_XREF Cost: 18  Bytes: 42  Cardinality: 3
                    5 TABLE ACCESS FULL TABLE CONTACTDBA.ACCT_XREF Cost: 18  Bytes: 56  Cardinality: 2

I hope this helps.


问:
How to autogenerate username and password in createuserwizard?
How to autogenerate username and password in createuserwizard vb.net !

I want username as int data type and auto increment as 1000, 1001, 1002 and so on ...

and password for all user in random numbers ... with characters as aA123Sb

in createuserwizard complete step it will show username and password....

how to do in vb.net ?

答:
If I understand correctly, instead of letting the user enter the user name and password you want to create it all programmatically?

If so, I don't think you want to use CreateUserWizard since you don't need to have the actual user interface, instead I think you want to look at Membership.CreateUser.

To create the username, all you'll need to do is to remember the last username and then increment it. The password is a little bit more difficult but here's an article with a couple of suggestions for doing this: Generating Random Passwords with ASP.NET


问:
Are reference values copied in Rust?
Am I correct to assume that, for the following code

```<code>let a = vec![1, 2, 3];
let b = &a;
let c = b;
</code>```

The memory presentation will be something like this, assuming the value of b is "B"?

  _            _
b|B|         c|B|
  |____________|
  |
  V
  _________
a|_________|
```

I'm only asking about immutable references, as there can be only 1 mutable reference, as far as I remember.

答:
Yes, this is correct.

In Rust terms, &T is Copy, which means that it can be copied bitwise without transferring ownership.

Title: Are reference values copied in Rust?

Body:
Am I correct to assume that, for the following code

let a = vec![1, 2, 3];
let b = &a;
let c = b;

The memory presentation will be something like this, assuming the value of b is "B"?

  _            _
b|B|         c|B|
  |____________|
  |
  V
  _________
a|_________|

I'm only asking about immutable references, as there can be only 1 mutable reference, as far as I remember.


问:
Why do I obtain this error when deploying app to Heroku?
I am getting some kind of error when deploying my app to heroku using git hub. The problem is, I don't understand the heroku logs and the entailing errors. Here is the heroku log: </p>

```<code>Marcuss-MacBook-Pro:Weather-App marcushurney$ heroku logs
2016-01-05T14:37:27.798077+00:00 app[web.1]: npm ERR! Please include the following file with any support request:
2016-01-05T14:37:27.798377+00:00 app[web.1]: npm ERR!     /app/npm-debug.log
2016-01-05T14:37:27.786949+00:00 app[web.1]: npm ERR! node v5.1.1
2016-01-05T14:37:27.786556+00:00 app[web.1]: npm ERR! argv "/app/.heroku/node/bin/node" "/app/.heroku/node/bin/npm" "start"
2016-01-05T14:37:27.787856+00:00 app[web.1]: npm ERR! npm  v3.3.12
2016-01-05T14:37:28.776245+00:00 heroku[web.1]: Process exited with status 1
2016-01-05T14:37:28.789412+00:00 heroku[web.1]: State changed from starting to crashed
2016-01-05T17:27:16.684869+00:00 heroku[web.1]: State changed from crashed to starting
2016-01-05T17:27:17.853743+00:00 heroku[web.1]: Starting process with command `npm start`
2016-01-05T17:27:20.423495+00:00 app[web.1]: npm ERR! node v5.1.1
2016-01-05T17:27:20.423130+00:00 app[web.1]: npm ERR! argv "/app/.heroku/node/bin/node" "/app/.heroku/node/bin/npm" "start"
2016-01-05T17:27:20.424111+00:00 app[web.1]: npm ERR! npm  v3.3.12
2016-01-05T17:27:20.425937+00:00 app[web.1]: npm ERR! missing script: start
2016-01-05T17:27:20.422441+00:00 app[web.1]: npm ERR! Linux 3.13.0-71-generic
2016-01-05T17:27:20.426242+00:00 app[web.1]: npm ERR!
2016-01-05T17:27:20.426432+00:00 app[web.1]: npm ERR! If you need help, you may report this error at:
2016-01-05T17:27:20.426634+00:00 app[web.1]: npm ERR!     <https://github.com/npm/npm/issues>
</code>```

答:
In my case, changing this:

```<code>"scripts": {
     "test": "echo \"Error: no test specified\" && exit 1"
    },
</code>```

to this:

```<code>"scripts": {
   "start": "node app.js"
    },
</code>```

was the solution

Body:
I am getting some kind of error when deploying my app to heroku using git hub. The problem is, I don't understand the heroku logs and the entailing errors. Here is the heroku log:

Marcuss-MacBook-Pro:Weather-App marcushurney$ heroku logs
2016-01-05T14:37:27.798077+00:00 app[web.1]: npm ERR! Please include the following file with any support request:
2016-01-05T14:37:27.798377+00:00 app[web.1]: npm ERR!     /app/npm-debug.log
2016-01-05T14:37:27.786949+00:00 app[web.1]: npm ERR! node v5.1.1
2016-01-05T14:37:27.786556+00:00 app[web.1]: npm ERR! argv "/app/.heroku/node/bin/node" "/app/.heroku/node/bin/npm" "start"
2016-01-05T14:37:27.787856+00:00 app[web.1]: npm ERR! npm  v3.3.12
2016-01-05T14:37:28.776245+00:00 heroku[web.1]: Process exited with status 1
2016-01-05T14:37:28.789412+00:00 heroku[web.1]: State changed from starting to crashed
2016-01-05T17:27:16.684869+00:00 heroku[web.1]: State changed from crashed to starting
2016-01-05T17:27:17.853743+00:00 heroku[web.1]: Starting process with command `npm start`
2016-01-05T17:27:20.423495+00:00 app[web.1]: npm ERR! node v5.1.1
2016-01-05T17:27:20.423130+00:00 app[web.1]: npm ERR! argv "/app/.heroku/node/bin/node" "/app/.heroku/node/bin/npm" "start"
2016-01-05T17:27:20.424111+00:00 app[web.1]: npm ERR! npm  v3.3.12
2016-01-05T17:27:20.425937+00:00 app[web.1]: npm ERR! missing script: start
2016-01-05T17:27:20.422441+00:00 app[web.1]: npm ERR! Linux 3.13.0-71-generic
2016-01-05T17:27:20.426242+00:00 app[web.1]: npm ERR!
2016-01-05T17:27:20.426432+00:00 app[web.1]: npm ERR! If you need help, you may report this error at:
2016-01-05T17:27:20.426634+00:00 app[web.1]: npm ERR!     <https://github.com/npm/npm/issues>

Body:
In my case, changing this:

"scripts": {
     "test": "echo \"Error: no test specified\" && exit 1"
    },

to this:

"scripts": {
   "start": "node app.js"
    },

was the solution


问:
Do different MySQL connections live in different threads?
I have a webapp which is hosted on an apache server that runs php scripts that connect to a MySQL database.

I know that Apache creates threads and processes to run different scripts when it receives requests, but I'm having a problem when more than one user tries to run a script that calls a stored procedure: one core of the server starts to operate at 90% while the other is only at 0%, which makes the process particularly slow when more than one person is using it at once.

Is there a way to take advantage of the processors full potential?

答:
Each MySQL connection starts its own thread in the mysqld process. But one MySQL connection is fixed to one thread. MySQL has no support for utilizing multiple cores for an individual connection.

Mysqld also runs numerous other helper threads at all times. Connection manager thread, replication threads, deadlock detection threads, various InnoDB threads for reading and writing, etc.

For more details, read:

https://dev.mysql.com/doc/refman/5.7/en/mysql-threads.html

https://dev.mysql.com/doc/refman/5.7/en/connection-threads.html

https://dba.stackexchange.com/questions/5666/possible-to-make-mysql-use-more-than-one-core

If your server has idle cores, then it's possible there isn't enough concurrent work to schedule threads over the multiple cores.


问:
Read from csv file into 2d array and sort the array using c
In my csv file, currently i have data like

```<code>45454, 32, 78, C, 67
45452, 22, 38, C, 34
</code>```

I want to add the data into 2d array and sort them.
Currently i am using this approach

```<code>#include<stdio.h>
#include<conio.h>
#include<String.h>

void getData(char *buff);
int main()
{
    FILE *fp = fopen("file1.csv", "r");
    int count = -1;
    do
    {
        char buff[1024];
        fgets(buff, 1024, (FILE*)fp);
        count++;
        if(count != 1)
        {
            printf(buff);
            getData(buff);
        }
    }
    while((getc(fp))!= EOF);

}
void getData(char buff[])
{
    char *token = strtok(buff,",");
    int counter=0;

    while( token != NULL )
    {
        counter++;
        printf(" %s\n",token);
        token = strtok(NULL,",");
    }
}
</code>```

But i want to read data using fgets and sscanf and store them into single dimensional VLA’s (variable-length arrays)
How can i do that?

答:
You don't actually need a 2-d array. You just need an array which holds your lines. Here you go:</p>

```<code>#include <stdio.h>
#include <stdlib.h>
#include <string.h>

struct row {
    int id;
    int col1;
    int col2;
    char col3;
    int col4;
};

int cmp(const void *a1, const void *a2) {
    const struct row *r1 = a1;
    const struct row *r2 = a2;
    return r1->id - r2->id;
}

void line_to_row(char *buff, struct row *r)
{
    char *saveptr;
    char *token = strtok_r(buff, ",", &saveptr);
    if (token == NULL) {
        exit(1);
    }
    r->id = atoi(token);

    token = strtok_r(buff, ",", &saveptr);
    if (token == NULL) {
        exit(1);
    }
    r->col1 = atoi(token);

    token = strtok_r(buff, ",", &saveptr);
    if (token == NULL) {
        exit(1);
    }
    r->col2 = atoi(token);

    token = strtok_r(buff, ",", &saveptr);
    if (token == NULL) {
        exit(1);
    }

    while (*token != '\0') {
        r->col3 = *token;
        token++;
    }

    r->col4 = atoi(buff + 1);
}

int main()
{
    FILE *fp = fopen("file1.csv", "r");
    if (fp == NULL) {
        exit(1);
    }
    char buff[1024 + 1];
    int c, i = 0, len = 10;
    struct row *rows = malloc(sizeof(*rows) * len);
    struct row *temp = rows;

    while (fgets(buff, 1024, (FILE*)fp)) {
        if (i == len - 1) {
            len += 10;
            temp = realloc(rows, sizeof(*rows) * len);
            if (temp == NULL) {
                exit(1);
            }
            rows = temp;
        }
        line_to_row(buff, &rows[i]);
        i++;
    }
    fclose(fp);

    if (i == 0) {
        return 0;
    }

    len = i;
    temp = realloc(rows, sizeof(*rows) * len);

    if (temp == NULL) {
        exit(1);
    }

    rows = temp;

    qsort(rows, len, sizeof(*rows), &cmp);

    for (i = 0; i < len; i++) {
        printf("%d\n", rows[i].id);
    }
    free(rows);
    return 0;
}
</code>```

Body:
In my csv file, currently i have data like

45454, 32, 78, C, 67
45452, 22, 38, C, 34

I want to add the data into 2d array and sort them.
Currently i am using this approach

#include<stdio.h>
#include<conio.h>
#include<String.h>

void getData(char *buff);
int main()
{
    FILE *fp = fopen("file1.csv", "r");
    int count = -1;
    do
    {
        char buff[1024];
        fgets(buff, 1024, (FILE*)fp);
        count++;
        if(count != 1)
        {
            printf(buff);
            getData(buff);
        }
    }
    while((getc(fp))!= EOF);

}
void getData(char buff[])
{
    char *token = strtok(buff,",");
    int counter=0;

    while( token != NULL )
    {
        counter++;
        printf(" %s\n",token);
        token = strtok(NULL,",");
    }
}

But i want to read data using fgets and sscanf and store them into single dimensional VLA’s (variable-length arrays)
How can i do that?

Body:
You don't actually need a 2-d array. You just need an array which holds your lines. Here you go:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

struct row {
    int id;
    int col1;
    int col2;
    char col3;
    int col4;
};

int cmp(const void *a1, const void *a2) {
    const struct row *r1 = a1;
    const struct row *r2 = a2;
    return r1->id - r2->id;
}

void line_to_row(char *buff, struct row *r)
{
    char *saveptr;
    char *token = strtok_r(buff, ",", &saveptr);
    if (token == NULL) {
        exit(1);
    }
    r->id = atoi(token);

    token = strtok_r(buff, ",", &saveptr);
    if (token == NULL) {
        exit(1);
    }
    r->col1 = atoi(token);

    token = strtok_r(buff, ",", &saveptr);
    if (token == NULL) {
        exit(1);
    }
    r->col2 = atoi(token);

    token = strtok_r(buff, ",", &saveptr);
    if (token == NULL) {
        exit(1);
    }

    while (*token != '\0') {
        r->col3 = *token;
        token++;
    }

    r->col4 = atoi(buff + 1);
}

int main()
{
    FILE *fp = fopen("file1.csv", "r");
    if (fp == NULL) {
        exit(1);
    }
    char buff[1024 + 1];
    int c, i = 0, len = 10;
    struct row *rows = malloc(sizeof(*rows) * len);
    struct row *temp = rows;

    while (fgets(buff, 1024, (FILE*)fp)) {
        if (i == len - 1) {
            len += 10;
            temp = realloc(rows, sizeof(*rows) * len);
            if (temp == NULL) {
                exit(1);
            }
            rows = temp;
        }
        line_to_row(buff, &rows[i]);
        i++;
    }
    fclose(fp);

    if (i == 0) {
        return 0;
    }

    len = i;
    temp = realloc(rows, sizeof(*rows) * len);

    if (temp == NULL) {
        exit(1);
    }

    rows = temp;

    qsort(rows, len, sizeof(*rows), &cmp);

    for (i = 0; i < len; i++) {
        printf("%d\n", rows[i].id);
    }
    free(rows);
    return 0;
}


问:
SonarQube on Java8-project gives jacoco-Exception
I just downloaded the latest version, SonarQube 4.3,
then try build a java-8 project with:

```<code>  mvn clean install
  mvn sonar:sonar
</code>```

That gives me the Exception below.

Googling, I got the impression this is an earlier issue that should have been fixed... ?

http://sonarqube.15.x6.nabble.com/Sonar-analyze-Java-1-8-project-Failure-td5023663.html

http://jira.codehaus.org/browse/SONARJAVA-482

Does SonarQube 4.3 support java-8?

Or any clue, what is the problem?

```<code>-------------------------------------------------------
 T E S T S
-------------------------------------------------------
java.lang.reflect.InvocationTargetException
        at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
        at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
        at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
        at java.lang.reflect.Method.invoke(Method.java:483)
        at sun.instrument.InstrumentationImpl.loadClassAndStartAgent(InstrumentationImpl.java:386)
        at sun.instrument.InstrumentationImpl.loadClassAndCallPremain(InstrumentationImpl.java:401)
Caused by: java.lang.RuntimeException: Class java/util/UUID could not be instrumented.
        at org.jacoco.agent.rt.internal_6effb9e.core.runtime.ModifiedSystemClassRuntime.createFor(ModifiedSystemClassRuntime.java:138)
        at org.jacoco.agent.rt.internal_6effb9e.core.runtime.ModifiedSystemClassRuntime.createFor(ModifiedSystemClassRuntime.java:99)
        at org.jacoco.agent.rt.internal_6effb9e.PreMain.createRuntime(PreMain.java:55)
        at org.jacoco.agent.rt.internal_6effb9e.PreMain.premain(PreMain.java:47)
        ... 6 more
Caused by: java.lang.NoSuchFieldException: $jacocoAccess
        at java.lang.Class.getField(Class.java:1690)
        at org.jacoco.agent.rt.internal_6effb9e.core.runtime.ModifiedSystemClassRuntime.createFor(ModifiedSystemClassRuntime.java:136)
        ... 9 more
FATAL ERROR in native method: processing of -javaagent failed
Exception in thread "main"
</code>```

答:
I was getting the same error when mvn building a Java 1.7 project using JDK 1.8. The solution was simple: I changed the jacoco plugin version to a newer version:

```<code><plugin>
    <groupId>org.jacoco</groupId>
    <artifactId>jacoco-maven-plugin</artifactId>
    <version>0.7.6.201602180812</version>
</code>```

(The project was using version 0.6.3.201306030806 before.)

Body:
I just downloaded the latest version, SonarQube 4.3,
then try build a java-8 project with:

  mvn clean install
  mvn sonar:sonar

That gives me the Exception below.

Googling, I got the impression this is an earlier issue that should have been fixed... ?

http://sonarqube.15.x6.nabble.com/Sonar-analyze-Java-1-8-project-Failure-td5023663.html

http://jira.codehaus.org/browse/SONARJAVA-482

Does SonarQube 4.3 support java-8?

Or any clue, what is the problem?

-------------------------------------------------------
 T E S T S
-------------------------------------------------------
java.lang.reflect.InvocationTargetException
        at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
        at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
        at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
        at java.lang.reflect.Method.invoke(Method.java:483)
        at sun.instrument.InstrumentationImpl.loadClassAndStartAgent(InstrumentationImpl.java:386)
        at sun.instrument.InstrumentationImpl.loadClassAndCallPremain(InstrumentationImpl.java:401)
Caused by: java.lang.RuntimeException: Class java/util/UUID could not be instrumented.
        at org.jacoco.agent.rt.internal_6effb9e.core.runtime.ModifiedSystemClassRuntime.createFor(ModifiedSystemClassRuntime.java:138)
        at org.jacoco.agent.rt.internal_6effb9e.core.runtime.ModifiedSystemClassRuntime.createFor(ModifiedSystemClassRuntime.java:99)
        at org.jacoco.agent.rt.internal_6effb9e.PreMain.createRuntime(PreMain.java:55)
        at org.jacoco.agent.rt.internal_6effb9e.PreMain.premain(PreMain.java:47)
        ... 6 more
Caused by: java.lang.NoSuchFieldException: $jacocoAccess
        at java.lang.Class.getField(Class.java:1690)
        at org.jacoco.agent.rt.internal_6effb9e.core.runtime.ModifiedSystemClassRuntime.createFor(ModifiedSystemClassRuntime.java:136)
        ... 9 more
FATAL ERROR in native method: processing of -javaagent failed
Exception in thread "main"

Body:
I was getting the same error when mvn building a Java 1.7 project using JDK 1.8. The solution was simple: I changed the jacoco plugin version to a newer version:

<plugin>
    <groupId>org.jacoco</groupId>
    <artifactId>jacoco-maven-plugin</artifactId>
    <version>0.7.6.201602180812</version>

(The project was using version 0.6.3.201306030806 before.)


问:
CollapsingToolbarLayout Title with ellipsize marquee
I want to use android's CollapsingToolbarLayout but have a title that, if the layout is collapsed, scrolls horizontally instead of being truncated.
I tried calling setCollapsedTitleTextAppearance with the following style but that didn't have any effect on the marquee (only text color and size).

```<code><style name="TitleText" parent="@android:style/TextAppearance.Medium">
    <item name="android:textSize">20sp</item>
    <item name="android:textStyle">bold</item>
    <item name="android:textColor">@color/material_blue_600</item>
    <item name="android:ellipsize">marquee</item>
    <item name="android:maxLines">1</item>
    <item name="android:scrollHorizontally">true</item>
    <item name="android:singleLine">true</item>
    <item name="android:marqueeRepeatLimit">marquee_forever</item>
</style>
</code>```

Did I miss something? What's the best way to achieve this behavior? Thanks.

答:
I ran into a similar problem myself trying to ellipsize a CollapsingToolbarLayout. After an investigation into where in the android SDK the TitleTextAppearance is handled, it seems like only a handful of text appearance directives are respected:

textColor, textSize, shadowColor, shadowDy, shadowDx, shadowRadius, and typeface.

The CollapsingToolbarLayout class uses a CollapsingTextHelper to apply the text appearance, see the relevant method below:

```<code>void setCollapsedTextAppearance(int resId) {
    TintTypedArray a = TintTypedArray.obtainStyledAttributes(mView.getContext(), resId,
            android.support.v7.appcompat.R.styleable.TextAppearance);
    if (a.hasValue(android.support.v7.appcompat.R.styleable.TextAppearance_android_textColor)) {
        mCollapsedTextColor = a.getColorStateList(
                android.support.v7.appcompat.R.styleable.TextAppearance_android_textColor);
    }
    if (a.hasValue(android.support.v7.appcompat.R.styleable.TextAppearance_android_textSize)) {
        mCollapsedTextSize = a.getDimensionPixelSize(
                android.support.v7.appcompat.R.styleable.TextAppearance_android_textSize,
                (int) mCollapsedTextSize);
    }
    mCollapsedShadowColor = a.getInt(
            android.support.v7.appcompat.R.styleable.TextAppearance_android_shadowColor, 0);
    mCollapsedShadowDx = a.getFloat(
            android.support.v7.appcompat.R.styleable.TextAppearance_android_shadowDx, 0);
    mCollapsedShadowDy = a.getFloat(
            android.support.v7.appcompat.R.styleable.TextAppearance_android_shadowDy, 0);
    mCollapsedShadowRadius = a.getFloat(
            android.support.v7.appcompat.R.styleable.TextAppearance_android_shadowRadius, 0);
    a.recycle();
    if (Build.VERSION.SDK_INT >= 16) {
        mCollapsedTypeface = readFontFamilyTypeface(resId);
    }
    recalculate();
}
</code>```

As Lovis said, if you want the ellipsize directive to be respected you're going to have to implement your own CollapsingToolbarLayout and CollapsingTextHelper classes.

Full Source for the CollapsingTextHelper class: https://android.googlesource.com/platform/frameworks/support/+/android-7.1.1_r23/design/src/android/support/design/widget/CollapsingTextHelper.java

Body:
I want to use android's CollapsingToolbarLayout but have a title that, if the layout is collapsed, scrolls horizontally instead of being truncated.
I tried calling setCollapsedTitleTextAppearance with the following style but that didn't have any effect on the marquee (only text color and size).

Did I miss something? What's the best way to achieve this behavior? Thanks.

Body:
I ran into a similar problem myself trying to ellipsize a CollapsingToolbarLayout. After an investigation into where in the android SDK the TitleTextAppearance is handled, it seems like only a handful of text appearance directives are respected:

textColor, textSize, shadowColor, shadowDy, shadowDx, shadowRadius, and typeface.

The CollapsingToolbarLayout class uses a CollapsingTextHelper to apply the text appearance, see the relevant method below:

void setCollapsedTextAppearance(int resId) {
    TintTypedArray a = TintTypedArray.obtainStyledAttributes(mView.getContext(), resId,
            android.support.v7.appcompat.R.styleable.TextAppearance);
    if (a.hasValue(android.support.v7.appcompat.R.styleable.TextAppearance_android_textColor)) {
        mCollapsedTextColor = a.getColorStateList(
                android.support.v7.appcompat.R.styleable.TextAppearance_android_textColor);
    }
    if (a.hasValue(android.support.v7.appcompat.R.styleable.TextAppearance_android_textSize)) {
        mCollapsedTextSize = a.getDimensionPixelSize(
                android.support.v7.appcompat.R.styleable.TextAppearance_android_textSize,
                (int) mCollapsedTextSize);
    }
    mCollapsedShadowColor = a.getInt(
            android.support.v7.appcompat.R.styleable.TextAppearance_android_shadowColor, 0);
    mCollapsedShadowDx = a.getFloat(
            android.support.v7.appcompat.R.styleable.TextAppearance_android_shadowDx, 0);
    mCollapsedShadowDy = a.getFloat(
            android.support.v7.appcompat.R.styleable.TextAppearance_android_shadowDy, 0);
    mCollapsedShadowRadius = a.getFloat(
            android.support.v7.appcompat.R.styleable.TextAppearance_android_shadowRadius, 0);
    a.recycle();
    if (Build.VERSION.SDK_INT >= 16) {
        mCollapsedTypeface = readFontFamilyTypeface(resId);
    }
    recalculate();
}

As Lovis said, if you want the ellipsize directive to be respected you're going to have to implement your own CollapsingToolbarLayout and CollapsingTextHelper classes.

Full Source for the CollapsingTextHelper class: https://android.googlesource.com/platform/frameworks/support/+/android-7.1.1_r23/design/src/android/support/design/widget/CollapsingTextHelper.java


问:
WCF Impersonation Level Error on System.Data.OracleClient
I currently have a WCF service running in IIS7 and I have have added impersonation on each of the public web methods with the following:

```<code>[OperationBehavior(Impersonation = ImpersonationOption.Required)]
public void TestMethod(){}
</code>```

When ever I call this method from my test client application I get the following error:

Could not load file or assembly 'System.Data.OracleClient, Version=4.0.0.0, Culture=neutral, PublicKeyToken=waeraewrar' or one of its dependencies. Either a required impersonation level was not provided, or the provided impersonation level is invalid.

I'm currently using Microsoft Enterprise Library 3.1, and .Net 4.0.

Sample code:

```<code>WcfService client = new WcfService();
client.TestMethod();
</code>```

答:
The error message suggests that the problem is that the impersonating user doesn't have access to the System.Data.OracleClient assembly DLL in the file system, and thus can't load it.

Can you not cause the System.Data.OracleClient assembly to be first loaded by code outside the service methods requiring impersonation... i.e. by code running with the IIS worker process identity. For example in your service instance constructor.

Once the assembly is loaded into the service's AppDomain, the service methods running under impersonation shouldn't need to do so again.

Body:
I currently have a WCF service running in IIS7 and I have have added impersonation on each of the public web methods with the following:

[OperationBehavior(Impersonation = ImpersonationOption.Required)]
public void TestMethod(){}

When ever I call this method from my test client application I get the following error:

Could not load file or assembly 'System.Data.OracleClient, Version=4.0.0.0, Culture=neutral, PublicKeyToken=waeraewrar' or one of its dependencies. Either a required impersonation level was not provided, or the provided impersonation level is invalid.

I'm currently using Microsoft Enterprise Library 3.1, and .Net 4.0.

Sample code:

WcfService client = new WcfService();
client.TestMethod();


问:
python 3: permission for ftp command "dir" in certain directories denied
The situation:

I'm trying to code a ftp file auto up and download program. It will iterate through my files and auto upload new files. The ftp server is build into my wifi router. I have included the ftp-server into my Ubuntu filesystem and everything work's fine (I can access everything). The home site is like family folders and my own folder.

Now my problem:

So far I was able to connect to the server and change into my directory and list the folders. But if I want to change from this directory into e.g. C++ (it's a folder inside my directory), I'll get an error message saying "Permission denied". The user account used to login is the same used in my file-system inclusion.

The python 3 code:

```<code>from ftplib import FTP_TLS

class ftp_client():

    def __init__(self, host, unandpw):
        self.host = host
        self.logindata = unandpw #should be a touple
        self.ftp = FTP_TLS(self.host)
        self.ftp.login(self.logindata[0], self.logindata[1])
        self.ftp.prot_p()

    def scan(self):
        self.ftp.cwd("/" + self.logindata[0] + "/")
        self.listoffiles = self.ftp.nlst()
        print("list of files: " + str(self.listoffiles))
        for file in self.listoffiles:
            self.ftp.cwd("/" + str(file) + "/")
            self.listoffilesinfiles = self.ftp.nlst()
            print(self.listoffilesinfiles)
            self.ftp.cwd("/" + self.logindata[0] + "/")
</code>```

I'm calling it via an external main file...

The console output:

```<code>list of files: ['C++', 'Documents', 'Pictures', 'Python', 'School',
'share', 'Videos']
Traceback (most recent call last):
  File "main.py", line 5, in <module>
    ftp.scan()
  File "/home/simon/Python/autoserversync/client.py", line 18, in scan
    self.ftp.cwd("/" + str(file) + "/")
  File "/usr/lib/python3.5/ftplib.py", line 630, in cwd
    return self.voidcmd(cmd)
  File "/usr/lib/python3.5/ftplib.py", line 277, in voidcmd
    return self.voidresp()
  File "/usr/lib/python3.5/ftplib.py", line 250, in voidresp
    resp = self.getresp()
  File "/usr/lib/python3.5/ftplib.py", line 245, in getresp
    raise error_perm(resp)
ftplib.error_perm: 550 /C++/: Permission denied.
</code>```

Now my question (obviously) is: how can I fix this?

答:
In your self.ftp.cwd("/" + str(file) + "/") line, you're adding a slash to the start of your path. Remember that in Unix, a path starting with a slash is an absolute path, starting from the root directory.

If your folders are in your home directory instead (judging by their names I'm guessing they are) try changing it to self.ftp.cwd("~/" + str(file) + "/") instead.

Body:
The situation:

I'm trying to code a ftp file auto up and download program. It will iterate through my files and auto upload new files. The ftp server is build into my wifi router. I have included the ftp-server into my Ubuntu filesystem and everything work's fine (I can access everything). The home site is like family folders and my own folder.

Now my problem:

So far I was able to connect to the server and change into my directory and list the folders. But if I want to change from this directory into e.g. C++ (it's a folder inside my directory), I'll get an error message saying "Permission denied". The user account used to login is the same used in my file-system inclusion.

The python 3 code:

from ftplib import FTP_TLS

class ftp_client():

    def __init__(self, host, unandpw):
        self.host = host
        self.logindata = unandpw #should be a touple
        self.ftp = FTP_TLS(self.host)
        self.ftp.login(self.logindata[0], self.logindata[1])
        self.ftp.prot_p()

    def scan(self):
        self.ftp.cwd("/" + self.logindata[0] + "/")
        self.listoffiles = self.ftp.nlst()
        print("list of files: " + str(self.listoffiles))
        for file in self.listoffiles:
            self.ftp.cwd("/" + str(file) + "/")
            self.listoffilesinfiles = self.ftp.nlst()
            print(self.listoffilesinfiles)
            self.ftp.cwd("/" + self.logindata[0] + "/")

I'm calling it via an external main file...

The console output:

list of files: ['C++', 'Documents', 'Pictures', 'Python', 'School',
'share', 'Videos']
Traceback (most recent call last):
  File "main.py", line 5, in <module>
    ftp.scan()
  File "/home/simon/Python/autoserversync/client.py", line 18, in scan
    self.ftp.cwd("/" + str(file) + "/")
  File "/usr/lib/python3.5/ftplib.py", line 630, in cwd
    return self.voidcmd(cmd)
  File "/usr/lib/python3.5/ftplib.py", line 277, in voidcmd
    return self.voidresp()
  File "/usr/lib/python3.5/ftplib.py", line 250, in voidresp
    resp = self.getresp()
  File "/usr/lib/python3.5/ftplib.py", line 245, in getresp
    raise error_perm(resp)
ftplib.error_perm: 550 /C++/: Permission denied.

Now my question (obviously) is: how can I fix this?


问:
Using Vim's tabs like buffers
I have looked at the ability to use tabs in Vim (with :tabe, :tabnew, etc.) as a replacement for my current practice of having many files open in the same window in hidden buffers.

I would like every distinct file that I have open to always be in its own tab. However, there are some things that get in the way of this. How do I fix these:

When commands like gf and ^] jump to a location in another file, the file opens in a new buffer in the current tab. Is there a way to have all of these sorts of commands open the file in a new tab, or switch to the existing tab with the file if it is already open?

When switching buffers I can use
:b <part of filename><tab>
and it will complete the names of files in existing buffers. <part of filename> can even be the middle of a filename instead of the beginning. Is there an equivalent for switching tabs?

答:
This is an answer for those not familiar with Vim and coming from other text editors (in my case Sublime Text).

I read through all these answers and it still wasn't clear. If you read through them enough things begin to make sense, but it took me hours of going back and forth between questions.

The first thing is, as others have explained:

Tab Pages, sound a lot like tabs, they act like tabs and look a lot like tabs in most other GUI editors, but they're not. I think it's an a bad mental model that was built on in Vim, which unfortunately clouds the extra power that you have within a tab page.

The first description that I understood was from @crenate's answer is that they are the equivalent to multiple desktops. When seen in that regard you'd only ever have a couple of desktops open but have lots of GUI windows open within each one.

I would say they are similar to in other editors/browsers:

Tab groupings

Sublime Text workspaces (i.e. a list of the open files that you have in a project)

When you see them like that you realise the power of them that you can easily group sets of files (buffers) together e.g. your CSS files, your HTML files and your JS files in different tab pages. Which is actually pretty awesome.

Other descriptions that I find confusing

Viewport

This makes no sense to me. A viewport which although it does have a defined dictionary term, I've only heard referring to Vim windows in the :help window doc. Viewport is not a term I've ever heard with regards to editors like Sublime Text, Visual Studio, Atom, Notepad++. In fact I'd never heard about it for Vim until I started to try using tab pages.

If you view tab pages like multiple desktops, then referring to a desktop as a single window seems odd.

Workspaces

This possibly makes more sense, the dictionary definition is:

A memory storage facility for temporary use.

So it's like a place where you store a group of buffers.

It didn't initially sound like Sublime Text's concept of a workspace which is a list of all the files that you have open in your project:

the sublime-workspace file, which contains user specific data, such as the open files and the modifications to each.

However thinking about it more, this does actually agree. If you regard a Vim tab page like a Sublime Text project, then it would seem odd to have just one file open in each project and keep switching between projects. Hence why using a tab page to have open only one file is odd.

Collection of windows

The :help window refers to tab pages this way. Plus numerous other answers use the same concept. However until you get your head around what a vim window is, then that's not much use, like building a castle on sand.

As I referred to above, a vim window is the same as a viewport and quiet excellently explained in this linux.com article:

A really useful feature in Vim is the ability to split the viewable area between one or more files, or just to split the window to view two bits of the same file more easily. The Vim documentation refers to this as a viewport or window, interchangeably.

You may already be familiar with this feature if you've ever used Vim's help feature by using :help topic or pressing the F1 key. When you enter help, Vim splits the viewport and opens the help documentation in the top viewport, leaving your document open in the bottom viewport.

I find it odd that a tab page is referred to as a collection of windows instead of a collection of buffers. But I guess you can have two separate tab pages open each with multiple windows all pointing at the same buffer, at least that's what I understand so far.

OwnerDisplayName: indentation

Title: Using Vim's tabs like buffers


问:
Given a commit sha, get ref (if any)
I have a pretty good understanding of how git (and github) works, but one thing frustratingly eludes me.

When I see a 'push' webhook from github, it'll contain a lot of nice info, incluing an array of commits, and the head commit, etc.  the webhook payload includes the 'ref' of the head commit.

However, given any specific commit, I cannot seem to find any way to query github via the API to see if that commit has any ref(s).

Use case: I know a SHA.  I'm curious if it's the actual commit that a branch ref points to.  I understand that not all commits have a ref, but I need to test a single commit regardless.

This simply has to be possible, but I'm so wrapped around the axle I'm not seeing it.

Ultimate use case: it seems consistent that a merge has more than one 'parent', and those parents represent the 'to' and 'from' branches involved in the merge.  Given a merge push, I must discover the source and target branches.  Obviously I cannot use the 'message' as this, while the default is useful, is overridable and therefore untrustworthy.

Dead in the water if I can't figure this out.

答:
A trip to Subway proved moderately effective. Hoping there's a more efficient way, but I can query all the refs for a given repo, then map the sha in question to that array looking for a match.

Any suggestions for a more efficient method of matching than pulling down hundreds of refs just to attempt to match one are appreciated.

Title: Given a commit sha, get ref (if any)


问:
Why can't I set up my Kalabox Drupal Site? SQLState[Hy000] error
I have a fresh install of Ubuntu 14.04 in Hyper-V, a fresh install of mysql and user 'root'@'localhost' with 'password'. I created a database called 'drupaltest'. Yet when I start up a kalabox Drupal Site, I try enter that information in and I get this error:

Failed to connect to your database server. The server reports the following message: SQLSTATE[HY000] [2002] No such file or directory.

Can you help me figure out what's going on with it?

答:
You can find the related information to your question here.  From this you find your database related information following these steps:

Use the Terminal option from the dropdown to access the location of the PHP app that you already created.  In this example it is the second option for the existing new Drupal 8 installation.

This will open the terminal navigated to the kalabox container.  confirm that it is in the parent directory. Check for the kalabox root files and directories; cli.yml, code, config, dockerfiles, etc..  They should resemble something like this:

You can see that the kalabox container is located in my user directory.

use the kbox services command to print the services available to the container.  If it doesn't work you may not be in the parent directory of the container and would refer back to step 2.