问:
wxPython - Plot update on specific parameter change
Dear all passionated programmers,

I am programming an GUI to investigate my data. Those data is displayed in a 3D plot on a panel. The Plot is filling a prepared FigureCanvas on my GUI by the time I hit a Button. The Plot function gathers some parameter information from my Interface and is created.
I want to automate the process by enabling the function to always create a new plot when a parameter is changed.

I am more than helpless right now. Maybe there is something I am missing.
Is there some module that I can use ? Or is there a common way of doing something like that:

```<code>class MainFrame(wx.Frame):

def __init__(self, *args, **kwargs):
    super(MainFrame, self).__init__(*args, **kwargs)

    self.InitUI()
    self.Show(True)

def InitUI(self):
    print __doc__
    self.figure1 = Figure(figsize=(1,1))
    self.mft_plot = FigureCanvas(panel, -1, self.figure1)

    self.SpinCtrl_Y = wx.SpinCtrl(panel, value="0", size=(60,30), max = 10000) # Y
self.SpinCtrl_times = wx.SpinCtrl(panel, value="0",size=(100,30),min=-200, max=500) # time

    btn5 = wx.Button(panel, label = 'Create Vol. Image', pos = ((650), 10),
                     size = (150, 25))
    btn5.Bind(wx.EVT_BUTTON, self.OnPlotCreation)

def OnPlotCreation(self, e):
    print 'Waiting for time point..'

    t_enter = self.SpinCtrl_times.GetValue()
      # Transform time sample point to dimensional time point ..
    self.t_in_ms0 = t_enter * 1e3

    print 'Seleted time point is: %.2f ms' %self.t_in_ms0

    # Check for a threshold..
    threshold = self.mftthreshold.GetValue()

    self.figure1.clear()
    print 'Plot.'
    plotting.plot_stat_map( index_img( self.img, float(t_enter) ), figure = self.figure1, threshold= threshold, cut_coords=(self.SpinCtrl_Y.GetValue()),
                             annotate=True, title='t=%.2f ms' %self.t_in_ms0 )
</code>```

For an simple example i posted you this, a lil bit long, code sample. The goal I want to achieve is the function automatically runs again after
self.mftthreshold or
self.SpinCtrl_times or self.SpinCtrl_Y was changed.

I hope anyone can give me a hind on how to make this possible.

Thankful Greetings,
Daniel

答:
So the solution was:

```<code>class MainFrame(wx.Frame):

def __init__(self, *args, **kwargs):
    super(MainFrame, self).__init__(*args, **kwargs)

    self.InitUI()
    self.Show(True)

def InitUI(self):
    print __doc__
    self.figure1 = Figure(figsize=(1,1))
    self.mft_plot = FigureCanvas(panel, -1, self.figure1)

    self.SpinCtrl_Y = wx.SpinCtrl(panel, value="0", size=(60,30), max = 10000) # Y
    self.SpinCtrl_times = wx.SpinCtrl(panel, value="0",size=(100,30),min=-200, max=500) # time

    btn5 = wx.Button(panel, label = 'Create Vol. Image', pos = ((650), 10),
                     size = (150, 25))

    btn5.Bind(wx.EVT_BUTTON, self.OnPlot)
    ***self.SpinCtrl_times.Bind(wx.EVT_SPINCTRL , self.OnPlot)***

def OnPlotCreation(self, e):
    print 'Waiting for time point..'

    t_enter = self.SpinCtrl_times.GetValue()
      # Transform time sample point to dimensional time point ..
    self.t_in_ms0 = t_enter * 1e3

    print 'Seleted time point is: %.2f ms' %self.t_in_ms0

    # Check for a threshold..
    threshold = self.mftthreshold.GetValue()

    self.figure1.clear()
    print 'Plot.'
    plotting.plot_stat_map( index_img( self.img, float(t_enter) ), figure = self.figure1, threshold= threshold, cut_coords=(self.SpinCtrl_Y.GetValue()),
                             annotate=True, title='t=%.2f ms' %self.t_in_ms0 )
</code>```

Thank you for the help Rolf of Saxony.

Body:
Dear all passionated programmers,

I am programming an GUI to investigate my data. Those data is displayed in a 3D plot on a panel. The Plot is filling a prepared FigureCanvas on my GUI by the time I hit a Button. The Plot function gathers some parameter information from my Interface and is created.
I want to automate the process by enabling the function to always create a new plot when a parameter is changed.

I am more than helpless right now. Maybe there is something I am missing.
Is there some module that I can use ? Or is there a common way of doing something like that:

class MainFrame(wx.Frame):

def __init__(self, *args, **kwargs):
    super(MainFrame, self).__init__(*args, **kwargs)

    self.InitUI()
    self.Show(True)

def InitUI(self):
    print __doc__
    self.figure1 = Figure(figsize=(1,1))
    self.mft_plot = FigureCanvas(panel, -1, self.figure1)

    self.SpinCtrl_Y = wx.SpinCtrl(panel, value="0", size=(60,30), max = 10000) # Y
self.SpinCtrl_times = wx.SpinCtrl(panel, value="0",size=(100,30),min=-200, max=500) # time

    btn5 = wx.Button(panel, label = 'Create Vol. Image', pos = ((650), 10),
                     size = (150, 25))
    btn5.Bind(wx.EVT_BUTTON, self.OnPlotCreation)

def OnPlotCreation(self, e):
    print 'Waiting for time point..'

    t_enter = self.SpinCtrl_times.GetValue()
      # Transform time sample point to dimensional time point ..
    self.t_in_ms0 = t_enter * 1e3

    print 'Seleted time point is: %.2f ms' %self.t_in_ms0

    # Check for a threshold..
    threshold = self.mftthreshold.GetValue()

    self.figure1.clear()
    print 'Plot.'
    plotting.plot_stat_map( index_img( self.img, float(t_enter) ), figure = self.figure1, threshold= threshold, cut_coords=(self.SpinCtrl_Y.GetValue()),
                             annotate=True, title='t=%.2f ms' %self.t_in_ms0 )

For an simple example i posted you this, a lil bit long, code sample. The goal I want to achieve is the function automatically runs again after
self.mftthreshold or
self.SpinCtrl_times or self.SpinCtrl_Y was changed.

I hope anyone can give me a hind on how to make this possible.

Thankful Greetings,
Daniel

Body:
So the solution was:

class MainFrame(wx.Frame):

def __init__(self, *args, **kwargs):
    super(MainFrame, self).__init__(*args, **kwargs)

    self.InitUI()
    self.Show(True)

def InitUI(self):
    print __doc__
    self.figure1 = Figure(figsize=(1,1))
    self.mft_plot = FigureCanvas(panel, -1, self.figure1)

    self.SpinCtrl_Y = wx.SpinCtrl(panel, value="0", size=(60,30), max = 10000) # Y
    self.SpinCtrl_times = wx.SpinCtrl(panel, value="0",size=(100,30),min=-200, max=500) # time

    btn5 = wx.Button(panel, label = 'Create Vol. Image', pos = ((650), 10),
                     size = (150, 25))

    btn5.Bind(wx.EVT_BUTTON, self.OnPlot)
    ***self.SpinCtrl_times.Bind(wx.EVT_SPINCTRL , self.OnPlot)***

def OnPlotCreation(self, e):
    print 'Waiting for time point..'

    t_enter = self.SpinCtrl_times.GetValue()
      # Transform time sample point to dimensional time point ..
    self.t_in_ms0 = t_enter * 1e3

    print 'Seleted time point is: %.2f ms' %self.t_in_ms0

    # Check for a threshold..
    threshold = self.mftthreshold.GetValue()

    self.figure1.clear()
    print 'Plot.'
    plotting.plot_stat_map( index_img( self.img, float(t_enter) ), figure = self.figure1, threshold= threshold, cut_coords=(self.SpinCtrl_Y.GetValue()),
                             annotate=True, title='t=%.2f ms' %self.t_in_ms0 )

Thank you for the help Rolf of Saxony.


来源: stackexchange

问:
Are there any example on how to write full-screen apps for Mac OS X in Objective-C with Cocoa?
Could someone point me to any examples on how to write full-screen apps for Mac OS X in Ojective-C with Cocoa?</p>

答:
http://nehe.gamedev.net/data/lessons/lesson.asp?lesson=02

There is an OSX Cocoa example for many of the tutorials.

ContentLicense: CC BY-SA 3.0

ContentLicense: CC BY-SA 2.5


问:
Count the records with the same difference of two date columns Rails
Just wanted to ask what will be the query for my problem using rails and I'm using PostgreSQL for the database, let's say I have two columns one is start_date and end_date, I want to get only the records that have the same days difference when I subtract the two columns then count it. Example:

```<code>start_date | end_date
2017-06-01 | 2017-06-03
2017-07-25 | 2017-07-31
2017-09-05 | 2017-09-07
</code>```

For this example, I have three records so when you get the difference of those three records this will be the result

first row is 2

second row is 6

third row is 2

So the records that I only need to get are those two records with 2 days difference

答:
DB: PostgreSQL

You can use like this:

```<code>TableName.select("DATE_PART('day', end_date - start_date) as diff, count(*) as total").group("diff")
</code>```

Body:
Just wanted to ask what will be the query for my problem using rails and I'm using PostgreSQL for the database, let's say I have two columns one is start_date and end_date, I want to get only the records that have the same days difference when I subtract the two columns then count it. Example:

start_date | end_date
2017-06-01 | 2017-06-03
2017-07-25 | 2017-07-31
2017-09-05 | 2017-09-07

For this example, I have three records so when you get the difference of those three records this will be the result

first row is 2

second row is 6

third row is 2

So the records that I only need to get are those two records with 2 days difference

Body:
DB: PostgreSQL

You can use like this:

TableName.select("DATE_PART('day', end_date - start_date) as diff, count(*) as total").group("diff")


问:
Bootstrap Dropdown menu inside Grid.MVC cell
I'm trying to render a dropdown menu with 6 options inside a Grid.MVC cell.
This example is very straightforward: you define an helper which generates the relevant markup.

This is my code:

```<code>@helper menuContestuale(int idEvento) {
<div class="dropdown">
    <a class="dropdown-toggle" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">»</a>
    <ul class="dropdown-menu">
        <li>
            @Html.ActionLink("Dettaglio", "DettaglioErrore/" + idEvento, "Home")
        </li>
       <li>
           @Html.ActionLink("Elimina anomalia", "EliminaErrore/" + idEvento, "Home")
       </li>
       <li>
           @Html.ActionLink("Elimina anomalie simili di questa persona", "EliminaSimiliPersona/" + idEvento, "Home")
       </li>
       <li>
           @Html.ActionLink("Elimina anomalie stesso processo di questa persona", "EliminaSimiliPersonaProcesso/" + idEvento, "Home")
       </li>
       <li>
           @Html.ActionLink("Elimina anomalie simili", "EliminaSimili/" + idEvento, "Home")
       </li>
       <li>
           @Html.ActionLink("Elimina intero processo", "EliminaProcesso/" + idEvento, "Home")
       </li>
    </ul>
</div>
}

@Html.Grid(Model).Columns(columns =>
{
    columns.Add(row => row.idEvento).RenderValueAs(row => menuContestuale(row.idEvento).ToHtmlString()).Encoded(false);
});
</code>```

The resulting HTML in the table cell has most tags stripped away.

```<code><td class="grid-cell" data-name="idEvento">
    »</a>
        <li>
            Dettaglio</a>
        </li>
       <li>
           Elimina anomalia</a>
       </li>
       <li>
           Elimina anomalie simili di questa persona</a>
       </li>
       <li>
           Elimina anomalie stesso processo di questa persona</a>
       </li>
       <li>
           Elimina anomalie simili</a>
       </li>
       <li>
           Elimina intero processo</a>
       </li>
    </ul>
</td>
</code>```

The same helper, called outside the Grid, returns correct markup.
Any ideas ?
Thanks in advance.

答:
Looks like you also need to call "Sanitized":

```<code>.Encoded(false).Sanitized(false)
</code>```

Sanitizer is responsible for stripping potentially dangerous HTML tags from the string, so it could be the one removing them in your case.

