问:
Django sessions set default key usage
So I have a question about session keys, normally when a user visits the site for the first time a session key does not exist yet hence you have to set a default.

```<code>set_date = request.session.get('set_date', '2017-07-06')
</code>```

I use sessions to store an user given date and use this date in different views. The code below does almost exactly what I want it to do, at least without a default set. When I set a default value for 'set_date', I can't seem to use the date in different views, once I switch views the default is set again.

What's the right way to set a default to 'set_date'?

```<code>views.py

"""
Check-ins listview
"""

from .forms import DateSelection

class CheckInsListView(generic.ListView, FormMixin):
    form_class = DateSelection
    model = Delivery
    paginate_by = 10
    queryset = Delivery.objects.filter(status='AR')
    template_name = 'check-ins.html'

    """
    Save the user given date in a session key set_date
    """

    def get_context_data(self, *args, **kwargs):
        context = super(CheckInsListView, self).get_context_data(*args, **kwargs)
        user_date = self.request.GET.get("date_selection")

        if user_date: # If user enters date
            self.request.session['set_date'] = user_date # Save given date in session
            context ['set_date'] = self.request.session['set_date'] # Sent date to context

        else:
            context ['set_date'] = self.request.session['set_date'] # Use date from session

        return context

    """
    Use the date from session to filter the query results
    """

    def get_queryset(self):
        queryset = super(CheckInsListView, self).get_queryset()

        user_date = self.request.GET.get('date_selection')
        session_date = self.request.session['set_date']

        if user_date:
            return queryset.filter(arrival_date__icontains=user_date) # Filter on user given date

        else:
            return queryset.filter(arrival_date__icontains=session_date) # Filter on date from session

        return queryset # Return queryset without filter
</code>```

Thanks in advance!

答:
In your question you mention get, which returns a default value if the key does not exist, but does not set the default value.

Use setdefault to set the default value when the key does not exist.

```<code>set_date = request.session.setdefault('set_date', '2017-07-06')
</code>```

Title: Django sessions set default key usage

Body:
So I have a question about session keys, normally when a user visits the site for the first time a session key does not exist yet hence you have to set a default.

set_date = request.session.get('set_date', '2017-07-06')

I use sessions to store an user given date and use this date in different views. The code below does almost exactly what I want it to do, at least without a default set. When I set a default value for 'set_date', I can't seem to use the date in different views, once I switch views the default is set again.

What's the right way to set a default to 'set_date'?

views.py

"""
Check-ins listview
"""

from .forms import DateSelection

class CheckInsListView(generic.ListView, FormMixin):
    form_class = DateSelection
    model = Delivery
    paginate_by = 10
    queryset = Delivery.objects.filter(status='AR')
    template_name = 'check-ins.html'

    """
    Save the user given date in a session key set_date
    """

    def get_context_data(self, *args, **kwargs):
        context = super(CheckInsListView, self).get_context_data(*args, **kwargs)
        user_date = self.request.GET.get("date_selection")

        if user_date: # If user enters date
            self.request.session['set_date'] = user_date # Save given date in session
            context ['set_date'] = self.request.session['set_date'] # Sent date to context

        else:
            context ['set_date'] = self.request.session['set_date'] # Use date from session

        return context

    """
    Use the date from session to filter the query results
    """

    def get_queryset(self):
        queryset = super(CheckInsListView, self).get_queryset()

        user_date = self.request.GET.get('date_selection')
        session_date = self.request.session['set_date']

        if user_date:
            return queryset.filter(arrival_date__icontains=user_date) # Filter on user given date

        else:
            return queryset.filter(arrival_date__icontains=session_date) # Filter on date from session

        return queryset # Return queryset without filter

Thanks in advance!

Body:
In your question you mention get, which returns a default value if the key does not exist, but does not set the default value.

Use setdefault to set the default value when the key does not exist.

set_date = request.session.setdefault('set_date', '2017-07-06')


来源: stackexchange

问:
Twilio outgoing browser call getting disconnected on hold
I'm using Twilio Outgoing Browser Calls in my project. The twiml to make call is like this :

```<code><Response>
    <Dial action="hold_twiml.php" callerId="xxxxxxxxxx">
          xxxxxxxxxx
    </Dial>
</Response>
</code>```

hold_twiml.php

```<code>if ( $_REQUEST['DialCallStatus'] == 'completed' ) { ?>
<Response>
    <Hangup/>
</Response>
<?php
}
else {
?>
<Response>
    <Play>http://demo.twilio.com/docs/classic.mp3</Play>
    <Redirect>hold_twiml.php</Redirect>
</Response>
<?php
}
?>
</code>```

I want to disconnect the call when the call ends from client/browser. For that I've added the if ( $_REQUEST['DialCallStatus'] == 'completed' ) condition and now the call is getting ended from both sides. But now the Hold feature is not working properly. When I click the hold button the following code will be executed.

```<code>if ( $action == 'hold' ) {
 $url = "holding_twiml.php";
 $call = $client->calls->read(
        array("ParentCallSid" => $_POST['callSid'])
    )[0];
} else {  // unhold
 $call = $client->calls($_POST['callSid'])->fetch();
 $url = "redirecting_twiml.php";
}
$call->update(
    array(
        "url" => $url,
        "method" => "POST"
    )
);
</code>```

holding_twiml.php

```<code><Response>
    <Enqueue waitUrl="hold_music_twiml.xml">xx</Enqueue>
</Response>
</code>```

hold_music_twiml.xml

```<code><Response>
    <Play>http://demo.twilio.com/docs/classic.mp3</Play>
</Response>
</code>```

redirecting_twiml.php

```<code><Response>
  <Dial action="hold_twiml.php">
    <Queue>xx</Queue>
  </Dial>
</Response>
</code>```

Now on clicking Hold, the call on browser is getting ended and the call over client(phone) is put into hold.

Can anyone help me to fix the issue? Thanks in advance.

答:
Twilio developer evangelist here.

You are using an action attribute on the <Dial> TwiML. From the documentation:

If you provide an 'action' URL, Twilio will continue the current call
  after the dialed party has hung up, using the TwiML received in your
  response to the 'action' URL request.

So, when the client hangs up, Twilio is continuing the call using the TwiML received from your action URL.

If you remove the action attribute or change the TwiML to <Hangup/> then your call will end when the client hangs up.

Let me know if that helps at all.

ContentLicense: CC BY-SA 3.0

Body:
I'm using Twilio Outgoing Browser Calls in my project. The twiml to make call is like this :

<Response>
    <Dial action="hold_twiml.php" callerId="xxxxxxxxxx">
          xxxxxxxxxx
    </Dial>
</Response>

hold_twiml.php

if ( $_REQUEST['DialCallStatus'] == 'completed' ) { ?>
<Response>
    <Hangup/>
</Response>
<?php
}
else {
?>
<Response>
    <Play>http://demo.twilio.com/docs/classic.mp3</Play>
    <Redirect>hold_twiml.php</Redirect>
</Response>
<?php
}
?>

I want to disconnect the call when the call ends from client/browser. For that I've added the if ( $_REQUEST['DialCallStatus'] == 'completed' ) condition and now the call is getting ended from both sides. But now the Hold feature is not working properly. When I click the hold button the following code will be executed.

if ( $action == 'hold' ) {
 $url = "holding_twiml.php";
 $call = $client->calls->read(
        array("ParentCallSid" => $_POST['callSid'])
    )[0];
} else {  // unhold
 $call = $client->calls($_POST['callSid'])->fetch();
 $url = "redirecting_twiml.php";
}
$call->update(
    array(
        "url" => $url,
        "method" => "POST"
    )
);

holding_twiml.php

<Response>
    <Enqueue waitUrl="hold_music_twiml.xml">xx</Enqueue>
</Response>

hold_music_twiml.xml

<Response>
    <Play>http://demo.twilio.com/docs/classic.mp3</Play>
</Response>

redirecting_twiml.php

<Response>
  <Dial action="hold_twiml.php">
    <Queue>xx</Queue>
  </Dial>
</Response>

Now on clicking Hold, the call on browser is getting ended and the call over client(phone) is put into hold.

Can anyone help me to fix the issue? Thanks in advance.


问:
AWS ALB setting Cache-Control private max-age header
I have a Symfony 3 application that is deployed on an AWS Beanstalk instance with one EC2 instance behind an Application Load Balancer since I use HTTP/2.

I have found a weird problem with the load balancer however.I know that it should not set any caching headers, but for some reason it does.On my testing machine, using the same code, I have this header sent with the response:

```<code>cache-control:private
</code>```

But on the AWS server this header is sent instead:

```<code>cache-control:private, max-age=86400
</code>```

This break my application since I do not want the client's browser to cache the response since my application should only be accessed by logged in users.The only way I have found to fix this is by calling this function in my app.php file before sending the response back to the client:

```<code>$response->headers->removeCacheControlDirective('private');
</code>```

This adds the no-cache directive to the cache-control header which prevents the browser from caching the response, but I am not sure if this is the right approach since the AWS app still sends the max-age directive and I am not sure the no-cache directive overwrites the others in all browsers.

After the fix this is what I get from my server:

```<code>cache-control:no-cache, private
</code>```

And this from AWS:

```<code>cache-control:no-cache, private, max-age=86400
</code>```

TL/DR: So, what I am asking, is there any way to remove the max-age directive from what the AWS server sends?

Thank you, I have used StackOverflow for many years but this is the first time I am asking a questions since I have not found the answer to this anywhere.

答:
So I have finally found the answer and it turns out it has nothing to do with AWS...
The reason for this is that in my .htaccess file I had a mod_expires directive with this line on it:

```<code>ExpiresByType text/html "access plus 1 days"
</code>```

Which added that cache header to all html pages...And for some reason neither my Apache on Linux or on Windows had mod_expires on but the web server from AWS had it...

Body:
I have a Symfony 3 application that is deployed on an AWS Beanstalk instance with one EC2 instance behind an Application Load Balancer since I use HTTP/2.

I have found a weird problem with the load balancer however.I know that it should not set any caching headers, but for some reason it does.On my testing machine, using the same code, I have this header sent with the response:

cache-control:private

But on the AWS server this header is sent instead:

cache-control:private, max-age=86400

This break my application since I do not want the client's browser to cache the response since my application should only be accessed by logged in users.The only way I have found to fix this is by calling this function in my app.php file before sending the response back to the client:

$response->headers->removeCacheControlDirective('private');

This adds the no-cache directive to the cache-control header which prevents the browser from caching the response, but I am not sure if this is the right approach since the AWS app still sends the max-age directive and I am not sure the no-cache directive overwrites the others in all browsers.

After the fix this is what I get from my server:

cache-control:no-cache, private

And this from AWS:

cache-control:no-cache, private, max-age=86400

TL/DR: So, what I am asking, is there any way to remove the max-age directive from what the AWS server sends?

