问:
how to close popup window when I called it in other function
I'm defined $modal.open({{..}) in function A and return the result.
then I'm using it in other function and i want to close the popup window in the other function..how I do it?

For example :

```<code>    function A( x, y)
       {
        var a = $modal.open({{..})
        return a.result ;
    }

    function B ( z,w,t)
    {

    // using function A to open the modal
        A(x1, y1).then(
            function (result1){
            // I want to close the popup window here
        });

}
</code>```

答:
We have added "isOpen" variable, by default false. when user will call function A, then true value will assign to this.
whenever user will call the another function, we are checking to isOpen value, then model object will be close.
You can try for this:

```<code>var isOpen=false;
function A( x, y)
   {
    var a = $modal.open({{..});
    isOpen=true;
    return a.result ;
}

function B ( z,w,t)
{
    A(x1, y1).then(
        function (result1){
        if(isOpen){
        $model.close(); // close popup window here:
        }
    });
</code>```

}

Body:
I'm defined $modal.open({{..}) in function A and return the result.
then I'm using it in other function and i want to close the popup window in the other function..how I do it?

For example :

    function A( x, y)
       {
        var a = $modal.open({{..})
        return a.result ;
    }

    function B ( z,w,t)
    {

    // using function A to open the modal
        A(x1, y1).then(
            function (result1){
            // I want to close the popup window here
        });

}

Body:
We have added "isOpen" variable, by default false. when user will call function A, then true value will assign to this.
whenever user will call the another function, we are checking to isOpen value, then model object will be close.
You can try for this:

var isOpen=false;
function A( x, y)
   {
    var a = $modal.open({{..});
    isOpen=true;
    return a.result ;
}

function B ( z,w,t)
{
    A(x1, y1).then(
        function (result1){
        if(isOpen){
        $model.close(); // close popup window here:
        }
    });

}


来源: stackexchange

问:
Contribute a Ionic 3 App to F-Droid
I'd like to contribute to the F-Droid GitLab Repo.

I followed this guide: https://gitlab.com/fdroid/fdroiddata/blob/master/CONTRIBUTING.md

I have done this already, many times with a normal native app. That worked great. But with an Ionic app it seems to be different. I see, for example, no gradle data in my Ionic app. Do I need gradle? Because the build failed because he can not run gradle clean ..

Heres my stack:

==== detail begin ==== FAILURE: Build failed with an exception.

What went wrong: Task 'clean' not found in root project.

This is how my metadata file looks like:

```<code>Categories:System
License:GPL-3.0
</code>```

[...]

```<code>Repo Type:git
Repo:<Repo Link>

Build:1.0,1
    commit=<commit>
    gradle=yes

Auto Update Mode:None
Update Check Mode:None
</code>```

Everything in <> is filled out correctly.

答:
You are forging new ground here!  We (F-Droid) don't have solid support for Cordoba/Ionic/etc.  but the only thing preventing it is someone doing the work!  We're working on adding a new build field sudo= which will let you download and install whatever you need to run your build.  I've never used Ionic, Cordoba, or any of these Javascript app things, so I don't know the details.

You can follow the progress of sudo= here:
https://gitlab.com/fdroid/fdroidserver/merge_requests/297

It'll still be a while yet before this is deployed on our infrastructure, but your testing it will speed up that process!

ContentLicense: CC BY-SA 3.0

Title: Contribute a Ionic 3 App to F-Droid

Body:
I'd like to contribute to the F-Droid GitLab Repo.

I followed this guide: https://gitlab.com/fdroid/fdroiddata/blob/master/CONTRIBUTING.md

I have done this already, many times with a normal native app. That worked great. But with an Ionic app it seems to be different. I see, for example, no gradle data in my Ionic app. Do I need gradle? Because the build failed because he can not run gradle clean ..

Heres my stack:

==== detail begin ==== FAILURE: Build failed with an exception.

What went wrong: Task 'clean' not found in root project.

This is how my metadata file looks like:

Categories:System
License:GPL-3.0

[...]

Repo Type:git
Repo:<Repo Link>

Build:1.0,1
    commit=<commit>
    gradle=yes

Auto Update Mode:None
Update Check Mode:None

Everything in <> is filled out correctly.


问:
GitHub Cloning sub projects Separately
I would like to have a multi module project in GitHub where each sub module can be clones separately. For example.,

```<code>my_project
 -- project-1
 -- project-2
</code>```

So each of those project should have a separate clonable GitHub url and at the same time if I would like to clone the entire repository, I could do so with cloning the top level my_project.

I'm not sure how to do this. I came across submodules and I'm not suite sure if this is the right thing.

All I understand about sub-modules is that I can attach an already existing repository to be part of my other repository. Is this correct? But I want to be able to create new repository from within my top project. Any ideas on where to look at?

答:
The first thing that comes to my mind are dependencies (your submodules). Here is how they are used (SO post)  and here is how they work internally (git documentation)

For seperate GitHub URLs you would need seperate projects/ repositories wich you couldn´t clone at once (execpt with a script...).

Maybe you could think about hosting your own git server and manage it that you can download every single sub-repo with a specific url and all at once with another url. I think -not tested- you could do this by file structure like you mentioned:

```<code>my_project (git repo)
 -- project-1 (git repo)
 -- project-2 (git repo)
</code>```

Title: GitHub Cloning sub projects Separately

Body:
I would like to have a multi module project in GitHub where each sub module can be clones separately. For example.,

my_project
 -- project-1
 -- project-2

So each of those project should have a separate clonable GitHub url and at the same time if I would like to clone the entire repository, I could do so with cloning the top level my_project.

I'm not sure how to do this. I came across submodules and I'm not suite sure if this is the right thing.

All I understand about sub-modules is that I can attach an already existing repository to be part of my other repository. Is this correct? But I want to be able to create new repository from within my top project. Any ideas on where to look at?

Body:
The first thing that comes to my mind are dependencies (your submodules). Here is how they are used (SO post)  and here is how they work internally (git documentation)

For seperate GitHub URLs you would need seperate projects/ repositories wich you couldn´t clone at once (execpt with a script...).

Maybe you could think about hosting your own git server and manage it that you can download every single sub-repo with a specific url and all at once with another url. I think -not tested- you could do this by file structure like you mentioned:

my_project (git repo)
 -- project-1 (git repo)
 -- project-2 (git repo)


问:
Add JavaScript object to JavaScript object
I'd like to have JavaScript objects within another JavaScript object as such:

```<code>Issues:

  - {"ID" : "1", "Name" : "Missing Documentation", "Notes" : "Issue1 Notes"}
  - {"ID" : "2", "Name" : "Software Bug", "Notes" : "Issue2 Notes, blah, blah"}
  - {"ID" : "2", "Name" : "System Not Ready", "Notes" : "Issue3 Notes, etc"}
  // etc...
</code>```

So, I'd like "Issues" to hold each of these JavaScript objects, so that I can just say Issues[0].Name, or Issues[2].ID, etc.

I've created the outer Issues JavaScript object:

```<code>var jsonIssues = {};
</code>```

I'm to the point where I need to add a JavaScript object to it, but don't know how. I'd like to be able to say:

```<code>Issues<code here>.Name = "Missing Documentation";
Issues<code here>.ID = "1";
Issues<code here>.Notes = "Notes, notes notes";
</code>```

Is there any way to do this? Thanks.

UPDATE: Per answers given, declared an array, and am pushing JavaScript objects on as needed:

```<code>var jsonArray_Issues = new Array();

jsonArray_Issues.push( { "ID" : id, "Name" : name, "Notes" : notes } );
</code>```

Thanks for the responses.

答:
As my first object is a native JavaScript object (used like a list of objects), push didn't work in my scenario, but I resolved it by adding new key as follows:

```<code>MyObjList['newKey'] = obj;
</code>```

In addition to this, may be useful to know how to delete the same object as inserted before:

```<code>delete MyObjList['newKey'][id];
</code>```

Hope it helps someone as it helped me.

ContentLicense: CC BY-SA 2.5

Body:
I'd like to have JavaScript objects within another JavaScript object as such:

Issues:

  - {"ID" : "1", "Name" : "Missing Documentation", "Notes" : "Issue1 Notes"}
  - {"ID" : "2", "Name" : "Software Bug", "Notes" : "Issue2 Notes, blah, blah"}
  - {"ID" : "2", "Name" : "System Not Ready", "Notes" : "Issue3 Notes, etc"}
  // etc...

So, I'd like "Issues" to hold each of these JavaScript objects, so that I can just say Issues[0].Name, or Issues[2].ID, etc.

I've created the outer Issues JavaScript object:

var jsonIssues = {};

I'm to the point where I need to add a JavaScript object to it, but don't know how. I'd like to be able to say:

Issues.Name = "Missing Documentation";
Issues.ID = "1";
Issues.Notes = "Notes, notes notes";

Is there any way to do this? Thanks.

UPDATE: Per answers given, declared an array, and am pushing JavaScript objects on as needed:

var jsonArray_Issues = new Array();

jsonArray_Issues.push( { "ID" : id, "Name" : name, "Notes" : notes } );

Thanks for the responses.

Body:
As my first object is a native JavaScript object (used like a list of objects), push didn't work in my scenario, but I resolved it by adding new key as follows:

MyObjList['newKey'] = obj;

In addition to this, may be useful to know how to delete the same object as inserted before:

delete MyObjList['newKey'][id];

Hope it helps someone as it helped me.

ContentLicense: CC BY-SA 4.0


问:
Is it possible to send SILENT LOCAL notification on iOS
My app wakes up from suspended mode on silent remote notification from a server, exactly as I want. This server sends a push notification with "content-available:1", which does the job.

Now I want to do this without the help of a server and so I want to send silent local notifications (from the app) at a time in the future (like after 15 min.), but can't find a way to set "content-available:1". So I end up getting local notification that doesn't wake up my app, as I can with remote notification.

I've searched for information and all I can find are examples of interactive notifications and how to set title, body, alert and triggers (based on location, date and so on.). But nothing about how to set content-available property.

So, is possible to set content-available for local notifications?

答:
The notification should be silent if you don't set all of this values:</p>

```<code>notification.alertBody = message;
notification.alertAction = @"Show";
notification.category = @"ACTION";
notification.soundName = UILocalNotificationDefaultSoundName;
</code>```

Body:
The notification should be silent if you don't set all of this values:

notification.alertBody = message;
notification.alertAction = @"Show";
notification.category = @"ACTION";
notification.soundName = UILocalNotificationDefaultSoundName;


问:
stdio.h in Visual Studio
I was wondering in which folder on my computer is stdio.h file placed. I have Windows 10, and Visual Studio 2015 (32 - bit) installed on my computer. Visual Studio includes tools for writing, compiling and executing C programs, so i think that it also must have stdio.h contained somewhere, am I right? I tried searching for stdio.h in folder C:\Program Files(x86)\Microsoft Visual Studio 14.0\VC and all of it's subfolders, but with no success. I would very appreciate if anyone could give me some guidelines or a solution to this problem. </p>

<p>Thank you in advanced for your time and answers! </p>

答:
"The headers, sources, and libraries are now distributed as part of a separate
Universal CRT SDK. This SDK is included with Visual Studio; it is installed by
default to C:\Program Files (x86)\Windows Kits\10."</p>

Title: stdio.h in Visual Studio

Body:
I was wondering in which folder on my computer is stdio.h file placed. I have Windows 10, and Visual Studio 2015 (32 - bit) installed on my computer. Visual Studio includes tools for writing, compiling and executing C programs, so i think that it also must have stdio.h contained somewhere, am I right? I tried searching for stdio.h in folder C:\Program Files(x86)\Microsoft Visual Studio 14.0\VC and all of it's subfolders, but with no success. I would very appreciate if anyone could give me some guidelines or a solution to this problem.

Thank you in advanced for your time and answers!


问:
throw new exception("Test"); does not throw my text
```<code>throw new Exception("Test");
</code>```

only Throws

I can't get my Text in there...

I also tried

```<code>throw new ArgumentException("Test");
</code>```

and with a try catch and without.

But it is my written throw that makes the window.

Edit:
Im working my way around so it is not possible that the throw comes.

答:
You will need to catch the exception and extract the message to display.

```<code>try
{
     //Your code here
}
catch(Exception e)
{
     var message = e.Message;
     MessageBox.Show(message);
}
</code>```

Body:
throw new Exception("Test");

only Throws

I can't get my Text in there...

I also tried

throw new ArgumentException("Test");

and with a try catch and without.

But it is my written throw that makes the window.

Edit:
Im working my way around so it is not possible that the throw comes.

Body:
You will need to catch the exception and extract the message to display.

try
{
     //Your code here
}
catch(Exception e)
{
     var message = e.Message;
     MessageBox.Show(message);
}


问:
Rename the file within each folder regardless of extension
So I have folders with different date, I was trying add the date of each folder to the image inside the folder.
My code looks like this:

```<code>import os, sys
path = os.path.dirname(sys.argv[0])
folder=[folder for folder in os.listdir(path) if os.path.isdir(folder)]
print(folder)
for n in range(len(folder)):
    for filename in os.listdir(path+"/"+folder[n]):
        os.rename(filename, filename+folder[n])
</code>```

but it give filename like this:
'IMG_6569 copy.png' -> 'IMG_6569 copy.png10May'.
How can I add the date before the file extension? Thanks

答:
You just need to split on the extension and add it after the updated bit like so</p>

```<code>import os, sys
path = os.path.dirname(sys.argv[0])
folder=[folder for folder in os.listdir(path) if os.path.isdir(folder)]
print(folder)
n=0
for n in range(len(folder)):
    for filename in os.listdir(path+"/"+folder[n]):
        name, extension = os.path.splitext(filename)
        os.rename(filename, name + folder[n] + extension)
</code>```

Body:
So I have folders with different date, I was trying add the date of each folder to the image inside the folder.
My code looks like this:

import os, sys
path = os.path.dirname(sys.argv[0])
folder=[folder for folder in os.listdir(path) if os.path.isdir(folder)]
print(folder)
for n in range(len(folder)):
    for filename in os.listdir(path+"/"+folder[n]):
        os.rename(filename, filename+folder[n])

but it give filename like this:
'IMG_6569 copy.png' -> 'IMG_6569 copy.png10May'.
How can I add the date before the file extension? Thanks

Body:
You just need to split on the extension and add it after the updated bit like so

import os, sys
path = os.path.dirname(sys.argv[0])
folder=[folder for folder in os.listdir(path) if os.path.isdir(folder)]
print(folder)
n=0
for n in range(len(folder)):
    for filename in os.listdir(path+"/"+folder[n]):
        name, extension = os.path.splitext(filename)
        os.rename(filename, name + folder[n] + extension)


问:
How do I run a docker container by its container name?
For example once I create a container with name of "duplo":

docker run --name="duplo" -it /bin/bash -c "sudo /build/backup.sh".

How do I execute an additional command within the container after it exits? I can see it listed by docker ps -a.

答:
docker start is the command I was looking for.

docker start -ia duplo


问:
submit form when elements change
In jQuery, if I assign class=auto_submit_form to a form, it will be submitted whenever any element is changed, with the following code:

```<code>/* automatically submit if any element in the form changes */
$(function() {
  $(".auto_submit_form").change(function() {
    this.submit();
  });
});
</code>```

However, if I want to the form to submit only when specified elements are changed:

```<code>/* submit if elements of class=auto_submit_item in the form changes */
$(function() {
  $(".auto_submit_item").change(function() {
    $(this).parents().filter("form").submit();
  });
});
</code>```

I'm just learning jQuery. Is there a better way to do this?

答:
I came up with a generic approach to this:

```<code>$('.autoSubmit, .autoSubmit select, .autoSubmit input, .autoSubmit textarea').change(function () {
    const el = $(this);
    let form;

    if (el.is('form')) { form = el; }
    else { form = el.closest('form'); }

    form.submit();
});
</code>```

All elements of a form:

```<code><form class="autoSubmit">
    <select><option>1</option><option>2</option></select>
</form>
</code>```

Only individual elements

```<code><form>
    <select class="autoSubmit"><option>1</option><option>2</option></select>
</form>
</code>```

OwnerDisplayName: Jeff Bauer

Title: submit form when elements change

Body:
In jQuery, if I assign class=auto_submit_form to a form, it will be submitted whenever any element is changed, with the following code:

/* automatically submit if any element in the form changes */
$(function() {
  $(".auto_submit_form").change(function() {
    this.submit();
  });
});

However, if I want to the form to submit only when specified elements are changed:

/* submit if elements of class=auto_submit_item in the form changes */
$(function() {
  $(".auto_submit_item").change(function() {
    $(this).parents().filter("form").submit();
  });
});

I'm just learning jQuery. Is there a better way to do this?

LastEditorDisplayName: sblundy

Body:
I came up with a generic approach to this:

$('.autoSubmit, .autoSubmit select, .autoSubmit input, .autoSubmit textarea').change(function () {
    const el = $(this);
    let form;

    if (el.is('form')) { form = el; }
    else { form = el.closest('form'); }

    form.submit();
});

All elements of a form:

<form class="autoSubmit">
    <select><option>1</option><option>2</option></select>
</form>

Only individual elements

<form>
    <select class="autoSubmit"><option>1</option><option>2</option></select>
</form>


问:
Can a single EBS be shared across multiple Amazon Docker Containers?
I want to copy some data from S3 to EBS when the FIRST Docker Container spins off. For subsequent spawned Docker Containers, I want to share the data I copied on the EBS. I do not want data to be duplicated for every Docker Container.

Can anyone tell me if a single EBS can be shared across multiple Amazon Docker Containers ?

答:
EBS can only be linked to a single ec2 instance

if you have docker containers spinned on single ec2 instance, it will work

If you have docker containers spinned on a ec2 cluster with multiple ec2 instances, it will not work; an option in such case would be to use EFS


问:
Can't connect to Flask web service, connection refused
I'm trying to run a simple web server on a Raspberry Pi with Flask. When I run my Flask app, it says:

running on http://127.0.0.1:5000/

But when I enter this address on my laptop's in Chrome, I get

ERR_CONNECTION_REFUSED

I can open 127.0.0.1:5000 on the Raspberry Pi's browser. What do I need to do to connect from another computer?

答:
A reason could also be in firewall refusing incoming connections on port 5000. Try:

```<code>sudo ufw allow 5000
</code>```

Body:
A reason could also be in firewall refusing incoming connections on port 5000. Try:

sudo ufw allow 5000


问:
How to make a python project downloaded from github as a frame or package?
such as i download a python project named x-master from github, which comprise a modul named x, and i want use this project just like this:

```<code>import x
from x import ....
</code>```

how should i do on windows??? Appreciate it!

答:
perhaps you have to install it.look and see if setup.py available in project and if use some installation command. you can install it in develop mod or production mod if you want to install it in develop mod use </p>

```<code>pip install -e .
</code>```

<p>and in production mod </p>

```<code>python setup.py install
</code>```

Body:
such as i download a python project named x-master from github, which comprise a modul named x, and i want use this project just like this:

import x
from x import ....

how should i do on windows??? Appreciate it!

Body:
perhaps you have to install it.look and see if setup.py available in project and if use some installation command. you can install it in develop mod or production mod if you want to install it in develop mod use

pip install -e .

and in production mod

python setup.py install


问:
LINQ Group by; How to make it flexible
considering the bit of code at the bottom, this is my problem:

I want to be able to group revenue based on input, e.g.:
- Year
- Month
- Week
- Units
etc.

Do I need to make a var for each combination (and change the Group by accordingly) or can I make something in which the Group by variables are flexible. Meaning that I can get the LocationRevenue on the level of input  for example: week, or month, or year; or year+month together, week+month together or any other combination.

```<code>var locationRevenues = revenues
.GroupBy(g => new { Location = g.Location, Month = DateTimeHelper.GetMonth(g.Date)})
.Select(r => new
{
    Location = r.Key,
    RevenueTotal = r.Sum(i => i.RevenueAmount),

})
.ToList();
</code>```

答:
Each time you add new groupBy select inside groupby clause and press Ctrl + R + M and generate new method. You may pass this as a parameter.

```<code>Do(Func<TSource, TKey>)

var locationRevenues = revenues
                .GroupBy(Func())
                .Select(r => new
                {
                    Location = r.Key,
                    RevenueTotal = r.Sum(i => i.RevenueAmount),

                })
                .ToList();

private static Func<Revenues, object> Func()
{
    return g => new { Location = g.Location, Month = 9 };
}
</code>```

Title: LINQ Group by; How to make it flexible

Body:
considering the bit of code at the bottom, this is my problem:

I want to be able to group revenue based on input, e.g.:
- Year
- Month
- Week
- Units
etc.

Do I need to make a var for each combination (and change the Group by accordingly) or can I make something in which the Group by variables are flexible. Meaning that I can get the LocationRevenue on the level of input  for example: week, or month, or year; or year+month together, week+month together or any other combination.

var locationRevenues = revenues
.GroupBy(g => new { Location = g.Location, Month = DateTimeHelper.GetMonth(g.Date)})
.Select(r => new
{
    Location = r.Key,
    RevenueTotal = r.Sum(i => i.RevenueAmount),

})
.ToList();

Body:
Each time you add new groupBy select inside groupby clause and press Ctrl + R + M and generate new method. You may pass this as a parameter.

Do(Func<TSource, TKey>)

var locationRevenues = revenues
                .GroupBy(Func())
                .Select(r => new
                {
                    Location = r.Key,
                    RevenueTotal = r.Sum(i => i.RevenueAmount),

                })
                .ToList();

private static Func<Revenues, object> Func()
{
    return g => new { Location = g.Location, Month = 9 };
}


问:
MVVM and Databinding with UniformGrid
I'm trying to style the back of a WPF chart with some rectangles. I'm using MVVM, and I need the rectangles to be uniformly sized. When defined via Xaml, this works with a fixed "BucketCount" of 4:

```<code><VisualBrush>
  <VisualBrush.Visual>
  <UniformGrid Height="500" Width="500" Rows="1" Columns="{Binding BucketCount}">
    <Rectangle Grid.Row="0" Grid.Column="0" Fill="#22ADD8E6" />
    <Rectangle Grid.Row="0" Grid.Column="1" Fill="#22D3D3D3"/>
    <Rectangle Grid.Row="0" Grid.Column="2" Fill="#22ADD8E6"/>
    <Rectangle Grid.Row="0" Grid.Column="3" Fill="#22D3D3D3"/>
  </UniformGrid>
 </VisualBrush.Visual>
<VisualBrush>
</code>```

How can I bind my ObservableCollection of Rectangles? There is no "ItemsSource" property on UniformGrid. Do I need to use an ItemsControl? If so, how can I do this?

Thanks in advance.

答:
You could use ItemsControl to Bind like this. Simple example where ItemsSource is just an ObservableCollection<Brush>

```<code><VisualBrush>
    <VisualBrush.Visual>
        <ItemsControl x:Name="itemsControl" ItemsSource="{Binding MyBrushes}">
            <ItemsControl.ItemsPanel>
                <ItemsPanelTemplate>
                    <UniformGrid Height="500" Width="500" Rows="1"/>
                </ItemsPanelTemplate>
            </ItemsControl.ItemsPanel>
            <ItemsControl.ItemTemplate>
                <DataTemplate>
                    <Rectangle Fill="{Binding}"/>
                </DataTemplate>
            </ItemsControl.ItemTemplate>
        </ItemsControl>
    </VisualBrush.Visual>
</VisualBrush>
</code>```

Update

It works for my usage scenario, but I might be missing something here. Here's the full code I've tried. I get the same result from both

MainWindow.xaml

```<code><Grid>
    <Grid.Background>
        <VisualBrush>
            <VisualBrush.Visual>
                <ItemsControl x:Name="itemsControl" ItemsSource="{Binding MyBrushes}">
                    <ItemsControl.ItemsPanel>
                        <ItemsPanelTemplate>
                            <UniformGrid Height="500" Width="500" Rows="1"/>
                        </ItemsPanelTemplate>
                    </ItemsControl.ItemsPanel>
                    <ItemsControl.ItemTemplate>
                        <DataTemplate>
                            <Rectangle Fill="{Binding}"/>
                        </DataTemplate>
                    </ItemsControl.ItemTemplate>
                </ItemsControl>
                <!--<UniformGrid Height="500" Width="500" Rows="1" Columns="4">
                    <Rectangle Grid.Row="0" Grid.Column="0" Fill="#22ADD8E6" />
                    <Rectangle Grid.Row="0" Grid.Column="1" Fill="#22D3D3D3"/>
                    <Rectangle Grid.Row="0" Grid.Column="2" Fill="#22ADD8E6"/>
                    <Rectangle Grid.Row="0" Grid.Column="3" Fill="#22D3D3D3"/>
                </UniformGrid>-->
            </VisualBrush.Visual>
        </VisualBrush>
    </Grid.Background>
</Grid>
</code>```

MainWindow.xaml.cs

```<code>public partial class MainWindow : Window
{
    public MainWindow()
    {
        InitializeComponent();
        BrushConverter brushConverter = new BrushConverter();
        MyBrushes = new ObservableCollection<Brush>();
        MyBrushes.Add(brushConverter.ConvertFrom("#22ADD8E6") as Brush);
        MyBrushes.Add(brushConverter.ConvertFrom("#22D3D3D3") as Brush);
        MyBrushes.Add(brushConverter.ConvertFrom("#22ADD8E6") as Brush);
        MyBrushes.Add(brushConverter.ConvertFrom("#22D3D3D3") as Brush);
        this.DataContext = this;
    }

    public ObservableCollection<Brush> MyBrushes
    {
        get;
        set;
    }
}
</code>```

Title: MVVM and Databinding with UniformGrid

Body:
I'm trying to style the back of a WPF chart with some rectangles. I'm using MVVM, and I need the rectangles to be uniformly sized. When defined via Xaml, this works with a fixed "BucketCount" of 4:

<VisualBrush>
  <VisualBrush.Visual>
  <UniformGrid Height="500" Width="500" Rows="1" Columns="{Binding BucketCount}">
    <Rectangle Grid.Row="0" Grid.Column="0" Fill="#22ADD8E6" />
    <Rectangle Grid.Row="0" Grid.Column="1" Fill="#22D3D3D3"/>
    <Rectangle Grid.Row="0" Grid.Column="2" Fill="#22ADD8E6"/>
    <Rectangle Grid.Row="0" Grid.Column="3" Fill="#22D3D3D3"/>
  </UniformGrid>
 </VisualBrush.Visual>
<VisualBrush>

How can I bind my ObservableCollection of Rectangles? There is no "ItemsSource" property on UniformGrid. Do I need to use an ItemsControl? If so, how can I do this?

Thanks in advance.

Body:
You could use ItemsControl to Bind like this. Simple example where ItemsSource is just an ObservableCollection<Brush>

<VisualBrush>
    <VisualBrush.Visual>
        <ItemsControl x:Name="itemsControl" ItemsSource="{Binding MyBrushes}">
            <ItemsControl.ItemsPanel>
                <ItemsPanelTemplate>
                    <UniformGrid Height="500" Width="500" Rows="1"/>
                </ItemsPanelTemplate>
            </ItemsControl.ItemsPanel>
            <ItemsControl.ItemTemplate>
                <DataTemplate>
                    <Rectangle Fill="{Binding}"/>
                </DataTemplate>
            </ItemsControl.ItemTemplate>
        </ItemsControl>
    </VisualBrush.Visual>
</VisualBrush>

Update

It works for my usage scenario, but I might be missing something here. Here's the full code I've tried. I get the same result from both

MainWindow.xaml

<Grid>
    <Grid.Background>
        <VisualBrush>
            <VisualBrush.Visual>
                <ItemsControl x:Name="itemsControl" ItemsSource="{Binding MyBrushes}">
                    <ItemsControl.ItemsPanel>
                        <ItemsPanelTemplate>
                            <UniformGrid Height="500" Width="500" Rows="1"/>
                        </ItemsPanelTemplate>
                    </ItemsControl.ItemsPanel>
                    <ItemsControl.ItemTemplate>
                        <DataTemplate>
                            <Rectangle Fill="{Binding}"/>
                        </DataTemplate>
                    </ItemsControl.ItemTemplate>
                </ItemsControl>
                <!--<UniformGrid Height="500" Width="500" Rows="1" Columns="4">
                    <Rectangle Grid.Row="0" Grid.Column="0" Fill="#22ADD8E6" />
                    <Rectangle Grid.Row="0" Grid.Column="1" Fill="#22D3D3D3"/>
                    <Rectangle Grid.Row="0" Grid.Column="2" Fill="#22ADD8E6"/>
                    <Rectangle Grid.Row="0" Grid.Column="3" Fill="#22D3D3D3"/>
                </UniformGrid>-->
            </VisualBrush.Visual>
        </VisualBrush>
    </Grid.Background>
</Grid>

MainWindow.xaml.cs

public partial class MainWindow : Window
{
    public MainWindow()
    {
        InitializeComponent();
        BrushConverter brushConverter = new BrushConverter();
        MyBrushes = new ObservableCollection<Brush>();
        MyBrushes.Add(brushConverter.ConvertFrom("#22ADD8E6") as Brush);
        MyBrushes.Add(brushConverter.ConvertFrom("#22D3D3D3") as Brush);
        MyBrushes.Add(brushConverter.ConvertFrom("#22ADD8E6") as Brush);
        MyBrushes.Add(brushConverter.ConvertFrom("#22D3D3D3") as Brush);
        this.DataContext = this;
    }

    public ObservableCollection<Brush> MyBrushes
    {
        get;
        set;
    }
}


问:
Unable to import cufflinks
Has anybody faced this error when importing cufflinks?

答: All talib dependencies have now been removed. Studies have been rewritten in pure python. </p>

Title: Unable to import cufflinks


答:
As long as it is stopped, you can do nothing.

Maybe you can start it

https://docs.docker.com/engine/reference/commandline/start/

see the doc

and if it says running, you can connect and launch some commands using

docker exec -it duplo bash

or maybe just modify a string in a file

docker exec -it duplo sed...

, see the associated doc

https://docs.docker.com/engine/reference/commandline/exec/

Title: How do I run a docker container by its container name?

Body:
For example once I create a container with name of "duplo":

docker run --name="duplo" -it /bin/bash -c "sudo /build/backup.sh".

How do I execute an additional command within the container after it exits? I can see it listed by docker ps -a.


问:
Error: Cannot read property 'replace' of undefined when building iOS Cordova
I created a cordova project using cordova create project hello com.hello Hello.

And added iOS platform using cordova platform add iOS.
And tried to do cordova run ios after cordova build ios.

But it shows me this error(I used --d/ --verbose to get the details).

/usr/bin/codesign --force --sign - --timestamp=none
  /Volumes/Untitled/Plot/PlotReel/platforms/ios/build/emulator/PlotReel.app
  /Volumes/Untitled/Plot/PlotReel/platforms/ios/build/emulator/PlotReel.app:
  replacing existing signature

** BUILD SUCCEEDED **

No scripts found for hook "before_deploy". Error: TypeError: Cannot
  read property 'replace' of undefined

```<code>at remove (/Volumes/Untitled/Plot/test/platforms/ios/cordova/node_modules/ios-sim/src/lib.js:282:70)
at Array.forEach (native)
at Object.getdevicetypes (/Volumes/Untitled/Plot/test/platforms/ios/cordova/node_modules/ios-sim/src/lib.js:292:22)
at Object.listEmulatorImages [as run] (/Volumes/Untitled/Plot/test/platforms/ios/cordova/lib/list-emulator-images:34:29)
at deployToSim (/Volumes/Untitled/Plot/test/platforms/ios/cordova/lib/run.js:146:50)
at /Volumes/Untitled/Plot/test/platforms/ios/cordova/lib/run.js:88:20
at _fulfilled (/Volumes/Untitled/Plot/test/platforms/ios/cordova/node_modules/q/q.js:834:54)
at self.promiseDispatch.done (/Volumes/Untitled/Plot/test/platforms/ios/cordova/node_modules/q/q.js:863:30)
at Promise.promise.promiseDispatch (/Volumes/Untitled/Plot/test/platforms/ios/cordova/node_modules/q/q.js:796:13)
at /Volumes/Untitled/Plot/test/platforms/ios/cordova/node_modules/q/q.js:604:44
</code>```

I have tried uninstalling and installing cordova again, but the problem is still remaining.

Please help me.

答:
I recently upgreaded to xcode 8.3.3 and ionic 3.4.0

I have removed ios-sim directory from  myApp/platforms/ios/cordova/node_modules and now it's working.

Body:
I created a cordova project using cordova create project hello com.hello Hello.

And added iOS platform using cordova platform add iOS.
And tried to do cordova run ios after cordova build ios.

But it shows me this error(I used --d/ --verbose to get the details).

/usr/bin/codesign --force --sign - --timestamp=none
  /Volumes/Untitled/Plot/PlotReel/platforms/ios/build/emulator/PlotReel.app
  /Volumes/Untitled/Plot/PlotReel/platforms/ios/build/emulator/PlotReel.app:
  replacing existing signature

** BUILD SUCCEEDED **

No scripts found for hook "before_deploy". Error: TypeError: Cannot
  read property 'replace' of undefined

at remove (/Volumes/Untitled/Plot/test/platforms/ios/cordova/node_modules/ios-sim/src/lib.js:282:70)
at Array.forEach (native)
at Object.getdevicetypes (/Volumes/Untitled/Plot/test/platforms/ios/cordova/node_modules/ios-sim/src/lib.js:292:22)
at Object.listEmulatorImages [as run] (/Volumes/Untitled/Plot/test/platforms/ios/cordova/lib/list-emulator-images:34:29)
at deployToSim (/Volumes/Untitled/Plot/test/platforms/ios/cordova/lib/run.js:146:50)
at /Volumes/Untitled/Plot/test/platforms/ios/cordova/lib/run.js:88:20
at _fulfilled (/Volumes/Untitled/Plot/test/platforms/ios/cordova/node_modules/q/q.js:834:54)
at self.promiseDispatch.done (/Volumes/Untitled/Plot/test/platforms/ios/cordova/node_modules/q/q.js:863:30)
at Promise.promise.promiseDispatch (/Volumes/Untitled/Plot/test/platforms/ios/cordova/node_modules/q/q.js:796:13)
at /Volumes/Untitled/Plot/test/platforms/ios/cordova/node_modules/q/q.js:604:44

I have tried uninstalling and installing cordova again, but the problem is still remaining.

Please help me.


问:
Cannot resolve @style/Theme.AppCompat.Light.NoActionBar
I have an AppCompatActivity, and the moment I want to run my code. I get this error at the start of the Activity:

You need to use a Theme.AppCompat theme (or descendant) with this activity

If I use Theme.AppCompat as it advises me, but then I get this:

Cannot resolve @style/Theme.AppCompat.Light.NoActionBar

Neither in the AndroidManifest.xml, nor in the styles files I can use it.

I am using those dependencies:

```<code>compile fileTree(include: ['*.jar'], dir: 'libs')
compile 'com.android.support:design:25.3.1'
compile 'com.google.firebase:firebase-database:10.2.0'
compile 'com.android.support:cardview-v7:25.3.1'
compile 'com.parse:parse-android:1.15.8'
compile 'com.google.firebase:firebase-auth:10.2.0'
compile 'com.facebook.android:facebook-android-sdk:[4,5)'
compile "com.android.support:support-core-utils:25.4.0"
compile 'com.android.support:appcompat-v7:25.4.0'
compile 'com.android.support:support-v4:25.4.0'
</code>```

答: You have mixed android support library versions in your dependencies. Make sure all com.android.support:* have the same version number.

Body:
I have an AppCompatActivity, and the moment I want to run my code. I get this error at the start of the Activity:

You need to use a Theme.AppCompat theme (or descendant) with this activity

If I use Theme.AppCompat as it advises me, but then I get this:

Cannot resolve @style/Theme.AppCompat.Light.NoActionBar

Neither in the AndroidManifest.xml, nor in the styles files I can use it.

I am using those dependencies:

compile fileTree(include: ['*.jar'], dir: 'libs')
compile 'com.android.support:design:25.3.1'
compile 'com.google.firebase:firebase-database:10.2.0'
compile 'com.android.support:cardview-v7:25.3.1'
compile 'com.parse:parse-android:1.15.8'
compile 'com.google.firebase:firebase-auth:10.2.0'
compile 'com.facebook.android:facebook-android-sdk:[4,5)'
compile "com.android.support:support-core-utils:25.4.0"
compile 'com.android.support:appcompat-v7:25.4.0'
compile 'com.android.support:support-v4:25.4.0'


问:
Generating a very large matrix of string combinations using combn() and bigmemory package
I have a vector x of 1,344 unique strings. I want to generate a matrix that gives me all possible groups of three values, regardless of order, and export that to a csv.

I'm running R on EC2 on a m1.large instance w 64bit Ubuntu. When using combn(x, 3) I get an out of memory error:

```<code>Error: cannot allocate vector of size 9.0 Gb
</code>```

The size of the resulting matrix is C1344,3 = 403,716,544 rows and three columns - which is the transpose of the result of combn() function.

I thought of using the bigmemory package to create a file backed big.matrix so I can then assign the results of the combn() function. I can create a preallocated big matrix:

```<code>library(bigmemory)
x <- as.character(1:1344)
combos <- 403716544
test <- filebacked.big.matrix(nrow = combos, ncol = 3,
        init = 0, backingfile = "test.matrix")
</code>```

But when I try to allocate the values test <- combn(x, 3) I still get the same: Error: cannot allocate vector of size 9.0 Gb

I even tried coercing the result of combn(x,3) but I think that because the combn() function is returning an error, the big.matrix function doesn't work either.

```<code>test <- as.big.matrix(matrix(combn(x, 3)), backingfile = "abc")
Error: cannot allocate vector of size 9.0 Gb
Error in as.big.matrix(matrix(combn(x, 3)), backingfile = "abc") :
  error in evaluating the argument 'x' in selecting a method for function 'as.big.matrix'
</code>```

Is there a way to combine these two functions together to get what I need? Are there any other ways of achieving this? Thanks.

答:
Here's a function I've written in R, which currently finds its (unexported) home in the LSPM package.  You give it the total number of items n, the number of items to select r, and the index of the combination you want i; it returns the values in 1:n corresponding to combination i.

```<code>".combinadic" <- function(n, r, i) {

  # http://msdn.microsoft.com/en-us/library/aa289166(VS.71).aspx
  # http://en.wikipedia.org/wiki/Combinadic

  if(i < 1 | i > choose(n,r)) stop("'i' must be 0 < i <= n!/(n-r)!")

  largestV <- function(n, r, i) {
    #v <- n-1
    v <- n                                  # Adjusted for one-based indexing
    #while(choose(v,r) > i) v <- v-1
    while(choose(v,r) >= i) v <- v-1        # Adjusted for one-based indexing
    return(v)
  }

  res <- rep(NA,r)
  for(j in 1:r) {
    res[j] <- largestV(n,r,i)
    i <- i-choose(res[j],r)
    n <- res[j]
    r <- r-1
  }
  res <- res + 1
  return(res)
}
</code>```

It allows you to generate each combination based on the value of the lexicographic index:

```<code>> .combinadic(1344, 3, 1)
[1] 3 2 1
> .combinadic(1344, 3, 2)
[1] 4 2 1
> .combinadic(1344, 3, 403716544)
[1] 1344 1343 1342
</code>```

So you just need to loop over 1:403716544 and append the results to a file.  It may take awhile, but it's at least feasible (see Dirk's answer).  You also may need to do it in several loops, since the vector 1:403716544 will not fit in memory on my machine.

Or you could just port the R code to C/C++ and do the looping / writing there, since it would be a lot faster.

Body:
I have a vector x of 1,344 unique strings. I want to generate a matrix that gives me all possible groups of three values, regardless of order, and export that to a csv.

I'm running R on EC2 on a m1.large instance w 64bit Ubuntu. When using combn(x, 3) I get an out of memory error:

Error: cannot allocate vector of size 9.0 Gb

The size of the resulting matrix is C1344,3 = 403,716,544 rows and three columns - which is the transpose of the result of combn() function.

I thought of using the bigmemory package to create a file backed big.matrix so I can then assign the results of the combn() function. I can create a preallocated big matrix:

library(bigmemory)
x <- as.character(1:1344)
combos <- 403716544
test <- filebacked.big.matrix(nrow = combos, ncol = 3,
        init = 0, backingfile = "test.matrix")

But when I try to allocate the values test <- combn(x, 3) I still get the same: Error: cannot allocate vector of size 9.0 Gb

I even tried coercing the result of combn(x,3) but I think that because the combn() function is returning an error, the big.matrix function doesn't work either.

test <- as.big.matrix(matrix(combn(x, 3)), backingfile = "abc")
Error: cannot allocate vector of size 9.0 Gb
Error in as.big.matrix(matrix(combn(x, 3)), backingfile = "abc") :
  error in evaluating the argument 'x' in selecting a method for function 'as.big.matrix'

Is there a way to combine these two functions together to get what I need? Are there any other ways of achieving this? Thanks.

Body:
Here's a function I've written in R, which currently finds its (unexported) home in the LSPM package.  You give it the total number of items n, the number of items to select r, and the index of the combination you want i; it returns the values in 1:n corresponding to combination i.

".combinadic" <- function(n, r, i) {

  # http://msdn.microsoft.com/en-us/library/aa289166(VS.71).aspx
  # http://en.wikipedia.org/wiki/Combinadic

  if(i < 1 | i > choose(n,r)) stop("'i' must be 0 < i <= n!/(n-r)!")

  largestV <- function(n, r, i) {
    #v <- n-1
    v <- n                                  # Adjusted for one-based indexing
    #while(choose(v,r) > i) v <- v-1
    while(choose(v,r) >= i) v <- v-1        # Adjusted for one-based indexing
    return(v)
  }

  res <- rep(NA,r)
  for(j in 1:r) {
    res[j] <- largestV(n,r,i)
    i <- i-choose(res[j],r)
    n <- res[j]
    r <- r-1
  }
  res <- res + 1
  return(res)
}

It allows you to generate each combination based on the value of the lexicographic index:

> .combinadic(1344, 3, 1)
[1] 3 2 1
> .combinadic(1344, 3, 2)
[1] 4 2 1
> .combinadic(1344, 3, 403716544)
[1] 1344 1343 1342

So you just need to loop over 1:403716544 and append the results to a file.  It may take awhile, but it's at least feasible (see Dirk's answer).  You also may need to do it in several loops, since the vector 1:403716544 will not fit in memory on my machine.

