问:
Is it possible to obtain batch size in keras layer
I'm design a specific keras layer using lambda function,how can I get the dynamic batch_size in the function?

I tried many times to solve this problem,but all failed.

def minus(inputs):
    x,y = inputs
    batch_size=K.shape(x)[0]
    e = K.get_variable_shape(x)
    for k in range(e[0]):
        for i in range(e[1]):
            for j in range(e[2]):
                if x[k][i][j]==0:
                   K.update(x[k][i][j], y[k][i][j])
    return x

def mymodel():
    inpA = keras.layers.Input(shape=(10,8),name='InputLayerA')
    inpB = keras.layers.Input(shape=(10,8),name='InputLayerB')
    print(inpA.shape)
    middle = keras.layers.Lambda(minus,name='minus')([inpA,inpB])

    ae = keras.Model([inpA,inpB],middle)
    ae.summary()
    return ae
```

When I new a model,like ae = mymodel() .I except a new x tensor,but the actual is error message:'NoneType' object cannot be interpreted as an integer.

答:
When using tensorflow I am using tf.shape(x) to get the batch-size for model layers, so I think you are right that K.shape(x) (keras equivalent?) can be used.

If i understand what you try to do correct, wouldn't this be sufficient? With the bonus of avoiding slow python for-loops.

import keras
import keras.backend as K

def minus(inputs):
    x,y = inputs
    change_index = K.cast(K.equal(x, 0),'float32')
    return x*(1-change_index)+y*change_index

def mymodel():
    inpA = keras.layers.Input(shape=(10,8),name='InputLayerA')
    inpB = keras.layers.Input(shape=(10,8),name='InputLayerB')
    print(inpA.shape)
    middle = keras.layers.Lambda(minus,name='minus')([inpA,inpB])

    ae = keras.Model([inpA,inpB],middle)
    ae.summary()
    return ae

ae = mymodel()
```

Body:
I'm design a specific keras layer using lambda function,how can I get the dynamic batch_size in the function?

I tried many times to solve this problem,but all failed.

def minus(inputs):
    x,y = inputs
    batch_size=K.shape(x)[0]
    e = K.get_variable_shape(x)
    for k in range(e[0]):
        for i in range(e[1]):
            for j in range(e[2]):
                if x[k][i][j]==0:
                   K.update(x[k][i][j], y[k][i][j])
    return x

def mymodel():
    inpA = keras.layers.Input(shape=(10,8),name='InputLayerA')
    inpB = keras.layers.Input(shape=(10,8),name='InputLayerB')
    print(inpA.shape)
    middle = keras.layers.Lambda(minus,name='minus')([inpA,inpB])

    ae = keras.Model([inpA,inpB],middle)
    ae.summary()
    return ae

When I new a model,like ae = mymodel() .I except a new x tensor,but the actual is error message:'NoneType' object cannot be interpreted as an integer.


来源: stackexchange

问:
Mixing for each and lambdas in c++
I wanted to play a little bit with  lambdas and for each(Range-based for-loop, not STL for_each) in C++0x. So i went to wiki and tried to rewrite examples from wiki using lambdas:

```<code>    std::vector<int> some_list;
some_list.push_back(42);
some_list.push_back(37);
int total = 0;
int value = 5;
for(int& x:some_list)
{
    [](int x)
    {
        cout << "xL=" <<x <<endl;
    };
}

for(auto x:some_list)
    cout<< "x="<<x<<endl;

    return result;
}
</code>```

Problem is that I don't see any cout in the lambda version, for each version prints x nicely... I presume that it is impossible to mix for each and lambdas because lambdas can only be in the place of the "functions", and cannot act as loop body, but I'm not sure, so if somebody can confirm it would be cool

compiler: GCC 4.6

答:
You're using a regular for loop it doesn't expect a lambda. The curly braces are just a code block so what you're doing is defining the lambda for each iteration but not invoking it.

What you want to do is use std::for_each.

ContentLicense: CC BY-SA 3.0

Title: Mixing for each and lambdas in c++

Body:
I wanted to play a little bit with  lambdas and for each(Range-based for-loop, not STL for_each) in C++0x. So i went to wiki and tried to rewrite examples from wiki using lambdas:

    std::vector<int> some_list;
some_list.push_back(42);
some_list.push_back(37);
int total = 0;
int value = 5;
for(int& x:some_list)
{
    [](int x)
    {
        cout << "xL=" <<x <<endl;
    };
}

for(auto x:some_list)
    cout<< "x="<<x<<endl;

    return result;
}

Problem is that I don't see any cout in the lambda version, for each version prints x nicely... I presume that it is impossible to mix for each and lambdas because lambdas can only be in the place of the "functions", and cannot act as loop body, but I'm not sure, so if somebody can confirm it would be cool

compiler: GCC 4.6


问:
Google cloud functions with bazel built protobuf dependencies
If I use bazel to build my protobuf dependent Go serverless functions, bazel will make the protobuf generated go code available at the import path that I specify.

Google cloud functions for go requires one to use go modules.

How can I add the dummy import path created by bazel to my go.mod file?  The function deploy to google cloud fails because the dummy import can not be resolved. (G cloud requires me to upload my go source, AWS lambdas would allow me to upload a binary, which would work fine.)

I'm guessing I'll have to either go with AWS lambdas, use serverless containers,  or write a genrule that copies the outputs of the proto generated code into my source directory but I'd like to avoid that ugliness.

答:
I work at Google on Go and Google Cloud Functions.

I see a few options for using Cloud Functions:

Publish the generated code publicly. You may not want to do this for a variety of reasons.

Copy the generated code into your source directory. This is the easiest. When you deploy your function, the current directory gets zipped up and sent to be built. We don't copy any dependencies from outside your current directory. If you do this, you can import the generated code by having the package path be prefixed by the module path of your directory.

Use vendoring. If you run go mod vendor and have that grab your generated code (at whatever path you choose), it will create a vendor directory with all of your dependencies. The Cloud Functions builder prefers go.mod over vendor, though. So you would have to .gcloudignore the go.mod and go.sum file to make sure they don't get uploaded when you deploy your code. https://cloud.google.com/functions/docs/writing/specifying-dependencies-go has more information.

ContentLicense: CC BY-SA 4.0


问:
How to detect numbering in simple vba string replacement
I'm trying to replace numbering (Word's 1. , 2. , etc.). In a simple string and replace search but I can't seem to find the numbers.

This is for Word 365, and I'm using the VB editor in there.

```<code>Sub ayaya()
Documents.Open FileName:=ActiveDocument.Path + "\Doc1.docm"
Selection.Find.ClearFormatting
Selection.Find.Replacement.ClearFormatting
With Selection.Find
    .Text = "SSS"
    .Replacement.Text = "PPP"
    .Forward = True
    .Wrap = wdFindContinue
    .Format = False
    .MatchCase = False
    .MatchWholeWord = False
    .MatchWildcards = False
    .MatchSoundsLike = False
    .MatchAllWordForms = False
End With
With Selection
    If .Find.Forward = True Then
        .Collapse Direction:=wdCollapseStart
    Else
        .Collapse Direction:=wdCollapseEnd
    End If
    .Find.Execute Replace:=wdReplaceAll
End With

End Sub

</code>```

My word document looked like this:

```<code>SSS
SSS
1.  SSS
</code>```

and turned to

```<code>PPP
PPP
1.  PPP
</code>```

but when I replace the search to any variation of

```<code>With Selection.Find
    .Text = "1. SSS"
</code>```

It does not find the text.

答: Numbering is a ListParagraphs Object and can't be searched as if it's plain text.</p>

Body:
I'm trying to replace numbering (Word's 1. , 2. , etc.). In a simple string and replace search but I can't seem to find the numbers.

This is for Word 365, and I'm using the VB editor in there.

Sub ayaya()
Documents.Open FileName:=ActiveDocument.Path + "\Doc1.docm"
Selection.Find.ClearFormatting
Selection.Find.Replacement.ClearFormatting
With Selection.Find
    .Text = "SSS"
    .Replacement.Text = "PPP"
    .Forward = True
    .Wrap = wdFindContinue
    .Format = False
    .MatchCase = False
    .MatchWholeWord = False
    .MatchWildcards = False
    .MatchSoundsLike = False
    .MatchAllWordForms = False
End With
With Selection
    If .Find.Forward = True Then
        .Collapse Direction:=wdCollapseStart
    Else
        .Collapse Direction:=wdCollapseEnd
    End If
    .Find.Execute Replace:=wdReplaceAll
End With

End Sub

My word document looked like this:

SSS
SSS
1.  SSS

and turned to

PPP
PPP
1.  PPP

but when I replace the search to any variation of

With Selection.Find
    .Text = "1. SSS"

It does not find the text.


问:
Overriding OMP_NUM_THREADS from code - for real
All the answers I was able to find so far suggest calling omp_set_num_threads. While it's a proper answer for most cases, it doesn't work for me. Internally, calling omp_set_num_threads causes a creation of per-thread ICV  (or modification, if current thread already has one), and the number of threads is stored there. This means that if there is a different thread, that starts a parallel region, it won't see our new value. So calling omp_set_num_threads != setting OMP_NUM_THREADS env variable.

Is there a way to change global ICV?

Side note - why would I want to to this: I'm working with a library spawns a worker thread for me, so I don't really control it's life-cycle.

Simplest example to reproduce:

export OMP_NUM_THREADS=3

```<code>#include <omp.h>
#include <iostream>
#include <thread>

void job() {
  #pragma omp parallel
  {
    if (omp_get_thread_num() == 0) {
      std::cout << "Num threads:" << omp_get_num_threads() << std::endl;
    }
  };
}

int main () {
  omp_set_num_threads(2);
  #pragma omp parallel
  {
    if (omp_get_thread_num() == 0) {
      std::cout << "Num threads:" << omp_get_num_threads() << std::endl;
    }
  };
  std::thread t(job);
  t.join();
}
</code>```

This produces

```<code>Num threads:2
Num threads:3
</code>```

答:
Overriding OMP_NUM_THREADS from code...

Change this:

```<code>int main () {
  omp_set_num_threads(2);
  #pragma omp parallel
  {
    if (omp_get_thread_num() == 0) {
      std::cout << "Num threads:" << omp_get_num_threads() << std::endl;
    }
  };
  std::thread t(job);
  t.join();
}
</code>```

to this:

```<code>int main () {
  #pragma omp parallel num_threads(2)
  {
    if (omp_get_thread_num() == 0) {
      std::cout << "Num threads:" << omp_get_num_threads() << std::endl;
    }
  };
  std::thread t(job);
  t.join();
}
</code>```

I believe that works with Microsoft compilers, which are stuck somewhere around 2003 for OpenMP. The 2003 release of OpenMP is roughly version 2.0 or 2.1, if I recall correctly.

Also see Difference between num_threads vs. omp_set_num_threads vs OMP_NUM_THREADS.

Body:
All the answers I was able to find so far suggest calling omp_set_num_threads. While it's a proper answer for most cases, it doesn't work for me. Internally, calling omp_set_num_threads causes a creation of per-thread ICV  (or modification, if current thread already has one), and the number of threads is stored there. This means that if there is a different thread, that starts a parallel region, it won't see our new value. So calling omp_set_num_threads != setting OMP_NUM_THREADS env variable.

Is there a way to change global ICV?

Side note - why would I want to to this: I'm working with a library spawns a worker thread for me, so I don't really control it's life-cycle.

Simplest example to reproduce:

export OMP_NUM_THREADS=3

#include <omp.h>
#include <iostream>
#include <thread>

void job() {
  #pragma omp parallel
  {
    if (omp_get_thread_num() == 0) {
      std::cout << "Num threads:" << omp_get_num_threads() << std::endl;
    }
  };
}