Thank you, I have used StackOverflow for many years but this is the first time I am asking a questions since I have not found the answer to this anywhere.

Body:
So I have finally found the answer and it turns out it has nothing to do with AWS...
The reason for this is that in my .htaccess file I had a mod_expires directive with this line on it:

ExpiresByType text/html "access plus 1 days"

Which added that cache header to all html pages...And for some reason neither my Apache on Linux or on Windows had mod_expires on but the web server from AWS had it...


问:
How do I use a PostgreSQL function that returns a table as a CakePHP 3 Model?
Using Cake PHP 3.x and we have a PostgreSQL 9.6.3 db.

We make extensive use of PG functions that return tables - for example

```<code>select * from getStudies(cid,UID, SID);
</code>```

Functions are used for various applications - one of them is more complex filtering of rows from a table - where Cake has difficulty.

One option is to implement the logic as a custom Cake Model method in PHP, but the SQL code and amount of  joins makes it messy in PHP.

We think we should be able to create a Cake Model from the function and then pass the parameters via Cake Model methods but so far - it is unclear how to do that.

This code works but it returns the data without the columns and I have not been able to figure out how to use reflection to get the _columns properties from the Model schema.

```<code>  public function getStudies($data = array()) {
      $customer_id = $data['customer_id'];
      $connection = ConnectionManager::get('default');
      $sql = "select * from getStudies($customer_id)";
      $results = $stmt->fetch();
      return $results;   }
</code>```

So -
Option 1 - figure out how to model a function that returns tables as a cake model

Option 2 - use reflection to get the _columns and merge it with the query result

Thanks

答:
As you've mentioned in the comments, the schema columns details can be accessed via its columns() method. You could process the results manually using the schema information, or use the function as the source, just like in your example.

The query builders from() method supports raw SQL as well as expressions, so you can basically add whatever you like, however expressions will be wrapped in parentheses, which will be invalid SQL in case of a function call, so you'd have to go with raw SQL, and bindings (please never inject (user)data into queries directly):

public function getStudies($customerId)
{
    return $this
        ->find()
        ->from([
            $this->alias() => 'getStudies(:customerId)'
        ])
        ->bind(':customerId', $customerId, 'integer');
}
```

<p>That should generate a query similar to</p>

<pre class="lang-sql prettyprint-override"><code>SELECT
    Alias.column1, Alias.column2, ...
FROM
    getStudies(:customerId) Alias
</code>```

Body:
Using Cake PHP 3.x and we have a PostgreSQL 9.6.3 db.

We make extensive use of PG functions that return tables - for example

select * from getStudies(cid,UID, SID);

Functions are used for various applications - one of them is more complex filtering of rows from a table - where Cake has difficulty.

One option is to implement the logic as a custom Cake Model method in PHP, but the SQL code and amount of  joins makes it messy in PHP.

We think we should be able to create a Cake Model from the function and then pass the parameters via Cake Model methods but so far - it is unclear how to do that.

This code works but it returns the data without the columns and I have not been able to figure out how to use reflection to get the _columns properties from the Model schema.

  public function getStudies($data = array()) {
      $customer_id = $data['customer_id'];
      $connection = ConnectionManager::get('default');
      $sql = "select * from getStudies($customer_id)";
      $results = $stmt->fetch();
      return $results;   }

So -
Option 1 - figure out how to model a function that returns tables as a cake model

Option 2 - use reflection to get the _columns and merge it with the query result

Thanks

Body:
As you've mentioned in the comments, the schema columns details can be accessed via its columns() method. You could process the results manually using the schema information, or use the function as the source, just like in your example.

The query builders from() method supports raw SQL as well as expressions, so you can basically add whatever you like, however expressions will be wrapped in parentheses, which will be invalid SQL in case of a function call, so you'd have to go with raw SQL, and bindings (please never inject (user)data into queries directly):

public function getStudies($customerId)
{
    return $this
        ->find()
        ->from([
            $this->alias() => 'getStudies(:customerId)'
        ])
        ->bind(':customerId', $customerId, 'integer');
}

That should generate a query similar to

SELECT
    Alias.column1, Alias.column2, ...
FROM
    getStudies(:customerId) Alias


问:
Difference between env/bin/python and env/lib/pythonX.Y (note the lib)
Sorry for the noob question - just trying to understand the flow of how python works.

Does anyone know what the difference between env/bin/python and env/lib/python3.6 is? It will be really helpful to know. (Note the different paths - bin and lib)

Thanks :)

EDIT: I only have one version of python installed in the environment. The one thing to notice here is that env/bin/python has a symbolic link to env/bin/python3.6 (which is a binary file, obviously). But there is a directory in env/lib/python3.6 in which there are directories like site-packages where the installed packages are stored.

So my questions is... when is the binary file in /env/bin used and when is the directory accessed? When I say 'python' in the shell, it goes to the bin but when I say 'import django' in the interpreter, it goes to python3.6 in lib and gets the package. Am i on the right track?

答:
Your machine can store multiple versions of python simultaneously, and which one is used depends on the PATH of your current terminal, or if you have a virtual environment set up and activated. You can tell which python interpreter is being used by typing the command

```<code>> which python
</code>```

If you have both python 2.7 and python 3 installed, you might also be able to choose one by using the full name in terminal

```<code>> python my_script.py # run using the default python interpreter
> python3 my_script.py # run using the configured version of python3
</code>```

You can find some additional resources in the official Python wiki that might help you learn about which version to use and why.

Body:
Your machine can store multiple versions of python simultaneously, and which one is used depends on the PATH of your current terminal, or if you have a virtual environment set up and activated. You can tell which python interpreter is being used by typing the command

> which python

If you have both python 2.7 and python 3 installed, you might also be able to choose one by using the full name in terminal

> python my_script.py # run using the default python interpreter
> python3 my_script.py # run using the configured version of python3

You can find some additional resources in the official Python wiki that might help you learn about which version to use and why.


问:
Update (pull) all docker images at once
Is there a command to update (pull) all the downloaded Docker images at once in the terminal ?</p>

答:
No, there is no built-in command to pull all docker images at once.

But you can try this (multiline) bash using docker --format :

```<code>for image in $(docker images --format "{{.Repository}}:{{.Tag}}" | grep -v '<none>')
do
  docker pull $image
done
</code>```

Or in one line:

```<code>for image in $(docker images --format "{{.Repository}}:{{.Tag}}" | grep -v '<none>'); do docker pull $image; done;
</code>```

Title: Update (pull) all docker images at once

Body:
No, there is no built-in command to pull all docker images at once.

But you can try this (multiline) bash using docker --format :

for image in $(docker images --format "{{.Repository}}:{{.Tag}}" | grep -v '<none>')
do
  docker pull $image
done

Or in one line:

for image in $(docker images --format "{{.Repository}}:{{.Tag}}" | grep -v '<none>'); do docker pull $image; done;


问:
Install new version of npm and use it instead of the shared one
We are many persons who work on the same server where our projects live. Every one of course has his own virtual environment.

We all share the same node.js v4.4.5 and npm 2.15.5.

However, I need npm >= 3.0.0, so I installed a newer version /usr/local/n/versions/node/8.1.3/bin/npm and I added aliases for node and npm into my ~/.bashrc

```<code> # ~/.bashrc
alias node='/usr/local/n/versions/node/8.1.3/bin/node'
alias npm='/usr/local/n/versions/node/8.1.3/bin/npm'
</code>```

Then I sourced it source ~/.bashrc and I thought it worked because

```<code>$ npm --version
5.0.3
</code>```

Until I run npm run dev

```<code>$ npm run dev

> training@1.0.0 dev /home/users/itsme/projects/training
> /usr/local/n/versions/node/8.1.3/bin/node build/dev-server.js

To use this template, you must update following to modules:

npm: 2.15.5 should be >= 3.0.0

npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! training@1.0.0 dev: `/usr/local/n/versions/node/8.1.3/bin/node build/dev-server.js`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the training@1.0.0 dev script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.

npm ERR! A complete log of this run can be found in:
npm ERR!     /home/users/itsme/.npm/_logs/2017-07-06T15_13_11_912Z-debug.log
</code>```

I don't understand why it seems to be running the shared outdated npm instead of mine.

And here another quite weird thing

```<code>$ which npm # shows the shared one

$ `which npm` --version
2.15.5
</code>```

答:
https://github.com/creationix/nvm

Node version manager makes managing multiple node environments a simple task.

Body:
We are many persons who work on the same server where our projects live. Every one of course has his own virtual environment.

We all share the same node.js v4.4.5 and npm 2.15.5.

However, I need npm >= 3.0.0, so I installed a newer version /usr/local/n/versions/node/8.1.3/bin/npm and I added aliases for node and npm into my ~/.bashrc

 # ~/.bashrc
alias node='/usr/local/n/versions/node/8.1.3/bin/node'
alias npm='/usr/local/n/versions/node/8.1.3/bin/npm'

Then I sourced it source ~/.bashrc and I thought it worked because

$ npm --version
5.0.3

Until I run npm run dev

$ npm run dev

> training@1.0.0 dev /home/users/itsme/projects/training
> /usr/local/n/versions/node/8.1.3/bin/node build/dev-server.js

To use this template, you must update following to modules:

npm: 2.15.5 should be >= 3.0.0

npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! training@1.0.0 dev: `/usr/local/n/versions/node/8.1.3/bin/node build/dev-server.js`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the training@1.0.0 dev script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.

npm ERR! A complete log of this run can be found in:
npm ERR!     /home/users/itsme/.npm/_logs/2017-07-06T15_13_11_912Z-debug.log

I don't understand why it seems to be running the shared outdated npm instead of mine.

And here another quite weird thing

$ which npm # shows the shared one

$ `which npm` --version
2.15.5


问:
Faster alternative to push_back(size is known)
I have a float vector. As I process certain data, I push it back.I always know what the size will be while declaring the vector.

For the largest case, it is 172,490,752 floats. This takes about eleven seconds just to push_back everything.

Is there a faster alternative, like a different data structure or something?

答:
The reason push_back is slow is that it will need to copy all the data several times as the vector grows, and even when it doesn’t need to copy data it needs to check. Vectors grow quickly enough that this doesn’t happen often, but it still does happen. A rough rule of thumb is that every element will need to be copied on average once or twice; the earlier elements will need to be copied a lot more, but almost half the elements won’t need to be copied at all.

You can avoid the copying, but not the checks, by calling reserve on the vector when you create it, ensuring it has enough space. You can avoid both the copying and the checks by creating it with the right size from the beginning, by giving the number of elements to the vector constructor, and then inserting using indexing as Tobias suggested; unfortunately, this also goes through the vector an extra time initializing everything.