Or you could just port the R code to C/C++ and do the looping / writing there, since it would be a lot faster.


问:
if else condition using sql query
I have problem to generate SQL query for below table.
Here is my table:

```<code>County          | Store     | Stock | Display | Designation
--------------- | --------- | ----- | ------- | ------------
USA             | USD       | 1     | Yes     | Merchandiser
USA             | USD       | 2     | Yes     | Promoter
</code>```

I want to be result like this

```<code>County          | Store     | Stock | Display | Designation
--------------- | --------- | ----- | ------- | ------------
USA             | USD       | 2     | Yes     | Merchandiser
USA             | USD       | 2     | Yes     | Promoter
</code>```

The Scenario is if Designation is Promoter, use both Display and Stock data.
If Designation is from Merchandiser, use data from Promoter for Stock data
How can i achieve this?

答:
I think you are expecting query like this</p>

```

    Select a.Country, a.Store
    , (CASE WHEN a.Designation = "Merchendiser" THEN (select  Top 1 b.Stock from YourTable b where b.Designation = "Promoter" and b.Country = a.Country and b.Store = a.Store order by id desc) ELSE a.Stock) as Stock
    , a.Display
    , a.Designation
    FROM YourTable a WHERE b.Designation = "Promoter"

```

Title: if else condition using sql query

