问:
postgresql trigger - Instead of insert dont work
This code works:

```<code>CREATE TRIGGER HandleRegistration
    BEFORE INSERT ON Registered
    FOR EACH ROW
    EXECUTE PROCEDURE registration_handler();
</code>```

But this one does not

```<code>CREATE TRIGGER HandleRegistration
    INSTEAD OF INSERT ON Registered
    FOR EACH ROW
    EXECUTE PROCEDURE registration_handler();
</code>```

I get the error:

"registered" is a table" - detail: Tables cannot have INSTEAD OF triggers.

But I have seen plenty examples online that this work. Why doesn't it work for me?

答:
https://www.postgresql.org/docs/current/static/sql-createtrigger.html

Triggers that are specified to fire INSTEAD OF the trigger event must
  be marked FOR EACH ROW, and can only be defined on views.

what you probably are looking for is RULE, not TRIGGER?..

https://www.postgresql.org/docs/current/static/sql-createrule.html

Alternatively, an INSTEAD rule can replace a given command by another,
  or cause a command not to be executed at all.

Body:
This code works:

CREATE TRIGGER HandleRegistration
    BEFORE INSERT ON Registered
    FOR EACH ROW
    EXECUTE PROCEDURE registration_handler();

But this one does not

CREATE TRIGGER HandleRegistration
    INSTEAD OF INSERT ON Registered
    FOR EACH ROW
    EXECUTE PROCEDURE registration_handler();

I get the error:

"registered" is a table" - detail: Tables cannot have INSTEAD OF triggers.

But I have seen plenty examples online that this work. Why doesn't it work for me?


来源: stackexchange

问:
Convert Excel File to CSV Then Load to SQL Table Using SSIS
I have a very large excel data to load to SQL table. For small data it works. However, for large data (more than 20 million records) I get the following error.

Excel to CSV : There were errors during task validation. Excel to CSV
  Error: "Excel Source" failed validation and returned validation status
  and returned validation status "VS_ISBROKEN". Excel to CSV: opening a
  rowset for "Table1$" failed. check that the object exists in the
  database. Excel to CSV:Error : SSIS  Error code DTS_E_OLEDBERROR. An
  OLE DB error has occurred .Error code 0x80004005.

答: My package had no problem. The issue is with the excel file . For small data the extension .xlsx works ( excel 2007) . For the large data i have to convert the data to  Excel 97 version which is (.xls). Doing so help load the data </p>

ContentLicense: CC BY-SA 3.0


问:
replacement of words in strings
I have a list of phrases, in which I want to replace certain words with a similar word, in case it is misspelled.

How can I search a string, a word that matches and replace it?

The expected result is the following example:

```<code>a1<- c(" the classroom is ful ")
a2<- c(" full")
</code>```

In this case I would be replacing ful for full in a1

答:
For a kind of ordered replacement, you can try this

```<code>a1 <- c("the classroome is ful")
# ordered replacement
badwords.corpus <- c("ful", "classroome")
goodwords.corpus <- c("full", "classroom")

qdap::mgsub(badwords.corpus, goodwords.corpus, a1) # or
stringi::stri_replace_all_fixed(a1, badwords.corpus, goodwords.corpus, vectorize_all = FALSE)
</code>```

For unordered replacement you can use an approximate string matching (see stringdist::amatch). Here is an example

```<code>a1 <- c("the classroome is ful")
a1
[1] "the classroome is ful"

library(stringdist)
goodwords.corpus <- c("full", "classroom")
badwords.corpus <- unlist(strsplit(a1, " ")) # extract words
for (badword in badwords.corpus){
  patt <- paste0('\\b', badword, '\\b')
  repl <- goodwords.corpus[amatch(badword, goodwords.corpus, maxDist = 1)] # you can change the distance see ?amatch
  final.word <- ifelse(is.na(repl), badword, repl)
  a1 <- gsub(patt, final.word, a1)
}
a1
[1] "the classroom is full"
</code>```

Title: replacement of words in strings

Body:
I have a list of phrases, in which I want to replace certain words with a similar word, in case it is misspelled.

How can I search a string, a word that matches and replace it?

The expected result is the following example:

a1<- c(" the classroom is ful ")
a2<- c(" full")

In this case I would be replacing ful for full in a1

Body:
For a kind of ordered replacement, you can try this

a1 <- c("the classroome is ful")
# ordered replacement
badwords.corpus <- c("ful", "classroome")
goodwords.corpus <- c("full", "classroom")

qdap::mgsub(badwords.corpus, goodwords.corpus, a1) # or
stringi::stri_replace_all_fixed(a1, badwords.corpus, goodwords.corpus, vectorize_all = FALSE)

For unordered replacement you can use an approximate string matching (see stringdist::amatch). Here is an example

a1 <- c("the classroome is ful")
a1
[1] "the classroome is ful"

library(stringdist)
goodwords.corpus <- c("full", "classroom")
badwords.corpus <- unlist(strsplit(a1, " ")) # extract words
for (badword in badwords.corpus){
  patt <- paste0('\\b', badword, '\\b')
  repl <- goodwords.corpus[amatch(badword, goodwords.corpus, maxDist = 1)] # you can change the distance see ?amatch
  final.word <- ifelse(is.na(repl), badword, repl)
  a1 <- gsub(patt, final.word, a1)
}
a1
[1] "the classroom is full"


问:
Save custom global data into a tenant
What I want to achieve is to have a global fragment with a custom data. This data-fragment must be accessible any time from a central source and it can be different between tenants. This data will be required for all devices

I have two ideas

The tenant:
What is the best way to save custom data into the tenant fragment? I have tried using the below request but with not luck.

```<code>PUT /tenant/tenants/tenant1 HTTP/1.1
Host: tenant1.enterpise.com
Content-Type: application/json
Accept: application/json
Authorization: Basic

{
 "customFragment:{
  "forms":[
     {
      "type": ....,
      "inputa" : ...
     },
     .....
   ],
   "products":[
     {
      "name": ....,
      "stock" : ...
     }
   ],
   .....
  }
}
</code>```

What can I do?

Using a managementObject with the custom data fragment.

May I use a management object into the database in order to achieve this? Will I be charge if this management object has not the isDevice property?

Thanks in advance!

答:
Both approaches are valid here

Storing it inside the tenant object

Your request is (almost) correct but this request cannot be executed with a user of tenant1. A tenant can not update its own tenant object. You need to execute this request from the parent tenant (either the management tenant or if it is subtenant of another tenant you can also do it from there).
Now for the almost part: For tenants you cannot directly create arbitrary fragments. You need to put your custom data into a fragment called "customProperties". What you put inside that fragment is then again up to you.

```<code>{
   "customProperties" : {
        "test": "test",
        "abc": {
            "test": 1
        }
   }
}
</code>```

For accessing this data you can use the API /tenant/currentTenant. This API is always available for every authenticated user regardless of access rights. It will return the tenant information (including the customProperties). This API is also read only, it is like the /user/currentUser API.

Storing inside a managedObject

In the inventory API you can add a fragment "c8y_Global" to an object. This will make this managedObject available for every user regardless of access rights (you still need valid credentials to the tenant of course.

```<code>{
   "c8y_Global": {},
   "myConfig": {
        ...
   }
}
</code>```

Regarding the charging better check directly with your platform provider but usually only devices are part of the charging and this would not be considered a device. Dashboards are btw also just such kind of managedObjects with this c8y_Global flag.

Title: Save custom global data into a tenant

Body:
What I want to achieve is to have a global fragment with a custom data. This data-fragment must be accessible any time from a central source and it can be different between tenants. This data will be required for all devices

I have two ideas

The tenant:
What is the best way to save custom data into the tenant fragment? I have tried using the below request but with not luck.

PUT /tenant/tenants/tenant1 HTTP/1.1
Host: tenant1.enterpise.com
Content-Type: application/json
Accept: application/json
Authorization: Basic

{
 "customFragment:{
  "forms":[
     {
      "type": ....,
      "inputa" : ...
     },
     .....
   ],
   "products":[
     {
      "name": ....,
      "stock" : ...
     }
   ],
   .....
  }
}

What can I do?

Using a managementObject with the custom data fragment.

May I use a management object into the database in order to achieve this? Will I be charge if this management object has not the isDevice property?

Thanks in advance!

Body:
Both approaches are valid here

Storing it inside the tenant object

Your request is (almost) correct but this request cannot be executed with a user of tenant1. A tenant can not update its own tenant object. You need to execute this request from the parent tenant (either the management tenant or if it is subtenant of another tenant you can also do it from there).
Now for the almost part: For tenants you cannot directly create arbitrary fragments. You need to put your custom data into a fragment called "customProperties". What you put inside that fragment is then again up to you.

{
   "customProperties" : {
        "test": "test",
        "abc": {
            "test": 1
        }
   }
}

For accessing this data you can use the API /tenant/currentTenant. This API is always available for every authenticated user regardless of access rights. It will return the tenant information (including the customProperties). This API is also read only, it is like the /user/currentUser API.

Storing inside a managedObject

In the inventory API you can add a fragment "c8y_Global" to an object. This will make this managedObject available for every user regardless of access rights (you still need valid credentials to the tenant of course.

{
   "c8y_Global": {},
   "myConfig": {
        ...
   }
}

Regarding the charging better check directly with your platform provider but usually only devices are part of the charging and this would not be considered a device. Dashboards are btw also just such kind of managedObjects with this c8y_Global flag.


问:
Disabling string interning within Jaxb2 speeds up unmarshalling from a Fastinfoset stream. Why is it so hard to disable?
I've measured the time cost of unmarshalling XML to objects using Jaxb2 using a large (1.7mb) XML payload with somewhat long (48 character) tag names. I observed via JProfiler running in sampling mode that string interning work was a solid portion of the time spent.

I did some research and found that Jaxb can be run in a mode where it doesn't intern strings. My theory was that in some cases not interning strings during unmarshalling could improve performance at the expense of using more heap memory due to not having to hash every tag name string during the interning process.

The method that I used to suppress Jaxb's interning behavior was to set on my Fastinfoset "StAXDocumentParser" (which implements XMLStreamReader) the "org.codehaus.stax2.internNames" and "org.codehaus.stax2.internNsUris" properties. It's not 100% clear to me why you must set these to "true" in order to prevent Jaxb from interning strings but that is how it works.

These JUnit-driven tests are what I used to conclude that disabling Jaxb's string interning behavior makes a big performance difference:

https://github.com/gjd6640/fastinfoset-performance-evaluation

So my question is multi-part:

1) Am I misunderstanding something important and shouldn't be trying to disable Jaxb's string interning behavior in the first place?

2) Is there a better way to direct Jaxb not to intern strings? The "StAXManager" class doesn't allow you to set these Woodstox-oriented properties. For this test I ended up extending StAXManager as shown below to hack around the problem. This is a hack that I'd prefer not to use in production. I suspect that the idea here is that when Jaxb is unmarshalling from a Woodstox stream it looks to see if Woodstox is already doing interning and when "yes" Jaxb reacts by disabling that step of the process. I'm cheating by piggybacking on that logic in the Jaxb library so would like a better way to go about this.

```<code>package com.sun.xml.fastinfoset.stax;
public class JaxbStringInternSuppressionStaxManager extends StAXManager {
    public JaxbStringInternSuppressionStaxManager() {
        // Add to the allowable list of feature names so that the user may set these "StAXInputFactory" properties
        super.features.put("org.codehaus.stax2.internNames", null);
        super.features.put("org.codehaus.stax2.internNsUris", null);
    }
}
</code>```

Update:

As usual, "A question well-put is half-answered". I've just noticed while drafting this question that "com.sun.xml.internal.bind.v2.runtime.unmarshaller.StAXStreamConnector" checks to see if class "com.sun.xml.internal.fastinfoset.stax.StAXDocumentParser" is assignable from the XMLStreamReader that you're using and if so does not enable string interning. In my case my stream object is a "com.sun.xml.fastinfoset.stax.StAXDocumentParser" so interning doesn't get disabled. Now the question is "why does it do this only for the internal flavor of the Fastinfoset library?" Maybe I'll find the answer by carefully reading this post.

Also, if there's a better forum for this sort of question such as an active developer user group please share that info and I'll see about linking them over to this post so that the right people will see this question.

答:
I wouldn't necessarily trust a profiler or a test without also measuring the real use case with and without interning, so be a bit skeptic. However, there are some issues with intern. In particular it uses a fixed-size pool size, so when the pool is full the would-be constant performance for hash lookups degrades to searching linked lists. See http://java-performance.info/string-intern-in-java-6-7-8/ for a longer discussion.

In short you can try to change the pool size with -XX:StringTableSize=n (where n should ideally be prime) and see what happens.

Use -XX:+PrintStringTableStatistics to see how the pool was used when the program terminates and try different sizes.

EDIT: this was an attempt to answer "is there a better way" (i.e. make intern faster). I'll leave the other question to someone more qualified.

Body:
I've measured the time cost of unmarshalling XML to objects using Jaxb2 using a large (1.7mb) XML payload with somewhat long (48 character) tag names. I observed via JProfiler running in sampling mode that string interning work was a solid portion of the time spent.

I did some research and found that Jaxb can be run in a mode where it doesn't intern strings. My theory was that in some cases not interning strings during unmarshalling could improve performance at the expense of using more heap memory due to not having to hash every tag name string during the interning process.

The method that I used to suppress Jaxb's interning behavior was to set on my Fastinfoset "StAXDocumentParser" (which implements XMLStreamReader) the "org.codehaus.stax2.internNames" and "org.codehaus.stax2.internNsUris" properties. It's not 100% clear to me why you must set these to "true" in order to prevent Jaxb from interning strings but that is how it works.

These JUnit-driven tests are what I used to conclude that disabling Jaxb's string interning behavior makes a big performance difference:

https://github.com/gjd6640/fastinfoset-performance-evaluation

So my question is multi-part:

1) Am I misunderstanding something important and shouldn't be trying to disable Jaxb's string interning behavior in the first place?

2) Is there a better way to direct Jaxb not to intern strings? The "StAXManager" class doesn't allow you to set these Woodstox-oriented properties. For this test I ended up extending StAXManager as shown below to hack around the problem. This is a hack that I'd prefer not to use in production. I suspect that the idea here is that when Jaxb is unmarshalling from a Woodstox stream it looks to see if Woodstox is already doing interning and when "yes" Jaxb reacts by disabling that step of the process. I'm cheating by piggybacking on that logic in the Jaxb library so would like a better way to go about this.

package com.sun.xml.fastinfoset.stax;
public class JaxbStringInternSuppressionStaxManager extends StAXManager {
    public JaxbStringInternSuppressionStaxManager() {
        // Add to the allowable list of feature names so that the user may set these "StAXInputFactory" properties
        super.features.put("org.codehaus.stax2.internNames", null);
        super.features.put("org.codehaus.stax2.internNsUris", null);
    }
}

Update:

As usual, "A question well-put is half-answered". I've just noticed while drafting this question that "com.sun.xml.internal.bind.v2.runtime.unmarshaller.StAXStreamConnector" checks to see if class "com.sun.xml.internal.fastinfoset.stax.StAXDocumentParser" is assignable from the XMLStreamReader that you're using and if so does not enable string interning. In my case my stream object is a "com.sun.xml.fastinfoset.stax.StAXDocumentParser" so interning doesn't get disabled. Now the question is "why does it do this only for the internal flavor of the Fastinfoset library?" Maybe I'll find the answer by carefully reading this post.

Also, if there's a better forum for this sort of question such as an active developer user group please share that info and I'll see about linking them over to this post so that the right people will see this question.


问:
django creating generic class to validate User authentication
I am trying to replace the generic View class with a custom class so that the user authentication happens automatically when i make a reference to this class.

The Base Class

```<code>class CustomView(View):

    def __init__(self, request):
        if not request.user.is_authenticated:
            redirect('register.registerForm')
</code>```

The sub class

class DashboardPage(CustomView):

```<code>def get(self, request):
    user_object = User.objects.get(username=request.user)
    all_files = user_object.files_set.all()
    return render(request, 'dashboard/dashboard.html', {'all_files': all_files})
</code>```

I expected the user authentication happened automatically when the CustomView class is called. And also wanted to know if this is the best way to generalize user authentication for all the pages in my application which require authentication.

I am getting the below error:

```<code>TypeError at /dashboard/
__init__() missing 1 required positional argument: 'request'
Request Method: GET
Request URL:    http://127.0.0.1:8000/dashboard/
Django Version: 1.11.7
Exception Type: TypeError
Exception Value:
__init__() missing 1 required positional argument: 'request'
Exception Location: C:\Program Files (x86)\Python36-32\lib\site-packages\django-1.11.7-py3.6.egg\django\views\generic\base.py in view, line 62
Python Executable:  C:\Program Files (x86)\Python36-32\python.exe
Python Version: 3.6.3
Python Path:
['C:\\Users\\Varun\\Desktop\\newsite',
 'C:\\Program Files (x86)\\Python36-32\\python36.zip',
 'C:\\Program Files (x86)\\Python36-32\\DLLs',
 'C:\\Program Files (x86)\\Python36-32\\lib',
 'C:\\Program Files (x86)\\Python36-32',
 'C:\\Program Files (x86)\\Python36-32\\lib\\site-packages',
 'C:\\Program Files '
 '(x86)\\Python36-32\\lib\\site-packages\\django-1.11.7-py3.6.egg',
 'C:\\Program Files '
 '(x86)\\Python36-32\\lib\\site-packages\\pytz-2017.3-py3.6.egg']
Server time:    Mon, 4 Dec 2017 20:43:12 +0000
</code>```

答:
You need to use the LoginRequired mixin:

```<code>from django.contrib.auth.mixins import LoginRequiredMixin

class MyView(LoginRequiredMixin, View):
    login_url = '/login/'
    redirect_field_name = 'redirect_to'
</code>```

If a user is not logged in, it will automatically redirect to the contents of the form field redirect_to. In the default login form view this field is called next.

Body:
I am trying to replace the generic View class with a custom class so that the user authentication happens automatically when i make a reference to this class.

The Base Class

class CustomView(View):

    def __init__(self, request):
        if not request.user.is_authenticated:
            redirect('register.registerForm')

The sub class

class DashboardPage(CustomView):

def get(self, request):
    user_object = User.objects.get(username=request.user)
    all_files = user_object.files_set.all()
    return render(request, 'dashboard/dashboard.html', {'all_files': all_files})

I expected the user authentication happened automatically when the CustomView class is called. And also wanted to know if this is the best way to generalize user authentication for all the pages in my application which require authentication.

I am getting the below error:

TypeError at /dashboard/
__init__() missing 1 required positional argument: 'request'
Request Method: GET
Request URL:    http://127.0.0.1:8000/dashboard/
Django Version: 1.11.7
Exception Type: TypeError
Exception Value:
__init__() missing 1 required positional argument: 'request'
Exception Location: C:\Program Files (x86)\Python36-32\lib\site-packages\django-1.11.7-py3.6.egg\django\views\generic\base.py in view, line 62
Python Executable:  C:\Program Files (x86)\Python36-32\python.exe
Python Version: 3.6.3
Python Path:
['C:\\Users\\Varun\\Desktop\\newsite',
 'C:\\Program Files (x86)\\Python36-32\\python36.zip',
 'C:\\Program Files (x86)\\Python36-32\\DLLs',
 'C:\\Program Files (x86)\\Python36-32\\lib',
 'C:\\Program Files (x86)\\Python36-32',
 'C:\\Program Files (x86)\\Python36-32\\lib\\site-packages',
 'C:\\Program Files '
 '(x86)\\Python36-32\\lib\\site-packages\\django-1.11.7-py3.6.egg',
 'C:\\Program Files '
 '(x86)\\Python36-32\\lib\\site-packages\\pytz-2017.3-py3.6.egg']
Server time:    Mon, 4 Dec 2017 20:43:12 +0000

Body:
You need to use the LoginRequired mixin:

from django.contrib.auth.mixins import LoginRequiredMixin

class MyView(LoginRequiredMixin, View):
    login_url = '/login/'
    redirect_field_name = 'redirect_to'

If a user is not logged in, it will automatically redirect to the contents of the form field redirect_to. In the default login form view this field is called next.


问:
How to concatenate two vectors of different dimensions
If X = [[ 1.  1.  1.  1.  1.  1.]] and Y = [[ 0.  0.  0.  0.]] - how can I concatenate the two vectors to form a single vector along column?

I did the following but it didn't work:

```<code>import tensorflow as tf
X = tf.constant(1.0, shape=[1, 6])
Y = tf.zeros(shape=[1,4])
XY = tf.concat((X,Y), axis = 0)
sess = tf.Session()
print(sess.run(XY))
</code>```

答:
If you want to concat them on axis 0, then their size must be equal

Assuming that you don't want it,

you need to set axis = 1 in the tf.concat method

Body:
If X = [[ 1.  1.  1.  1.  1.  1.]] and Y = [[ 0.  0.  0.  0.]] - how can I concatenate the two vectors to form a single vector along column?

I did the following but it didn't work:

import tensorflow as tf
X = tf.constant(1.0, shape=[1, 6])
Y = tf.zeros(shape=[1,4])
XY = tf.concat((X,Y), axis = 0)
sess = tf.Session()
print(sess.run(XY))


问:
PHP+JSON Display result with no key?
First of all, sorry because my english is bad.

Ive got a problem.
Requesting data from URL in JSON format and got something like:

```<code>array(1) { ["NICK_HERE"]=> array(5) { ["id"]=> int(123456789) ["name"]=> string(11) "NICK_HERE" ["class"]=> int(538) ["level"]=> int(97) ["online"]=> int(1420061059000) } }
</code>```

And then, I want to display something from there, normally it would be $x['NICK_HERE']['id'], but because NICK_HERE will be changing, and because i can't use a variable in there, is there a way to bypass this?
For example something like $x[0]['id'] ?
Sort of choose first, no matter whats that?

Appreciate your help!

P.s. Happy New Year!

