问:
Closing DataSource if supplied to Jdbc class
I need a little advise. I come to a need to close DataSource, but FluentJdbc once gets DataSource seems I do not have a way to get it back to close. Ideally I would love to wrap DataSource into try() block, but in that case connection pool is opened and instantly closed.

One way it would be to store DataSource within hash, but seems a bit overhead.

I have following code to store multiple connections:

```<code>public class FluentJdbcFactory {
    private final static Logger logger = LoggerFactory.getLogger("Defrauder");
    private final static Map<String, FluentJdbc> instances = new HashMap<>();

    private static Properties get(String propertiesName) {
        try (InputStream in = FluentJdbcFactory.class.getClassLoader().getResourceAsStream(propertiesName)) {
            Properties p = new Properties();
            p.load(in);
            return p;
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    public static FluentJdbc getInstance(String propertiesName) {
        if (!instances.containsKey(propertiesName)) {
            HikariDataSource ds = DatasourceConfig.setup(get(propertiesName));
            instances.put(propertiesName, new FluentJdbcBuilder()
                    .connectionProvider(ds)
                    .defaultSqlHandler(() -> FluentJdbcFactory::isCriticalSqlException)
                    .build());
        }
        return instances.get(propertiesName);
    }

    public static void close() {
        instances.forEach((k,v)->v.NON_EXISTANT_CLOSE_METHOD);
    }
}
</code>```

Anything I could so smarter?

答:
I come to a need to close DataSource, but FluentJdbc once gets DataSource seems I do not have a way to get it back to close.

I don't think there is a smart way to do this.  The assumption in the FluentJdbc API is that:

it takes care of the lifecycle of connections, statements and result sets

you take care of the lifecycle of the Datasource.

But the dumb way is pretty light-weight.  Create a class with attributes for a DataSource and a FluentJdbc, and use instances of that class as the values in your instances map.  Maybe 30 simple lines of code?

Body:
I need a little advise. I come to a need to close DataSource, but FluentJdbc once gets DataSource seems I do not have a way to get it back to close. Ideally I would love to wrap DataSource into try() block, but in that case connection pool is opened and instantly closed.

One way it would be to store DataSource within hash, but seems a bit overhead.

I have following code to store multiple connections:

public class FluentJdbcFactory {
    private final static Logger logger = LoggerFactory.getLogger("Defrauder");
    private final static Map<String, FluentJdbc> instances = new HashMap<>();