Body:
I have problem to generate SQL query for below table.
Here is my table:

County          | Store     | Stock | Display | Designation
--------------- | --------- | ----- | ------- | ------------
USA             | USD       | 1     | Yes     | Merchandiser
USA             | USD       | 2     | Yes     | Promoter

I want to be result like this

County          | Store     | Stock | Display | Designation
--------------- | --------- | ----- | ------- | ------------
USA             | USD       | 2     | Yes     | Merchandiser
USA             | USD       | 2     | Yes     | Promoter

The Scenario is if Designation is Promoter, use both Display and Stock data.
If Designation is from Merchandiser, use data from Promoter for Stock data
How can i achieve this?

Body:
I think you are expecting query like this

    Select a.Country, a.Store
    , (CASE WHEN a.Designation = "Merchendiser" THEN (select  Top 1 b.Stock from YourTable b where b.Designation = "Promoter" and b.Country = a.Country and b.Store = a.Store order by id desc) ELSE a.Stock) as Stock
    , a.Display
    , a.Designation
    FROM YourTable a WHERE b.Designation = "Promoter"


问:
SQL query to fetch rows from one table which are not present in other 3 tables
I have 4 tables,

A, B , C , D

A has column Aid,
B has column Aid,
C has column Aid,
D has column Aid