答:
My advice (because I think it is the simplest is to use current(), but you can also use array_column()...

Code: (Demo)

```<code>$array=[
    "NICK_HERE"=>["id"=>123456789,"name"=>"NICK_HERE","class"=>538,"level"=>97,"online"=>1420061059000]
];

echo current($array)['id'];

echo "\n";

echo array_column($array,'id')[0];
</code>```

Output:

```<code>123456789
123456789
</code>```

These methods assume that the subarray element id is guaranteed to exist.  If it might not, you will need to check with isset() before trying to access -- to avoid a Notice.

Title: PHP+JSON Display result with no key?

Body:
First of all, sorry because my english is bad.

Ive got a problem.
Requesting data from URL in JSON format and got something like:

array(1) { ["NICK_HERE"]=> array(5) { ["id"]=> int(123456789) ["name"]=> string(11) "NICK_HERE" ["class"]=> int(538) ["level"]=> int(97) ["online"]=> int(1420061059000) } }

And then, I want to display something from there, normally it would be $x['NICK_HERE']['id'], but because NICK_HERE will be changing, and because i can't use a variable in there, is there a way to bypass this?
For example something like $x[0]['id'] ?
Sort of choose first, no matter whats that?

Appreciate your help!

P.s. Happy New Year!

Body:
My advice (because I think it is the simplest is to use current(), but you can also use array_column()...

Code: (Demo)

$array=[
    "NICK_HERE"=>["id"=>123456789,"name"=>"NICK_HERE","class"=>538,"level"=>97,"online"=>1420061059000]
];

echo current($array)['id'];

echo "\n";

echo array_column($array,'id')[0];

Output:

123456789
123456789

These methods assume that the subarray element id is guaranteed to exist.  If it might not, you will need to check with isset() before trying to access -- to avoid a Notice.


问:
Exclude Woocommerce products from search loop
I am trying to create a custom search results page where Woocommerce product results are displayed separately to blog / general posts.

My aim is to display them as separate blocks with different styling.

```<code>[Block 1] - Woocommerce results

[Block 2] - Blog / Post results
</code>```

I have managed to display the products in one loop, but I am struggling to exclude products from the post loop.

I have tried creating a custom loop, however this just displays all the posts within those terms, rather than the posts returned in the search.

The loop I usually use is:

```<code><?php $loop = new WP_Query( array( 'post_type' => 'post' ?>
    <p>Something here</p>
<?php endwhile; wp_reset_query(); ?>
</code>```

However I believe this just isn't compatible and suitable for my needs.

If there's a better solution to separating these I would absolutely love to hear more.

答:
The problem you are having is that you have one main query, where you actually want to do two queries. You could of course modify the main query to contain both post types, but you would end up with a random number of both post types where you actually want to fill both columns.

If you modify the main query to only return one of the columns, you end up with a situation where it is awful to run the other query to get the rest of the posts. I think you should be able to use the posts_join and posts_where filters if you need them, but I am unsure about posts_search. You can use either WP_Query or get_posts to finally do the two queries you need.

```<code><?php
  // Since we are searching, we probably should get the search keyword
  $search = get_query_var('s');

  // Since we want to be able to navigate, we probably should figure out on which page we are
  $paged = get_query_var('paged');

  // Anything else we want to do in search queries we should be able to do in
  // a posts_join or posts_where filter by checking if is_search() is true

  // With that out of the way, we can construct our queries
  $query_posts_page = new WP_Query([
    's' => $search,
    'paged' => $paged,
    'post_type' => ['post', 'page']
  ]);
  $query_woocommerce = new WP_Query([
    's' => $search,
    'paged' => $paged,
    'post_type' => 'product'
  ]);
?>
<div class="col">
  <?php
    if ( $query_posts_page->have_posts() ) {
      while ( $the_query->have_posts() ) {
        $query_posts_page->the_post();
        echo get_the_title();
      }

      /* Restore original Post Data */
      wp_reset_postdata();
    } else {
      echo 'Nope, no more data';
    }
  ?>
</div>
<div class="col">
  <?php
    if ( $query_woocommerce->have_posts() ) {
      while ( $query_woocommerce->have_posts() ) {
        $query_posts_page->the_post();
        echo get_the_title();
      }

      /* Restore original Post Data */
      wp_reset_postdata();
    } else {
      echo 'Nope, no more data';
    }
  ?>
</div>
</code>```

There is however still another problem. we can't automatically generate pagination, considering we are running two custom queries instead of the main query. Furthermore, we are unlikely to have an equal number of normal page/posts and products.

We can figure out what the maximum number of pages is for each of the loops by using max_num_pages. You can generate something yourself using that.

```<code><?php
  $maximum_page = max($query_posts_page->max_num_pages, $query_woocommerce->max_num_pages);
  for( $i = 1; $i < $maximum_page; $i++) {
    echo "{$i} ";
  }
</code>```

Body:
I am trying to create a custom search results page where Woocommerce product results are displayed separately to blog / general posts.

My aim is to display them as separate blocks with different styling.

[Block 1] - Woocommerce results

[Block 2] - Blog / Post results

I have managed to display the products in one loop, but I am struggling to exclude products from the post loop.

I have tried creating a custom loop, however this just displays all the posts within those terms, rather than the posts returned in the search.

The loop I usually use is:

<?php $loop = new WP_Query( array( 'post_type' => 'post' ?>

Something here

<?php endwhile; wp_reset_query(); ?>

However I believe this just isn't compatible and suitable for my needs.

If there's a better solution to separating these I would absolutely love to hear more.

Body:
The problem you are having is that you have one main query, where you actually want to do two queries. You could of course modify the main query to contain both post types, but you would end up with a random number of both post types where you actually want to fill both columns.

If you modify the main query to only return one of the columns, you end up with a situation where it is awful to run the other query to get the rest of the posts. I think you should be able to use the posts_join and posts_where filters if you need them, but I am unsure about posts_search. You can use either WP_Query or get_posts to finally do the two queries you need.

<?php
  // Since we are searching, we probably should get the search keyword
  $search = get_query_var('s');

  // Since we want to be able to navigate, we probably should figure out on which page we are
  $paged = get_query_var('paged');

  // Anything else we want to do in search queries we should be able to do in
  // a posts_join or posts_where filter by checking if is_search() is true

  // With that out of the way, we can construct our queries
  $query_posts_page = new WP_Query([
    's' => $search,
    'paged' => $paged,
    'post_type' => ['post', 'page']
  ]);
  $query_woocommerce = new WP_Query([
    's' => $search,
    'paged' => $paged,
    'post_type' => 'product'
  ]);
?>
<div class="col">
  <?php
    if ( $query_posts_page->have_posts() ) {
      while ( $the_query->have_posts() ) {
        $query_posts_page->the_post();
        echo get_the_title();
      }

      /* Restore original Post Data */
      wp_reset_postdata();
    } else {
      echo 'Nope, no more data';
    }
  ?>
</div>
<div class="col">
  <?php
    if ( $query_woocommerce->have_posts() ) {
      while ( $query_woocommerce->have_posts() ) {
        $query_posts_page->the_post();
        echo get_the_title();
      }

      /* Restore original Post Data */
      wp_reset_postdata();
    } else {
      echo 'Nope, no more data';
    }
  ?>
</div>

There is however still another problem. we can't automatically generate pagination, considering we are running two custom queries instead of the main query. Furthermore, we are unlikely to have an equal number of normal page/posts and products.

We can figure out what the maximum number of pages is for each of the loops by using max_num_pages. You can generate something yourself using that.

<?php
  $maximum_page = max($query_posts_page->max_num_pages, $query_woocommerce->max_num_pages);
  for( $i = 1; $i < $maximum_page; $i++) {
    echo "{$i} ";
  }


Title: Locating timessteps with a non-succesive value

Body:
I have a very long timeseries indicating wether a day was dry (no rain) or wet. Part of the timeserie is shown here:

Date          DryDay
2009-05-07    0
2009-05-08    0
2009-05-09    1
2009-05-10    1
2009-05-11    1
2009-05-12    1
2009-05-13    1
2009-05-14    0
2009-05-15    0
2009-05-16    0
2009-05-17    0
2009-05-18    1
2009-05-20    0
2009-05-21    1
2009-05-22    0
2009-05-23    1
2009-05-24    1
2009-05-25    1
2009-05-26    0
2009-05-27    0
2009-05-28    1
2009-05-29    1
2009-05-30    0
....

I need to find dry periods, which means that I want to find periods with succesive dry days (more than one dry days succesive). Therefore I would like change the value of DryDay from 1 to 0 when there is only on dry day succesive. Like this:

Date          DryDay
2009-05-07    0
2009-05-08    0
2009-05-09    1
2009-05-10    1
2009-05-11    1
2009-05-12    1
2009-05-13    1
2009-05-14    0
2009-05-15    0
2009-05-16    0
2009-05-17    0
2009-05-18    0
2009-05-20    0
2009-05-21    0
2009-05-22    0
2009-05-23    1
2009-05-24    1
2009-05-25    1
2009-05-26    0
2009-05-27    0
2009-05-28    1
2009-05-29    1
2009-05-30    0
...

Can anyone help me how to do this with Pandas?

Body:
There might be a better way but here is one,

df['DryDay'] = ((df['DryDay'] == 1) & ((df['DryDay'].shift() == 1) | (df['DryDay'].shift(-1) == 1))).astype(int)

    Date        DryDay
0   2009-05-07  0
1   2009-05-08  0
2   2009-05-09  1
3   2009-05-10  1
4   2009-05-11  1
5   2009-05-12  1
6   2009-05-13  1
7   2009-05-14  0
8   2009-05-15  0
9   2009-05-16  0
10  2009-05-17  0
11  2009-05-18  0
12  2009-05-20  0
13  2009-05-21  0
14  2009-05-22  0
15  2009-05-23  1
16  2009-05-24  1
17  2009-05-25  1
18  2009-05-26  0
19  2009-05-27  0
20  2009-05-28  1
21  2009-05-29  1
22  2009-05-30  0


问:
Django "Did you mean?" query
I am writing a fairly simple Django application where users can enter string queries. The application will the search through the database for this string.

```<code>Entry.objects.filter(headline__contains=query)
</code>```

This query is pretty strait forward but not really helpful to someone who isn't 100% sure what they are looking for. So I expanded the search.

```<code>from django.utils import stopwords

results = Entry.objects.filter(headline__contains=query)
if(!results):
    query = strip_stopwords(query)
    for(q in query.split(' ')):
        results += Entry.objects.filter(headline__contains=q)
</code>```

I would like to add some additional functionality to this. Searching for miss spelled words, plurals, common homophones (sound the same spelled differently), ect. I was just wondering if any of these things were built into Djangos query language. It isn't important enough for me to write a huge algorithm for I am really just looking for something built in.

Thanks in advance for all the answers.

答:
You could try using python's difflib module.

```<code>>>> from difflib import get_close_matches
>>> get_close_matches('appel', ['ape', 'apple', 'peach', 'puppy'])
['apple', 'ape']
>>> import keyword
>>> get_close_matches('wheel', keyword.kwlist)
['while']
>>> get_close_matches('apple', keyword.kwlist)
[]
>>> get_close_matches('accept', keyword.kwlist)
['except']
</code>```

Problem is that to use difflib one must build a list of words from the database. That can be expensive. Maybe if you cache the list of words and only rebuild it once in a while.

Some database systems support a search method to do what you want, like PostgreSQL's fuzzystrmatch module. If that is your case you could try calling it.

edit:

For your new "requirement", well, you are out of luck. No, there is nothing built in inside django's query language.

OwnerDisplayName: Matt Campbell

ContentLicense: CC BY-SA 2.5

Title: Django "Did you mean?" query

Body:
I am writing a fairly simple Django application where users can enter string queries. The application will the search through the database for this string.

Entry.objects.filter(headline__contains=query)

This query is pretty strait forward but not really helpful to someone who isn't 100% sure what they are looking for. So I expanded the search.

from django.utils import stopwords

results = Entry.objects.filter(headline__contains=query)
if(!results):
    query = strip_stopwords(query)
    for(q in query.split(' ')):
        results += Entry.objects.filter(headline__contains=q)

I would like to add some additional functionality to this. Searching for miss spelled words, plurals, common homophones (sound the same spelled differently), ect. I was just wondering if any of these things were built into Djangos query language. It isn't important enough for me to write a huge algorithm for I am really just looking for something built in.

Thanks in advance for all the answers.

LastEditorDisplayName: Fabian Steeg

Body:
You could try using python's difflib module.

>>> from difflib import get_close_matches
>>> get_close_matches('appel', ['ape', 'apple', 'peach', 'puppy'])
['apple', 'ape']
>>> import keyword
>>> get_close_matches('wheel', keyword.kwlist)
['while']
>>> get_close_matches('apple', keyword.kwlist)
[]
>>> get_close_matches('accept', keyword.kwlist)
['except']

Problem is that to use difflib one must build a list of words from the database. That can be expensive. Maybe if you cache the list of words and only rebuild it once in a while.

Some database systems support a search method to do what you want, like PostgreSQL's fuzzystrmatch module. If that is your case you could try calling it.

edit:

For your new "requirement", well, you are out of luck. No, there is nothing built in inside django's query language.

OwnerDisplayName: nosklo

LastEditorDisplayName: nosklo


问:
Matching a url pattern in <intent-filter>
I'd like one of my activities to pick up a particular url. The pattern is:

```<code>http://www.example.com/abc123/foo/xyz789
</code>```

The path components "abc123" and "xyz789" can be any sequence of alpha-numerics, length > 1.

Doing this in my manifest:

```<code><activity>
  <intent-filter>
    <action
      android:name="android.intent.action.VIEW" />
    <category
      android:name="android.intent.category.DEFAULT" />
    <category
      android:name="android.intent.category.BROWSABLE" />

    <data
      android:scheme="http"
      android:host="example.com"
      android:pathPattern="/.*/foo/.*" />
</code>```

but it seems that any pattern from my domain is getting matched, ie:

```<code>myexample.com
myexample.com/whatever
</code>```

both get matched. I guess maybe the .* operator is not working as I expect here? Any help would be great,

Thanks

http://developer.android.com/guide/topics/manifest/data-element.html

答:
The problem is that .* matches everything, -and nothing-, so "/.*/" matches "//", which is equivalent to just "/" in a path.

Also, you can ensure that the two path segments "abc123" in your example are equal with the expression matcher supported here.

In other words, you want want to alter your paths to something simpler that can be matched. if it's your component that's receiving the intent, you can pass a fake URL that is just the variable parts of the real URL. for example, if you want to match,

```<code>http://www.example.com/.+/foo/.+
</code>```

Where the two captured groups are equal, just pass http://mystuff/abc123 in the intent, and set the data pattern to http://mystuff/*

Then parse that when you receive the intent, and transform it into the real URL by filling in the known constant parts.

ContentLicense: CC BY-SA 4.0

Body:
I'd like one of my activities to pick up a particular url. The pattern is:

http://www.example.com/abc123/foo/xyz789

The path components "abc123" and "xyz789" can be any sequence of alpha-numerics, length > 1.

Doing this in my manifest:

<activity>
  <intent-filter>
    <action
      android:name="android.intent.action.VIEW" />
    <category
      android:name="android.intent.category.DEFAULT" />
    <category
      android:name="android.intent.category.BROWSABLE" />

    <data
      android:scheme="http"
      android:host="example.com"
      android:pathPattern="/.*/foo/.*" />

but it seems that any pattern from my domain is getting matched, ie:

myexample.com
myexample.com/whatever

both get matched. I guess maybe the .* operator is not working as I expect here? Any help would be great,

Thanks

http://developer.android.com/guide/topics/manifest/data-element.html

Body:
The problem is that .* matches everything, -and nothing-, so "/.*/" matches "//", which is equivalent to just "/" in a path.

Also, you can ensure that the two path segments "abc123" in your example are equal with the expression matcher supported here.

In other words, you want want to alter your paths to something simpler that can be matched. if it's your component that's receiving the intent, you can pass a fake URL that is just the variable parts of the real URL. for example, if you want to match,

http://www.example.com/.+/foo/.+

Where the two captured groups are equal, just pass http://mystuff/abc123 in the intent, and set the data pattern to http://mystuff/*

Then parse that when you receive the intent, and transform it into the real URL by filling in the known constant parts.


问:
JavaScript Check if array using categories contains string
I have an array containing the following data.

```<code>[ { name: 'hello', value: 'Bot hello!' },
  { name: 'help', value: 'Print help sheet.' },
  { name: 'kick', value: 'Kicks a user.' },
  { name: 'ping', value: 'Check the bot\'s Connection' },
  { name: 'roll', value: 'Roll a die.' } ]

var str = "ping"
if (str == //One of the names in the array){
   //Do stuff

}
</code>```

How can I create a function to check whether a string such as "ping" is equal to one of the values in the "name:" category? I want this to be dynamic so if the string is equal to "roll" it will flag that roll is in the array.

答:
In ES6:

var data = [ { name: 'hello', value: 'Bot hello!' },
  { name: 'help', value: 'Print help sheet.' },
  { name: 'kick', value: 'Kicks a user.' },
  { name: 'ping', value: 'Check the bot\'s Connection' },
  { name: 'roll', value: 'Roll a die.' } ]

var str = "ping"

console.log(data.some(x => x.name === str))```

Body:
I have an array containing the following data.

[ { name: 'hello', value: 'Bot hello!' },
  { name: 'help', value: 'Print help sheet.' },
  { name: 'kick', value: 'Kicks a user.' },
  { name: 'ping', value: 'Check the bot\'s Connection' },
  { name: 'roll', value: 'Roll a die.' } ]

var str = "ping"
if (str == //One of the names in the array){
   //Do stuff

}

How can I create a function to check whether a string such as "ping" is equal to one of the values in the "name:" category? I want this to be dynamic so if the string is equal to "roll" it will flag that roll is in the array.


Body:
Try this ....

((df1.DryDay.rolling(2,min_periods=1).sum()>1)|(df1.DryDay.iloc[::-1].rolling(2,min_periods=1).sum()>1)).astype(int)
Out[95]:
0     0
1     0
2     1
3     1
4     1
5     1
6     1
7     0
8     0
9     0
10    0
11    0
12    0
13    0
14    0
15    1
16    1
17    1
18    0
19    0
20    1
21    1
22    0
Name: DryDay, dtype: int32


问:
l[:] performance problem
Recently I was debugging a code like following

```<code>def getList():
    #query db and return a list
    total_list = Model.objects.all()
    result = list()
    for item in total_list:
        if item.attr1:
            result.append(item)
    return result

# in main code
org_list = getList()
list = orgList[:]#this line cause cpu problems.

if len(org_list)>0 and org_list[0].is_special:
    my_item = org_list[0]

for i in list:
    print_item(i)

doSomethingelse(list[0])
</code>```

In order to simplify the code I change most of it but the main part is here.

In getList method we query db and get 20~30 rows. Then we create a python list from it and return it.
in main method we get org_list variable from getList method
and slice it with orgList[:]

and loop over this list and call spesific elements on it like list[0]

The problem here is that this code runs on a really busy server and unfortunaletty it uses most of the cpu and eventually locks our servers.
Problem here is the line that we slice list varibale with list[:]
if we dont do that and just use org_list variable instead our servers does not have a problem. Does anybosy have any idea why that might happen. is slicing uses alot of cpu or when we use a sliced list. does it uses alot of cpu?

答:
unfortunately actual code is property of the company I worked for so I cannot give it exactly like it is but here is some part of it (variable names are changed,but argument of mainTree method was really named list.)

```<code>    mainObj = get_object_or_404(MainObj, code_name=my_code_name)
    if (not mainObj.is_now()) and (not request.user.is_staff):
        return HttpResponseRedirect("/")

    main_tree = mainObj.main_tree()
    objects = main_tree[:] # !!!
    if objects.__len__() == 1 and not objects[0].has_special_page:
        my_code_name = objects[0].code_name

...
...
...

mainObj.main_tree() is the following

    def main_tree(self):
        def append_obj_recursive(list, obj):
            list.append(obj)
            for c in self.obj_set.filter(parent_obj=obj):
                append_obj_recursive(list, c)
            return list

        root_obj = self.get_or_create_root_obj();
        top_level_objs = self.obj_set.filter(parent_obj=root_obj).order_by("weight")
        objs = []

        for tlc in top_level_objs:
            append_obj_recursive(objs, tlc)
        return objs
</code>```

This is a really weird problem. slicing  should not cause such a bizare problem. If I can find an answer I will post it here too.

Title: l[:] performance problem

Body:
Recently I was debugging a code like following

def getList():
    #query db and return a list
    total_list = Model.objects.all()
    result = list()
    for item in total_list:
        if item.attr1:
            result.append(item)
    return result

# in main code
org_list = getList()
list = orgList[:]#this line cause cpu problems.

if len(org_list)>0 and org_list[0].is_special:
    my_item = org_list[0]

for i in list:
    print_item(i)

doSomethingelse(list[0])

In order to simplify the code I change most of it but the main part is here.

In getList method we query db and get 20~30 rows. Then we create a python list from it and return it.
in main method we get org_list variable from getList method
and slice it with orgList[:]

and loop over this list and call spesific elements on it like list[0]

The problem here is that this code runs on a really busy server and unfortunaletty it uses most of the cpu and eventually locks our servers.
Problem here is the line that we slice list varibale with list[:]
if we dont do that and just use org_list variable instead our servers does not have a problem. Does anybosy have any idea why that might happen. is slicing uses alot of cpu or when we use a sliced list. does it uses alot of cpu?

Body:
unfortunately actual code is property of the company I worked for so I cannot give it exactly like it is but here is some part of it (variable names are changed,but argument of mainTree method was really named list.)

    mainObj = get_object_or_404(MainObj, code_name=my_code_name)
    if (not mainObj.is_now()) and (not request.user.is_staff):
        return HttpResponseRedirect("/")

    main_tree = mainObj.main_tree()
    objects = main_tree[:] # !!!
    if objects.__len__() == 1 and not objects[0].has_special_page:
        my_code_name = objects[0].code_name

...
...
...

mainObj.main_tree() is the following

    def main_tree(self):
        def append_obj_recursive(list, obj):
            list.append(obj)
            for c in self.obj_set.filter(parent_obj=obj):
                append_obj_recursive(list, c)
            return list

        root_obj = self.get_or_create_root_obj();
        top_level_objs = self.obj_set.filter(parent_obj=root_obj).order_by("weight")
        objs = []

        for tlc in top_level_objs:
            append_obj_recursive(objs, tlc)
        return objs

This is a really weird problem. slicing  should not cause such a bizare problem. If I can find an answer I will post it here too.


答:
You could use native array method some</p>

```<code>function contain(array, value) {
  return array.some(a => a.name === value);
}
if (contain(array, 'ping')){
   //Do stuff

}
</code>```

Title: JavaScript Check if array using categories contains string

Body:
You could use native array method some

function contain(array, value) {
  return array.some(a => a.name === value);
}
if (contain(array, 'ping')){
   //Do stuff

}


问:
Cannot resolve method ask - Akka Streaming with Java
I'm experimenting with akka, and (following the documentation), I have the following code:

```<code>Source<String, NotUsed> words =
                Source.from(Arrays.asList("hello", "hi"));
        Timeout askTimeout = Timeout.apply(5, TimeUnit.SECONDS);

        words
                .mapAsync(5, elem -> ask(ref, elem, askTimeout))
                .map(elem -> (String) elem)
                // continue processing of the replies from the actor
                .map(elem -> elem.toLowerCase())
                .runWith(Sink.ignore(), materializer);
</code>```

But I cannot find the "import static" directive to make the "ask method" work.
I got:

Cannot resolve method ask

What i'm doing wrong? I'm using akka v 2.4 (with Java, no Scala) and  following and following step by step the documentation:
http://doc.akka.io/docs/akka/2.4/java/stream/stream-integrations.html

Thanks.

答: This worked for me: import akka.pattern.ask

Body:
I'm experimenting with akka, and (following the documentation), I have the following code:

Source<String, NotUsed> words =
                Source.from(Arrays.asList("hello", "hi"));
        Timeout askTimeout = Timeout.apply(5, TimeUnit.SECONDS);

        words
                .mapAsync(5, elem -> ask(ref, elem, askTimeout))
                .map(elem -> (String) elem)
                // continue processing of the replies from the actor
                .map(elem -> elem.toLowerCase())
                .runWith(Sink.ignore(), materializer);

But I cannot find the "import static" directive to make the "ask method" work.
I got:

Cannot resolve method ask

What i'm doing wrong? I'm using akka v 2.4 (with Java, no Scala) and  following and following step by step the documentation:
http://doc.akka.io/docs/akka/2.4/java/stream/stream-integrations.html

Thanks.


问:
How to prevent using library compiled for a different version
Is there any standard way to force users to use my dll library exactly in the same version used during compilation ?

Lets assume I have library in version 1.0 with a function:

```<code>extern "C" void A();
</code>```

In version 1.1 I have added breaking change e.g.: another parameter to this function so I have:

```<code>extern "C" void A(int);
</code>```

The exported name in dll is exactly the same but if the developer compile the product with version 1.1, then send it to the customer and the customer will update only the product (exe file) then everything will fail. And it may fail in random point at runtime (depending on when this changed function is executed).

Are there any standard ways to prevent loading the library in wrong version ? I'm mostly interested with solution for Windows dll files. (But if there are solutions specific to other platforms, please leave the comment)

The example above is simplified. Adding c++ mangling solves the particular problem above, but I'm looking for more general solution.

My idea is to add a static object in the library header file. This static object in constructor could execute method from the library and the method in name has encoded current version like: init_library_1_1(); So if the method is missing in dll then at very beginning user see that something is wrong. But the solution looks like a dirty workaround. And I have to take care that developer include this file.

Is there any better solution for such problem ?

答:
There is no standard answer but many compiler/linker pairs have non-standard features to perform these kinds of tests.

Visual C++ for example has "#pragma detect_mismatch" that places a record in the output object file and then when the link is performed the records are tested and if they don't match an error is reported. I don't believe this would do any good if the DLL were loaded dynamically at run-time rather than statically during the load. I believe gcc/clang have something similar but don't know the details.

Body:
Is there any standard way to force users to use my dll library exactly in the same version used during compilation ?

Lets assume I have library in version 1.0 with a function:

extern "C" void A();

In version 1.1 I have added breaking change e.g.: another parameter to this function so I have:

extern "C" void A(int);

The exported name in dll is exactly the same but if the developer compile the product with version 1.1, then send it to the customer and the customer will update only the product (exe file) then everything will fail. And it may fail in random point at runtime (depending on when this changed function is executed).

Are there any standard ways to prevent loading the library in wrong version ? I'm mostly interested with solution for Windows dll files. (But if there are solutions specific to other platforms, please leave the comment)

The example above is simplified. Adding c++ mangling solves the particular problem above, but I'm looking for more general solution.

My idea is to add a static object in the library header file. This static object in constructor could execute method from the library and the method in name has encoded current version like: init_library_1_1(); So if the method is missing in dll then at very beginning user see that something is wrong. But the solution looks like a dirty workaround. And I have to take care that developer include this file.

Is there any better solution for such problem ?


问:
create variable conditionally by group in R (write function)
I want to create a variable by group conditioned on existing variable on individual level. Each individual has a outlier variable 1, 2, 3. I want to create a new variable by group so that the new var = 2 whenever there is at least one individual in that group whose outlier variable = 2; and the new var = 3 whenever there is at least one individual in that group whose outlier variable = 3.

The data looks like this

```<code>grpid id outlier
1     1   1
1     2   1
1     3   2
2     4   1
2     5   3
2     6   1
3     7   1
3     8   1
3     9   1
</code>```

Ideal output like this

```<code>grpid id outlier  goutlier
1     1   1       2
1     2   1       2
1     3   2       2
2     4   1       3
2     5   3       3
2     6   1       3
3     7   1       1
3     8   1       1
3     9   1       1
</code>```

Any suggestions?

Thanks!

答:
It is easy with dplyr

```<code>library(dplyr)
df <- read.table(header = TRUE,sep = ",",
                 text = "grpid,id,outlier
1,1,1
1,2,1
1,3,2
2,4,1
2,5,3
2,6,1
3,7,1
3,8,1
3,9,1")

df %>% group_by(grpid) %>% mutate(goutlier = max(outlier))
</code>```

Body:
I want to create a variable by group conditioned on existing variable on individual level. Each individual has a outlier variable 1, 2, 3. I want to create a new variable by group so that the new var = 2 whenever there is at least one individual in that group whose outlier variable = 2; and the new var = 3 whenever there is at least one individual in that group whose outlier variable = 3.

The data looks like this

grpid id outlier
1     1   1
1     2   1
1     3   2
2     4   1
2     5   3
2     6   1
3     7   1
3     8   1
3     9   1

Ideal output like this

grpid id outlier  goutlier
1     1   1       2
1     2   1       2
1     3   2       2
2     4   1       3
2     5   3       3
2     6   1       3
3     7   1       1
3     8   1       1
3     9   1       1

Any suggestions?

Thanks!

Body:
It is easy with dplyr

library(dplyr)
df <- read.table(header = TRUE,sep = ",",
                 text = "grpid,id,outlier
1,1,1
1,2,1
1,3,2
2,4,1
2,5,3
2,6,1
3,7,1
3,8,1
3,9,1")

df %>% group_by(grpid) %>% mutate(goutlier = max(outlier))


问:
How to check if all inputs are not empty with JQuery in order to show div
I have a form where, after the user answer every question in it, he clicks a button and a div is shown. How can I show a div when all inputs are filled?

The div can ONLY be shown after EVERY FIELD is filled!!

The div is shown when the user clicks the button

答:
Lets say that you have two input fields, and a button and a hidden div.
Now you can do the following</p>

```<code><input type="text" name="username">
<input type="text" name="password">
<button type="submit">submit</button>
<div class="showDiv hidden"></div>
<script>
    var totalInputLength = $('input').length;
    $('button').click(function(){
        var validInputs = $('input').filter((key,value) => v.value).length;
        if (validInputs == totalInputLength) {
            $('.showDiv').removeClass('hidden');
        } else {
            $('.showDiv').addClass('hidden');
        }
    });
</script>
</code>```

Body:
Lets say that you have two input fields, and a button and a hidden div.
Now you can do the following

<input type="text" name="username">
<input type="text" name="password">
<button type="submit">submit</button>
<div class="showDiv hidden"></div>
<script>
    var totalInputLength = $('input').length;
    $('button').click(function(){
        var validInputs = $('input').filter((key,value) => v.value).length;
        if (validInputs == totalInputLength) {
            $('.showDiv').removeClass('hidden');
        } else {
            $('.showDiv').addClass('hidden');
        }
    });
</script>


问:
How to search SQL database to prevent duplicated variables
I am trying to create a question and answer website, like quora or stackoverflow. How can I put in a custom method to search if the tagName already exists, so it can just select it, rather than create a duplicate. I already have an idea it should look something like this:

```<code>var objectExists = _context.Tag.Find(a => a.Name == tag);
if (objectExists == null)
{
   _context.QuestionTag.Add(new QuestionTag(){Tag = new Tag(){ Name = tag });
}
</code>```

But I can't seem to incoporate that logic into the parseTag method

```<code> public async Task BuildQuestion(string title, string body, string tags, ApplicationUser user)
            {
                var question = new Question
                {
                    Title = title,
                    Body = body,
                    QuestionTags = ParseTags(tags),
                    User = user
                };
                _context.Add(question);
                await _context.SaveChangesAsync();
            }

    public List<QuestionTag> ParseTags(string tags)
    {
        var tagList = tags.Split(new char[] {' '}, StringSplitOptions.RemoveEmptyEntries).ToList();
        var questionTags = new List<QuestionTag>();

        foreach(var tag in tagList)
        {
            questionTags.Add(new QuestionTag()
            {
                Tag = new Tag(){Name = tag}}
            );
        }
        return questionTags;
    }
</code>```

答:
How about only adding the non-existing tags to the database in ParseTags()?

```<code>public List<QuestionTag> ParseTags(string tags)
{
    var tagList = tags.Split(new char[] {' '}, StringSplitOptions.RemoveEmptyEntries).ToList();
    var questionTags = new List<QuestionTag>();
    var anyNewTags = false; //to see if we have to SaveChanges()

    foreach(var tag in tagList)
    {
        //You should do the check and add your tags here
        var objectExists = _context.Tag.Find(a => a.Name == tag);
        if (objectExists == null)
        {
           //tag doesn't exist
           //create a new tag, add it to db
           //also add it to the tag list

           var newTag = new QuestionTag() { Tag = new Tag() { Name = tag } };
           _context.QuestionTag.Add(newTag);
           questionTags.Add(newTag);

           //there is a new tag, we have to call SaveChanges()
           anyNewTags = true;
        }
        else
        {
           //tag exists, just grab it, no need to add anything.
           questionTags.Add(objectExists);
        }
    }

    //do we have new tags, do we need to call SaveChanges()?
    if (anyNewTags) _context.SaveChanges();

    return questionTags;
}
</code>```

Body:
I am trying to create a question and answer website, like quora or stackoverflow. How can I put in a custom method to search if the tagName already exists, so it can just select it, rather than create a duplicate. I already have an idea it should look something like this:

var objectExists = _context.Tag.Find(a => a.Name == tag);
if (objectExists == null)
{
   _context.QuestionTag.Add(new QuestionTag(){Tag = new Tag(){ Name = tag });
}

But I can't seem to incoporate that logic into the parseTag method

 public async Task BuildQuestion(string title, string body, string tags, ApplicationUser user)
            {
                var question = new Question
                {
                    Title = title,
                    Body = body,
                    QuestionTags = ParseTags(tags),
                    User = user
                };
                _context.Add(question);
                await _context.SaveChangesAsync();
            }

    public List<QuestionTag> ParseTags(string tags)
    {
        var tagList = tags.Split(new char[] {' '}, StringSplitOptions.RemoveEmptyEntries).ToList();
        var questionTags = new List<QuestionTag>();

        foreach(var tag in tagList)
        {
            questionTags.Add(new QuestionTag()
            {
                Tag = new Tag(){Name = tag}}
            );
        }
        return questionTags;
    }

Body:
How about only adding the non-existing tags to the database in ParseTags()?

public List<QuestionTag> ParseTags(string tags)
{
    var tagList = tags.Split(new char[] {' '}, StringSplitOptions.RemoveEmptyEntries).ToList();
    var questionTags = new List<QuestionTag>();
    var anyNewTags = false; //to see if we have to SaveChanges()

    foreach(var tag in tagList)
    {
        //You should do the check and add your tags here
        var objectExists = _context.Tag.Find(a => a.Name == tag);
        if (objectExists == null)
        {
           //tag doesn't exist
           //create a new tag, add it to db
           //also add it to the tag list

           var newTag = new QuestionTag() { Tag = new Tag() { Name = tag } };
           _context.QuestionTag.Add(newTag);
           questionTags.Add(newTag);

           //there is a new tag, we have to call SaveChanges()
           anyNewTags = true;
        }
        else
        {
           //tag exists, just grab it, no need to add anything.
           questionTags.Add(objectExists);
        }
    }

    //do we have new tags, do we need to call SaveChanges()?
    if (anyNewTags) _context.SaveChanges();

    return questionTags;
}


问:
Angular 5: How to get Current queryparams [Routing]
I am having trouble trying to get the queryparams into a component. For now, I just want to console.log(...) it.
I am using the ActivatedRoute from @angular/router for this task.

I am redeveloping a certain platform for work so unfortunately some irrelevant code will have be to substituted with "..."

My Component.ts code:

```<code>import { Component, OnInit, ViewEncapsulation } from '@angular/core';
import { RelevantReportService } from './../reportServices/relevantReports.service';
import { ActivatedRoute ,Params, Router } from '@angular/router';

@Component({
  selector: 'vr-reports',
  templateUrl: './reports.component.html',
  styleUrls: ['./reports.component.scss'],
  providers: [RelevantReportService],
  encapsulation: ViewEncapsulation.None
})
export class ReportsComponent implements OnInit {

  reportSections: any;
  constructor( private relevantReportService: RelevantReportService,
               private router: Router,
               private activatedRoute : ActivatedRoute

             ) { }

  ngOnInit() {
   ...

    console.log(this.activatedRoute.queryParams.value.reportName)
    // console.log(this.activatedRoute.queryParams._value.reportName)
  }
...

}
</code>```

When I do console.log(this.activatedRoute.queryParams.value.reportName), the console spits out the queryparams (which is exactly what I wanted) HOWEVER it also says

"Property 'value' does not exist on type 'Observable' "

so I believe this not the correct way of tackling it.

答:
It's observable in order to be able to monitor for changes in the params (by subscribing to observable). To get currently passed query params use:

```<code>this.activatedRoute.snapshot.queryParams
</code>```

You could also use ActivatedRouteSnapshot instead of ActivatedRoute

Body:
I am having trouble trying to get the queryparams into a component. For now, I just want to console.log(...) it.
I am using the ActivatedRoute from @angular/router for this task.

I am redeveloping a certain platform for work so unfortunately some irrelevant code will have be to substituted with "..."

My Component.ts code:

import { Component, OnInit, ViewEncapsulation } from '@angular/core';
import { RelevantReportService } from './../reportServices/relevantReports.service';
import { ActivatedRoute ,Params, Router } from '@angular/router';

@Component({
  selector: 'vr-reports',
  templateUrl: './reports.component.html',
  styleUrls: ['./reports.component.scss'],
  providers: [RelevantReportService],
  encapsulation: ViewEncapsulation.None
})
export class ReportsComponent implements OnInit {

  reportSections: any;
  constructor( private relevantReportService: RelevantReportService,
               private router: Router,
               private activatedRoute : ActivatedRoute

             ) { }

  ngOnInit() {
   ...

    console.log(this.activatedRoute.queryParams.value.reportName)
    // console.log(this.activatedRoute.queryParams._value.reportName)
  }
...

}

When I do console.log(this.activatedRoute.queryParams.value.reportName), the console spits out the queryparams (which is exactly what I wanted) HOWEVER it also says

"Property 'value' does not exist on type 'Observable' "

so I believe this not the correct way of tackling it.

Body:
It's observable in order to be able to monitor for changes in the params (by subscribing to observable). To get currently passed query params use:

this.activatedRoute.snapshot.queryParams

You could also use ActivatedRouteSnapshot instead of ActivatedRoute


问:
Firebase - Deploy Your Site - Deletes Cloud Functions

Question

How can I deploy my Firebase site without erasing Cloud Functions.

Maybe, include both site and cloud-functions in one deploy? What does that look like?

Maybe, deploy the site without erasing cloud-functions? I don't find a firebase deploy --only site or similar

Context

I have a Firebase project that uses Cloud Functions. The code is in two folders:

```<code>-site-code
-cloud_function-code
</code>```

When I want to deploy the project, I use firebase CLI tools, in two steps:

Step 1

from -site-code I run:

```<code>firebase deploy
</code>```

Step 2

then from cloud_functions-code I run:

```<code>firebase deploy --only functions
</code>```

Issue

When I run firebase deploy from -site-code, my Firebase Cloud Functions are deleted, so I must follow up with firebase deploy --only functions from -cloud_functions-code.

I did not find an --only directive for deploying just the site code from -site-code

答:
The Firebase CLI provides a way to deploy single functions as shown in its documentation:</p>

```<code>firebase deploy --only functions:name_of_function
</code>```

Body:
Question

How can I deploy my Firebase site without erasing Cloud Functions.

Maybe, include both site and cloud-functions in one deploy? What does that look like?

Maybe, deploy the site without erasing cloud-functions? I don't find a firebase deploy --only site or similar

Context

I have a Firebase project that uses Cloud Functions. The code is in two folders:

-site-code
-cloud_function-code

When I want to deploy the project, I use firebase CLI tools, in two steps:

Step 1

from -site-code I run:

firebase deploy

Step 2

then from cloud_functions-code I run:

firebase deploy --only functions

Issue

When I run firebase deploy from -site-code, my Firebase Cloud Functions are deleted, so I must follow up with firebase deploy --only functions from -cloud_functions-code.

I did not find an --only directive for deploying just the site code from -site-code

Body:
The Firebase CLI provides a way to deploy single functions as shown in its documentation:

firebase deploy --only functions:name_of_function


问:
TLS Configuration OpenSIPS
I'm trying to configure my OpenSIPS server to allow TLS encrypted communications.

At first, I'm trying with the build-in certificates that OpenSIPS provide.
What I've done until now is generating a new Residential Script (opensips_residential.cfg) in which ENABLE_TCP & ENABLE_TLS have been enabled.
Now I have two configuration files, opensips.cfg with the follow lines:

```<code>#
# $Id$
#
# OpenSIPS residential configuration script
#     by OpenSIPS Solutions <team@opensips-solutions.com>
#
# This script was generated via "make menuconfig", from
#   the "Residential" scenario.
# You can enable / disable more features / functionalities by
#   re-generating the scenario with different options.#
#
# Please refer to the Core CookBook at:
#      http://www.opensips.org/Resources/DocsCookbooks
# for a explanation of possible statements, functions and parameters.
#

####### Global Parameters #########

log_level=3
log_stderror=no
log_facility=LOG_LOCAL0

children=4

/* uncomment the following line to enable debugging */
#debug_mode=yes

/* uncomment the next line to enable the auto temporary blacklisting of
   not available destinations (default disabled) */
#disable_dns_blacklist=no

/* uncomment the next line to enable IPv6 lookup after IPv4 dns
   lookup failures (default disabled) */
#dns_try_ipv6=yes

/* comment the next line to enable the auto discovery of local aliases
   based on revers DNS on IPs */
auto_aliases=no

listen=udp:192.168.1.57:5060   # CUSTOMIZE ME

####### Modules Section ########

#set module path
mpath="/usr/local//lib64/opensips/modules/"

#### SIGNALING module
loadmodule "signaling.so"

#### StateLess module
loadmodule "sl.so"

#### Transaction Module
loadmodule "tm.so"
modparam("tm", "fr_timeout", 5)
modparam("tm", "fr_inv_timeout", 30)
modparam("tm", "restart_fr_on_each_reply", 0)
modparam("tm", "onreply_avp_mode", 1)

#### Record Route Module
loadmodule "rr.so"
/* do not append from tag to the RR (no need for this script) */
modparam("rr", "append_fromtag", 0)

#### MAX ForWarD module
loadmodule "maxfwd.so"

#### SIP MSG OPerationS module
loadmodule "sipmsgops.so"

#### FIFO Management Interface
loadmodule "mi_fifo.so"
modparam("mi_fifo", "fifo_name", "/tmp/opensips_fifo")
modparam("mi_fifo", "fifo_mode", 0666)

#### URI module
loadmodule "uri.so"
modparam("uri", "use_uri_table", 0)

#### USeR LOCation module
loadmodule "usrloc.so"
modparam("usrloc", "nat_bflag", "NAT")
modparam("usrloc", "db_mode",   0)

#### REGISTRAR module
loadmodule "registrar.so"

/* uncomment the next line not to allow more than 10 contacts per AOR */
#modparam("registrar", "max_contacts", 10)

#### ACCounting module
loadmodule "acc.so"
/* what special events should be accounted ? */
modparam("acc", "early_media", 0)
modparam("acc", "report_cancels", 0)
/* by default we do not adjust the direct of the sequential requests.
   if you enable this parameter, be sure the enable "append_fromtag"
   in "rr" module */
modparam("acc", "detect_direction", 0)

#### UDP protocol
loadmodule "proto_udp.so"

####### Routing Logic ########

# main request routing logic

route{
    if (!mf_process_maxfwd_header("10")) {
        sl_send_reply("483","Too Many Hops");
        exit;
    }

    if (has_totag()) {
        # sequential requests within a dialog should
        # take the path determined by record-routing
        if (loose_route()) {

            if (is_method("BYE")) {
                # do accunting, even if the transaction fails
                do_accounting("log","failed");
            } else if (is_method("INVITE")) {
                # even if in most of the cases is useless, do RR for
                # re-INVITEs alos, as some buggy clients do change route set
                # during the dialog.
                record_route();
            }

            # route it out to whatever destination was set by loose_route()
            # in $du (destination URI).
            route(relay);
        } else {

            if ( is_method("ACK") ) {
                if ( t_check_trans() ) {
                    # non loose-route, but stateful ACK; must be an ACK after
                    # a 487 or e.g. 404 from upstream server
                    t_relay();
                    exit;
                } else {
                    # ACK without matching transaction ->
                    # ignore and discard
                    exit;
                }
            }
            sl_send_reply("404","Not here");
        }
        exit;
    }

    # CANCEL processing
    if (is_method("CANCEL"))
    {
        if (t_check_trans())
            t_relay();
        exit;
    }

    t_check_trans();

    if ( !(is_method("REGISTER")  ) ) {
        if (from_uri==myself)
        {
        } else {
            # if caller is not local, then called number must be local
            if (!uri==myself) {
                send_reply("403","Rely forbidden");
                exit;
            }
        }
    }

    # preloaded route checking
    if (loose_route()) {
        xlog("L_ERR",
        "Attempt to route with preloaded Route's [$fu/$tu/$ru/$ci]");
        if (!is_method("ACK"))
            sl_send_reply("403","Preload Route denied");
        exit;
    }

    # record routing
    if (!is_method("REGISTER|MESSAGE"))
        record_route();

    # account only INVITEs
    if (is_method("INVITE")) {
        do_accounting("log");
    }

    if (!uri==myself) {
        append_hf("P-hint: outbound\r\n");
        route(relay);
    }

    # requests for my domain
    if (is_method("PUBLISH|SUBSCRIBE"))
    {
        sl_send_reply("503", "Service Unavailable");
        exit;
    }

    if (is_method("REGISTER"))
    {
        if (!save("location"))
            sl_reply_error();

        exit;
    }

    if ($rU==NULL) {
        # request with no Username in RURI
        sl_send_reply("484","Address Incomplete");
        exit;
    }

    # do lookup with method filtering
    if (!lookup("location","m")) {
        t_newtran();
        t_reply("404", "Not Found");
        exit;
    }

    # when routing via usrloc, log the missed calls also
    do_accounting("log","missed");
    route(relay);
}

route[relay] {
    # for INVITEs enable some additional helper routes
    if (is_method("INVITE")) {
        t_on_branch("per_branch_ops");
        t_on_reply("handle_nat");
        t_on_failure("missed_call");
    }

    if (!t_relay()) {
        send_reply("500","Internal Error");
    };
    exit;
}

branch_route[per_branch_ops] {
    xlog("new branch at $ru\n");
}

onreply_route[handle_nat] {

    xlog("incoming reply\n");
}

failure_route[missed_call] {
    if (t_was_cancelled()) {
        exit;
    }

    # uncomment the following lines if you want to block client
    # redirect based on 3xx replies.
    ##if (t_check_status("3[0-9][0-9]")) {
    ##t_reply("404","Not found");
    ##  exit;
    ##}

}
</code>```

And the other configuration file is the one that I generated with menuconfig tool:

```<code>#
# OpenSIPS residential configuration script
#     by OpenSIPS Solutions <team@opensips-solutions.com>
#
# This script was generated via "make menuconfig", from
#   the "Residential" scenario.
# You can enable / disable more features / functionalities by
#   re-generating the scenario with different options.#
#
# Please refer to the Core CookBook at:
#      http://www.opensips.org/Resources/DocsCookbooks
# for a explanation of possible statements, functions and parameters.
#

####### Global Parameters #########

log_level=3
log_stderror=no
log_facility=LOG_LOCAL0

children=4

/* uncomment the following lines to enable debugging */
#debug_mode=yes

/* uncomment the next line to enable the auto temporary blacklisting of
   not available destinations (default disabled) */
#disable_dns_blacklist=no

/* uncomment the next line to enable IPv6 lookup after IPv4 dns
   lookup failures (default disabled) */
#dns_try_ipv6=yes

/* comment the next line to enable the auto discovery of local aliases
   based on revers DNS on IPs */
auto_aliases=no

listen=udp:192.168.1.57:5060   # CUSTOMIZE ME

listen=tcp:192.168.1.57:5060   # CUSTOMIZE ME
listen=tls:192.168.1.57:5061   # CUSTOMIZE ME

####### Modules Section ########

#set module path
mpath="/usr/local/lib/opensips/modules/"

#### SIGNALING module
loadmodule "signaling.so"

#### StateLess module
loadmodule "sl.so"

#### Transaction Module
loadmodule "tm.so"
modparam("tm", "fr_timeout", 5)
modparam("tm", "fr_inv_timeout", 30)
modparam("tm", "restart_fr_on_each_reply", 0)
modparam("tm", "onreply_avp_mode", 1)

#### Record Route Module
loadmodule "rr.so"
/* do not append from tag to the RR (no need for this script) */
modparam("rr", "append_fromtag", 0)

#### MAX ForWarD module
loadmodule "maxfwd.so"

#### SIP MSG OPerationS module
loadmodule "sipmsgops.so"

#### FIFO Management Interface
loadmodule "mi_fifo.so"
modparam("mi_fifo", "fifo_name", "/tmp/opensips_fifo")
modparam("mi_fifo", "fifo_mode", 0666)

#### URI module
loadmodule "uri.so"
modparam("uri", "use_uri_table", 0)

#### USeR LOCation module
loadmodule "usrloc.so"
modparam("usrloc", "nat_bflag", "NAT")
modparam("usrloc", "db_mode",   0)

#### REGISTRAR module
loadmodule "registrar.so"
modparam("registrar", "tcp_persistent_flag", "TCP_PERSISTENT")

/* uncomment the next line not to allow more than 10 contacts per AOR */
#modparam("registrar", "max_contacts", 10)

#### ACCounting module
loadmodule "acc.so"
/* what special events should be accounted ? */
modparam("acc", "early_media", 0)
modparam("acc", "report_cancels", 0)
/* by default we do not adjust the direct of the sequential requests.
   if you enable this parameter, be sure the enable "append_fromtag"
   in "rr" module */
modparam("acc", "detect_direction", 0)

loadmodule "proto_udp.so"

loadmodule "proto_tcp.so"
loadmodule "proto_tls.so"
modparam("proto_tls","verify_cert", "1")
modparam("proto_tls","require_cert", "0")
modparam("proto_tls","tls_method", "TLSv1")
modparam("proto_tls","certificate", "/usr/local/etc/opensips/tls/user/user-cert.pem")
modparam("proto_tls","private_key", "/usr/local/etc/opensips/tls/user/user-privkey.pem")
modparam("proto_tls","ca_list", "/usr/local/etc/opensips/tls/user/user-calist.pem")

####### Routing Logic ########

# main request routing logic

route{

    if (!mf_process_maxfwd_header("10")) {
        sl_send_reply("483","Too Many Hops");
        exit;
    }

    if (has_totag()) {
        # sequential request withing a dialog should
        # take the path determined by record-routing
        if (loose_route()) {

            if (is_method("BYE")) {
                # do accounting even if the transaction fails
                do_accounting("log","failed");
            } else if (is_method("INVITE")) {
                # even if in most of the cases is useless, do RR for
                # re-INVITEs alos, as some buggy clients do change route set
                # during the dialog.
                record_route();
            }

            # route it out to whatever destination was set by loose_route()
            # in $du (destination URI).
            route(relay);
        } else {

            if ( is_method("ACK") ) {
                if ( t_check_trans() ) {
                    # non loose-route, but stateful ACK; must be an ACK after
                    # a 487 or e.g. 404 from upstream server
                    t_relay();
                    exit;
                } else {
                    # ACK without matching transaction ->
                    # ignore and discard
                    exit;
                }
            }
            sl_send_reply("404","Not here");
        }
        exit;
    }

    # CANCEL processing
    if (is_method("CANCEL"))
    {
        if (t_check_trans())
            t_relay();
        exit;
    }

    t_check_trans();

    if ( !(is_method("REGISTER")  ) ) {

        if (from_uri==myself)

        {

        } else {
            # if caller is not local, then called number must be local

            if (!uri==myself) {
                send_reply("403","Rely forbidden");
                exit;
            }
        }

    }

    # preloaded route checking
    if (loose_route()) {
        xlog("L_ERR",
        "Attempt to route with preloaded Route's [$fu/$tu/$ru/$ci]");
        if (!is_method("ACK"))
            sl_send_reply("403","Preload Route denied");
        exit;
    }

    # record routing
    if (!is_method("REGISTER|MESSAGE"))
        record_route();

    # account only INVITEs
    if (is_method("INVITE")) {

        do_accounting("log");
    }

    if (!uri==myself) {
        append_hf("P-hint: outbound\r\n");

        # if you have some interdomain connections via TLS
        ## CUSTOMIZE IF NEEDED
        ##if ($rd=="tls_domain1.net"
        ## || $rd=="tls_domain2.net"
        ##) {
        ##  force_send_socket(tls:127.0.0.1:5061); # CUSTOMIZE
        ##}

        route(relay);
    }

    # requests for my domain

    if (is_method("PUBLISH|SUBSCRIBE"))
    {
        sl_send_reply("503", "Service Unavailable");
        exit;
    }

    if (is_method("REGISTER"))
    {

        if ( proto==TCP || proto==TLS || 0 ) setflag(TCP_PERSISTENT);

        if (!save("location"))
            sl_reply_error();

        exit;
    }

    if ($rU==NULL) {
        # request with no Username in RURI
        sl_send_reply("484","Address Incomplete");
        exit;
    }

    # do lookup with method filtering
    if (!lookup("location","m")) {

        t_newtran();
        t_reply("404", "Not Found");
        exit;
    }

    # when routing via usrloc, log the missed calls also
    do_accounting("log","missed");
    route(relay);
}

route[relay] {
    # for INVITEs enable some additional helper routes
    if (is_method("INVITE")) {

        t_on_branch("per_branch_ops");
        t_on_reply("handle_nat");
        t_on_failure("missed_call");
    }

    if (!t_relay()) {
        send_reply("500","Internal Error");
    };
    exit;
}

branch_route[per_branch_ops] {
    xlog("new branch at $ru\n");
}

onreply_route[handle_nat] {

    xlog("incoming reply\n");
}

failure_route[missed_call] {
    if (t_was_cancelled()) {
        exit;
    }

    # uncomment the following lines if you want to block client
    # redirect based on 3xx replies.
    ##if (t_check_status("3[0-9][0-9]")) {
    ##t_reply("404","Not found");
    ##  exit;
    ##}

}
</code>```

I don't know if I have to replace my opensips.cfg file with opensips_residential.cfg. I have tried that and when I attempt to start my server with command 'opensipsctl start' I get several errors, I can provide them in another message if it's necessary.

答: Make sure you have your certs path setup properly, I also wouldn't use a self-signed cert. Go to letsencrypt get a cert and put the path on your opensips.cfg file. Replace your existing config with the new generated configuration.</p>

Title: TLS Configuration OpenSIPS

Body:
I'm trying to configure my OpenSIPS server to allow TLS encrypted communications.

At first, I'm trying with the build-in certificates that OpenSIPS provide.
What I've done until now is generating a new Residential Script (opensips_residential.cfg) in which ENABLE_TCP & ENABLE_TLS have been enabled.
Now I have two configuration files, opensips.cfg with the follow lines:

#
# $Id$
#
# OpenSIPS residential configuration script
#     by OpenSIPS Solutions <team@opensips-solutions.com>
#
# This script was generated via "make menuconfig", from
#   the "Residential" scenario.
# You can enable / disable more features / functionalities by
#   re-generating the scenario with different options.#
#
# Please refer to the Core CookBook at:
#      http://www.opensips.org/Resources/DocsCookbooks
# for a explanation of possible statements, functions and parameters.
#

####### Global Parameters #########

log_level=3
log_stderror=no
log_facility=LOG_LOCAL0

children=4

/* uncomment the following line to enable debugging */
#debug_mode=yes

/* uncomment the next line to enable the auto temporary blacklisting of
   not available destinations (default disabled) */
#disable_dns_blacklist=no

/* uncomment the next line to enable IPv6 lookup after IPv4 dns
   lookup failures (default disabled) */
#dns_try_ipv6=yes

/* comment the next line to enable the auto discovery of local aliases
   based on revers DNS on IPs */
auto_aliases=no

listen=udp:192.168.1.57:5060   # CUSTOMIZE ME

####### Modules Section ########

#set module path
mpath="/usr/local//lib64/opensips/modules/"

#### SIGNALING module
loadmodule "signaling.so"

#### StateLess module
loadmodule "sl.so"

#### Transaction Module
loadmodule "tm.so"
modparam("tm", "fr_timeout", 5)
modparam("tm", "fr_inv_timeout", 30)
modparam("tm", "restart_fr_on_each_reply", 0)
modparam("tm", "onreply_avp_mode", 1)

#### Record Route Module
loadmodule "rr.so"
/* do not append from tag to the RR (no need for this script) */
modparam("rr", "append_fromtag", 0)

#### MAX ForWarD module
loadmodule "maxfwd.so"

#### SIP MSG OPerationS module
loadmodule "sipmsgops.so"

#### FIFO Management Interface
loadmodule "mi_fifo.so"
modparam("mi_fifo", "fifo_name", "/tmp/opensips_fifo")
modparam("mi_fifo", "fifo_mode", 0666)

#### URI module
loadmodule "uri.so"
modparam("uri", "use_uri_table", 0)

#### USeR LOCation module
loadmodule "usrloc.so"
modparam("usrloc", "nat_bflag", "NAT")
modparam("usrloc", "db_mode",   0)

#### REGISTRAR module
loadmodule "registrar.so"

/* uncomment the next line not to allow more than 10 contacts per AOR */
#modparam("registrar", "max_contacts", 10)

#### ACCounting module
loadmodule "acc.so"
/* what special events should be accounted ? */
modparam("acc", "early_media", 0)
modparam("acc", "report_cancels", 0)
/* by default we do not adjust the direct of the sequential requests.
   if you enable this parameter, be sure the enable "append_fromtag"
   in "rr" module */
modparam("acc", "detect_direction", 0)

#### UDP protocol
loadmodule "proto_udp.so"

####### Routing Logic ########

# main request routing logic

route{
    if (!mf_process_maxfwd_header("10")) {
        sl_send_reply("483","Too Many Hops");
        exit;
    }

    if (has_totag()) {
        # sequential requests within a dialog should
        # take the path determined by record-routing
        if (loose_route()) {

            if (is_method("BYE")) {
                # do accunting, even if the transaction fails
                do_accounting("log","failed");
            } else if (is_method("INVITE")) {
                # even if in most of the cases is useless, do RR for
                # re-INVITEs alos, as some buggy clients do change route set
                # during the dialog.
                record_route();
            }

            # route it out to whatever destination was set by loose_route()
            # in $du (destination URI).
            route(relay);
        } else {

            if ( is_method("ACK") ) {
                if ( t_check_trans() ) {
                    # non loose-route, but stateful ACK; must be an ACK after
                    # a 487 or e.g. 404 from upstream server
                    t_relay();
                    exit;
                } else {
                    # ACK without matching transaction ->
                    # ignore and discard
                    exit;
                }
            }
            sl_send_reply("404","Not here");
        }
        exit;
    }

    # CANCEL processing
    if (is_method("CANCEL"))
    {
        if (t_check_trans())
            t_relay();
        exit;
    }

    t_check_trans();

    if ( !(is_method("REGISTER")  ) ) {
        if (from_uri==myself)
        {
        } else {
            # if caller is not local, then called number must be local
            if (!uri==myself) {
                send_reply("403","Rely forbidden");
                exit;
            }
        }
    }

    # preloaded route checking
    if (loose_route()) {
        xlog("L_ERR",
        "Attempt to route with preloaded Route's [$fu/$tu/$ru/$ci]");
        if (!is_method("ACK"))
            sl_send_reply("403","Preload Route denied");
        exit;
    }

    # record routing
    if (!is_method("REGISTER|MESSAGE"))
        record_route();

    # account only INVITEs
    if (is_method("INVITE")) {
        do_accounting("log");
    }

    if (!uri==myself) {
        append_hf("P-hint: outbound\r\n");
        route(relay);
    }

    # requests for my domain
    if (is_method("PUBLISH|SUBSCRIBE"))
    {
        sl_send_reply("503", "Service Unavailable");
        exit;
    }

    if (is_method("REGISTER"))
    {
        if (!save("location"))
            sl_reply_error();

        exit;
    }

    if ($rU==NULL) {
        # request with no Username in RURI
        sl_send_reply("484","Address Incomplete");
        exit;
    }

    # do lookup with method filtering
    if (!lookup("location","m")) {
        t_newtran();
        t_reply("404", "Not Found");
        exit;
    }

    # when routing via usrloc, log the missed calls also
    do_accounting("log","missed");
    route(relay);
}

route[relay] {
    # for INVITEs enable some additional helper routes
    if (is_method("INVITE")) {
        t_on_branch("per_branch_ops");
        t_on_reply("handle_nat");
        t_on_failure("missed_call");
    }

    if (!t_relay()) {
        send_reply("500","Internal Error");
    };
    exit;
}

branch_route[per_branch_ops] {
    xlog("new branch at $ru\n");
}

onreply_route[handle_nat] {

    xlog("incoming reply\n");
}

failure_route[missed_call] {
    if (t_was_cancelled()) {
        exit;
    }

    # uncomment the following lines if you want to block client
    # redirect based on 3xx replies.
    ##if (t_check_status("3[0-9][0-9]")) {
    ##t_reply("404","Not found");
    ##  exit;
    ##}

}

And the other configuration file is the one that I generated with menuconfig tool:

#
# OpenSIPS residential configuration script
#     by OpenSIPS Solutions <team@opensips-solutions.com>
#
# This script was generated via "make menuconfig", from
#   the "Residential" scenario.
# You can enable / disable more features / functionalities by
#   re-generating the scenario with different options.#
#
# Please refer to the Core CookBook at:
#      http://www.opensips.org/Resources/DocsCookbooks
# for a explanation of possible statements, functions and parameters.
#

####### Global Parameters #########

log_level=3
log_stderror=no
log_facility=LOG_LOCAL0

children=4

/* uncomment the following lines to enable debugging */
#debug_mode=yes

/* uncomment the next line to enable the auto temporary blacklisting of
   not available destinations (default disabled) */
#disable_dns_blacklist=no

/* uncomment the next line to enable IPv6 lookup after IPv4 dns
   lookup failures (default disabled) */
#dns_try_ipv6=yes

/* comment the next line to enable the auto discovery of local aliases
   based on revers DNS on IPs */
auto_aliases=no

listen=udp:192.168.1.57:5060   # CUSTOMIZE ME

listen=tcp:192.168.1.57:5060   # CUSTOMIZE ME
listen=tls:192.168.1.57:5061   # CUSTOMIZE ME

####### Modules Section ########

#set module path
mpath="/usr/local/lib/opensips/modules/"

#### SIGNALING module
loadmodule "signaling.so"

#### StateLess module
loadmodule "sl.so"

#### Transaction Module
loadmodule "tm.so"
modparam("tm", "fr_timeout", 5)
modparam("tm", "fr_inv_timeout", 30)
modparam("tm", "restart_fr_on_each_reply", 0)
modparam("tm", "onreply_avp_mode", 1)

#### Record Route Module
loadmodule "rr.so"
/* do not append from tag to the RR (no need for this script) */
modparam("rr", "append_fromtag", 0)

#### MAX ForWarD module
loadmodule "maxfwd.so"

#### SIP MSG OPerationS module
loadmodule "sipmsgops.so"

#### FIFO Management Interface
loadmodule "mi_fifo.so"
modparam("mi_fifo", "fifo_name", "/tmp/opensips_fifo")
modparam("mi_fifo", "fifo_mode", 0666)

#### URI module
loadmodule "uri.so"
modparam("uri", "use_uri_table", 0)

#### USeR LOCation module
loadmodule "usrloc.so"
modparam("usrloc", "nat_bflag", "NAT")
modparam("usrloc", "db_mode",   0)

#### REGISTRAR module
loadmodule "registrar.so"
modparam("registrar", "tcp_persistent_flag", "TCP_PERSISTENT")

/* uncomment the next line not to allow more than 10 contacts per AOR */
#modparam("registrar", "max_contacts", 10)

#### ACCounting module
loadmodule "acc.so"
/* what special events should be accounted ? */
modparam("acc", "early_media", 0)
modparam("acc", "report_cancels", 0)
/* by default we do not adjust the direct of the sequential requests.
   if you enable this parameter, be sure the enable "append_fromtag"
   in "rr" module */
modparam("acc", "detect_direction", 0)

loadmodule "proto_udp.so"

loadmodule "proto_tcp.so"
loadmodule "proto_tls.so"
modparam("proto_tls","verify_cert", "1")
modparam("proto_tls","require_cert", "0")
modparam("proto_tls","tls_method", "TLSv1")
modparam("proto_tls","certificate", "/usr/local/etc/opensips/tls/user/user-cert.pem")
modparam("proto_tls","private_key", "/usr/local/etc/opensips/tls/user/user-privkey.pem")
modparam("proto_tls","ca_list", "/usr/local/etc/opensips/tls/user/user-calist.pem")

####### Routing Logic ########

# main request routing logic

route{

    if (!mf_process_maxfwd_header("10")) {
        sl_send_reply("483","Too Many Hops");
        exit;
    }

    if (has_totag()) {
        # sequential request withing a dialog should
        # take the path determined by record-routing
        if (loose_route()) {

            if (is_method("BYE")) {
                # do accounting even if the transaction fails
                do_accounting("log","failed");
            } else if (is_method("INVITE")) {
                # even if in most of the cases is useless, do RR for
                # re-INVITEs alos, as some buggy clients do change route set
                # during the dialog.
                record_route();
            }

            # route it out to whatever destination was set by loose_route()
            # in $du (destination URI).
            route(relay);
        } else {

            if ( is_method("ACK") ) {
                if ( t_check_trans() ) {
                    # non loose-route, but stateful ACK; must be an ACK after
                    # a 487 or e.g. 404 from upstream server
                    t_relay();
                    exit;
                } else {
                    # ACK without matching transaction ->
                    # ignore and discard
                    exit;
                }
            }
            sl_send_reply("404","Not here");
        }
        exit;
    }

    # CANCEL processing
    if (is_method("CANCEL"))
    {
        if (t_check_trans())
            t_relay();
        exit;
    }

    t_check_trans();

    if ( !(is_method("REGISTER")  ) ) {

        if (from_uri==myself)

        {

        } else {
            # if caller is not local, then called number must be local

            if (!uri==myself) {
                send_reply("403","Rely forbidden");
                exit;
            }
        }

    }

    # preloaded route checking
    if (loose_route()) {
        xlog("L_ERR",
        "Attempt to route with preloaded Route's [$fu/$tu/$ru/$ci]");
        if (!is_method("ACK"))
            sl_send_reply("403","Preload Route denied");
        exit;
    }

    # record routing
    if (!is_method("REGISTER|MESSAGE"))
        record_route();

    # account only INVITEs
    if (is_method("INVITE")) {

        do_accounting("log");
    }

    if (!uri==myself) {
        append_hf("P-hint: outbound\r\n");

        # if you have some interdomain connections via TLS
        ## CUSTOMIZE IF NEEDED
        ##if ($rd=="tls_domain1.net"
        ## || $rd=="tls_domain2.net"
        ##) {
        ##  force_send_socket(tls:127.0.0.1:5061); # CUSTOMIZE
        ##}

        route(relay);
    }

    # requests for my domain

    if (is_method("PUBLISH|SUBSCRIBE"))
    {
        sl_send_reply("503", "Service Unavailable");
        exit;
    }

    if (is_method("REGISTER"))
    {

        if ( proto==TCP || proto==TLS || 0 ) setflag(TCP_PERSISTENT);

        if (!save("location"))
            sl_reply_error();

        exit;
    }

    if ($rU==NULL) {
        # request with no Username in RURI
        sl_send_reply("484","Address Incomplete");
        exit;
    }

    # do lookup with method filtering
    if (!lookup("location","m")) {

        t_newtran();
        t_reply("404", "Not Found");
        exit;
    }

    # when routing via usrloc, log the missed calls also
    do_accounting("log","missed");
    route(relay);
}

route[relay] {
    # for INVITEs enable some additional helper routes
    if (is_method("INVITE")) {

        t_on_branch("per_branch_ops");
        t_on_reply("handle_nat");
        t_on_failure("missed_call");
    }

    if (!t_relay()) {
        send_reply("500","Internal Error");
    };
    exit;
}

branch_route[per_branch_ops] {
    xlog("new branch at $ru\n");
}

onreply_route[handle_nat] {

    xlog("incoming reply\n");
}

failure_route[missed_call] {
    if (t_was_cancelled()) {
        exit;
    }

    # uncomment the following lines if you want to block client
    # redirect based on 3xx replies.
    ##if (t_check_status("3[0-9][0-9]")) {
    ##t_reply("404","Not found");
    ##  exit;
    ##}

}

I don't know if I have to replace my opensips.cfg file with opensips_residential.cfg. I have tried that and when I attempt to start my server with command 'opensipsctl start' I get several errors, I can provide them in another message if it's necessary.