int main () {
  omp_set_num_threads(2);
  #pragma omp parallel
  {
    if (omp_get_thread_num() == 0) {
      std::cout << "Num threads:" << omp_get_num_threads() << std::endl;
    }
  };
  std::thread t(job);
  t.join();
}

This produces

Num threads:2
Num threads:3

Body:
Overriding OMP_NUM_THREADS from code...

Change this:

int main () {
  omp_set_num_threads(2);
  #pragma omp parallel
  {
    if (omp_get_thread_num() == 0) {
      std::cout << "Num threads:" << omp_get_num_threads() << std::endl;
    }
  };
  std::thread t(job);
  t.join();
}

to this:

int main () {
  #pragma omp parallel num_threads(2)
  {
    if (omp_get_thread_num() == 0) {
      std::cout << "Num threads:" << omp_get_num_threads() << std::endl;
    }
  };
  std::thread t(job);
  t.join();
}

I believe that works with Microsoft compilers, which are stuck somewhere around 2003 for OpenMP. The 2003 release of OpenMP is roughly version 2.0 or 2.1, if I recall correctly.

Also see Difference between num_threads vs. omp_set_num_threads vs OMP_NUM_THREADS.


问:
Separate frontend and backend users with sfDoctrineGuardPlugin
i'm starting a project adn i'm using symfony, my first time with symfony, really great actually, i already install the sfDoctrineGuardPlugin and everything is ok untill now, why?, because frontend users can login in the backend and vice versa, i dont't want that, so, i start to google, i found Symfony sfDoctrineGuardPlugin custom login query here in SO, but i don't know where i should place the function so, i haven't tested it.

As i don't want frontend users can login in the backend, i think i can use credentials, can i?? but, symfony check for users credentials after they are logged, and i don't want tha neither, so, how can i achieve this?, maybe if i could have namespaces in the session, i can check if an admin in the backend namespace and also for frontend users, so they never get fixed, i think.

I don't know really know if sfDoctrineGuardPlugin have some configuration that can manage this situation, exist such a config??

Also, in my backend, i will like to have a page to manage the frontend users, and other for backend users, because frontend users will have a profile and addresses, think this is much easier, but i don't know where to start.

need some help over here

thanks

答:
After a few days coding, i was able to do it exactly as i wanted, i'm going to share my solution:

I started with an example i found here in SO, you can read the post here:

Symfony sfDoctrineGuardPlugin custom login query
it gave me an idea and i executed it, so, i create \lib\Util.class.php, with to functions, one for query backend users and another for frontend users

```<code>static public function retrieveCustomer($username, $isActive = true)
{
    $query = Doctrine_Core::getTable('sfGuardUser')->createQuery('u')
    ->leftJoin('u.Groups g')
    ->leftJoin('g.Permissions p')
    ->where('u.username = ?', $username)
    ->addWhere('u.is_active = ?', $isActive)
    ->addWhere('g.name = ?', 'customers');

    return $query->fetchOne();
}

static public function retrieveAdmin($username, $isActive = true)
{
    $query = Doctrine_Core::getTable('sfGuardUser')->createQuery('u')
    ->leftJoin('u.Groups g')
    ->leftJoin('g.Permissions p')
    ->where('u.username = ?', $username)
    ->addWhere('u.is_active = ?', $isActive)
    ->whereIn('g.name', array('administrators','operators'));

    return $query->fetchOne();
}
</code>```

Now, in the app.yml of each app, i override the default query of the plugin

```<code>#Example for apps/backend/config/app.yml
all:
    sf_guard_plugin:
        retrieve_by_username_callable: Util::retrieveAdmin
</code>```

untill now all was good, but i started to face another problem, so i open a new thread:
Overwriting isAuthenticated() in symfony and there i got the final step for my solution, that was setting differents session name for each app, so, in the factories.yml of each app:

```<code>#apps\backend\config\factories.yml
storage:
  class: sfSessionStorage
  param:
    session_name: backend
</code>```

and now all is set, frontend users can not log in in backend app and vice versa.

feel free to comment

ContentLicense: CC BY-SA 2.5

Body:
After a few days coding, i was able to do it exactly as i wanted, i'm going to share my solution:

I started with an example i found here in SO, you can read the post here:

Symfony sfDoctrineGuardPlugin custom login query
it gave me an idea and i executed it, so, i create \lib\Util.class.php, with to functions, one for query backend users and another for frontend users

static public function retrieveCustomer($username, $isActive = true)
{
    $query = Doctrine_Core::getTable('sfGuardUser')->createQuery('u')
    ->leftJoin('u.Groups g')
    ->leftJoin('g.Permissions p')
    ->where('u.username = ?', $username)
    ->addWhere('u.is_active = ?', $isActive)
    ->addWhere('g.name = ?', 'customers');

    return $query->fetchOne();
}

static public function retrieveAdmin($username, $isActive = true)
{
    $query = Doctrine_Core::getTable('sfGuardUser')->createQuery('u')
    ->leftJoin('u.Groups g')
    ->leftJoin('g.Permissions p')
    ->where('u.username = ?', $username)
    ->addWhere('u.is_active = ?', $isActive)
    ->whereIn('g.name', array('administrators','operators'));

    return $query->fetchOne();
}

Now, in the app.yml of each app, i override the default query of the plugin

#Example for apps/backend/config/app.yml
all:
    sf_guard_plugin:
        retrieve_by_username_callable: Util::retrieveAdmin

untill now all was good, but i started to face another problem, so i open a new thread:
Overwriting isAuthenticated() in symfony and there i got the final step for my solution, that was setting differents session name for each app, so, in the factories.yml of each app:

#apps\backend\config\factories.yml
storage:
  class: sfSessionStorage
  param:
    session_name: backend

and now all is set, frontend users can not log in in backend app and vice versa.

feel free to comment


问:
Facebook login with Python Requests and BeautifulSoup
I'm trying to login to Facebook using the Python Requests- and BeautifulSoup modules (just as an exercise), and I'm having some problems with finding the POST parameters to send to the server.

The first thing I did was that I identified the POST parameters I would need to send by manually login into Facebook in a browser:

Then I wrote some code to get the Facebook front page and extract values from the login form fields:

```<code>import requests
from bs4 import BeautifulSoup

r = requests.get('https://www.facebook.com/', headers={'user-agent':'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:40.0) Gecko/20100101 Firefox/40.1'})
r.encoding = 'utf-8'
bs = BeautifulSoup(r.text, 'html.parser')

login_params = {
    'email': 'myemail@something.com',
    'pass': 'mypassword',
    'default_persistent': bs.select('input[name=default_persistent]')[0].get('value'),
    #'lgndim': bs.select('input[name=lgndim]')[0].get('value'),  #Empty value attribute.
    #'lgnjs': bs.select('input[name=lgnjs]')[0].get('value'),  #This one has value="n" for some reason.
    'lgnrnd': bs.select('input[name=lgnrnd]')[0].get('value'),
    'locale': bs.select('input[name=locale]')[0].get('value'),
    'lsd': bs.select('input[name=lsd]')[0].get('value'),
    #'qsstamp': bs.select('input[name=qsstamp]')[0].get('value'),  #This one isn't found at all.
    #'timezone': bs.select('#u_0_w')[0].get('value'),  #Empty value attribute.
}
</code>```

The parameters that are commented out are the ones I'm having trouble with. I can retrieve those input elements (except one), but the problem is that their value attributes are empty or wrong. Let's take the parameter "lgndim" as an example. When I select it with BeautifulSoup in my script I get this:

```<code>input autocomplete="off" id="u_0_y" name="lgndim" type="hidden" value=""
</code>```

But when I write the request text into a html file likes this:

```<code>with open('hello.htm', 'w', encoding='utf8') as f:
    f.write(r.text)
</code>```

and view the input element in my browser it looks like this:

```<code>input autocomplete="off" name="lgndim" value="eyJ3IjoyNTYwLCJoIjoxNDQwLCJhdyI6MjU2MCwiYWgiOjE0MDAsImMiOjI0fQ==" id="u_0_y" type="hidden"
</code>```

Anyone know what's wrong here? I'm completely stuck, any help would be greatly appreciated. I hope I gave enough information.

答:
```<code>#IMPORTS
import requests
import time
from bs4 import BeautifulSoup

#CONSTRAINTS
EMAIL = your_email
PASSW = your_password
LOGIN_URL = "https://www.facebook.com/login.php?refsrc=https%3A%2F%2Fm.facebook.com%2F&refid=8"
FACEBOOK_URL = "http://www.facebook.com"

#VARS
s = None

#MAIN CLASS
class facebook():
    def __init__(self):
        self.s = requests.session()
        self.login()
        self.find_accounts_by_name()

    def login(self):
        #GET DEFAULT VALUES FROM PAGE
        r = self.s.get(FACEBOOK_URL, verify=False)
        print r.text
        soup = BeautifulSoup(r.text)
        #GET DEFAULT VALUES
        tmp = soup.find(attrs={"name": "lsd"})
        lsd = tmp["value"]

        data = {
            'lsd': lsd
        }
        data['email'] = EMAIL
        data['pass'] = PASSW
        data['login'] = 'Log In'

        r = self.s.post(LOGIN_URL , data=data, verify=False)
        print r.text
</code>```

Body:
I'm trying to login to Facebook using the Python Requests- and BeautifulSoup modules (just as an exercise), and I'm having some problems with finding the POST parameters to send to the server.

The first thing I did was that I identified the POST parameters I would need to send by manually login into Facebook in a browser:

Then I wrote some code to get the Facebook front page and extract values from the login form fields:

import requests
from bs4 import BeautifulSoup

r = requests.get('https://www.facebook.com/', headers={'user-agent':'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:40.0) Gecko/20100101 Firefox/40.1'})
r.encoding = 'utf-8'
bs = BeautifulSoup(r.text, 'html.parser')

login_params = {
    'email': 'myemail@something.com',
    'pass': 'mypassword',
    'default_persistent': bs.select('input[name=default_persistent]')[0].get('value'),
    #'lgndim': bs.select('input[name=lgndim]')[0].get('value'),  #Empty value attribute.
    #'lgnjs': bs.select('input[name=lgnjs]')[0].get('value'),  #This one has value="n" for some reason.
    'lgnrnd': bs.select('input[name=lgnrnd]')[0].get('value'),
    'locale': bs.select('input[name=locale]')[0].get('value'),
    'lsd': bs.select('input[name=lsd]')[0].get('value'),
    #'qsstamp': bs.select('input[name=qsstamp]')[0].get('value'),  #This one isn't found at all.
    #'timezone': bs.select('#u_0_w')[0].get('value'),  #Empty value attribute.
}

The parameters that are commented out are the ones I'm having trouble with. I can retrieve those input elements (except one), but the problem is that their value attributes are empty or wrong. Let's take the parameter "lgndim" as an example. When I select it with BeautifulSoup in my script I get this:

input autocomplete="off" id="u_0_y" name="lgndim" type="hidden" value=""

But when I write the request text into a html file likes this:

with open('hello.htm', 'w', encoding='utf8') as f:
    f.write(r.text)

and view the input element in my browser it looks like this:

input autocomplete="off" name="lgndim" value="eyJ3IjoyNTYwLCJoIjoxNDQwLCJhdyI6MjU2MCwiYWgiOjE0MDAsImMiOjI0fQ==" id="u_0_y" type="hidden"

Anyone know what's wrong here? I'm completely stuck, any help would be greatly appreciated. I hope I gave enough information.

Body:
#IMPORTS
import requests
import time
from bs4 import BeautifulSoup

#CONSTRAINTS
EMAIL = your_email
PASSW = your_password
LOGIN_URL = "https://www.facebook.com/login.php?refsrc=https%3A%2F%2Fm.facebook.com%2F&amp;refid=8"
FACEBOOK_URL = "http://www.facebook.com"