(Aid is common column in all the 4 tables)

now i want to fetch rows from A table which are not present in B or C or D
can anyone please let me know the SQL query for this.

答:
Prepare example data:

```<code>CREATE TABLE A (aid int);
CREATE TABLE B (aid int);
CREATE TABLE C (aid int);
CREATE TABLE D (aid int);
INSERT INTO A VALUES (1);
INSERT INTO A VALUES (2);
INSERT INTO A VALUES (3);
INSERT INTO A VALUES (4);
INSERT INTO A VALUES (5);
INSERT INTO B VALUES (2);
INSERT INTO C VALUES (3);
INSERT INTO D VALUES (4);
</code>```

Query:

```<code>SELECT aid
FROM A
LEFT OUTER JOIN B on A.aid=B.aid
LEFT OUTER JOIN C on A.aid=C.aid
LEFT OUTER JOIN D on A.aid=D.aid
WHERE B.aid IS NULL AND C.aid IS NULL AND D.aid IS NULL;
</code>```

The results are 1 and 5.

Body:
Prepare example data:

CREATE TABLE A (aid int);
CREATE TABLE B (aid int);
CREATE TABLE C (aid int);
CREATE TABLE D (aid int);
INSERT INTO A VALUES (1);
INSERT INTO A VALUES (2);
INSERT INTO A VALUES (3);
INSERT INTO A VALUES (4);
INSERT INTO A VALUES (5);
INSERT INTO B VALUES (2);
INSERT INTO C VALUES (3);
INSERT INTO D VALUES (4);