    private static Properties get(String propertiesName) {
        try (InputStream in = FluentJdbcFactory.class.getClassLoader().getResourceAsStream(propertiesName)) {
            Properties p = new Properties();
            p.load(in);
            return p;
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    public static FluentJdbc getInstance(String propertiesName) {
        if (!instances.containsKey(propertiesName)) {
            HikariDataSource ds = DatasourceConfig.setup(get(propertiesName));
            instances.put(propertiesName, new FluentJdbcBuilder()
                    .connectionProvider(ds)
                    .defaultSqlHandler(() -> FluentJdbcFactory::isCriticalSqlException)
                    .build());
        }
        return instances.get(propertiesName);
    }

    public static void close() {
        instances.forEach((k,v)->v.NON_EXISTANT_CLOSE_METHOD);
    }
}

Anything I could so smarter?


来源: stackexchange

问:
message queue thinking
We have implemented a message queue by using C# Queue. We know we only have ONE consumer to take available message out from the queue for processing with a while loop. We also know there is only ONE producer to put message onto the queue.

We have a lock on above message queue to make sure the consumer and producer cannot access the queue simultaneously.

My question is is that lock necessary? If the Queue increase its Count property AFTER an item is actually added and if the consumer check the Count before retrieve, the consumer should get a complete message item even we don't have that lock. Right? So we will not face a partial message item issue. Then we can get rid of that lock?

That lock will slow down the system and occasionally we can see the retrieve thread is blocked for a while because we have a very heavy producer.

EDIT:

Unfortunately we are using .Net 3.5.

答:
The lock is necessary, if you're using Queue<T>.  You could easily remove this by replacing that with ConcurrentQueue<T>, however, you may want to consider simplifying this code by replacing it with a BlockingCollection<T>.

This would allow your consumer to eliminate the lock and while checking, and just do a single foreach on collection.GetConsumingEnumerable().  The producer can eliminate the lock and add items as needed.  It also would easily allow you to scale up to using multiple producers, since you mentioned you have a "very heavy producer" at the moment.

ContentLicense: CC BY-SA 2.5

Title: message queue thinking


问:
How to share data between two web pages?
Im trying working on a web app project and trying to figure out how to display my answer on the second web page.

I have put a a text box on my first webpage and have corrected the coding of my application as I have received the correct answers in the textbox after I have debugged it.

Ideally I want to remove this textbox and want my answers which I managed to display on my textbox displayed on a label in the next webpage. Here is the calculation part of my code;

```<code>var cost = ((int)duration.TotalMinutes) * 0.35m;
                txtCost.Text = cost.ToString("c");
</code>```

I'd like to make my answer appear in my second webpage and not have it displayed in the first. I have tried using Session["Cost"] = cost; on the button click event handler of the first webpage double cost = (double)(Session["Cost"]);
                lblDisplay.Text = cost.ToString("c");
and this on the second webpage but every time I Debug it and run I always get $0.00 displayed on my label. Can someone help me fix this?

答:
In ASP.NET WebForms application, you can pass data around in various ways:

Cache

See the Learning Curve answer for examples.
However, the object put in the cache is not guaranteed to be found again if the server experiences memory shortage or alike. The ASP.NET manages the cache and evicts objects on its own to maintain memory availability. This is in contrast with ApplicationState and SessionState where the objects are kept until they are removed manually, or the Application ends or Session expires.

Session and Application states

You can put any object in the SessionState object and retrieve it elsewhere in your code. However, you need to cast it appropriately as the SessionState accepts object-s. E.g. if you store a number, when you retrieving it, you must do the casting yourself, just as you already did it.
The reason it doesn't work, is perhaps you're trying to retrieve it from within another user's SessionState. Yes, the SessionState is a per-user structure. If you need to add the value as from one device and use it on another, use ApplicationState:

```<code>Application["cost"] = cost;
</code>```

Redirecting Response

Using this technique, you could force the browser to request another page from the server and specify the full query string, including the variables you need. E.g. :

```<code>var destination = Server.UrlEncode("/someOtherPage.aspx?cost=34.65");
Response.Redirect(destination);
</code>```

As an alternative, you can use Server.Transfer("someOtherPage.aspx") to save the roundtrip. However, in that case, the browser doesn't change the address in the address bar so the user is misled that she browses one page, but in fact, it is the someOtherPage.aspx.

ContentLicense: CC BY-SA 3.0

Body:
Im trying working on a web app project and trying to figure out how to display my answer on the second web page.

I have put a a text box on my first webpage and have corrected the coding of my application as I have received the correct answers in the textbox after I have debugged it.

Ideally I want to remove this textbox and want my answers which I managed to display on my textbox displayed on a label in the next webpage. Here is the calculation part of my code;

var cost = ((int)duration.TotalMinutes) * 0.35m;
                txtCost.Text = cost.ToString("c");

I'd like to make my answer appear in my second webpage and not have it displayed in the first. I have tried using Session["Cost"] = cost; on the button click event handler of the first webpage double cost = (double)(Session["Cost"]);
                lblDisplay.Text = cost.ToString("c");
and this on the second webpage but every time I Debug it and run I always get $0.00 displayed on my label. Can someone help me fix this?

Body:
In ASP.NET WebForms application, you can pass data around in various ways:

Cache

See the Learning Curve answer for examples.
However, the object put in the cache is not guaranteed to be found again if the server experiences memory shortage or alike. The ASP.NET manages the cache and evicts objects on its own to maintain memory availability. This is in contrast with ApplicationState and SessionState where the objects are kept until they are removed manually, or the Application ends or Session expires.

Session and Application states

You can put any object in the SessionState object and retrieve it elsewhere in your code. However, you need to cast it appropriately as the SessionState accepts object-s. E.g. if you store a number, when you retrieving it, you must do the casting yourself, just as you already did it.
The reason it doesn't work, is perhaps you're trying to retrieve it from within another user's SessionState. Yes, the SessionState is a per-user structure. If you need to add the value as from one device and use it on another, use ApplicationState:

Application["cost"] = cost;

Redirecting Response

Using this technique, you could force the browser to request another page from the server and specify the full query string, including the variables you need. E.g. :

var destination = Server.UrlEncode("/someOtherPage.aspx?cost=34.65");
Response.Redirect(destination);

As an alternative, you can use Server.Transfer("someOtherPage.aspx") to save the roundtrip. However, in that case, the browser doesn't change the address in the address bar so the user is misled that she browses one page, but in fact, it is the someOtherPage.aspx.


问:
repeat a group of characters
I have the following input to be matched by a regex:

```<code>1.1.1.1
1.01.1.1
01.01.091.01
1.10.100.0010
</code>```

So I have allways four groups consisting of digits. While the first three ones should match, the last one should not.

So I wrote this regex:

```<code>^(\d*[1-9]+\.){4}$
</code>```

In general this regex should return all those strings where any of the digits in any of the groups is not followed by a zero. Or more easily: I want to not match all numbers with trailing zeros.

However this doesn´t match anything. regex1010.com tells this:

A repeated capturing group will only capture the last iteration. Put a
  capturing group around the repeated group to capture all iterations or
  use a non-capturing group instead if you're not interested in the data

But when I add a further capturing group I get the same message:

```<code>^((\d*[1-9]+\.)){4}$
</code>```

The same applies to a non-capturing group:

```<code>^(?:\d*[1-9]+\.){4}$
</code>```

Of course I could just write the same group four times, but that´s fairly clumsy and hard to read.

答:
As mentioned by others the dot is the point, so we have three identical groups and one without the dot.

So this regex does it for me:

```<code>(?:\d*[1-9]\.){3}(?:\d*[1-9])
</code>```

Title: repeat a group of characters

Body:
I have the following input to be matched by a regex:

1.1.1.1
1.01.1.1
01.01.091.01
1.10.100.0010

So I have allways four groups consisting of digits. While the first three ones should match, the last one should not.

So I wrote this regex:

^(\d*[1-9]+\.){4}$

In general this regex should return all those strings where any of the digits in any of the groups is not followed by a zero. Or more easily: I want to not match all numbers with trailing zeros.

However this doesn´t match anything. regex1010.com tells this:

A repeated capturing group will only capture the last iteration. Put a
  capturing group around the repeated group to capture all iterations or
  use a non-capturing group instead if you're not interested in the data

But when I add a further capturing group I get the same message:

^((\d*[1-9]+\.)){4}$

The same applies to a non-capturing group:

^(?:\d*[1-9]+\.){4}$

Of course I could just write the same group four times, but that´s fairly clumsy and hard to read.

Body:
As mentioned by others the dot is the point, so we have three identical groups and one without the dot.

So this regex does it for me:

(?:\d*[1-9]\.){3}(?:\d*[1-9])


问:
Rails ActiveRecord joining issues
I have the following code: subscribers = Subscriber.find(:all, :joins => :profile, :conditions => ['subscribers.active IS NULL'])

When I do this: puts subscribers.first.inspect, I should be seeing the profile information as well, but I'm not... Here are the model associations

```<code>class Subscriber < ActiveRecord::Base
  has_one :profile
  has_many :medias
end

class Profile < ActiveRecord::Base
  belongs_to :subscriber
end
</code>```

I am still trying to get used to writing joins in MySQL so I apologize for the sloppiness

答:
Try:

```<code>subscribers = Subscriber.find(:all, :include => :profile, :conditions => ['subscribers.active IS NULL'])
</code>```

However inspect doesn't look into nested relations. You can try to_yaml:

```<code>puts subscribers.first.to_yaml
</code>```

Result is structured and easy readable and include is used only for performance.
It fetches profile with subscriber in single query.
You can also do:

```<code>puts Subscriber.where('active IS NULL').includes(:profile).first.to_yaml
</code>```

Generally you should use joins when you want to filter data by a joined relation column.

Title: Rails ActiveRecord joining issues

Body:
I have the following code: subscribers = Subscriber.find(:all, :joins => :profile, :conditions => ['subscribers.active IS NULL'])

When I do this: puts subscribers.first.inspect, I should be seeing the profile information as well, but I'm not... Here are the model associations

class Subscriber < ActiveRecord::Base
  has_one :profile
  has_many :medias
end

class Profile < ActiveRecord::Base
  belongs_to :subscriber
end

I am still trying to get used to writing joins in MySQL so I apologize for the sloppiness

Body:
Try:

subscribers = Subscriber.find(:all, :include => :profile, :conditions => ['subscribers.active IS NULL'])

However inspect doesn't look into nested relations. You can try to_yaml:

puts subscribers.first.to_yaml

Result is structured and easy readable and include is used only for performance.
It fetches profile with subscriber in single query.
You can also do:

puts Subscriber.where('active IS NULL').includes(:profile).first.to_yaml

Generally you should use joins when you want to filter data by a joined relation column.


问:
Visual Studio 2015 Community Edition Installation Stuck In Windows 10
I am trying to install VS 2015 in Windows 10 and the installation is stuck at the "Applying Microsoft Visual Studio 2015 x86 Debug Runtime - 14.0.23026" section for around 4 hours.

The Acquiring section is showing 100% though.

Terminated the same to find the below details in a log file:

```<code>[2015-08-02T16:48:28]i305: Verified acquired payload:
VSSetupUtility_Complete_vs_community at path: C:\ProgramData\Package Cache\.unverified\VSSetupUtility_Complete_vs_community, moving to: C:\ProgramData\Package Cache\7DB2302D-A398-3430-A694-   6B1ECD9A8D22\packages\vs_community\VSSetupUtility.exe.
[0CD8:1FE0][2015-08-02T16:48:28]i000: MUX:  Source confirmed
[0CD8:1FE0][2015-08-02T16:48:28]i000: MUX:  Set the Cache Complete Event
[0CD8:1854][2015-08-02T19:23:22]i000: MUX:  Go to CancelPrompt page.
[0CD8:1854][2015-08-02T19:23:26]i000: MUX:  Go to Progress page.
[0CD8:1854][2015-08-02T19:28:19]i000: MUX:  Go to CancelPrompt page.
</code>```

After "Set the Cache Complete Event" it is stuck for 3 hours...

When I look at the Task Manager details -> Analyze wait chain for the exe, it shows deadlock.

This is the 3rd time I am trying to install VS 2015 community edition; 2 times using the web installer and the 3rd time using an ISO.

答:
In Windows 10 I go it through restarting Windows in Safe Mode! It's only way when my installation was fast as possible and avoid any hangs/stucks.

But don't forget to start Windows Installer Service before VS setup.

Body:
I am trying to install VS 2015 in Windows 10 and the installation is stuck at the "Applying Microsoft Visual Studio 2015 x86 Debug Runtime - 14.0.23026" section for around 4 hours.

The Acquiring section is showing 100% though.

Terminated the same to find the below details in a log file:

[2015-08-02T16:48:28]i305: Verified acquired payload:
VSSetupUtility_Complete_vs_community at path: C:\ProgramData\Package Cache\.unverified\VSSetupUtility_Complete_vs_community, moving to: C:\ProgramData\Package Cache\7DB2302D-A398-3430-A694-   6B1ECD9A8D22\packages\vs_community\VSSetupUtility.exe.
[0CD8:1FE0][2015-08-02T16:48:28]i000: MUX:  Source confirmed
[0CD8:1FE0][2015-08-02T16:48:28]i000: MUX:  Set the Cache Complete Event
[0CD8:1854][2015-08-02T19:23:22]i000: MUX:  Go to CancelPrompt page.
[0CD8:1854][2015-08-02T19:23:26]i000: MUX:  Go to Progress page.
[0CD8:1854][2015-08-02T19:28:19]i000: MUX:  Go to CancelPrompt page.

After "Set the Cache Complete Event" it is stuck for 3 hours...

When I look at the Task Manager details -> Analyze wait chain for the exe, it shows deadlock.

This is the 3rd time I am trying to install VS 2015 community edition; 2 times using the web installer and the 3rd time using an ISO.


问:
C# - T type, array, list indexing
I want to write a method where i can send any type of [], List<>...etc. But in the code when I use T and I want to index the input array, list or anything the error says "Cannot apply indexing with [] to an expression of type 'T'". Theres any solution for this or I have to write a separate code for array, list..etc?

public void NormSort<T>(ref T input, int n)
{
    for (int i = 0; i < n - 2; i++)
    {
        for (int j = 0; j < n - 1; j++)
        {
            if (Comparer<T>.Default.Compare(input[i], input[j]) > 0)
            {
                Swap<T>(input[i], input[j]);
            }
        }
    }
}

public void Swap<T>(T item1, T item2)
 {
     var temp = item1;
     item1 = item2;
     item2 = temp;
 }
```

So wheres the input[i], input[j], there i got that error.

答:
The easiest way to do that is probably to make the parameter IList<T> for some T, since IList<T> has the indexer support and both arrays and lists implement IList<T>. Note that you probably don't need to pass the n here, since IList<T> also has a .Count property. So:

```<code>public void NormSort<T>(IList<T> input) {
    int n = input.Count;
    // ...
}
</code>```

Note that your Swap method won't work, however; that isn't pass-by-ref, and even if it was: you can't pass indexer values by ref - you need to get and set separately; perhaps:

```<code>public static void NormSort<T>(IList<T> input)
{
    int n = input.Count;
    var comparer = Comparer<T>.Default;
    for (int i = 0; i < n - 1; i++)
    {
        for (int j = i; j < n; j++)
        {
            T x = input[i], y = input[j];
            if (comparer.Compare(x, y) > 0)
            {
                input[i] = y;
                input[j] = x;
            }
        }
    }
}
</code>```

Note that a more typical implementation here would be an extension method:

```<code>public static void Sort<T>(this IList<T> input) {...}
</code>```

Then you can just use:

```<code>myListOrArray.Sort();
</code>```

and as a nice side-effect, if the compiler knows it is a List<T>, it will prefer the inbuilt List<T>.Sort() which will be more efficient - but it will compile for any IList<T> type.

Title: C# - T type, array, list indexing

Body:
I want to write a method where i can send any type of [], List<>...etc. But in the code when I use T and I want to index the input array, list or anything the error says "Cannot apply indexing with [] to an expression of type 'T'". Theres any solution for this or I have to write a separate code for array, list..etc?

public void NormSort<T>(ref T input, int n)
{
    for (int i = 0; i < n - 2; i++)
    {
        for (int j = 0; j < n - 1; j++)
        {
            if (Comparer<T>.Default.Compare(input[i], input[j]) > 0)
            {
                Swap<T>(input[i], input[j]);
            }
        }
    }
}

public void Swap<T>(T item1, T item2)
 {
     var temp = item1;
     item1 = item2;
     item2 = temp;
 }

So wheres the input[i], input[j], there i got that error.

Body:
The easiest way to do that is probably to make the parameter IList<T> for some T, since IList<T> has the indexer support and both arrays and lists implement IList<T>. Note that you probably don't need to pass the n here, since IList<T> also has a .Count property. So:

public void NormSort<T>(IList<T> input) {
    int n = input.Count;
    // ...
}

Note that your Swap method won't work, however; that isn't pass-by-ref, and even if it was: you can't pass indexer values by ref - you need to get and set separately; perhaps:

public static void NormSort<T>(IList<T> input)
{
    int n = input.Count;
    var comparer = Comparer<T>.Default;
    for (int i = 0; i < n - 1; i++)
    {
        for (int j = i; j < n; j++)
        {
            T x = input[i], y = input[j];
            if (comparer.Compare(x, y) > 0)
            {
                input[i] = y;
                input[j] = x;
            }
        }
    }
}

Note that a more typical implementation here would be an extension method:

public static void Sort<T>(this IList<T> input) {...}

Then you can just use:

myListOrArray.Sort();

and as a nice side-effect, if the compiler knows it is a List<T>, it will prefer the inbuilt List<T>.Sort() which will be more efficient - but it will compile for any IList<T> type.


问:
Replace everything not in the String
I know when I use .replace I can replace a specified String for another string. For example:

```<code>String string = “hi fjrkfinnek”;

string.replace(“fjrkfinnek”, “”);
</code>```

I know using this will replace that specified part of the string with a blank space in this example. However, is it possible to remove everything that’s not “hi” instead of referencing what I want to replace?

The output I would desire is to remove everything but Hi by saying Remove everything that’s not Hi if that can be done!

答:
Given the String you provided you can split it into words using the split() function and then append only those parts that don't contain the "hi".

If you use java 8, you can do that with a filter:

```<code>String string = “hi fjrkfinnek”;
    Arrays.asList(string.split(" ")).stream()
                     .filter(s -> !s.equals("hi")).collect(Collectors.joining());
</code>```

In the code above, I get each word as a String then I stream it and I apply a filter so that only those different than "hi" are allowed. Finally I just join back into a String.

Title: Replace everything not in the String

Body:
I know when I use .replace I can replace a specified String for another string. For example:

String string = “hi fjrkfinnek”;

string.replace(“fjrkfinnek”, “”);

I know using this will replace that specified part of the string with a blank space in this example. However, is it possible to remove everything that’s not “hi” instead of referencing what I want to replace?

The output I would desire is to remove everything but Hi by saying Remove everything that’s not Hi if that can be done!

Body:
Given the String you provided you can split it into words using the split() function and then append only those parts that don't contain the "hi".

If you use java 8, you can do that with a filter:

String string = “hi fjrkfinnek”;
    Arrays.asList(string.split(" ")).stream()
                     .filter(s -> !s.equals("hi")).collect(Collectors.joining());

In the code above, I get each word as a String then I stream it and I apply a filter so that only those different than "hi" are allowed. Finally I just join back into a String.


问:
$uibModal - dismiss failing to invoke
I know there are numerous threads on this issue, but I have tried to follow solutions provided but am having no success.

The one I followed which resolved the error Unknown provider: $uibModalInstanceProvider, was the answer from @GeorgeKach in Unknown provider: $uibModalInstanceProvider - Bootstrap UI modal. The error has been removed and the modal opens, but my dismissal/close methods aren't invoking.

```<code>    vm.open = function() {

        console.log('open') //invokes

        var modalInstance = $uibModal.open({
            templateUrl: 'p3sweb/app/components/app/views/modalTemplate.html',
            appendTo: undefined,
            controller: function($uibModalInstance ,$scope){

                vm.ok = function () {
                    console.log('ok') //fails
                    $uibModalInstance.close();
                };

                vm.cancel = function () {
                    console.log('close') //fails
                    $uibModalInstance.dismiss('cancel');
                };

            }
        })

        modalInstance.result.then(function() {
          //resolved
        }, function() {
          //rejected
        })
    }
</code>```

Question

Why are my ok and cancel methods not invoking? Rather than providing a work around, can someone explain why they aren't invoking?

Template

```<code><div class="modal-header d-flex flex-column align-items-center justify-content-center">
    <i class="fa fa-warning fa-3x"></i>
    <p class="h4 txt-phase-red">Remove Patent</p>
</div>
<div class="modal-body d-flex flex-column align-items-center justify-content-center">
    <p class="font-body">Are you sure you want to remove patent application xxxxxxxxxx?</p>
</div>
<div class="modal-footer">
    <button class="btn btn--lg font-body font-body--component bg-phase-red txt-white" ng-click="$ctrl.cancel()">No</button>
    <button class="btn btn--lg font-body font-body--component bg-phase-green txt-white" ng-click="$ctrl.ok()">Yes</button>
</div>
</code>```

答:
For your concept use $scope instead vm or add attribute controllerAs

Change vm to $scope:

```<code>$scope.ok = function () {
    console.log('ok') //fails
     $uibModalInstance.close();
            };

$scope.cancel = function () {
  console.log('close') //fails
  $uibModalInstance.dismiss('cancel');
};
</code>```

or:

```<code>var modalInstance = $uibModal.open({
        templateUrl: 'p3sweb/app/components/app/views/modalTemplate.html',
        appendTo: undefined,
        controllerAs: 'vm',  <--- add
        controller: function($uibModalInstance ,$scope){

            vm.ok = function () {
                console.log('ok') //fails
                $uibModalInstance.close();
            };

            vm.cancel = function () {
                console.log('close') //fails
                $uibModalInstance.dismiss('cancel');
            };

        }
    })
</code>```

Title: $uibModal - dismiss failing to invoke

Body:
I know there are numerous threads on this issue, but I have tried to follow solutions provided but am having no success.

The one I followed which resolved the error Unknown provider: $uibModalInstanceProvider, was the answer from @GeorgeKach in Unknown provider: $uibModalInstanceProvider - Bootstrap UI modal. The error has been removed and the modal opens, but my dismissal/close methods aren't invoking.

    vm.open = function() {

        console.log('open') //invokes

        var modalInstance = $uibModal.open({
            templateUrl: 'p3sweb/app/components/app/views/modalTemplate.html',
            appendTo: undefined,
            controller: function($uibModalInstance ,$scope){

                vm.ok = function () {
                    console.log('ok') //fails
                    $uibModalInstance.close();
                };

                vm.cancel = function () {
                    console.log('close') //fails
                    $uibModalInstance.dismiss('cancel');
                };

            }
        })

        modalInstance.result.then(function() {
          //resolved
        }, function() {
          //rejected
        })
    }

Question

Why are my ok and cancel methods not invoking? Rather than providing a work around, can someone explain why they aren't invoking?

Template

Remove Patent

Are you sure you want to remove patent application xxxxxxxxxx?

    <button class="btn btn--lg font-body font-body--component bg-phase-red txt-white" ng-click="$ctrl.cancel()">No</button>
    <button class="btn btn--lg font-body font-body--component bg-phase-green txt-white" ng-click="$ctrl.ok()">Yes</button>

Body:
For your concept use $scope instead vm or add attribute controllerAs

Change vm to $scope:

$scope.ok = function () {
    console.log('ok') //fails
     $uibModalInstance.close();
            };

$scope.cancel = function () {
  console.log('close') //fails
  $uibModalInstance.dismiss('cancel');
};

or:

var modalInstance = $uibModal.open({
        templateUrl: 'p3sweb/app/components/app/views/modalTemplate.html',
        appendTo: undefined,
        controllerAs: 'vm',  <--- add
        controller: function($uibModalInstance ,$scope){

            vm.ok = function () {
                console.log('ok') //fails
                $uibModalInstance.close();
            };

            vm.cancel = function () {
                console.log('close') //fails
                $uibModalInstance.dismiss('cancel');
            };

        }
    })


问:
Regular expressions REGEX 4 digits PIN code with at least one different than others
I tried different regex which I found here but they are not working.

for example:

```<code>1111 = false
1112 = true
</code>```

It's my homework so I must do it in regex :)

答:
You can use this regex:

```<code>^(\d)(?!\1+$)\d{3}$
</code>```

Explanation:

^ - Match line start

(\d) - match first digit and capture it in back reference #1 i.e. \1

(?!..) is a negative lookahead

(?!\1+$) means disallow the match if first digit is followed by same digit (captured group) till end.

\d{3}$ match next 3 digit followed by line end

Body:
I tried different regex which I found here but they are not working.

for example:

1111 = false
1112 = true

It's my homework so I must do it in regex :)

Body:
You can use this regex:

^(\d)(?!\1+$)\d{3}$

Explanation:

^ - Match line start

(\d) - match first digit and capture it in back reference #1 i.e. \1

(?!..) is a negative lookahead

(?!\1+$) means disallow the match if first digit is followed by same digit (captured group) till end.

\d{3}$ match next 3 digit followed by line end


问:
Converting Django project from MySQL to Mongo, any major pitfalls?
I want to try Mongodb w/ mongoengine.  I'm new to Django and databases and I'm having a fit with Foreign Keys, Joins, Circular Imports (you name it).  I know I could eventually work through these issues but Mongo just seems like a simpler solution for what I am doing.  My question is I'm using a lot of pluggable apps (Imagekit, Haystack, Registration, etc) and wanted to know if these apps will continue to work if I make the switch. Are there any known headaches that I will encounter, if so I might just keep banging my head with MySQL.</p>

答:
I have recently tried this (although without Mongoengine).  There are a huge number of pitfalls, IMHO:

No admin interface.

No Auth  django.contrib.auth relies on the DB interface.

Many things rely on django.contrib.auth.User.  For example, the RequestContext class.  This is a huge hindrance.

No Registration (Relies on the DB interface and django.contrib.auth)

Basically, search through the django interface for references to django.contrib.auth and you'll see how many things will be broken.

That said, it's possible that MongoEngine provides some support to replace/augment django.contrib.auth with something better, but there are so many things that depend on it that it's hard to say how you'd monkey patch something that much.


问:
Summing one ArrayList of Integers to another ArrayList of Integers, gives error: variable expected
I have two ArrayList of 6 elements in my Android application. Let's call them ArrayList "A" and "B". Each object in my class has this line in the constructor:

```<code>likes = new ArrayList<Integer>();
</code>```

I could also add this line in the constructor (I'm not sure which one is better, but I want to initialize the size to 6, and all elements should be 0):

```<code>likes = new ArrayList<>(Collections.nCopies(6, 0));
</code>```

I have a method in my class called Calculate, which is supposed to take a new ArrayList of Integers, B, of the same size as A, as a parameter. Then add / sum B with this object's ArrayList, A.

Here is the method:

```<code>public void Calculate(ArrayList<Integer> likes){
    for(int i = 0; i < likes.size(); i++){
        this.likes.get(i) += likes.get(i);
        //this.likes.get(i) = 3;
    }
}
</code>```

I'm getting a red line under the line this.likes.get(i), saying:

Variable Expected

Even if I try to just say this.likes.get(i) = 3; I get the same error.

Let's say A = {0,0,0,0,0,0}, and B = {1,0,0,-1,1,0}

What is the correct way to sum to ArrayList, to make A = {1,0,0,-1,1,0}?

答:
You can't assign a value to a value such as this.likes.get(i).
You can only assign values to variables.

To modify the i'th element of an ArrayList you should use the ArrayList's set method:

```<code>this.likes.set(i,this.likes.get(i) + likes.get(i));
</code>```

Body:
I have two ArrayList of 6 elements in my Android application. Let's call them ArrayList "A" and "B". Each object in my class has this line in the constructor:

likes = new ArrayList<Integer>();

I could also add this line in the constructor (I'm not sure which one is better, but I want to initialize the size to 6, and all elements should be 0):

likes = new ArrayList<>(Collections.nCopies(6, 0));

I have a method in my class called Calculate, which is supposed to take a new ArrayList of Integers, B, of the same size as A, as a parameter. Then add / sum B with this object's ArrayList, A.

Here is the method:

public void Calculate(ArrayList<Integer> likes){
    for(int i = 0; i < likes.size(); i++){
        this.likes.get(i) += likes.get(i);
        //this.likes.get(i) = 3;
    }
}

I'm getting a red line under the line this.likes.get(i), saying:

Variable Expected

Even if I try to just say this.likes.get(i) = 3; I get the same error.

Let's say A = {0,0,0,0,0,0}, and B = {1,0,0,-1,1,0}

What is the correct way to sum to ArrayList, to make A = {1,0,0,-1,1,0}?

Body:
You can't assign a value to a value such as this.likes.get(i).
You can only assign values to variables.

To modify the i'th element of an ArrayList you should use the ArrayList's set method:

this.likes.set(i,this.likes.get(i) + likes.get(i));


答:
you need to use set(index,value) because there is no container on the left side to hold the value so hence the error , so you can pass the resultant value to list to set it at the desired position</p>

```<code>this.likes.set(i,this.likes.get(i) += likes.get(i));
</code>```

Title: Summing one ArrayList of Integers to another ArrayList of Integers, gives error: variable expected

Body:
you need to use set(index,value) because there is no container on the left side to hold the value so hence the error , so you can pass the resultant value to list to set it at the desired position

this.likes.set(i,this.likes.get(i) += likes.get(i));


问:
Error when installing python
I was trying to install python and for some weird and unknown reason, the installation process is stopped and returns this error

An error occurred during the installation of assembly 'Microsoft.VC90.CRT,version="9.0.21022.8",publicKeyToken="1fc8b3b9a1e18e3b",processorArchitecture="amd64",type="win32"'. Please refer to Help and Support for more information.

This is the first time I encountered such error. I tried 'googling' it but there seems to be no way to fix this up. Do you guys have any suggestions? I just want to install python.

答:
I know this is an old post but I recently ran into this exact same issue.
It was caused by my machine having pending Windows updates that needed a restart to be applied.

Once you've reset your machine remove the C:\Python27 folder (this is important).

Rerun the installer and it should work with no issues :-)

Title: Error when installing python


问:
Exception in cleaner thread when reading files from S3 in local Spark
Following is in my class-path:

aws-java-sdk-1.7.4.jar

hadoop-aws-2.7.3.jar

spark-sql-2.2.0.jar

Following code works fine:

```<code>object MySparkJob {
  def main(args:Array[String]):Unit = {
    val conf = new SparkConf().setAppName("MySparkTest").setMaster("local[4]")
    val spark = new SparkContext(conf)
    ......all credentials config stuff here.......
    val input = spark.textFile("s3a://mybucket/access_2017-10-30.log_10.0.0.176.gz")
    val pageStats = input filter(_.contains("pagestat"))
    val parsedRecords = pageStats flatMap accessLogRecordToCaseClass
    val evIDs = parsedRecords map (_.evid)
    println("Size is " + evIDs.collect().toSet.size)
    spark.stop
  }
}
</code>```

I run the job with sbt clean compile run.

But in the console I see following warning with the exception wrapped:

```<code>17/11/10 15:22:28 WARN FileSystem: exception in the cleaner thread but it will continue to run
java.lang.InterruptedException
        at java.lang.Object.wait(Native Method)
        at java.lang.ref.ReferenceQueue.remove(ReferenceQueue.java:143)
        at java.lang.ref.ReferenceQueue.remove(ReferenceQueue.java:164)
        at org.apache.hadoop.fs.FileSystem$Statistics$StatisticsDataReferenceCleaner.run(FileSystem.java:3063)
        at java.lang.Thread.run(Thread.java:748)
</code>```

Though this is a warning I still would like to understand why it happens. Probably some of you encountered similar thing in the past and can advise?

答: Don't worry; it's just a cleanup tread being told to stop in application shutdown. HADOOP-12829 explicitly toned down the warning message when interrupted to ""Cleaner thread interrupted, will stop"</p>

Body:
Following is in my class-path:

aws-java-sdk-1.7.4.jar

hadoop-aws-2.7.3.jar

spark-sql-2.2.0.jar

Following code works fine:

object MySparkJob {
  def main(args:Array[String]):Unit = {
    val conf = new SparkConf().setAppName("MySparkTest").setMaster("local[4]")
    val spark = new SparkContext(conf)
    ......all credentials config stuff here.......
    val input = spark.textFile("s3a://mybucket/access_2017-10-30.log_10.0.0.176.gz")
    val pageStats = input filter(_.contains("pagestat"))
    val parsedRecords = pageStats flatMap accessLogRecordToCaseClass
    val evIDs = parsedRecords map (_.evid)
    println("Size is " + evIDs.collect().toSet.size)
    spark.stop
  }
}

I run the job with sbt clean compile run.

But in the console I see following warning with the exception wrapped:

17/11/10 15:22:28 WARN FileSystem: exception in the cleaner thread but it will continue to run
java.lang.InterruptedException
        at java.lang.Object.wait(Native Method)
        at java.lang.ref.ReferenceQueue.remove(ReferenceQueue.java:143)
        at java.lang.ref.ReferenceQueue.remove(ReferenceQueue.java:164)
        at org.apache.hadoop.fs.FileSystem$Statistics$StatisticsDataReferenceCleaner.run(FileSystem.java:3063)
        at java.lang.Thread.run(Thread.java:748)

Though this is a warning I still would like to understand why it happens. Probably some of you encountered similar thing in the past and can advise?


问:
Not Able To Install Stanford-Core-NLP Gem
I am trying to install the Stanford-Core-NLP gem, which is one of the major projects on github for natural language processing using Ruby. It provides Ruby bindings for the Stanford-Core-NLP pakage, which where written in Java. When I try following the first step of the the installation instructions, which is:

```<code>gem install stanford-core-nlp
</code>```

I get the following error:

```<code>ERROR:  Error installing stanford-core-nlp:
ERROR: Failed to build gem native extension.

/home/user/.rvm/rubies/ruby-1.9.2-p320/bin/ruby extconf.rb
*** extconf.rb failed ***
Could not create Makefile due to some reason, probably lack of
necessary libraries and/or headers.  Check the mkmf.log file for more
details.  You may need configuration options.

Provided configuration options:
--with-opt-dir
--without-opt-dir
--with-opt-include
--without-opt-include=${opt-dir}/include
--with-opt-lib
--without-opt-lib=${opt-dir}/lib
--with-make-prog
--without-make-prog
--srcdir=.
--curdir
--ruby=/home/user/.rvm/rubies/ruby-1.9.2-p320/bin/ruby
extconf.rb:53:in `<main>': JAVA_HOME is not set. (RuntimeError)
</code>```

I am running Ruby 1.9.2, which according to the repo, is the latest version the gem has been tested on and Java 1.7.0_40. I also tried looking for the mkmf.log file, but was unable to locate it.

答:
I've been wrestling with this on Ubuntu. The thing that works reliably (though it is a sledgehammer) is:

```<code>JAVA_HOME=/usr/lib/whatever gem install stanford-core-nlp
</code>```

The installation script is sensitive to the format of JAVA_HOME - it shouldn't end in a slash character.

Body:
I am trying to install the Stanford-Core-NLP gem, which is one of the major projects on github for natural language processing using Ruby. It provides Ruby bindings for the Stanford-Core-NLP pakage, which where written in Java. When I try following the first step of the the installation instructions, which is:

gem install stanford-core-nlp

I get the following error:

ERROR:  Error installing stanford-core-nlp:
ERROR: Failed to build gem native extension.

/home/user/.rvm/rubies/ruby-1.9.2-p320/bin/ruby extconf.rb
*** extconf.rb failed ***
Could not create Makefile due to some reason, probably lack of
necessary libraries and/or headers.  Check the mkmf.log file for more
details.  You may need configuration options.

Provided configuration options:
--with-opt-dir
--without-opt-dir
--with-opt-include
--without-opt-include=${opt-dir}/include
--with-opt-lib
--without-opt-lib=${opt-dir}/lib
--with-make-prog
--without-make-prog
--srcdir=.
--curdir
--ruby=/home/user/.rvm/rubies/ruby-1.9.2-p320/bin/ruby
extconf.rb:53:in `': JAVA_HOME is not set. (RuntimeError)

I am running Ruby 1.9.2, which according to the repo, is the latest version the gem has been tested on and Java 1.7.0_40. I also tried looking for the mkmf.log file, but was unable to locate it.

Body:
I've been wrestling with this on Ubuntu. The thing that works reliably (though it is a sledgehammer) is:

JAVA_HOME=/usr/lib/whatever gem install stanford-core-nlp

The installation script is sensitive to the format of JAVA_HOME - it shouldn't end in a slash character.


问:
Using datatables to search table Asp.net MVC
I'm using datatables in order to search a table however when add another table row datatables doesn't an I realized in researching I have to same amount of rows and columns. What I would like to know is there a way I could get around; because I would love to use it but I need to include that table row. This is what I have.

Javascript

```<code>    <script type="text/javascript">

    $(document).ready(function () {
        $('#data').DataTable();
    });

</script>
</code>```

Form

```<code>    <h2>Transaction List</h2>
@using (Html.BeginForm())
{
    @Html.AntiForgeryToken()

    <div>
        <h4>Transaction List Details</h4>
        <div style="text-align:right">
            @Html.ActionLink("Posted Items Report", "TransactionListRpt", "Post")
            <input id="Print" type="button" value="Print Approved List" name="Print" class="btn-link"/>
        </div>
        <hr />

        <table id="data" >

            <thead>
           @Html.CheckBox("TheOneCheckBoxToRuleThemAll")Select All
                <tr>

                    <th class="col-lg-3 ">Expense Account</th>
                    <th class="col-lg-3 ">Item Number</th>
                    <th class="col-sm-1">Quantity</th>
                    <th class="col-sm-1 ">UOM</th>
                    <th class="col-sm-1 ">Cost</th>
                    <th class="col-sm-1 ">Extended Cost</th>

                    <th></th>
                </tr>
            </thead>
            <tbody>
    @for (int i = 0; i < Model.Count; i++)
    {
        @Html.HiddenFor(m => m[i].requisitionNumber)
        @Html.HiddenFor(m => m[i].inventory_acccount)
        @Html.HiddenFor(m => m[i].department)
        @Html.HiddenFor(m => m[i].docNumber)
        @Html.HiddenFor(m => m[i].docType)

        <tr>
            <td>@Html.CheckBoxFor(m => m[i].postTrnx, new { @class = "checkGroup1" })</td>
            <td class="label">
                @Html.DisplayFor(m => m[i].requisitionNumber)
            @Html.DisplayFor(m => m[i].transactionDate)
            @Html.DisplayFor(m => m[i].docType)
        </td>
    </tr>
        foreach (var item in Model[i].items)
        {
                    @Html.HiddenFor(m => item.description)
                    @Html.HiddenFor(m => item.expense_account)
                    @Html.HiddenFor(m => item.itemNumber)
                    <tr>

                        <td class="col-lg-3 tabledata">@item.expense_account.account_desc</td>
                        <td class="col-lg-3 tabledata">@item.itemNumber</td>
                        <td class="col-sm-1 tabledata">@item.quantity</td>
                        <td class="col-sm-1 tabledata">@item.selecteduomtext </td>
                        <td class="col-sm-1 tabledata">@item.price</td>
                        <td class="col-sm-1 tabledata">@item.extended_cost</td>
                        <td>@Html.ActionLink("Edit", "Edit", new { id = @item.lineNum, name = Model[i].docNumber })</td>
                    </tr>

                  }

                    }
</tbody>
        </table>
        <br /><br /><br />
    </div>

       <div>

<input type="submit" value="Post" name="Approve" class="btn btn-primary btn-lg" onclick="return confirm('Click OK to continue or Cancel to abort');" />
        @*<input type="button" value="View Posted Transactions" class="btn btn-primary btn-lg" onclick="location.href='@Url.Action("TransactionListRpt","Post")'"/>*@
    </div>

}
</code>```

答:
You can call just like this, to enable searching</p>

```<code>$('#data').dataTable({
        "searching": true
    });
</code>```

Body:
I'm using datatables in order to search a table however when add another table row datatables doesn't an I realized in researching I have to same amount of rows and columns. What I would like to know is there a way I could get around; because I would love to use it but I need to include that table row. This is what I have.

Javascript

Form

Transaction List

@using (Html.BeginForm())
{
    @Html.AntiForgeryToken()

Transaction List Details

            @Html.ActionLink("Posted Items Report", "TransactionListRpt", "Post")
            <input id="Print" type="button" value="Print Approved List" name="Print" class="btn-link"/>

           @Html.CheckBox("TheOneCheckBoxToRuleThemAll")Select All

                    Expense Account
                    Item Number
                    Quantity
                    UOM
                    Cost
                    Extended Cost

    @for (int i = 0; i < Model.Count; i++)
    {
        @Html.HiddenFor(m => m[i].requisitionNumber)
        @Html.HiddenFor(m => m[i].inventory_acccount)
        @Html.HiddenFor(m => m[i].department)
        @Html.HiddenFor(m => m[i].docNumber)
        @Html.HiddenFor(m => m[i].docType)

            @Html.CheckBoxFor(m => m[i].postTrnx, new { @class = "checkGroup1" })

                @Html.DisplayFor(m => m[i].requisitionNumber)
            @Html.DisplayFor(m => m[i].transactionDate)
            @Html.DisplayFor(m => m[i].docType)

        foreach (var item in Model[i].items)
        {
                    @Html.HiddenFor(m => item.description)
                    @Html.HiddenFor(m => item.expense_account)
                    @Html.HiddenFor(m => item.itemNumber)

                        @item.expense_account.account_desc
                        @item.itemNumber
                        @item.quantity
                        @item.selecteduomtext
                        @item.price
                        @item.extended_cost
                        @Html.ActionLink("Edit", "Edit", new { id = @item.lineNum, name = Model[i].docNumber })

                  }

                    }

<input type="submit" value="Post" name="Approve" class="btn btn-primary btn-lg" onclick="return confirm('Click OK to continue or Cancel to abort');" />
        @*<input type="button" value="View Posted Transactions" class="btn btn-primary btn-lg" onclick="location.href='@Url.Action("TransactionListRpt","Post")'"/>*@

}

Body:
You can call just like this, to enable searching

$('#data').dataTable({
        "searching": true
    });


问:
is it possible to use twice ifPresent each one checking different return or bifurcate map
Context: I have chained objects generated by wsdl2java. There is an already created method that call the soap web services, receives the xml and unmarshalling it in cascaded objects.

Desire: I want to get two different objects which lies in different hierarchy nodes. From mapping perspective they are hold "far" from one another but from business perspective they are a "couple".

This is currently working:

```<code>Optional.ofNullable(onderneming.getOndernemingOfVestiging()).map(OndernemingOfVestigingType::getCode) //same return
        .map(CodeOndernemingOfVestigingType::getValue) // different object return
        .ifPresent(o -> myMethod("onderneming_type", o.getValue()));

Optional.ofNullable(onderneming.getOndernemingOfVestiging()).map(OndernemingOfVestigingType::getCode) //same return
        .map(CodeOndernemingOfVestigingType::getBeschrijving) // different object return
        .ifPresent(o -> myMethod("onderneming_type_omschrijving", o.getValue()));
</code>```

What I am trying is something like (pseudo-explanation):

```<code>Optional.ofNullable(onderneming.getOndernemingOfVestiging()).map(OndernemingOfVestigingType::getCode) //same return
        .map(CodeOndernemingOfVestigingType::getValue) // different object return
        .ifPresent(o -> myMethod("onderneming_type", o.getValue()))
        .map(CodeOndernemingOfVestigingType::getBeschrijving) // different object return
        .ifPresent(o -> myMethod("onderneming_type_omschrijving", o.getValue()));
</code>```

I understand that this doesn't work because I can have only one terminate clausure and ifPresent appears twice.

From dummy viewpoint, my question could be also: is it possible to fork/bifurcate/divide map in two different direction in same lambda expression?

*** Based on Eugene suggestion I did successfully

```<code>Optional.ofNullable(onderneming.getOndernemingOfVestiging()).map(OndernemingOfVestigingType::getCode)
        .ifPresent(o -> {
            System.out.println(o.getValue().getValue());
            System.out.println(o.getBeschrijving().getValue());
        });
</code>```

I changed from myMethod to System.out.println so no confusion is caused (I don't care about myMethod in this context. It could be anyother method of any instanced object).

Althought it works and it sounds a good progress compared to original one (instead of two lambda sentences there are only one), I see some problem: "o.getValue().getValue()" and  "o.getBeschrijving().getValue()" are null unsafety, aren't they?

答:
I've a bit simplified your example here if u don't mind and here is what I came up with:

```<code>static class User {

    private final Integer age;

    private final String name;

    public User(Integer age, String name) {
        this.age = age;
        this.name = name;
    }

    public Optional<Integer> getAge() {
        return Optional.ofNullable(age);
    }

    public String getName() {
        return name;
    }
}
</code>```

And then :

```<code>    Optional<User> user = Optional.of(new User(null, "test"));

    user.map(u -> Map.entry(u, u.getAge())) // this is java-9 Map.entry; but you can use a Pair or a List/array etc
            .ifPresent(x -> {
                System.out.println("name = " + x.getKey().getName());
                x.getValue().ifPresent(age -> {
                    System.out.println("age = " + age);
                });
            });
</code>```

You could apply the same thing to your input

Body:
Context: I have chained objects generated by wsdl2java. There is an already created method that call the soap web services, receives the xml and unmarshalling it in cascaded objects.

Desire: I want to get two different objects which lies in different hierarchy nodes. From mapping perspective they are hold "far" from one another but from business perspective they are a "couple".

This is currently working:

Optional.ofNullable(onderneming.getOndernemingOfVestiging()).map(OndernemingOfVestigingType::getCode) //same return
        .map(CodeOndernemingOfVestigingType::getValue) // different object return
        .ifPresent(o -> myMethod("onderneming_type", o.getValue()));

Optional.ofNullable(onderneming.getOndernemingOfVestiging()).map(OndernemingOfVestigingType::getCode) //same return
        .map(CodeOndernemingOfVestigingType::getBeschrijving) // different object return
        .ifPresent(o -> myMethod("onderneming_type_omschrijving", o.getValue()));

What I am trying is something like (pseudo-explanation):

Optional.ofNullable(onderneming.getOndernemingOfVestiging()).map(OndernemingOfVestigingType::getCode) //same return
        .map(CodeOndernemingOfVestigingType::getValue) // different object return
        .ifPresent(o -> myMethod("onderneming_type", o.getValue()))
        .map(CodeOndernemingOfVestigingType::getBeschrijving) // different object return
        .ifPresent(o -> myMethod("onderneming_type_omschrijving", o.getValue()));

I understand that this doesn't work because I can have only one terminate clausure and ifPresent appears twice.

From dummy viewpoint, my question could be also: is it possible to fork/bifurcate/divide map in two different direction in same lambda expression?

*** Based on Eugene suggestion I did successfully

Optional.ofNullable(onderneming.getOndernemingOfVestiging()).map(OndernemingOfVestigingType::getCode)
        .ifPresent(o -> {
            System.out.println(o.getValue().getValue());
            System.out.println(o.getBeschrijving().getValue());
        });

I changed from myMethod to System.out.println so no confusion is caused (I don't care about myMethod in this context. It could be anyother method of any instanced object).

Althought it works and it sounds a good progress compared to original one (instead of two lambda sentences there are only one), I see some problem: "o.getValue().getValue()" and  "o.getBeschrijving().getValue()" are null unsafety, aren't they?

Body:
I've a bit simplified your example here if u don't mind and here is what I came up with:

static class User {

    private final Integer age;

    private final String name;

    public User(Integer age, String name) {
        this.age = age;
        this.name = name;
    }

    public Optional<Integer> getAge() {
        return Optional.ofNullable(age);
    }

    public String getName() {
        return name;
    }
}

And then :

    Optional<User> user = Optional.of(new User(null, "test"));

    user.map(u -> Map.entry(u, u.getAge())) // this is java-9 Map.entry; but you can use a Pair or a List/array etc
            .ifPresent(x -> {
                System.out.println("name = " + x.getKey().getName());
                x.getValue().ifPresent(age -> {
                    System.out.println("age = " + age);
                });
            });

You could apply the same thing to your input


问:
How do I edit code on PythonanyWhere console?
I am brand new to Python, and tried downloading Python on my computer but had some issues because I have a very old Macbook that can only run OSX 10.6. I have been trying to use Python Anywhere, but I cant seem to edit the code I write in the console. For example, if I write a bunch of code and then run it and get an parentheses error, I have to re-enter all of that code onto the next command line and add the parentheses rather than just adding the parentheses to the code and re-running it. I can just copy and paste the bad code onto the new line, fix the error, and then re-run the code, but this gets tedious. Sorry if this is a dumb question, but I have used R a bit before and in R you can simply edit the code, then run it again, so I am wondering if there is a way to write Python code in this same manner. </p>

答:
There's two main ways of entering code into PythonAnywhere:

the first is to type it interactively into a live interpreter or "Console".  You do that from the PythonAnywhere "Consoles" tab.  it sounds like that's what you've done so far

the second is to create a file.  You do that via the "Files" tab.  if you create a new file with a .py ending (eg hello.py) PythonAnywhere will bring up an editor which you can use to save a file, and then you can run it, see the output below the editor, then make changes, re-run, etc.


问:
Upload Files with Websockets and Nodejs
I'm trying to implement a file uploader, where a HTML input file is sent by a WebSocket to a Nodejs server.

Tried to read the file in a BLOB and binary string from the FileReader API of HTML and sent it to Nodejs server so it can be written to a file in the server. Tried createWriteStream and writeFile with ascii or base 64 encoding in the Nodejs part.

Still the file saved in server doesn't work properly.

Am I missing something?

Thank you

UPDATE

Client

```<code>    var uploader = $("#uploader"),
        files = uploader.prop('files'),
        file_reader = new FileReader();
    file_reader.onload = function(evt) {
        socketClient.write({
            'action': 'ExtensionSettings->upload',
            'domain': structureUser.domain,
            'v_id': ext,
            'file': file_reader.result
        });
    };
    file_reader.readAsDataURL(files[0]);
    //readAsDataURL
    uploader.replaceWith(uploader.clone());
</code>```

Server

```<code>var stream = fs.createWriteStream("file");
stream.once("open", function() {
    stream.write(msg.file, "base64");
    stream.on('finish', function() {
        stream.close();
    });
});
</code>```

答:
Consider starting a separate http server on a different port being used by the websocket and then upload the file via traditional post action in a form. Returning status code 204 (no content) ensures the browser doesn't hang after the post action. The server code assumes directory 'upload' already exists. This worked for me:

Client

```<code><form method="post" enctype="multipart/form-data" action="http://localhost:8080/fileupload">
    <input name="filename" type="file">
    <input type="submit">
</form>
</code>```

Server

```<code>http = require('http');
formidable = require('formidable');
fs = require('fs');

http.createServer(function (req, res) {

    if (req.url === '/fileupload') {

        var form = new formidable.IncomingForm();
        form.parse(req, function (err, fields, files) {
            var prevpath = files.filename.path;
            var name = files.filename.name;
            var newpath = './upload/' + name;

            var is = fs.createReadStream(prevpath);
            var os = fs.createWriteStream(newpath);

                // more robust than using fs.rename
                // allows moving across different mounted filesystems
            is.pipe(os);

                // removes the temporary file originally
                // created by the post action
            is.on('end',function() {
                fs.unlinkSync(prevpath);
            });

                // prevents browser from hanging, assuming
                // success status/processing
                // is handled by websocket based server code
            res.statusCode = 204;
            res.end();

        });

    }

})
.listen (8080);
</code>```

Title: Upload Files with Websockets and Nodejs

Body:
I'm trying to implement a file uploader, where a HTML input file is sent by a WebSocket to a Nodejs server.

Tried to read the file in a BLOB and binary string from the FileReader API of HTML and sent it to Nodejs server so it can be written to a file in the server. Tried createWriteStream and writeFile with ascii or base 64 encoding in the Nodejs part.

Still the file saved in server doesn't work properly.

Am I missing something?

Thank you

UPDATE

Client

    var uploader = $("#uploader"),
        files = uploader.prop('files'),
        file_reader = new FileReader();
    file_reader.onload = function(evt) {
        socketClient.write({
            'action': 'ExtensionSettings->upload',
            'domain': structureUser.domain,
            'v_id': ext,
            'file': file_reader.result
        });
    };
    file_reader.readAsDataURL(files[0]);
    //readAsDataURL
    uploader.replaceWith(uploader.clone());

Server

var stream = fs.createWriteStream("file");
stream.once("open", function() {
    stream.write(msg.file, "base64");
    stream.on('finish', function() {
        stream.close();
    });
});

Body:
Consider starting a separate http server on a different port being used by the websocket and then upload the file via traditional post action in a form. Returning status code 204 (no content) ensures the browser doesn't hang after the post action. The server code assumes directory 'upload' already exists. This worked for me:

Client

<form method="post" enctype="multipart/form-data" action="http://localhost:8080/fileupload">
    <input name="filename" type="file">
    <input type="submit">
</form>

Server

http = require('http');
formidable = require('formidable');
fs = require('fs');

http.createServer(function (req, res) {

    if (req.url === '/fileupload') {

        var form = new formidable.IncomingForm();
        form.parse(req, function (err, fields, files) {
            var prevpath = files.filename.path;
            var name = files.filename.name;
            var newpath = './upload/' + name;

            var is = fs.createReadStream(prevpath);
            var os = fs.createWriteStream(newpath);

                // more robust than using fs.rename
                // allows moving across different mounted filesystems
            is.pipe(os);

                // removes the temporary file originally
                // created by the post action
            is.on('end',function() {
                fs.unlinkSync(prevpath);
            });

                // prevents browser from hanging, assuming
                // success status/processing
                // is handled by websocket based server code
            res.statusCode = 204;
            res.end();

        });

    }

})
.listen (8080);


问:
Converting Json data to html?
```<code><script>
  $(document).ready(function() {

    $("#getMessage").on("click", function() {
      $.getJSON("/json/cats.json", function(json) {

        var html = "";
        // Only change code below this line.
        json.forEach(function(val){
                     var keys = Object.keys(val);
                     html+="<div class='cat'>";
                     keys.forEach(function(key){
                       html+="<strong>"+key+"</strong>;"+val[key]+"<br>";
                     });
        html+="</div><br>";
                     });

        // Only change code above this line.

        $(".message").html(html);

      });
    });
  });
</script>

<div class="container-fluid">
  <div class = "row text-center">
    <h2>Cat Photo Finder</h2>
  </div>
  <div class = "row text-center">
    <div class = "col-xs-12 well message">
      The message will go here
   </div>
  </div>
  <div class = "row text-center">
    <div class = "col-xs-12">
      <button id = "getMessage" class = "btn btn-primary">
        Get Message
      </button>
    </div>
  </div>
</div>
</code>```

<p>So I am an amateur front end developer I just finished some basic JS and started learning about json and jquery but this above bit of code is going over my head.
Could some one please explain the javascript part of it. </p>

答:
$(document).ready(function() { // means that whenever the document is ready you get an annonimous function

    $("#getMessage").on("click", function() {// this is jQuery selector for an element in the DOM called getMEssage (this is the ID)
      $.getJSON("/json/cats.json", function(json) { // this gets the JSON data from /json/cats.json

        var html = ""; //you create an empthy variable called html
        // Only change code below this line.
        json.forEach(function(val){ // you go over each element in the json object that came from the cats.json file
                     var keys = Object.keys(val); // you get the key
                     html+="
";// you add a div element with the class cat to the html variable you did create at every iteration
                     keys.forEach(function(key){ //you itewrate over all keys
                       html+=""+key+";"+val[key]+"
"; // you add the key (in bold text) + the value for the key (not in bold) to the html and you break the row
                     });
        html+="

"; // now you close the div element and you break the row
                     });

        // Only change code above this line.

        $(".message").html(html); // then you select all the elements with the message class and you set their html to be equal to your variable called html

      });
    });
  });```

Hope it helps.
All the best,
PIY

Title: Converting Json data to html?

Body:
Cat Photo Finder

      The message will go here

      <button id = "getMessage" class = "btn btn-primary">
        Get Message
      </button>

So I am an amateur front end developer I just finished some basic JS and started learning about json and jquery but this above bit of code is going over my head.
Could some one please explain the javascript part of it.

Body:
$(document).ready(function() { // means that whenever the document is ready you get an annonimous function

    $("#getMessage").on("click", function() {// this is jQuery selector for an element in the DOM called getMEssage (this is the ID)
      $.getJSON("/json/cats.json", function(json) { // this gets the JSON data from /json/cats.json

        var html = ""; //you create an empthy variable called html
        // Only change code below this line.
        json.forEach(function(val){ // you go over each element in the json object that came from the cats.json file
                     var keys = Object.keys(val); // you get the key
                     html+="<div class='cat'>";// you add a div element with the class cat to the html variable you did create at every iteration
                     keys.forEach(function(key){ //you itewrate over all keys
                       html+="<strong>"+key+"</strong>;"+val[key]+"<br>"; // you add the key (in bold text) + the value for the key (not in bold) to the html and you break the row
                     });
        html+="</div><br>"; // now you close the div element and you break the row
                     });

        // Only change code above this line.

        $(".message").html(html); // then you select all the elements with the message class and you set their html to be equal to your variable called html

      });
    });
  });

Hope it helps.
All the best,
PIY


问:
Indexing uploaded documents - searchable only by the users that uploaded them
If someone could point me in the right direction that would be most helpful.

I have written a custom CMS where I want to be able to allow each individual user to upload documents (.doc .docx .pdf .rtf .txt etc) and then be able to search the contents of those files for keywords.

The CMS is written entirely in PHP and MySQL within a Linux environment.

Once uploaded the documents would be stored in the users  private folder on the server "as is". There will be hundreds if not thousands of documents stored by each user.

It is very important that the specific users files are searchable only by that user.

Could anyone point me in the right direction? I have had a look at Solr but these types of solutions seem so complicated. I have spent an entire week looking at different solutions and this is my last attempt at finding a solution.

Thank you in advance.

答:
2 choices I see.

A search index per user. Their documents are indexed separately from everyone else's. When they do a search, they hit their own search index. There is no danger of seeing other's results, or getting scores based on contents from other's documents. The downside is having to store and update the index separately. I would look into using Lucene for something like this, as the indices will be small.

A single search index. The users all share a search index. The results from searches would have to be filtered down so that only results were returned for that user. The upside is implementing a single search index (Solr would be great for this). The down side is the risk of cross talk between users searches. Scoring would be impacted by other users documents, resulting in poorer search results.

I hate to say it, but from a quality standpoint, I'd lean towards number 1. Number 2 seems more efficient and easier, but user results are more important to me.


问:
Binding database resultset array into a comma seperated string in php
I have an array which is an output of a database query like this(in JSON format) :

```<code>[
 {
  "id":1,
  "name":"Category group sidebar",
  "location":"category_group_sidebar",
  "width":250,
  "height":225
  },
{
  "id":2,
  "name":"Category sidebar",
  "location":"category_sidebar",
  "width":250,
  "height":225
  }
]
</code>```

I want this result to be appended with following string and results to be comma separated as following:

```<code>The ad space names are Category group sidebar,Category sidebar and the dimensions are 250,225
</code>```

答:
This will take all properties found within the array of each array, join the inner array by space, the outer array created by array_map will be joined with comma. </p>

```<code>$jsonData = json_decode($yourJsonData, true);
$output = implode(", ", array_map($jsonData, function(item) { return implode(" ", $item); });
</code>```

Body:
I have an array which is an output of a database query like this(in JSON format) :

[
 {
  "id":1,
  "name":"Category group sidebar",
  "location":"category_group_sidebar",
  "width":250,
  "height":225
  },
{
  "id":2,
  "name":"Category sidebar",
  "location":"category_sidebar",
  "width":250,
  "height":225
  }
]

I want this result to be appended with following string and results to be comma separated as following:

The ad space names are Category group sidebar,Category sidebar and the dimensions are 250,225

Body:
This will take all properties found within the array of each array, join the inner array by space, the outer array created by array_map will be joined with comma.

$jsonData = json_decode($yourJsonData, true);
$output = implode(", ", array_map($jsonData, function(item) { return implode(" ", $item); });


问:
How to know the Octal Permission of a file
In my Java application , I am running following command to get the Octal permission and file name.

```<code>stat -c "%a %n" <file name>
</code>```

This command works on Linux but the Solaris version I have doesnt have stat command supported.

How can I achieve this with a command which works on both Linux and Solaris
There are some options with perl stat but unfortunately I cant use perl.

答:
You can achieve same thing using find command

```<code>find <file name> -printf "%m %f"

find <directory name> -maxdepth 0 -printf "%m %f"
</code>```

Example:

```<code>find /etc/passwd -printf "%m %f"

find /etc -maxdepth 0 -printf "%m %f"
</code>```

Body:
In my Java application , I am running following command to get the Octal permission and file name.

stat -c "%a %n" <file name>

This command works on Linux but the Solaris version I have doesnt have stat command supported.

How can I achieve this with a command which works on both Linux and Solaris
There are some options with perl stat but unfortunately I cant use perl.

Body:
You can achieve same thing using find command

find <file name> -printf "%m %f"

find <directory name> -maxdepth 0 -printf "%m %f"

Example:

find /etc/passwd -printf "%m %f"

find /etc -maxdepth 0 -printf "%m %f"


问:
Oracle SQL OR AND Statement
I have a requirement like below where text in "" are passed from user

If  users chose “Tutte le Attività” no filters on this.
If users  chose “Solo Attività senza Impatto EHS” then  JOBPLAN.PRIORITY = null or JOBPLAN.PRIORITY <> 9
If users chose “Solo Attività con Impatto EHS” then JOBPLAN.PRIORITY = 9

I have written below code :
where condition ...

```<code>AND (('Tutte le Attività' = (:IMP))
  OR ('Solo Attività senza Impatto EHS' = (:IMP) and TAB1.PRI IS NULL OR TAB1.PRI NOT IN ('9'))
  OR ('Solo Attività con Impatto EHS' = (:IMP) and TAB1.PRI IN ('9')))
</code>```

Where IMP are bind variables.

For some reason second condition is getting failed.

is my code right?

答:
AND has precedence over OR. So you need more parentheses:

```<code>OR ('Solo Attività senza Impatto EHS' = :IMP
    and (TAB1.PRI IS NULL OR TAB1.PRI NOT IN ('9'))
   )
</code>```

Title: Oracle SQL OR AND Statement

Body:
I have a requirement like below where text in "" are passed from user

If  users chose “Tutte le Attività” no filters on this.
If users  chose “Solo Attività senza Impatto EHS” then  JOBPLAN.PRIORITY = null or JOBPLAN.PRIORITY <> 9
If users chose “Solo Attività con Impatto EHS” then JOBPLAN.PRIORITY = 9

I have written below code :
where condition ...

AND (('Tutte le Attività' = (:IMP))
  OR ('Solo Attività senza Impatto EHS' = (:IMP) and TAB1.PRI IS NULL OR TAB1.PRI NOT IN ('9'))
  OR ('Solo Attività con Impatto EHS' = (:IMP) and TAB1.PRI IN ('9')))

Where IMP are bind variables.

For some reason second condition is getting failed.

is my code right?

Body:
AND has precedence over OR. So you need more parentheses:

OR ('Solo Attività senza Impatto EHS' = :IMP
    and (TAB1.PRI IS NULL OR TAB1.PRI NOT IN ('9'))
   )


答:
```<code>$array = json_decode($json_array);
foreach ($array as $key => $value) {
 if(!isset($str)){
   $str= $value['name'];
 }else{
   $str= ",".$value['name'];
 }
}
$string = "The ad space names are ".$str" and the dimensions are 250,225";
echo $string;
</code>```

Title: Binding database resultset array into a comma seperated string in php


问:
wpf controltemplate is applied to window,and how to add controls
i have defined a controltemplate that is used to windows ,then windows have the same view as basically.

after that ,i should add different controls in different windows. and i have no idea how to add the elements' host in controltemplate to hold different parts of controls which likes the picture bellow.

and one more thing, how to access the controls and how to set the buttons' actions in controltemplate of different window? it should be use a windowBase class to do that ?

first .the screen picture

and the control template file

```<code><ImageSource x:Key="BtnCloseNormal">../images/others/popup_btn_reduction_normal.png</ImageSource>
<ImageSource x:Key="BtnCloseMouseOver">../images/others/popup_btn_reduction_mouseover.png</ImageSource>
<ImageSource x:Key="BtnClosePressed">../images/others/popup_btn_reduction_selected.png</ImageSource>

<Style x:Key="StatedButtonStyle" TargetType="{x:Type c:StatedButton}">
    <Setter Property="Template">
        <Setter.Value>
            <ControlTemplate TargetType="{x:Type c:StatedButton}" >
                <Grid>
                    <Border>
                        <Image x:Name ="btnImg" Source="{Binding NormalBackground ,RelativeSource={RelativeSource TemplatedParent}}" Stretch="Fill"/>
                    </Border>
                    <ContentPresenter HorizontalAlignment="Center" VerticalAlignment="Center"></ContentPresenter>
                </Grid>
                <ControlTemplate.Triggers>
                    <Trigger Property="IsMouseOver" Value="True">
                        <Setter TargetName="btnImg" Property="Source"  Value="{Binding MouseOverBackground ,RelativeSource={RelativeSource TemplatedParent}}"/>
                    </Trigger>
                    <Trigger Property="IsPressed" Value="True">
                        <Setter TargetName="btnImg" Property="Source"  Value="{Binding PressedBackground ,RelativeSource={RelativeSource TemplatedParent}}"/>
                    </Trigger>
                </ControlTemplate.Triggers>
            </ControlTemplate>
        </Setter.Value>
    </Setter>
</Style>

<Style x:Key="WindowBaseStyle" TargetType="{x:Type Window}">
    <Setter Property="Background" Value="{x:Null}"></Setter>
    <Setter Property="AllowsTransparency" Value="True"></Setter>
    <Setter Property="WindowStyle" Value="None"></Setter>
    <Setter Property="Template">
        <Setter.Value>
            <ControlTemplate TargetType="{x:Type Window}">
                <Grid Background="{x:Null}">
                    <Border CornerRadius="10" Background="White" Margin="20">
                        <Border.Effect>
                            <DropShadowEffect BlurRadius="10" Color="Black" Direction="270" ShadowDepth="5" RenderingBias="Quality" Opacity="0.6"></DropShadowEffect>
                        </Border.Effect>
                        <Grid>
                            <Grid.RowDefinitions>
                                <RowDefinition Height="40"/>
                                <RowDefinition Height="10"/>
                                <RowDefinition/>
                                <RowDefinition Height="40"/>
                                <RowDefinition Height="20"/>
                            </Grid.RowDefinitions>
                            <Grid Grid.Row="0">
                                <Grid.ColumnDefinitions>
                                    <ColumnDefinition Width="2*"/>
                                    <ColumnDefinition Width="*"/>
                                    <ColumnDefinition Width="40"/>
                                    <ColumnDefinition Width="40"/>
                                    <ColumnDefinition Width="60"/>
                                </Grid.ColumnDefinitions>
                                <Label x:Name="lblTitle" Grid.Column="0" Margin="20,6,0,0" FontSize="18" FontWeight="Bold"
                                       Content="{TemplateBinding Title}">
                                </Label>
                                <c:StatedButton Grid.Column="2" Width="30" Height="30" Style="{StaticResource StatedButtonStyle}"
                                                    NormalBackground="{StaticResource BtnCloseNormal}"
                                                    MouseOverBackground="{DynamicResource BtnCloseMouseOver}"
                                                    PressedBackground="{StaticResource BtnClosePressed}"/>
                                <c:StatedButton Grid.Column="3" Width="30" Height="30" Style="{StaticResource StatedButtonStyle}"
                                                    NormalBackground="{StaticResource BtnCloseNormal}"
                                                    MouseOverBackground="{DynamicResource BtnCloseMouseOver}"
                                                    PressedBackground="{StaticResource BtnClosePressed}"/>
                                <c:StatedButton Grid.Column="4" Width="30" Height="30" Style="{StaticResource StatedButtonStyle}"
                                                    NormalBackground="{StaticResource BtnCloseNormal}"
                                                    MouseOverBackground="{DynamicResource BtnCloseMouseOver}"
                                                    PressedBackground="{StaticResource BtnClosePressed}"/>
                            </Grid>
                            <Separator Background="LightGray" Grid.Row="1" Height="2"></Separator>
                            <Grid Grid.Row="2">
                                <!--some controls will be insert here-->
                            </Grid>
                            <Grid Grid.Row="3" Background="Red" >
                                <!--some controls will be insert here-->
                                <ContentControl Content="{Binding }"></ContentControl>
                            </Grid>
                        </Grid>
                    </Border>
                </Grid>
            </ControlTemplate>
        </Setter.Value>
    </Setter>
</Style>
</code>```

and the window.xaml

```<code><Window x:Class="WpfApp1.Window1"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    xmlns:local="clr-namespace:WpfApp1"
    xmlns:uctrls="clr-namespace:WpfApp1.Uctrls"
    mc:Ignorable="d"
    Style="{StaticResource WindowBaseStyle}"
    Title="Window1 -- title" Height="300" Width="500">
<Grid>
    <Label x:Name="lblTitle" Content="title"></Label>
    <Button x:Name="BtnTest" Content="Get TextBox1" Click="BtnTestClick"></Button>
    <uctrls:UserControlBase>
        <Grid>
            <Button Content="what "></Button>
        </Grid>
    </uctrls:UserControlBase>
</Grid>
</code>```

答:
i have done it myself.
just use code bellow to host new controls

```<code><AdornerDecorator>
     <contentpresenter/>
</AdornerDecorator>
</code>```

and create a windowBase as parent class of new windows.

Body:
i have defined a controltemplate that is used to windows ,then windows have the same view as basically.

after that ,i should add different controls in different windows. and i have no idea how to add the elements' host in controltemplate to hold different parts of controls which likes the picture bellow.

and one more thing, how to access the controls and how to set the buttons' actions in controltemplate of different window? it should be use a windowBase class to do that ?

first .the screen picture

and the control template file

<ImageSource x:Key="BtnCloseNormal">../images/others/popup_btn_reduction_normal.png</ImageSource>
<ImageSource x:Key="BtnCloseMouseOver">../images/others/popup_btn_reduction_mouseover.png</ImageSource>
<ImageSource x:Key="BtnClosePressed">../images/others/popup_btn_reduction_selected.png</ImageSource>

and the window.xaml

<Window x:Class="WpfApp1.Window1"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    xmlns:local="clr-namespace:WpfApp1"
    xmlns:uctrls="clr-namespace:WpfApp1.Uctrls"
    mc:Ignorable="d"
    Style="{StaticResource WindowBaseStyle}"
    Title="Window1 -- title" Height="300" Width="500">
<Grid>

    <Button x:Name="BtnTest" Content="Get TextBox1" Click="BtnTestClick"></Button>
    <uctrls:UserControlBase>
        <Grid>
            <Button Content="what "></Button>
        </Grid>
    </uctrls:UserControlBase>
</Grid>

Body:
i have done it myself.
just use code bellow to host new controls

<AdornerDecorator>
     <contentpresenter/>
</AdornerDecorator>

and create a windowBase as parent class of new windows.


问:
Css Table-cell and relative width
I'm struggling with a CSS issue and I was hoping for some help.

Here's the story:

I'm designing a header. It's split in two divs. First one must be 70% wide and second one 30% wide. I used the css-property "Display: table-cell" in order to place them side by side.

```<code>div.chapo {
width: 70%;
display: table-cell;
}

div.img_header {
width: 30%;
display: table-cell;
background-position: center center;
background-repeat: no-repeat;
background-size: cover;
-webkit-background-size: cover;
background-image: url(...);
}
</code>```

It's working fine when the text placed in the first div is long enough:

Buuuut... when text is short, it's all messy:

I can't figure out why my widths values aren't kept in this specific case.

Thanks in advance for all who would be kind enough to help me...

Here's the fiddle link: https://jsfiddle.net/vinny38/verucw8p/3/

答:
Try like this:
You have to define float property as well as you must define height:255px  (as for another div you have given height as 255px )for your img_header class. It's really necessary.

body,
div {
  margin: 0;
  padding: 0;
  font-family: 'Roboto condensed', sans-serif;
  box-sizing: border-box
}

div.inside {
  position: relative;
}

div.chapo {
  background-color: #ef4056;
  background-image: none;
  width: 70%;
  float:left;
  height: 255px;
  display: table-cell;
  vertical-align: top;
  background-color: #aaa;
  color: #fff;
  padding: 20px 8%;
  position: relative;
}

h1 {
  margin-top: 0;
  font: 1.4em 'Oswald', Helvetica, sans-serif;
  font-weight: bold;
  text-transform: uppercase;
}

div.chapo p {
  width: 100%;
  min-width: 100%;
  position: relative;
  padding: 0;
  font-size: 1em;
  font-weight: 300;
}
.clearfix {
  clear:both;
}
.img_header {
  width: 30%;
height: 255px;
  float: right;
  position: relative;
  display: table-cell;
  vertical-align: top;
  background-position: center center;
  background-repeat: no-repeat;
  background-size: cover;
  -webkit-background-size: cover;
  background-image: url(https://image.freepik.com/free-psd/abstract-background-design_1297-73.jpg);
}

div.mod_breadcrumb {
  height: 40px;
  margin: 0;
  padding-top: 5px;
  padding-right: 30px;
  padding-bottom: 5px;
  background-color: #e3e3e3;
  padding-left: 8%;
}

.mod_breadcrumb ul li {
  height: 30px;
  display: inline-block;
  padding: 3px 0;
  color: #828282;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="inside">
  <div class="ce_text chapo">

    <div class='text-chapo'>
    <h1>My header</h1>
      <p>Lorem </p>
      <p>Aliquam porttitor.</p>
    </div>
  </div>

  <div class="img_header"></div>

  <div class="mod_breadcrumb block">
    <ul>
      <li></li>
      <li></li>
      <li></li>
    </ul>
  </div>
</div>
<div class="clearfix"></div></code>```

Title: Css Table-cell and relative width

Body:
I'm struggling with a CSS issue and I was hoping for some help.

Here's the story:

I'm designing a header. It's split in two divs. First one must be 70% wide and second one 30% wide. I used the css-property "Display: table-cell" in order to place them side by side.

div.chapo {
width: 70%;
display: table-cell;
}

div.img_header {
width: 30%;
display: table-cell;
background-position: center center;
background-repeat: no-repeat;
background-size: cover;
-webkit-background-size: cover;
background-image: url(...);
}

It's working fine when the text placed in the first div is long enough:

Buuuut... when text is short, it's all messy:

I can't figure out why my widths values aren't kept in this specific case.

Thanks in advance for all who would be kind enough to help me...

Here's the fiddle link: https://jsfiddle.net/vinny38/verucw8p/3/

Body:
Try like this:
You have to define float property as well as you must define height:255px  (as for another div you have given height as 255px )for your img_header class. It's really necessary.

body,
div {
  margin: 0;
  padding: 0;
  font-family: 'Roboto condensed', sans-serif;
  box-sizing: border-box
}

div.inside {
  position: relative;
}

div.chapo {
  background-color: #ef4056;
  background-image: none;
  width: 70%;
  float:left;
  height: 255px;
  display: table-cell;
  vertical-align: top;
  background-color: #aaa;
  color: #fff;
  padding: 20px 8%;
  position: relative;
}

h1 {
  margin-top: 0;
  font: 1.4em 'Oswald', Helvetica, sans-serif;
  font-weight: bold;
  text-transform: uppercase;
}

div.chapo p {
  width: 100%;
  min-width: 100%;
  position: relative;
  padding: 0;
  font-size: 1em;
  font-weight: 300;
}
.clearfix {
  clear:both;
}
.img_header {
  width: 30%;
height: 255px;
  float: right;
  position: relative;
  display: table-cell;
  vertical-align: top;
  background-position: center center;
  background-repeat: no-repeat;
  background-size: cover;
  -webkit-background-size: cover;
  background-image: url(https://image.freepik.com/free-psd/abstract-background-design_1297-73.jpg);
}

div.mod_breadcrumb {
  height: 40px;
  margin: 0;
  padding-top: 5px;
  padding-right: 30px;
  padding-bottom: 5px;
  background-color: #e3e3e3;
  padding-left: 8%;
}

.mod_breadcrumb ul li {
  height: 30px;
  display: inline-block;
  padding: 3px 0;
  color: #828282;
}

<div class="inside">
  <div class="ce_text chapo">

    <div class='text-chapo'>
    <h1>My header</h1>
      <p>Lorem </p>
      <p>Aliquam porttitor.</p>
    </div>
  </div>

  <div class="img_header"></div>

  <div class="mod_breadcrumb block">
    <ul>
      <li></li>
      <li></li>
      <li></li>
    </ul>
  </div>
</div>
<div class="clearfix"></div>


问:
Create a List of Sentences based on Multiple Arrays of Integers and Words
I am trying to generate a list of strings from all possible combinations of multiple arrays.

```<code>l = ''

zero = [2, 3, 4, 5, 6]
one = ['boys', 'girls', 'pythons', 'baddies']
three = ['the', 'grandmas', 'bunny's']

# Do something with i, j, k. Iterate...
s = '{0!s} apples brings all the {1} to {2} yard'.format(zero[i], one[j], two[k])
l = l + s + '\n'
</code>```

Expected output, l:

```<code>2 apples brings all the boys to the yard
3 apples brings all the boys to the yard
...
...
5 apples brings all the baddies to bunny's yard
6 apples brings all the baddies to bunny's yard
</code>```

How can I generate a list that exhausts all possible i, j, k, combinations? The above is just an example. In the real world I have seven variables ([i] - [o]).

答:
try itertools for finding combinations,

```<code>import itertools

l = ''

zero = [2, 3, 4, 5, 6]
one = ['boys', 'girls', 'pythons', 'baddies']
three = ['the', 'grandmas', 'bunny\'s']
s = '{0!s} apples brings all the {1} to {2} yard'

for combination in itertools.product(zero, one, three):
    l = l + s.format(combination[0], combination[1], combination[2]) + '\n'
print(l)
</code>```

output:

```<code>2 apples brings all the boys to the yard
2 apples brings all the boys to grandmas yard
2 apples brings all the boys to bunnys yard
2 apples brings all the girls to the yard
2 apples brings all the girls to grandmas yard
2 apples brings all the girls to bunnys yard
2 apples brings all the pythons to the yard
2 apples brings all the pythons to grandmas yard
2 apples brings all the pythons to bunnys yard
2 apples brings all the baddies to the yard
2 apples brings all the baddies to grandmas yard
2 apples brings all the baddies to bunnys yard
3 apples brings all the boys to the yard
3 apples brings all the boys to grandmas yard
3 apples brings all the boys to bunnys yard
3 apples brings all the girls to the yard
3 apples brings all the girls to grandmas yard
3 apples brings all the girls to bunnys yard
3 apples brings all the pythons to the yard
3 apples brings all the pythons to grandmas yard
3 apples brings all the pythons to bunnys yard
3 apples brings all the baddies to the yard
3 apples brings all the baddies to grandmas yard
3 apples brings all the baddies to bunnys yard
4 apples brings all the boys to the yard
4 apples brings all the boys to grandmas yard
4 apples brings all the boys to bunnys yard
4 apples brings all the girls to the yard
4 apples brings all the girls to grandmas yard
4 apples brings all the girls to bunnys yard
4 apples brings all the pythons to the yard
4 apples brings all the pythons to grandmas yard
4 apples brings all the pythons to bunnys yard
4 apples brings all the baddies to the yard
4 apples brings all the baddies to grandmas yard
4 apples brings all the baddies to bunnys yard
5 apples brings all the boys to the yard
5 apples brings all the boys to grandmas yard
5 apples brings all the boys to bunnys yard
5 apples brings all the girls to the yard
5 apples brings all the girls to grandmas yard
5 apples brings all the girls to bunnys yard
5 apples brings all the pythons to the yard
5 apples brings all the pythons to grandmas yard
5 apples brings all the pythons to bunnys yard
5 apples brings all the baddies to the yard
5 apples brings all the baddies to grandmas yard
5 apples brings all the baddies to bunnys yard
6 apples brings all the boys to the yard
6 apples brings all the boys to grandmas yard
6 apples brings all the boys to bunnys yard
6 apples brings all the girls to the yard
6 apples brings all the girls to grandmas yard
6 apples brings all the girls to bunnys yard
6 apples brings all the pythons to the yard
6 apples brings all the pythons to grandmas yard
6 apples brings all the pythons to bunnys yard
6 apples brings all the baddies to the yard
6 apples brings all the baddies to grandmas yard
6 apples brings all the baddies to bunnys yard
</code>```

Body:
I am trying to generate a list of strings from all possible combinations of multiple arrays.

l = ''

zero = [2, 3, 4, 5, 6]
one = ['boys', 'girls', 'pythons', 'baddies']
three = ['the', 'grandmas', 'bunny's']

# Do something with i, j, k. Iterate...
s = '{0!s} apples brings all the {1} to {2} yard'.format(zero[i], one[j], two[k])
l = l + s + '\n'

Expected output, l:

2 apples brings all the boys to the yard
3 apples brings all the boys to the yard
...
...
5 apples brings all the baddies to bunny's yard
6 apples brings all the baddies to bunny's yard

How can I generate a list that exhausts all possible i, j, k, combinations? The above is just an example. In the real world I have seven variables ([i] - [o]).

Body:
try itertools for finding combinations,

import itertools

l = ''

zero = [2, 3, 4, 5, 6]
one = ['boys', 'girls', 'pythons', 'baddies']
three = ['the', 'grandmas', 'bunny\'s']
s = '{0!s} apples brings all the {1} to {2} yard'

for combination in itertools.product(zero, one, three):
    l = l + s.format(combination[0], combination[1], combination[2]) + '\n'
print(l)

output:

2 apples brings all the boys to the yard
2 apples brings all the boys to grandmas yard
2 apples brings all the boys to bunnys yard
2 apples brings all the girls to the yard
2 apples brings all the girls to grandmas yard
2 apples brings all the girls to bunnys yard
2 apples brings all the pythons to the yard
2 apples brings all the pythons to grandmas yard
2 apples brings all the pythons to bunnys yard
2 apples brings all the baddies to the yard
2 apples brings all the baddies to grandmas yard
2 apples brings all the baddies to bunnys yard
3 apples brings all the boys to the yard
3 apples brings all the boys to grandmas yard
3 apples brings all the boys to bunnys yard
3 apples brings all the girls to the yard
3 apples brings all the girls to grandmas yard
3 apples brings all the girls to bunnys yard
3 apples brings all the pythons to the yard
3 apples brings all the pythons to grandmas yard
3 apples brings all the pythons to bunnys yard
3 apples brings all the baddies to the yard
3 apples brings all the baddies to grandmas yard
3 apples brings all the baddies to bunnys yard
4 apples brings all the boys to the yard
4 apples brings all the boys to grandmas yard
4 apples brings all the boys to bunnys yard
4 apples brings all the girls to the yard
4 apples brings all the girls to grandmas yard
4 apples brings all the girls to bunnys yard
4 apples brings all the pythons to the yard
4 apples brings all the pythons to grandmas yard
4 apples brings all the pythons to bunnys yard
4 apples brings all the baddies to the yard
4 apples brings all the baddies to grandmas yard
4 apples brings all the baddies to bunnys yard
5 apples brings all the boys to the yard
5 apples brings all the boys to grandmas yard
5 apples brings all the boys to bunnys yard
5 apples brings all the girls to the yard
5 apples brings all the girls to grandmas yard
5 apples brings all the girls to bunnys yard
5 apples brings all the pythons to the yard
5 apples brings all the pythons to grandmas yard
5 apples brings all the pythons to bunnys yard
5 apples brings all the baddies to the yard
5 apples brings all the baddies to grandmas yard
5 apples brings all the baddies to bunnys yard
6 apples brings all the boys to the yard
6 apples brings all the boys to grandmas yard
6 apples brings all the boys to bunnys yard
6 apples brings all the girls to the yard
6 apples brings all the girls to grandmas yard
6 apples brings all the girls to bunnys yard
6 apples brings all the pythons to the yard
6 apples brings all the pythons to grandmas yard
6 apples brings all the pythons to bunnys yard
6 apples brings all the baddies to the yard
6 apples brings all the baddies to grandmas yard
6 apples brings all the baddies to bunnys yard

ContentLicense: CC BY-SA 4.0