#VARS
s = None

#MAIN CLASS
class facebook():
    def __init__(self):
        self.s = requests.session()
        self.login()
        self.find_accounts_by_name()

    def login(self):
        #GET DEFAULT VALUES FROM PAGE
        r = self.s.get(FACEBOOK_URL, verify=False)
        print r.text
        soup = BeautifulSoup(r.text)
        #GET DEFAULT VALUES
        tmp = soup.find(attrs={"name": "lsd"})
        lsd = tmp["value"]

        data = {
            'lsd': lsd
        }
        data['email'] = EMAIL
        data['pass'] = PASSW
        data['login'] = 'Log In'

        r = self.s.post(LOGIN_URL , data=data, verify=False)
        print r.text


问:
Create shiny dashboard sidebar menu from dataframe
I am trying to create menu items under the dashboard Sidebar automatically from a table without success. I am using the code below.

```<code>library(shiny)
library(shinydashboard)

header = dashboardHeader(title = "title")
sidebar = dashboardSidebar(sidebarMenuOutput("sidebarMenu"))
body = dashboardBody()

ui = dashboardPage(header, sidebar, body)

labels = data.frame(id = c(1,2,3),
                    name = c("lab1", "lab2", "lab3"))

server = function(input, output) {

  output$sidebarMenu <- renderMenu({
    sidebarMenu(id="tabs",
                for (i in labels) {
                  menuItem(labels$name[i], tabName = labels$id[i])
                  })

  })
}

shinyApp(ui, server)
</code>```

data.frame labels contains the labels and id I need to use in the menu. I am running a for loop. How should I do it?

答:
```<code>for (i in labels)
</code>```

This loop does not work since you will always get the dataframe, not not a row of the dataframe. Anyhow, I did not get it to work with the loop, i normally use a combination of lapply to store all items in a list and use do.call to visualize it with the renderUI function.

```<code>library(shiny)
library(shinydashboard)

labels = data.frame(id = c(1,2,3),
                    name = c("lab1", "lab2", "lab3"))

header = dashboardHeader(title = "title")
sidebar = dashboardSidebar(sidebarMenu(id="mytabs",
                                    uiOutput("sidebar_menu_UI")))
body = dashboardBody()

ui = dashboardPage(header, sidebar, body)

server = function(input, output) {

    output$sidebar_menu_UI <- renderUI({

        myTabs = lapply(1:nrow(labels) , function(i) {

            menuItem(labels$name[i], tabName = labels$id[i])
        })

        print(myTabs)

        do.call(sidebarMenu, myTabs)
    })
}

shinyApp(ui, server)
</code>```

Body:
I am trying to create menu items under the dashboard Sidebar automatically from a table without success. I am using the code below.

library(shiny)
library(shinydashboard)

header = dashboardHeader(title = "title")
sidebar = dashboardSidebar(sidebarMenuOutput("sidebarMenu"))
body = dashboardBody()

ui = dashboardPage(header, sidebar, body)

labels = data.frame(id = c(1,2,3),
                    name = c("lab1", "lab2", "lab3"))

server = function(input, output) {

  output$sidebarMenu <- renderMenu({
    sidebarMenu(id="tabs",
                for (i in labels) {
                  menuItem(labels$name[i], tabName = labels$id[i])
                  })

  })
}

shinyApp(ui, server)

data.frame labels contains the labels and id I need to use in the menu. I am running a for loop. How should I do it?

Body:
for (i in labels)

This loop does not work since you will always get the dataframe, not not a row of the dataframe. Anyhow, I did not get it to work with the loop, i normally use a combination of lapply to store all items in a list and use do.call to visualize it with the renderUI function.

library(shiny)
library(shinydashboard)

labels = data.frame(id = c(1,2,3),
                    name = c("lab1", "lab2", "lab3"))

header = dashboardHeader(title = "title")
sidebar = dashboardSidebar(sidebarMenu(id="mytabs",
                                    uiOutput("sidebar_menu_UI")))
body = dashboardBody()

ui = dashboardPage(header, sidebar, body)

server = function(input, output) {

    output$sidebar_menu_UI <- renderUI({

        myTabs = lapply(1:nrow(labels) , function(i) {

            menuItem(labels$name[i], tabName = labels$id[i])
        })

        print(myTabs)

        do.call(sidebarMenu, myTabs)
    })
}

shinyApp(ui, server)


问:
Concatenate string in typescript/javascript
EDIT: This string is a part of json and i am writing it onto a file. In that json file i see the escape charaters. With console.log, I don't see any escape character.

I am trying to concatenate a string such that I get the following output:

```<code>"OR("1admin", "2admin")"
</code>```

But the output I keep on getting is

```<code>"OR(\"1admin\", \"2admin\")"
</code>```

Sample code

var str = "OR("
for (let i = 1; i < 3; i++) {
  str += '"' + i + 'admin' + '", ';
}
str = str.trim().substring(0, str.length - 2).concat(')')
console.log(str)```
</div>
</div>
</p>

<p>I have tried using regex and string split.
eg.</p>

<p><code>.replace(/'/g, '"')</code> This when i tried something like this <code>"'" + i + "admin" + "', "</code> and tried to replace <code>'</code> with <code>"</code></p>

```.split('\\').join('').trim() This also didn' work.
```

What am I doing wrong?

答:
As mentioned, you already got the correct result in your original snippet.

If the character escape syntax seems curious to you, I'd recommend something like the following using template strings.

You can write the " in template strings unescaped and use interpolation to print your variables.

Edit: Seems like you want JSON formatting. You can use JSON.stringify for that. JSON formatted strings will contain escape characters that show up in console.log output.

const f = (n, s) => {
    const a = new Array(n)
      .fill()
      .map((_, i) => `"${i + 1}${s}"`);
    return `OR(${a.join(', ')})`;
}

console.log(`output: ${f(2, "admin")}`)
console.log(`json-formatted: ${JSON.stringify(f(2, "admin"))}`)```

Body:
EDIT: This string is a part of json and i am writing it onto a file. In that json file i see the escape charaters. With console.log, I don't see any escape character.

I am trying to concatenate a string such that I get the following output:

"OR("1admin", "2admin")"

But the output I keep on getting is

"OR(\"1admin\", \"2admin\")"

Sample code

var str = "OR("
for (let i = 1; i < 3; i++) {
  str += '"' + i + 'admin' + '", ';
}
str = str.trim().substring(0, str.length - 2).concat(')')
console.log(str)

I have tried using regex and string split.
eg.