Query:

SELECT aid
FROM A
LEFT OUTER JOIN B on A.aid=B.aid
LEFT OUTER JOIN C on A.aid=C.aid
LEFT OUTER JOIN D on A.aid=D.aid
WHERE B.aid IS NULL AND C.aid IS NULL AND D.aid IS NULL;

The results are 1 and 5.


问:
NSDictionary returning an optional integer when retrieving information
I have dictionary declared like this:

```<code>var friendLetterCount:NSDictionary = NSDictionary(dictionary: [String:Int]())
</code>```

and I obviously want to retrieve the information for the keys in the Dictionary, but when I do it, it only returns optional integers, how do I make this so that they are integers only?

I retrieve like this:

```<code>friendLetterCount["a"]
</code>```

and when I print it to the console it says

```<code>optional(1)
</code>```

I've tried converting it in all the ways I can imagine, but it always gives me an error saying

```<code>'(NSObject, AnyObject)' is not convertible to 'Int'
</code>```

Any suggestions would be appreciated.

答:
In case if you are not sure about the value is always Integer (Usually happens this with String/Intger),the safest way is :</p>

```<code>if let count = friendLetterCount["a"]?.integerValue  {

}
</code>```

Body:
I have dictionary declared like this:

var friendLetterCount:NSDictionary = NSDictionary(dictionary: [String:Int]())

