问:
Why child process returns exit status = 32512 in unix?
In my program I'm executing given command and getting result (log, and exit status). Also my program have to support shell specific commands (i.e. commands which contains shell specific characters ~(tild),|(pipe),*). But when I try to run sh -c ls | wc in my home directory via my program it failed and its exit status was 32512, also in stderr stream "sh: ls | wc: command not found" was printed.

But the interesting thing is that the command sh -c ls | wc works correct if I run it in shell.

What is the problem? Or more preferable how can I run shell specific commands via my program (i.ec which command with which parameters should I run)?

The code part bellow is in child part after fork(). It executs the command.

tokenized_command is std::vector<std::string> where in my case "sh", "-c", "ls", "|", "wc" are stored, also I have tried to store there "sh", "-c", "\"ls | wc\"" but result is same. command is char * where full command line is stored.

```<code>        boost::shared_array<const char *> bargv(new const char *[tokenized_command.size() + 1]);
        const char **argv = bargv.get();
        for(int i = 0; i < tokenized_command.size(); ++i)
        {
            argv[i] = tokenized_command[i].c_str();
            printf("argv[%d]: %s\n", i, argv[i]); //trace
        }
        argv[tokenized_command.size()] = NULL;

        if(execvp(argv[0], (char * const *)argv) == -1)
        {
            fprintf(stderr, "Failed to execute command %s: %s", command, strerror(errno));
            _exit(EXIT_FAILURE);
        }
</code>```

P.S.

I know that using system(command) instead execvp can solve my problem. But system() waits until command is finished, and this is not good enough for my program. And also I'm sure that in implementation of system() one of exec-family functions is used, so the problem can be solved via exec as well, but I don't know how.

答:
execvp takes a path to an executable, and arguments with which to launch that executable. It doesn't take bourne shell commands.

ls | wc is a bourne shell command (among others), and it can't be broken down into the path to an executable and some arguments due to the use of a pipe. This means it can't be executed using execvp.

To execute a bourne shell command using execvp, one has to execute sh and pass -c and the command for arguments.

So you want to execute ls | wc using execvp.

```<code>char *const argv[] = {
    "sh",
    "-c", "ls | wc",  // Command to execute.
    NULL
};

execvp(argv[0], argv)
</code>```

You apparently tried

```<code>char *const argv[] = {
    "sh",
    "-c", "ls",  // Command to execute.
    "|",         // Stored in called sh's $0.
    "wc",        // Stored in called sh's $1.
    NULL
};
</code>```

That would be the same as bourne shell command sh -c ls '|' wc.

And both are very different than shell command sh -c ls | wc. That would be

```<code>char *const argv[] = {
    "sh",
    "-c", "sh -c ls | wc",  // Command to execute.
    NULL
};
</code>```

You seem to think | and wc are passed to the sh, but that's not the case at all. | is a special character which results in a pipe, not an argument.

As for the exit code,

```<code>Bits 15-8 = Exit code.
Bit     7 = 1 if a core dump was produced.
Bits  6-0 = Signal number that killed the process.
</code>```

32512 = 0x7F00

So it didn't die from a signal, a core dump wasn't produced, and it exited with code 127 (0x7F).

What 127 means is unclear, which is why it should accompanied by an error message. You tried to execute program ls | wc, but there is no such program.

Body:
In my program I'm executing given command and getting result (log, and exit status). Also my program have to support shell specific commands (i.e. commands which contains shell specific characters ~(tild),|(pipe),*). But when I try to run sh -c ls | wc in my home directory via my program it failed and its exit status was 32512, also in stderr stream "sh: ls | wc: command not found" was printed.

But the interesting thing is that the command sh -c ls | wc works correct if I run it in shell.

What is the problem? Or more preferable how can I run shell specific commands via my program (i.ec which command with which parameters should I run)?

The code part bellow is in child part after fork(). It executs the command.

tokenized_command is std::vector<std::string> where in my case "sh", "-c", "ls", "|", "wc" are stored, also I have tried to store there "sh", "-c", "\"ls | wc\"" but result is same. command is char * where full command line is stored.

        boost::shared_array<const char *> bargv(new const char *[tokenized_command.size() + 1]);
        const char **argv = bargv.get();
        for(int i = 0; i < tokenized_command.size(); ++i)
        {
            argv[i] = tokenized_command[i].c_str();
            printf("argv[%d]: %s\n", i, argv[i]); //trace
        }
        argv[tokenized_command.size()] = NULL;

        if(execvp(argv[0], (char * const *)argv) == -1)
        {
            fprintf(stderr, "Failed to execute command %s: %s", command, strerror(errno));
            _exit(EXIT_FAILURE);
        }

P.S.

I know that using system(command) instead execvp can solve my problem. But system() waits until command is finished, and this is not good enough for my program. And also I'm sure that in implementation of system() one of exec-family functions is used, so the problem can be solved via exec as well, but I don't know how.

Body:
execvp takes a path to an executable, and arguments with which to launch that executable. It doesn't take bourne shell commands.

ls | wc is a bourne shell command (among others), and it can't be broken down into the path to an executable and some arguments due to the use of a pipe. This means it can't be executed using execvp.

To execute a bourne shell command using execvp, one has to execute sh and pass -c and the command for arguments.

So you want to execute ls | wc using execvp.

char *const argv[] = {
    "sh",
    "-c", "ls | wc",  // Command to execute.
    NULL
};

execvp(argv[0], argv)

You apparently tried

char *const argv[] = {
    "sh",
    "-c", "ls",  // Command to execute.
    "|",         // Stored in called sh's $0.
    "wc",        // Stored in called sh's $1.
    NULL
};

That would be the same as bourne shell command sh -c ls '|' wc.

And both are very different than shell command sh -c ls | wc. That would be

char *const argv[] = {
    "sh",
    "-c", "sh -c ls | wc",  // Command to execute.
    NULL
};

You seem to think | and wc are passed to the sh, but that's not the case at all. | is a special character which results in a pipe, not an argument.

As for the exit code,

Bits 15-8 = Exit code.
Bit     7 = 1 if a core dump was produced.
Bits  6-0 = Signal number that killed the process.

32512 = 0x7F00

So it didn't die from a signal, a core dump wasn't produced, and it exited with code 127 (0x7F).

What 127 means is unclear, which is why it should accompanied by an error message. You tried to execute program ls | wc, but there is no such program.


来源: stackexchange

问:
new variable multiple if/then code from sas to r
I would like to transform in R this sas code to create a new variable from an existing one:

```<code>if eta=0 then eta1=0;
if 0<eta<=4 then eta1=1;
if 4<eta<=9 then eta1=2;
if 9<eta<=14 then eta1=3;
if 14<eta<=19 then eta1=4;
if 19<eta<=24 then eta1=5;
if 24<eta<=29 then eta1=6;
</code>```

.... and so on..

I tried with ifelse but here my new variable eta1 is not binary..

then i tried this:

```<code>eta1[eta<1]<- 0
eta1[eta>=1 & eta<=4]<- 1
eta1[eta>=5 & eta<=9]<- 2
</code>```

and this:

```<code>pop%>%
  mutate(
    eta1=case_when(
      eta%in% c(1,2,3,4)~1,
      eta%in% c(5,6,7,8,9)~2

    )
  )
</code>```

and this

```<code>pop%>%
  mutate(
    eta1=case_when(
      eta%in% c("1","2","3","4")~"1",
      eta%in% c("5","6","7","8","9")~"2"

    )
  )
</code>```

but these don't work..
so I can't understand how to create it without losing infos

How can I fix it?

Thank you!

答:
I believe a simple solution would be to create a data frame for the transformation (eta to eta1):

```<code>eta2eta1 <- data.frame(eta = 0:29,
       eta1 = c(0, rep(1, 4), rep(2, 5), rep(3, 5), rep(4, 5), rep(5, 5), rep(6, 5)))
</code>```

```<code>eta eta1
0    0
1    1
2    1
3    1
4    1
5    2
6    2
7    2
8    2
9    2
[...]
</code>```

And then merge the datasets using simply left_join:

```<code># install.packages("tidyverse") # if needed
library(tidyverse)

left_join(originaldata, eta2eta1, by = "eta")

</code>```

if-else statements

A more burdensome solution, in my opinion, would be to use ifelse statements, such as:

```<code>originaldata %>%
  mutate(eta1 = ifelse(eta == 0, 0,
                ifelse(eta %in% 1:4, 1,
                ifelse(eta %in% 5:9, 2,
                ifelse(eta %in% 10:14, 3,
                ifelse(eta %in% 15:19, 4,
                ifelse(eta %in% 20:24, 5, 6)))))))
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I would like to transform in R this sas code to create a new variable from an existing one:

if eta=0 then eta1=0;
if 0<eta<=4 then eta1=1;
if 4<eta<=9 then eta1=2;
if 9<eta<=14 then eta1=3;
if 14<eta<=19 then eta1=4;
if 19<eta<=24 then eta1=5;
if 24<eta<=29 then eta1=6;

.... and so on..

I tried with ifelse but here my new variable eta1 is not binary..

then i tried this:

eta1[eta<1]<- 0
eta1[eta>=1 & eta<=4]<- 1
eta1[eta>=5 & eta<=9]<- 2

and this:

pop%>%
  mutate(
    eta1=case_when(
      eta%in% c(1,2,3,4)~1,
      eta%in% c(5,6,7,8,9)~2

    )
  )

and this

pop%>%
  mutate(
    eta1=case_when(
      eta%in% c("1","2","3","4")~"1",
      eta%in% c("5","6","7","8","9")~"2"

    )
  )

but these don't work..
so I can't understand how to create it without losing infos

How can I fix it?

Thank you!

Body:
I believe a simple solution would be to create a data frame for the transformation (eta to eta1):

eta2eta1 <- data.frame(eta = 0:29,
       eta1 = c(0, rep(1, 4), rep(2, 5), rep(3, 5), rep(4, 5), rep(5, 5), rep(6, 5)))

eta eta1
0    0
1    1
2    1
3    1
4    1
5    2
6    2
7    2
8    2
9    2
[...]

And then merge the datasets using simply left_join:

# install.packages("tidyverse") # if needed
library(tidyverse)

left_join(originaldata, eta2eta1, by = "eta")

if-else statements

A more burdensome solution, in my opinion, would be to use ifelse statements, such as:

originaldata %>%
  mutate(eta1 = ifelse(eta == 0, 0,
                ifelse(eta %in% 1:4, 1,
                ifelse(eta %in% 5:9, 2,
                ifelse(eta %in% 10:14, 3,
                ifelse(eta %in% 15:19, 4,
                ifelse(eta %in% 20:24, 5, 6)))))))


问:
Cannot make predictions after recursive feature elimination
I have carried out recursive feature elimination on my dataset and now trying to make predictions based on the features that are returned by my RFE but keep encountering this error:

```<code>ValueError: X has 31 features per sample; expecting 9
</code>```

This is the code I have written to get the optimal features and transform my data based on the features returned

```<code>no_list = np.arange(1,len(list(dat)))
acc_score = 0
n_features = 0
score_list = []
for x in range(len(no_list)):
    X_train,X_test,y_train,y_test = train_test_split(X,y,test_size = 0.2,random_state=100)
    log_reg = LogisticRegression()
    rfe = RFE(log_reg,no_list[x])
    X_train_rfe = rfe.fit_transform(X_train,y_train)
    X_test_rfe = rfe.transform(X_test)
    log_reg.fit(X_train_rfe,y_train)
    score = log_reg.score(X_test_rfe,y_test)
    score_list.append(score)
    if(score > acc_score):
        acc_score = score
        n_features = no_list[x]