Body:
I'm trying to render a dropdown menu with 6 options inside a Grid.MVC cell.
This example is very straightforward: you define an helper which generates the relevant markup.

This is my code:

@helper menuContestuale(int idEvento) {

    »

            @Html.ActionLink("Dettaglio", "DettaglioErrore/" + idEvento, "Home")

           @Html.ActionLink("Elimina anomalia", "EliminaErrore/" + idEvento, "Home")

           @Html.ActionLink("Elimina anomalie simili di questa persona", "EliminaSimiliPersona/" + idEvento, "Home")

           @Html.ActionLink("Elimina anomalie stesso processo di questa persona", "EliminaSimiliPersonaProcesso/" + idEvento, "Home")

           @Html.ActionLink("Elimina anomalie simili", "EliminaSimili/" + idEvento, "Home")

           @Html.ActionLink("Elimina intero processo", "EliminaProcesso/" + idEvento, "Home")

}

@Html.Grid(Model).Columns(columns =>
{
    columns.Add(row => row.idEvento).RenderValueAs(row => menuContestuale(row.idEvento).ToHtmlString()).Encoded(false);
});

The resulting HTML in the table cell has most tags stripped away.

    »

            Dettaglio

           Elimina anomalia

           Elimina anomalie simili di questa persona

           Elimina anomalie stesso processo di questa persona

           Elimina anomalie simili

           Elimina intero processo

The same helper, called outside the Grid, returns correct markup.
Any ideas ?
Thanks in advance.

Body:
Looks like you also need to call "Sanitized":

.Encoded(false).Sanitized(false)

Sanitizer is responsible for stripping potentially dangerous HTML tags from the string, so it could be the one removing them in your case.


问:
zf3 - calling custom plugin from Module.php
I'm new to Zend Framework 3. And migrating my Zend Framework 2 application to Zend Framework 3.

Currently I'm trying to call userPlugin from Application Module's Module.php file.

Here is my code,

```<code>public function onRoute(MvcEvent $e)
{
    $sm = $e->getApplication()->getServiceManager();
    $userPlugin = $sm->get('ControllerPluginManager')->get('userPlugin');
    $userPlugin->setServiceManager($e->getApplication()->getServiceManager());
    $checkLogin = $userPlugin->isLoggedIn();
}
</code>```

And in my module.config.php,

```<code>'controller_plugins' => array(
    //This is also not working
    //'invokables' => array(
    //    'userPlugin' => 'User\Controller\Plugin\UserPlugin',
    //),
    'factories' => [
        Controller\Plugin\UserPlugin::class => InvokableFactory::class,
    ],
    'aliases' => [
        'userPlugin' => Controller\Plugin\UserPlugin::class,
    ]
)
</code>```

But getting this error

Uncaught Zend\ServiceManager\Exception\ServiceNotFoundException: A plugin by the name "UserPlugin" was not found in the plugin manager Zend\Mvc\Controller\PluginManager

Where am I wrong?

答:
Use below code </p>

```<code> $sm = $e->getApplication()->getServiceManager();
 $checkLogin = $sm->get('ControllerPluginManager')
                  ->get(Controller\Plugin\UserPlugin::class)
                  ->isLoggedIn();
</code>```

Body:
I'm new to Zend Framework 3. And migrating my Zend Framework 2 application to Zend Framework 3.

Currently I'm trying to call userPlugin from Application Module's Module.php file.

Here is my code,

public function onRoute(MvcEvent $e)
{
    $sm = $e->getApplication()->getServiceManager();
    $userPlugin = $sm->get('ControllerPluginManager')->get('userPlugin');
    $userPlugin->setServiceManager($e->getApplication()->getServiceManager());
    $checkLogin = $userPlugin->isLoggedIn();
}

And in my module.config.php,

'controller_plugins' => array(
    //This is also not working
    //'invokables' => array(
    //    'userPlugin' => 'User\Controller\Plugin\UserPlugin',
    //),
    'factories' => [
        Controller\Plugin\UserPlugin::class => InvokableFactory::class,
    ],
    'aliases' => [
        'userPlugin' => Controller\Plugin\UserPlugin::class,
    ]
)

But getting this error

Uncaught Zend\ServiceManager\Exception\ServiceNotFoundException: A plugin by the name "UserPlugin" was not found in the plugin manager Zend\Mvc\Controller\PluginManager

Where am I wrong?

Body:
Use below code

 $sm = $e->getApplication()->getServiceManager();
 $checkLogin = $sm->get('ControllerPluginManager')
                  ->get(Controller\Plugin\UserPlugin::class)
                  ->isLoggedIn();


问:
how to read file line by line and change characters if line contain specific value
I have a FASTA file (testfile.fa), which contains title lines (contain > in the beginning) and lines with characters meaning some types of nucleotides (A, C, G, T, a, g, c, t, N).

```<code>>chr1
cccccccccttttttttaaaa
AAAACCCCTTCCCCCCCCGGG
GGGGGGGGGGGGGGGGGGGGG
TTTTTTTTTTTTTTTTTTTTT
>chr1_alt
TCTCTCTCTCTCTCTCTCTCT
gggtttccccccccccccccc
CGCGCGCGCGCGCGCGCGCGC
CCCCCAAAAAAAAAAAAAAAA
>chr2
CCCCCCCCCCCCCCCCCCCCC
TTTTTTTTTTTTATTTTTTTT
>chr3
AAAAAAAAAAAAAAAAAAAAA
GGGGGGGGGGGGGGGGGGGGG
TTTTTTTTTTTTTTTTTTTTT
</code>```

I need to read this file line by line and change small characters (a, c, t, g) to N in every sequence except titles, which contain >. So I use the following code:

```<code>#!/bin/bash
while read line
do
    if [[ $line =~ ">" ]]
    then
        echo $line
    else
        tr 'c' 'N'
        echo $line
    fi
done < testfile.fa
</code>```

But the results are confusing:

```<code>>chr1
# the first line was missed
AAAACCCCTTCCCCCCCCGGG
GGGGGGGGGGGGGGGGGGGGG
TTTTTTTTTTTTTTTTTTTTT
>Nhr1_alt #the character was changed but the line contains >
TCTCTCTCTCTCTCTCTCTCT
gggtttNNNNNNNNNNNNNNN
CGCGCGCGCGCGCGCGCGCGC
CCCCCAAAAAAAAAAAAAAAA
>Nhr2 #the character was changed but the line contains >
CCCCCCCCCCCCCCCCCCCCC
TTTTTTTTTTTTATTTTTTTT
>Nhr3 #the character was changed but the line contains >
AAAAAAAAAAAAAAAAAAAAA
GGGGGGGGGGGGGGGGGGGGG
TTTTTTTTTTTTTTTTTTTTTcccccccccttttttttaaaa #the first line from the first sequence comes here
</code>```

What can be the probable reason of these problems and how can I solve them? Thank you in advance!

答:
To change all lowercase variable with an awk statement, we could use:

```<code>awk '{ if (substr($0,1,1) != ">") { stat="";for ( i=1;i<=length($0);i++ ) { if ( substr($0,i,1) ~ /[[:lower:]]/ ) { stat=stat"N" } else stat=stat substr($0,i,1) } print stat } else { print $0 } }' testfile.fa
</code>```

We use awk's substr function and just print any lines with > as the first character. With the other lines, we build a variable stat changing all lower case letters to N and then printing the final stat result.

Body:
I have a FASTA file (testfile.fa), which contains title lines (contain > in the beginning) and lines with characters meaning some types of nucleotides (A, C, G, T, a, g, c, t, N).

>chr1
cccccccccttttttttaaaa
AAAACCCCTTCCCCCCCCGGG
GGGGGGGGGGGGGGGGGGGGG
TTTTTTTTTTTTTTTTTTTTT
>chr1_alt
TCTCTCTCTCTCTCTCTCTCT
gggtttccccccccccccccc
CGCGCGCGCGCGCGCGCGCGC
CCCCCAAAAAAAAAAAAAAAA
>chr2
CCCCCCCCCCCCCCCCCCCCC
TTTTTTTTTTTTATTTTTTTT
>chr3
AAAAAAAAAAAAAAAAAAAAA
GGGGGGGGGGGGGGGGGGGGG
TTTTTTTTTTTTTTTTTTTTT

I need to read this file line by line and change small characters (a, c, t, g) to N in every sequence except titles, which contain >. So I use the following code:

#!/bin/bash
while read line
do
    if [[ $line =~ ">" ]]
    then
        echo $line
    else
        tr 'c' 'N'
        echo $line
    fi
done < testfile.fa

But the results are confusing:

>chr1
# the first line was missed
AAAACCCCTTCCCCCCCCGGG
GGGGGGGGGGGGGGGGGGGGG
TTTTTTTTTTTTTTTTTTTTT
>Nhr1_alt #the character was changed but the line contains >
TCTCTCTCTCTCTCTCTCTCT
gggtttNNNNNNNNNNNNNNN
CGCGCGCGCGCGCGCGCGCGC
CCCCCAAAAAAAAAAAAAAAA
>Nhr2 #the character was changed but the line contains >
CCCCCCCCCCCCCCCCCCCCC
TTTTTTTTTTTTATTTTTTTT
>Nhr3 #the character was changed but the line contains >
AAAAAAAAAAAAAAAAAAAAA
GGGGGGGGGGGGGGGGGGGGG
TTTTTTTTTTTTTTTTTTTTTcccccccccttttttttaaaa #the first line from the first sequence comes here

What can be the probable reason of these problems and how can I solve them? Thank you in advance!

Body:
To change all lowercase variable with an awk statement, we could use:

awk '{ if (substr($0,1,1) != ">") { stat="";for ( i=1;i<=length($0);i++ ) { if ( substr($0,i,1) ~ /[[:lower:]]/ ) { stat=stat"N" } else stat=stat substr($0,i,1) } print stat } else { print $0 } }' testfile.fa

We use awk's substr function and just print any lines with > as the first character. With the other lines, we build a variable stat changing all lower case letters to N and then printing the final stat result.