.replace(/'/g, '"') This when i tried something like this "'" + i + "admin" + "', " and tried to replace ' with "

.split('\\').join('').trim() This also didn' work.

What am I doing wrong?


问:
Cannot assign to property 'observationTime' is a get-only property
I am getting this error when trying to set the observationTime to a time interval. Not sure why I can set a property, ive set it like this in other places </p>

```<code>weatherReading?.observationTime = NSTimeIntervalSince1970

@objcMembers class WeatherThirdPartyReadings: NSObject  {

    private var _temperature: Double
    private var _speed: Double
    private var _direction: Double
    private var _observationTime: Double
    private var _isSummaryLoaded: Bool

    var temperature: Double {
        return _temperature
    }
    var speed: Double {
        return _speed
    }
    var direction: Double {
        return _direction
    }
    var observationTime: Double {
        return _observationTime
    }
    var isSummaryLoaded: Bool {
        return _isSummaryLoaded
    }

    init(temperature: Double, speed: Double, direction: Double, observationTime: Double, isSummaryLoaded: Bool) {
        self._temperature = temperature
        self._speed = speed
        self._direction = direction
        self._observationTime = observationTime
        self._isSummaryLoaded = isSummaryLoaded
    }
}
</code>```

答:
You need

```<code>var observationTime: Double {
    set {
        _observationTime = newValue
    }
    get{
        return _observationTime
    }
}
</code>```

As this

```<code>var observationTime: Double {
    return _observationTime
}
</code>```

makes it a read only property which the3 default implementation of get

```<code>@objcMembers class WeatherThirdPartyReadings: NSObject  {

    var temperature: Double
    var speed: Double
    var direction: Double
    var observationTime: Double
    var isSummaryLoaded: Bool

    init(temperature: Double, speed: Double, direction: Double, observationTime: Double, isSummaryLoaded: Bool) {
        self.temperature = temperature
        self.speed = speed
        self.direction = direction
        self.observationTime = observationTime
        self.isSummaryLoaded = isSummaryLoaded
    }
}
</code>```

Body:
I am getting this error when trying to set the observationTime to a time interval. Not sure why I can set a property, ive set it like this in other places

weatherReading?.observationTime = NSTimeIntervalSince1970

@objcMembers class WeatherThirdPartyReadings: NSObject  {

    private var _temperature: Double
    private var _speed: Double
    private var _direction: Double
    private var _observationTime: Double
    private var _isSummaryLoaded: Bool

    var temperature: Double {
        return _temperature
    }
    var speed: Double {
        return _speed
    }
    var direction: Double {
        return _direction
    }
    var observationTime: Double {
        return _observationTime
    }
    var isSummaryLoaded: Bool {
        return _isSummaryLoaded
    }

    init(temperature: Double, speed: Double, direction: Double, observationTime: Double, isSummaryLoaded: Bool) {
        self._temperature = temperature
        self._speed = speed
        self._direction = direction
        self._observationTime = observationTime
        self._isSummaryLoaded = isSummaryLoaded
    }
}

Body:
You need

var observationTime: Double {
    set {
        _observationTime = newValue
    }
    get{
        return _observationTime
    }
}

As this

var observationTime: Double {
    return _observationTime
}

makes it a read only property which the3 default implementation of get

@objcMembers class WeatherThirdPartyReadings: NSObject  {

    var temperature: Double
    var speed: Double
    var direction: Double
    var observationTime: Double
    var isSummaryLoaded: Bool

    init(temperature: Double, speed: Double, direction: Double, observationTime: Double, isSummaryLoaded: Bool) {
        self.temperature = temperature
        self.speed = speed
        self.direction = direction
        self.observationTime = observationTime
        self.isSummaryLoaded = isSummaryLoaded
    }
}


问:
Qt - Why won't my widgets line up using a vertical layout inside a splitter?
As per the screenshot below, why won't my widgets line up using a vertical layout inside a splitter?

```<code>/********************************************************************************
** Form generated from reading UI file 'test.ui'
**
** Created: Tue Apr 12 16:51:51 2011
**      by: Qt User Interface Compiler version 4.6.2
**
** WARNING! All changes made in this file will be lost when recompiling UI file!
********************************************************************************/

#ifndef UI_TEST_H
#define UI_TEST_H

#include <QtCore/QVariant>
#include <QtGui/QAction>
#include <QtGui/QApplication>
#include <QtGui/QButtonGroup>
#include <QtGui/QGridLayout>
#include <QtGui/QHeaderView>
#include <QtGui/QLineEdit>
#include <QtGui/QListWidget>
#include <QtGui/QMainWindow>
#include <QtGui/QSplitter>
#include <QtGui/QTreeWidget>
#include <QtGui/QVBoxLayout>
#include <QtGui/QWidget>

QT_BEGIN_NAMESPACE

class Ui_MainWindow
{
public:
    QWidget *centralwidget;
    QGridLayout *gridLayout;
    QSplitter *splitter;
    QTreeWidget *treeWidget;
    QWidget *widget;
    QVBoxLayout *verticalLayout;
    QLineEdit *lineEdit;
    QListWidget *listWidget;

    void setupUi(QMainWindow *MainWindow)
    {
    if (MainWindow->objectName().isEmpty())
        MainWindow->setObjectName(QString::fromUtf8("MainWindow"));
    MainWindow->resize(800, 600);
    centralwidget = new QWidget(MainWindow);
    centralwidget->setObjectName(QString::fromUtf8("centralwidget"));
    gridLayout = new QGridLayout(centralwidget);
    gridLayout->setObjectName(QString::fromUtf8("gridLayout"));
    splitter = new QSplitter(centralwidget);
    splitter->setObjectName(QString::fromUtf8("splitter"));
    splitter->setOrientation(Qt::Horizontal);
    treeWidget = new QTreeWidget(splitter);
    QTreeWidgetItem *__qtreewidgetitem = new QTreeWidgetItem();
    __qtreewidgetitem->setText(0, QString::fromUtf8("1"));
    treeWidget->setHeaderItem(__qtreewidgetitem);
    treeWidget->setObjectName(QString::fromUtf8("treeWidget"));
    splitter->addWidget(treeWidget);
    widget = new QWidget(splitter);
    widget->setObjectName(QString::fromUtf8("widget"));
    verticalLayout = new QVBoxLayout(widget);
    verticalLayout->setObjectName(QString::fromUtf8("verticalLayout"));
    verticalLayout->setContentsMargins(0, 0, 0, 0);
    lineEdit = new QLineEdit(widget);
    lineEdit->setObjectName(QString::fromUtf8("lineEdit"));

    verticalLayout->addWidget(lineEdit);

    listWidget = new QListWidget(widget);
    listWidget->setObjectName(QString::fromUtf8("listWidget"));

    verticalLayout->addWidget(listWidget);

    splitter->addWidget(widget);

    gridLayout->addWidget(splitter, 0, 0, 1, 1);

    MainWindow->setCentralWidget(centralwidget);

    retranslateUi(MainWindow);

    QMetaObject::connectSlotsByName(MainWindow);
    } // setupUi

    void retranslateUi(QMainWindow *MainWindow)
    {
    MainWindow->setWindowTitle(QApplication::translate("MainWindow", "MainWindow", 0, QApplication::UnicodeUTF8));
    } // retranslateUi

};

namespace Ui {
    class MainWindow: public Ui_MainWindow {};
} // namespace Ui

QT_END_NAMESPACE

#endif // UI_TEST_H
</code>```

This is just a dummy ui uploaded here for the purpose of the question. In my real ui design I've tried every imaginable combination, but as soon as I start using splitters, it all goes out of alignment.

答: Make sure that the tree widget and the widget with the vertical layout both have the same size policy (e.g. QSizePolicy::MinimumExpanding).</p>

Body:
As per the screenshot below, why won't my widgets line up using a vertical layout inside a splitter?

/********************************************************************************
** Form generated from reading UI file 'test.ui'
**
** Created: Tue Apr 12 16:51:51 2011
**      by: Qt User Interface Compiler version 4.6.2
**
** WARNING! All changes made in this file will be lost when recompiling UI file!
********************************************************************************/

#ifndef UI_TEST_H
#define UI_TEST_H

#include <QtCore/QVariant>
#include <QtGui/QAction>
#include <QtGui/QApplication>
#include <QtGui/QButtonGroup>
#include <QtGui/QGridLayout>
#include <QtGui/QHeaderView>
#include <QtGui/QLineEdit>
#include <QtGui/QListWidget>
#include <QtGui/QMainWindow>
#include <QtGui/QSplitter>
#include <QtGui/QTreeWidget>
#include <QtGui/QVBoxLayout>
#include <QtGui/QWidget>

QT_BEGIN_NAMESPACE

class Ui_MainWindow
{
public:
    QWidget *centralwidget;
    QGridLayout *gridLayout;
    QSplitter *splitter;
    QTreeWidget *treeWidget;
    QWidget *widget;
    QVBoxLayout *verticalLayout;
    QLineEdit *lineEdit;
    QListWidget *listWidget;

    void setupUi(QMainWindow *MainWindow)
    {
    if (MainWindow->objectName().isEmpty())
        MainWindow->setObjectName(QString::fromUtf8("MainWindow"));
    MainWindow->resize(800, 600);
    centralwidget = new QWidget(MainWindow);
    centralwidget->setObjectName(QString::fromUtf8("centralwidget"));
    gridLayout = new QGridLayout(centralwidget);
    gridLayout->setObjectName(QString::fromUtf8("gridLayout"));
    splitter = new QSplitter(centralwidget);
    splitter->setObjectName(QString::fromUtf8("splitter"));
    splitter->setOrientation(Qt::Horizontal);
    treeWidget = new QTreeWidget(splitter);
    QTreeWidgetItem *__qtreewidgetitem = new QTreeWidgetItem();
    __qtreewidgetitem->setText(0, QString::fromUtf8("1"));
    treeWidget->setHeaderItem(__qtreewidgetitem);
    treeWidget->setObjectName(QString::fromUtf8("treeWidget"));
    splitter->addWidget(treeWidget);
    widget = new QWidget(splitter);
    widget->setObjectName(QString::fromUtf8("widget"));
    verticalLayout = new QVBoxLayout(widget);
    verticalLayout->setObjectName(QString::fromUtf8("verticalLayout"));
    verticalLayout->setContentsMargins(0, 0, 0, 0);
    lineEdit = new QLineEdit(widget);
    lineEdit->setObjectName(QString::fromUtf8("lineEdit"));

    verticalLayout->addWidget(lineEdit);

    listWidget = new QListWidget(widget);
    listWidget->setObjectName(QString::fromUtf8("listWidget"));

    verticalLayout->addWidget(listWidget);

    splitter->addWidget(widget);

    gridLayout->addWidget(splitter, 0, 0, 1, 1);

    MainWindow->setCentralWidget(centralwidget);

    retranslateUi(MainWindow);

    QMetaObject::connectSlotsByName(MainWindow);
    } // setupUi

    void retranslateUi(QMainWindow *MainWindow)
    {
    MainWindow->setWindowTitle(QApplication::translate("MainWindow", "MainWindow", 0, QApplication::UnicodeUTF8));
    } // retranslateUi

};

namespace Ui {
    class MainWindow: public Ui_MainWindow {};
} // namespace Ui

QT_END_NAMESPACE

#endif // UI_TEST_H

This is just a dummy ui uploaded here for the purpose of the question. In my real ui design I've tried every imaginable combination, but as soon as I start using splitters, it all goes out of alignment.


问:
UnicodeDecodeError: 'utf-8' codec can't decode byte 0xff in position 0

I tried to migrate the django file and the sqlite3 database file to
MySQL data, and I encountered such an error.

create database:
create database mysite_db default charset=utf8mb4 default collate
utf8mb4_unicode_ci;

Data migration in db_sqlite3:
python manage.py dumpdata > data.json

input mysql:
python manage.py loaddata data.json

```<code>File "C:\blog_env\lib\site-packages\django\core\management\commands\loaddata.py", line 113, in loaddata
    self.load_label(fixture_label)
  File "C:\blog_env\lib\site-packages\django\core\management\commands\loaddata.py", line 168, in load_label
    for obj in objects:
  File "C:\blog_env\lib\site-packages\django\core\serializers\json.py", line 66, in Deserializer
    stream_or_string = stream_or_string.decode()
UnicodeDecodeError: 'utf-8' codec can't decode byte 0xff in position 0: invalid start byte
(blog_env) PS C:\blog_env\mysite>
</code>```

答:
I had the same problem recently... here's my solution:

Confirm the encoding format of 'file_path':

download and open the file with Notepad++

check the lower right corner; there you can see whether your file was encoded in the compatible format, or if it has the Byte Order Marker or BOM sign,

if either of these is true, simply 'save as' the correct/required format.

You should be fine with the above.

Body:
I tried to migrate the django file and the sqlite3 database file to
MySQL data, and I encountered such an error.

create database:
create database mysite_db default charset=utf8mb4 default collate
utf8mb4_unicode_ci;

Data migration in db_sqlite3:
python manage.py dumpdata > data.json

input mysql:
python manage.py loaddata data.json

File "C:\blog_env\lib\site-packages\django\core\management\commands\loaddata.py", line 113, in loaddata
    self.load_label(fixture_label)
  File "C:\blog_env\lib\site-packages\django\core\management\commands\loaddata.py", line 168, in load_label
    for obj in objects:
  File "C:\blog_env\lib\site-packages\django\core\serializers\json.py", line 66, in Deserializer
    stream_or_string = stream_or_string.decode()
UnicodeDecodeError: 'utf-8' codec can't decode byte 0xff in position 0: invalid start byte
(blog_env) PS C:\blog_env\mysite>


问:
Get previous intent name from Rasa action?
I have an intent called intent_yes which is shared in several different conversational flows. When the user says "Yes" or "Yeah" etc., it will call my webhook / Rasa action. I need to know what they've said yes to. How can we get the previous intent name from a Rasa webhook action?

答:
This is probably not good design - you're better off writing individual stories for each flow and then having a corresponding action for each circumstance, however within the custom action's run method you can access the tracker.  This object holds all the events of the conversation in a list called tracker.events, which
will look something like this:

```<code>[{'event': 'action', 'timestamp': 1558688062.7624729, 'name': 'action_listen', 'policy': None, 'confidence': None},
{'event': 'user', 'timestamp': 1558688062.7628329, 'text': '/joke', 'parse_data': {'text': '/joke', 'intent': {'name': 'joke', 'confidence': 1.0}, 'intent_ranking': [{'name': 'joke', 'confidence': 1.0}], 'entities': []}, 'input_channel': 'rest'}]
</code>```

To get the user messages just iterate backwards over this list until you find "event":"user" and the intent is given inside "parse_data"["intent"]

Body:
This is probably not good design - you're better off writing individual stories for each flow and then having a corresponding action for each circumstance, however within the custom action's run method you can access the tracker.  This object holds all the events of the conversation in a list called tracker.events, which
will look something like this:

[{'event': 'action', 'timestamp': 1558688062.7624729, 'name': 'action_listen', 'policy': None, 'confidence': None},
{'event': 'user', 'timestamp': 1558688062.7628329, 'text': '/joke', 'parse_data': {'text': '/joke', 'intent': {'name': 'joke', 'confidence': 1.0}, 'intent_ranking': [{'name': 'joke', 'confidence': 1.0}], 'entities': []}, 'input_channel': 'rest'}]

To get the user messages just iterate backwards over this list until you find "event":"user" and the intent is given inside "parse_data"["intent"]


问:
How can I avoid flipping between ttyUSB0 and ttyUSB1 when reconnecting to USB port under Python using pySerial?
I have a serial Python program, Linux environment (Raspbian / Raspberry Pi), that uses a serial port via a USB-to-serial adapter. I need to handle a situation when the user unplugs the USB adapter and then reinsert it.

The problem is that, on reconnect, the ttyUSB0 becomes ttyUSB1 and so the port is no longer found. However, if I stop the Python program (keyboard interrupt) and again unplug and reinsert the USB adapter, then the port goes back to ttyUSB0 (and so I can start over again). This can happen only when the Python program is stopped.

I tested the program in a flip-flop mode (and it seems to be working) in order to use ttyUSB1 when ttyUSB0 is no longer found and then vice versa, use ttyUSB0 back in case ttyUSB1 is no longer found, etc., but this looks like a weird solution to me.

Is there a better way to force pySerial to "forget" it has ever been connected to ttyUSB0 in case of error and release the current port to the system while the program is still running?

Here is a working flip-flop test program:

```<code>import serial
import time

p = "/dev/ttyUSB0"

while True:
    error_flag = False
    try:
        s = serial.Serial(port=p, baudrate=9600, bytesize=8, parity="N", stopbits=1, timeout=None, xonxoff=False, rtscts=False, write_timeout=None, dsrdtr=False, inter_byte_timeout=None)
    except Exception as e:
        error_flag = True
        if "ttyUSB0" in str(e):
            p = "/dev/ttyUSB1"
            print ("port is now", p)
        elif "ttyUSB1" in str(e):
            p = "/dev/ttyUSB0"
            print ("port is now", p)
        else:
            print (e)   # none of the above

    # if not error_flag, do whatever, etc.

    time.sleep(1)
</code>```

答:
Do not forget to close the file descriptor of /dev/ttyUSB0 as soon as you detect that the user unplugged the USB adapter (read or write with error), and before the reinsertion.

If you properly close the device, the ttyUSB1 device will never appear. On the other hand, you can see in some cases also ttyUSB2, ttyUSB3, and so on, if all the previous ttyUSBx's are blocked because not closed.

Body:
I have a serial Python program, Linux environment (Raspbian / Raspberry Pi), that uses a serial port via a USB-to-serial adapter. I need to handle a situation when the user unplugs the USB adapter and then reinsert it.

The problem is that, on reconnect, the ttyUSB0 becomes ttyUSB1 and so the port is no longer found. However, if I stop the Python program (keyboard interrupt) and again unplug and reinsert the USB adapter, then the port goes back to ttyUSB0 (and so I can start over again). This can happen only when the Python program is stopped.

I tested the program in a flip-flop mode (and it seems to be working) in order to use ttyUSB1 when ttyUSB0 is no longer found and then vice versa, use ttyUSB0 back in case ttyUSB1 is no longer found, etc., but this looks like a weird solution to me.

Is there a better way to force pySerial to "forget" it has ever been connected to ttyUSB0 in case of error and release the current port to the system while the program is still running?

Here is a working flip-flop test program:

import serial
import time

p = "/dev/ttyUSB0"

while True:
    error_flag = False
    try:
        s = serial.Serial(port=p, baudrate=9600, bytesize=8, parity="N", stopbits=1, timeout=None, xonxoff=False, rtscts=False, write_timeout=None, dsrdtr=False, inter_byte_timeout=None)
    except Exception as e:
        error_flag = True
        if "ttyUSB0" in str(e):
            p = "/dev/ttyUSB1"
            print ("port is now", p)
        elif "ttyUSB1" in str(e):
            p = "/dev/ttyUSB0"
            print ("port is now", p)
        else:
            print (e)   # none of the above

    # if not error_flag, do whatever, etc.

    time.sleep(1)


答:
The issue is that when you use this syntax you are saying the public property only has a getter and no setter is available. You need to also create the setter for the property.

```<code>var observationTime: Double {
    get {
        return _observationTime
    }
    set {
        _observationTime = newValue
    }
}
</code>```

Unless you explicitly need a backing variable for some other reason not indicated in your post, you could simply just declare the variable like so:

```<code>var observationTime: Double
</code>```

Title: Cannot assign to property 'observationTime' is a get-only property

Body:
The issue is that when you use this syntax you are saying the public property only has a getter and no setter is available. You need to also create the setter for the property.

var observationTime: Double {
    get {
        return _observationTime
    }
    set {
        _observationTime = newValue
    }
}

Unless you explicitly need a backing variable for some other reason not indicated in your post, you could simply just declare the variable like so:

var observationTime: Double


问:
Can scrapy skip the error of empty data and keeping scraping?
I want to scrape product pages from its sitemap, the products page are similar, but not all of them are the same.

for example

Product A
https://www.vitalsource.com/products/environment-the-science-behind-the-stories-jay-h-withgott-matthew-v9780134446400

Product B
https://www.vitalsource.com/products/abnormal-psychology-susan-nolen-hoeksema-v9781259765667

we can see the product A has the subtitle but another one doesn't have.

So I get errors when I trying to scrape all the product pages.

My question is, is there a way to let the spider skip the error for returning no data?

There is a simple way to bypass it. that is not using strip()
But I am wondering if there is a better way to do the job.

```<code>import scrapy
import re
from VitalSource.items import VitalsourceItem
from scrapy.selector import Selector
from scrapy.spiders import SitemapSpider

class VsSpider(SitemapSpider):
    name = 'VS'
    allowed_domains = ['vitalsource.com']
    sitemap_urls = ['https://storage.googleapis.com/vst-stargate-production/sitemap/sitemap1.xml.gz']
    sitemap_rules = [
        ('/products/', 'parse_product'),
    ]
    def parse_product(self, response):
        selector = Selector(response=response)
        item = VitalsourceItem()
        item['Ebook_Title'] = response.css('.product-overview__title-header::text').extract()[1].strip
        item['Ebook_SubTitle'] = response.css("div.subtitle.subtitle-pdp::text").extract().strip
        print(item)
        return item
</code>```

error message

```<code>    item['Ebook_SubTitle'] = response.css("div.subtitle.subtitle-pdp::text").extract().strip
AttributeError: 'list' object has no attribute 'strip'
</code>```

答:
In general scrapy will not stop crawling if callbacks raise an exception. e.g.:

```<code>def start_requests(self):
    for i in range(10):
        yield Requst(
            f'http://example.org/page/{i}',
            callback=self.parse,
            errback=self.errback,
        )

def parse(self, response):
    # first page
    if 'page/1' in response.request.url:
        raise ValueError()
    yield {'url': response.url}

def errback(self, failure):
    print(f"oh no, failed to parse {failure.request}")
</code>```

In this example 10 requests will be made and 9 items will be scraped but 1 will fail and got o errback

In your case you have nothing to fear - any request that does not raise an exception will scrape as it should, for the ones that do you'll just see an exception traceback in your terminal/logs.

Body:
I want to scrape product pages from its sitemap, the products page are similar, but not all of them are the same.

for example

Product A
https://www.vitalsource.com/products/environment-the-science-behind-the-stories-jay-h-withgott-matthew-v9780134446400

Product B
https://www.vitalsource.com/products/abnormal-psychology-susan-nolen-hoeksema-v9781259765667

we can see the product A has the subtitle but another one doesn't have.

So I get errors when I trying to scrape all the product pages.

My question is, is there a way to let the spider skip the error for returning no data?

There is a simple way to bypass it. that is not using strip()
But I am wondering if there is a better way to do the job.

import scrapy
import re
from VitalSource.items import VitalsourceItem
from scrapy.selector import Selector
from scrapy.spiders import SitemapSpider

class VsSpider(SitemapSpider):
    name = 'VS'
    allowed_domains = ['vitalsource.com']
    sitemap_urls = ['https://storage.googleapis.com/vst-stargate-production/sitemap/sitemap1.xml.gz']
    sitemap_rules = [
        ('/products/', 'parse_product'),
    ]
    def parse_product(self, response):
        selector = Selector(response=response)
        item = VitalsourceItem()
        item['Ebook_Title'] = response.css('.product-overview__title-header::text').extract()[1].strip
        item['Ebook_SubTitle'] = response.css("div.subtitle.subtitle-pdp::text").extract().strip
        print(item)
        return item

error message

    item['Ebook_SubTitle'] = response.css("div.subtitle.subtitle-pdp::text").extract().strip
AttributeError: 'list' object has no attribute 'strip'

Body:
In general scrapy will not stop crawling if callbacks raise an exception. e.g.:

def start_requests(self):
    for i in range(10):
        yield Requst(
            f'http://example.org/page/{i}',
            callback=self.parse,
            errback=self.errback,
        )

def parse(self, response):
    # first page
    if 'page/1' in response.request.url:
        raise ValueError()
    yield {'url': response.url}

def errback(self, failure):
    print(f"oh no, failed to parse {failure.request}")

In this example 10 requests will be made and 9 items will be scraped but 1 will fail and got o errback

In your case you have nothing to fear - any request that does not raise an exception will scrape as it should, for the ones that do you'll just see an exception traceback in your terminal/logs.


问:
How to apply texture for 3d model from mixamo?
I downloaded 3model from here https://www.turbosquid.com/3d-models/cartoon-boy-rigged-character-3d-model-1214430, than I add animation on mixamo site and after that add this model to Xcode! How to correct apply texture for model in xcode, because it’s has a lot of texture for shoes, body, eyes and e.t.c ?</p>

答:
Try to do the following:

Export the model in obj format without the textures

Export the material and textures in the same folder (.mtl, .png, etc...)

Zip all the content

Upload the entire zip in Mixamo


问:
Laravel Eloquent - distinct() and count() not working properly together
So I'm trying to get the number of distinct pids on a query, but the returned value is wrong.

This is what I try to do:

```<code>$ad->getcodes()->groupby('pid')->distinct()->count()
</code>```

what returns the value "2", while the value it should return, should be "1".

As a workaround, I'm doing this:

```<code>count($ad->getcodes()->groupby('pid')->distinct()->get())
</code>```

what works fine and returns "1"

Is there any rule where count and distinct cannot be on the same query? I find the workaround kind of "heavy", I would like to make the original query work :(

答:
try this</p>

```<code>$ad->getcodes()->groupby('pid')->distinct()->count('pid')
</code>```

Body:
So I'm trying to get the number of distinct pids on a query, but the returned value is wrong.

This is what I try to do:

$ad->getcodes()->groupby('pid')->distinct()->count()

what returns the value "2", while the value it should return, should be "1".

As a workaround, I'm doing this:

count($ad->getcodes()->groupby('pid')->distinct()->get())

what works fine and returns "1"

Is there any rule where count and distinct cannot be on the same query? I find the workaround kind of "heavy", I would like to make the original query work :(

Body:
try this

$ad->getcodes()->groupby('pid')->distinct()->count('pid')


问:
C++ how to sort vector<class *> with operator <
i have

```<code> class c1{

public:
    int number;

    c1()
    {
        number=rand()%10;
    }

    bool operator < (c1 *w)
    {
        return number < w->number;
    }

};

vector<c1*> vec = { ... }
sort(vec.begin(),vec.end())
</code>```

why it dosent sort ?

but if we had

```<code> bool operator < (c1 w)
    {
        return number < w.number;
    }
</code>```

and

```<code>vector<c1> vec = { ... }
</code>```

it would have been sorted !

答:
You need to pass a compare function to std::sort:

```<code>bool compare_c1 (c1* x, c1* y)
{
  return *x < y;
}

std::sort(v.begin(), v.end(), compare_c1);
</code>```

Or if you are using GCC >= 4.5 or Visual Studio 2010 (I'm do not know sure about Intel compiler) you can use lambdas (they are part of the C++0x standard):

```<code>std::sort(v.begin(), v.end(), [] (c1* x, c1* y) { return *x < y; });
</code>```

Body:
i have

 class c1{

public:
    int number;

    c1()
    {
        number=rand()%10;
    }

    bool operator < (c1 *w)
    {
        return number < w->number;
    }

};

vector<c1*> vec = { ... }
sort(vec.begin(),vec.end())

why it dosent sort ?

but if we had

 bool operator < (c1 w)
    {
        return number < w.number;
    }

and

vector<c1> vec = { ... }

it would have been sorted !

Body:
You need to pass a compare function to std::sort:

bool compare_c1 (c1* x, c1* y)
{
  return *x < y;
}

std::sort(v.begin(), v.end(), compare_c1);

Or if you are using GCC >= 4.5 or Visual Studio 2010 (I'm do not know sure about Intel compiler) you can use lambdas (they are part of the C++0x standard):

std::sort(v.begin(), v.end(), [] (c1* x, c1* y) { return *x < y; });


问:
Django 2.0: sqlite IntegrityError: FOREIGN KEY constraint failed
I'm working on adding Django 2.0 support to the django-pagetree library. During automated testing, using an sqlite in-memory database, I'm getting a bunch of errors like this:

```<code>  File "/home/nnyby/src/django-pagetree/pagetree/tests/test_models.py", line 638, in setUp
    'children': [],
  File "/home/nnyby/src/django-pagetree/pagetree/models.py", line 586, in add_child_section_from_dict

...

  File "/home/nnyby/src/django-pagetree/venv/lib/python3.5/site-packages/django/db/backends/base/base.py", line 239, in _commit
    return self.connection.commit()
django.db.utils.IntegrityError: FOREIGN KEY constraint failed
</code>```

This is noted in the Django 2.0 release notes: https://docs.djangoproject.com/en/2.0/releases/2.0/#foreign-key-constraints-are-now-enabled-on-sqlite

From that description, which I don't fully understand, this shouldn't apply for test databases that aren't persistent, right? Wouldn't my sqlite test db get created with the appropriate options when using Django 2.0?

The app settings I'm using for testing are here: https://github.com/ccnmtl/django-pagetree/blob/master/runtests.py

答:
I met a different situation with the same error. The problem was that I used the same Model name and field name

Incorrect code:

class Column(models.Model):
    ...

class ColumnToDepartment(models.Model):
    column = models.ForeignKey(Column, on_delete=models.CASCADE)
```
<p>Solution:</p>
<pre class="lang-py prettyprint-override"><code>class Column(models.Model):
    ...

class ColumnToDepartment(models.Model):
    referring_column = models.ForeignKey(Column, on_delete=models.CASCADE)
</code>```

Body:
I'm working on adding Django 2.0 support to the django-pagetree library. During automated testing, using an sqlite in-memory database, I'm getting a bunch of errors like this:

  File "/home/nnyby/src/django-pagetree/pagetree/tests/test_models.py", line 638, in setUp
    'children': [],
  File "/home/nnyby/src/django-pagetree/pagetree/models.py", line 586, in add_child_section_from_dict

...

  File "/home/nnyby/src/django-pagetree/venv/lib/python3.5/site-packages/django/db/backends/base/base.py", line 239, in _commit
    return self.connection.commit()
django.db.utils.IntegrityError: FOREIGN KEY constraint failed

This is noted in the Django 2.0 release notes: https://docs.djangoproject.com/en/2.0/releases/2.0/#foreign-key-constraints-are-now-enabled-on-sqlite

From that description, which I don't fully understand, this shouldn't apply for test databases that aren't persistent, right? Wouldn't my sqlite test db get created with the appropriate options when using Django 2.0?

The app settings I'm using for testing are here: https://github.com/ccnmtl/django-pagetree/blob/master/runtests.py

Body:
I met a different situation with the same error. The problem was that I used the same Model name and field name

Incorrect code:

class Column(models.Model):
    ...

class ColumnToDepartment(models.Model):
    column = models.ForeignKey(Column, on_delete=models.CASCADE)

Solution:

class Column(models.Model):
    ...

class ColumnToDepartment(models.Model):
    referring_column = models.ForeignKey(Column, on_delete=models.CASCADE)


问:
How to get() multiple updated values only once in Firebase Real Time Database (Angular)
I am updating all data for each user in Firebase - Real Time Database at fixed periods of time and I am using:

```<code>this.db.list('/' + this.user.uid + '/data).valueChanges()
.subscribe(items=>{
    console.log(items)
});
</code>```

to retrieve the update. But because multiple values are updated(even though all at once) I receive in the web application one update at a time.
Is this normal? Is there any way to update all and receive the update only once?

答:
If you really don't like multiple emissions, you could try some RxJS operators before your subscribe.

```<code>this.db.list('/' + this.user.uid + '/data).valueChanges().pipe(
    buffer(interval(1000))
)
    .subscribe(items=>{
          console.log(items);
});
</code>```

For example, that would emit an array of values inside of a one second span.

If there's a way to listen to when you update (or rather, the confirmation from the server that updating was successful), you could listen to that, then just grab the current value of this.db.list instead of each value change as it comes in.

Body:
I am updating all data for each user in Firebase - Real Time Database at fixed periods of time and I am using:

this.db.list('/' + this.user.uid + '/data).valueChanges()
.subscribe(items=>{
    console.log(items)
});

to retrieve the update. But because multiple values are updated(even though all at once) I receive in the web application one update at a time.
Is this normal? Is there any way to update all and receive the update only once?

Body:
If you really don't like multiple emissions, you could try some RxJS operators before your subscribe.

this.db.list('/' + this.user.uid + '/data).valueChanges().pipe(
    buffer(interval(1000))
)
    .subscribe(items=>{
          console.log(items);
});

For example, that would emit an array of values inside of a one second span.

If there's a way to listen to when you update (or rather, the confirmation from the server that updating was successful), you could listen to that, then just grab the current value of this.db.list instead of each value change as it comes in.


问:
Uncaught Error: Can't resolve all parameters for <Service>
This error prevents my app from loading due to a Modal Service

followed this post

app.module

```<code>import { ModalService } from './Services/Modal/modal.service';

providers: [
...,
ModalService,
...
]
</code>```

modal.service.ts

```<code>import { Injectable } from '@angular/core';
import { ModalController } from '@ionic/angular';
import { ProfileComponent } from '..';
import { ChatComponent} from '..';
import { Contact } from '../../../Schemas/Contact';
import 'core-js/es7/reflect';

@Injectable({
  providedIn: 'root'
})
export class ModalService {

  constructor(
    private modalCtrl: ModalController
  ) { }

  public async openChat(contact: Contact) {
    const chat = await this.modalCtrl.create({
      component: ChatComponent,
      componentProps: {contact}
    });
    return await chat.present();
  }

  public async openProfileComponent(info: Info) {
    const profileComponent = await this.modalCtrl.create({
      component: ProfileComponent,
      componentProps: {info}
    });
    return await profileComponent.present();
  }

  public dismiss() {
    return this.modalCtrl.dismiss();
  }
}
</code>```

the page that has the issue:

```<code>import { ModalService } from 'src/app/Services/Modal/modal.service';

export class ChatComponent {
  constructor(
    ...
    public modalService: ModalService,
    ) {}

 public async openProfile() {
    this.modalService.openProfileComponent(this.info);
 }
}

</code>```

I am not sure why this is happening as there are other Pages that are using this service as well and there is no problem with it. I have tried comparing and seeing what is different but I am unable to see why it's unable to resolve the parameter.

I know I have a circular dependency, that I will address once it is loading on my device. But, it can't resolve it and I have no idea

```<code>-entryComponent -(click)-> chatComponent
                           |-(click)->profileComponent
</code>```

答: can't make an ionic 4 modal controller without circle dependency error so scrapping it.</p>

Body:
This error prevents my app from loading due to a Modal Service

followed this post

app.module

import { ModalService } from './Services/Modal/modal.service';

providers: [
...,
ModalService,
...
]

modal.service.ts

import { Injectable } from '@angular/core';
import { ModalController } from '@ionic/angular';
import { ProfileComponent } from '..';
import { ChatComponent} from '..';
import { Contact } from '../../../Schemas/Contact';
import 'core-js/es7/reflect';

@Injectable({
  providedIn: 'root'
})
export class ModalService {

  constructor(
    private modalCtrl: ModalController
  ) { }

  public async openChat(contact: Contact) {
    const chat = await this.modalCtrl.create({
      component: ChatComponent,
      componentProps: {contact}
    });
    return await chat.present();
  }

  public async openProfileComponent(info: Info) {
    const profileComponent = await this.modalCtrl.create({
      component: ProfileComponent,
      componentProps: {info}
    });
    return await profileComponent.present();
  }

  public dismiss() {
    return this.modalCtrl.dismiss();
  }
}

the page that has the issue:

import { ModalService } from 'src/app/Services/Modal/modal.service';

export class ChatComponent {
  constructor(
    ...
    public modalService: ModalService,
    ) {}

 public async openProfile() {
    this.modalService.openProfileComponent(this.info);
 }
}

I am not sure why this is happening as there are other Pages that are using this service as well and there is no problem with it. I have tried comparing and seeing what is different but I am unable to see why it's unable to resolve the parameter.

I know I have a circular dependency, that I will address once it is loading on my device. But, it can't resolve it and I have no idea

-entryComponent -(click)-> chatComponent
                           |-(click)->profileComponent


问:
simple validation form with javascript
i have a 'div' tag included error message on the my form.
this tag displaying when button is clicked and inputs are null.
my code is working but, 'div' tag is hide speedly.

<htlm>

Username Or Password is incorrect.

<form id="Main" method="POST">
<input id="User" type="text" name="Name" placeholder="Enter Your Username">

<input id="Pass" type="password" name="Pass" placeholder="Enter Your Password"/>

<button id="bt">Login</button>
<button >Cancel</button>
</form>

```

<pre class="lang-css prettyprint-override"><code>div#ShowError{
opacity:0.0;
}
</code>```

```<code>var btn = document.getElementById("bt");
btn.addEventListener("click",func);

var Username = document.getElementById("User");
var Password = document.getElementById("Pass");

function func()
{

    if(Username.value == "" || Password.value == "")
    {
        document.getElementById("ShowError").style.opacity = "1.0";
    }
}
</code>```

答:
Clicking a submit button will submit the form.

So the JavaScript runs, the form submits, and a new page is loaded. The JavaScript hasn't run on the new page.

Prevent the default behaviour of the event if you don't want the form to submit.

```<code>function func(e)
{

    if(Username.value == "" || Password.value == "")
    {
        e.preventDefault();
        document.getElementById("ShowError").style.opacity = "1.0";
    }
}
</code>```

Title: simple validation form with javascript

Body:
i have a 'div' tag included error message on the my form.
this tag displaying when button is clicked and inputs are null.
my code is working but, 'div' tag is hide speedly.

<htlm>

Username Or Password is incorrect.

<form id="Main" method="POST">
<input id="User" type="text" name="Name" placeholder="Enter Your Username">

<input id="Pass" type="password" name="Pass" placeholder="Enter Your Password"/>

<button id="bt">Login</button>
<button >Cancel</button>
</form>

div#ShowError{
opacity:0.0;
}

var btn = document.getElementById("bt");
btn.addEventListener("click",func);

var Username = document.getElementById("User");
var Password = document.getElementById("Pass");

function func()
{

    if(Username.value == "" || Password.value == "")
    {
        document.getElementById("ShowError").style.opacity = "1.0";
    }
}

Body:
Clicking a submit button will submit the form.

So the JavaScript runs, the form submits, and a new page is loaded. The JavaScript hasn't run on the new page.

Prevent the default behaviour of the event if you don't want the form to submit.

function func(e)
{

    if(Username.value == "" || Password.value == "")
    {
        e.preventDefault();
        document.getElementById("ShowError").style.opacity = "1.0";
    }
}


问:
PowerQuery (in PowerBI) weird caching issue
For the past couple of days, I have been trying to overcome a weird issue within Power Query in Power BI Desktop.

I have two tables, one is called the "Mappings" table, and the purpose of this table is to give me a column called "FMReference" after a bunch of transformations.
Mappings Screenshot

I have my main table called "Entry", which DOESN'T HAVE FMReference, and thus, needs to be merged with the Mappings table. To make the merge simpler, I have created a simple column on both tables named "CombinedForMerge". Entry Screenshot

After the setup for the columns are complete, I proceed to create a Left Outer Merge with the Entry and Mappings tables, using the columns I have just made. Left Outer Merge Screenshot

As you can see on the screenshot, the FMReference column says A4.28, which is what I am expecting on my results. However, once I expand that merge to give me the FMReference, I am getting a different value, A3.2! Wrong Value Screenshot

Power BI clearly cached the wrong value on PowerQuery, as I have filtered the Mappings table to JUST one row, to get JUST the one value. Filtered Mappings Screenshot

I have tried clearing the cache from the Power BI Options, but this didn't change anything.

I've also tried rebuilding the Power BI report from a clean, new PBIX, just copying the transformations up to this point, but I am still getting the same issue.

I've tried copying the results of the Mappings table onto a static table, and used it for the merge instead. This worked, which clearly means it is something to do caching on the data transformations on Power BI.

I've refreshed the Preview, as well as Refreshed ALL a few times, but it still returns the wrong result.

I would appreciate any help at this point, the data is very sensitive so I cannot share a lot, but I am happy to give more details if needed.

Thanks in advance!

答:
I ran into similar inexplicably odd behavior when using fuzzy merge, set for an exact match. I wound up swapping the tables and using a Right Outer merge instead. For some reason, that worked. I have no idea what caused the problem or why the Right Outer merge approach worked though. It was quite odd.

So what I'm saying is: Instead of starting your merge from XXXXEntry and matching to XXXXMappings with a Left Outer merge, you might try starting from XXXXMappings and matching to XXXXEntry with a Right Outer merge.

One way to do that, if you still want the merge in the same place in the same query, is to just edit your existing query's code in the formula bar. To do that, click on the Applied Step that is associated with the merge, most likely called Merged Queries; then in the formula bar, swap the references to the tables and change JoinKind.LeftOuter to JoinKind.RightOuter. (One table reference will likely be the name of the Applied Step before your Merged Queries step, instead of XXXXEntry. For me, in the before and after examples that follow, it was #"Changed Type".)

Before:

```<code>= Table.NestedJoin(#"Changed Type", {"CombinedForMerge"}, XXXXMappings, {"CombinedForMerge"}, "Changed Type", JoinKind.LeftOuter)
</code>```

After:

```<code>= Table.NestedJoin(XXXXMappings, {"CombinedForMerge"}, #"Changed Type", {"CombinedForMerge"}, "XXXXMappings", JoinKind.RightOuter)
</code>```

Good luck.

Body:
I ran into similar inexplicably odd behavior when using fuzzy merge, set for an exact match. I wound up swapping the tables and using a Right Outer merge instead. For some reason, that worked. I have no idea what caused the problem or why the Right Outer merge approach worked though. It was quite odd.

So what I'm saying is: Instead of starting your merge from XXXXEntry and matching to XXXXMappings with a Left Outer merge, you might try starting from XXXXMappings and matching to XXXXEntry with a Right Outer merge.

One way to do that, if you still want the merge in the same place in the same query, is to just edit your existing query's code in the formula bar. To do that, click on the Applied Step that is associated with the merge, most likely called Merged Queries; then in the formula bar, swap the references to the tables and change JoinKind.LeftOuter to JoinKind.RightOuter. (One table reference will likely be the name of the Applied Step before your Merged Queries step, instead of XXXXEntry. For me, in the before and after examples that follow, it was #"Changed Type".)

Before:

= Table.NestedJoin(#"Changed Type", {"CombinedForMerge"}, XXXXMappings, {"CombinedForMerge"}, "Changed Type", JoinKind.LeftOuter)

After:

= Table.NestedJoin(XXXXMappings, {"CombinedForMerge"}, #"Changed Type", {"CombinedForMerge"}, "XXXXMappings", JoinKind.RightOuter)

Good luck.


问:
Unable to invoke mixin module method in spec
I have the following module:

```<code># lib/translator/sms_command.rb
module Translator
  module SmsCommand
    def self.included(klass)
      puts "SmsCommand initialized in #{klass}"
    end
    def alias_command(name)

    end
  end
end
</code>```

And the following spec:

```<code># spec/translator/sms_command_spec.rb
require 'spec_helper'

class ExampleCommand
  include Translator::SmsCommand
  alias_command :x
end

module Translator
  describe SmsCommand do
    describe "#alias_command" do
      it "registers the class with the command registry" do
        Translator::SmsCommand.command_registry.should include_key :x
      end

    end
  end
end
</code>```

Yes #alias_command does nothing at this stage but that's because I'm in the midst of developing it.  However, when I run my spec I am seeing...

```<code>SmsCommand initialized in ExampleCommand
</code>```

so the module is certainly being mixed in, however the spec barfs on the alias_command :x line in the ExampleCommand as if the alias_command method is never becoming available.

```<code>/spec/translator/sms_command_spec.rb:5:in `<class:ExampleCommand>': undefined method `alias_command' for ExampleCommand:Class (NoMethodError)
</code>```

I could solve this problem through inheritance though I'd prefer the mixin module.  What am I missing?

答:
You want to define a class method called alias_command, don't you?
In this case you need to extend the class with the module, a simple include will turn the included method into an instance method!

You can do it in a widely accepted way as follows:

```<code>module Translator
  module SmsCommand
    def self.included(klass)
      puts "SmsCommand initialized in #{klass}"
      klass.extend ClassMethods
    end
    module ClassMethods
      def alias_command(name)
      end
    end
  end
end
</code>```

This way when you include the module, it will automatically extend the target class with the class methods!

Body:
I have the following module:

# lib/translator/sms_command.rb
module Translator
  module SmsCommand
    def self.included(klass)
      puts "SmsCommand initialized in #{klass}"
    end
    def alias_command(name)

    end
  end
end

And the following spec:

# spec/translator/sms_command_spec.rb
require 'spec_helper'

class ExampleCommand
  include Translator::SmsCommand
  alias_command :x
end

module Translator
  describe SmsCommand do
    describe "#alias_command" do
      it "registers the class with the command registry" do
        Translator::SmsCommand.command_registry.should include_key :x
      end

    end
  end
end

Yes #alias_command does nothing at this stage but that's because I'm in the midst of developing it.  However, when I run my spec I am seeing...

SmsCommand initialized in ExampleCommand

so the module is certainly being mixed in, however the spec barfs on the alias_command :x line in the ExampleCommand as if the alias_command method is never becoming available.

/spec/translator/sms_command_spec.rb:5:in `<class:ExampleCommand>': undefined method `alias_command' for ExampleCommand:Class (NoMethodError)

I could solve this problem through inheritance though I'd prefer the mixin module.  What am I missing?

Body:
You want to define a class method called alias_command, don't you?
In this case you need to extend the class with the module, a simple include will turn the included method into an instance method!

You can do it in a widely accepted way as follows:

module Translator
  module SmsCommand
    def self.included(klass)
      puts "SmsCommand initialized in #{klass}"
      klass.extend ClassMethods
    end
    module ClassMethods
      def alias_command(name)
      end
    end
  end
end

This way when you include the module, it will automatically extend the target class with the class methods!


问:
Format the tick in plotly histogram's x-axis
I have the simple dataframe d below and I want to creata a histogram based on the frequency of its values. I am trying to set the inital value as 0 and then display the values in the x-axis by 5 but neither of those seems to work since values begin from 1 and then display 8. I would prefer a clear plotly solution on this as first choice, without ggplot() interference.

```<code>d<-data.frame(c(1,5,7,5,4,5,6,7,8,9,10,15,13))
x <- list(
  tick0=0,
  dtick=5

)

# Create the plotly histogram

plot_ly(alpha = 0.9) %>%
  add_histogram(x = as.factor(d[,1]),source="subset") %>%
  # Add titles in plot and axes
  layout(barmode = "overlay",xaxis=x,margin=list(b=100))
</code>```

答:
Something like the below approaches it a little differently but I think the result is what you are looking for.</p>

```<code>d<-data.frame(x = c(1,5,7,5,4,5,6,7,8,9,10,15,13))

gg <- ggplot(d, aes(x)) + geom_histogram() + stat_bin(breaks = c(0, 5, 10, 15), binwidth = 5)

ggplotly(gg)
</code>```

Body:
I have the simple dataframe d below and I want to creata a histogram based on the frequency of its values. I am trying to set the inital value as 0 and then display the values in the x-axis by 5 but neither of those seems to work since values begin from 1 and then display 8. I would prefer a clear plotly solution on this as first choice, without ggplot() interference.

d<-data.frame(c(1,5,7,5,4,5,6,7,8,9,10,15,13))
x <- list(
  tick0=0,
  dtick=5

)

# Create the plotly histogram

plot_ly(alpha = 0.9) %>%
  add_histogram(x = as.factor(d[,1]),source="subset") %>%
  # Add titles in plot and axes
  layout(barmode = "overlay",xaxis=x,margin=list(b=100))

Body:
Something like the below approaches it a little differently but I think the result is what you are looking for.

d<-data.frame(x = c(1,5,7,5,4,5,6,7,8,9,10,15,13))

gg <- ggplot(d, aes(x)) + geom_histogram() + stat_bin(breaks = c(0, 5, 10, 15), binwidth = 5)

ggplotly(gg)


问:
On pressing a button in panel, why is the data being sent twice, Is there a solution to only send it once?
If I press a radio button (send data) on Panel, the data is being sent twice or thrice, sometimes once, for the following code:

```<code>on sysvar RC::send_data

{
systemData.byte(0) = 0x01;

systemData.byte(1) = 0x01;

systemData.byte(2) = 0x01;

systemData.byte(3) = 0x01;

systemData.byte(4) = 0x01;

systemData.byte(5) = 0x01;

systemData.byte(6) = 0x01;

systemData.byte(7) = 0xFF;

output(systemData);
}
</code>```

I need to make it only sent once if I press once, how to achieve it?

And why is the data being sent multiple times randomly?

Expected:

```<code>Tx : 01010101010101FF
</code>```

Error Outcome:

```<code>Tx : 01010101010101FF
Tx : 01010101010101FF
</code>```

答:
When you press your button, the sysvar is set to a certain value. You can configure this value in the panel designer in property Pressed of the button.

When you release the button, the sysvar is set to a different value. You can configure this value in the panel designer on property Released of the button.

Your on sysvar event handler gets called once when pressing the button and once when releasing the button.

You could use an if-statement in your event handler to only react on certain values of the sysvar.

Body:
If I press a radio button (send data) on Panel, the data is being sent twice or thrice, sometimes once, for the following code:

on sysvar RC::send_data

{
systemData.byte(0) = 0x01;

systemData.byte(1) = 0x01;

systemData.byte(2) = 0x01;

systemData.byte(3) = 0x01;

systemData.byte(4) = 0x01;

systemData.byte(5) = 0x01;

systemData.byte(6) = 0x01;

systemData.byte(7) = 0xFF;

output(systemData);
}

I need to make it only sent once if I press once, how to achieve it?

And why is the data being sent multiple times randomly?

Expected:

Tx : 01010101010101FF

Error Outcome:

Tx : 01010101010101FF
Tx : 01010101010101FF


问:
Google Cloud Kubernetes Laravel Get Visitor IP
I'm trying to get visitor IP on my Laravel application that uses Nginx on Google Cloud Kubernetes Engine, under load balancer.

I have set up TrustProxies.php like this:

```<code><?php

namespace App\Http\Middleware;

use Illuminate\Http\Request;
use Fideloper\Proxy\TrustProxies as Middleware;

class TrustProxies extends Middleware
{
    /**
     * The trusted proxies for this application.
     *
     * @var array
     */
    protected $proxies = '*';

    /**
     * The headers that should be used to detect proxies.
     *
     * @var int
     */
    protected $headers = Request::HEADER_X_FORWARDED_ALL;
}
</code>```

I have also tried

```<code>protected $proxies = '**';
</code>```

And

```<code>protected $proxies = ['loadbalancer_ip_here'];
</code>```

No matter what I have tried, it will always return load balancer ip.

Might this be caused by Nginx configuration? Help appreciated.

答:
You have to set traffic policy in your nginx service

```<code>externalTrafficPolicy: "Local"
</code>```

and also

```<code>healthCheckNodePort: "numeric port number for the service"
</code>```

More details in Preserving the client source IP doc

Body:
I'm trying to get visitor IP on my Laravel application that uses Nginx on Google Cloud Kubernetes Engine, under load balancer.

I have set up TrustProxies.php like this:

<?php

namespace App\Http\Middleware;

use Illuminate\Http\Request;
use Fideloper\Proxy\TrustProxies as Middleware;

class TrustProxies extends Middleware
{
    /**
     * The trusted proxies for this application.
     *
     * @var array
     */
    protected $proxies = '*';

    /**
     * The headers that should be used to detect proxies.
     *
     * @var int
     */
    protected $headers = Request::HEADER_X_FORWARDED_ALL;
}

I have also tried

protected $proxies = '**';

And

protected $proxies = ['loadbalancer_ip_here'];

No matter what I have tried, it will always return load balancer ip.

Might this be caused by Nginx configuration? Help appreciated.

Body:
You have to set traffic policy in your nginx service

externalTrafficPolicy: "Local"

and also

healthCheckNodePort: "numeric port number for the service"

More details in Preserving the client source IP doc


问:
Simulink: How can I use object instances from workspace in an embedded matlab function?
In this case I have a neural network (NN) instance in my base workspace that I wish to use in a simulation with Simulink. I wrapped the use of the NN in an Embedded Matlab function with input arguments that should be used in by the net.

In principal I wish to do something like this:

```<code>function XBDDprime = NN(F, XB, XBD, XBDD)
%#eml
global net;
XBDDprime = net([F XB XBD XBDD]');
</code>```

Where the goal is to fetch the net object from base workspace (which is an instance of the class network).

This a swing at the problem where I used evalin to read the variable from workspace:

```<code>function XBDDprime = NN(F, XB, XBD, XBDD)
%#eml
eml.extrinsic('evalin');
net = evalin('base', 'net'); %Fetch net from workspace
XBDDprime = net([F XB XBD XBDD]'); %Error!
</code>```

This doesn't compile because it seems like simulink thinks net is an array and net(...) is array subscripting (actual error message: Subscripting into an mxArray is not supported).

It seems to me like Simulink needs to have a full definition of any object used to be able to compile the embedded matlab function, is that correct? Is there even a solution? Can I use Simulink.Signal somehow to wrap the NN and add that as an argument to the function block?

Edit

I tried using load as well to load the serialized net object from file. That didn't work either. Seems to be the same problem where the compiler thinks s is an mxArray.

```<code>function XBDDprime = NN(F, XB, XBD, XBDD)
%#eml
eml.extrinsic('load')
s = load('net');
XBDDprime = s.net([F XB XBD XBDD]');
</code>```

Solution

I finally caved and went for the matlab function block which can look like any of the examples above.

答: You could define the net parameter as an input of the NN function and use a From Workspace block to get it into your model. I'm not sure if this will work with an Embedded MATLAB function block, you might need to switch to an M Code block.

Body:
In this case I have a neural network (NN) instance in my base workspace that I wish to use in a simulation with Simulink. I wrapped the use of the NN in an Embedded Matlab function with input arguments that should be used in by the net.

In principal I wish to do something like this:

function XBDDprime = NN(F, XB, XBD, XBDD)
%#eml
global net;
XBDDprime = net([F XB XBD XBDD]');

Where the goal is to fetch the net object from base workspace (which is an instance of the class network).

This a swing at the problem where I used evalin to read the variable from workspace:

function XBDDprime = NN(F, XB, XBD, XBDD)
%#eml
eml.extrinsic('evalin');
net = evalin('base', 'net'); %Fetch net from workspace
XBDDprime = net([F XB XBD XBDD]'); %Error!

This doesn't compile because it seems like simulink thinks net is an array and net(...) is array subscripting (actual error message: Subscripting into an mxArray is not supported).

It seems to me like Simulink needs to have a full definition of any object used to be able to compile the embedded matlab function, is that correct? Is there even a solution? Can I use Simulink.Signal somehow to wrap the NN and add that as an argument to the function block?

Edit

I tried using load as well to load the serialized net object from file. That didn't work either. Seems to be the same problem where the compiler thinks s is an mxArray.

function XBDDprime = NN(F, XB, XBD, XBDD)
%#eml
eml.extrinsic('load')
s = load('net');
XBDDprime = s.net([F XB XBD XBDD]');

Solution

I finally caved and went for the matlab function block which can look like any of the examples above.


问:
Is there any difference between native-base <View/> and react-native <View/>?
I know native-base in a wrapper on react-native library but there are some components which we can import from react-native as well as from native-base also eg., View, Text, etc., Is there any difference between these two imported components. I am new to react native just want to know.</p>

答:
Native Base uses the original react native view and extends it a little bit.

Here is the full code from native base' view:

```<code>import React, { Component } from "react";
import PropTypes from "prop-types";
import { View, ViewPropTypes } from "react-native";
import { connectStyle } from "native-base-shoutem-theme";
import mapPropsToStyleNames from "../utils/mapPropsToStyleNames";

class ViewNB extends Component {
  render() {
    return <View ref={c => (this._root = c)} {...this.props} />;
  }
}

ViewNB.propTypes = {
  ...ViewPropTypes,
  style: PropTypes.oneOfType([
    PropTypes.object,
    PropTypes.number,
    PropTypes.array
  ])
};

const StyledViewNB = connectStyle(
  "NativeBase.ViewNB",
  {},
  mapPropsToStyleNames
)(ViewNB);
export { StyledViewNB as ViewNB };
</code>```

Source: https://github.com/GeekyAnts/NativeBase/blob/master/src/basic/View.js

Body:
Native Base uses the original react native view and extends it a little bit.

Here is the full code from native base' view:

import React, { Component } from "react";
import PropTypes from "prop-types";
import { View, ViewPropTypes } from "react-native";
import { connectStyle } from "native-base-shoutem-theme";
import mapPropsToStyleNames from "../utils/mapPropsToStyleNames";

class ViewNB extends Component {
  render() {
    return <View ref={c => (this._root = c)} {...this.props} />;
  }
}

ViewNB.propTypes = {
  ...ViewPropTypes,
  style: PropTypes.oneOfType([
    PropTypes.object,
    PropTypes.number,
    PropTypes.array
  ])
};

const StyledViewNB = connectStyle(
  "NativeBase.ViewNB",
  {},
  mapPropsToStyleNames
)(ViewNB);
export { StyledViewNB as ViewNB };

Source: https://github.com/GeekyAnts/NativeBase/blob/master/src/basic/View.js


问:
Call an excel macro in specific instance of excel in VBA
I'm receiving out of resources errors in 32-bit Excel 365 (64-bit remedies the problem but our IT won't allow it for the number of users that would use this book, so I'm stuck with 32-bit). I have plenty of RAM so I'm trying to split the two workbooks into different instances to allow more memory allocation (if this is a bad strategy I'd be happy to know why/alternatives!).

My set-up has two workbooks, Workbook A opens Workbook B and Workbook B runs the heavy lifting code and then transfers the data back to Workbook A in value format.

Excel Instance 1: Workbook A

Excel Instance 2: Workbook B

I want WkbA (open in Excel Instance 1) to call a macro on WrkB open in Excel Instance 2. I wrote the code below to try this.

```<code>Dim WkbB As Object
Set WkbB = New Excel.Application
With WkbB
    .Visible = True
    .Workbooks.Open "P:\Root\WorkbookB.xlsm", True, False
End With

Application.Run "'WkbB.xlsm'!Main"
</code>```

At the 'End With' line, the Code opens WkbA and WrkB in two separate Excel Instances as I want

Excel Instance 1: WrkA

Excel Instance 2: WrkB

But at the Application.Run line excel opens WrkB again in instance 1

Excel Instance 1: WrkA & WrkB

Excel Instance 2: WrkB

Instead of calling the Main subroutine in Instance 2 WorkbookB.

答:
Change

```<code>Application.Run "'WkbB.xlsm'!Main"
</code>```

to

```<code>WrkB.Run "'WorkbookB.xlsm'!Main"
</code>```

Body:
I'm receiving out of resources errors in 32-bit Excel 365 (64-bit remedies the problem but our IT won't allow it for the number of users that would use this book, so I'm stuck with 32-bit). I have plenty of RAM so I'm trying to split the two workbooks into different instances to allow more memory allocation (if this is a bad strategy I'd be happy to know why/alternatives!).

My set-up has two workbooks, Workbook A opens Workbook B and Workbook B runs the heavy lifting code and then transfers the data back to Workbook A in value format.

Excel Instance 1: Workbook A

Excel Instance 2: Workbook B

I want WkbA (open in Excel Instance 1) to call a macro on WrkB open in Excel Instance 2. I wrote the code below to try this.

Dim WkbB As Object
Set WkbB = New Excel.Application
With WkbB
    .Visible = True
    .Workbooks.Open "P:\Root\WorkbookB.xlsm", True, False
End With

Application.Run "'WkbB.xlsm'!Main"

At the 'End With' line, the Code opens WkbA and WrkB in two separate Excel Instances as I want

Excel Instance 1: WrkA

Excel Instance 2: WrkB

But at the Application.Run line excel opens WrkB again in instance 1

Excel Instance 1: WrkA & WrkB

Excel Instance 2: WrkB

Instead of calling the Main subroutine in Instance 2 WorkbookB.

Body:
Change

Application.Run "'WkbB.xlsm'!Main"

to

WrkB.Run "'WorkbookB.xlsm'!Main"


问:
Very simple map implemention in C (for caching purpose)?
I have a program that read urls in a file and does a gethostbyname() on each URL host. This call is quite consuming. I want to cache them.

Is there a very simple map-base code snippet in C out there that I could use to do the caching? (I just don't want to reinvent the wheel).

It has to have the following points :

Open-source with a permissive license (think BSD or public domain).

Very simple : ideally less than 100 LOC

Keys are char* and values void*. No need to copy them.

No real need to implement remove(), but contains() is either needed or put() should replace the value.

PS: I tagged it homework, since it could be. I'm just being very lazy and do want to avoid all the common pitfalls I could encounter while reimplementing.

答:
You can try using following implemntation

clib


问:
How to ask for confirmation and use e.PreventDefault on click event
I'm trying to implement some very basic (in my opinion) functionality with jQuery. I have Delete link:

```<code><a href="/Delete" class="prompt-for-delete">Delete</a>
</code>```

and all I want is when the link is clicked to show some kind of confirmation window like:

Are you sure you want to delete this : Yes/No

And if No is clicked I want to prevent the link from executing. I use jquery-1.10.2.min.js and
jquery-ui-1.10.3.min.js my HTML is:

```<code><div id="dialog-confirm" ></div>
<a href="/Delete" class="prompt-for-delete">Delete</a>
</code>```

I tried several options I found on the internet. The last one is:

```<code>$(document).ready(function () {

        $('.prompt-for-delete').click(function (e) {
            $("#dialog-confirm").dialog({
                resizable: false,
                height: 140,
                modal: true,
                buttons: {
                    "Delete all items": function () {
                        $(this).dialog("close");
                    },
                    Cancel: function () {
                        $(this).dialog("close");
                    }
                }
            });
        });

    });
</code>```

which is just to get something working but with this I get the dialog opened and automatically closed after a second. It seems like something very standard so could you provide an example of how to achieve this?

答:
```<code><a href="_blank" onclick="if(!confirm('Are you sure?')) event.preventDefault()">click</a>
</code>```

Body:
I'm trying to implement some very basic (in my opinion) functionality with jQuery. I have Delete link:

Delete

and all I want is when the link is clicked to show some kind of confirmation window like:

Are you sure you want to delete this : Yes/No

And if No is clicked I want to prevent the link from executing. I use jquery-1.10.2.min.js and
jquery-ui-1.10.3.min.js my HTML is:

Delete

I tried several options I found on the internet. The last one is:

$(document).ready(function () {

        $('.prompt-for-delete').click(function (e) {
            $("#dialog-confirm").dialog({
                resizable: false,
                height: 140,
                modal: true,
                buttons: {
                    "Delete all items": function () {
                        $(this).dialog("close");
                    },
                    Cancel: function () {
                        $(this).dialog("close");
                    }
                }
            });
        });

    });

which is just to get something working but with this I get the dialog opened and automatically closed after a second. It seems like something very standard so could you provide an example of how to achieve this?