If you know the number of floats at compile time and not just runtime, you could use an std::array, which avoids all these problems. If you only know the number at runtime, I would second Mark’s suggestion to go with std::unique_ptr<float[]>. You would create it with

```<code>size_t size = /* Number of floats */;
auto floats = unique_ptr<float[]>{new float[size]};
</code>```

You don’t need to do anything special to delete this; when it goes out of scope it will free the memory. In most respects you can use it like a vector, but it won’t automatically resize.

Body:
The reason push_back is slow is that it will need to copy all the data several times as the vector grows, and even when it doesn’t need to copy data it needs to check. Vectors grow quickly enough that this doesn’t happen often, but it still does happen. A rough rule of thumb is that every element will need to be copied on average once or twice; the earlier elements will need to be copied a lot more, but almost half the elements won’t need to be copied at all.

You can avoid the copying, but not the checks, by calling reserve on the vector when you create it, ensuring it has enough space. You can avoid both the copying and the checks by creating it with the right size from the beginning, by giving the number of elements to the vector constructor, and then inserting using indexing as Tobias suggested; unfortunately, this also goes through the vector an extra time initializing everything.

If you know the number of floats at compile time and not just runtime, you could use an std::array, which avoids all these problems. If you only know the number at runtime, I would second Mark’s suggestion to go with std::unique_ptr<float[]>. You would create it with

size_t size = /* Number of floats */;
auto floats = unique_ptr<float[]>{new float[size]};

You don’t need to do anything special to delete this; when it goes out of scope it will free the memory. In most respects you can use it like a vector, but it won’t automatically resize.


问:
How do I transfer base64 data into a readable image stream without saving locally
I'm working with the Microsoft Bot Framework (hosting on Azure) using Node.js, and saving files locally isn't an option. I have image data in base64 format, and I need to transfer that data into a readable stream of an image file that I can pump into Azure using their Blob Storage API (which takes a stream).

```<code>            var base64ImageData; //my base64 image

            //Create myStream here

            //Then send to Azure
            blobService.createBlockBlobFromStream('mycontainer',
            nameForBlob, myStream, fileSize,
            function (error, result, response){
                if(!error)
                    console.log(response);
                else
                    console.log(error)
            });
</code>```

Any help would be appreciated. I can't figure out how to decode the base64 and make a stream out of it without saving a jpg onto my disk.

答:
Please try something like this:

```<code>var azureStorage = require('azure-storage');
var streamifier = require('streamifier');

var base64String = 'iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAADsMAAA7DAcdvqGQAAAEiSURBVDhPxZIhT0NBEITnoBKBrEQgEUhISEiqKiFUYJDI/gBEc8VVY5AYHKKGBIEAVBFN+A8EUVFZUdGk/XbvGtqmpS8ImGTu5vbd7N3tPv0Pog5gzeSGB4oiqgSbCnphNbRQsKEQorbY/YCqaqwrXatl4WIJosrsfELtw3vucOFxsP4J6eRnlJnfOf3S4xk/J0hmO3kPfmE+5er+9ilSAqtoU203TGEFC7pDHcFBNvf82wxSgqAzxhPmDsbdHLtl9FZhbmDuul5AKmLUNuoDtQMH8BGeQ0OXBIckGOX1HL67ELlq6m8pBRyjbF56umEzz9KbPnXM9qBKjhhuMFsdVmKxC/ZzvCbpVW9kvRLzCeydY/9J+sx11laPXyB63/8C0gQlpj3Fc3O2WAAAAABJRU5ErkJggg==';
var blobService = azureStorage.createBlobService('account-name',
    'account-key');
var buffer = Buffer.from(base64String, 'base64');
var stream = streamifier.createReadStream(buffer);
blobService.createBlockBlobFromStream('container-name', 'checked.png', stream, buffer.byteLength, function(error, response) {
        if (error) {
            console.log('Error!');
            console.log(error);
        } else {
            console.log('Blob uploaded successfully!');
            console.log(response);
        }
    });
</code>```

I had to install streamifier node package to convert buffer to stream.

Body:
I'm working with the Microsoft Bot Framework (hosting on Azure) using Node.js, and saving files locally isn't an option. I have image data in base64 format, and I need to transfer that data into a readable stream of an image file that I can pump into Azure using their Blob Storage API (which takes a stream).

            var base64ImageData; //my base64 image

            //Create myStream here

            //Then send to Azure
            blobService.createBlockBlobFromStream('mycontainer',
            nameForBlob, myStream, fileSize,
            function (error, result, response){
                if(!error)
                    console.log(response);
                else
                    console.log(error)
            });

Any help would be appreciated. I can't figure out how to decode the base64 and make a stream out of it without saving a jpg onto my disk.

Body:
Please try something like this:

var azureStorage = require('azure-storage');
var streamifier = require('streamifier');

var base64String = 'iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAADsMAAA7DAcdvqGQAAAEiSURBVDhPxZIhT0NBEITnoBKBrEQgEUhISEiqKiFUYJDI/gBEc8VVY5AYHKKGBIEAVBFN+A8EUVFZUdGk/XbvGtqmpS8ImGTu5vbd7N3tPv0Pog5gzeSGB4oiqgSbCnphNbRQsKEQorbY/YCqaqwrXatl4WIJosrsfELtw3vucOFxsP4J6eRnlJnfOf3S4xk/J0hmO3kPfmE+5er+9ilSAqtoU203TGEFC7pDHcFBNvf82wxSgqAzxhPmDsbdHLtl9FZhbmDuul5AKmLUNuoDtQMH8BGeQ0OXBIckGOX1HL67ELlq6m8pBRyjbF56umEzz9KbPnXM9qBKjhhuMFsdVmKxC/ZzvCbpVW9kvRLzCeydY/9J+sx11laPXyB63/8C0gQlpj3Fc3O2WAAAAABJRU5ErkJggg==';
var blobService = azureStorage.createBlobService('account-name',
    'account-key');
var buffer = Buffer.from(base64String, 'base64');
var stream = streamifier.createReadStream(buffer);
blobService.createBlockBlobFromStream('container-name', 'checked.png', stream, buffer.byteLength, function(error, response) {
        if (error) {
            console.log('Error!');
            console.log(error);
        } else {
            console.log('Blob uploaded successfully!');
            console.log(response);
        }
    });

I had to install streamifier node package to convert buffer to stream.


问:
Regex to identify 3+ consecutive of same alpha/numeric
I have been trying to write/find a regex that will identify where there are 3+ consecutive instances of an alpha/numeric.

Example:

```<code>CHAIRMAN AAAAAAAND CHIEF EXECUTIVE OFFICER
</code>```

this would be a match b/c of the '**AAAAAAA**'

Thanks!

答:
You are on the right track, here is an example in Python:

```<code>import re

text = "CHAIRMAN AAAAAAAND CHIEF EXECUTIVE OFFICER"

regex = re.compile("([A-Za-z0-9])\\1\\1")

if re.search(regex, text):
    print ("yuppers")
</code>```

The regex itself is looking for any letter or number, followed by whatever letter or number it matched twice.  You can do stuff like:

```<code>[A-Z\d]\\1{2}
</code>```

and make the call of the regex case insensitive instead but with little regexes like this I think just spelling it out is easier to read for others down the road.

Body:
I have been trying to write/find a regex that will identify where there are 3+ consecutive instances of an alpha/numeric.

Example:

CHAIRMAN AAAAAAAND CHIEF EXECUTIVE OFFICER

this would be a match b/c of the '**AAAAAAA**'

Thanks!

Body:
You are on the right track, here is an example in Python:

import re

text = "CHAIRMAN AAAAAAAND CHIEF EXECUTIVE OFFICER"

regex = re.compile("([A-Za-z0-9])\\1\\1")

if re.search(regex, text):
    print ("yuppers")

The regex itself is looking for any letter or number, followed by whatever letter or number it matched twice.  You can do stuff like:

[A-Z\d]\\1{2}

and make the call of the regex case insensitive instead but with little regexes like this I think just spelling it out is easier to read for others down the road.


问:
Exception in thread "main" java.lang.IllegalStateException: The driver executable does not exist: /Users/Golcha/Desktop/Automation/geckodriver.exe
Getting the following error

Exception in thread "main" java.lang.IllegalStateException: The driver
  executable does not exist:
  /Users/Golcha/Desktop/Automation/geckodriver.exe

Code:

```<code>import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;

public class selenium{

    private static WebDriver driver;

    public static void main(String[]args){

        System.setProperty("webdriver.gecko.driver","Users/Golcha/Desktop/Automation/geckodriver.exe");

        setDriver(new FirefoxDriver());
    }

    public static WebDriver getDriver() {
        return driver;
    }

    public static void setDriver(WebDriver driver) {
        selenium.driver = driver;
    }

}
</code>```

答:
I thing you have not mentioned the complete(full) path for the Geckodriver in your System.setProperty() method. you have missed the drive letter "C"

"C:/Users/Golcha/Desktop/Automation/geckodriver.exe"

Let me know if this solved your problem.

Body:
Getting the following error

Exception in thread "main" java.lang.IllegalStateException: The driver
  executable does not exist:
  /Users/Golcha/Desktop/Automation/geckodriver.exe

Code:

import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;

public class selenium{

    private static WebDriver driver;

    public static void main(String[]args){

        System.setProperty("webdriver.gecko.driver","Users/Golcha/Desktop/Automation/geckodriver.exe");

        setDriver(new FirefoxDriver());
    }

    public static WebDriver getDriver() {
        return driver;
    }

    public static void setDriver(WebDriver driver) {
        selenium.driver = driver;
    }

}


问:
How can I use and display the same image shown as Launch Image for an iOS app in React Native?
I would like to use exactly the same image that appears at the launch of the app, to display it in my first scene and put over it an activity indicator.

I've seen that in ./ios/<app name>/Images.xcassets/LaunchImage.launchimage there are all the images used for the launch, and there's a JSON file containing informations about which image file to use, but how can I know which is my case (orientation, device)?

Any suggestions? Thank you very much, I'm using React Native.

答:
let the image be parent in the render():