问:
Can I change the process.env.NODE_ENV in dev?
I'm using a node package API client in my react-native project that uses the process.env.NODE_ENV to determine whether to return development or production data.  I'd like to test it in my dev environment (simulator) against the production database (it's read-only and the data greatly differs between dev and prod).

From what I can tell from this:
https://github.com/reactjs/react-redux/issues/39#issuecomment-131415769
process.env.NODE_ENV is set to development by default when the dev flag is true.

I've tried setting the NODE_ENV to production in my environment but it isn't picked up in the actual simulator (it still says development).

Is there some way to specify this when starting up or using run-*?

答:
In your AppDelegate.m startup (before calling jsBundleForBundleRoot), add this:

```<code>[RCTBundleURLProvider sharedSettings].enableDev = false;
</code>```

Or for Android, it should be something like this (untested):

```<code>PreferenceManager.getDefaultSharedPreferences(this).edit().putBoolean("js_dev_mode_debug", false);
</code>```

Note that these change the defaults, which I believe exist beyond the execution of your app. So you'll probably need to run them again with true to reset them back to the default values.

Body:
In your AppDelegate.m startup (before calling jsBundleForBundleRoot), add this:

[RCTBundleURLProvider sharedSettings].enableDev = false;

Or for Android, it should be something like this (untested):

PreferenceManager.getDefaultSharedPreferences(this).edit().putBoolean("js_dev_mode_debug", false);

Note that these change the defaults, which I believe exist beyond the execution of your app. So you'll probably need to run them again with true to reset them back to the default values.


问:
background color transition in few seconds w/o JQuery
https://codepen.io/codeispoetry/pen/dRKKEY

.back {
  margin: 20px;
  padding: 100px;
  background: yellow;
  font-size: 30px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="back">

  Fun place to stay. We got a golf cart to see the rest of the island, but the house is well-equipped and comfortable. Vanessa was kind to pick us up and make golf cart rental arrangements. We were here on our honeymoon, it was perfect for a memorable trip!
  Hosts easily available

</div></code>```

I want that yellow background should change with time to yellow, but I want to do ith through CSS. there is enough solution available on StackOverflow that do it with Jquery, but can we achieve this through CSS so that it works on all the browser.

https://www.w3schools.com/css/css3_animations.asp i tried this, but it roll backs to the original color. How to make th after color permanent.

答:
This is probably what you're looking for.</p>

```<code>.block {
    background-color: yellow;
}

.block:hover {
    background-color: white;
    -webkit-transition: background-color 1000ms linear;
    -ms-transition: background-color 1000ms linear;
    transition: background-color 1000ms linear;
}
</code>```

Body:
https://codepen.io/codeispoetry/pen/dRKKEY

.back {
  margin: 20px;
  padding: 100px;
  background: yellow;
  font-size: 30px;
}

  Fun place to stay. We got a golf cart to see the rest of the island, but the house is well-equipped and comfortable. Vanessa was kind to pick us up and make golf cart rental arrangements. We were here on our honeymoon, it was perfect for a memorable trip!
  Hosts easily available

I want that yellow background should change with time to yellow, but I want to do ith through CSS. there is enough solution available on StackOverflow that do it with Jquery, but can we achieve this through CSS so that it works on all the browser.

https://www.w3schools.com/css/css3_animations.asp i tried this, but it roll backs to the original color. How to make th after color permanent.

Body:
This is probably what you're looking for.

.block {
    background-color: yellow;
}

.block:hover {
    background-color: white;
    -webkit-transition: background-color 1000ms linear;
    -ms-transition: background-color 1000ms linear;
    transition: background-color 1000ms linear;
}


问:
Are there any implementations of Kmeans with Cosine distance in Apache Spark/PySpark?
Are there any working implementations of KMeans with Cosine distance applied to a Tf-IDF processed data frame in Apache Spark?

Spark, of course has Euclidean distance implementation in the ml library, but not so for any other distance measures.

答:
The KMeans algorithm is based on Euclidean distance, and can not directly use cosine distance. Here is a good explanation of this fact:

K-Means is implicitly based on pairwise Euclidean distances b/w data points, because the sum of squared deviations from centroid is equal to the sum of pairwise squared Euclidean distances divided by the number of points.

If you wish to use cosine distance (or any other metric), KMedoids might be a good option. It is similar to KMeans, but uses the median, instead of the mean, in it's update step. This allows the use of arbitrary distance metrics.


问:
Delphi: Logging UI events fired by user
I've been asked to put something in place into our programs in order to log somewhere what's happening on forms...

Logging something such ...clicked either this or that button, context menu, events fired on components and so on..

This mostly because we are dealing with legacy code, not quite structured unfortunately that we are adjusting/reviewing (Delphi XE10) when possible and we would like to track everything is happening (or most of it) from an user's point of view in order to
- being able to have a lead on what the user did when something mysterious happens
- being able to review the code where necessary when we have no idea of how thing have happened
- eventually speed issues

I'm not talking about exceptions or data logging...those are properly handled.

It's just about the UI.

Do you know if there is any library that might do something similar?
If not, how would you try to achieve this?

Code examples are happily accepted (even simple such as one/more form/s with a few buttons etc)

Thanks all!!!

答:
As a lightweight solution you can use OutputDebugString(PChar('My logtext')), or TFile.AppendAllText('log.txt','My logtext').

If you want fancy logging with special viewers, thread-safe, etc, you could include some special logging framework. In that case it's better search online and compare features yourself instead of asking for an opinion here.

Title: Delphi: Logging UI events fired by user


问:
Angular 2 loader on each http request
What i am trying to do is:

I want to use the spinner whenever a http request accurs. In other words i want user to see a loading screen whenever a http request happens in my app.component.

My spinner.component and spinner-service files are same with the answer in this question.

And my app.component's component is

```<code>@Component({
    selector: 'todoApi',
    template: `
        <div class="foo">
            <spinner-component></spinner-component>
            <h1>Internship Project</h1>
            <a [routerLink]="['Dashboard']">Dashboard</a>
            <a [routerLink]="['Tasks']">List</a>
            <router-outlet></router-outlet>
        <div>
    `,
    directives: [ROUTER_DIRECTIVES,SpinnerComponent],
    providers: [
        ROUTER_PROVIDERS,
    ]
})

@RouteConfig([
    {
        path: '/dashboard',
        name: 'Dashboard',
        component: DashboardComponent,
        useAsDefault: true
    },{
        path: '/tasks',
        name: 'Tasks',
        component: TaskComponent
    },{
        path: '/detail/:id',
        name: 'TaskDetail',
        component: TaskDetailComponent
    },
])
</code>```

To conclue , whenever a http request occurs in one of these routes, i want to show the spinner to user. I know this has been a bad question , but i am new to angular 2 and i would realy be grateful if anyone could help me with that.

Thanks alot!
 Edit!:

Solution with Günther's answer:
I wrapped my http and spinner-service into a HttpClient component and used it instead of regular http module. Here is my HttpClient component:

```<code>import { Injectable } from '@angular/core';
import { Http, Headers } from '@angular/http';
import { SpinnerService} from './spinner-service';

@Injectable()
export class HttpClient {
  constructor(
      private http: Http,
      public spinner: SpinnerService
    ){

  }

  createAuthorizationHeader(headers:Headers) {
    headers.append('Authorization', 'Basic ' + btoa('username:password'));
  }

  get(url) {
    this.spinner.start();
    let headers = new Headers();
    this.createAuthorizationHeader(headers);
    return this.http.get(url, { headers: headers }).do(data=> {this.spinner.stop()});
  }

  post(url, data) {
    this.spinner.start();
    let headers = new Headers();
    this.createAuthorizationHeader(headers);
    return this.http.post(url, data, { headers: headers }).do(data=> {this.spinner.stop()});
  }
}
</code>```

答:
Thanks for your answer Günter Zöchbauer's, An example which I built based on my needs. I did not use an HTTP wrapper which would be easier to use, however, this example works with multiple services calls based on your counter suggestion. Hope it helps someone :)

Create the Loader service.

```<code>import { Injectable } from '@angular/core';
import { BehaviorSubject } from 'rxjs/BehaviorSubject';

@Injectable()

export class LoaderService {
    public loaderCounter: BehaviorSubject<number> = new BehaviorSubject<number>(0);
    displayLoader(value: boolean) {
      let counter = value ? this.loaderCounter.value + 1 : this.loaderCounter.value - 1;
      this.loaderCounter.next(counter);
    }
}
</code>```

Include the service within the providers of your maain module file
(Ex: AppModule)

In your main component file (Ex: AppComponent), subscribe to the
changes and reflect to the loader (in my case it's a seperate
component).

```<code>//Imports
import { Subscription } from 'rxjs/Subscription';
import { LoaderService } from './core/loader.service';
..
@Component({
  selector: 'my-app',
  template: `
    <div class="container-fluid content">
      <router-outlet></router-outlet>
    </div>
    <spinner [visible]="displayLoader"></spinner>
  `
})

export class AppComponent implements OnInit, OnDestroy {
    displayLoader: boolean;
    loaderSubscription: Subscription;
    constructor(private loaderService: LoaderService) {}

    ngOnInit() {
        this.loaderSubscription = this.loaderService.loaderCounter.subscribe((counter: number) => {
            this.displayLoader = counter != 0;
        });
    }

    ngOnDestroy() {
        this.loaderSubscription.unsubscribe();
    }
}
</code>```

Using the loader service:

```<code> import { LoaderService } from './core/loader.service';
    ..
    export class SampleComponent implements OnInit {
        constructor(private _service: SomeService, private loader: LoaderService) { }

    ngOnInit() {
        this.loader.displayLoader(true);
        this._service.getBalance().subscribe(
            response => ..do something..,
            () => .. error..,
            () => this.loader.displayLoader(false)
        );
    }
}
</code>```

Title: Angular 2 loader on each http request

Body:
What i am trying to do is:

I want to use the spinner whenever a http request accurs. In other words i want user to see a loading screen whenever a http request happens in my app.component.

My spinner.component and spinner-service files are same with the answer in this question.

And my app.component's component is

@Component({
    selector: 'todoApi',
    template: `

            <spinner-component></spinner-component>

Internship Project

            Dashboard
            List
            <router-outlet></router-outlet>

    `,
    directives: [ROUTER_DIRECTIVES,SpinnerComponent],
    providers: [
        ROUTER_PROVIDERS,
    ]
})

@RouteConfig([
    {
        path: '/dashboard',
        name: 'Dashboard',
        component: DashboardComponent,
        useAsDefault: true
    },{
        path: '/tasks',
        name: 'Tasks',
        component: TaskComponent
    },{
        path: '/detail/:id',
        name: 'TaskDetail',
        component: TaskDetailComponent
    },
])

To conclue , whenever a http request occurs in one of these routes, i want to show the spinner to user. I know this has been a bad question , but i am new to angular 2 and i would realy be grateful if anyone could help me with that.

Thanks alot!
 Edit!:

Solution with Günther's answer:
I wrapped my http and spinner-service into a HttpClient component and used it instead of regular http module. Here is my HttpClient component:

import { Injectable } from '@angular/core';
import { Http, Headers } from '@angular/http';
import { SpinnerService} from './spinner-service';

@Injectable()
export class HttpClient {
  constructor(
      private http: Http,
      public spinner: SpinnerService
    ){

  }

  createAuthorizationHeader(headers:Headers) {
    headers.append('Authorization', 'Basic ' + btoa('username:password'));
  }

  get(url) {
    this.spinner.start();
    let headers = new Headers();
    this.createAuthorizationHeader(headers);
    return this.http.get(url, { headers: headers }).do(data=> {this.spinner.stop()});
  }

  post(url, data) {
    this.spinner.start();
    let headers = new Headers();
    this.createAuthorizationHeader(headers);
    return this.http.post(url, data, { headers: headers }).do(data=> {this.spinner.stop()});
  }
}

Body:
Thanks for your answer Günter Zöchbauer's, An example which I built based on my needs. I did not use an HTTP wrapper which would be easier to use, however, this example works with multiple services calls based on your counter suggestion. Hope it helps someone :)

Create the Loader service.

import { Injectable } from '@angular/core';
import { BehaviorSubject } from 'rxjs/BehaviorSubject';

@Injectable()

export class LoaderService {
    public loaderCounter: BehaviorSubject<number> = new BehaviorSubject<number>(0);
    displayLoader(value: boolean) {
      let counter = value ? this.loaderCounter.value + 1 : this.loaderCounter.value - 1;
      this.loaderCounter.next(counter);
    }
}

Include the service within the providers of your maain module file
(Ex: AppModule)

In your main component file (Ex: AppComponent), subscribe to the
changes and reflect to the loader (in my case it's a seperate
component).

//Imports
import { Subscription } from 'rxjs/Subscription';
import { LoaderService } from './core/loader.service';
..
@Component({
  selector: 'my-app',
  template: `
    <div class="container-fluid content">
      <router-outlet></router-outlet>
    </div>
    <spinner [visible]="displayLoader"></spinner>
  `
})

export class AppComponent implements OnInit, OnDestroy {
    displayLoader: boolean;
    loaderSubscription: Subscription;
    constructor(private loaderService: LoaderService) {}

    ngOnInit() {
        this.loaderSubscription = this.loaderService.loaderCounter.subscribe((counter: number) => {
            this.displayLoader = counter != 0;
        });
    }

    ngOnDestroy() {
        this.loaderSubscription.unsubscribe();
    }
}

Using the loader service:

 import { LoaderService } from './core/loader.service';
    ..
    export class SampleComponent implements OnInit {
        constructor(private _service: SomeService, private loader: LoaderService) { }

    ngOnInit() {
        this.loader.displayLoader(true);
        this._service.getBalance().subscribe(
            response => ..do something..,
            () => .. error..,
            () => this.loader.displayLoader(false)
        );
    }
}


问:
Substring is not found in string
I use bash version 3.2.51(1)

I work with job chains and want to start a new job when the old one is finished.
So I check which jobs are currently running and only if the job number of the last run can not be found, a new job is to be submitted.

Here is the part of my script:

```<code>    Job_ID=$(msub -E fvcom.pbs)

    # test whether job is still running

    CONTINUE="just started"
    # do this loop, until the CONTINUE variable is empty (i.e. job is finished)
    until [ -z "$CONTINUE" ] ; do
       # wait $WAIT seconds
       sleep $WAIT
       # query if job is still running
       RUNNING=$(./show_my_run)
      echo $RUNNING
      echo $Job_ID

       # check whether specific job is still running
       # then job ID is present in job overview
       if [[ $RUNNING == *"$Job_ID"* ]] ; then
       CONTINUE="Job_ID found"
       echo $CONTINUE
       else
       CONTINUE=""
       echo "Job_ID not found"
       fi

    done
</code>```

The output is:

city.12345/1202110.batch.com kdd046 Running 4 00:59:14 Tue Jul 4

city.12345

Job_ID not found

Obviously I can see that Job_ID is present and the job is still running...
The pattern is only recognized if there are several jobs running and the pattern is somewhere in the middle:

city.54321/1202133.batch.com kdd046 Running 4 00:59:14 Tue Jul 4  city.12345/1202110.batch.com kdd046 Running 4 00:56:19 Tue Jul 4

city.12345

Job_ID found

I also tried using

...

if echo "$RUNNING" | grep -q "$Job_ID"; then

...

but with same results.

What am I doing wrong?

答:
Using  declare -p Job_ID  I found that there was a line break at the beginning of the variable Job_ID that was not shown using echo.

Now, I included a change to get rid of this extra line and it works:

```<code>  Job_ID=$(msub -E fvcom.pbs | perl -p -e 'chomp' )
</code>```

Title: Substring is not found in string

Body:
I use bash version 3.2.51(1)

I work with job chains and want to start a new job when the old one is finished.
So I check which jobs are currently running and only if the job number of the last run can not be found, a new job is to be submitted.

Here is the part of my script:

    Job_ID=$(msub -E fvcom.pbs)

    # test whether job is still running

    CONTINUE="just started"
    # do this loop, until the CONTINUE variable is empty (i.e. job is finished)
    until [ -z "$CONTINUE" ] ; do
       # wait $WAIT seconds
       sleep $WAIT
       # query if job is still running
       RUNNING=$(./show_my_run)
      echo $RUNNING
      echo $Job_ID

       # check whether specific job is still running
       # then job ID is present in job overview
       if [[ $RUNNING == *"$Job_ID"* ]] ; then
       CONTINUE="Job_ID found"
       echo $CONTINUE
       else
       CONTINUE=""
       echo "Job_ID not found"
       fi

    done

The output is:

city.12345/1202110.batch.com kdd046 Running 4 00:59:14 Tue Jul 4

city.12345

Job_ID not found

Obviously I can see that Job_ID is present and the job is still running...
The pattern is only recognized if there are several jobs running and the pattern is somewhere in the middle:

city.54321/1202133.batch.com kdd046 Running 4 00:59:14 Tue Jul 4  city.12345/1202110.batch.com kdd046 Running 4 00:56:19 Tue Jul 4

city.12345

Job_ID found

I also tried using

...

if echo "$RUNNING" | grep -q "$Job_ID"; then

...

but with same results.

What am I doing wrong?

Body:
Using  declare -p Job_ID  I found that there was a line break at the beginning of the variable Job_ID that was not shown using echo.

Now, I included a change to get rid of this extra line and it works:

  Job_ID=$(msub -E fvcom.pbs | perl -p -e 'chomp' )


问:
SQL group by with like condition
suppose there is a SQL table: testTable with columns: clientID, colA, colB, colC.

```<code>reference   clientID    colA    colB    colC
---------------------------------------------
001            1        test1   test2   test3
002            1        test1   ball2   test3
003            2        test1   ball2   test3
004            2        test1   ball2   test3
005            3        test1   test2   test3
006            4        test1   test2   test3
007            4        test1   test2   test3
009            5        test1   ball2   test3
---------------------------------------------
</code>```

i would like to select all the distinct rows where colB is like 'test' and group by the clientID. so i end up with:

```<code>reference    clientID    colA    colB    colC
----------------------------------------------
001             1        test1   test2   test3
005             3        test1   test2   test3
006             4        test1   test2   test3
----------------------------------------------
</code>```

EDIT:
reference column is unique
if i use
select distinct * .. from .. where colB like '%test%' group by clientID
then the results returned does not have clientID grouped

答:
Just a distinct is not suffice?

```<code>Select distinct * from #data where ColB like 'test%'
</code>```

Or you can use top 1 with ties if you require only certain columns to consider on distinct

```<code>Select top (1) with ties * from #groupby where ColB like 'test%'
order by row_number() over(partition by clientid order by cola,colb,colc)--you can include your required columns only
</code>```

Title: SQL group by with like condition

Body:
suppose there is a SQL table: testTable with columns: clientID, colA, colB, colC.

reference   clientID    colA    colB    colC
---------------------------------------------
001            1        test1   test2   test3
002            1        test1   ball2   test3
003            2        test1   ball2   test3
004            2        test1   ball2   test3
005            3        test1   test2   test3
006            4        test1   test2   test3
007            4        test1   test2   test3
009            5        test1   ball2   test3
---------------------------------------------

i would like to select all the distinct rows where colB is like 'test' and group by the clientID. so i end up with:

reference    clientID    colA    colB    colC
----------------------------------------------
001             1        test1   test2   test3
005             3        test1   test2   test3
006             4        test1   test2   test3
----------------------------------------------

EDIT:
reference column is unique
if i use
select distinct * .. from .. where colB like '%test%' group by clientID
then the results returned does not have clientID grouped

Body:
Just a distinct is not suffice?

Select distinct * from #data where ColB like 'test%'

Or you can use top 1 with ties if you require only certain columns to consider on distinct

Select top (1) with ties * from #groupby where ColB like 'test%'
order by row_number() over(partition by clientid order by cola,colb,colc)--you can include your required columns only


问:
Why using PosixFilePermission to set permissions on directory does not work
Below is my code:

```<code>String DirectoryPath = "/Users/xxx/uploads/image";
Path newDirectoryPath = Paths.get(DirecotryPath);

if (!Files.exists(newDirectoryPath)) {
    Set<PosixFilePermission> permissions = PosixFilePermissions.fromString("rwxrwxrwx");
    FileAttribute<Set<PosixFilePermission>> fileAttributes = PosixFilePermissions.asFileAttribute(permissions);
    Files.createDirectories(newDirectoryPath, fileAttributes);
}
</code>```

After creating the directory, the permission of the directory is not 777.

答:
It's because of the actual umask setting of the executing user.

From PosixFileAttributeView

When the access permissions are set at file creation time then the actual value of the permissions may differ that the value of the attribute object. The reasons for this are implementation specific. On UNIX systems, for example, a process has a umask that impacts the permission bits of newly created files. Where an implementation supports the setting of the access permissions, and the underlying file system supports access permissions, then it is required that the value of the actual access permissions will be equal or less than the value of the attribute provided to the createFile or createDirectory methods. In other words, the file may be more secure than requested.

example

Posix.java

```<code>// add the omitted import statements
public class Posix {

    public static void main(String[] args) throws IOException {
        Path newDirectoryPath = Paths.get("/tmp/image");
        Files.deleteIfExists(newDirectoryPath);
        Set<PosixFilePermission> permissions
                = PosixFilePermissions.fromString("rwxrwxrwx");
        FileAttribute<Set<PosixFilePermission>> fileAttributes
                = PosixFilePermissions.asFileAttribute(permissions);
        Files.createDirectories(newDirectoryPath, fileAttributes);
    }
}
</code>```

execute in the shell

```<code>$ cd /tmp
$ javac Posix.java

$ umask 001
$ java Posix
$ ls -ld image/

drwxrwxrw-. 2 suboptimal suboptimal 6 Jul  5 12:38 image/

$ umask 002
$ java Posix
$ ls -ld image/

drwxrwxr-x. 2 suboptimal suboptimal 6 Jul  5 12:38 image/

$ umask 004
$ java Posix
$ ls -ld image/

drwxrwx-wx. 2 suboptimal suboptimal 6 Jul  5 12:38 image/
</code>```

Body:
Below is my code:

String DirectoryPath = "/Users/xxx/uploads/image";
Path newDirectoryPath = Paths.get(DirecotryPath);

if (!Files.exists(newDirectoryPath)) {
    Set<PosixFilePermission> permissions = PosixFilePermissions.fromString("rwxrwxrwx");
    FileAttribute<Set<PosixFilePermission>> fileAttributes = PosixFilePermissions.asFileAttribute(permissions);
    Files.createDirectories(newDirectoryPath, fileAttributes);
}

After creating the directory, the permission of the directory is not 777.

Body:
It's because of the actual umask setting of the executing user.

From PosixFileAttributeView

When the access permissions are set at file creation time then the actual value of the permissions may differ that the value of the attribute object. The reasons for this are implementation specific. On UNIX systems, for example, a process has a umask that impacts the permission bits of newly created files. Where an implementation supports the setting of the access permissions, and the underlying file system supports access permissions, then it is required that the value of the actual access permissions will be equal or less than the value of the attribute provided to the createFile or createDirectory methods. In other words, the file may be more secure than requested.

example

Posix.java

// add the omitted import statements
public class Posix {

    public static void main(String[] args) throws IOException {
        Path newDirectoryPath = Paths.get("/tmp/image");
        Files.deleteIfExists(newDirectoryPath);
        Set<PosixFilePermission> permissions
                = PosixFilePermissions.fromString("rwxrwxrwx");
        FileAttribute<Set<PosixFilePermission>> fileAttributes
                = PosixFilePermissions.asFileAttribute(permissions);
        Files.createDirectories(newDirectoryPath, fileAttributes);
    }
}

execute in the shell

$ cd /tmp
$ javac Posix.java

$ umask 001
$ java Posix
$ ls -ld image/

drwxrwxrw-. 2 suboptimal suboptimal 6 Jul  5 12:38 image/

$ umask 002
$ java Posix
$ ls -ld image/

drwxrwxr-x. 2 suboptimal suboptimal 6 Jul  5 12:38 image/

$ umask 004
$ java Posix
$ ls -ld image/

drwxrwx-wx. 2 suboptimal suboptimal 6 Jul  5 12:38 image/


问:
iOS: How to get the constraints for button inside horizontal stack-view right?
I am new to iOS development and am following the udacity course for iOS development. I am stuck at the lesson whose link I have given below.

https://classroom.udacity.com/courses/ud585/lessons/6991272849/concepts/72642287220923#

I am unable to reduce the size of stop button in the last stack view. I tried reducing the size of the button by setting the width constraint of the button to 64 and height of stack-view containing that button to 64. But XCode gives error of conflicting constraints.

I am attaching screenshots below for reference.

What I actually want is:

https://d17h27t6h515a5.cloudfront.net/topher/2016/November/582a8006_interface/interface.png

答: You can take a uiview inside your last stack and then You can take your stop button. Then you can change properties of your "stop" UIbutton.</p>


答:
Using awk:

```<code>$ awk '/^[^>]/{gsub(/[actg]/,"N")}1' file
>chr1
NNNNNNNNNNNNNNNNNNNNN
AAAACCCCTTCCCCCCCCGGG
GGGGGGGGGGGGGGGGGGGGG
TTTTTTTTTTTTTTTTTTTTT
>chr1_alt
TCTCTCTCTCTCTCTCTCTCT
NNNNNNNNNNNNNNNNNNNNN
CGCGCGCGCGCGCGCGCGCGC
CCCCCAAAAAAAAAAAAAAAA
>chr2
CCCCCCCCCCCCCCCCCCCCC
TTTTTTTTTTTTATTTTTTTT
>chr3
AAAAAAAAAAAAAAAAAAAAA
GGGGGGGGGGGGGGGGGGGGG
TTTTTTTTTTTTTTTTTTTTT
</code>```

Explained:

```<code>/^[^>]/ {               # if the record starts with anything but >
    gsub(/[actg]/,"N")  # replace all actg with N
}1                      # output
</code>```

Title: how to read file line by line and change characters if line contain specific value

Body:
Using awk:

$ awk '/^[^>]/{gsub(/[actg]/,"N")}1' file
>chr1
NNNNNNNNNNNNNNNNNNNNN
AAAACCCCTTCCCCCCCCGGG
GGGGGGGGGGGGGGGGGGGGG
TTTTTTTTTTTTTTTTTTTTT
>chr1_alt
TCTCTCTCTCTCTCTCTCTCT
NNNNNNNNNNNNNNNNNNNNN
CGCGCGCGCGCGCGCGCGCGC
CCCCCAAAAAAAAAAAAAAAA
>chr2
CCCCCCCCCCCCCCCCCCCCC
TTTTTTTTTTTTATTTTTTTT
>chr3
AAAAAAAAAAAAAAAAAAAAA
GGGGGGGGGGGGGGGGGGGGG
TTTTTTTTTTTTTTTTTTTTT

Explained:

/^[^>]/ {               # if the record starts with anything but >
    gsub(/[actg]/,"N")  # replace all actg with N
}1                      # output


答:
The where clause goes before the having and the group by. If you want to filter out records before the grouping the condition goes in the where clause, and if you want to filter out grouped records the condition goes in the having clause:

```<code>select ...
from ...
where ...
group by ...
having ...
</code>```

or something like this one if above thing is not worked

```<code>select ...
from (
   select ...
   from ...
   where ...
   group by ...
   having ...
) x
where ...
</code>```

Title: SQL group by with like condition

Body:
The where clause goes before the having and the group by. If you want to filter out records before the grouping the condition goes in the where clause, and if you want to filter out grouped records the condition goes in the having clause:

select ...
from ...
where ...
group by ...
having ...

or something like this one if above thing is not worked

select ...
from (
   select ...
   from ...
   where ...
   group by ...
   having ...
) x
where ...


问:
PHP & MySQL - not inserting into database
I've got an problem in my code. The insert is not working. The code is below.

HTML:

```<code><form action="staff.php" method="post" class="center" enctype="multipart/form-data" autocomplete="off">
    <input type="hidden" name="size" value="1000000">
    <input type="text" placeholder="headline of the news" name="title">
    <input type="file" accept="image/*" name="image">
    <select name="side" value="side">
        <option>Left</option>
        <option>Header</option>
        <option>Main</option>
        <option>Ending</option>
    </select>
    <textarea name="desc" id="description" cols="30" rows="10" placeholder="full news" name="desc"></textarea>
    <input type="submit" name="go" value="Post">
</form>
</code>```

PHP:

```<code><?php
$db = mysqli_connect("DB SERVER", "DB USER", "DB PASS", "DataBase");
$charset = mysqli_set_charset($db,"utf8");
$msg = "";
if (isset($_POST['go'])) {
    $target = "images/".basename($_FILES['image']['name']);
    $title = $_POST['title'];
    $image = $_FILES['image']['name'];
    $side = $_POST['side'];
    $desc = $_POST['desc'];
    $sql = "INSERT INTO contents (title, image, side, description)
    VALUES ('$title', '$image', '$side', '$desc')";
    $result = mysqli_query($db, $sql);
    if (move_uploaded_file($_FILES['image']['tmp_name'], $target)) {
        $msg = "<p class='success'>Image uploaded successfully</p>";
    } else {
        $msg = "<p class='error'>There was a problem uploading the image</p>";
    }
}
?>
</code>```

Everything is fine except the inserting into database.

答:
Use as</p>

```<code><?php
$db = mysqli_connect("DB SERVER", "DB USER", "DB PASS", "DataBase") or die(mysqli_error("Could not connect to Database"));
mysqli_query($db,"SET NAMES 'utf8'");
$msg = "";
if (isset($_POST['go'])) {
    $target = "images/".basename($_FILES['image']['name']);

    $title = mysqli_real_escape_string($db,$_POST['title']);
    $image = mysqli_real_escape_string($db,$_FILES['image']['name']);
    $side = mysqli_real_escape_string($db,$_POST['side']);
    $desc = mysqli_real_escape_string($db,$_POST['desc']);
    $sql = "INSERT INTO contents (title, image, side, description)
    VALUES ('$title', '$image', '$side', '$desc')";
    $result = mysqli_query($db,$sql) or die(mysqli_error($db));
    if (move_uploaded_file($_FILES['image']['tmp_name'], $target)) {
       $msg = "<p class='success'>Image uploaded successfully</p>";
    }else{
       $msg = "<p class='error'>There was a problem uploading the image</p>";
    }
}
?>
</code>```

Body:
I've got an problem in my code. The insert is not working. The code is below.

HTML:

<form action="staff.php" method="post" class="center" enctype="multipart/form-data" autocomplete="off">
    <input type="hidden" name="size" value="1000000">
    <input type="text" placeholder="headline of the news" name="title">
    <input type="file" accept="image/*" name="image">
    <select name="side" value="side">
        <option>Left</option>
        <option>Header</option>
        <option>Main</option>
        <option>Ending</option>
    </select>
    <textarea name="desc" id="description" cols="30" rows="10" placeholder="full news" name="desc"></textarea>
    <input type="submit" name="go" value="Post">
</form>

PHP:

<?php
$db = mysqli_connect("DB SERVER", "DB USER", "DB PASS", "DataBase");
$charset = mysqli_set_charset($db,"utf8");
$msg = "";
if (isset($_POST['go'])) {
    $target = "images/".basename($_FILES['image']['name']);
    $title = $_POST['title'];
    $image = $_FILES['image']['name'];
    $side = $_POST['side'];
    $desc = $_POST['desc'];
    $sql = "INSERT INTO contents (title, image, side, description)
    VALUES ('$title', '$image', '$side', '$desc')";
    $result = mysqli_query($db, $sql);
    if (move_uploaded_file($_FILES['image']['tmp_name'], $target)) {
        $msg = "
Image uploaded successfully
";
    } else {
        $msg = "
There was a problem uploading the image
";
    }
}
?>

Everything is fine except the inserting into database.

Body:
Use as

<?php
$db = mysqli_connect("DB SERVER", "DB USER", "DB PASS", "DataBase") or die(mysqli_error("Could not connect to Database"));
mysqli_query($db,"SET NAMES 'utf8'");
$msg = "";
if (isset($_POST['go'])) {
    $target = "images/".basename($_FILES['image']['name']);

    $title = mysqli_real_escape_string($db,$_POST['title']);
    $image = mysqli_real_escape_string($db,$_FILES['image']['name']);
    $side = mysqli_real_escape_string($db,$_POST['side']);
    $desc = mysqli_real_escape_string($db,$_POST['desc']);
    $sql = "INSERT INTO contents (title, image, side, description)
    VALUES ('$title', '$image', '$side', '$desc')";
    $result = mysqli_query($db,$sql) or die(mysqli_error($db));
    if (move_uploaded_file($_FILES['image']['tmp_name'], $target)) {
       $msg = "<p class='success'>Image uploaded successfully</p>";
    }else{
       $msg = "<p class='error'>There was a problem uploading the image</p>";
    }
}
?>


问:
Django-- Deactivate User account instead of deleting it
I want to deactivate the User account instead of deleting it. I want to do something like user.is_active = False. I have a view to delete User profile and it works but now I need to change it to only deactivate.
Here is my view:

```<code>def delete_profile(request):
    user = User.objects.filter(id = request.user.profile.user_id)
    try:
        user.delete()
    except:
        messages.error(request,'Please try again.')
        return redirect('profile')

    messages.success(request, 'Profile successfully deleted.')
    return redirect('index')
</code>```

I tried User.is_active = False , it displays the success message but doesn't do anything. When I check the User in admin panel it will still have User marked as active.

Any Idea how I can achieve this? Thanks in advance

答: After calling user.is_active = False you need to write the changes to the database by calling user.save()

Body:
I want to deactivate the User account instead of deleting it. I want to do something like user.is_active = False. I have a view to delete User profile and it works but now I need to change it to only deactivate.
Here is my view:

def delete_profile(request):
    user = User.objects.filter(id = request.user.profile.user_id)
    try:
        user.delete()
    except:
        messages.error(request,'Please try again.')
        return redirect('profile')

    messages.success(request, 'Profile successfully deleted.')
    return redirect('index')

I tried User.is_active = False , it displays the success message but doesn't do anything. When I check the User in admin panel it will still have User marked as active.

Any Idea how I can achieve this? Thanks in advance


答:
Try this,</p>

```<code> Select distinct * From tableA where colB like '%test%'
</code>```

Title: SQL group by with like condition

Body:
Try this,

 Select distinct * From tableA where colB like '%test%'


答:
try this code

.back {
  margin: 20px;
  padding: 100px;
  // background: yellow;
  font-size: 30px;
}

div {
  background-color: red;
  -webkit-animation-name: example;
  /* Safari 4.0 - 8.0 */
  -webkit-animation-duration: 4s;
  /* Safari 4.0 - 8.0 */
  animation-name: example;
  animation-duration: 4s;
  animation-iteration-count: infinite;
}

/* Safari 4.0 - 8.0 */

@-webkit-keyframes example {
  from {
    background-color: red;
  }
  to {
    background-color: yellow;
  }
}

/* Standard syntax */

@keyframes example {
  from {
    background-color: red;
  }
  to {
    background-color: yellow;
  }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="back">

  Fun place to stay. We got a golf cart to see the rest of the island, but the house is well-equipped and comfortable. Vanessa was kind to pick us up and make golf cart rental arrangements. We were here on our honeymoon, it was perfect for a memorable trip!
  Hosts easily available

</div></code>```

Title: background color transition in few seconds w/o JQuery

Body:
try this code

.back {
  margin: 20px;
  padding: 100px;
  // background: yellow;
  font-size: 30px;
}

div {
  background-color: red;
  -webkit-animation-name: example;
  /* Safari 4.0 - 8.0 */
  -webkit-animation-duration: 4s;
  /* Safari 4.0 - 8.0 */
  animation-name: example;
  animation-duration: 4s;
  animation-iteration-count: infinite;
}

/* Safari 4.0 - 8.0 */

@-webkit-keyframes example {
  from {
    background-color: red;
  }
  to {
    background-color: yellow;
  }
}

/* Standard syntax */

@keyframes example {
  from {
    background-color: red;
  }
  to {
    background-color: yellow;
  }
}

<div class="back">

  Fun place to stay. We got a golf cart to see the rest of the island, but the house is well-equipped and comfortable. Vanessa was kind to pick us up and make golf cart rental arrangements. We were here on our honeymoon, it was perfect for a memorable trip!
  Hosts easily available

</div>


问:
Getting elements from XML file in Perl
I have a file on a server that I want to parse in Perl. I've tried it with XML:Simple and XML:LibXML and I can't get the xml elements in both cases.

This is my .xml file:

```<code><csixml version="1.0">
    <head>
    <details>
        <name-link>linkName</name-link>
        <table>links</table>
        <model>XS1-556</model>
    </details>
        <fields>
            <field name="name1" />
            <field name="name2"/>
            <field name="name3"/>
            <field name="name4"/>
            <field name="name5"/>
            <field name="name6" />
            <field name="name7"/>
            <field name="name8"/>
            <field name="name9"/>
            <field name="name10"/>
            <field name="name11"/>
            <field name="name12x"/>
            <field name="name13"/>
            <field name="name14"/>
            <field name="name15"/>
            <field name="name16"/>
            <field name="name17"/>
        </fields>
    </head>
    <data>
        <record time="2017/06/01 00:00:00" no="742">
        <v1>14.85</v1>
        <v2>34.1</v2>
        <v3>600</v3>
        <v4>0</v4>
        <v5>0</v5>
        <v6>0</v6>
        <v7>0</v7>
        <v8>11.22</v8>
        <v9>0.41</v9>
        <v10>215</v10>
        <v11>7.043</v11>
        <v12>1.325</v12>
        <v13>2017-05-31T23:47:14</v13>
        <v14>202.3</v14>
        <v15>0</v15>
        <v16>42.85</v16>
        <v17>12.25</v17>
        </record>
        </data>
    </csixml>
</code>```

And this is the code :

```<code>my $parser = new XML::Simple;
$data = $parser->XMLin( get( $url ));

#print Dumper($data);

print $data->{'r'}[0]{'v1'};
print $data->{'r'}[1]{'v2'};
</code>```

When I try it with XML:LibXML it gives me an error that says:

```<code>Start tag expected, '<' not found
</code>```

答:
I've tryed all of thoose solutions but finally I found it:

```<code>my ($_xml) = new XML::Simple (KeyAttr=>[]);

    my $url = 'http://www.example.com';
    my $agent = LWP::UserAgent->new;
    my $request = HTTP::Request->new(GET => $url);
    $request->content_type('application/xml');
    my $response = $agent->request($request);

                if ($response->is_success) {
                     print "HTTP response is good\n";

                    my ($_message) = $response->decoded_content;
                    my ($_data) = $_xml->XMLin($_message,ForceArray => 1);

                    foreach my $_e (@{$_data->{data}})
                    {
                        foreach my $_r (@{$_e->{r}})
                        {

                        print $_r->{time}.": ".$_r->{no}."\n";

                        }
                    }

                } else {

                die "Awooga! HTTP request failed with ". $response->status_line;

                }
</code>```

Finally I use XML:Simple and I get my xml elements with: $_r->{time} and it works great. I hope this will help someone, thanks to everyone!!

Title: Getting elements from XML file in Perl

Body:
I have a file on a server that I want to parse in Perl. I've tried it with XML:Simple and XML:LibXML and I can't get the xml elements in both cases.

This is my .xml file:

<csixml version="1.0">

        <name-link>linkName</name-link>

links

        <model>XS1-556</model>

        <fields>
            <field name="name1" />
            <field name="name2"/>
            <field name="name3"/>
            <field name="name4"/>
            <field name="name5"/>
            <field name="name6" />
            <field name="name7"/>
            <field name="name8"/>
            <field name="name9"/>
            <field name="name10"/>
            <field name="name11"/>
            <field name="name12x"/>
            <field name="name13"/>
            <field name="name14"/>
            <field name="name15"/>
            <field name="name16"/>
            <field name="name17"/>
        </fields>

    <data>
        <record time="2017/06/01 00:00:00" no="742">
        <v1>14.85</v1>
        <v2>34.1</v2>
        <v3>600</v3>
        <v4>0</v4>
        <v5>0</v5>
        <v6>0</v6>
        <v7>0</v7>
        <v8>11.22</v8>
        <v9>0.41</v9>
        <v10>215</v10>
        <v11>7.043</v11>
        <v12>1.325</v12>
        <v13>2017-05-31T23:47:14</v13>
        <v14>202.3</v14>
        <v15>0</v15>
        <v16>42.85</v16>
        <v17>12.25</v17>
        </record>
        </data>
    </csixml>

And this is the code :

my $parser = new XML::Simple;
$data = $parser->XMLin( get( $url ));

#print Dumper($data);

print $data->{'r'}[0]{'v1'};
print $data->{'r'}[1]{'v2'};

When I try it with XML:LibXML it gives me an error that says:

Start tag expected, '<' not found

Body:
I've tryed all of thoose solutions but finally I found it:

my ($_xml) = new XML::Simple (KeyAttr=>[]);

    my $url = 'http://www.example.com';
    my $agent = LWP::UserAgent->new;
    my $request = HTTP::Request->new(GET => $url);
    $request->content_type('application/xml');
    my $response = $agent->request($request);

                if ($response->is_success) {
                     print "HTTP response is good\n";

                    my ($_message) = $response->decoded_content;
                    my ($_data) = $_xml->XMLin($_message,ForceArray => 1);

                    foreach my $_e (@{$_data->{data}})
                    {
                        foreach my $_r (@{$_e->{r}})
                        {

                        print $_r->{time}.": ".$_r->{no}."\n";

                        }
                    }

                } else {

                die "Awooga! HTTP request failed with ". $response->status_line;

                }

Finally I use XML:Simple and I get my xml elements with: $_r->{time} and it works great. I hope this will help someone, thanks to everyone!!


问:
Static lib loading related issue
Suppose I want to version the libs in binaries made. For static libs, I thought this approach would work but it does not:

LibInfo.h - Base class for all libinfo classes. Registers an object in gvLibInfo vector when a child is constructed.

```<code>#ifndef IFACE_H
#define IFACE_H

#include <vector>

class LibInfo;
extern std::vector<LibInfo*> gvLibInfo;

class LibInfo
{
    public:
        virtual int getversion() = 0;
        void reglib()
        {
            gvLibInfo.push_back(this);
        }

        LibInfo()
        {
            reglib();
        }
        virtual ~LibInfo()
        {}
};

#endif
</code>```

Lib1.h - Derived from LibInfo and creates an object l1. Lib2.h is the same except getversion returns 2.

```<code>#ifndef LIB1_H
#define LIB1_H

#include "LibInfo.h"

class Lib1 : public LibInfo
{
    public:
        int getversion()
        {
            return 1;
        }

    private:
};

Lib1 l1;

#endif
</code>```

main.cpp

```<code>#include "Lib1.h"
#include <iostream>
using namespace std;

vector<LibInfo*> gvLibInfo;

int main()
{
    for(vector<LibInfo*>::iterator it = gvLibInfo.begin(); it != gvLibInfo.end(); it++)
    {
        cout << (*it)->getversion() << endl;
    }

    return 0;
}
</code>```

Compiling -

```<code>g++ -c Lib1.h -o Lib1.o
g++ -c Lib2.h -o Lib2.o
ar cr lib.a Lib1.o Lib2.o
g++ main.cpp -o app -L/home/duminda/statictest/lib.a
</code>```

When I run, nothing happens. I thought this maybe due to one of several reasons:

At the time Lib1 l1 is made, gvLibInfo has not been constructed.

I saw somewhere that the linker will remove any unused variables from a static lib. However, when I run on the binary nm it shows up this :

0000000000603280 B gvLibInfo

0000000000603270 B l1

0000000000603278 B l2

I guess l1 & l2(The corresponding object of class Lib2 are there but what does that 'B' flag mean?
3. Something else I don't know.

答:
Change the top of main.cpp to look like this, so that the vector is created before the derived instances. </p>

```<code>#include "LibInfo.h"

std::vector<LibInfo*> gvLibInfo;

#include "Lib1.h"
#include "Lib2.h"
</code>```

<p>BTW, the 'B' from nm indicates symbol in BSS (uninitialized data).  The man page for nm has all the symbol types listed. </p>

Title: Static lib loading related issue

Body:
Suppose I want to version the libs in binaries made. For static libs, I thought this approach would work but it does not:

LibInfo.h - Base class for all libinfo classes. Registers an object in gvLibInfo vector when a child is constructed.

#ifndef IFACE_H
#define IFACE_H

#include <vector>

class LibInfo;
extern std::vector<LibInfo*> gvLibInfo;

class LibInfo
{
    public:
        virtual int getversion() = 0;
        void reglib()
        {
            gvLibInfo.push_back(this);
        }

        LibInfo()
        {
            reglib();
        }
        virtual ~LibInfo()
        {}
};

#endif

Lib1.h - Derived from LibInfo and creates an object l1. Lib2.h is the same except getversion returns 2.

#ifndef LIB1_H
#define LIB1_H

#include "LibInfo.h"

class Lib1 : public LibInfo
{
    public:
        int getversion()
        {
            return 1;
        }

    private:
};

Lib1 l1;

#endif

main.cpp

#include "Lib1.h"
#include <iostream>
using namespace std;

vector<LibInfo*> gvLibInfo;

int main()
{
    for(vector<LibInfo*>::iterator it = gvLibInfo.begin(); it != gvLibInfo.end(); it++)
    {
        cout << (*it)->getversion() << endl;
    }

    return 0;
}

Compiling -

g++ -c Lib1.h -o Lib1.o
g++ -c Lib2.h -o Lib2.o
ar cr lib.a Lib1.o Lib2.o
g++ main.cpp -o app -L/home/duminda/statictest/lib.a

When I run, nothing happens. I thought this maybe due to one of several reasons:

At the time Lib1 l1 is made, gvLibInfo has not been constructed.

I saw somewhere that the linker will remove any unused variables from a static lib. However, when I run on the binary nm it shows up this :

0000000000603280 B gvLibInfo

0000000000603270 B l1

0000000000603278 B l2

I guess l1 & l2(The corresponding object of class Lib2 are there but what does that 'B' flag mean?
3. Something else I don't know.

Body:
Change the top of main.cpp to look like this, so that the vector is created before the derived instances.

#include "LibInfo.h"

std::vector<LibInfo*> gvLibInfo;

#include "Lib1.h"
#include "Lib2.h"

BTW, the 'B' from nm indicates symbol in BSS (uninitialized data).  The man page for nm has all the symbol types listed.


问:
How do I insert a span in a string?
I have this sample:-

link

CODE HTML:

```<code><p>
  width (10mm)
</p>
</code>```

CODE JS:

```<code>jQuery(document).ready(function(){
    //First bracket detection
});
</code>```

The structure I want to obtain is the following (after document is ready):

```<code><p>
    width <span>(10mm)</span>
</p>
</code>```

I thought I could detect the first parenthesis in the string and then add a span.

Can you give me a simple example please how can I do this?

Thanks in advance!

答:
use this :</p>

```<code>jQuery(document).ready(function () {
    var $p = $("p");
    var text = $p.text().trim();
    text = text.split(" ");
    text = text[0] + "<span>" + text[1] + "</span>";
    $p.text(text);
});
</code>```

Title: How do I insert a span in a string?

Body:
I have this sample:-

link

CODE HTML:

  width (10mm)

CODE JS:

jQuery(document).ready(function(){
    //First bracket detection
});

The structure I want to obtain is the following (after document is ready):

    width (10mm)

I thought I could detect the first parenthesis in the string and then add a span.

Can you give me a simple example please how can I do this?

Thanks in advance!

Body:
use this :

jQuery(document).ready(function () {
    var $p = $("p");
    var text = $p.text().trim();
    text = text.split(" ");
    text = text[0] + "<span>" + text[1] + "</span>";
    $p.text(text);
});


问:
codeigniter - .htaccess redirection issue in http to https
When I try to redirect with or without www (example.com, www.example.com) To https://www.example.com, I am getting "The page isn’t redirecting properly" Error Message.

```<code>RewriteEngine on
RewriteCond %{HTTP_HOST} ^www\.example\.com$
RewriteRule ^(.*)$ "https\:\/\/example\.com\/$1" [R=301,L]
</code>```

I tied below code also

```<code>RewriteEngine On
RewriteCond %{HTTPS} off
RewriteRule (.*) https://www.example.com%{REQUEST_URI}
</code>```

But when i try to redirect without www To https://www.example.com is working fine.

I need to redirect with or without www example.com To https://www.example.com

答:
Below code is redirecting (with or without www).example.com to https://www.example.com</p>

```<code>RewriteEngine on
RewriteCond %{HTTP_HOST} ^(www\.)?(example.com)$
RewriteCond %{HTTP:X-Forwarded-Proto} !https [NC]
RewriteCond %{HTTPS} off
RewriteRule (.*) https://www.example.com/$1 [R=302,L]
</code>```

Body:
When I try to redirect with or without www (example.com, www.example.com) To https://www.example.com, I am getting "The page isn’t redirecting properly" Error Message.

RewriteEngine on
RewriteCond %{HTTP_HOST} ^www\.example\.com$
RewriteRule ^(.*)$ "https\:\/\/example\.com\/$1" [R=301,L]

I tied below code also

RewriteEngine On
RewriteCond %{HTTPS} off
RewriteRule (.*) https://www.example.com%{REQUEST_URI}

But when i try to redirect without www To https://www.example.com is working fine.

I need to redirect with or without www example.com To https://www.example.com

Body:
Below code is redirecting (with or without www).example.com to https://www.example.com

RewriteEngine on
RewriteCond %{HTTP_HOST} ^(www\.)?(example.com)$
RewriteCond %{HTTP:X-Forwarded-Proto} !https [NC]
RewriteCond %{HTTPS} off
RewriteRule (.*) https://www.example.com/$1 [R=302,L]


问:
How can I combine a tuple elements into a list in python
Consider the following code below:

```<code>list1 = ['1x', '2x']
list2 = ['x18', 'x74']
list3 = [('100p1', '100p2'), ('300p1', '300p2')]

gen_list = [[a,b] for a in list1 for b in list2]

for new_list in gen_list:
    for c in list3:
        print(new_list.extend(c))
</code>```

My target result is like this:

```<code>[['1x','x18, '100p1', '100p2'],
 ['1x','x74, '100p1', '100p2'],
 ['1x','x18, '300p1', '300p2'],
 ['1x','x74, '300p1', '300p2'],
 ['2x','x18, '100p1', '100p2'],
 ['2x','x74, '100p1', '100p2'],
 ['2x','x18, '300p1', '300p2'],
 ['2x','x74, '300p1', '300p2']]
</code>```

but the result of the above code is this:

```<code>None
None
None
None
None
None
None
None
</code>```

What necessary correction do I need to apply on my code? Thanks in advance.

答:
using itertools.product, unpacking and a list comprehension

```<code>[[l[0], l[2], *l[1]] for l in itertools.product(list1, list3, list2)]
</code>```

or

```<code>[[l1, l2, *l3] for l1, l3, l2 in itertools.product(list1, list3, list2)]
</code>```

before Python 3.5

For versions before Python 3.5 you could do something like this

```<code>[[l1, l2] + list(l3) for l1, l3, l2 in itertools.product(list1, list3, list2)]
</code>```

If you know l3 only contains 2 elements you can use nested unpacking, as mentioned by @ShadowRanger

```<code>[[a, b, c1, c2] for a, (c1, c2), b in itertools.product(list1, list3, list2)]
</code>```

Body:
Consider the following code below:

list1 = ['1x', '2x']
list2 = ['x18', 'x74']
list3 = [('100p1', '100p2'), ('300p1', '300p2')]

gen_list = [[a,b] for a in list1 for b in list2]

for new_list in gen_list:
    for c in list3:
        print(new_list.extend(c))

My target result is like this:

[['1x','x18, '100p1', '100p2'],
 ['1x','x74, '100p1', '100p2'],
 ['1x','x18, '300p1', '300p2'],
 ['1x','x74, '300p1', '300p2'],
 ['2x','x18, '100p1', '100p2'],
 ['2x','x74, '100p1', '100p2'],
 ['2x','x18, '300p1', '300p2'],
 ['2x','x74, '300p1', '300p2']]

but the result of the above code is this:

None
None
None
None
None
None
None
None

What necessary correction do I need to apply on my code? Thanks in advance.

Body:
using itertools.product, unpacking and a list comprehension

[[l[0], l[2], *l[1]] for l in itertools.product(list1, list3, list2)]

or

[[l1, l2, *l3] for l1, l3, l2 in itertools.product(list1, list3, list2)]

before Python 3.5

For versions before Python 3.5 you could do something like this

[[l1, l2] + list(l3) for l1, l3, l2 in itertools.product(list1, list3, list2)]

If you know l3 only contains 2 elements you can use nested unpacking, as mentioned by @ShadowRanger

[[a, b, c1, c2] for a, (c1, c2), b in itertools.product(list1, list3, list2)]


问:
How to get the value of parameter in servlet?
```<code>public class Sender extends HttpServlet {

  @Override
  protected void doPost(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {

    Test t=new Test();
    StringBuilder a=player;

  }

  public void attackPlayer(StringBuilder player){
    System.out.println("code"+player);
  }
}
</code>```

i want to store the value of player in variable a. Is it possible to get the value of parameter

答:
Since you are using doPost() method, you must pass parameter by a http-post request. Or if you want to pass parameters through URL, then you must catch the parameter in doGet() method in your servlet.

```<code>http://example.com?username=Miiii&pass=123
</code>```

In above URL, username is a parameter having value = Miiii
and same with pass too. and two parameters are separated by &.

If you want to hide your parameters and their values, you can send them through a form in HTML and select method=POST in form attribute.
This form (POST method) parameters will call doPost() directly, so catch them in doPost().

Also in your servlet; the way to get parameter is :

```<code> // see the same way in doGet() and doPost().. no change in catching style

 String user = request.getParameter("username");
 String password = request.getParameter("pass");

  NB:
 "username" must be exactly same as **username** = Miiii & pass...
</code>```

Body:
public class Sender extends HttpServlet {

  @Override
  protected void doPost(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {

    Test t=new Test();
    StringBuilder a=player;

  }

  public void attackPlayer(StringBuilder player){
    System.out.println("code"+player);
  }
}

i want to store the value of player in variable a. Is it possible to get the value of parameter

Body:
Since you are using doPost() method, you must pass parameter by a http-post request. Or if you want to pass parameters through URL, then you must catch the parameter in doGet() method in your servlet.

http://example.com?username=Miiii&pass=123

In above URL, username is a parameter having value = Miiii
and same with pass too. and two parameters are separated by &.

If you want to hide your parameters and their values, you can send them through a form in HTML and select method=POST in form attribute.
This form (POST method) parameters will call doPost() directly, so catch them in doPost().

Also in your servlet; the way to get parameter is :

 // see the same way in doGet() and doPost().. no change in catching style

 String user = request.getParameter("username");
 String password = request.getParameter("pass");

  NB:
 "username" must be exactly same as **username** = Miiii & pass...

ContentLicense: CC BY-SA 4.0


问:
Binding textblock value doesn't change after changing binded value
Why does TextBlock "T1" not show "101" after clicking on Button "B1" and still shows "100"?

```<code><StackPanel>
    <TextBlock Name="T1" Text="{x:Bind value, Mode=OneWay}"/>
    <Button Name="B1" Content="+1" Click="B1_Click"/>
</StackPanel>
</code>```

and

```<code>public sealed partial class MainPage : Page
{
    public int value;
    public MainPage()
    {
        InitializeComponent();
        value = 100; // initial value
    }
    private void B1_Click(object sender, Windows.UI.Xaml.RoutedEventArgs e)
    {
        value = value + 1;
    }
}
</code>```

答:
Your value is a field, yes it works with x:Bind. Actually it should even work being private.

But in order for the UI to update the value of value, you need to make one of the three changes below -

Call Bindings.Update() after setting it.

change it to a dependency property.

Change it to a normal property but implement INotifyPropertyChanged on your page and raise property changed event on the setter. You can read more from here.

But which one to pick? This is normally what I do -

If the property rarely changes, I use Bindings.Update() and remove Mode=OneWay from the binding to have the best performance.

If the property lives in the code-behind of a UI element (like in your case), I go with a dependency property.

If the property lives inside a ViewModel, I use INPC.

Body:
Why does TextBlock "T1" not show "101" after clicking on Button "B1" and still shows "100"?

<StackPanel>
    <TextBlock Name="T1" Text="{x:Bind value, Mode=OneWay}"/>
    <Button Name="B1" Content="+1" Click="B1_Click"/>
</StackPanel>

and

public sealed partial class MainPage : Page
{
    public int value;
    public MainPage()
    {
        InitializeComponent();
        value = 100; // initial value
    }
    private void B1_Click(object sender, Windows.UI.Xaml.RoutedEventArgs e)
    {
        value = value + 1;
    }
}


问:
Need to change date format in angular 2
Currently using Date() gives it in format

```<code>Wed Jul 05 2017 15:14:53 GMT+0530 (India Standard Time)
</code>```

i want to change it so that I get it in this format (want GMT time not IST)

```<code>Jul 5 15:14:53 2017 GMT
</code>```

I also want to know how I can get the time say 2 years from now.

EDIT:

I have fixed the format but now having problems in setting it up to gmt time instead of ist fixed it by :

```<code>let d = new Date();
let month = d.toLocaleString("en-us", { month: "short" });
let datestring = month + " " + d.getDate() + " " + (d.getHours()) + ":" + (d.getMinutes())+ ":" +d.getSeconds() + " " + (d.getFullYear()+2) + " GMT";
</code>```

but naturally that does not actauly show the gmt, its just IST so now trying to fix that.

答:
You can use the momentjs library and get the date in GMT time as follows:

```<code>@Pipe({
    name: 'gmtDate'
}) export class GmtDate implements PipeTransform {
    transform(value: Date, addYear: number = 0): string {
        // utc() - turns date into GMT
        return moment(value).add(addYear, 'year').utc().format("MMM D HH:mm:ss YYYY")
    }
}

@Component({
    selector: 'my-app',
    template: `
        <div>
          <h2>{{myDate | gmtDate}}</h2>
          <h2>{{myDate | gmtDate:2}}</h2>
        </div>
    `,
}) export class App {
    myDate: string = new Date();;
}
</code>```

Here is a plnkr demo of above pipe.

Title: Need to change date format in angular 2

Body:
Currently using Date() gives it in format

Wed Jul 05 2017 15:14:53 GMT+0530 (India Standard Time)

i want to change it so that I get it in this format (want GMT time not IST)

Jul 5 15:14:53 2017 GMT

I also want to know how I can get the time say 2 years from now.

EDIT:

I have fixed the format but now having problems in setting it up to gmt time instead of ist fixed it by :

let d = new Date();
let month = d.toLocaleString("en-us", { month: "short" });
let datestring = month + " " + d.getDate() + " " + (d.getHours()) + ":" + (d.getMinutes())+ ":" +d.getSeconds() + " " + (d.getFullYear()+2) + " GMT";

but naturally that does not actauly show the gmt, its just IST so now trying to fix that.

Body:
You can use the momentjs library and get the date in GMT time as follows:

@Pipe({
    name: 'gmtDate'
}) export class GmtDate implements PipeTransform {
    transform(value: Date, addYear: number = 0): string {
        // utc() - turns date into GMT
        return moment(value).add(addYear, 'year').utc().format("MMM D HH:mm:ss YYYY")
    }
}

@Component({
    selector: 'my-app',
    template: `
        <div>
          <h2>{{myDate | gmtDate}}</h2>
          <h2>{{myDate | gmtDate:2}}</h2>
        </div>
    `,
}) export class App {
    myDate: string = new Date();;
}

Here is a plnkr demo of above pipe.


问:
IoC with AOP (PostSharp) in MonoDroid
I'm working on a MonoDroid app, and there really isn't a good DI solution yet (at least that I know of).

I've gotten PostSharp to work on MonoDroid, and I'm using the Location Intercept aspect as a way to inject dependencies into fields/properties without using a service locator (outside of the aspect anyway).

Here's what I'm working with so far: https://github.com/mgroves/MonodroidStockPortfolio/blob/develop/MonoStockPortfolio/Framework/IoCAttribute.cs

It's rough, and definitely needs refactoring, but you get the idea from the basic structure.  However, I'm not completely convinced that this approach is the best way.  How would you go about using DI/IoC in a MonoDroid app, with or without PostSharp?

答:
It's more "classic container" rather than AOP, and MonoDroid isn't a platform I've tested it on (it's been tested on Mono, MonoTouch, Silverlight, Windows Mobile and WinPhone7 though), but TinyIoC should work if it fits the bill:

http://hg.grumpydev.com/tinyioc/wiki/Home

Title: IoC with AOP (PostSharp) in MonoDroid


问:
Accessing json data from wunderground API?
I have this async function below that taps into a weather API and I would just like to retrieve two pieces of info from the API: Temperature in F & C. I removed the API_Key but it's free to get one on the site if necessary.

I can confirm I am receiving the json object due to my console.log(response) statement, but Im not sure how to access these data points in such heavily embedded json notation.

I guess my question is if I wanted to access say 'full' for full city name I thought I'd do something like response.observation_location.full but that doesn't work...

Help?

```<code>async loadWeather() {
        // let zip = this.args.zip || 97239;
        let response = await fetch(`http://api.wunderground.com/api/API_KEY/conditions/q/CA/San_Francisco.json`);
        console.log(response);
        this.weather = await response.json();
        // setTimeout( () => { this.loadWeather(); }, 2000);
    }
</code>```

Here is a partial output of the response json:

```<code>{
    "response": {
        "version": "0.1",
        "termsofService": "http://www.wunderground.com/weather/api/d/terms.html",
        "features": {
            "conditions": 1
        }
    },
    "current_observation": {
        "image": {
            "url": "http://icons.wxug.com/graphics/wu2/logo_130x80.png",
            "title": "Weather Underground",
            "link": "http://www.wunderground.com"
        },
        "display_location": {
            "full": "San Francisco, CA",
            "city": "San Francisco",
            "state": "CA",
            "state_name": "California",
            "country": "US",
            "country_iso3166": "US",
            "zip": "94102",
            "magic": "1",
            "wmo": "99999",
            "latitude": "37.77999878",
            "longitude": "-122.41999817",
            "elevation": "60.0"
        },
        "observation_location": {
            "full": "SOMA, San Francisco, California",
            "city": "SOMA, San Francisco",
            "state": "California",
            "country": "US",
            "country_iso3166": "US",
            "latitude": "37.778488",
            "longitude": "-122.408005",
            "elevation": "23 ft"
        },
</code>```

I have tried doing console.log(response["current_observation"]) just to access a nested data value but that doesnt seem to work as it returns undefined.

答:
Ok I solved my own issue, but for the record:

response needed to be converted to json via resonse.json()

and then I can access properties as expected

```<code>this.weather = await response.json();
console.log(this.weather["current_observation"]["temp_f"]);
console.log(this.weather["current_observation"]["temp_c"]);
</code>```

Body:
I have this async function below that taps into a weather API and I would just like to retrieve two pieces of info from the API: Temperature in F & C. I removed the API_Key but it's free to get one on the site if necessary.

I can confirm I am receiving the json object due to my console.log(response) statement, but Im not sure how to access these data points in such heavily embedded json notation.

I guess my question is if I wanted to access say 'full' for full city name I thought I'd do something like response.observation_location.full but that doesn't work...

Help?

async loadWeather() {
        // let zip = this.args.zip || 97239;
        let response = await fetch(`http://api.wunderground.com/api/API_KEY/conditions/q/CA/San_Francisco.json`);
        console.log(response);
        this.weather = await response.json();
        // setTimeout( () => { this.loadWeather(); }, 2000);
    }

Here is a partial output of the response json:

{
    "response": {
        "version": "0.1",
        "termsofService": "http://www.wunderground.com/weather/api/d/terms.html",
        "features": {
            "conditions": 1
        }
    },
    "current_observation": {
        "image": {
            "url": "http://icons.wxug.com/graphics/wu2/logo_130x80.png",
            "title": "Weather Underground",
            "link": "http://www.wunderground.com"
        },
        "display_location": {
            "full": "San Francisco, CA",
            "city": "San Francisco",
            "state": "CA",
            "state_name": "California",
            "country": "US",
            "country_iso3166": "US",
            "zip": "94102",
            "magic": "1",
            "wmo": "99999",
            "latitude": "37.77999878",
            "longitude": "-122.41999817",
            "elevation": "60.0"
        },
        "observation_location": {
            "full": "SOMA, San Francisco, California",
            "city": "SOMA, San Francisco",
            "state": "California",
            "country": "US",
            "country_iso3166": "US",
            "latitude": "37.778488",
            "longitude": "-122.408005",
            "elevation": "23 ft"
        },

I have tried doing console.log(response["current_observation"]) just to access a nested data value but that doesnt seem to work as it returns undefined.

Body:
Ok I solved my own issue, but for the record:

response needed to be converted to json via resonse.json()

and then I can access properties as expected

this.weather = await response.json();
console.log(this.weather["current_observation"]["temp_f"]);
console.log(this.weather["current_observation"]["temp_c"]);


问:
Error trying to send email through Gmail using SwiftMailer
I'm following Symfony 3 Documentation to send an email from my controller, but I'm getting an error. I made sure to follow each step from the above page correctly, but no use.

This is how my controller looks like:

```<code><?php

namespace MyBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Symfony\Component\HttpFoundation\Response;

class DefaultController extends Controller
{
    /**
     * @Route("/")
     */
    public function indexAction(\Swift_Mailer $mailer)
    {
        $message = (new \Swift_Message('Hello Email'))
            ->setFrom('send@example.com')
            ->setTo('my.address@gmail.com')
            ->setBody(
                $this->renderView(
                    // app/Resources/views/Emails/registration.html.twig
                    'MyBundle::Emails/registration.html.twig',
                    array('name' => 'John Doe')
                ),
                'text/html'
            );

        $mailer->send($message);

        return new Response('<html<body>Sent</body></html>');
    }
}
</code>```

This is the error I'm getting:

Controller "MyBundle\Controller\DefaultController::indexAction()" requires that you provide a value for the "$mailer" argument. Either the argument is nullable and no null value has been provided, no default value has been provided or because there is a non optional argument after this one.

Comparing to the documentation page, I'm pretty sure everything is as it should be, so can anyone please help me find the source of this error?

答: Simply remove the $mailer from your constructor (you are not in a service, you are in a controller) , and use $this->get('mailer')->send($message); to send. (again, you are in a controller, you have access to the mailer service, no need to try and inject it into the constructor)

Body:
I'm following Symfony 3 Documentation to send an email from my controller, but I'm getting an error. I made sure to follow each step from the above page correctly, but no use.

This is how my controller looks like:

<?php

namespace MyBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Symfony\Component\HttpFoundation\Response;

class DefaultController extends Controller
{
    /**
     * @Route("/")
     */
    public function indexAction(\Swift_Mailer $mailer)
    {
        $message = (new \Swift_Message('Hello Email'))
            ->setFrom('send@example.com')
            ->setTo('my.address@gmail.com')
            ->setBody(
                $this->renderView(
                    // app/Resources/views/Emails/registration.html.twig
                    'MyBundle::Emails/registration.html.twig',
                    array('name' => 'John Doe')
                ),
                'text/html'
            );

        $mailer->send($message);

        return new Response('<htmlSent');
    }
}

This is the error I'm getting:

Controller "MyBundle\Controller\DefaultController::indexAction()" requires that you provide a value for the "$mailer" argument. Either the argument is nullable and no null value has been provided, no default value has been provided or because there is a non optional argument after this one.

Comparing to the documentation page, I'm pretty sure everything is as it should be, so can anyone please help me find the source of this error?


问:
Installing Windows Server for SharePoint
I want to install Microsoft SharePoint 2016 on my computer. To do this, first I need to install Windows Server. And I have 2 questions about doing it in the best way:

1.Which version should I choose - Windows Server 2012 (R2) or 2016?

2.Should I install it directly on computer as a second system OR install it on virtual machine (VirtualBox)

答:
Windows Server 2016.  In general the latest Operating System has better security and Microsoft support sunsets at a later date.

Either is fine.  Just keep in mind, if you install on a virtual machine, make sure you do not use dynamic memory.  SharePoints distributed cache has problems with vms using dynamic memory and Microsoft does not recommend.


问:
Permutations with repetition without two consecutive equal elements
I need a function that generates all the permutation with repetition of an iterable with the clause that two consecutive elements must be different; for example

```<code>f([0,1],3).sort()==[(0,1,0),(1,0,1)]
#or
f([0,1],3).sort()==[[0,1,0],[1,0,1]]
#I don't need the elements in the list to be sorted.
#the elements of the return can be tuples or lists, it doesn't change anything
</code>```

Unfortunatly itertools.permutation doesn't work for what I need (each element in the iterable is present once or no times in the return)

I've tried a bunch of definitions; first, filterting elements from itertools.product(iterable,repeat=r) input, but is too slow for what I need.

```<code>from itertools import product
def crp0(iterable,r):
l=[]
for f in product(iterable,repeat=r):
    #print(f)
    b=True
    last=None #supposing no element of the iterable is None, which is fine for me
    for element in f:
        if element==last:
            b=False
            break
        last=element
    if b: l.append(f)
return l
</code>```

Second, I tried to build r for cycle, one inside the other (where r is the class of the permutation, represented as k in math).

```<code>def crp2(iterable,r):
    a=list(range(0,r))
    s="\n"
    tab="    " #4 spaces
    l=[]
    for i in a:
        s+=(2*i*tab+"for a["+str(i)+"] in iterable:\n"+
        (2*i+1)*tab+"if "+str(i)+"==0 or a["+str(i)+"]!=a["+str(i-1)+"]:\n")
    s+=(2*i+2)*tab+"l.append(a.copy())"
    exec(s)
    return l
</code>```

I know, there's no need you remember me: exec is ugly, exec can be dangerous, exec isn't easy-readable... I know.
To understand better the function I suggest you to replace exec(s) with print(s).

I give you an example of what string is inside the exec for crp([0,1],2):

```<code>for a[0] in iterable:
    if 0==0 or a[0]!=a[-1]:
        for a[1] in iterable:
            if 1==0 or a[1]!=a[0]:
                l.append(a.copy())
</code>```

But, apart from using exec, I need a better functions because crp2 is still too slow (even if faster than crp0); there's any way to recreate the code with r for without using exec? There's any other way to do what I need?

答:
You could try to return a generator instead of a list. With large values of r, your method will take a very long time to process product(iterable,repeat=r) and will return a huge list.

With this variant, you should get the first element very fast:

```<code>from itertools import product

def crp0(iterable, r):
    for f in product(iterable, repeat=r):
        last = f[0]
        b = True
        for element in f[1:]:
            if element == last:
                b = False
                break
            last = element
        if b:
            yield f

for no_repetition in crp0([0, 1, 2], 12):
    print(no_repetition)

# (0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1)
# (1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0)
</code>```

Body:
I need a function that generates all the permutation with repetition of an iterable with the clause that two consecutive elements must be different; for example

f([0,1],3).sort()==[(0,1,0),(1,0,1)]
#or
f([0,1],3).sort()==[[0,1,0],[1,0,1]]
#I don't need the elements in the list to be sorted.
#the elements of the return can be tuples or lists, it doesn't change anything

Unfortunatly itertools.permutation doesn't work for what I need (each element in the iterable is present once or no times in the return)

I've tried a bunch of definitions; first, filterting elements from itertools.product(iterable,repeat=r) input, but is too slow for what I need.

from itertools import product
def crp0(iterable,r):
l=[]
for f in product(iterable,repeat=r):
    #print(f)
    b=True
    last=None #supposing no element of the iterable is None, which is fine for me
    for element in f:
        if element==last:
            b=False
            break
        last=element
    if b: l.append(f)
return l

Second, I tried to build r for cycle, one inside the other (where r is the class of the permutation, represented as k in math).

def crp2(iterable,r):
    a=list(range(0,r))
    s="\n"
    tab="    " #4 spaces
    l=[]
    for i in a:
        s+=(2*i*tab+"for a["+str(i)+"] in iterable:\n"+
        (2*i+1)*tab+"if "+str(i)+"==0 or a["+str(i)+"]!=a["+str(i-1)+"]:\n")
    s+=(2*i+2)*tab+"l.append(a.copy())"
    exec(s)
    return l

I know, there's no need you remember me: exec is ugly, exec can be dangerous, exec isn't easy-readable... I know.
To understand better the function I suggest you to replace exec(s) with print(s).

I give you an example of what string is inside the exec for crp([0,1],2):

for a[0] in iterable:
    if 0==0 or a[0]!=a[-1]:
        for a[1] in iterable:
            if 1==0 or a[1]!=a[0]:
                l.append(a.copy())

But, apart from using exec, I need a better functions because crp2 is still too slow (even if faster than crp0); there's any way to recreate the code with r for without using exec? There's any other way to do what I need?

Body:
You could try to return a generator instead of a list. With large values of r, your method will take a very long time to process product(iterable,repeat=r) and will return a huge list.

With this variant, you should get the first element very fast:

from itertools import product

def crp0(iterable, r):
    for f in product(iterable, repeat=r):
        last = f[0]
        b = True
        for element in f[1:]:
            if element == last:
                b = False
                break
            last = element
        if b:
            yield f

for no_repetition in crp0([0, 1, 2], 12):
    print(no_repetition)

# (0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1)
# (1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0)