rfe = RFE(log_reg,n_features)
rfe.fit_transform(X_train,y_train)
predictions = rfe.predict(X_test)
</code>```

答:
Transform your X_test before sending it into predict. Your rfe uses the log_reg model that only take n_features.

```<code>rfe = RFE(log_reg,n_features)
rfe.fit_transform(X_train,y_train)
X_test = rfe.transform(X_test)
predictions = rfe.predict(X_test)
</code>```

Body:
I have carried out recursive feature elimination on my dataset and now trying to make predictions based on the features that are returned by my RFE but keep encountering this error:

ValueError: X has 31 features per sample; expecting 9

This is the code I have written to get the optimal features and transform my data based on the features returned

no_list = np.arange(1,len(list(dat)))
acc_score = 0
n_features = 0
score_list = []
for x in range(len(no_list)):
    X_train,X_test,y_train,y_test = train_test_split(X,y,test_size = 0.2,random_state=100)
    log_reg = LogisticRegression()
    rfe = RFE(log_reg,no_list[x])
    X_train_rfe = rfe.fit_transform(X_train,y_train)
    X_test_rfe = rfe.transform(X_test)
    log_reg.fit(X_train_rfe,y_train)
    score = log_reg.score(X_test_rfe,y_test)
    score_list.append(score)
    if(score > acc_score):
        acc_score = score
        n_features = no_list[x]
rfe = RFE(log_reg,n_features)
rfe.fit_transform(X_train,y_train)
predictions = rfe.predict(X_test)

Body:
Transform your X_test before sending it into predict. Your rfe uses the log_reg model that only take n_features.

rfe = RFE(log_reg,n_features)
rfe.fit_transform(X_train,y_train)
X_test = rfe.transform(X_test)
predictions = rfe.predict(X_test)


问:
Counting particular words
I'm working on a function that can count the number of words (including contractions like couldn't) in a list having exactly five letters.

I searched the internet for a similar issue but came up empty-handed.

```<code>def word_count(wlist):
    """ This function counts the number of words (including contractions like couldn't) in a list w/ exactly 5
        letters."""
    w = 0
    for word in x:
        w += 1 if len(word) == 5 else 0
    return w

x = ["adsfe", "as", "jkiejjl", "jsengd'e", "jjies"]
print(word_count(x))
</code>```

I'd like this function to count the number of words (including contractions like couldn't) in a list w/ exactly five letters. Any feedback is appreciated.

答:
A compact alternative with a smaller memory-footprint:

```<code>def word5(wlist, n=5):
    return sum((1 for word in wlist if len(word) == n))
</code>```

This also works but is about 2.5 times slower:

```<code>def word5(wlist, n=5):
    return sum((int(len(word) == n) for word in wlist))
</code>```

Title: Counting particular words

Body:
I'm working on a function that can count the number of words (including contractions like couldn't) in a list having exactly five letters.

I searched the internet for a similar issue but came up empty-handed.

def word_count(wlist):
    """ This function counts the number of words (including contractions like couldn't) in a list w/ exactly 5
        letters."""
    w = 0
    for word in x:
        w += 1 if len(word) == 5 else 0
    return w

x = ["adsfe", "as", "jkiejjl", "jsengd'e", "jjies"]
print(word_count(x))

I'd like this function to count the number of words (including contractions like couldn't) in a list w/ exactly five letters. Any feedback is appreciated.

Body:
A compact alternative with a smaller memory-footprint:

def word5(wlist, n=5):
    return sum((1 for word in wlist if len(word) == n))

This also works but is about 2.5 times slower:

def word5(wlist, n=5):
    return sum((int(len(word) == n) for word in wlist))


问:
how to fix django admin "You don't have permission to view or edit anything."?
for the sake of customizing the default admin site , i have made the following changes:

```<code>admin.py:

class CustomAdminSite(admin.AdminSite):

def get_urls(self):
    urls = super(CustomAdminSite, self).get_urls()
    custom_urls = [
        # re_path(r'^.*\.html', views.custom_admin_template_loader, name='custom-loader'),

        url(r'^.*\.html', self.admin_view(self.my_view), name="my-view"),
    ]
    return urls + custom_urls

def my_view(self, request):
    context = {}
    load_template = request.path.split('/')[-1]
    template = loader.get_template('admin/' + load_template)
    request.current_app = self.name
    return HttpResponse(template.render(context, request))
</code>```

```<code>    apps.py:
from django.contrib.admin.apps import AdminConfig

class MyAdminConfig(AdminConfig):
    default_site = 'myproject.admin.CustomAdminSite'
</code>```

```<code>settings.py:

INSTALLED_APPS = [
    'myproject.apps.MyAdminConfig',
</code>```

nothing changed in urls.py

so if i access admin/ it works , but if i access another template using the view i made , it says You don't have permission to edit anything , how to fix it?
for clarifications on WHY i m using that view, it is because i overrided the default admin templates and now i have a navigation bar , which means i need to navigate through different html files (templates)

答:
Solution :

i needed to pass context + set the request.current_app , (added in my custom view)

```<code>    context = {
        **self.each_context(request),
        'title': self.index_title,
        'app_list': app_list,
    }

    request.current_app = self.name
</code>```

Body:
for the sake of customizing the default admin site , i have made the following changes:

admin.py:

class CustomAdminSite(admin.AdminSite):

def get_urls(self):
    urls = super(CustomAdminSite, self).get_urls()
    custom_urls = [
        # re_path(r'^.*\.html', views.custom_admin_template_loader, name='custom-loader'),

        url(r'^.*\.html', self.admin_view(self.my_view), name="my-view"),
    ]
    return urls + custom_urls

def my_view(self, request):
    context = {}
    load_template = request.path.split('/')[-1]
    template = loader.get_template('admin/' + load_template)
    request.current_app = self.name
    return HttpResponse(template.render(context, request))

    apps.py:
from django.contrib.admin.apps import AdminConfig

class MyAdminConfig(AdminConfig):
    default_site = 'myproject.admin.CustomAdminSite'

settings.py:

INSTALLED_APPS = [
    'myproject.apps.MyAdminConfig',

nothing changed in urls.py

so if i access admin/ it works , but if i access another template using the view i made , it says You don't have permission to edit anything , how to fix it?
for clarifications on WHY i m using that view, it is because i overrided the default admin templates and now i have a navigation bar , which means i need to navigate through different html files (templates)

Body:
Solution :

i needed to pass context + set the request.current_app , (added in my custom view)

    context = {
        **self.each_context(request),
        'title': self.index_title,
        'app_list': app_list,
    }

    request.current_app = self.name


问:
How to replace a certain word from a string with another one and excluding certain types of said word in atom regex
I'm using atom to try and find the word "Next" and replace it with the word "Continue", but only when the string starts with "al "" (the space and the quotation mark are important)

I've tried to use atom's Regex find and replace tool to accomplish this and I believe I'm quite close. The code below managed to find the strings I wanted, but I'm not sure how the replace code should go.

(al \")(.*Next)

I've tried fiddling with the $1 and $2 thingies, but I just can't seem to figure this out :(

答:
You should re-arrange the first capturing group bounds and remove the second one:

```<code>(al ".*)Next
</code>```

Then, replace with $1Continue. See the regex demo and the regex graph:

Details

(al ".*) - Capturing group #1: al, space, " and then any 0+ chars other than line break chars

Next - a Next substring.

Note we capture what we need to keep and just match what we want to remove.

Body:
You should re-arrange the first capturing group bounds and remove the second one:

(al ".*)Next

Then, replace with $1Continue. See the regex demo and the regex graph:

Details

(al ".*) - Capturing group #1: al, space, " and then any 0+ chars other than line break chars

Next - a Next substring.

Note we capture what we need to keep and just match what we want to remove.


问:
Duplicate entries in the list
Having to enter 8 unique entries, logic should detect if any entry is duplicate otherwise continue until all 8 entries are entered.

I've played around with the For loop but it seems to not give me desired output, i want to go back to last entry if duplicate entry is scanned instead it will give a message "Duplicate SCAN, please rescan" but also the counter moves on.

sorry, i'm new to this i thought i've included code. Hoping it goes through this time.

```<code>x=1
mac_list = []
while (x <=8):
    MAC1 = input("SCAN MAC"+str(x)+":")

for place in mac_list:

    print (mac_list)
    if place==MAC1:
        print ("place"+place)
        print ("Duplicate SCAN, please rescan")
else:
    mac_list.append(MAC1)
    x+=1
</code>```

答:
Store the entries in a set, check if the set has fewer than 8 elements. If it does not, break the loop.</p>

```<code>entries = set()
counter = 0

while len(entries) < 8:
    counter += 1
    entries.add(input("Enter an item: "))
</code>```

Title: Duplicate entries in the list

Body:
Having to enter 8 unique entries, logic should detect if any entry is duplicate otherwise continue until all 8 entries are entered.

I've played around with the For loop but it seems to not give me desired output, i want to go back to last entry if duplicate entry is scanned instead it will give a message "Duplicate SCAN, please rescan" but also the counter moves on.

sorry, i'm new to this i thought i've included code. Hoping it goes through this time.

x=1
mac_list = []
while (x <=8):
    MAC1 = input("SCAN MAC"+str(x)+":")

for place in mac_list:

    print (mac_list)
    if place==MAC1:
        print ("place"+place)
        print ("Duplicate SCAN, please rescan")
else:
    mac_list.append(MAC1)
    x+=1

Body:
Store the entries in a set, check if the set has fewer than 8 elements. If it does not, break the loop.

entries = set()
counter = 0

while len(entries) < 8:
    counter += 1
    entries.add(input("Enter an item: "))


问:
How do you in SAS return the list of all columns in all tables in a library that contain a target value?
I am trying to map out fields I see in an application to columns in the source database using SAS EG.

If I search for 'SomeString' or someNumericValue in Library = SomeLibrary
I want the code to output a table that lists the tableName ColumnName that contains the value searched.

Proc SQL:
Select * columns C from all tables in Library L that contain the value or string = 'SomeValue'

答:
Great challenge!  I can get you some of the way there - the mp_searchdata macro of the SASjs macro core library will query all tables in a library (source database) for a string or numeric value.  It returns all columns, but will filter for only matching records.

To execute:

```<code>/* import library */
filename mc url "https://raw.githubusercontent.com/sasjs/core/main/all.sas";
%inc mc;

/* run macro */
%mp_searchdata(lib=yourlib, string=SomeString)
</code>```

Body:
Great challenge!  I can get you some of the way there - the mp_searchdata macro of the SASjs macro core library will query all tables in a library (source database) for a string or numeric value.  It returns all columns, but will filter for only matching records.

To execute:

/* import library */
filename mc url "https://raw.githubusercontent.com/sasjs/core/main/all.sas";
%inc mc;

/* run macro */
%mp_searchdata(lib=yourlib, string=SomeString)


问:
JSF: How to let #{...} expansion not be escaped?
I have a custom EL function (defined in myfunctions.taglib.xml) which returns a chunk of HTML, I want to copy it verbatim to the output,

```<code><f:verbatim>
    #{mylib:generateHtml()}
</f:verbatim>
</code>```

however, the expansion of #{...} is always escaped. How to make it not be escaped?

答:
Use <h:outputText escape="false" />. The <f:verbatim> serves an entirely different purpose specifically for JSP views and is dangerous on Facelets and is deprecated in JSF 2.0.

```<code><h:outputText value="#{bean.html}" escape="false" />
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have a custom EL function (defined in myfunctions.taglib.xml) which returns a chunk of HTML, I want to copy it verbatim to the output,

<f:verbatim>
    #{mylib:generateHtml()}
</f:verbatim>

however, the expansion of #{...} is always escaped. How to make it not be escaped?

Body:
Use <h:outputText escape="false" />. The <f:verbatim> serves an entirely different purpose specifically for JSP views and is dangerous on Facelets and is deprecated in JSF 2.0.

<h:outputText value="#{bean.html}" escape="false" />


问:
How can i check specific server running or not(using virsh commands), before I start | restart it?
I'm trying to restart, start, shutdown a specific virtual machine.
Here, at first I want to check if the virtual machine is already in required state or not before I run the script.

These are the list of VMs.

```<code>[root@demohost05 ~]# virsh list --all
Id    Name                           State
----------------------------------------------------
5     OwnCloud01                     running
6     OwnCloud02                     running
7     SiteMon                        running
-     vmtest                         shut off
</code>```

I want to check if vmtest is runnnig or not before I implement

```<code>virsh start vmtest
</code>```

How can check the status using if condition in shell script ?

How can I avoid to enter password when I've to use sudo command.

```<code>sudo virsh start vmtest
</code>```

I also tried to give root permission using

```<code>sudo -i
virsh start vmtest
</code>```

But script ends without implementing 2nd line.
How can I use both commands in same script file?

```<code>if [conditions]
then
{

}
fi
</code>```

I couldnt figure out how to check conditions for such scripts.

Thank you.

答:
I like Sharad's answer but I reversed it into a busy loop while waiting for a VM to shutdown

```<code>    virsh shutdown $VM
    state=$(virsh list --all | grep " $VM " | awk '{ print $3}')
    while ([ "$state" != "" ] && [ "$state" == "running" ]); do
      sleep 10
      state=$(virsh list --all | grep " $VM " | awk '{ print $3}')
    done;
    # now do something else to the shutdown VM and finally restart it
    virsh start $VM
</code>```

In my case I create a snapshot when the VM is shut down, then I restart it. I hard-coded a 10 second sleep into the loop because it seems like a reasonable retry period, given that a Windows VM could take a long time if it is installing updates - could be several minutes or even longer.

Body:
I'm trying to restart, start, shutdown a specific virtual machine.
Here, at first I want to check if the virtual machine is already in required state or not before I run the script.

These are the list of VMs.

[root@demohost05 ~]# virsh list --all
Id    Name                           State
----------------------------------------------------
5     OwnCloud01                     running
6     OwnCloud02                     running
7     SiteMon                        running
-     vmtest                         shut off

I want to check if vmtest is runnnig or not before I implement

virsh start vmtest

How can check the status using if condition in shell script ?

How can I avoid to enter password when I've to use sudo command.

sudo virsh start vmtest

I also tried to give root permission using

sudo -i
virsh start vmtest

But script ends without implementing 2nd line.
How can I use both commands in same script file?

if [conditions]
then
{

}
fi

I couldnt figure out how to check conditions for such scripts.

Thank you.

Body:
I like Sharad's answer but I reversed it into a busy loop while waiting for a VM to shutdown

    virsh shutdown $VM
    state=$(virsh list --all | grep " $VM " | awk '{ print $3}')
    while ([ "$state" != "" ] && [ "$state" == "running" ]); do
      sleep 10
      state=$(virsh list --all | grep " $VM " | awk '{ print $3}')
    done;
    # now do something else to the shutdown VM and finally restart it
    virsh start $VM

In my case I create a snapshot when the VM is shut down, then I restart it. I hard-coded a 10 second sleep into the loop because it seems like a reasonable retry period, given that a Windows VM could take a long time if it is installing updates - could be several minutes or even longer.


问:
i have a dataset where the target variable has 15% null values and i want to use those null rows as my test set is it possible?
i am using machine learning algorithm linear regression for predicting the values of real estate sale price and keeping the sale price as my target variable .But sale price has 15% null values in it so can i use that 15 % as my test set and the nun-null values as my training set?</p>

答: Yes, you can do this but since you dont have the real values for that test set, you will not be able to evaluate the performance of your model. There wont be any ground truth to evaluate against. I would suggest to use non-null data in a 80-10-10 split for train-validatiton-test and check accuracy. If this accuracy is good, then use this model to predict null values and then use the entire non-null data to train and then use that model to predict null data again. Then evaluate the predictions from both and you will have perfect evaluation and results.</p>


问:
Assigning named type to literal type value
Go newbie here. I am trying to assign an uint64  value to a variable of a named type with underlying type unit64. Compiler is unhappy and can't see the two types are exactly the same. What's the right way to do this?

```<code>package main

import "fmt"
import "math/rand"

type myType uint64

var x myType

func main() {
    x = rand.Uint64()
    fmt.Println(x)
}
</code>```

This throws compiler error:

```<code>./prog.go:12:4: cannot use rand.Uint64() (type uint64) as type myType in assignment
</code>```

答: You can convert it myType(rand.Uint64()). Usefull links: Type Assertion in Go and Type Conversion in Go as well as an excellent answer in this stack overflow question "How to cast to a type alias in go"

Body:
Go newbie here. I am trying to assign an uint64  value to a variable of a named type with underlying type unit64. Compiler is unhappy and can't see the two types are exactly the same. What's the right way to do this?

package main

import "fmt"
import "math/rand"

type myType uint64

var x myType

func main() {
    x = rand.Uint64()
    fmt.Println(x)
}

This throws compiler error:

./prog.go:12:4: cannot use rand.Uint64() (type uint64) as type myType in assignment


问:
Why POST in red language change the first character of parameters to upper-case automaticlly?
For the following simple code,

```<code>Red []

#include %tools.red

url: to url! rejoin ["http://somesite.com:7466/japi"]

response: write url [
        post [
        Content-Type: "application/json"
        req: "requestinfo"
        list: "This is a pie."
    ]
    {}
]

print response
</code>```

The result is something like:

{"Status":"fail","Value":"unknown request: \u0026{POST /japi HTTP/1.1
  1 1 map[Accept:[/] Content-Type:[application/json] Req:[requestinfo]
  List:[This is a pie.] Content-Length:[0]] {} \u003cnil\u003e 0 []
  false somesite.com:7466 map[] map[] \u003cnil\u003e map[]
  176.116.100.233:31144 /japi \u003cnil\u003e \u003cnil\u003e \u003cnil\u003e 0xc0002a2640}"}

My question is, why the parameters (such as req, list) are automatically capitalized?

答:
The HTTP/1.1 RFC says in section 4.2:

Each header field consists of a name followed by a colon (":") and the field value. Field names are case-insensitive.

Therefore, capitalization of first character of header names has no side-effect on a compliant HTTP server.

Though, from the "parameters" term you are using, and the req: "requestinfo" part in your source code, I wonder if you are not trying to pass those information as POST data rather, by mistakenly putting them in the headers list. If that is the case, then the right way to pass them is:

```<code>Red []

#include %tools.red

url: http://somesite.com:7466/japi

response: write url [
    POST [Content-Type: "application/json"]
    "req=requestinfo&list=This%20is%20a%20pie."
]

print response
</code>```

Body:
For the following simple code,

Red []

#include %tools.red

url: to url! rejoin ["http://somesite.com:7466/japi"]

response: write url [
        post [
        Content-Type: "application/json"
        req: "requestinfo"
        list: "This is a pie."
    ]
    {}
]

print response

The result is something like:

{"Status":"fail","Value":"unknown request: \u0026{POST /japi HTTP/1.1
  1 1 map[Accept:[/] Content-Type:[application/json] Req:[requestinfo]
  List:[This is a pie.] Content-Length:[0]] {} \u003cnil\u003e 0 []
  false somesite.com:7466 map[] map[] \u003cnil\u003e map[]
  176.116.100.233:31144 /japi \u003cnil\u003e \u003cnil\u003e \u003cnil\u003e 0xc0002a2640}"}

My question is, why the parameters (such as req, list) are automatically capitalized?

Body:
The HTTP/1.1 RFC says in section 4.2:

Each header field consists of a name followed by a colon (":") and the field value. Field names are case-insensitive.

Therefore, capitalization of first character of header names has no side-effect on a compliant HTTP server.

Though, from the "parameters" term you are using, and the req: "requestinfo" part in your source code, I wonder if you are not trying to pass those information as POST data rather, by mistakenly putting them in the headers list. If that is the case, then the right way to pass them is:

Red []

#include %tools.red

url: http://somesite.com:7466/japi

response: write url [
    POST [Content-Type: "application/json"]
    "req=requestinfo&list=This%20is%20a%20pie."
]

print response


问:
Is it possible to Let and Get with different data types in VBA?
I'm currently working on an Excel VBA Add-In to process a CSV export from one system into the format the stakeholders would like to view it in. I'm fairly new to OOP, but I thought it might be possible to convert priority types within the Let code and have the data stored in the same format it will be output in.

I've written the following class:

```<code>'Class Module "Project"
Option Explicit

Private m_sPriority As String

Property Let Priority(lInput As Long)
    Select Case lInput
        Case 1
            m_sPriority = "High"
        Case 2
            m_sPriority = "Medium"
        Case 3
            m_sPriority = "Low"
        Case Else
            m_sPriority = "No Priority"
    End Select
End Property

Property Get Priority() As String
    Priority = m_sPriority
End Property
</code>```

And this is the module to test it:

```<code>'Standard Module
Option Explicit

Sub test()
        Dim Project As Project
        Set Project = New Project

        Project.Priority = 1
        Debug.Print Project.Priority
End Sub
</code>```

I would expect to see "High" output to the console when running this.

Is there a way to accomplish this in VBA, or alternately, is my code malformed?

答:
Yes, your code is malformed. For whatever it's worth, you can't do that in .NET either - the syntax makes it rather unambiguous, whether in C#:

private string _priority;
public string Priority
{
    get { return _priority; }
    private set { _priority = value; }
}
```

<p>...or in VB:</p>

<pre class="lang-vb prettyprint-override"><code>Private _priority As String
Public Property Priority() As String
    Get
        Return _priority
    End Get
    Private Set(ByVal value As String)
        _priority = value
    End Set
End Property
</code>```

A property is either a Long or a String, it can't be both. Get/Let/Set accessors must be consistent, in VBA as well.

You can cheat by losing type safety and early binding, by making your property a Variant... but that's not really a good way to get started with OOP ;-)

```<code>Public Enum PriorityLevel
    NoPriority = 0
    HighPriority
    MediumPriority
    LowPriority
End Enum

Private Type InstanceState
    Priority As PriorityLevel
    '...
End Type

Private this As InstanceState

Public Property Get Priority() As Variant
    Priority = PriorityName(this.Priority)
End Property

Public Property Let Priority(ByVal value As Variant)
    this.Priority = value
End Property

Private Function PriorityName(ByVal value As PriorityLevel) As String
    Select Case value
        Case HighPriority
            PriorityName = "High"
        Case MediumPriority
            PriorityName = "Medium"
        Case LowPriority
            PriorityName= "Low"
        Case Else
            PriorityName= "Undefined"
    End Select
End Function
</code>```

While this works perfectly fine and looks pretty neat on the surface, consuming this class when you haven't written it is definitely going to be surprising: if you set (Let) a Long, you rightfully expect to Get a Long too. This class is begging for a PriorityName get-only property:

```<code>Public Property Get Priority() As PriorityLevel
    Priority = this.Priority
End Property

Public Property Let Priority(ByVal value As PriorityLevel)
    this.Priority = value
End Property

Public Property Get PriorityName() As String
    Select Case this.Priority
        Case HighPriority
            PriorityName = "High"
        Case MediumPriority
            PriorityName = "Medium"
        Case LowPriority
            PriorityName = "Low"
        Case Else
            PriorityName = "Undefined"
    End Select
End Property
</code>```

Now, the benefits of early binding and type safety (whatever little of it you get to leverage in VBA) are immediately apparent: when you write code that assigns the Priority property of an object of this type, IntelliSense for the Enum type guides the writing of the expression:

Moreover, the Enum is abstracting the underlying numeric value, which becomes irrelevant: instead of a magic hard-coded 1, the code now says HighPriority. Also, the Get accessor is as simple as it gets, which is very good: a Get accessor should never raise any errors, so the simpler, the better.

Morale of the story: don't hack around type safety if you can help it, do everything you can to keep your code early-bound - avoid Object and Variant as much as possible; cast Object to a known class/interface everywhere you can.

For example prefer this:

```<code>Dim sheet As Worksheet
' Workbook.Worksheets(index) returns Object; casting it to Worksheet
Set sheet = ActiveWorkbook.Worksheets(1)
sheet.Range("A1").Value = 42
</code>```

To this:

```<code>' "Range("A1").Value" is entirely late-bound. Beware of typos!
ActiveWorkbook.Worksheets(1).Range("A1").Value = 42
</code>```

Body:
I'm currently working on an Excel VBA Add-In to process a CSV export from one system into the format the stakeholders would like to view it in. I'm fairly new to OOP, but I thought it might be possible to convert priority types within the Let code and have the data stored in the same format it will be output in.

I've written the following class:

'Class Module "Project"
Option Explicit

Private m_sPriority As String

Property Let Priority(lInput As Long)
    Select Case lInput
        Case 1
            m_sPriority = "High"
        Case 2
            m_sPriority = "Medium"
        Case 3
            m_sPriority = "Low"
        Case Else
            m_sPriority = "No Priority"
    End Select
End Property

Property Get Priority() As String
    Priority = m_sPriority
End Property

And this is the module to test it:

'Standard Module
Option Explicit

Sub test()
        Dim Project As Project
        Set Project = New Project

        Project.Priority = 1
        Debug.Print Project.Priority
End Sub

I would expect to see "High" output to the console when running this.

Is there a way to accomplish this in VBA, or alternately, is my code malformed?

Body:
Yes, your code is malformed. For whatever it's worth, you can't do that in .NET either - the syntax makes it rather unambiguous, whether in C#:

private string _priority;
public string Priority
{
    get { return _priority; }
    private set { _priority = value; }
}

...or in VB:

Private _priority As String
Public Property Priority() As String
    Get
        Return _priority
    End Get
    Private Set(ByVal value As String)
        _priority = value
    End Set
End Property

A property is either a Long or a String, it can't be both. Get/Let/Set accessors must be consistent, in VBA as well.

You can cheat by losing type safety and early binding, by making your property a Variant... but that's not really a good way to get started with OOP ;-)

Public Enum PriorityLevel
    NoPriority = 0
    HighPriority
    MediumPriority
    LowPriority
End Enum

Private Type InstanceState
    Priority As PriorityLevel
    '...
End Type

Private this As InstanceState

Public Property Get Priority() As Variant
    Priority = PriorityName(this.Priority)
End Property

Public Property Let Priority(ByVal value As Variant)
    this.Priority = value
End Property

Private Function PriorityName(ByVal value As PriorityLevel) As String
    Select Case value
        Case HighPriority
            PriorityName = "High"
        Case MediumPriority
            PriorityName = "Medium"
        Case LowPriority
            PriorityName= "Low"
        Case Else
            PriorityName= "Undefined"
    End Select
End Function

While this works perfectly fine and looks pretty neat on the surface, consuming this class when you haven't written it is definitely going to be surprising: if you set (Let) a Long, you rightfully expect to Get a Long too. This class is begging for a PriorityName get-only property:

Public Property Get Priority() As PriorityLevel
    Priority = this.Priority
End Property

Public Property Let Priority(ByVal value As PriorityLevel)
    this.Priority = value
End Property

Public Property Get PriorityName() As String
    Select Case this.Priority
        Case HighPriority
            PriorityName = "High"
        Case MediumPriority
            PriorityName = "Medium"
        Case LowPriority
            PriorityName = "Low"
        Case Else
            PriorityName = "Undefined"
    End Select
End Property

Now, the benefits of early binding and type safety (whatever little of it you get to leverage in VBA) are immediately apparent: when you write code that assigns the Priority property of an object of this type, IntelliSense for the Enum type guides the writing of the expression:

Moreover, the Enum is abstracting the underlying numeric value, which becomes irrelevant: instead of a magic hard-coded 1, the code now says HighPriority. Also, the Get accessor is as simple as it gets, which is very good: a Get accessor should never raise any errors, so the simpler, the better.

Morale of the story: don't hack around type safety if you can help it, do everything you can to keep your code early-bound - avoid Object and Variant as much as possible; cast Object to a known class/interface everywhere you can.

For example prefer this:

Dim sheet As Worksheet
' Workbook.Worksheets(index) returns Object; casting it to Worksheet
Set sheet = ActiveWorkbook.Worksheets(1)
sheet.Range("A1").Value = 42

To this:

' "Range("A1").Value" is entirely late-bound. Beware of typos!
ActiveWorkbook.Worksheets(1).Range("A1").Value = 42


问:
Is Disney's FastPass Valid and/or Useful Queue Theory
At Disney World, they use a system called Fastpass to create a second, shorter line for popular rides.  The idea is that you can wait in the standard line, often with a wait longer than an hour, or you can get a FastPass which allows you to come back during a specified time block (usually a couple hours later) and only wait for 10 minutes or less.  You can only be "waiting" for one ride at a time with a FastPass.

I have been trying to figure out the queue theory behind this concept, but the only explanation I have found is that it is designed to get people out of the lines and doing things that will bring in additional revenue (shopping, eating, etc).

Is this why FastPass was implemented, or is there a real visitor efficiency problem that it solving?  Are there software applications that have applied similar logic?  Are there software applications that should apply similar logic?

Part of the problem I see with implementing something similar in software is that it is based on users choosing their queue.  Do to the faster wait cycles in software, I think a good application of this theory would require the application to be smart enough to know what queues to place people in based on their needs without requiring end-user choice.

UPDATE

12 years (and two major updates to FastPass later), Disney's FastPass: A Complicated History gives the in-depth, definitive answer of "it's complicated"

答:
You do not get on more rides. The lines for unpopular lines are longer now, because more people are killing time on them while waiting for their popular-ride passes to mature. Capacity is capacity. </p>

<p>"Twitter is currently really busy. Please come back between 15:00 and 15:15 and we guarantee to get you your tweets in 5 seconds or less."  </p>

OwnerDisplayName: Nathan Voxland

LastEditorDisplayName: Nathan Voxland

Body:
You do not get on more rides. The lines for unpopular lines are longer now, because more people are killing time on them while waiting for their popular-ride passes to mature. Capacity is capacity.

"Twitter is currently really busy. Please come back between 15:00 and 15:15 and we guarantee to get you your tweets in 5 seconds or less."


问:
Rails 4 exception stack traces don't show in development
I'm following the rails tutorial book and using the c9.io web IDE as I follow the tutorials. While working on my sample application, I noticed that exceptions aren't being shown on the page in while in development mode. Additionally, the exception stack traces aren't being logged in log/development.log either. This predicament is making it difficult to debug errors in my code.

Error from application

Error in development.log

```<code>Completed 500 Internal Server Error in 116ms (ActiveRecord: 2.3ms)
</code>```

What I've already tried / researched

config.log_level = :debug (in config/environments/development.rb)

config.consider_all_requests_local       = true

this

that

the other

config/environments/development.rb

```<code>Rails.application.configure do
  # Settings specified here will take precedence over those in config/application.rb.

  # In the development environment your application's code is reloaded on
  # every request. This slows down response time but is perfect for development
  # since you don't have to restart the web server when you make code changes.
  config.cache_classes = false

  # Do not eager load code on boot.
  config.eager_load = false

  # Show full error reports and disable caching.
  config.consider_all_requests_local       = true
  config.action_controller.perform_caching = false

  # Don't care if the mailer can't send.
  config.action_mailer.raise_delivery_errors = false

  # Print deprecation notices to the Rails logger.
  config.active_support.deprecation = :log

  # Raise an error on page load if there are pending migrations.
  config.active_record.migration_error = :page_load

  # Debug mode disables concatenation and preprocessing of assets.
  # This option may cause significant delays in view rendering with a large
  # number of complex assets.
  config.assets.debug = true

  # Asset digests allow you to set far-future HTTP expiration dates on all assets,
  # yet still be able to expire them through the digest params.
  config.assets.digest = true

  # Adds additional error checking when serving assets at runtime.
  # Checks for improperly declared sprockets dependencies.
  # Raises helpful error messages.
  config.assets.raise_runtime_errors = true

  # Raises error for missing translations
  # config.action_view.raise_on_missing_translations = true
  config.log_level = :debug
end
</code>```

Please keep in mind that I am not interested in answers that attempt to find a solution for the exception being thrown. I'm only looking to enable the exception stack traces so that I may debug the problem myself.

Edit 2/25/2017

Gemfile

```<code>source 'https://rubygems.org'

gem 'rails',                   '4.2.2'
gem 'bcrypt',                  '3.1.7'
gem 'faker',                   '1.4.2'
gem 'carrierwave',             '0.10.0'
gem 'mini_magick',             '3.8.0'
gem 'fog',                     '1.36.0'
gem 'will_paginate',           '3.0.7'
gem 'bootstrap-will_paginate', '0.0.10'
gem 'bootstrap-sass',          '3.2.0.0'
gem 'sass-rails',              '5.0.2'
gem 'uglifier',                '2.5.3'
gem 'coffee-rails',            '4.1.0'
gem 'jquery-rails',            '4.0.3'
gem 'turbolinks',              '2.3.0'
gem 'jbuilder',                '2.2.3'
gem 'sdoc',                    '0.4.0', group: :doc

group :development, :test do
  gem 'sqlite3',     '1.3.9'
  gem 'byebug',      '3.4.0'
  gem 'web-console', '2.0.0.beta3'
  gem 'spring',      '1.1.3'
end

group :test do
  gem 'minitest-reporters', '1.0.5'
  gem 'mini_backtrace',     '0.1.3'
  gem 'guard-minitest',     '2.3.1'
end

group :production do
  gem 'pg',             '0.17.1'
  gem 'rails_12factor', '0.0.2'
  gem 'puma',           '3.1.0'
end
</code>```

答:
I got the same error in a Rails 4 app migrated to Rails 5 app.

Running WEBrick on dev mode and config.consider_all_requests_local = true.
Turns out the gem 'web-console'; Using 'bundle update web-console' does not work if the Gemfile is a specific version. So I have to manually change it and update.

Body:
I'm following the rails tutorial book and using the c9.io web IDE as I follow the tutorials. While working on my sample application, I noticed that exceptions aren't being shown on the page in while in development mode. Additionally, the exception stack traces aren't being logged in log/development.log either. This predicament is making it difficult to debug errors in my code.

Error from application

Error in development.log

Completed 500 Internal Server Error in 116ms (ActiveRecord: 2.3ms)

What I've already tried / researched

config.log_level = :debug (in config/environments/development.rb)

config.consider_all_requests_local       = true

this

that

the other

config/environments/development.rb

Rails.application.configure do
  # Settings specified here will take precedence over those in config/application.rb.

  # In the development environment your application's code is reloaded on
  # every request. This slows down response time but is perfect for development
  # since you don't have to restart the web server when you make code changes.
  config.cache_classes = false

  # Do not eager load code on boot.
  config.eager_load = false

  # Show full error reports and disable caching.
  config.consider_all_requests_local       = true
  config.action_controller.perform_caching = false

  # Don't care if the mailer can't send.
  config.action_mailer.raise_delivery_errors = false

  # Print deprecation notices to the Rails logger.
  config.active_support.deprecation = :log

  # Raise an error on page load if there are pending migrations.
  config.active_record.migration_error = :page_load

  # Debug mode disables concatenation and preprocessing of assets.
  # This option may cause significant delays in view rendering with a large
  # number of complex assets.
  config.assets.debug = true

  # Asset digests allow you to set far-future HTTP expiration dates on all assets,
  # yet still be able to expire them through the digest params.
  config.assets.digest = true

  # Adds additional error checking when serving assets at runtime.
  # Checks for improperly declared sprockets dependencies.
  # Raises helpful error messages.
  config.assets.raise_runtime_errors = true

  # Raises error for missing translations
  # config.action_view.raise_on_missing_translations = true
  config.log_level = :debug
end

Please keep in mind that I am not interested in answers that attempt to find a solution for the exception being thrown. I'm only looking to enable the exception stack traces so that I may debug the problem myself.

Edit 2/25/2017

Gemfile

source 'https://rubygems.org'

gem 'rails',                   '4.2.2'
gem 'bcrypt',                  '3.1.7'
gem 'faker',                   '1.4.2'
gem 'carrierwave',             '0.10.0'
gem 'mini_magick',             '3.8.0'
gem 'fog',                     '1.36.0'
gem 'will_paginate',           '3.0.7'
gem 'bootstrap-will_paginate', '0.0.10'
gem 'bootstrap-sass',          '3.2.0.0'
gem 'sass-rails',              '5.0.2'
gem 'uglifier',                '2.5.3'
gem 'coffee-rails',            '4.1.0'
gem 'jquery-rails',            '4.0.3'
gem 'turbolinks',              '2.3.0'
gem 'jbuilder',                '2.2.3'
gem 'sdoc',                    '0.4.0', group: :doc

group :development, :test do
  gem 'sqlite3',     '1.3.9'
  gem 'byebug',      '3.4.0'
  gem 'web-console', '2.0.0.beta3'
  gem 'spring',      '1.1.3'
end

group :test do
  gem 'minitest-reporters', '1.0.5'
  gem 'mini_backtrace',     '0.1.3'
  gem 'guard-minitest',     '2.3.1'
end

group :production do
  gem 'pg',             '0.17.1'
  gem 'rails_12factor', '0.0.2'
  gem 'puma',           '3.1.0'
end


问:
How to import external module/dependencies like Flic in my Android project which is using Bazel as build system?
For importing module dependency in my Android project, for ex. For making my app compatible with Flic I have to import the whole Flic project as module dependency in my existing Android project. It works fine when built with gradle but with Bazel it shows error while importing any class of Flic.</p>

答:
I'm not familiar with Flic, but looking at the instructions here, it looks like flic can be depended upon using http_archive and writing a small android_library rule for it:

WORKSPACE:

```<code>load("@bazel_tools//tools/build_defs/repo:http.bzl", "http_archive")

http_archive(
  name = "flic-android",
  # latest commit as of writing this answer
  url = "https://github.com/50ButtonsEach/fliclib-android/archive/ddfbfebfd5090bb2cc80a7e66c613134ffc4071a.zip",
  build_file = "@//:BUILD.flic-android",
  strip_prefix = "fliclib-android-ddfbfebfd5090bb2cc80a7e66c613134ffc4071a"
)
</code>```

BUILD.flic-android (put this next to the WORKSPACE file):

```<code>package(default_visibility = ["//visibility:public"])

android_library(
  name = "flic",
  manifest = "fliclib/src/main/AndroidManifest.xml",
  srcs = glob(["fliclib/src/main/java/io/flic/lib/*.java"]),

  idl_srcs =        glob(["fliclib/src/main/aidl/io/flic/lib/*.aidl"]),
  # "external/flic-android" must be included in the import root because this
  # rule is being evaluated in an external repository
  idl_import_root = "external/flic-android/fliclib/src/main/aidl",

  custom_package = "io.flic.lib",
)
</code>```

Finally, add "@flic-android//:flic" to the deps of any android_binary or android_library rules that use Flic.

(Side note: flic's build.gradle file listed com.android.support:appcompat-v7:22.1.1 as a compile-time dependency, but it doesn't appear to be needed to compile the library, so I didn't include that here)

Body:
I'm not familiar with Flic, but looking at the instructions here, it looks like flic can be depended upon using http_archive and writing a small android_library rule for it:

WORKSPACE:

load("@bazel_tools//tools/build_defs/repo:http.bzl", "http_archive")

http_archive(
  name = "flic-android",
  # latest commit as of writing this answer
  url = "https://github.com/50ButtonsEach/fliclib-android/archive/ddfbfebfd5090bb2cc80a7e66c613134ffc4071a.zip",
  build_file = "@//:BUILD.flic-android",
  strip_prefix = "fliclib-android-ddfbfebfd5090bb2cc80a7e66c613134ffc4071a"
)

BUILD.flic-android (put this next to the WORKSPACE file):

package(default_visibility = ["//visibility:public"])

android_library(
  name = "flic",
  manifest = "fliclib/src/main/AndroidManifest.xml",
  srcs = glob(["fliclib/src/main/java/io/flic/lib/*.java"]),

  idl_srcs =        glob(["fliclib/src/main/aidl/io/flic/lib/*.aidl"]),
  # "external/flic-android" must be included in the import root because this
  # rule is being evaluated in an external repository
  idl_import_root = "external/flic-android/fliclib/src/main/aidl",

  custom_package = "io.flic.lib",
)

Finally, add "@flic-android//:flic" to the deps of any android_binary or android_library rules that use Flic.

(Side note: flic's build.gradle file listed com.android.support:appcompat-v7:22.1.1 as a compile-time dependency, but it doesn't appear to be needed to compile the library, so I didn't include that here)


问:
Conditional assignment not working for possibly undefined variable
I have this at the beginning of a rails view partial:

```<code><% enabled = true unless defined?(enabled) %>
</code>```

This is to handle cases when the calling view doesn't pass in the enabled local, by setting a default.

But enabled doesn't get set to true.

I'm aware that of the construct enabled ||= true, but I can't use that here because of the possibility that the passed-in value is false. That would get overwritten with true.

答:
You can achieve a similar effect to what you were originally trying to do by combining defined? with the OR operator ||:

defined?(enabled) || enabled = true
```

<p>Example:</p>

<pre class="lang-rb prettyprint-override"><code>2.4.4 :001 > enabled
NameError: undefined local variable or method `enabled' for main:Object
    from (irb):1
        ...(etc.)
2.4.4 :002 > defined?(enabule) || enabled = true
 => true
2.4.4 :003 > enabled
 => true
2.4.4 :004 > enabled = false
 => false
2.4.4 :005 > defined?(enabule) || enabled = true
 => true
2.4.4 :006 > enabled
 => true
</code>```

Body:
I have this at the beginning of a rails view partial:

<% enabled = true unless defined?(enabled) %>

This is to handle cases when the calling view doesn't pass in the enabled local, by setting a default.

But enabled doesn't get set to true.

I'm aware that of the construct enabled ||= true, but I can't use that here because of the possibility that the passed-in value is false. That would get overwritten with true.

Body:
You can achieve a similar effect to what you were originally trying to do by combining defined? with the OR operator ||:

defined?(enabled) || enabled = true

Example:

2.4.4 :001 > enabled
NameError: undefined local variable or method `enabled' for main:Object
    from (irb):1
        ...(etc.)
2.4.4 :002 > defined?(enabule) || enabled = true
 => true
2.4.4 :003 > enabled
 => true
2.4.4 :004 > enabled = false
 => false
2.4.4 :005 > defined?(enabule) || enabled = true
 => true
2.4.4 :006 > enabled
 => true


问:
Creating API versioning for my php application (Social App)
I'm currently working on a Social Application.

I would like to have a versioning system on my PHP backend, but I don't know where to start: I have looked up a bunch of articles online, but I couldn't really understand what I've found.

Let's say my application is v1.0. Then I create a new version v2.0 and of course I update the PHP files too. After this, if someone hasn't updated their app from v1.0, I would like them to reach myapp.com/v1.0/ so that the app doesn't crash.

What would you recommend?

A typical PHP file of mine looks like this, for example:

```<code><?php

// Include files

include_once ('../../config.php');

include_once (ROOT_DIR . '/config/includes.php');

$_USERDATA = Validator::validateUser($_POST["userId"], $_POST["session"]);

// Valid session

$qry = $db->prepare('SELECT n.id, n.type, n.time, n.isRead, n.postId, n.commentId, n.text, n.inReplyToCommentId, u.id as byUserId,
    ( SELECT COUNT(nu.id)
    FROM notificationUsers AS nu
    WHERE nu.notificationId = n.id ) as detail1,
    ( SELECT nu2.userId
    FROM notificationUsers AS nu2
    WHERE nu2.notificationId = n.id ORDER BY nu2.id DESC LIMIT 1 ) as latestUserId FROM notifications AS n LEFT JOIN userData AS u ON n.byUserId = u.id
    WHERE n.userId = :userId ORDER BY n.time DESC');
$qry->bindParam(':userId', $_USERDATA["userId"], PDO::PARAM_INT);
$qry->execute();

$notificationsArray = $qry->fetchAll(PDO::FETCH_ASSOC);

$returnValue = array();
$returnValue["status"] = "1";
$returnValue["title"] = "Success";
$returnValue["message"] = "Downloaded notifications";
$returnValue["data_notifications"] = $notificationsArray;
exit(json_encode($returnValue));

?>
</code>```

...

UPDATE 1

So I decided to do the following:

Placing every not shared file inside a folder like so:

```<code>/api/v1.0/file.php
</code>```

But every resource for example (images) is outside the API

```<code>/resources/images/profilepictures/image.jpg
</code>```

If I make a minor change, I just update the files within the api/v1.0/ folder.

Then, all the users that are using the Application v1.1, they are requesting myapp.com/api/v1.1/, but I redirect them to api/v1.0/ where I can present the users the right data (depending on if the request was from v1.0 or v1.1)

If the versions add up and I release a bigger update, I'll create a new folder with the name v2.0, and so it goes...

Or what do you think? How should I do it?

答:
As i can see you want to write your APIs in plain PHP without any frameworks.
I just want to lead you to a correct way and give you some vision to starting server-side development in PHP.

At the first choose a framework to code with. Maybe CodeIgniter, It is a easy-to-use one [Read followings]

Study about MVC design-pattern that most of frameworks support that and it will make your life easy when you want to maintenance or extend your existing code - This is necessary and easy enough, don't be scared

Cloning your whole project for backward compatibility is an overkill (assume you want to simply fix a bug in database access layer (Model/Repository), you should repeat it for all other versions) - You can achieve this by cloning just Controllers and defining new routes - [Still you have previous problem in business-logic in Controller layer because of design-pattern]

If you want a stronger approach you should start coding with Repository pattern with service layer (aka MVCS) and using a desired framework maybe Laravel to prevent code-coupling in different versions Controller layer and keep your shared Business-logic in Service layer (Separate it from Controller)

Document the important things In Code via using documentation comment tags such as @deprecated and @since to specify when some functionalities are deprecated or added (Because you cannot clear the deprecated functionalities until that the related version has been retired.) [check this link to get idea]

Study about versioning standards - SEMVER

Do not code in plain PHP

Body:
I'm currently working on a Social Application.

I would like to have a versioning system on my PHP backend, but I don't know where to start: I have looked up a bunch of articles online, but I couldn't really understand what I've found.

Let's say my application is v1.0. Then I create a new version v2.0 and of course I update the PHP files too. After this, if someone hasn't updated their app from v1.0, I would like them to reach myapp.com/v1.0/ so that the app doesn't crash.

What would you recommend?

A typical PHP file of mine looks like this, for example:

<?php

// Include files

include_once ('../../config.php');

include_once (ROOT_DIR . '/config/includes.php');

$_USERDATA = Validator::validateUser($_POST["userId"], $_POST["session"]);

// Valid session

$qry = $db->prepare('SELECT n.id, n.type, n.time, n.isRead, n.postId, n.commentId, n.text, n.inReplyToCommentId, u.id as byUserId,
    ( SELECT COUNT(nu.id)
    FROM notificationUsers AS nu
    WHERE nu.notificationId = n.id ) as detail1,
    ( SELECT nu2.userId
    FROM notificationUsers AS nu2
    WHERE nu2.notificationId = n.id ORDER BY nu2.id DESC LIMIT 1 ) as latestUserId FROM notifications AS n LEFT JOIN userData AS u ON n.byUserId = u.id
    WHERE n.userId = :userId ORDER BY n.time DESC');
$qry->bindParam(':userId', $_USERDATA["userId"], PDO::PARAM_INT);
$qry->execute();

$notificationsArray = $qry->fetchAll(PDO::FETCH_ASSOC);

$returnValue = array();
$returnValue["status"] = "1";
$returnValue["title"] = "Success";
$returnValue["message"] = "Downloaded notifications";
$returnValue["data_notifications"] = $notificationsArray;
exit(json_encode($returnValue));

?>

...

UPDATE 1

So I decided to do the following:

Placing every not shared file inside a folder like so:

/api/v1.0/file.php

But every resource for example (images) is outside the API

/resources/images/profilepictures/image.jpg

If I make a minor change, I just update the files within the api/v1.0/ folder.

Then, all the users that are using the Application v1.1, they are requesting myapp.com/api/v1.1/, but I redirect them to api/v1.0/ where I can present the users the right data (depending on if the request was from v1.0 or v1.1)

If the versions add up and I release a bigger update, I'll create a new folder with the name v2.0, and so it goes...

Or what do you think? How should I do it?


问:
Loading of a resource blocked by Content Security Policy
I'm getting the error below in the console of my browser:

Content Security Policy: The page’s settings blocked the loading of a resource at http://localhost:3000/favicon.ico (“default-src”).

I searched online and saw that this should be fixed with the snippet of code below:

```<code><meta http-equiv="Content-Security-Policy" content="default-src *;
    img-src * 'self' data: https: http:;
    script-src 'self' 'unsafe-inline' 'unsafe-eval' *;
    style-src  'self' 'unsafe-inline' *">
</code>```

I added this to my front-end app.component.html file (the parent template for all my front-end views), but this didn't work as expected.

I've also tried multiple permutations thereupon to no avail.

My front-end is at localhost:4200 and back-end at localhost:3000.

Below is the snippet of code from my back-end server (middleware):

```<code>app.use(cors());
app.options('*',cors());
var allowCrossDomain = function(req,res,next) {
    res.header('Access-Control-Allow-Origin', '*');
    res.header('Access-Control-Allow-Methods', 'GET, PUT, POST, DELETE');
    res.header('Access-Control-Allow-Headers', 'Content-Type');
    next();
}
app.use(allowCrossDomain);
</code>```

I also have now added the following middleware to my backend (Express) server:

```<code>const csp = require('express-csp-header');

app.use(csp({
  policies: {
      'default-src': [csp.SELF, 'http://localhost:3000/', 'http://localhost:4200/' ],
      'script-src': [csp.SELF, csp.INLINE],
      'style-src': [csp.SELF],
      'img-src': ['data:', 'favico.ico'],
      'worker-src': [csp.NONE],
      'block-all-mixed-content': true
  }
}));

</code>```

. . . but still hasn't fixed the problem.

Here is a screenshot:

What am I doing wrong and how can I fix it?

答:
Content Security Policy (CSP) is a mechanism to help prevent Cross-Site Scripting (XSS) and is best handled at server side; please note it can be handled at client side as well, making use of the <meta> tag element of your HTML.

When configured and enabled, a web server will return the appropriate Content-Security-Policy in the HTTP response header.

You may want to read more about CSP on the on the HTML5Rocks website and Mozilla developer page here and here.

Google CSP Evaluator is a handy and free online tool to help test CSP for your website or web application.

In your instance, you may need to add the line below without enforcing HTTPS as protocol using the https: directive;

Because your website or application (as shared) is not available over HTTPS.

res.header('Content-Security-Policy', "img-src 'self'");
```
<p>Starting with <code>default-src</code> directive set to <code>none</code> is a great way to start deploying your CSP settings.</p>
<p>In case you opt to use the Content-Security-Policy middleware for Express
, you may get started as illustrated in the snippet below;</p>
<pre class="lang-js prettyprint-override"><code>const csp = require('express-csp-header');
app.use(csp({
    policies: {
        'default-src': [csp.NONE],
        'img-src': [csp.SELF],
    }
}));

// HTTP response header will be defined as:
// "Content-Security-Policy: default-src 'none'; img-src 'self';"
</code>```

Remember CSP are case or application specific and based on your project requirements.

As such, you need to fine tune in order to meet your need.

Body:
I'm getting the error below in the console of my browser:

Content Security Policy: The page’s settings blocked the loading of a resource at http://localhost:3000/favicon.ico (“default-src”).

I searched online and saw that this should be fixed with the snippet of code below:

<meta http-equiv="Content-Security-Policy" content="default-src *;
    img-src * 'self' data: https: http:;
    script-src 'self' 'unsafe-inline' 'unsafe-eval' *;
    style-src  'self' 'unsafe-inline' *">

I added this to my front-end app.component.html file (the parent template for all my front-end views), but this didn't work as expected.

I've also tried multiple permutations thereupon to no avail.

My front-end is at localhost:4200 and back-end at localhost:3000.

Below is the snippet of code from my back-end server (middleware):

app.use(cors());
app.options('*',cors());
var allowCrossDomain = function(req,res,next) {
    res.header('Access-Control-Allow-Origin', '*');
    res.header('Access-Control-Allow-Methods', 'GET, PUT, POST, DELETE');
    res.header('Access-Control-Allow-Headers', 'Content-Type');
    next();
}
app.use(allowCrossDomain);

I also have now added the following middleware to my backend (Express) server:

const csp = require('express-csp-header');

app.use(csp({
  policies: {
      'default-src': [csp.SELF, 'http://localhost:3000/', 'http://localhost:4200/' ],
      'script-src': [csp.SELF, csp.INLINE],
      'style-src': [csp.SELF],
      'img-src': ['data:', 'favico.ico'],
      'worker-src': [csp.NONE],
      'block-all-mixed-content': true
  }
}));

. . . but still hasn't fixed the problem.

Here is a screenshot:

What am I doing wrong and how can I fix it?

Body:
Content Security Policy (CSP) is a mechanism to help prevent Cross-Site Scripting (XSS) and is best handled at server side; please note it can be handled at client side as well, making use of the <meta> tag element of your HTML.

When configured and enabled, a web server will return the appropriate Content-Security-Policy in the HTTP response header.

You may want to read more about CSP on the on the HTML5Rocks website and Mozilla developer page here and here.

Google CSP Evaluator is a handy and free online tool to help test CSP for your website or web application.

In your instance, you may need to add the line below without enforcing HTTPS as protocol using the https: directive;

Because your website or application (as shared) is not available over HTTPS.

res.header('Content-Security-Policy', "img-src 'self'");

Starting with default-src directive set to none is a great way to start deploying your CSP settings.

In case you opt to use the Content-Security-Policy middleware for Express
, you may get started as illustrated in the snippet below;

const csp = require('express-csp-header');
app.use(csp({
    policies: {
        'default-src': [csp.NONE],
        'img-src': [csp.SELF],
    }
}));

// HTTP response header will be defined as:
// "Content-Security-Policy: default-src 'none'; img-src 'self';"

Remember CSP are case or application specific and based on your project requirements.

As such, you need to fine tune in order to meet your need.


问:
Installing Kivy in Anaconda
I am trying to install Kivy in Anaconda 3 4.1.1 in Windows 7. But I couldn't find a proper user guide to instruct me how to do so. But so far I was able to find instructions to install it on OS X on the link https://github.com/kivy/kivy/wiki/Connecting-Kivy-with-Anaconda-(OSX). But I couldn't find a one for Windows operating systems. </p>

<p>Can anyone provide me with instructions on how to install Kivy in Anaconda? </p>

答:
Kivy now has official Anaconda releases on all platforms. You can install it with:</p>

```<code>conda install kivy -c conda-forge
</code>```

Title: Installing Kivy in Anaconda

Body:
I am trying to install Kivy in Anaconda 3 4.1.1 in Windows 7. But I couldn't find a proper user guide to instruct me how to do so. But so far I was able to find instructions to install it on OS X on the link https://github.com/kivy/kivy/wiki/Connecting-Kivy-with-Anaconda-(OSX). But I couldn't find a one for Windows operating systems.

Can anyone provide me with instructions on how to install Kivy in Anaconda?

Body:
Kivy now has official Anaconda releases on all platforms. You can install it with:

conda install kivy -c conda-forge


问:
meteor emit event then used by aframe eventlistener
I have an aframe object in main.html:

```<code><a-gltf-model id='player1'  foobox playmyclip src="#myMixBun" ></a-gltf-model>
</code>```

I want to have it perform a gltf clip animation when the eventListener ‘driveplay’ is emitted.
In foofile.js:

```<code>AFRAME.registerComponent('playmyclip', {
  init: function () {
    var el = this.el;
    el.addEventListener('driveplay', function () {
    el.setAttribute('animation-mixer', {clip: 'Drive', loop: 'once'});
    });
  }
});
</code>```

Currently I have it so when the j key is hit ‘driveplay’ is emitted:

```<code>AFRAME.registerComponent('foobox', {
    init: function() {
    var el = this.el
    var swingno = 0;
     self = this;
          document.addEventListener('keydown', (event) => {
          const keyName = event.key;
                if (keyName === 'j') {
                el.emit('driveplay',{},true);

                             // code to store record of event in Mongo for second player
                var playerid = self.el.getAttribute('id');
               var playerMid = Games.findOne({name: playerid})._id;
              Games.update({_id: playerMid},{$set:{swings : swingno}});
              swingno = swingno + 1;
             }
       })
   }
  });
</code>```

But I also need to have the animation to happen at the same time on player2‘s screen. So in the above code I increment a variable in Mongo every time the animation happens. Then in main.js meteor automatically emits an event whenever “swingno” changes in Mongo.
main.js:

```<code>import {EventEmitter} from 'meteor/raix:eventemitter';
Event = new EventEmitter();
var swingcnt1 = 0;
Template.hello.helpers({
  counter() {
        if (Games.findOne())   //mongo is ready to access
      {
          var plyr1Swing = Games.findOne({name: "player1"}).swings;
        if (plyr1Swing !== swingcnt1) {
        Event.emit('driveplay',{},true);
    swingcnt1 = plyr1Swing;
        console.log(“this shows on player2’s console automatically”, swingcnt1);
   }
}
else    {null}
return { ........};
},
</code>```

When player1 hits the “j” key the animation happens correctly on his screen, plus the event is recorded in Mongo, and player2 receives the updated Mongo value (since it show in the console.log).

The problem is the

```<code>Event.emit('driveplay',{},true);
</code>```

statement doesn’t trigger the animation in player2‘s screen. This is a little tricky, since I need meteor’s “raix:eventemitter” package to create an event that the aframe event listener can see.  It’s possible I’m not actually emitting an event at all, since I don’t know how to test if it’s working. Or possibly aframe can’t see the emitted event.

Possibly there’s an easier way of doing this. Thanks for any help.

答:
SOLVED  The solution  was to use the listener code from meteor’s raix:eventemitter package inside Aframe’s component.

https://atmospherejs.com/raix/eventemitter

```<code>AFRAME.registerComponent('playmyclip', {
  init: function ()
      var el = this.el;
    listener = function() {
           el.setAttribute('animation-mixer', {clip: 'Drive', loop: 'once'});
   };
   Event.on('driveplay', listener);
 }
});
</code>```

Plus the foobox component no longer needs:

```<code> if (keyName === 'j') {
  el.emit('driveplay',{},true);
</code>```

Both player1 and player2 get the animation event from

```<code> Event.emit('driveplay',{},true);
</code>```

in main.js when the meteor helper notices a change in the mongodb.

Body:
I have an aframe object in main.html:

I want to have it perform a gltf clip animation when the eventListener ‘driveplay’ is emitted.
In foofile.js:

AFRAME.registerComponent('playmyclip', {
  init: function () {
    var el = this.el;
    el.addEventListener('driveplay', function () {
    el.setAttribute('animation-mixer', {clip: 'Drive', loop: 'once'});
    });
  }
});

Currently I have it so when the j key is hit ‘driveplay’ is emitted:

AFRAME.registerComponent('foobox', {
    init: function() {
    var el = this.el
    var swingno = 0;
     self = this;
          document.addEventListener('keydown', (event) => {
          const keyName = event.key;
                if (keyName === 'j') {
                el.emit('driveplay',{},true);

                             // code to store record of event in Mongo for second player
                var playerid = self.el.getAttribute('id');
               var playerMid = Games.findOne({name: playerid})._id;
              Games.update({_id: playerMid},{$set:{swings : swingno}});
              swingno = swingno + 1;
             }
       })
   }
  });

But I also need to have the animation to happen at the same time on player2‘s screen. So in the above code I increment a variable in Mongo every time the animation happens. Then in main.js meteor automatically emits an event whenever “swingno” changes in Mongo.
main.js:

import {EventEmitter} from 'meteor/raix:eventemitter';
Event = new EventEmitter();
var swingcnt1 = 0;
Template.hello.helpers({
  counter() {
        if (Games.findOne())   //mongo is ready to access
      {
          var plyr1Swing = Games.findOne({name: "player1"}).swings;
        if (plyr1Swing !== swingcnt1) {
        Event.emit('driveplay',{},true);
    swingcnt1 = plyr1Swing;
        console.log(“this shows on player2’s console automatically”, swingcnt1);
   }
}
else    {null}
return { ........};
},

When player1 hits the “j” key the animation happens correctly on his screen, plus the event is recorded in Mongo, and player2 receives the updated Mongo value (since it show in the console.log).

The problem is the

Event.emit('driveplay',{},true);

statement doesn’t trigger the animation in player2‘s screen. This is a little tricky, since I need meteor’s “raix:eventemitter” package to create an event that the aframe event listener can see.  It’s possible I’m not actually emitting an event at all, since I don’t know how to test if it’s working. Or possibly aframe can’t see the emitted event.

Possibly there’s an easier way of doing this. Thanks for any help.

Body:
SOLVED  The solution  was to use the listener code from meteor’s raix:eventemitter package inside Aframe’s component.

https://atmospherejs.com/raix/eventemitter

AFRAME.registerComponent('playmyclip', {
  init: function ()
      var el = this.el;
    listener = function() {
           el.setAttribute('animation-mixer', {clip: 'Drive', loop: 'once'});
   };
   Event.on('driveplay', listener);
 }
});

Plus the foobox component no longer needs:

 if (keyName === 'j') {
  el.emit('driveplay',{},true);

Both player1 and player2 get the animation event from

 Event.emit('driveplay',{},true);

in main.js when the meteor helper notices a change in the mongodb.


问:
writing in arduino with Solid principles
I am a C programmer and I am new in cpp.for some understandable reason i want to write my program in S.O.L.I.D way

I want to write a program in c++ in Arduino with OOP.

there are classA , classB ,ClassC and classD.

classA have to get data from serial port and give an array of bytes
to classB.

ClassB do some process and give another array of bytes to classC

classC make this array into a defined format it to propper
output. e.g json

classD take this output and send it via mqtt

my problems are

how can I program classA that if I change SerialPort to SPI or other peripheral just by changing a parameter?(Objects or entities should be open for extension, but closed for modification)

how these class communicate with each other that if in future  instead of json in classC I choose xml without modifying other class I can extend classC?

sorry for bad English If I am not clear ask in comment

答:
Embedded programming and OOP are not the best friends, especially in a very limited system like Arduino. The answer to both questions in classic OOP is polymorphism (with virtual functions). You can create an interface for classA and implement getting data in different ways in every derived class.

```<code>class DataGatherer {
public:
    virtual char* getData() = 0;
    virtual ~IClassA () = default;
};

class SerialPortDataGatherer: public DataGatherer {
public:
    char* getData() override {
        //any code here
    }
};
</code>```

For less resource-expensive solution you can pretty easily do mapping of parameter to a function (e.g. with a simple switch-case statement), if the functions will have common format (like they return array of data or whatever you actually need)

```<code>enum DataSources {
    SerialPort,
    SPI
}

char* getDataFromSerialPort() {
// logic here
}

char* getDataFromSPI() {
// logic here
}

char* getData(DataSources source) {
    switch(source) {
    case SerialPort:
        return getDataFromSerialPort();
    case SPI:
        return getDataFromSPI();
}
</code>```

Note that the first version will likely require a switch-case at some point as well (where you make the decision which input type you should use).

Body:
Embedded programming and OOP are not the best friends, especially in a very limited system like Arduino. The answer to both questions in classic OOP is polymorphism (with virtual functions). You can create an interface for classA and implement getting data in different ways in every derived class.

class DataGatherer {
public:
    virtual char* getData() = 0;
    virtual ~IClassA () = default;
};

class SerialPortDataGatherer: public DataGatherer {
public:
    char* getData() override {
        //any code here
    }
};

For less resource-expensive solution you can pretty easily do mapping of parameter to a function (e.g. with a simple switch-case statement), if the functions will have common format (like they return array of data or whatever you actually need)

enum DataSources {
    SerialPort,
    SPI
}

char* getDataFromSerialPort() {
// logic here
}

char* getDataFromSPI() {
// logic here
}

char* getData(DataSources source) {
    switch(source) {
    case SerialPort:
        return getDataFromSerialPort();
    case SPI:
        return getDataFromSPI();
}

Note that the first version will likely require a switch-case at some point as well (where you make the decision which input type you should use).


问:
iOS - State restoration - Get previously restored view controller
I have a navigation controller with several view controllers inside.

While restoring app application(_:viewControllerWithRestorationIdentifierPath:coder:) method calls for each controller one by one initially for first in stack then for second and so on.
At time of restoring second view controller I need to get reference to first one (to make some connection between them).

Is there any way to get previously restored controller at this step without saving this controller somewhere in the app? (the same is about navigation controller I don't save referents to it anywhere in the app)

答:
Encode the second view controller in the first view controller's encodeRestorableState method. e.g.

FirstViewController.m

```<code>- (void)prepareForSegue:(UIStoryboardSegue *)segue{
     // configure and store it...
     // self.secondViewController = controller;
}

- (void)encodeRestorableStateWithCoder:(NSCoder *)coder {
    [super encodeRestorableStateWithCoder:coder];
    if (self.secondViewController) {
        [coder encodeObject:self.secondViewController forKey:kSecondViewControllerKey];
    }
}

- (void)decodeRestorableStateWithCoder:(NSCoder *)coder {
    [super decodeRestorableStateWithCoder:coder];
    self.secondViewController = [coder decodeObjectForKey:kSecondViewControllerKey];
}

- (void)applicationFinishedRestoringState{
    // self.secondViewController's properties are now also decoded and ready to be used
}
</code>```

application:viewControllerWithRestorationIdentifierPath: can return nil for the second view controller and it will one from the storyboard for you and the reference will be what is returned in decodeObjectForKey.

Body:
Encode the second view controller in the first view controller's encodeRestorableState method. e.g.

FirstViewController.m

- (void)prepareForSegue:(UIStoryboardSegue *)segue{
     // configure and store it...
     // self.secondViewController = controller;
}

- (void)encodeRestorableStateWithCoder:(NSCoder *)coder {
    [super encodeRestorableStateWithCoder:coder];
    if (self.secondViewController) {
        [coder encodeObject:self.secondViewController forKey:kSecondViewControllerKey];
    }
}

- (void)decodeRestorableStateWithCoder:(NSCoder *)coder {
    [super decodeRestorableStateWithCoder:coder];
    self.secondViewController = [coder decodeObjectForKey:kSecondViewControllerKey];
}

- (void)applicationFinishedRestoringState{
    // self.secondViewController's properties are now also decoded and ready to be used
}

application:viewControllerWithRestorationIdentifierPath: can return nil for the second view controller and it will one from the storyboard for you and the reference will be what is returned in decodeObjectForKey.


问:
R - image of a pixel matrix?
How would you you make an image from a matrix in R?

Matrix values would correspond to pixel intensity on image (although I am just interested in 0,1 values white or black at the moment.), while column and row numbers correspond to vertical and horizontal location on the image.

By make an image I mean display it on the screen and save it as a jpg.

答:
You can display it on the screen easiest using 'image':

```<code>m = matrix(runif(100),10,10)
par(mar=c(0, 0, 0, 0))
image(m, useRaster=TRUE, axes=FALSE)
</code>```

You can also have a look at the raster package...

Title: R - image of a pixel matrix?

Body:
You can display it on the screen easiest using 'image':

m = matrix(runif(100),10,10)
par(mar=c(0, 0, 0, 0))
image(m, useRaster=TRUE, axes=FALSE)

You can also have a look at the raster package...


问:
Call a field/table in a DoCmd
I want to use a field (DropPath) found in SetupExp table to be referenced in a DoCmd.OutPutTo

```<code>droppath.SetupExp = D:\Export\
</code>```

This works

```<code>DoCmd.OutputTo acOutputTable, "CustItemExp", "Excel97-Excel2003Workbook(*.xls)", "D:\Export\CustItemExp" & Format(Date, "yymmdd") & ".xls", False, "", 0, acExportQualityPrint
</code>```

This does not:

```<code>DoCmd.OutputTo acOutputTable, "CustItemExp", "Excel97-Excel2003Workbook(*.xls)", "droppath.SetupExp" & Format(Date, "yymmdd") & ".xls", False, "", 0, acExportQualityPrint
</code>```

It should look at the droppath.SetupExp to create a CSV file called CustItemExp.csv in that location.

答:
You cannot reference table or query field values directly in VBA in the same way as you might the properties of objects on forms or reports.

Instead you'll need to acquire the value of a record within your table either using a domain aggregate function such as DLookup or DFirst, or by opening a recordset of the table records and retrieving the value.

Based on your examples, I might suggest something along the lines of:

```<code>DoCmd.OutputTo acOutputTable, "CustItemExp", acFormatXLS, DFirst("droppath", "setupexp") & "CustItemExp" & Format(Date, "yymmdd") & ".xls"
</code>```

Title: Call a field/table in a DoCmd

Body:
I want to use a field (DropPath) found in SetupExp table to be referenced in a DoCmd.OutPutTo

droppath.SetupExp = D:\Export\

This works

DoCmd.OutputTo acOutputTable, "CustItemExp", "Excel97-Excel2003Workbook(*.xls)", "D:\Export\CustItemExp" & Format(Date, "yymmdd") & ".xls", False, "", 0, acExportQualityPrint

This does not:

DoCmd.OutputTo acOutputTable, "CustItemExp", "Excel97-Excel2003Workbook(*.xls)", "droppath.SetupExp" & Format(Date, "yymmdd") & ".xls", False, "", 0, acExportQualityPrint

It should look at the droppath.SetupExp to create a CSV file called CustItemExp.csv in that location.

Body:
You cannot reference table or query field values directly in VBA in the same way as you might the properties of objects on forms or reports.

Instead you'll need to acquire the value of a record within your table either using a domain aggregate function such as DLookup or DFirst, or by opening a recordset of the table records and retrieving the value.

Based on your examples, I might suggest something along the lines of:

DoCmd.OutputTo acOutputTable, "CustItemExp", acFormatXLS, DFirst("droppath", "setupexp") & "CustItemExp" & Format(Date, "yymmdd") & ".xls"