render() {
    return (
      <Image source={require('./yourImagepath/image.png')} style=
        {styles.backgroundImage}>
        <View>
          ....
        </View>
      </Image>
    );
      const styles = StyleSheet.create({
        backgroundImage: {
          flex: 1,
          width: '100%',
          height: '100%',
       },
    }
}


问:
Special Characters Shown as Html Code and Asp Post breaks
Hello guys sometimes from user i get string like: N106 ORG ,,test''(09090909)

in code behind i assign this value to textbox with javascript

like:

```<code>$("#Address1").val('@(Model.AddressLineOne)');
</code>```

(@Model.AddressLineOne is the users input address as i mentioned above)

if user input start with ,, and has no ending  it shows like

N106 ORG ,,test'&#39(09090909) so after,, character "" shown as &#39&#39.

Asp gives error on Save

System.Web.HttpRequestValidationException: A potentially dangerous Request.Form value was detected from the client (Address="...  N106 ORG ,,test&#39&#39(09090909).

can you suggest what to do with this characters? p.s alsow i dont want [Allow Html] tag in asp ! i dont need  '&#39 in field and database!

答: You should encode such inputs before processing. refer this</p>

Body:
Hello guys sometimes from user i get string like: N106 ORG ,,test''(09090909)

in code behind i assign this value to textbox with javascript

like:

$("#Address1").val('@(Model.AddressLineOne)');

(@Model.AddressLineOne is the users input address as i mentioned above)

if user input start with ,, and has no ending  it shows like

N106 ORG ,,test'&#39(09090909) so after,, character "" shown as &#39&#39.

Asp gives error on Save

System.Web.HttpRequestValidationException: A potentially dangerous Request.Form value was detected from the client (Address="...  N106 ORG ,,test&#39&#39(09090909).

can you suggest what to do with this characters? p.s alsow i dont want [Allow Html] tag in asp ! i dont need  '&#39 in field and database!


答:
```<code>def Skew(Genome):
    skew = {}

    for base in range(1, len(Genome)+1): # since we start at 1 and not 0 as we should we are adding one to the length

        if Genome[base - 1] == "G":  # subtracting one since we start at one so base at the 0 position  has to be included
            skew[base] = skew[base - 1] + 1
        elif Genome[base - 1] == "C":
            skew[base] = skew[base - 1] - 1
        else:
            skew[base] = skew[base - 1]

    return skew
</code>```

Title: Python Skew Genome

Body:
I am trying to write skew genome function but keep  getting Error:

Failed test #2.
Test Dataset: AGCGTGCCGAAATATGCCGCCAGACCTGCTGCGGTGGCCTCGCCGACTTCACGGATGCCAAGTGCATAGAGGAAGCGAGCAAAGGTGGTTTCTTTCGCTTTATCCAGCGCGTTAACCACGTTCTGTGCCGACTTT
Your output: ['0', '0']
Correct output: ['0', '0', '1', '0', '1', '1', '2', '1', '0', '1', '1', '1', '1', '1', '1', '1', '2', '1', '0', '1', '0', '-1', '-1', '0', '0', '-1', '-2', '-2', '-1', '-2', '-2', '-1', '-2', '-1', '0', '0', '1', '2', '1', '0', '0', '-1', '0', '-1', '-2', '-1', '-1', '-2', '-2', '-2', '-3', '-3', '-4', '-3', '-2', '-2', '-2', '-1', '-2', '-3', '-3', '-3', '-2', '-2', '-1', '-2', '-2', '-2', '-2', '-1', '-1', '0', '1', '1', '1', '2', '1', '2', '2', '3', '2', '2', '2', '2', '3', '4', '4', '5', '6', '6', '6', '6', '5', '5', '5', '5', '4', '5', '4', '4', '4', '4', '4', '4', '3', '2', '2', '3', '2', '3', '2', '3', '3', '3', '3', '3', '2', '1', '1', '0', '1', '1', '1', '0', '0', '1', '1', '2', '1', '0', '1', '1', '0', '0', '0', '0']

My code:

Genome = "CATGGGCATCGGCCATACGCC"
def SymbolArray(Genome, symbol):
    array = {}
    n = len(Genome)
    ExtendedGenome = Genome + Genome[0:n//2]
    for i in range(n):
        array[i] = PatternCount(symbol, ExtendedGenome[i:i+(n//2)])
    return array
def Skew(Genome):
    skew = {}
    skew[0]=0
    n = len(Genome)
    for i in range(1, n+1):
        skew[i] = skew[i-1]
        if Genome[i-1] == "G":
            skew[i] = skew[i-1]+1
        elif Genome[i-1] == "C":
            skew[i] = skew[i-1]-1
        else:
            skew[i] = skew[i-1]
        return skew
    for i in skew.items():
        Skew(Genome)


问:
Can not handle properly a simple exception
I wrote a PHP class to manage some statistic functions but there are some functions that need a minimum of elements i.e. >0.
So I added a try catch and I still get the same error.

```<code>/**
 * Calculates the minimum for a given set of values.
 *
 * @param array $values The input values
 * @return float|int The minimum of values as an integer or float
 */
public static function min($values)
{
    try {
        min($values);
    } catch (Exception $e) {
        return 0;
    }
}
</code>```

And I get:

```<code>ErrorException in Statistics.php line 41: min(): Array must contain at least one element
</code>```

Thanks in advance.

答:
```<code>public static function min($values)
{
    if (count($values) < 1) {
        return 0;
    }

    return min($values);
}
</code>```

If you are looking to return 0 when the array is empty, then a simple if statement will suffice.  Personally I'd handle this problem higher up in the stack instead of creating my own min function to handle it differently to the built-in function.

Body:
I wrote a PHP class to manage some statistic functions but there are some functions that need a minimum of elements i.e. >0.
So I added a try catch and I still get the same error.

/**
 * Calculates the minimum for a given set of values.
 *
 * @param array $values The input values
 * @return float|int The minimum of values as an integer or float
 */
public static function min($values)
{
    try {
        min($values);
    } catch (Exception $e) {
        return 0;
    }
}

And I get:

ErrorException in Statistics.php line 41: min(): Array must contain at least one element

Thanks in advance.

Body:
public static function min($values)
{
    if (count($values) < 1) {
        return 0;
    }

    return min($values);
}

If you are looking to return 0 when the array is empty, then a simple if statement will suffice.  Personally I'd handle this problem higher up in the stack instead of creating my own min function to handle it differently to the built-in function.


问:
User access control for particular page?
I need to create a new blank page for a client's Drupal-6 based website. and it must have access only for users under custom created role-admin . We will put the page live when content is done. How can I assign page access only for a particular role?

I don't give User-1 login info to client. So, making unpublished is not a solution for me :|

Is there any module for my need? or any other solution?

Thanks a lot!!

答: Make the role only allowed to edit own pages in permissions. Go into authoring information on the page and set that user as the author.</p>

ContentLicense: CC BY-SA 2.5


问:
PHP: echo number of duplicates in a table by most common
I am trying to echo the most common duplicates in a table. I have been able to echo the name of the duplicates but what I'm looking for is a separate column in the table that shows how many times the duplicate occurs. Is there a way of echoing the COUNT(*) value? Also a way of organizing the values by size would be helpful.

My php:

```<code>$interests = "SELECT name, COUNT(*) FROM pageinterests WHERE pageid = '$id' GROUP BY name HAVING COUNT(*) > 1";
$interestresults = mysqli_query($conn, $interests);
</code>```

My html:

```<code>      <div class="panel panel-default panel-table">
<div class="panel-heading">
<div class="row">
<h2 class="cba-title">Interests</h2>

                    </div>
                    </div>
                    <div>
                            <?php
                                if(mysqli_num_rows($interestresults) > 0){
                                    $rim = mysqli_num_rows($interestresults);
                                    echo "
                                     <table class = 'table table-striped table-bordered table-list'>
                                     <thead>
                                      <tr>
                                       <th>Name</th>

                                      </tr>
                                       </thead>
                                      <tbody>'";

                                    for($x = 1; $x <= $rim; $x++){
                                        $rat = mysqli_fetch_assoc($interestresults);
                                        echo "<tr>

                                            <td>".$rat['name']."</td>
                                            </tr>";

                                    }

                                    echo '</tbody>
                                        </table>
                                      </center>';
                                }else{
                                    echo " There doesn't seem to be any common interests yet";
                                }
                            ?>
                        </div>
                        </div>
</code>```

答:
Use an alias  and order by for correct count sequence</p>

```<code>    $interests = "SELECT name, COUNT(*) AS my_count
          FROM pageinterests
          WHERE pageid = '$id'
          GROUP BY name HAVING COUNT(*) > 1
          ORDER BY my_count";

    .......

   for($x = 1; $x <= $rim; $x++){
       $rat = mysqli_fetch_assoc($interestresults);
       echo "<tr>

        <td>".$rat['name']."</td>
        <td>".$rat['my_count']."</td>
          </tr>";

    }
</code>```

Body:
I am trying to echo the most common duplicates in a table. I have been able to echo the name of the duplicates but what I'm looking for is a separate column in the table that shows how many times the duplicate occurs. Is there a way of echoing the COUNT(*) value? Also a way of organizing the values by size would be helpful.

My php:

$interests = "SELECT name, COUNT(*) FROM pageinterests WHERE pageid = '$id' GROUP BY name HAVING COUNT(*) > 1";
$interestresults = mysqli_query($conn, $interests);

My html:

Interests

                            <?php
                                if(mysqli_num_rows($interestresults) > 0){
                                    $rim = mysqli_num_rows($interestresults);
                                    echo "

                                       Name

'";

                                    for($x = 1; $x <= $rim; $x++){
                                        $rat = mysqli_fetch_assoc($interestresults);
                                        echo "

                                            ".$rat['name']."

";

                                    }

                                    echo '

                                      ';
                                }else{
                                    echo " There doesn't seem to be any common interests yet";
                                }
                            ?>

Body:
Use an alias  and order by for correct count sequence

    $interests = "SELECT name, COUNT(*) AS my_count
          FROM pageinterests
          WHERE pageid = '$id'
          GROUP BY name HAVING COUNT(*) > 1
          ORDER BY my_count";

    .......

   for($x = 1; $x <= $rim; $x++){
       $rat = mysqli_fetch_assoc($interestresults);
       echo "<tr>

        <td>".$rat['name']."</td>
        <td>".$rat['my_count']."</td>
          </tr>";

    }


问:
iOS: Animating a circle slice into a wider one
Core-Animation treats angles as described in this image:
(image from http://btk.tillnagel.com/tutorials/rotation-translation-matrix.html)

EDIT: Adding an animated gif to explain better what I'm needing:

I need to animate a slice to grow wider, starting at 300:315 degrees, and ending 300:060.

To create each slice I'm using this function:

```<code>extension CGFloat {
    func toRadians() -> CGFloat {
        return self * CGFloat(Double.pi) / 180.0
    }
}
func createSlice(angle1:CGFloat, angle2:CGFloat) -> UIBezierPath! {
    let path: UIBezierPath = UIBezierPath()
    let width: CGFloat = self.frame.size.width/2
    let height: CGFloat = self.frame.size.height/2
    let centerToOrigin: CGFloat = sqrt((height)*(height)+(width)*(width));
    let ctr: CGPoint = CGPoint(x: width, y: height)
    path.move(to: ctr)
    path.addArc( withCenter: ctr,
                 radius: centerToOrigin,
                 startAngle: CGFloat(angle1).toRadians(),
                 endAngle: CGFloat(angle2).toRadians(),
                 clockwise: true
    )
    path.close()
    return path
}
</code>```

I can now create the two slices and a sublayer with the smaller one, but I can't find how to proceed from this point:

```<code>func doStuff() {
    path1 = self.createSlice(angle1: 300,angle2: 315)
    path2 = self.createSlice(angle1: 300,angle2: 60)

    let shapeLayer = CAShapeLayer()
    shapeLayer.path = path1.cgPath
    shapeLayer.fillColor = UIColor.cyan.cgColor
    self.layer.addSublayer(shapeLayer)
</code>```

I would highly appreciate any help here!

答:
So at last I have found a solution. It took me time to understand that there is indeed no way to animate the fill of the shape, but we can trick CA engine by creating a filled circle by making the stroke (i.e. the border of the arc) extremely wide, so that it fills the whole circle!

```<code>extension CGFloat {
    func toRadians() -> CGFloat {
        return self * CGFloat(Double.pi) / 180.0
    }
}

import UIKit

class SliceView: UIView {

    let circleLayer = CAShapeLayer()
    var fromAngle:CGFloat = 30
    var toAngle:CGFloat = 150
    var color:UIColor = UIColor.magenta

    override init(frame: CGRect) {
        super.init(frame: frame)
        setup()
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    convenience init(frame:CGRect, fromAngle:CGFloat, toAngle:CGFloat, color:UIColor) {
        self.init(frame:frame)
        self.fromAngle = fromAngle
        self.toAngle = toAngle
        self.color = color
    }

    func setup() {
        circleLayer.strokeColor = color.cgColor
        circleLayer.fillColor = UIColor.clear.cgColor
        layer.addSublayer(circleLayer)
        layer.backgroundColor = UIColor.brown.cgColor
    }

    override func layoutSubviews() {
        super.layoutSubviews()

        let startAngle:CGFloat = (fromAngle-90).toRadians()
        let endAngle:CGFloat = (toAngle-90).toRadians()
        let center = CGPoint(x: bounds.midX, y: bounds.midY)
        let radius = min(bounds.width, bounds.height) / 4
        let path = UIBezierPath(arcCenter: CGPoint(x: 0,y :0), radius: radius, startAngle: startAngle, endAngle: endAngle, clockwise: true)

        circleLayer.position = center
        circleLayer.lineWidth = radius*2
        circleLayer.path = path.cgPath
    }

    public func animate() {
        let pathAnimation = CABasicAnimation(keyPath: "strokeEnd")
        pathAnimation.duration = 3.0;
        pathAnimation.fromValue = 0.0;
        pathAnimation.toValue = 1.0;
        circleLayer.add(pathAnimation, forKey: "strokeEndAnimation")
    }
}
</code>```

So, now we can add it into our view controller and run the animation. In my case - I'm bridging it into Objecive-C but you can easily adapt it to swift.

I simply can't believe that in 2017 it was still not possible to find a ready solution for this simple task. It took me days to have that done. I really hope it will help others!

Here is how I'm using my class:

```<code>@implementation ViewController
{
    SliceView *sv_;
}

- (void)viewDidLoad {
    [super viewDidLoad];

    self.view.backgroundColor = UIColor.grayColor;
    CGFloat width = 240.0;
    CGFloat height = 160.0;

    CGRect r = CGRectMake(
                          self.view.frame.size.width/2 - width/2,
                          self.view.frame.size.height/2 - height/2,
                          width, height);
    sv_ = [[SliceView alloc] initWithFrame:r fromAngle:150 toAngle:30 color:[UIColor yellowColor] ];
    [self.view addSubview:sv_];
}

- (IBAction)pressedGo:(id)sender {
    [sv_ animate];
}
</code>```

Body:
Core-Animation treats angles as described in this image:
(image from http://btk.tillnagel.com/tutorials/rotation-translation-matrix.html)

EDIT: Adding an animated gif to explain better what I'm needing:

I need to animate a slice to grow wider, starting at 300:315 degrees, and ending 300:060.

To create each slice I'm using this function:

extension CGFloat {
    func toRadians() -> CGFloat {
        return self * CGFloat(Double.pi) / 180.0
    }
}
func createSlice(angle1:CGFloat, angle2:CGFloat) -> UIBezierPath! {
    let path: UIBezierPath = UIBezierPath()
    let width: CGFloat = self.frame.size.width/2
    let height: CGFloat = self.frame.size.height/2
    let centerToOrigin: CGFloat = sqrt((height)*(height)+(width)*(width));
    let ctr: CGPoint = CGPoint(x: width, y: height)
    path.move(to: ctr)
    path.addArc( withCenter: ctr,
                 radius: centerToOrigin,
                 startAngle: CGFloat(angle1).toRadians(),
                 endAngle: CGFloat(angle2).toRadians(),
                 clockwise: true
    )
    path.close()
    return path
}

I can now create the two slices and a sublayer with the smaller one, but I can't find how to proceed from this point:

func doStuff() {
    path1 = self.createSlice(angle1: 300,angle2: 315)
    path2 = self.createSlice(angle1: 300,angle2: 60)

    let shapeLayer = CAShapeLayer()
    shapeLayer.path = path1.cgPath
    shapeLayer.fillColor = UIColor.cyan.cgColor
    self.layer.addSublayer(shapeLayer)

I would highly appreciate any help here!

Body:
So at last I have found a solution. It took me time to understand that there is indeed no way to animate the fill of the shape, but we can trick CA engine by creating a filled circle by making the stroke (i.e. the border of the arc) extremely wide, so that it fills the whole circle!

extension CGFloat {
    func toRadians() -> CGFloat {
        return self * CGFloat(Double.pi) / 180.0
    }
}

import UIKit

class SliceView: UIView {

    let circleLayer = CAShapeLayer()
    var fromAngle:CGFloat = 30
    var toAngle:CGFloat = 150
    var color:UIColor = UIColor.magenta

    override init(frame: CGRect) {
        super.init(frame: frame)
        setup()
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    convenience init(frame:CGRect, fromAngle:CGFloat, toAngle:CGFloat, color:UIColor) {
        self.init(frame:frame)
        self.fromAngle = fromAngle
        self.toAngle = toAngle
        self.color = color
    }

    func setup() {
        circleLayer.strokeColor = color.cgColor
        circleLayer.fillColor = UIColor.clear.cgColor
        layer.addSublayer(circleLayer)
        layer.backgroundColor = UIColor.brown.cgColor
    }

    override func layoutSubviews() {
        super.layoutSubviews()

        let startAngle:CGFloat = (fromAngle-90).toRadians()
        let endAngle:CGFloat = (toAngle-90).toRadians()
        let center = CGPoint(x: bounds.midX, y: bounds.midY)
        let radius = min(bounds.width, bounds.height) / 4
        let path = UIBezierPath(arcCenter: CGPoint(x: 0,y :0), radius: radius, startAngle: startAngle, endAngle: endAngle, clockwise: true)

        circleLayer.position = center
        circleLayer.lineWidth = radius*2
        circleLayer.path = path.cgPath
    }

    public func animate() {
        let pathAnimation = CABasicAnimation(keyPath: "strokeEnd")
        pathAnimation.duration = 3.0;
        pathAnimation.fromValue = 0.0;
        pathAnimation.toValue = 1.0;
        circleLayer.add(pathAnimation, forKey: "strokeEndAnimation")
    }
}

So, now we can add it into our view controller and run the animation. In my case - I'm bridging it into Objecive-C but you can easily adapt it to swift.

I simply can't believe that in 2017 it was still not possible to find a ready solution for this simple task. It took me days to have that done. I really hope it will help others!

Here is how I'm using my class:

@implementation ViewController
{
    SliceView *sv_;
}

- (void)viewDidLoad {
    [super viewDidLoad];

    self.view.backgroundColor = UIColor.grayColor;
    CGFloat width = 240.0;
    CGFloat height = 160.0;

    CGRect r = CGRectMake(
                          self.view.frame.size.width/2 - width/2,
                          self.view.frame.size.height/2 - height/2,
                          width, height);
    sv_ = [[SliceView alloc] initWithFrame:r fromAngle:150 toAngle:30 color:[UIColor yellowColor] ];
    [self.view addSubview:sv_];
}

- (IBAction)pressedGo:(id)sender {
    [sv_ animate];
}


问:
How to fix height: auto with flexbox in Firefox?
I have a problem with flexbox and height: auto in Firefox:

.portfolio {
  width: 100%;
  position: relative;
  overflow: visible;
  display: flex;
  flex-direction: row;
  flex-wrap: wrap;
  justify-content: space-between;
  background-color: red;
}

.portfolio a {
  display: block;
  background-color: black;
  width: 30%;
  height: auto;
  padding-top: 30%;
  /* 1:1 Aspect Ratio */
  position: relative;
  /* If you want text inside of it */
  margin-bottom: 5%;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="portfolio">

    <div class="portfolio_item">
    </div>

    <div class="portfolio_item">
    </div>

    <div class="portfolio_item">
    </div>

    <div class="portfolio_item">
    </div>

    <div class="portfolio_item">
    </div>

    <div class="portfolio_item">
    </div>

</div></code>```

When div .portfolio have height: auto, in Firefox this div is not visible. Chrome, Safari and others works fine... I really don't have idea how to make this working... anyone?

答:
.portfolio has no height by default. Setting the height to auto will do nothing in this case.

Setting height: 30%; to .portfolio's children will do nothing, because the logic of that goes: take up 30% of the parent's height, which is 0. Again, if you set .portfolio a's height to 30vh (30% of the viewport height) That would work, or if you could give it a pixel value

In the example below, I've set the height to 100px but obviously you can change it to whatever you want.

.portfolio {
  width: 100%;
  height: 100px;
  position: relative;
  overflow: visible;
  display: flex;
  flex-direction: row;
  flex-wrap: wrap;
  justify-content: space-between;
  background-color: red;
}

.portfolio a {
  display: block;
  background-color: black;
  width: 30%;
  height: auto;
  padding-top: 30%;
  /* 1:1 Aspect Ratio */
  position: relative;
  /* If you want text inside of it */
  margin-bottom: 5%;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="portfolio">

    <div class="portfolio_item">
    </div>

    <div class="portfolio_item">
    </div>

    <div class="portfolio_item">
    </div>

    <div class="portfolio_item">
    </div>

    <div class="portfolio_item">
    </div>

    <div class="portfolio_item">
    </div>

</div></code>```

Body:
I have a problem with flexbox and height: auto in Firefox:

.portfolio {
  width: 100%;
  position: relative;
  overflow: visible;
  display: flex;
  flex-direction: row;
  flex-wrap: wrap;
  justify-content: space-between;
  background-color: red;
}

.portfolio a {
  display: block;
  background-color: black;
  width: 30%;
  height: auto;
  padding-top: 30%;
  /* 1:1 Aspect Ratio */
  position: relative;
  /* If you want text inside of it */
  margin-bottom: 5%;
}

When div .portfolio have height: auto, in Firefox this div is not visible. Chrome, Safari and others works fine... I really don't have idea how to make this working... anyone?

Body:
.portfolio has no height by default. Setting the height to auto will do nothing in this case.

Setting height: 30%; to .portfolio's children will do nothing, because the logic of that goes: take up 30% of the parent's height, which is 0. Again, if you set .portfolio a's height to 30vh (30% of the viewport height) That would work, or if you could give it a pixel value

In the example below, I've set the height to 100px but obviously you can change it to whatever you want.

.portfolio {
  width: 100%;
  height: 100px;
  position: relative;
  overflow: visible;
  display: flex;
  flex-direction: row;
  flex-wrap: wrap;
  justify-content: space-between;
  background-color: red;
}

.portfolio a {
  display: block;
  background-color: black;
  width: 30%;
  height: auto;
  padding-top: 30%;
  /* 1:1 Aspect Ratio */
  position: relative;
  /* If you want text inside of it */
  margin-bottom: 5%;
}

<div class="portfolio">
  <a href="#">
    <div class="portfolio_item">
    </div>
  </a>
  <a href="#">
    <div class="portfolio_item">
    </div>
  </a>
  <a href="#">
    <div class="portfolio_item">
    </div>
  </a>
  <a href="#">
    <div class="portfolio_item">
    </div>
  </a>
  <a href="#">
    <div class="portfolio_item">
    </div>
  </a>
  <a href="#">
    <div class="portfolio_item">
    </div>
  </a>
</div>


问:
Tensorflow: Merge two 2-D tensors according to even and odd indices
I want to perform a check for even and odd elements of the batch and swap them if needed. I managed to result with two tensors I want to interweave:

```<code>def tf_oplu(x, name=None):

    even = x[:,::2] #slicing into odd and even parts on the batch
    odd = x[:,1::2]

    even_flatten = tf.reshape(even, [-1]) # flatten tensors
    #in row-major order to apply function across them

    odd_flatten = tf.reshape(odd, [-1])

    compare = tf.to_float(even_flatten<odd_flatten)
    compare_not = tf.to_float(even_flatten>=odd_flatten)

    #def oplu(x,y): # trivial function
    #    if x<y : # (x<y)==1
    #       return y, x
    #    else:
    #       return x, y # (x<y)==0

    even_flatten_new = odd_flatten * compare + even_flatten * compare_not
    odd_flatten_new = odd_flatten * compare_not + even_flatten * compare

    # convolute back

    even_new = tf.reshape(even_flatten_new,[100,128])
    odd_new = tf.reshape(odd_flatten_new,[100,128])
</code>```

Now I want to get back $[100,256]$ tensor with even and odd places filled. In numpy I would of course do:

```<code>y = np.empty((even_new.size + odd_newsize,), dtype=even_new.dtype)
y[:,0::2] = even_new
y[:,1::2] = odd_new

return y
</code>```

But such thing is not possible for tensoflow, as tensor is not modifiable. I suppose it is possible with either sparse tensor or tf.gather_nd, but both require generating array of indices, which is again non-trivial task for me.
One more note: I don not want to use any python functions via tf.py_func, as I checked that they run on CPU only. Maybe lambda and tf.map_fn may help somehow? Thanks!

答:
To interleave two matrices vertically, you do not big guns such as gather or map_fn. You can simply interleave them as follows:

```<code>tf.reshape(
  tf.stack([even_new, odd_new], axis=1),
  [-1, tf.shape(even_new)[1]])
</code>```

EDIT

To interleave them horizontally:

```<code>tf.reshape(
  tf.concat([even_new[...,tf.newaxis], odd_new[...,tf.newaxis]], axis=-1),
  [tf.shape(even_new)[0],-1])
</code>```

The idea is to use stack to interleave them in memory. The dimension where the stack occurs gives the granularity of the interleaving. If we stack at axis=0, then the interleaving occurs at each element, mixing columns. If we stack at axis=1, entire input rows remain contiguous, interleaving occurs between rows.

Body:
I want to perform a check for even and odd elements of the batch and swap them if needed. I managed to result with two tensors I want to interweave:

def tf_oplu(x, name=None):

    even = x[:,::2] #slicing into odd and even parts on the batch
    odd = x[:,1::2]

    even_flatten = tf.reshape(even, [-1]) # flatten tensors
    #in row-major order to apply function across them

    odd_flatten = tf.reshape(odd, [-1])

    compare = tf.to_float(even_flatten<odd_flatten)
    compare_not = tf.to_float(even_flatten>=odd_flatten)

    #def oplu(x,y): # trivial function
    #    if x<y : # (x<y)==1
    #       return y, x
    #    else:
    #       return x, y # (x<y)==0

    even_flatten_new = odd_flatten * compare + even_flatten * compare_not
    odd_flatten_new = odd_flatten * compare_not + even_flatten * compare

    # convolute back

    even_new = tf.reshape(even_flatten_new,[100,128])
    odd_new = tf.reshape(odd_flatten_new,[100,128])

Now I want to get back $[100,256]$ tensor with even and odd places filled. In numpy I would of course do:

y = np.empty((even_new.size + odd_newsize,), dtype=even_new.dtype)
y[:,0::2] = even_new
y[:,1::2] = odd_new

return y

But such thing is not possible for tensoflow, as tensor is not modifiable. I suppose it is possible with either sparse tensor or tf.gather_nd, but both require generating array of indices, which is again non-trivial task for me.
One more note: I don not want to use any python functions via tf.py_func, as I checked that they run on CPU only. Maybe lambda and tf.map_fn may help somehow? Thanks!

Body:
To interleave two matrices vertically, you do not big guns such as gather or map_fn. You can simply interleave them as follows:

tf.reshape(
  tf.stack([even_new, odd_new], axis=1),
  [-1, tf.shape(even_new)[1]])

EDIT

To interleave them horizontally:

tf.reshape(
  tf.concat([even_new[...,tf.newaxis], odd_new[...,tf.newaxis]], axis=-1),
  [tf.shape(even_new)[0],-1])

The idea is to use stack to interleave them in memory. The dimension where the stack occurs gives the granularity of the interleaving. If we stack at axis=0, then the interleaving occurs at each element, mixing columns. If we stack at axis=1, entire input rows remain contiguous, interleaving occurs between rows.


问:
Writing JavaScript code using PHP echos (for leaflet map points)
Im trying to create map points in Leaflet, wich uses javaScript to write points, for example:

```<code>L.marker([39.0865039, -9.2636987], {icon: tree3}).addTo(map)
 .bindPopup('<a class="speciallink">Olive Tree</a>')
 .openPopup();
</code>```

In MySQL i have the coords stored, and then i tried to make the following code:

```<code>    <?php
     $res=mysql_query("SELECT * FROM arv_especie");
     $rowArv=mysql_fetch_array($res);
     $idPointVarzea=mysql_query("SELECT * FROM map_point_varzea");
     while ($row=mysql_fetch_array($idPointVarzea)) {
       echo "L.marker([" . $row["coordHori"] . ", " . $row["coordVerti"] . "], {icon: tree" . $row["ARV_id"] . "}).addTo(map)
       .bindPopup($('<a class='speciallink'>" . $rowArv["ARV_Especie"] . "</a>').click(function() {
       document.getElementById('DivShow" . $row["ARV_id"] . "').click();
       })[0])
       .openPopup();";
     }
?>
</code>```

this code is inserted in a

答:
I would suggest writing a javascript layer to request geojson from your php/crud server rather than attempting to embed the geojson in the php constructed response. You will have better separation of concerns and, if you are interested, there are several php frameworks and libraries capable of producing geojson or facilitating a crud system.

EX: Doctrine2-Spatial for Doctrine ORM support mysql geometries.

Disclosure: I work on D2-Spatial and Leaflet.Draw

Body:
Im trying to create map points in Leaflet, wich uses javaScript to write points, for example:

L.marker([39.0865039, -9.2636987], {icon: tree3}).addTo(map)
 .bindPopup('Olive Tree')
 .openPopup();

In MySQL i have the coords stored, and then i tried to make the following code:

    <?php
     $res=mysql_query("SELECT * FROM arv_especie");
     $rowArv=mysql_fetch_array($res);
     $idPointVarzea=mysql_query("SELECT * FROM map_point_varzea");
     while ($row=mysql_fetch_array($idPointVarzea)) {
       echo "L.marker([" . $row["coordHori"] . ", " . $row["coordVerti"] . "], {icon: tree" . $row["ARV_id"] . "}).addTo(map)
       .bindPopup($('" . $rowArv["ARV_Especie"] . "').click(function() {
       document.getElementById('DivShow" . $row["ARV_id"] . "').click();
       })[0])
       .openPopup();";
     }
?>

this code is inserted in a


问:
How do I clear the image cache after editing an image on my site?
I'm using an outside page to update an image in my system. When I'm redirected back to the page I've worked in, I still see the old picture. I don't see my changes until I press ctrl+f5. Is their any way to redirect with history delete or any other solution?</p>

答:
The decision to refresh or not is up to the browser. A standard technique for solving this is to add a timestamp to your images. For example:

```<code><img src='/images/foo.jpg?ts=1'/>
</code>```

When you update the image, send back:

```<code><img src='/images/foo.jpg?ts=2'/>
</code>```

The browser will see two different URL and request the image again. You can use a timestamp (last modified time of the file), a hash of the file contents, an incrementing integer, ... Anything to change the URL and force the browser to reload.

N.B. When serving static files, web servers will ignore the query string. So you don't need any code running to implement this. This technique also works well for any content that you want to force a refresh on including CSS, JS, ...

Body:
The decision to refresh or not is up to the browser. A standard technique for solving this is to add a timestamp to your images. For example:

<img src='/images/foo.jpg?ts=1'/>

When you update the image, send back:

<img src='/images/foo.jpg?ts=2'/>

The browser will see two different URL and request the image again. You can use a timestamp (last modified time of the file), a hash of the file contents, an incrementing integer, ... Anything to change the URL and force the browser to reload.

N.B. When serving static files, web servers will ignore the query string. So you don't need any code running to implement this. This technique also works well for any content that you want to force a refresh on including CSS, JS, ...


问:
how to initialize all the base class objects from derived class using base keyword
The following code initializes the base class from derived class using 'base' keyword by calling the base class constructor from the derived class.

```<code>    class A
    {

        public int a;
        public int b;
        public A(int x, int y)
        {
            a = x;
            b = y;
        }
    }
    class B : A
    {
        int c;
        public B(int s, int n,int z)
            : base(s, n)
        {
            c = z;
        }
        public int add()
        {
            return a + b+c;
        }

    }
    class Program
    {
        static void Main(string[] args)
        {
            B b = new B(2, 3,5);
            Console.WriteLine(b.add());//the output is 10 OK

        }
    }
</code>```

Question

what happens if a derived class inherits from more than one base class.then how to initialize all the base classes from the derived class using base keyword(how to call the base class constructors).**

```<code>class A
    {

        public int a;
        public int b;
        public A(int x, int y)
        {
            a = x;
            b = y;
        }
    }
    class B:A
    {

        public int d;
        public int e;
        public B(int x, int y)
        {
            d = x;
            e = y;
        }
    }
    class C:B
    {

    }
</code>```

then from class C how to initialize both the base classes using base keyword.

答:
As others have said, in .Net you can only inherit from one Class, however you can implement a large number of interfaces.  The difference and how to achieve an effect similar to inheriting from a number of classes is out of scope of this question.

In your example (using the previous code sample as a standard) you would have to do the following

```<code>class A
{

    public int a;
    public int b;
    public A(int x, int y)
    {
        a = x;
        b = y;
    }
}
class B:A
{

    public int d;
    public int e;
    public B(int x, int y): base (x, y)
    {
        d = x;
        e = y;
    }
}
class C:B
{
    public C(int m, int n) : base(m, n)

}
</code>```

This would in effect instantiate C, which then calls the constructor of B which then calls the constructor of A.

Body:
The following code initializes the base class from derived class using 'base' keyword by calling the base class constructor from the derived class.

    class A
    {

        public int a;
        public int b;
        public A(int x, int y)
        {
            a = x;
            b = y;
        }
    }
    class B : A
    {
        int c;
        public B(int s, int n,int z)
            : base(s, n)
        {
            c = z;
        }
        public int add()
        {
            return a + b+c;
        }

    }
    class Program
    {
        static void Main(string[] args)
        {
            B b = new B(2, 3,5);
            Console.WriteLine(b.add());//the output is 10 OK

        }
    }

Question

what happens if a derived class inherits from more than one base class.then how to initialize all the base classes from the derived class using base keyword(how to call the base class constructors).**

class A
    {

        public int a;
        public int b;
        public A(int x, int y)
        {
            a = x;
            b = y;
        }
    }
    class B:A
    {

        public int d;
        public int e;
        public B(int x, int y)
        {
            d = x;
            e = y;
        }
    }
    class C:B
    {

    }

then from class C how to initialize both the base classes using base keyword.

Body:
As others have said, in .Net you can only inherit from one Class, however you can implement a large number of interfaces.  The difference and how to achieve an effect similar to inheriting from a number of classes is out of scope of this question.

In your example (using the previous code sample as a standard) you would have to do the following

class A
{

    public int a;
    public int b;
    public A(int x, int y)
    {
        a = x;
        b = y;
    }
}
class B:A
{

    public int d;
    public int e;
    public B(int x, int y): base (x, y)
    {
        d = x;
        e = y;
    }
}
class C:B
{
    public C(int m, int n) : base(m, n)

}

This would in effect instantiate C, which then calls the constructor of B which then calls the constructor of A.


问:
How can I use properties in pom.xml in spring application context xml file?
I have a an spring context file which is similar to what is given below

```<code><?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">

    <context:property-placeholder
                location="classpath:application.properties, classpath:application-${env}.properties"/>

    <context:annotation-config/>
</beans>
</code>```

The snippet of pom.xml where profiles are configured is as below-

```<code>        <profile>
            <id>dev</id>
            <properties>
                <env>dev</env>
            </properties>
        </profile>
        <profile>
            <id>test</id>
            <properties>
                <env>test</env>
            </properties>
        </profile>
        <profile>
            <id>prod</id>
            <properties>
                <env>prod</env>
            </properties>
        </profile>
</code>```

I want to use the property 'env' which is decided based on selected maven profile, in my spring application-context file.

How can I do that?

Edit:- Its a Spring web app

```<code>        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-web</artifactId>
            <version>4.1.6.RELEASE</version>
        </dependency>
</code>```

答:
Not directly answering your question but, if you can use Spring Boot, I think what you are trying to do is easily solved by using Spring Profiles.

Essentially you avoid manually coding in the multiple profiles in Maven and in your XML and let Spring do it for you. Here is a basic example.

Body:
I have a an spring context file which is similar to what is given below

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">

    <context:property-placeholder
                location="classpath:application.properties, classpath:application-${env}.properties"/>

    <context:annotation-config/>
</beans>

The snippet of pom.xml where profiles are configured is as below-

        <profile>
            <id>dev</id>
            <properties>
                <env>dev</env>
            </properties>
        </profile>
        <profile>
            <id>test</id>
            <properties>
                <env>test</env>
            </properties>
        </profile>
        <profile>
            <id>prod</id>
            <properties>
                <env>prod</env>
            </properties>
        </profile>

I want to use the property 'env' which is decided based on selected maven profile, in my spring application-context file.

How can I do that?

Edit:- Its a Spring web app

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-web</artifactId>
            <version>4.1.6.RELEASE</version>
        </dependency>


问:
How to add a separator in a TinyMCE dropdown menu
I am working on a WordPress plugin and I can add TinyMCE buttons that present a dropdown menu when clicked. However, I would like to add a horizontal separator (i.e., a horizontal line) to that drop down menu to group options.

I have googled this for some time and the only information I have found is about adding a vertical separator (i.e., a vertical line) between buttons on the menu itself.

Is it possible to add a horizontal separator to a dropdown menu in TinyMCE, and if so, how can I do it? Or is my only option to group these other items by using a submenu?

```<code>            ed.addButton('d12-mb-button-2', {
            title:'Add a message block with a custom title',
            type:'menubutton',
            image: url + '/d12-mb-mce-button-2.png',
            menu: [
                    {
                    text: 'Part of a series',
                    value: 'Part',
                    icon: 'icon d12mb-part',
                    onclick: function() {
                        ed.windowManager.open( {
                            title: 'Please enter the data for this message box',
                            body: [{
                                type: 'textbox',
                                name: 'title',
                                label: 'This series of articles is about:'
                            },
                            {
                                type: 'textbox',
                                minHeight: 200,
                                minWidth: 400,
                                multiline: 'true',
                                name: 'description',
                                label: 'Description of this series:'
                            }
                            ],
                            onsubmit: function( epart ) {
                                ed.selection.setContent('[d12-part series="' + epart.data.title + '"]' + epart.data.description + '[/d12-part]');
                            }
                        });
                    }
                }, // End of "Part"
                {
                    text: 'Add a support message',
                    value: 'Support',
                    icon: 'icon d12mb-support',
                    onclick: function() {
                        ed.windowManager.open( {
                            title: 'Please enter the support information',
                            body: [{
                                type: 'textbox',
                                name: 'title',
                                label: 'Support title:'
                            },
                            {
                                type: 'textbox',
                                minHeight: 200,
                                minWidth: 400,
                                multiline: 'true',
                                name: 'description',
                                label: 'Support message:'
                            }
                            ],
                            onsubmit: function( esupport ) {
                                ed.selection.setContent('[d12-support title="' + esupport.data.title + '"]' + esupport.data.description + '[/d12-support]');
                            }
                        });
                    }
                }, // End of "Support"
</code>```

I need to add a horizontal separator right after the 'end of "Part"' item.

(FWIW, the entire file I am working on is here.)

答:
I'm not suer if I understand you correctly, but if you need a horizontal line like this in the Full Featured Example - (in the drop-down menu Format) - after subscript and before formats, there solution is in the API: Insert a | Pipe character between menu items.

Maybe in your case, you can just rewrite the code to match the pattern here and apply | .

Body:
I am working on a WordPress plugin and I can add TinyMCE buttons that present a dropdown menu when clicked. However, I would like to add a horizontal separator (i.e., a horizontal line) to that drop down menu to group options.

I have googled this for some time and the only information I have found is about adding a vertical separator (i.e., a vertical line) between buttons on the menu itself.

Is it possible to add a horizontal separator to a dropdown menu in TinyMCE, and if so, how can I do it? Or is my only option to group these other items by using a submenu?

            ed.addButton('d12-mb-button-2', {
            title:'Add a message block with a custom title',
            type:'menubutton',
            image: url + '/d12-mb-mce-button-2.png',
            menu: [
                    {
                    text: 'Part of a series',
                    value: 'Part',
                    icon: 'icon d12mb-part',
                    onclick: function() {
                        ed.windowManager.open( {
                            title: 'Please enter the data for this message box',
                            body: [{
                                type: 'textbox',
                                name: 'title',
                                label: 'This series of articles is about:'
                            },
                            {
                                type: 'textbox',
                                minHeight: 200,
                                minWidth: 400,
                                multiline: 'true',
                                name: 'description',
                                label: 'Description of this series:'
                            }
                            ],
                            onsubmit: function( epart ) {
                                ed.selection.setContent('[d12-part series="' + epart.data.title + '"]' + epart.data.description + '[/d12-part]');
                            }
                        });
                    }
                }, // End of "Part"
                {
                    text: 'Add a support message',
                    value: 'Support',
                    icon: 'icon d12mb-support',
                    onclick: function() {
                        ed.windowManager.open( {
                            title: 'Please enter the support information',
                            body: [{
                                type: 'textbox',
                                name: 'title',
                                label: 'Support title:'
                            },
                            {
                                type: 'textbox',
                                minHeight: 200,
                                minWidth: 400,
                                multiline: 'true',
                                name: 'description',
                                label: 'Support message:'
                            }
                            ],
                            onsubmit: function( esupport ) {
                                ed.selection.setContent('[d12-support title="' + esupport.data.title + '"]' + esupport.data.description + '[/d12-support]');
                            }
                        });
                    }
                }, // End of "Support"

I need to add a horizontal separator right after the 'end of "Part"' item.

(FWIW, the entire file I am working on is here.)


答:
```<code>SELECT name, COUNT(*) as mycount FROM ...
</code>```

Title: PHP: echo number of duplicates in a table by most common


问:
Plot a binary timeline in matplotlib
I'm trying to plot a binary timeline using matplotlib (I might be able to consider alternative libraries, though).

Now, by "binary timeline" I mean the "display of chronological events, where the event space is made of two opposite events".
An example of such an event space could be {no_one_in_the_team_is_sick, at_least_one_person_in_the_team_is_sick}.

The representation I'd like to replicate is this (I did it using d3):

I've tried exploring the use of stacked horizontal bars, but it's clearly not the right tool for the job.

Is there an easier and/or more correct way of achieving that result?

答:
You may use broken_barhto plot a binary timeline.

```<code>import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import matplotlib.dates

#create a time series s with dates as index and 0 and 1 for events
dates = pd.date_range("2017-04-01","2017-06-15", freq="D")
events = np.random.random_integers(0,1,size=len(dates))
s = pd.Series(events, index=dates)

fig, ax= plt.subplots(figsize=(6,2))

# plot green for event==1
s1 = s[s == 1]
inxval = matplotlib.dates.date2num(s1.index.to_pydatetime())
times= zip(inxval, np.ones(len(s1)))
plt.broken_barh(times, (-1,1), color="green")
# plot red for event==0
s2 = s[s == 0]
inxval = matplotlib.dates.date2num(s2.index.to_pydatetime())
times= zip(inxval, np.ones(len(s2)))
plt.broken_barh(times, (-1,1), color="red")

#format axes
ax.margins(0)
ax.set_yticks([])
ax.xaxis.set_major_locator(matplotlib.dates.MonthLocator())
ax.xaxis.set_minor_locator(matplotlib.dates.DayLocator())
monthFmt = matplotlib.dates.DateFormatter("%b")
ax.xaxis.set_major_formatter(monthFmt)
plt.tight_layout()
plt.show()
</code>```

ContentLicense: CC BY-SA 4.0

Title: Plot a binary timeline in matplotlib

Body:
You may use broken_barhto plot a binary timeline.

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import matplotlib.dates

#create a time series s with dates as index and 0 and 1 for events
dates = pd.date_range("2017-04-01","2017-06-15", freq="D")
events = np.random.random_integers(0,1,size=len(dates))
s = pd.Series(events, index=dates)

fig, ax= plt.subplots(figsize=(6,2))

# plot green for event==1
s1 = s[s == 1]
inxval = matplotlib.dates.date2num(s1.index.to_pydatetime())
times= zip(inxval, np.ones(len(s1)))
plt.broken_barh(times, (-1,1), color="green")
# plot red for event==0
s2 = s[s == 0]
inxval = matplotlib.dates.date2num(s2.index.to_pydatetime())
times= zip(inxval, np.ones(len(s2)))
plt.broken_barh(times, (-1,1), color="red")

#format axes
ax.margins(0)
ax.set_yticks([])
ax.xaxis.set_major_locator(matplotlib.dates.MonthLocator())
ax.xaxis.set_minor_locator(matplotlib.dates.DayLocator())
monthFmt = matplotlib.dates.DateFormatter("%b")
ax.xaxis.set_major_formatter(monthFmt)
plt.tight_layout()
plt.show()


问:
nth word in a text
how can I find the nth word in a text.

example:

```<code>my_txt("hello to you all" , 3)

all
</code>```

I don't wanna use any built in function ...and this is not a homework :D

答:
Since everything is a built in function in one way or another, I'm gonna ignore your claim to not want to use built in functions.

```<code>def my_txt(text, n):
    return text.split()[n]
</code>```

Main drawback with this is that you'll get punctuation included. I leave it as exercise to figure out how to get rid of that. :)

Title: nth word in a text

Body:
how can I find the nth word in a text.

example:

my_txt("hello to you all" , 3)

all

I don't wanna use any built in function ...and this is not a homework :D

Body:
Since everything is a built in function in one way or another, I'm gonna ignore your claim to not want to use built in functions.

def my_txt(text, n):
    return text.split()[n]

Main drawback with this is that you'll get punctuation included. I leave it as exercise to figure out how to get rid of that. :)


问:
JavaScript Regexp between two strings without capturing first string
So I've gone through several examples and this seems like it should be very simple, however nothing seems to be working.

I'm pulling an html file from an email and trying to parse it out using REGEXP. The line that I'm working on currently is this:

```<code><br><br><b>STATUS:</b> Cancel<br><br><b>
</code>```

And throughout the whole document there are a bunch of those tags.

I'm using regexr.com to do my testing.

The closest expression I've been able to come up with is:

```<code>(?:STATUS:<\/b> )(.*?)(?=&lt)
</code>```

When I use that though, it returns:

```<code>STATUS:</b> Cancel
</code>```

I'm just trying to get the "Cancel". I've seen other questions answered with using lookbehind, but that's not supported in JavaScript. Is there a work around for this or am I approaching this the wrong way?

Edit

I'm trying to pull the information via a Google Web App.

What I've learned so far is it depends on how your browser displays the info if you see "<" or the actual "<" so to make it easier to see, I shifted my characters in the REGEXP to:

```<code>(?:<b>STATUS:<\/b>)(.*?)(?=<br>)
</code>```

The line I'm trying to interpret would be:

```<code><b>STATUS:</b> Cancel<br>
</code>```

Here's the code I'm using to run the REGEXP:

```<code>var re = new RegExp('(?:<b>STATUS:<\/b> )(.*?)(?=<br>)');
var status = messages[i].getBody().match(re)[1];
var child = XmlService.createElement('Status').setText(status);
root.addContent(child);
</code>```

When I try to run it, I get the same thing

```<code>match[0] = "<b>STATUS:</b> Cancel"
match[1] = "<b>STATUS:</b> Cancel"
</code>```

答:
Alright, I think I got it. And apologies for any confusion.

I'm not sure if this is a bug somewhere, but the REGEXP works if you add parenthesis after the look ahead. The actual word will return in the third spot or match[2]

```<code>/(?:(<b>STATUS:<\/b> ))(.*?)(?=<br>)/
</code>```

This is working for me:

```<code>var re = new RegExp('(?:(<b>STATUS:<\/b> ))(.*?)(?=<br>)');
var status = messages[i].getBody().match(re)[2];
var child = XmlService.createElement('Status').setText(status);
root.addContent(child);
</code>```

It's an answer, however it doesn't make much sense to me. If someone can explain what's being pulled it would be much appreciated.

```<code>match[0] = "<b>STATUS:</b> Cancel"
match[1] = "<b>STATUS:</b> "
match[2] = "Cancel"
match[3] = null
</code>```

Body:
So I've gone through several examples and this seems like it should be very simple, however nothing seems to be working.

I'm pulling an html file from an email and trying to parse it out using REGEXP. The line that I'm working on currently is this:

STATUS: Cancel

And throughout the whole document there are a bunch of those tags.

I'm using regexr.com to do my testing.

The closest expression I've been able to come up with is:

(?:STATUS:<\/b> )(.*?)(?=&lt)

When I use that though, it returns:

STATUS: Cancel

I'm just trying to get the "Cancel". I've seen other questions answered with using lookbehind, but that's not supported in JavaScript. Is there a work around for this or am I approaching this the wrong way?

Edit

I'm trying to pull the information via a Google Web App.

What I've learned so far is it depends on how your browser displays the info if you see "<" or the actual "<" so to make it easier to see, I shifted my characters in the REGEXP to:

(?:STATUS:<\/b>)(.*?)(?=
)

The line I'm trying to interpret would be:

STATUS: Cancel

Here's the code I'm using to run the REGEXP:

var re = new RegExp('(?:STATUS:<\/b> )(.*?)(?=
)');
var status = messages[i].getBody().match(re)[1];
var child = XmlService.createElement('Status').setText(status);
root.addContent(child);

When I try to run it, I get the same thing

match[0] = "STATUS: Cancel"
match[1] = "STATUS: Cancel"

Body:
Alright, I think I got it. And apologies for any confusion.

I'm not sure if this is a bug somewhere, but the REGEXP works if you add parenthesis after the look ahead. The actual word will return in the third spot or match[2]

/(?:(<b>STATUS:<\/b> ))(.*?)(?=<br>)/

This is working for me:

var re = new RegExp('(?:(<b>STATUS:<\/b> ))(.*?)(?=<br>)');
var status = messages[i].getBody().match(re)[2];
var child = XmlService.createElement('Status').setText(status);
root.addContent(child);

It's an answer, however it doesn't make much sense to me. If someone can explain what's being pulled it would be much appreciated.

match[0] = "<b>STATUS:</b> Cancel"
match[1] = "<b>STATUS:</b> "
match[2] = "Cancel"
match[3] = null


问:
Fixing my background image and website layout on Blogger using CSS or HTML
Heres my website: www.ChrisStephensMusic.net

As you can see the background image is not full size and moves when the page is scrolled. I'd like it to be full size and remain still while the content scrolls. I've tried the CSS suggestions I could find when searching this topic here but they do nothing when I add them to the "Custom CSS" on Blogger. Is there a better way to fix this using HTML or is there something else I need to do to get the custom CSS to be recognized?

答:
Add the following CSS -

```<code>.bg-photo-container, div.bg-photo-overlay {
  height: 100%;
  position: fixed;
}
</code>```

The custom CSS option is not working because some invalid rules have been added to it, which is causing every rule after that to be ignored. I would instead suggest, adding this via HTML/JavaScript gadget by wrapping the code in a style tag so that it looks like

```<code><style>
  .bg-photo-container, div.bg-photo-overlay {
    height: 100%;
    position: fixed;
  }
</style>
</code>```

The final result should look like -

Body:
Add the following CSS -

.bg-photo-container, div.bg-photo-overlay {
  height: 100%;
  position: fixed;
}

The custom CSS option is not working because some invalid rules have been added to it, which is causing every rule after that to be ignored. I would instead suggest, adding this via HTML/JavaScript gadget by wrapping the code in a style tag so that it looks like

<style>
  .bg-photo-container, div.bg-photo-overlay {
    height: 100%;
    position: fixed;
  }
</style>

The final result should look like -


问:
Storing numeric values in Lucene 6.5.0
I need to Store the Numeric field in the Lucene docs, but Lucene 6.5.1 the signature of the NumericField is like

NumericDocValuesField(String name, long value)

In older lucene versions the method is like,

NumericField(String, Field.Store, boolean)

.
Can someone guide me how to store the numeric values in the document using lucene6.5.1.

Regards,

Raghavan

答:
NumericDocValuesField is used for scoring/sorting only:
http://lucene.apache.org/core/6_5_0/core/org/apache/lucene/document/NumericDocValuesField.html

If you like to store any kind of values (including numeric) you have to use a StoredField:
https://lucene.apache.org/core/6_5_0/core/org/apache/lucene/document/StoredField.html

Depending on what you need you have to add multiple fields for multiple purposes. If you have a numeric value as long and you like to do range queries and sort you would do something like this:

```<code>// for range queries
new LongPoint(field, value);
// for storing the value
new StoredField(field, value);
// for sorting / scoring
new NumericDocValuesField(field, value);
</code>```

Title: Storing numeric values in Lucene 6.5.0

Body:
NumericDocValuesField is used for scoring/sorting only:
http://lucene.apache.org/core/6_5_0/core/org/apache/lucene/document/NumericDocValuesField.html

If you like to store any kind of values (including numeric) you have to use a StoredField:
https://lucene.apache.org/core/6_5_0/core/org/apache/lucene/document/StoredField.html

Depending on what you need you have to add multiple fields for multiple purposes. If you have a numeric value as long and you like to do range queries and sort you would do something like this:

// for range queries
new LongPoint(field, value);
// for storing the value
new StoredField(field, value);
// for sorting / scoring
new NumericDocValuesField(field, value);