and I obviously want to retrieve the information for the keys in the Dictionary, but when I do it, it only returns optional integers, how do I make this so that they are integers only?

I retrieve like this:

friendLetterCount["a"]

and when I print it to the console it says

optional(1)

I've tried converting it in all the ways I can imagine, but it always gives me an error saying

'(NSObject, AnyObject)' is not convertible to 'Int'

Any suggestions would be appreciated.

Body:
In case if you are not sure about the value is always Integer (Usually happens this with String/Intger),the safest way is :

if let count = friendLetterCount["a"]?.integerValue  {

}


问:
Divide and Conquer Algo to find maximum difference between two ordered elements
Given an array arr[] of integers, find out the difference between any two elements such that larger element appears after the smaller number in arr[].

```<code>Max Difference = Max { arr[x] - arr[y] | x > y }
</code>```

Examples:

If array is [2, 3, 10, 6, 4, 8, 1, 7] then returned value should be 8 (Diff between 10 and 2).

If array is [ 7, 9, 5, 6, 3, 2 ] then returned value should be 2 (Diff between 7 and 9)

My Algorithm:

I thought of using D&C algorithm.
Explanation

```<code>2, 3, 10, 6, 4, 8, 1, 7

then

2,3,10,6      and     4,8,1,7

then

2,3  and 10,6  and  4,8 and 1,7

then

2 and 3   10 and 6   4 and 8    1 and 7
</code>```

Here as these elements will remain in same order, i will get the maximum difference, here it's 6.

Now i will move back to merege these arrays and again find the difference between minimum of first block and maximum of second block and keep doing this till end.

I am not able to implement this in my code.
can anyone please provide a pseudo code for this?

答:
largest differance in array

```<code>condition : - larger number should appear after smaller number
{ 10, 3, 6, 4, 8, 1, 7 }     6
{ 2, 3, 10, 6, 4, 8, 1 }     8
{ 7, 9, 5, 6, 3, 2 }         1
{ 1, 2, 3, 4 }               3
{ 4, 3, 2, 1  }              0

#include<stdio.h>
int main(){
  int n = 7;
  int arr[7] = { 10, 3, 6, 14, 8, 1, 7 };

  int i;
  int max_diff = 0;
  int min = arr[0];

  for( i=0; i<n; i++){
    if( (arr[i] - min) > max_diff ){
      max_diff = arr[i] - min;
    }

    if(arr[i] < min){
      min = arr[i];
    }
  }
  printf("max diff = %d", max_diff);

  return 0;
}
</code>```

//time complexity O(n)

//space   complexity O(1)

for better understanding please visit https://www.youtube.com/watch?v=thPG6eTPf68&t=130s

Body:
Given an array arr[] of integers, find out the difference between any two elements such that larger element appears after the smaller number in arr[].

Max Difference = Max { arr[x] - arr[y] | x > y }

Examples:

If array is [2, 3, 10, 6, 4, 8, 1, 7] then returned value should be 8 (Diff between 10 and 2).

If array is [ 7, 9, 5, 6, 3, 2 ] then returned value should be 2 (Diff between 7 and 9)

My Algorithm:

I thought of using D&C algorithm.
Explanation

2, 3, 10, 6, 4, 8, 1, 7

then

2,3,10,6      and     4,8,1,7

then

2,3  and 10,6  and  4,8 and 1,7

then

2 and 3   10 and 6   4 and 8    1 and 7

Here as these elements will remain in same order, i will get the maximum difference, here it's 6.

Now i will move back to merege these arrays and again find the difference between minimum of first block and maximum of second block and keep doing this till end.

I am not able to implement this in my code.
can anyone please provide a pseudo code for this?

Body:
largest differance in array

condition : - larger number should appear after smaller number
{ 10, 3, 6, 4, 8, 1, 7 }     6
{ 2, 3, 10, 6, 4, 8, 1 }     8
{ 7, 9, 5, 6, 3, 2 }         1
{ 1, 2, 3, 4 }               3
{ 4, 3, 2, 1  }              0

#include<stdio.h>
int main(){
  int n = 7;
  int arr[7] = { 10, 3, 6, 14, 8, 1, 7 };

  int i;
  int max_diff = 0;
  int min = arr[0];

  for( i=0; i<n; i++){
    if( (arr[i] - min) > max_diff ){
      max_diff = arr[i] - min;
    }

    if(arr[i] < min){
      min = arr[i];
    }
  }
  printf("max diff = %d", max_diff);

  return 0;
}

//time complexity O(n)

//space   complexity O(1)

for better understanding please visit https://www.youtube.com/watch?v=thPG6eTPf68&t=130s


问:
What's the difference between an object and a class in Perl?
I'm having a little trouble getting my head around the conceptual difference between an object and a class.  I don't really understand the distinction between the two in any programming language, but currently I'm working with Perl, and Moose, so  I'd prefer an explanation using those things.

Cheers

答:
There are lots of "a class is a blueprint, an object is something built from that blueprint", but since you've asked for a specific example using Moose and Perl, I thought I'd provide one.

In this following example, we're going have a class named 'Hacker'.  The class (like a blueprint) describes what hackers are (their attributes) and what they can do (their methods):

```<code>package Hacker;       # Perl 5 spells 'class' as 'package'

use Moose;            # Also enables strict and warnings;

# Attributes in Moose are declared with 'has'.  So a hacker
# 'has' a given_name, a surname, a login name (which they can't change)
# and a list of languages they know.

has 'given_name'       => (is => 'rw', isa => 'Str');
has 'surname'          => (is => 'rw', isa => 'Str');
has 'login'            => (is => 'ro', isa => 'Str');
has 'languages'        => (is => 'rw', isa => 'ArrayRef[Str]');

# Methods are what a hacker can *do*, and are declared in basic Moose
# with subroutine declarations.

# As a simple method, hackers can return their full name when asked.

sub full_name {
    my ($self) = @_;   # $self is my specific hacker.

    # Attributes in Moose are automatically given 'accessor' methods, so
    # it's easy to query what they are for a specific ($self) hacker.

    return join(" ", $self->given_name, $self->surname);
}

# Hackers can also say hello.

sub say_hello {
    my ($self) = @_;

    print "Hello, my name is ", $self->full_name, "\n";

    return;
}

# Hackers can say which languages they like best.

sub praise_languages {
    my ($self) = @_;

    my $languages = $self->languages;

    print "I enjoy programming in: @$languages\n";

    return;
}

1;   # Perl likes files to end in a true value for historical reasons.
</code>```

Now that we've got our Hacker class, we can start making Hacker objects:

```<code>#!/usr/bin/perl
use strict;
use warnings;
use autodie;

use Hacker;    # Assuming the above is in Hacker.pm

# $pjf is a Hacker object

my $pjf = Hacker->new(
    given_name => "Paul",
    surname    => "Fenwick",
    login      => "pjf",
    languages  => [ qw( Perl C JavaScript) ],
);

# So is $jarich

my $jarich = Hacker->new(
    given_name => "Jacinta",
    surname    => "Richardson",
    login      => "jarich",
    languages  => [ qw( Perl C Haskell ) ],
);

# $pjf can introduce themselves.

$pjf->say_hello;
$pjf->praise_languages;

print "\n----\n\n";

# So can $jarich

$jarich->say_hello;
$jarich->praise_languages;
</code>```

This results in the following output:

```<code>Hello, my name is Paul Fenwick
I enjoy programming in: Perl C JavaScript

----

Hello, my name is Jacinta Richardson
I enjoy programming in: Perl C Haskell
</code>```

If I want I can have as many Hacker objects as I like, but there's still only one Hacker class that describes how all of these work.

All the best,

Paul

LastEditorDisplayName: brian d foy

Body:
There are lots of "a class is a blueprint, an object is something built from that blueprint", but since you've asked for a specific example using Moose and Perl, I thought I'd provide one.

In this following example, we're going have a class named 'Hacker'.  The class (like a blueprint) describes what hackers are (their attributes) and what they can do (their methods):

package Hacker;       # Perl 5 spells 'class' as 'package'

use Moose;            # Also enables strict and warnings;

# Attributes in Moose are declared with 'has'.  So a hacker
# 'has' a given_name, a surname, a login name (which they can't change)
# and a list of languages they know.

has 'given_name'       => (is => 'rw', isa => 'Str');
has 'surname'          => (is => 'rw', isa => 'Str');
has 'login'            => (is => 'ro', isa => 'Str');
has 'languages'        => (is => 'rw', isa => 'ArrayRef[Str]');

# Methods are what a hacker can *do*, and are declared in basic Moose
# with subroutine declarations.

# As a simple method, hackers can return their full name when asked.

sub full_name {
    my ($self) = @_;   # $self is my specific hacker.

    # Attributes in Moose are automatically given 'accessor' methods, so
    # it's easy to query what they are for a specific ($self) hacker.

    return join(" ", $self->given_name, $self->surname);
}

# Hackers can also say hello.

sub say_hello {
    my ($self) = @_;

    print "Hello, my name is ", $self->full_name, "\n";

    return;
}

# Hackers can say which languages they like best.

sub praise_languages {
    my ($self) = @_;

    my $languages = $self->languages;

    print "I enjoy programming in: @$languages\n";

    return;
}

1;   # Perl likes files to end in a true value for historical reasons.

Now that we've got our Hacker class, we can start making Hacker objects:

#!/usr/bin/perl
use strict;
use warnings;
use autodie;

use Hacker;    # Assuming the above is in Hacker.pm

# $pjf is a Hacker object

my $pjf = Hacker->new(
    given_name => "Paul",
    surname    => "Fenwick",
    login      => "pjf",
    languages  => [ qw( Perl C JavaScript) ],
);

# So is $jarich

my $jarich = Hacker->new(
    given_name => "Jacinta",
    surname    => "Richardson",
    login      => "jarich",
    languages  => [ qw( Perl C Haskell ) ],
);

# $pjf can introduce themselves.

$pjf->say_hello;
$pjf->praise_languages;

print "\n----\n\n";

# So can $jarich

$jarich->say_hello;
$jarich->praise_languages;

This results in the following output:

Hello, my name is Paul Fenwick
I enjoy programming in: Perl C JavaScript

----

Hello, my name is Jacinta Richardson
I enjoy programming in: Perl C Haskell

If I want I can have as many Hacker objects as I like, but there's still only one Hacker class that describes how all of these work.

All the best,

Paul

OwnerDisplayName: pjf


问:
Two-key encryption/decryption?
I'm looking to store some fairly sensitive data using PHP and MySQL and will be using some form of reversible encryption to do so since I need to get the data back out in plain text for it to be of any use.

I'll be deriving the encryption key from the users' username/password combination but I'm stumped for what to do in the (inevitable) event of a password being forgotten. I realise that the purpose of encryption is that it can only be undone using the correct key but this must have been addressed before..

I'm trying to get my head around whether or not public key cryptography would apply to the problem but all I can think of is that the private key will still need to be correct to decrypt the data..

Any ideas?

答:
Why are you using a different key for every user?

If you choose one key, it is much easier to handle.

Store your encryption key outside of the database.

Your application will still have to have access to it, but someone with a db dump will not be able to read the encrypted info.

Title: Two-key encryption/decryption?