问:
How can I embed my navigation controller into my tab bar controller programmatically in Swift Xcode 8.2?
I have been teaching my self how to develop and I got to the point to where I need guidance from experts. I created some of the user interface programmatically using the MVC structure. My question is how can I embed my navigation controller into my tab bar controller so my tab bar controller can be on every screen.  I made the tab bar controller in main.storyboard and referenced it in the View controller I named Home Controller.

```<code>    let storyboard: UIStoryboard = UIStoryboard(name: "Main", bundle: nil)

    let tabViewController = storyboard.instantiateViewController(withIdentifier: "TabBar")

    self.present(tabViewController, animated: true, completion: nil)
</code>```

The code above is in the view did load function. I was wondering do I need to change up the root view controller in my app delegates?

```<code>    window = UIWindow(frame: UIScreen.main.bounds)
    window?.makeKeyAndVisible()

    let layout = UICollectionViewFlowLayout()
    window?.rootViewController =  UINavigationController(rootViewController: HomeController(collectionViewLayout: layout))
</code>```

This is in my finished launched func.

答:
Use following lines</p>

```<code>var navigationController = UINavigationController(rootViewController: viewController));

tabBarController.viewControllers = [navigationController,firstViewControllersecondViewController, ]
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I have been teaching my self how to develop and I got to the point to where I need guidance from experts. I created some of the user interface programmatically using the MVC structure. My question is how can I embed my navigation controller into my tab bar controller so my tab bar controller can be on every screen.  I made the tab bar controller in main.storyboard and referenced it in the View controller I named Home Controller.

    let storyboard: UIStoryboard = UIStoryboard(name: "Main", bundle: nil)

    let tabViewController = storyboard.instantiateViewController(withIdentifier: "TabBar")

    self.present(tabViewController, animated: true, completion: nil)

The code above is in the view did load function. I was wondering do I need to change up the root view controller in my app delegates?

    window = UIWindow(frame: UIScreen.main.bounds)
    window?.makeKeyAndVisible()

    let layout = UICollectionViewFlowLayout()
    window?.rootViewController =  UINavigationController(rootViewController: HomeController(collectionViewLayout: layout))

This is in my finished launched func.

Body:
Use following lines

var navigationController = UINavigationController(rootViewController: viewController));

tabBarController.viewControllers = [navigationController,firstViewControllersecondViewController, ]


来源: stackexchange

问:
Ajax not working with Node js - Express js
Im trying to send data from my server side to my client side with ajax but when i use res.send(data) in node, it show me a empty html with the data and i want to get data from my client side without reloading the page and edit something in my actual html

Here's my server-side code

```<code>    app.post('/',(req,res)=>{
    var userName = req.body.username;
    var password = req.body.password;

    connection.query('SELECT * from admin',(err, rows, fields)=> {
      if (!err){
        if((userName == rows[0].usuario) && (password == rows[0].contraseña)){
            res.sendStatus(200);

        }else{
            res.send('Incorrect username or password')
        }
      }else{
        res.send('Error while performing Query.');
      }

    });

});
</code>```

Here's my client-side code

```<code>$(document).ready(function(){
$('#login-form').submit(function (e) {
        setTimeout(function () {
        e.preventDefault();
        $.ajax({
            type: 'POST',
            url: '/',
            dataType: 'jsonp',
            data: ({username: $('input[name=username]'),password: $('input[name=password]')}),
            success: function(data,textStatus){
                if(textStatus.statusCode == 200) {
                    $('.error-user').html('Succes');
                }else{
                    $('.error-user').html('Not Success');
                }

            },
        });
        }, 1000);

});
});
</code>```

UPDATE: I removed the setTimeOut() but when I submit the form the page freeze like two seconds and then nothing happen, I get this 'error Maximum call stack size exceeded', dont get me data just stay in the same view if like post method was never called

UPDATE-FINAL: I got values from input outside of the ajax and it works nice,thanks :#

答:
If I understand you correctly, you may be using the  request method.

To retrieve the data from your node server's data you should use the GET method when the page completes loading.

To send a request to node when the form is  submitted your often will send a request  from the client side js to make a persistent change to  a database on the node server. Depending on what you would like to achieve, you should use the POST, PUT, PATCH, DELETE methods.

These methods will typically create, update, update a portion of data set, or remove records or documents from an SQL or NoSQL database available to your node server.

ContentLicense: CC BY-SA 3.0

Body:
Im trying to send data from my server side to my client side with ajax but when i use res.send(data) in node, it show me a empty html with the data and i want to get data from my client side without reloading the page and edit something in my actual html

Here's my server-side code

    app.post('/',(req,res)=>{
    var userName = req.body.username;
    var password = req.body.password;

    connection.query('SELECT * from admin',(err, rows, fields)=> {
      if (!err){
        if((userName == rows[0].usuario) && (password == rows[0].contraseña)){
            res.sendStatus(200);

        }else{
            res.send('Incorrect username or password')
        }
      }else{
        res.send('Error while performing Query.');
      }

    });

});

Here's my client-side code

$(document).ready(function(){
$('#login-form').submit(function (e) {
        setTimeout(function () {
        e.preventDefault();
        $.ajax({
            type: 'POST',
            url: '/',
            dataType: 'jsonp',
            data: ({username: $('input[name=username]'),password: $('input[name=password]')}),
            success: function(data,textStatus){
                if(textStatus.statusCode == 200) {
                    $('.error-user').html('Succes');
                }else{
                    $('.error-user').html('Not Success');
                }

            },
        });
        }, 1000);

});
});

UPDATE: I removed the setTimeOut() but when I submit the form the page freeze like two seconds and then nothing happen, I get this 'error Maximum call stack size exceeded', dont get me data just stay in the same view if like post method was never called

UPDATE-FINAL: I got values from input outside of the ajax and it works nice,thanks :#


问:
Pure JavaScript: Combine onload and onresize in one function?
A bit stuck here.

I'm trying to display and output the live(responsive) height and width of the inner page.

In this code, I feel like I am repeating myself to much. Is there anyway to make the code look cleaner or put it in one function?

Personally, I don't want to use JQuery in this case.

var pageSize = document.getElementById("innerSize");

window.onload = function() {
  var w = document.documentElement.clientWidth;
  var h = document.documentElement.clientHeight;

  pageSize.innerHTML = "Width: " + w + "
" + " Height: " + h;
}

window.onresize = function() {
  var w = document.documentElement.clientWidth;
  var h = document.documentElement.clientHeight;

  pageSize.innerHTML = "Width: " + w + "
" + " Height: " + h;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="innerSize"></div></code>```

答:
In this code, I feel like I am repeating myself to much. Is there anyway to make the code look cleaner or put it in one function?

Yes, you are repeating yourself too much.  Set the same functions all in one go (or split them up in separate lines -- coders choice), either way, set them to the same function.

var pageSize = document.getElementById("innerSize");

window.onload = window.onresize = setWidth;

function setWidth() {
  var w = document.documentElement.clientWidth;
  var h = document.documentElement.clientHeight;

  pageSize.innerHTML = "Width: " + w + "
" + " Height: " + h;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="innerSize"></div></code>```

Body:
In this code, I feel like I am repeating myself to much. Is there anyway to make the code look cleaner or put it in one function?

Yes, you are repeating yourself too much.  Set the same functions all in one go (or split them up in separate lines -- coders choice), either way, set them to the same function.

var pageSize = document.getElementById("innerSize");

window.onload = window.onresize = setWidth;

function setWidth() {
  var w = document.documentElement.clientWidth;
  var h = document.documentElement.clientHeight;

  pageSize.innerHTML = "Width: " + w + "<br>" + " Height: " + h;
}

<div id="innerSize"></div>


问:
extract specific data from numpy ndarray
New to pandas any help is appreciated

```<code>def csv_reader(fileName):
    reqcols=['_id__$oid','payload','channel']
    io = pd.read_csv(fileName,sep=",",usecols=reqcols)
    print(io['payload'].values)
    return io
</code>```

Output row of io['payload']:

```<code>{
    "destination_ip": "172.31.14.66",
    "date": "2014-10-19T01:32:36.669861",
    "classification": "Potentially Bad Traffic",
    "proto": "UDP",
    "source_ip": "172.31.0.2",
    "priority": "`2",
    "header": "1:2003195:5",
    "signature": "ET POLICY Unusual number of DNS No Such Name Responses ",
    "source_port": "53",
    "destination_port": "34638",
    "sensor": "5cda4a12-4730-11e4-9ee4-0a0b6e7c3e9e"
}
</code>```

I am trying to extract specific data from the ndarray object. What is the method that can be used to extract from the dataframe

```<code>"destination_ip": "172.31.13.124",
"proto": "ICMP",
"source_ip": "201.158.32.1",
"date": "2014-09-28T14:49:43.391463",
"sensor": "139cfdf2-471e-11e4-9ee4-0a0b6e7c3e9e"
</code>```

答:
I think you need first convert string reperesentation of dicts to dictionaries in each row by json.loads or ast.literal_eval in column payload, then create new DataFrame by constructor, filter columns by subset, and if necessary add original columns by concat:

```<code>d = {'_id__$oid': ['542f8', '542f8', '542f8'], 'channel': ['snort_alert', 'snort_alert', 'snort_alert'], 'payload': ['{"destination_ip":"172.31.14.66","date": "2014-10-19T01:32:36.669861","classification":"Potentially Bad Traffic","proto":"UDP","source_ip":"172.31.0.2","priority":"2","header":"1:2003195:5","signature":"ET POLICY Unusual number of DNS No Such Name Responses ","source_port":"53","destination_port":"34638","sensor":"5cda4a12-4730-11e4-9ee4-0a0b6e7c3e9e"}', '{"destination_ip":"172.31.14.66","date": "2014-10-19T01:32:36.669861","classification":"Potentially Bad Traffic","proto":"UDP","source_ip":"172.31.0.2","priority":"2","header":"1:2003195:5","signature":"ET POLICY Unusual number of DNS No Such Name Responses ","source_port":"53","destination_port":"34638","sensor":"5cda4a12-4730-11e4-9ee4-0a0b6e7c3e9e"}', '{"destination_ip":"172.31.14.66","date": "2014-10-19T01:32:36.669861","classification":"Potentially Bad Traffic","proto":"UDP","source_ip":"172.31.0.2","priority":"2","header":"1:2003195:5","signature":"ET POLICY Unusual number of DNS No Such Name Responses ","source_port":"53","destination_port":"34638","sensor":"5cda4a12-4730-11e4-9ee4-0a0b6e7c3e9e"}']}
reqcols=['_id__$oid','payload','channel']
df = pd.DataFrame(d)
print (df)
  _id__$oid      channel                                            payload
0     542f8  snort_alert  {"destination_ip":"172.31.14.66","date": "2014...
1     542f8  snort_alert  {"destination_ip":"172.31.14.66","date": "2014...
2     542f8  snort_alert  {"destination_ip":"172.31.14.66","date": "2014...
</code>```

```<code>import json
import ast
df.payload = df.payload.apply(json.loads)
#another slowier solution
#df.payload = df.payload.apply(ast.literal_eval)

required = ["destination_ip", "proto", "source_ip", "date", "sensor"]
df1 = pd.DataFrame(df.payload.values.tolist())[required]
print (df1)
  destination_ip proto   source_ip                        date  \
0   172.31.14.66   UDP  172.31.0.2  2014-10-19T01:32:36.669861
1   172.31.14.66   UDP  172.31.0.2  2014-10-19T01:32:36.669861
2   172.31.14.66   UDP  172.31.0.2  2014-10-19T01:32:36.669861

                                 sensor
0  5cda4a12-4730-11e4-9ee4-0a0b6e7c3e9e
1  5cda4a12-4730-11e4-9ee4-0a0b6e7c3e9e
2  5cda4a12-4730-11e4-9ee4-0a0b6e7c3e9e

df2 = pd.concat([df[['_id__$oid','channel']], df1], axis=1)
print (df2)
  _id__$oid      channel destination_ip proto   source_ip  \
0     542f8  snort_alert   172.31.14.66   UDP  172.31.0.2
1     542f8  snort_alert   172.31.14.66   UDP  172.31.0.2
2     542f8  snort_alert   172.31.14.66   UDP  172.31.0.2

                         date                                sensor
0  2014-10-19T01:32:36.669861  5cda4a12-4730-11e4-9ee4-0a0b6e7c3e9e
1  2014-10-19T01:32:36.669861  5cda4a12-4730-11e4-9ee4-0a0b6e7c3e9e
2  2014-10-19T01:32:36.669861  5cda4a12-4730-11e4-9ee4-0a0b6e7c3e9e
</code>```

Timings:

```<code>#[30000 rows x 3 columns]
df = pd.concat([df]*10000).reset_index(drop=True)
print (df)

In [38]: %timeit pd.DataFrame(df.payload.apply(json.loads).values.tolist())[required]
1 loop, best of 3: 379 ms per loop

In [39]: %timeit pd.read_json('[{}]'.format(df.payload.str.cat(sep=',')))[required]
1 loop, best of 3: 528 ms per loop

In [40]: %timeit pd.DataFrame(df.payload.apply(ast.literal_eval).values.tolist())[required]
1 loop, best of 3: 1.98 s per loop
</code>```

Body:
New to pandas any help is appreciated

def csv_reader(fileName):
    reqcols=['_id__$oid','payload','channel']
    io = pd.read_csv(fileName,sep=",",usecols=reqcols)
    print(io['payload'].values)
    return io

Output row of io['payload']:

{
    "destination_ip": "172.31.14.66",
    "date": "2014-10-19T01:32:36.669861",
    "classification": "Potentially Bad Traffic",
    "proto": "UDP",
    "source_ip": "172.31.0.2",
    "priority": "`2",
    "header": "1:2003195:5",
    "signature": "ET POLICY Unusual number of DNS No Such Name Responses ",
    "source_port": "53",
    "destination_port": "34638",
    "sensor": "5cda4a12-4730-11e4-9ee4-0a0b6e7c3e9e"
}

I am trying to extract specific data from the ndarray object. What is the method that can be used to extract from the dataframe

"destination_ip": "172.31.13.124",
"proto": "ICMP",
"source_ip": "201.158.32.1",
"date": "2014-09-28T14:49:43.391463",
"sensor": "139cfdf2-471e-11e4-9ee4-0a0b6e7c3e9e"

Body:
I think you need first convert string reperesentation of dicts to dictionaries in each row by json.loads or ast.literal_eval in column payload, then create new DataFrame by constructor, filter columns by subset, and if necessary add original columns by concat:

d = {'_id__$oid': ['542f8', '542f8', '542f8'], 'channel': ['snort_alert', 'snort_alert', 'snort_alert'], 'payload': ['{"destination_ip":"172.31.14.66","date": "2014-10-19T01:32:36.669861","classification":"Potentially Bad Traffic","proto":"UDP","source_ip":"172.31.0.2","priority":"2","header":"1:2003195:5","signature":"ET POLICY Unusual number of DNS No Such Name Responses ","source_port":"53","destination_port":"34638","sensor":"5cda4a12-4730-11e4-9ee4-0a0b6e7c3e9e"}', '{"destination_ip":"172.31.14.66","date": "2014-10-19T01:32:36.669861","classification":"Potentially Bad Traffic","proto":"UDP","source_ip":"172.31.0.2","priority":"2","header":"1:2003195:5","signature":"ET POLICY Unusual number of DNS No Such Name Responses ","source_port":"53","destination_port":"34638","sensor":"5cda4a12-4730-11e4-9ee4-0a0b6e7c3e9e"}', '{"destination_ip":"172.31.14.66","date": "2014-10-19T01:32:36.669861","classification":"Potentially Bad Traffic","proto":"UDP","source_ip":"172.31.0.2","priority":"2","header":"1:2003195:5","signature":"ET POLICY Unusual number of DNS No Such Name Responses ","source_port":"53","destination_port":"34638","sensor":"5cda4a12-4730-11e4-9ee4-0a0b6e7c3e9e"}']}
reqcols=['_id__$oid','payload','channel']
df = pd.DataFrame(d)
print (df)
  _id__$oid      channel                                            payload
0     542f8  snort_alert  {"destination_ip":"172.31.14.66","date": "2014...
1     542f8  snort_alert  {"destination_ip":"172.31.14.66","date": "2014...
2     542f8  snort_alert  {"destination_ip":"172.31.14.66","date": "2014...

import json
import ast
df.payload = df.payload.apply(json.loads)
#another slowier solution
#df.payload = df.payload.apply(ast.literal_eval)

required = ["destination_ip", "proto", "source_ip", "date", "sensor"]
df1 = pd.DataFrame(df.payload.values.tolist())[required]
print (df1)
  destination_ip proto   source_ip                        date  \
0   172.31.14.66   UDP  172.31.0.2  2014-10-19T01:32:36.669861
1   172.31.14.66   UDP  172.31.0.2  2014-10-19T01:32:36.669861
2   172.31.14.66   UDP  172.31.0.2  2014-10-19T01:32:36.669861

                                 sensor
0  5cda4a12-4730-11e4-9ee4-0a0b6e7c3e9e
1  5cda4a12-4730-11e4-9ee4-0a0b6e7c3e9e
2  5cda4a12-4730-11e4-9ee4-0a0b6e7c3e9e

df2 = pd.concat([df[['_id__$oid','channel']], df1], axis=1)
print (df2)
  _id__$oid      channel destination_ip proto   source_ip  \
0     542f8  snort_alert   172.31.14.66   UDP  172.31.0.2
1     542f8  snort_alert   172.31.14.66   UDP  172.31.0.2
2     542f8  snort_alert   172.31.14.66   UDP  172.31.0.2

                         date                                sensor
0  2014-10-19T01:32:36.669861  5cda4a12-4730-11e4-9ee4-0a0b6e7c3e9e
1  2014-10-19T01:32:36.669861  5cda4a12-4730-11e4-9ee4-0a0b6e7c3e9e
2  2014-10-19T01:32:36.669861  5cda4a12-4730-11e4-9ee4-0a0b6e7c3e9e

Timings:

#[30000 rows x 3 columns]
df = pd.concat([df]*10000).reset_index(drop=True)
print (df)

In [38]: %timeit pd.DataFrame(df.payload.apply(json.loads).values.tolist())[required]
1 loop, best of 3: 379 ms per loop

In [39]: %timeit pd.read_json('[{}]'.format(df.payload.str.cat(sep=',')))[required]
1 loop, best of 3: 528 ms per loop

In [40]: %timeit pd.DataFrame(df.payload.apply(ast.literal_eval).values.tolist())[required]
1 loop, best of 3: 1.98 s per loop


问:
Controller not calling in AngularJS
I am facing problem in call to controller in child ui state router.

URL is changing but controller not call.

no console error*

Please check code:

HTML

```<code><a style="cursor: pointer;" class="btn btn-default btn-xs"  ui-sref="interactions.details({id:n.id})">Detail</a>
</code>```

Router

```<code>.state('interactions', {
            url: '/interactions',
            data: {
                pageTitle: 'Interaction',
                IsLoginPage: false
            },
            templateUrl: '../../modules/interaction/views/interaction.html',
            controller: 'interactionCtl'
        })
        .state('interactions.details', {
            url:'/details/:id',
            data: {
                pageTitle: 'Interaction Details',
                IsLoginPage: false
            },
            templateUrl: '../../modules/interaction/views/interactionDetail.html',
            controller:'interactionCtlDetails'
        }).run(function ($rootScope, settings, $cookies, $http, $location, AuthenticationService, $state, $stateParams) {

    $rootScope.$state = $state;
    $rootScope.$stateParams = $stateParams;

});
</code>```

Controller

```<code>    warApp.controller('interactionCtlDetails', ["$scope", '$rootScope','$stateParams', 'settings', 'categoryService', 'blockUI',
        function ($scope, interactionService, $rootScope, $stateParams ,settings, categoryService, blockUI) {

            var id = $stateParams.id;
console.log(id);

    });
</code>```

答:
Annotation array should be in sync with the parameters in the function declaration.Here annotation array is not in sync with the parameters in the function declaration.

Second parameter in your annotation array is 'interactionService' but in function, thats 'rootScope'.

Try with below controller code

```<code>warApp.controller('interactionCtlDetails', ['$scope', '$rootScope', '$stateParams', 'settings', 'categoryService', 'blockUI',
function ($scope, $rootScope, $stateParams ,settings, categoryService, blockUI) {
        var id = $stateParams.id;
        console.log(id);
});
</code>```

Title: Controller not calling in AngularJS

Body:
I am facing problem in call to controller in child ui state router.

URL is changing but controller not call.

no console error*

Please check code:

HTML

Detail

Router

.state('interactions', {
            url: '/interactions',
            data: {
                pageTitle: 'Interaction',
                IsLoginPage: false
            },
            templateUrl: '../../modules/interaction/views/interaction.html',
            controller: 'interactionCtl'
        })
        .state('interactions.details', {
            url:'/details/:id',
            data: {
                pageTitle: 'Interaction Details',
                IsLoginPage: false
            },
            templateUrl: '../../modules/interaction/views/interactionDetail.html',
            controller:'interactionCtlDetails'
        }).run(function ($rootScope, settings, $cookies, $http, $location, AuthenticationService, $state, $stateParams) {

    $rootScope.$state = $state;
    $rootScope.$stateParams = $stateParams;

});

Controller

    warApp.controller('interactionCtlDetails', ["$scope", '$rootScope','$stateParams', 'settings', 'categoryService', 'blockUI',
        function ($scope, interactionService, $rootScope, $stateParams ,settings, categoryService, blockUI) {

            var id = $stateParams.id;
console.log(id);

    });

Body:
Annotation array should be in sync with the parameters in the function declaration.Here annotation array is not in sync with the parameters in the function declaration.

Second parameter in your annotation array is 'interactionService' but in function, thats 'rootScope'.

Try with below controller code

warApp.controller('interactionCtlDetails', ['$scope', '$rootScope', '$stateParams', 'settings', 'categoryService', 'blockUI',
function ($scope, $rootScope, $stateParams ,settings, categoryService, blockUI) {
        var id = $stateParams.id;
        console.log(id);
});


问:
how to group identical instances in r into one and at the same time, generate frequency and average stats?
I'm at the last stage of cleaning/organizing data and would appreciate suggestions for this step. I'm new to R and don't understand fully how dataframes or other data types work. (I'm trying to learn but have a project due so need a quick solution). I've imported the data from a CSV file.

I want to group instances with the same (date, ID1, ID2, ID3). I want the average of all stats in the output and also a new column with the number of instances grouped.

Note: ID3 contains . I'd like to rename these to "na" before grouping
I've tried solutions

```<code>tdata$ID3[is.na(tdata$ID3)] <- "NA"
tdata[["ID3"]][is.na(tdata[["ID3"]])] <- "NA"
</code>```

But get Error:

```<code>In `[<-.factor`(`*tmp*`, is.na(tdata[["ID3"]]), value = c(3L, 3L,  :
  invalid factor level, NA generated
</code>```

The data is:

```<code>      date     ID1     ID2     ID3 stat1 stat2 stat.3
1 12-03-07  abc123  wxy456  pqr123    10    20     30
2 12-03-07  abc123  wxy456  pqr123    20    40     60
3 10-04-07  bcd456  wxy456  hgf356    10    20     40
4 12-03-07  abc123  wxy456  pqr123    30    60     90
5  5-09-07  spa234  int345   <NA>     40    50     70
</code>```

Desired Output

```<code>date      ID1,     ID2,   ID3,   n, stat1, stat2, stat 3
12-03-07 abc123, wxy456, pqr457, 3,   20,   40, 60
10-04-07 bcd456, wxy456, hgf356, 1,   10,   20, 40
05-09-07 spa234, int345, big234, 1 ,  40,   50, 70
</code>```

I tried this solution: How to merge multiple data.frames and sum and average columns at the same time in R

But I was not successful merging the columns which have to be grouped and tested for similarity.

```<code>DF <- merge(tdata$date, tdata$ID1, tdata$ID2, tdata$ID3, by = "Name", all = T)

Error in fix.by(by.x, x) : 'by' must specify uniquely valid columns
</code>```

Finally, to generate the n column. Perhaps insert a rows of 1s and use the sum of the column while summarizing?

答:
We can do this with dplyr.  After grouping by the 'ID' columns, add 'date' and 'n' also in the grouping variables, and get the mean of 'stat' columns

```<code>library(dplyr)
df1 %>%
   group_by(ID1, ID2, ID3) %>%
   group_by(date = first(date), n =n(), add=TRUE)  %>%
   summarise_at(vars(matches("stat")), mean)
</code>```

NOTE: Regarding change the 'NA' to 'big234', we can convert the 'ID3' to character class and change it before doing the above operation

```<code>df1$ID3 <- as.character(df1$ID3)
df1$ID3[is.na(df1$ID3)] <- "big234"
</code>```

Body:
I'm at the last stage of cleaning/organizing data and would appreciate suggestions for this step. I'm new to R and don't understand fully how dataframes or other data types work. (I'm trying to learn but have a project due so need a quick solution). I've imported the data from a CSV file.

I want to group instances with the same (date, ID1, ID2, ID3). I want the average of all stats in the output and also a new column with the number of instances grouped.

Note: ID3 contains . I'd like to rename these to "na" before grouping
I've tried solutions

tdata$ID3[is.na(tdata$ID3)] <- "NA"
tdata[["ID3"]][is.na(tdata[["ID3"]])] <- "NA"

But get Error:

In `[<-.factor`(`*tmp*`, is.na(tdata[["ID3"]]), value = c(3L, 3L,  :
  invalid factor level, NA generated

The data is:

      date     ID1     ID2     ID3 stat1 stat2 stat.3
1 12-03-07  abc123  wxy456  pqr123    10    20     30
2 12-03-07  abc123  wxy456  pqr123    20    40     60
3 10-04-07  bcd456  wxy456  hgf356    10    20     40
4 12-03-07  abc123  wxy456  pqr123    30    60     90
5  5-09-07  spa234  int345   <NA>     40    50     70

Desired Output

date      ID1,     ID2,   ID3,   n, stat1, stat2, stat 3
12-03-07 abc123, wxy456, pqr457, 3,   20,   40, 60
10-04-07 bcd456, wxy456, hgf356, 1,   10,   20, 40
05-09-07 spa234, int345, big234, 1 ,  40,   50, 70

I tried this solution: How to merge multiple data.frames and sum and average columns at the same time in R

But I was not successful merging the columns which have to be grouped and tested for similarity.

DF <- merge(tdata$date, tdata$ID1, tdata$ID2, tdata$ID3, by = "Name", all = T)

Error in fix.by(by.x, x) : 'by' must specify uniquely valid columns

Finally, to generate the n column. Perhaps insert a rows of 1s and use the sum of the column while summarizing?

Body:
We can do this with dplyr.  After grouping by the 'ID' columns, add 'date' and 'n' also in the grouping variables, and get the mean of 'stat' columns

library(dplyr)
df1 %>%
   group_by(ID1, ID2, ID3) %>%
   group_by(date = first(date), n =n(), add=TRUE)  %>%
   summarise_at(vars(matches("stat")), mean)

NOTE: Regarding change the 'NA' to 'big234', we can convert the 'ID3' to character class and change it before doing the above operation

df1$ID3 <- as.character(df1$ID3)
df1$ID3[is.na(df1$ID3)] <- "big234"


问:
Generating PDF's from form responses with a template.
I'm currently using Form Publisher add in to make PDF's from the form responses with my required template but it is allowing me to generate only 100 files in a month. I have requirement with minimum of 500 files in month and I cannot afford premium license purchase for Form Publisher. Please help me with the basic script to generate PDF's based on form response data with my desired template.

I will share the template and sample sheet if it can be done.

Regards
Gopikrishna

答: What tools are available for your usage? If you use pdftk, there is a fill_form command that can take a PDF & FDF/XFDF data, and combine the two.


问:
Flask redis server session: Error in save_session
Folks:
I am moving my Flask app with redis for session storage into docker containers. My app runs happily when redis is run locally. However, when running a docker-compose with a redis image, I see the following error. I get an identical error whether my redis container is running or stopped:

```<code>2017-04-02 03:36:09,861] ERROR in app: Exception on / [GET]
web_1    | Traceback (most recent call last):
web_1    |   File "/usr/local/lib/python2.7/site-packages/flask/app.py", line 1988, in wsgi_app
web_1    |     response = self.full_dispatch_request()
web_1    |   File "/usr/local/lib/python2.7/site-packages/flask/app.py", line 1643, in full_dispatch_request
web_1    |     response = self.process_response(response)
web_1    |   File "/usr/local/lib/python2.7/site-packages/flask/app.py", line 1864, in process_response
web_1    |     self.save_session(ctx.session, response)
web_1    |   File "/usr/local/lib/python2.7/site-packages/flask/app.py", line 926, in save_session
web_1    |     return self.session_interface.save_session(self, session, response)
web_1    |   File "/usr/local/lib/python2.7/site-packages/flask_session/sessions.py", line 165, in save_session
web_1    |     self.redis.setex(name=self.key_prefix + session.sid, value=val,
web_1    | AttributeError: 'str' object has no attribute 'setex'
</code>```

I have added the following configuration properties to my app for session config:

```<code>SESSION_TYPE = "redis"
SESSION_REDIS = "redis:6379"
</code>```

I don't think this is a docker-compose issue as my app is successfully able to connect to the MySQL instance, still, here is my docker-compose.yml file just in case it points to something:

```<code>version: "3"
services:
  mysql:
    build:
      context: db/
  web:
    build:
      context: web/
    ports:
    - "10080:80"
    depends_on:
    - "mysql"
    - "redis"
  redis:
    image: "redis:alpine"
</code>```

答:
Figured it out. The issue was in session config. I had to change </p>

```<code>SESSION_REDIS = "redis:6379"
</code>```

<p>to </p>

```<code>SESSION_REDIS = redis.Redis("redis")
</code>```

Body:
Folks:
I am moving my Flask app with redis for session storage into docker containers. My app runs happily when redis is run locally. However, when running a docker-compose with a redis image, I see the following error. I get an identical error whether my redis container is running or stopped:

2017-04-02 03:36:09,861] ERROR in app: Exception on / [GET]
web_1    | Traceback (most recent call last):
web_1    |   File "/usr/local/lib/python2.7/site-packages/flask/app.py", line 1988, in wsgi_app
web_1    |     response = self.full_dispatch_request()
web_1    |   File "/usr/local/lib/python2.7/site-packages/flask/app.py", line 1643, in full_dispatch_request
web_1    |     response = self.process_response(response)
web_1    |   File "/usr/local/lib/python2.7/site-packages/flask/app.py", line 1864, in process_response
web_1    |     self.save_session(ctx.session, response)
web_1    |   File "/usr/local/lib/python2.7/site-packages/flask/app.py", line 926, in save_session
web_1    |     return self.session_interface.save_session(self, session, response)
web_1    |   File "/usr/local/lib/python2.7/site-packages/flask_session/sessions.py", line 165, in save_session
web_1    |     self.redis.setex(name=self.key_prefix + session.sid, value=val,
web_1    | AttributeError: 'str' object has no attribute 'setex'

I have added the following configuration properties to my app for session config:

SESSION_TYPE = "redis"
SESSION_REDIS = "redis:6379"

I don't think this is a docker-compose issue as my app is successfully able to connect to the MySQL instance, still, here is my docker-compose.yml file just in case it points to something:

version: "3"
services:
  mysql:
    build:
      context: db/
  web:
    build:
      context: web/
    ports:
    - "10080:80"
    depends_on:
    - "mysql"
    - "redis"
  redis:
    image: "redis:alpine"

Body:
Figured it out. The issue was in session config. I had to change

SESSION_REDIS = "redis:6379"

to

SESSION_REDIS = redis.Redis("redis")


问:
Mongoose Model Methods: Properties don't save?
I'm trying to write a method on a mongoose model that will populate some fields based on an object I pass in.

```<code>let mySchema = mongoose.Schema({
    name: String,
    age: Number,
    street: { type: String, default: 'No' }
});

mySchema.methods.populate = function(o) {
    this.age = o.age + 10;
});
</code>```

Elsewhere, i'll initialize an instance and run the method:

```<code>let newThing = new MySchema();
newThing.populate({ age: 12 });
newThing.save();
</code>```

This successfully saves a new object in mongo with no properties other than the default street name. Am I doing something wrong?

答:
You can refer to this code which will work.

In server.js

```<code>    var mongoose = require('mongoose')
    var Model = require('./model')

    mongoose.Promise = global.Promise;
    mongoose.connect('**dbUrl**')

    var NewData = new Model({
        name: 'Tolsee'
    })

    NewData.populate({ age: 15 })

    NewData.save(function(err){
        if (err) {
            throw err
        }else{
            console.log('Your data is saved successfully')
        }
    })
</code>```

In model.js

```<code>var mongoose = require('mongoose')
var Schema = mongoose.Schema

const customSchema = new Schema({
    name: String,
    age: Number,
    street: { type: String, default: 'No' }
})

// Custom function
customSchema.methods.populate = function(o) {
    this.age = o.age
    return this.age
}

// create the model to export
var custom = mongoose.model('customModel', customSchema)

module.exports = custom
</code>```

First, You will need to create a model in order to use the schema. Instance of these models are documents which can use the custom methods you define.

Body:
I'm trying to write a method on a mongoose model that will populate some fields based on an object I pass in.

let mySchema = mongoose.Schema({
    name: String,
    age: Number,
    street: { type: String, default: 'No' }
});

mySchema.methods.populate = function(o) {
    this.age = o.age + 10;
});

Elsewhere, i'll initialize an instance and run the method:

let newThing = new MySchema();
newThing.populate({ age: 12 });
newThing.save();

This successfully saves a new object in mongo with no properties other than the default street name. Am I doing something wrong?

Body:
You can refer to this code which will work.

In server.js

    var mongoose = require('mongoose')
    var Model = require('./model')

    mongoose.Promise = global.Promise;
    mongoose.connect('**dbUrl**')

    var NewData = new Model({
        name: 'Tolsee'
    })

    NewData.populate({ age: 15 })

    NewData.save(function(err){
        if (err) {
            throw err
        }else{
            console.log('Your data is saved successfully')
        }
    })

In model.js

var mongoose = require('mongoose')
var Schema = mongoose.Schema

const customSchema = new Schema({
    name: String,
    age: Number,
    street: { type: String, default: 'No' }
})

// Custom function
customSchema.methods.populate = function(o) {
    this.age = o.age
    return this.age
}

// create the model to export
var custom = mongoose.model('customModel', customSchema)

module.exports = custom

First, You will need to create a model in order to use the schema. Instance of these models are documents which can use the custom methods you define.


问:
Max bitrate value for Google chrome browser
I have a simple question.

What is the current maximum bitrate value supported by Google Chrome browser for web camera ?

For example, if I have a virtual source with high bitrate output (constant bitrate 50 Mbits)

Would I be able to get all 50 Mbits in my Chrome browser when using this device?

Thank you.

答:
The camera's bitrate is irrelevant in this case, since WebRTC is going to encode that information using a video codec that compresses that information anyway.

What matters for WebRTC are 4 separate parameters:

The resolution supplied and the one the other end of the session is capable of receiving

The frame rate supplied and the one the other end of the session is capable of receiving

The network conditions - there's a limit enforced by the network and it is dynamic in nature, so WebRTC will try to estimate it at all times and accommodate to it

The maximum bitrate imposed by the participants

WebRTC in its nature will not limit the amount of bandwidth it takes and will try to use as much as it possibly can. That said, the actual bitrate used even without any limits will still depend on (1), (2) and the type of codec being used. It won't reach 50mbps...

For the most part, 2.5mbps will be enough for almost any type of content in WebRTC. 1080p will take up to 4mbps and 4K probably around 15mbps.


问:
What does these ACPI names mean?
I dumped the ACPI tables on my laptop with the RW Everything. But I don't know what all these strange abbreviations mean.

I can guess _PR stands for processor, but where can I look up the others?

ADD 1

I have a feeling that these names are arbitrary. They are just variables. Variable names can be anything. It is their values that matter. And the values are assigned in operation regions to indicate addresses.

答:
The ACPI Specification lists many predefined names.
Yes, _PR is for the Processor Namespace, but it is depreciated.

PNTF and XWMB are not defined in the specification. You can read Section 5.3 ACPI Namespace for the rules for naming. The important thing is that these 32-bit identifiers must be globally unique so that they can be referenced. The manufacturer will have defined these, and without more context it will be hard to guess their use.

_SB (System Bus) is another pre-defined root namespace, see 5.3.1 Predefined Root Namespaces.
All Device/Bus Objects are defined under this (_SB) namespace.

6.5.1 _INI (Init):
_INI is a device initialization object that performs device specific initialization. This control method is located under a device object and is run only when OSPM loads a description table.

6.2.11 _OSC (Operating System Capabilities)
This optional object is a control method that is used by OSPM to communicate to the platform the feature support or capabilities provided by a device’s driver.

LNKA-LNKH have to do with PCI interrupt routing.

And so forth. Go through the ones you are interested in and search in the ACPI specification. If it isn't in the specification you might be able to guess, but without more information it will be difficult.

The main thing to note about these labels is that they are used in other blocks to reference data or methods or to coordinate events. This is how the OS can go from something happening to taking the correct device specific actions, e.g. putting a device into a low power mode when a timer expires to indicate no user activity for some length of time specified by an OS power scheme. These labels are not just variables though, they often have methods (like that _INI one) associated with them. Those methods can get called from the OS directly or from other blocks.

Title: What does these ACPI names mean?


问:
How to get Erlang to show UI components "debugger" and "observer" on Linux?
I'm running Kubuntu 15.04 64-bit and trying to get Erlang's 18.1 'debugger' or 'observer' to run (EDIT: from within the shell):

```<code>observer:start().
debugger:start().
</code>```

I get the following error:

```<code>{error,{{load_driver,"No driver found"},
    [{wxe_server,start,1,[{file,"wxe_server.erl"},{line,65}]},
     {wx,new,1,[{file,"wx.erl"},{line,115}]},
     {observer_wx,init,1,[{file,"observer_wx.erl"},{line,96}]},
     {wx_object,init_it,6,[{file,"wx_object.erl"},{line,337}]},
     {proc_lib,init_p_do_apply,3,
               [{file,"proc_lib.erl"},{line,240}]}]}}

ERROR REPORT==== 4-Oct-2015::15:34:01 ===
ERROR: Could not find 'wxe_driver.so' in: /home/howler/erlang/18.1/lib/wx-1.5/priv
</code>```

I've tried various forums and have followed the prescribed advice concerning wxWidgets but I still can't get it to work?

Does anyone know of a definitive way to solve this problem?

答:
If someone struggling with this issue in "asdf" version manager in ubuntu then you need to install following packages

sudo apt-get -y install libwxgtk3.0-dev libgl1-mesa-dev libglu1-mesa-dev libpng3

Body:
I'm running Kubuntu 15.04 64-bit and trying to get Erlang's 18.1 'debugger' or 'observer' to run (EDIT: from within the shell):

observer:start().
debugger:start().

I get the following error:

{error,{{load_driver,"No driver found"},
    [{wxe_server,start,1,[{file,"wxe_server.erl"},{line,65}]},
     {wx,new,1,[{file,"wx.erl"},{line,115}]},
     {observer_wx,init,1,[{file,"observer_wx.erl"},{line,96}]},
     {wx_object,init_it,6,[{file,"wx_object.erl"},{line,337}]},
     {proc_lib,init_p_do_apply,3,
               [{file,"proc_lib.erl"},{line,240}]}]}}

ERROR REPORT==== 4-Oct-2015::15:34:01 ===
ERROR: Could not find 'wxe_driver.so' in: /home/howler/erlang/18.1/lib/wx-1.5/priv

I've tried various forums and have followed the prescribed advice concerning wxWidgets but I still can't get it to work?

Does anyone know of a definitive way to solve this problem?


问:
Wordpress image links 404
Im migrating a wordpress site for the first time. I can get the site to load here: http://www.foureyescomic.com/ by updating the config file and the database table like this:

But now I'm getting images with broken links like this:

答:
Yep, that happens because the absolute URLs of the images are stored as text within your posts' content in the wp_posts table. If your site's backend is functioning, you can use a database find/replace plugin to find the old urls in that table and replace them with the new urls. Or you can just do it with SQL/phpMyadmin if you're comfortable with that.

I find the easiest is by using this plugin: Better Search & Replace

It's pretty straightforward from there:

Install and activate the plugin, then in wp-admin go to Tools > Better Search Replace.

In the Search For field, put your old url. Ex:  http://www.oldurl.com

Then in Replace With put your new url. Ex:  http://www.newurl.com

In the Select tables section select wp_posts (or whatever your posts table is if you use a differnet prefix)

You can leave Run as dry run? checked if you want to do a dry run first to see what'll be changed. If it's unchecked, the changes will be made in your database.

Hit the Search/Replace button and that should do it!

Make sure you're using the exact strings you want to find and replace, and think about whether the search string could potentially occur anywhere else in that table where you wouldn't want it to change, otherwise you could screw things up. You should definitely have your DB backed up before you run this.

Hope that helps.

Title: Wordpress image links 404


问:
Android- making 2 buttons side by side
Hey guys so I did look at other questions regarding this and I even looked online and I see nothing wrong with my code but every time I try to make a AVD to check out how the app looks the buttons dont show side by side but in android studio render screen it does.

If anyone could help I would be really thankful!

This is once i load the AVD in android studio

This is how is shows in the render in android studio

```<code>    <?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/activity_main"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.example.jarvis.imquest.MainActivity">

    <ImageView
        android:id="@+id/image_message"
        android:src="@drawable/ic_message"
        android:layout_marginTop="20dp"
        android:layout_centerHorizontal="true"
        android:layout_width="100dp"
        android:layout_height="100dp" />

    <LinearLayout
        android:orientation="vertical"
        android:layout_below="@+id/image_message"
        android:id="@+id/group_login"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

        <android.support.design.widget.TextInputLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content">

            <EditText
                android:id="@+id/main_editLogin"
                android:hint="Enter Username"
                android:padding="5dp"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"/>
        </android.support.design.widget.TextInputLayout>

        <android.support.design.widget.TextInputLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content">

            <EditText
                android:id="@+id/main_editPassword"
                android:hint="Enter Password"
                android:padding="5dp"
                android:inputType="textPassword"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"/>
        </android.support.design.widget.TextInputLayout>
    </LinearLayout>

    <LinearLayout
        android:layout_below="@+id/group_login"
        android:orientation="horizontal"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:weightSum="2">

        <Button
            android:layout_weight="1"
            android:id="@+id/main_btnLogin"
            android:background="@color/colorPrimaryDark"
            android:textColor="@color/colorAccent"
            android:text="Login"
            android:layout_marginRight="5dp"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            style="@style/Widget.AppCompat.Button.Borderless"
            />

        <Button
            android:layout_weight="1"
            android:id="@+id/main_btnSignup"
            android:background="@color/colorPrimaryDark"
            android:textColor="@color/colorAccent"
            android:text="SignUp"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            style="@style/Widget.AppCompat.Button.Borderless"
            />
    </LinearLayout>

</RelativeLayout>
</code>```

答:
Add attribute android:weightSum="2" to your LinearLayout and remove attributeandroid:layout_toRightOf="@+id/main_btnLogin" from signup button.

Try this:

```<code>    <LinearLayout
        android:layout_below="@+id/group_login"
        android:orientation="horizontal"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:weightSum="2">

        <Button
            android:layout_weight="1"
            android:id="@+id/main_btnLogin"
            android:background="@color/colorPrimaryDark"
            android:textColor="@color/colorAccent"
            android:text="Login"
            android:layout_marginRight="5dp"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            style="@style/Widget.AppCompat.Button.Borderless"
            />

        <Button
            android:layout_weight="1"
            android:id="@+id/main_btnSignup"
            android:background="@color/colorPrimaryDark"
            android:textColor="@color/colorAccent"
            android:text="SignUp"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            style="@style/Widget.AppCompat.Button.Borderless"
            />
    </LinearLayout>
</code>```

OUTPUT on my Galaxy Note3 device:

Title: Android- making 2 buttons side by side

Body:
Hey guys so I did look at other questions regarding this and I even looked online and I see nothing wrong with my code but every time I try to make a AVD to check out how the app looks the buttons dont show side by side but in android studio render screen it does.

If anyone could help I would be really thankful!

This is once i load the AVD in android studio

This is how is shows in the render in android studio

    <?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/activity_main"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.example.jarvis.imquest.MainActivity">

    <ImageView
        android:id="@+id/image_message"
        android:src="@drawable/ic_message"
        android:layout_marginTop="20dp"
        android:layout_centerHorizontal="true"
        android:layout_width="100dp"
        android:layout_height="100dp" />

    <LinearLayout
        android:orientation="vertical"
        android:layout_below="@+id/image_message"
        android:id="@+id/group_login"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

        <android.support.design.widget.TextInputLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content">

            <EditText
                android:id="@+id/main_editLogin"
                android:hint="Enter Username"
                android:padding="5dp"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"/>
        </android.support.design.widget.TextInputLayout>

        <android.support.design.widget.TextInputLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content">

            <EditText
                android:id="@+id/main_editPassword"
                android:hint="Enter Password"
                android:padding="5dp"
                android:inputType="textPassword"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"/>
        </android.support.design.widget.TextInputLayout>
    </LinearLayout>

    <LinearLayout
        android:layout_below="@+id/group_login"
        android:orientation="horizontal"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:weightSum="2">

        <Button
            android:layout_weight="1"
            android:id="@+id/main_btnLogin"
            android:background="@color/colorPrimaryDark"
            android:textColor="@color/colorAccent"
            android:text="Login"
            android:layout_marginRight="5dp"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            style="@style/Widget.AppCompat.Button.Borderless"
            />

        <Button
            android:layout_weight="1"
            android:id="@+id/main_btnSignup"
            android:background="@color/colorPrimaryDark"
            android:textColor="@color/colorAccent"
            android:text="SignUp"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            style="@style/Widget.AppCompat.Button.Borderless"
            />
    </LinearLayout>

</RelativeLayout>

Body:
Add attribute android:weightSum="2" to your LinearLayout and remove attributeandroid:layout_toRightOf="@+id/main_btnLogin" from signup button.

Try this:

    <LinearLayout
        android:layout_below="@+id/group_login"
        android:orientation="horizontal"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:weightSum="2">

        <Button
            android:layout_weight="1"
            android:id="@+id/main_btnLogin"
            android:background="@color/colorPrimaryDark"
            android:textColor="@color/colorAccent"
            android:text="Login"
            android:layout_marginRight="5dp"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            style="@style/Widget.AppCompat.Button.Borderless"
            />

        <Button
            android:layout_weight="1"
            android:id="@+id/main_btnSignup"
            android:background="@color/colorPrimaryDark"
            android:textColor="@color/colorAccent"
            android:text="SignUp"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            style="@style/Widget.AppCompat.Button.Borderless"
            />
    </LinearLayout>

OUTPUT on my Galaxy Note3 device:


问:
SSH from Synology NAS to remote server
When I run competitions for Icelandic Horses, I want to automatically upload the results from our Synology NAS to a remote webserver. The program we use automatically generates the html-files that needs to be uploaded.

What is the easiest way to achieve this? I have SSH access on both the NAS and the webserver.

Any help is appreciated :)

答:
In this case you can create a cron task in the synology console with the command:

```<code>sudo -i
vi /etc/crontab
</code>```

Edit the file and add a line like this at the end of the file with a scp command:

```<code>0 0 * * * root scp -r "-i/root/.ssh/mykey" 'root@serverurl.com:/some/remote/path' '/some/local/path'
</code>```

Finally you have to reload the configuration restarting the service with:

```<code>synoservice -restart crond
</code>```

Before all this you must to configure a pair keys to avoid the password entry:

cd to a private directory of the user which will be running the script (typically "$HOME/.ssh", to be created if needed). That directory must be protected to write acces from other users, fix the modes if needed.

generate the keypair using command "ssh-keygen"
("/usr/syno/bin/ssh-keygen" if not in your PATH)

at the prompt "Enter file in which to save the key", choose a file
name (let's say "mykey")

at the prompt "Enter passphrase (empty for no passphrase):" press
return (this will create a passwordless private key)

Two files will be created: "mykey" and "mykey.pub"

copy the contents of mykey.pub inside "$HOME/.ssh/authorized_key"
file of user account on the remote machine your script is going to
connect to.

in your script, add "-i" as argument to the
ssh command

Also in this forum is explained how to make the copy with rsync instead of scp

Title: SSH from Synology NAS to remote server

Body:
In this case you can create a cron task in the synology console with the command:

sudo -i
vi /etc/crontab

Edit the file and add a line like this at the end of the file with a scp command:

0 0 * * * root scp -r "-i/root/.ssh/mykey" 'root@serverurl.com:/some/remote/path' '/some/local/path'

Finally you have to reload the configuration restarting the service with:

synoservice -restart crond

Before all this you must to configure a pair keys to avoid the password entry:

cd to a private directory of the user which will be running the script (typically "$HOME/.ssh", to be created if needed). That directory must be protected to write acces from other users, fix the modes if needed.

generate the keypair using command "ssh-keygen"
("/usr/syno/bin/ssh-keygen" if not in your PATH)

at the prompt "Enter file in which to save the key", choose a file
name (let's say "mykey")

at the prompt "Enter passphrase (empty for no passphrase):" press
return (this will create a passwordless private key)

Two files will be created: "mykey" and "mykey.pub"

copy the contents of mykey.pub inside "$HOME/.ssh/authorized_key"
file of user account on the remote machine your script is going to
connect to.

in your script, add "-i" as argument to the
ssh command

Also in this forum is explained how to make the copy with rsync instead of scp


问:
Parsing C# UrlTokenEncode string with PHP
I have the following c# code that converts an image into a base64 encoded string using UrlTokenEncode:

```<code>        byte[] imageArray = System.IO.File.ReadAllBytes(note_path);
        string base64ImageRepresentation = HttpServerUtility.UrlTokenEncode(imageArray);

        byte[] data = Encoding.UTF8.GetBytes($"id={id}&apikey={apikey}&friend_ids={friend_ids}&ttl={ttl}&note={base64ImageRepresentation}");

        Console.Write(sendRequest("upload-note", data));
        Console.ReadLine();
</code>```

I send this to my lamp server to be parsed via php. Obviously this doesn't work because of how UrlTokenEncode uses - for +, _ for /, and integer value for padding equals signs. I have the following code to overcome this:

```<code>                $request->note = str_replace('-', '+', str_replace('_', '/', $request->note));
                $lastCharacter = substr($request->note, -1);
                if($lastCharacter == 1 || $lastCharacter == 2){
                    $request->note = substr($request->note, 0, -$lastCharacter);
                    if($lastCharacter == 1){
                        $request->note = $request->note . '=';
                    } else {
                        $request->note = $request->note . '==';
                    }
                }
</code>```

My concern for this process comes from the trailing equals signs. I read that there will only ever be 1 or 2 equals signs for padding, but can there ever be a case where there is no padding? If that were possible, then the last character of a string could potentially be any random integer value correct? If that is true then my current process for decoding in php will not work, since it assumes the last character will always be 1 or 2 and that that character will represent the number of equal signs needed...

If my process will not work, is there a better way to decode a c# UrlTokenEncode string with PHP?

答:
To answer my above questions:

There will only ever be 0, 1, or 2 equals signs for padding at the end of a base64 encoded string

If there is no padding then 0 is appended to base64 string

I created the following functions to convert a base64 string created via c#'s UrlTokenEncode method back to a regular base64 string, as well as convert from a regular base64 string to the format UrlTokenDecode expects.

```<code>function convertToUrlTokenFormat($val){

    $padding = substr_count($val, '=');
    $val = str_replace('=', '', $val);
    $val .= $padding;
    $val = str_replace('+', '-', str_replace('/', '_', $val));

    return $val;

}

function convertFromUrlTokenFormat($val){

    $val = str_replace('-', '+', str_replace('_', '/', $val));
    $lastCharacter = substr($val, -1);
    $val = substr($val, 0, -1);
    switch($lastCharacter){
        case 1:
            $val = $val . "=";
            break;
        case 2:
            $val = $val . "==";
            break;
    }

    return $val;

}
</code>```

Body:
I have the following c# code that converts an image into a base64 encoded string using UrlTokenEncode:

        byte[] imageArray = System.IO.File.ReadAllBytes(note_path);
        string base64ImageRepresentation = HttpServerUtility.UrlTokenEncode(imageArray);

        byte[] data = Encoding.UTF8.GetBytes($"id={id}&apikey={apikey}&friend_ids={friend_ids}&ttl={ttl}&note={base64ImageRepresentation}");

        Console.Write(sendRequest("upload-note", data));
        Console.ReadLine();

I send this to my lamp server to be parsed via php. Obviously this doesn't work because of how UrlTokenEncode uses - for +, _ for /, and integer value for padding equals signs. I have the following code to overcome this:

                $request->note = str_replace('-', '+', str_replace('_', '/', $request->note));
                $lastCharacter = substr($request->note, -1);
                if($lastCharacter == 1 || $lastCharacter == 2){
                    $request->note = substr($request->note, 0, -$lastCharacter);
                    if($lastCharacter == 1){
                        $request->note = $request->note . '=';
                    } else {
                        $request->note = $request->note . '==';
                    }
                }

My concern for this process comes from the trailing equals signs. I read that there will only ever be 1 or 2 equals signs for padding, but can there ever be a case where there is no padding? If that were possible, then the last character of a string could potentially be any random integer value correct? If that is true then my current process for decoding in php will not work, since it assumes the last character will always be 1 or 2 and that that character will represent the number of equal signs needed...

If my process will not work, is there a better way to decode a c# UrlTokenEncode string with PHP?

Body:
To answer my above questions:

There will only ever be 0, 1, or 2 equals signs for padding at the end of a base64 encoded string

If there is no padding then 0 is appended to base64 string

I created the following functions to convert a base64 string created via c#'s UrlTokenEncode method back to a regular base64 string, as well as convert from a regular base64 string to the format UrlTokenDecode expects.

function convertToUrlTokenFormat($val){

    $padding = substr_count($val, '=');
    $val = str_replace('=', '', $val);
    $val .= $padding;
    $val = str_replace('+', '-', str_replace('/', '_', $val));

    return $val;

}

function convertFromUrlTokenFormat($val){

    $val = str_replace('-', '+', str_replace('_', '/', $val));
    $lastCharacter = substr($val, -1);
    $val = substr($val, 0, -1);
    switch($lastCharacter){
        case 1:
            $val = $val . "=";
            break;
        case 2:
            $val = $val . "==";
            break;
    }

    return $val;

}


问:
Trying To Create a Slidebar Menu in IOS
I want to create a slidebar menu in my app (As shown in the image below)

When I click that hamburger icon, it should show a menu as shown below.

I am currently using the SWRevealController, a lib written in Objective C. I created a bridging header and imported the class. This is my current Set up

My initial view which branches to a Menu Controller or the UIViewTable is a SWRevealController, and the segues are subclasses of SWRevealViewControllerSegueSetController. In my Food Item View Controller (the controller where the hamburger navigation exist), I added the following code to activate the slidebar action.

```<code>override func viewDidLoad() {
        super.viewDidLoad()

        //Creating the slidebar Navigation using SWRevealViewController
        if self.revealViewController() != nil {
            menuButton.target = self.revealViewController()
            menuButton.action = #selector(SWRevealViewController.revealToggle(_:))
            self.view.addGestureRecognizer(self.revealViewController().panGestureRecognizer())
        }

}
</code>```

However, when I click the button, it is still not responding. When I did this with my other application, it worked fine. I am not sure why it is not working here

This is the source I used as reference: http://www.appcoda.com/sidebar-menu-swift/

View Controller Full Code

```<code>@IBOutlet weak var thumbnail_image: UIImageView!
    //@IBOutlet weak var food_detail: UITextView!
    @IBOutlet weak var testing: UILabel!

    @IBOutlet weak var menuButton: UIBarButtonItem!
    var jsonResponseFood: NSArray = NSArray() //API for types of food available
    var jsonResponseRecipe: NSArray = NSArray() // API for recipes in food
    var selectedFood: foodItem?
    var postStr: String?

    //Initializing API
    let FullRecipeAPIModel = fullRecipeAPIModel()

    override func viewDidLoad() {
        super.viewDidLoad()

        //Creating the slidebar Navigation using SWRevealViewController
        if self.revealViewController() != nil {
            menuButton.target = self.revealViewController()
            menuButton.action = #selector(SWRevealViewController.revealToggle(_:))
            self.view.addGestureRecognizer(self.revealViewController().panGestureRecognizer())
        }

        print(selectedFood?.name as String!)
        //testing.text = self.selectedFood?.name

        let APIModel = apiModel()

        APIModel.delegate = self
        FullRecipeAPIModel.delegate = self
        APIModel.downloadItems(postString: postStr!)

        // Do any additional setup after loading the view.
    }
</code>```

Thank you StackOverflow.

答:
Problem in your code is you are not setting SWRevealController as root view.No Storyboard option available by code wise we have to do configuration once again. This library was designed  like that. so if you change code as below it will work like a charm.</p>

```<code>if(stat == "login"){
                if(responseString == "invalid"){
                    self.isValid = false;
                    print(self.isValid)
                }

                DispatchQueue.main.async(execute: {
                    if self.checkLogin(data: responseString!) == true {
                        let storyboard = UIStoryboard(name: "food", bundle: nil)
                        let controller = storyboard.instantiateViewController(withIdentifier: "foodItemViewController") as! foodItemViewController
                        let navController = UINavigationController(rootViewController: controller) // Creating a navigation controller with VC1 at the root of the navigation stack.
                        let appDelegate = UIApplication.shared.delegate as! AppDelegate
                        let menuView :MenuController = storyboard.instantiateViewController(withIdentifier: "menuBar") as! MenuController
                        let revealController = SWRevealViewController()

                        revealController.frontViewController = navController;
                        revealController.rearViewController = menuView;

                        appDelegate.window?.rootViewController = revealController

                    }
                    else{
                        //Show alert here
                        self.showAlert(title: "User Does Not Exist", alertTitle: "Close", message: "");
                    }
                });
            }
            else{
                //CODE COULD BE SIMPLIFIED
                DispatchQueue.main.async(execute: {
                    if(responseString == "duplicate"){
                        //Show alert here
                        self.showAlert(title: "User with this email already exist", alertTitle: "Close", message: "Please register with another email address")
                    }
                    else{
                        //Show Food UITable
                        let storyboard = UIStoryboard(name: "food", bundle: nil)
                        let controller = storyboard.instantiateViewController(withIdentifier: "entranceFoodController")
                        /*let navController = UINavigationController(rootViewController: controller) // Creating a navigation controller with VC1 at the root of the navigation stack.*/
                        let appDelegate = UIApplication.shared.delegate as! AppDelegate

                        let menuView :MenuController = storyboard.instantiateViewController(withIdentifier: "menuBar") as! MenuController
                        let revealController = SWRevealViewController()

                        revealController.frontViewController = controller;
                        revealController.rearViewController = menuView;

                        appDelegate.window?.rootViewController = revealController                    }

                });
            }
</code>```

Title: Trying To Create a Slidebar Menu in IOS

Body:
I want to create a slidebar menu in my app (As shown in the image below)

When I click that hamburger icon, it should show a menu as shown below.

I am currently using the SWRevealController, a lib written in Objective C. I created a bridging header and imported the class. This is my current Set up

My initial view which branches to a Menu Controller or the UIViewTable is a SWRevealController, and the segues are subclasses of SWRevealViewControllerSegueSetController. In my Food Item View Controller (the controller where the hamburger navigation exist), I added the following code to activate the slidebar action.

override func viewDidLoad() {
        super.viewDidLoad()

        //Creating the slidebar Navigation using SWRevealViewController
        if self.revealViewController() != nil {
            menuButton.target = self.revealViewController()
            menuButton.action = #selector(SWRevealViewController.revealToggle(_:))
            self.view.addGestureRecognizer(self.revealViewController().panGestureRecognizer())
        }

}

However, when I click the button, it is still not responding. When I did this with my other application, it worked fine. I am not sure why it is not working here

This is the source I used as reference: http://www.appcoda.com/sidebar-menu-swift/

View Controller Full Code

@IBOutlet weak var thumbnail_image: UIImageView!
    //@IBOutlet weak var food_detail: UITextView!
    @IBOutlet weak var testing: UILabel!

    @IBOutlet weak var menuButton: UIBarButtonItem!
    var jsonResponseFood: NSArray = NSArray() //API for types of food available
    var jsonResponseRecipe: NSArray = NSArray() // API for recipes in food
    var selectedFood: foodItem?
    var postStr: String?

    //Initializing API
    let FullRecipeAPIModel = fullRecipeAPIModel()

    override func viewDidLoad() {
        super.viewDidLoad()

        //Creating the slidebar Navigation using SWRevealViewController
        if self.revealViewController() != nil {
            menuButton.target = self.revealViewController()
            menuButton.action = #selector(SWRevealViewController.revealToggle(_:))
            self.view.addGestureRecognizer(self.revealViewController().panGestureRecognizer())
        }

        print(selectedFood?.name as String!)
        //testing.text = self.selectedFood?.name

        let APIModel = apiModel()

        APIModel.delegate = self
        FullRecipeAPIModel.delegate = self
        APIModel.downloadItems(postString: postStr!)

        // Do any additional setup after loading the view.
    }

Thank you StackOverflow.

Body:
Problem in your code is you are not setting SWRevealController as root view.No Storyboard option available by code wise we have to do configuration once again. This library was designed  like that. so if you change code as below it will work like a charm.

if(stat == "login"){
                if(responseString == "invalid"){
                    self.isValid = false;
                    print(self.isValid)
                }

                DispatchQueue.main.async(execute: {
                    if self.checkLogin(data: responseString!) == true {
                        let storyboard = UIStoryboard(name: "food", bundle: nil)
                        let controller = storyboard.instantiateViewController(withIdentifier: "foodItemViewController") as! foodItemViewController
                        let navController = UINavigationController(rootViewController: controller) // Creating a navigation controller with VC1 at the root of the navigation stack.
                        let appDelegate = UIApplication.shared.delegate as! AppDelegate
                        let menuView :MenuController = storyboard.instantiateViewController(withIdentifier: "menuBar") as! MenuController
                        let revealController = SWRevealViewController()

                        revealController.frontViewController = navController;
                        revealController.rearViewController = menuView;

                        appDelegate.window?.rootViewController = revealController

                    }
                    else{
                        //Show alert here
                        self.showAlert(title: "User Does Not Exist", alertTitle: "Close", message: "");
                    }
                });
            }
            else{
                //CODE COULD BE SIMPLIFIED
                DispatchQueue.main.async(execute: {
                    if(responseString == "duplicate"){
                        //Show alert here
                        self.showAlert(title: "User with this email already exist", alertTitle: "Close", message: "Please register with another email address")
                    }
                    else{
                        //Show Food UITable
                        let storyboard = UIStoryboard(name: "food", bundle: nil)
                        let controller = storyboard.instantiateViewController(withIdentifier: "entranceFoodController")
                        /*let navController = UINavigationController(rootViewController: controller) // Creating a navigation controller with VC1 at the root of the navigation stack.*/
                        let appDelegate = UIApplication.shared.delegate as! AppDelegate

                        let menuView :MenuController = storyboard.instantiateViewController(withIdentifier: "menuBar") as! MenuController
                        let revealController = SWRevealViewController()

                        revealController.frontViewController = controller;
                        revealController.rearViewController = menuView;

                        appDelegate.window?.rootViewController = revealController                    }

                });
            }


问:
output of a recursion implementation
I've try to implement a recursion algorithm: 'X' is a global variable

```<code>def build_paths(m,n):
    Result = []
    Move = X[(m,n)][1]
    if Move[0] == "None":
       return(Move[0])
    else:
       if Move[0]=="UP":
          m -= 1
       elif Move[0]=="Left":
          n -= 1
       else:
          m -= 1
          n -= 1
       Result = [build_paths(m,n),Move[0]]
    return(Result)
</code>```

This generates

```<code>[[[[[[['None', 'LEFT'], 'DIAG'], 'DIAG'], 'DIAG'], 'UP'], 'DIAG'], 'DIAG']
</code>```

This is in essence what I want, but I really want is

```<code>['None','LEFT','DIAG','DIAG','UP','DIAG','DIAG']
</code>```

Then I changed the 2nd last line of my recursion function to

```<code>Result = [build_paths(m,n)].extend(Move[0])
</code>```

I think logically it is correct, i.e., I keep on extend my list, but eventually, it only outputs

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

I couldn't figure out why it happens...

答:
build_paths() returns a list, and extend returns None (it modifies its argument), so you'd want:

```<code>Result = build_paths(m,n)
Result.append(Move[0])
</code>```

Title: output of a recursion implementation

Body:
I've try to implement a recursion algorithm: 'X' is a global variable

def build_paths(m,n):
    Result = []
    Move = X[(m,n)][1]
    if Move[0] == "None":
       return(Move[0])
    else:
       if Move[0]=="UP":
          m -= 1
       elif Move[0]=="Left":
          n -= 1
       else:
          m -= 1
          n -= 1
       Result = [build_paths(m,n),Move[0]]
    return(Result)

This generates

[[[[[[['None', 'LEFT'], 'DIAG'], 'DIAG'], 'DIAG'], 'UP'], 'DIAG'], 'DIAG']

This is in essence what I want, but I really want is

['None','LEFT','DIAG','DIAG','UP','DIAG','DIAG']

Then I changed the 2nd last line of my recursion function to

Result = [build_paths(m,n)].extend(Move[0])

I think logically it is correct, i.e., I keep on extend my list, but eventually, it only outputs

None

I couldn't figure out why it happens...

Body:
build_paths() returns a list, and extend returns None (it modifies its argument), so you'd want:

Result = build_paths(m,n)
Result.append(Move[0])


问:
What is a good design for an interface with optional components?
Suppose I have an interface that supports a few potential operations:

```<code>interface Frobnicator {
    int doFoo(double v);
    int doBar();
}
</code>```

Now, some instances will only support one or the other of these operations.  They may support both.  The client code won't necessarily know until it actually gets one from the relevant factory, via dependency injection, or wherever it is getting instances from.

I see a few ways of handling this.  One, which seems to be the general tactic taken in the Java API, is to just have the interface as shown above and have unsupported methods raise UnsupportedOperationException.  This has the disadvantage, however, of not being fail-fast - client code can't tell whether doFoo will work until it tries to call doFoo.

This could be augmented with supportsFoo() and supportsBar() methods, defined to return true iff the corresponding do method works.

Another strategy is to factor the doFoo and doBar methods into FooFrobnicator and BarFrobnicator methods, respectively.  These methods would then return null if the operation is unsupported.  To keep the client code from having to do instanceof checks, I define a Frobnicator interface as follows:

```<code>interface Frobnicator {
    /* Get a foo frobnicator, returning null if not possible */
    FooFrobnicator getFooFrobnicator();
    /* Get a bar frobnicator, returning null if not possible */
    BarFrobnicator getBarFrobnicator();
}

interface FooFrobnicator {
    int doFoo(double v);
}

interface BarFrobnicator {
    int doBar();
}
</code>```

Alternatively, FooFrobnicator and BarFrobnicator could extend Frobnicator, and the get* methods possibly be renamed as*.

One issue with this is naming: the Frobnicator really isn't a frobnicator, it's a way of getting frobnicators (unless I use the as* naming).  It also gets a tad unwieldy.  The naming may be further complicated, as the Frobnicator will be retrieved from a FrobnicatorEngine service.

Does anyone have any insight into a good, preferably well-accepted solution to this problem?  Is there an appropriate design pattern?  Visitor is not appropriate in this case, as the client code needs a particular type of interface (and should preferably fail-fast if it can't get it), as opposed to dispatching on what kind of object it got.  Whether or not different features are supported can vary on a variety of things - the implementation of Frobnicator, the run-time configuration of that implementation (e.g. it supports doFoo only if some system service is present to enable Foo), etc.

Update: Run-time configuration is the other monkey wrench in this business.  It may be possible to carry the FooFrobnicator and BarFrobnicator types through to avoid the problem, particularly if I make heaver use of Guice-modules-as-configuration, but it introduces complexity into other surrounding interfaces (such as the factory/builder that produces Frobnicators in the first place).  Basically, the implementation of the factory that produces frobnicators is configured at run-time (either via properties or a Guice module), and I want it to make it fairly easy for the user to say "hook up this frobnicator provider an this client".  I admit that it's a problem with potential inherent design problems, and that I may also be overthinking some of the generalization issues, but I'm going for some combination of least-ugliness and least-astonishment.

答:
The most obvious solution  is to just define two interfaces FooFrobnicator and BarFrobnicator. This should be fine as class can implement multiple interfaces.

You could then provide a super (marker) interface if necessary.

ContentLicense: CC BY-SA 2.5

Body:
Suppose I have an interface that supports a few potential operations:

interface Frobnicator {
    int doFoo(double v);
    int doBar();
}

Now, some instances will only support one or the other of these operations.  They may support both.  The client code won't necessarily know until it actually gets one from the relevant factory, via dependency injection, or wherever it is getting instances from.

I see a few ways of handling this.  One, which seems to be the general tactic taken in the Java API, is to just have the interface as shown above and have unsupported methods raise UnsupportedOperationException.  This has the disadvantage, however, of not being fail-fast - client code can't tell whether doFoo will work until it tries to call doFoo.

This could be augmented with supportsFoo() and supportsBar() methods, defined to return true iff the corresponding do method works.

Another strategy is to factor the doFoo and doBar methods into FooFrobnicator and BarFrobnicator methods, respectively.  These methods would then return null if the operation is unsupported.  To keep the client code from having to do instanceof checks, I define a Frobnicator interface as follows:

interface Frobnicator {
    /* Get a foo frobnicator, returning null if not possible */
    FooFrobnicator getFooFrobnicator();
    /* Get a bar frobnicator, returning null if not possible */
    BarFrobnicator getBarFrobnicator();
}

interface FooFrobnicator {
    int doFoo(double v);
}

interface BarFrobnicator {
    int doBar();
}

Alternatively, FooFrobnicator and BarFrobnicator could extend Frobnicator, and the get* methods possibly be renamed as*.

One issue with this is naming: the Frobnicator really isn't a frobnicator, it's a way of getting frobnicators (unless I use the as* naming).  It also gets a tad unwieldy.  The naming may be further complicated, as the Frobnicator will be retrieved from a FrobnicatorEngine service.

Does anyone have any insight into a good, preferably well-accepted solution to this problem?  Is there an appropriate design pattern?  Visitor is not appropriate in this case, as the client code needs a particular type of interface (and should preferably fail-fast if it can't get it), as opposed to dispatching on what kind of object it got.  Whether or not different features are supported can vary on a variety of things - the implementation of Frobnicator, the run-time configuration of that implementation (e.g. it supports doFoo only if some system service is present to enable Foo), etc.

Update: Run-time configuration is the other monkey wrench in this business.  It may be possible to carry the FooFrobnicator and BarFrobnicator types through to avoid the problem, particularly if I make heaver use of Guice-modules-as-configuration, but it introduces complexity into other surrounding interfaces (such as the factory/builder that produces Frobnicators in the first place).  Basically, the implementation of the factory that produces frobnicators is configured at run-time (either via properties or a Guice module), and I want it to make it fairly easy for the user to say "hook up this frobnicator provider an this client".  I admit that it's a problem with potential inherent design problems, and that I may also be overthinking some of the generalization issues, but I'm going for some combination of least-ugliness and least-astonishment.


问:
How to convert gif in mp4 video with Nodejs?
Is there a way to convert a .gif uploaded image into .mp4 with only Nodejs?  How do I integrate that with a MEAN app? I want to be able to store the converted .mp4 file to S3.

Using : https://www.npmjs.com/package/fluent-ffmpeg-extended but get error : Invalid Input

```<code>var upload = multer({
    storage: multerS3({
       s3: s3,
       bucket: 'mybucket',
       key: function (req, file, cb) {
        var extension = file.originalname.substring(file.originalname.lastIndexOf('.')+1).toLowerCase();
            if(extension == "gif"){
                console.log(file);
                var proc = new ffmpeg({ source: file })
                  .usingPreset('podcast')
                  .saveToFile('/path/to/your_target.m4v', function(stdout, stderr) {
                    console.log('file has been converted succesfully');
                  });
            }
            else{
                cb(null, file.originalname);
            }
        }
    })
});
</code>```

Many thanks.

答:
you can use this library. it's a wrapper for ffmpeg executable, so you'll need to have it as well.

https://www.npmjs.com/package/fluent-ffmpeg-extended

This thread will be helpful as well,

https://www.bountysource.com/issues/36060167-converting-gif-buffer-to-mp4-buffer-without-writing-to-file-first

Body:
Is there a way to convert a .gif uploaded image into .mp4 with only Nodejs?  How do I integrate that with a MEAN app? I want to be able to store the converted .mp4 file to S3.

Using : https://www.npmjs.com/package/fluent-ffmpeg-extended but get error : Invalid Input

var upload = multer({
    storage: multerS3({
       s3: s3,
       bucket: 'mybucket',
       key: function (req, file, cb) {
        var extension = file.originalname.substring(file.originalname.lastIndexOf('.')+1).toLowerCase();
            if(extension == "gif"){
                console.log(file);
                var proc = new ffmpeg({ source: file })
                  .usingPreset('podcast')
                  .saveToFile('/path/to/your_target.m4v', function(stdout, stderr) {
                    console.log('file has been converted succesfully');
                  });
            }
            else{
                cb(null, file.originalname);
            }
        }
    })
});

Many thanks.


问:
vb.net datatype in manually added column
```<code>Dim pctofpax As New DataColumn
        pctofpax = New DataColumn("PCTPAX1", GetType(Decimal))
        pctofpax.Expression = "[ASOFPAX] / [YEPAX]"
        ds.Tables("workplease").Columns.Add(pctofpax)

        Dim avgppax As New DataColumn
        avgppax = New DataColumn("AVG PAX", GetType(Double))
        avgppax.Expression = "[Current Sales] / [Current PAX]"
        ds.Tables("workplease").Columns.Add(avgppax)
</code>```

These are two columns that i added into my asp.net/vb.net datagrid. the problem is i keep trying to change the datatypes so they show up as numbers with only two decimals but it is not working

```<code>            <span lang="en-us">Sales As Of Analysis</span><br />
        <asp:GridView ID="GridView1" runat="server" BackColor="White"
            BorderColor="#999999" BorderStyle="None" BorderWidth="1px" CellPadding="3"
            GridLines="Vertical">
            <RowStyle BackColor="#EEEEEE" ForeColor="Black" />
            <FooterStyle BackColor="#CCCCCC" ForeColor="Black" />
            <PagerStyle BackColor="#999999" ForeColor="Black" HorizontalAlign="Center" />
            <SelectedRowStyle BackColor="#008A8C" Font-Bold="True" ForeColor="White" />
            <HeaderStyle BackColor="#000084" Font-Bold="True" ForeColor="White" />
            <AlternatingRowStyle BackColor="#DCDCDC" />
        </asp:GridView>
    <asp:BoundColumn DataField="PCTPAX1"
                 HeaderText="PCTPAX1"
                 DataFormatString="{0:c}">

    </div>
    </form>
</body>
</html>
</code>```

and nothing happend to my data

答: Changing the type of a column which is already in your datatable doesn't work. or at least not that i know. if you just want to get a different formatting, look at the answers above.</p>

Body:
Dim pctofpax As New DataColumn
        pctofpax = New DataColumn("PCTPAX1", GetType(Decimal))
        pctofpax.Expression = "[ASOFPAX] / [YEPAX]"
        ds.Tables("workplease").Columns.Add(pctofpax)

        Dim avgppax As New DataColumn
        avgppax = New DataColumn("AVG PAX", GetType(Double))
        avgppax.Expression = "[Current Sales] / [Current PAX]"
        ds.Tables("workplease").Columns.Add(avgppax)

These are two columns that i added into my asp.net/vb.net datagrid. the problem is i keep trying to change the datatypes so they show up as numbers with only two decimals but it is not working

            Sales As Of Analysis

        <asp:GridView ID="GridView1" runat="server" BackColor="White"
            BorderColor="#999999" BorderStyle="None" BorderWidth="1px" CellPadding="3"
            GridLines="Vertical">
            <RowStyle BackColor="#EEEEEE" ForeColor="Black" />
            <FooterStyle BackColor="#CCCCCC" ForeColor="Black" />
            <PagerStyle BackColor="#999999" ForeColor="Black" HorizontalAlign="Center" />
            <SelectedRowStyle BackColor="#008A8C" Font-Bold="True" ForeColor="White" />
            <HeaderStyle BackColor="#000084" Font-Bold="True" ForeColor="White" />
            <AlternatingRowStyle BackColor="#DCDCDC" />
        </asp:GridView>
    <asp:BoundColumn DataField="PCTPAX1"
                 HeaderText="PCTPAX1"
                 DataFormatString="{0:c}">

    </form>

and nothing happend to my data


问:
Saving struct to a file in C
In my assignment I was given two functions to write

```<code>int openFileFromConsole(FILE *fp)
</code>```

It takes an empty file pointer as input to the function using call by reference. And updates the pointer to point to the appropriate HDD address. IMPORTANT: Later, it asks the user through the console to provide the name and also asks for the file open type: "w", "r", "a" and UPDATES the file pointer. It returns 1 if succeeded, or 0 if fails.

```<code>void saveStudentGradeInfoTofile(FILE *fp)
</code>```

This function gets the student info and saves it first into the student data-type (which is struct but disguised using typedef) then saves it to file. The student information is being provided by the register through the console. This takes the file pointer by reference as input and update the file using fprint.

This program is supposed to open a file through console depending on the user input then collect information and store them to a struct and save it to that file.I have written the two functions(correctly I think?).But I am having a hard time implementing them to main() since the first one is an int type function.Any help would be appreciated.

```<code>typedef struct student {
    char name[50];
    char id [20];
    int score;
}student;

int openFileFromConsole(FILE *fp);
void saveStudentGradeInfoTofile(FILE *fp);

int main()
{
   return 0;
}

int openFileFromConsole(FILE *fp){
    char filePath[100],fileOpenType[10];
    printf("Enter Path name: ");
    scanf("%s", filePath);
    printf("Enter file open type w, r or a: ");
    scanf("%s", fileOpenType);

     fp = fopen(filePath,fileOpenType);
     if(fp != NULL) {
        printf("File has been opened");
     return 1;

     }
     else printf("File not found");
     return 0;
}
void saveStudentGradeInfoTofile(FILE *fp){

     int numOfStudent ;
     student s[100];
     printf ("Get the number of students :");
     scanf("%d",&numOfStudent);

     for(int i = 0; i < numOfStudent; i++) {

         printf("\nEnter ID number:");

         scanf(" %s",s[i].id);

         printf("Enter name: ");
         scanf("%s,",s[i].name);

         printf("Enter score: ");
         scanf("%d",&s[i].score);

         fprintf(fp,"id : %s, Name: %s,  score =%d\n",s[i].id,s[i].name,s[i].score);

         printf("\n");
}
}
</code>```

答:
Just in case you want to pass the file path as an argument to your program</p>

```<code>int main(int c /* argument counter */, char *v[] /*argument list */)
{
   FILE *fp;
   if(c >= 2) {
   char *path = v[1]; /* this is the second argument (the first one, v[0], is the program's name): ./foo myfile.txt */
   fp = fopen(path, "your mode goes here");
   /* ... */
   }
}
</code>```

Title: Saving struct to a file in C

Body:
In my assignment I was given two functions to write

int openFileFromConsole(FILE *fp)

It takes an empty file pointer as input to the function using call by reference. And updates the pointer to point to the appropriate HDD address. IMPORTANT: Later, it asks the user through the console to provide the name and also asks for the file open type: "w", "r", "a" and UPDATES the file pointer. It returns 1 if succeeded, or 0 if fails.

void saveStudentGradeInfoTofile(FILE *fp)

This function gets the student info and saves it first into the student data-type (which is struct but disguised using typedef) then saves it to file. The student information is being provided by the register through the console. This takes the file pointer by reference as input and update the file using fprint.

This program is supposed to open a file through console depending on the user input then collect information and store them to a struct and save it to that file.I have written the two functions(correctly I think?).But I am having a hard time implementing them to main() since the first one is an int type function.Any help would be appreciated.

typedef struct student {
    char name[50];
    char id [20];
    int score;
}student;

int openFileFromConsole(FILE *fp);
void saveStudentGradeInfoTofile(FILE *fp);

int main()
{
   return 0;
}

int openFileFromConsole(FILE *fp){
    char filePath[100],fileOpenType[10];
    printf("Enter Path name: ");
    scanf("%s", filePath);
    printf("Enter file open type w, r or a: ");
    scanf("%s", fileOpenType);

     fp = fopen(filePath,fileOpenType);
     if(fp != NULL) {
        printf("File has been opened");
     return 1;

     }
     else printf("File not found");
     return 0;
}
void saveStudentGradeInfoTofile(FILE *fp){

     int numOfStudent ;
     student s[100];
     printf ("Get the number of students :");
     scanf("%d",&numOfStudent);

     for(int i = 0; i < numOfStudent; i++) {

         printf("\nEnter ID number:");

         scanf(" %s",s[i].id);

         printf("Enter name: ");
         scanf("%s,",s[i].name);

         printf("Enter score: ");
         scanf("%d",&s[i].score);

         fprintf(fp,"id : %s, Name: %s,  score =%d\n",s[i].id,s[i].name,s[i].score);

         printf("\n");
}
}

Body:
Just in case you want to pass the file path as an argument to your program

int main(int c /* argument counter */, char *v[] /*argument list */)
{
   FILE *fp;
   if(c >= 2) {
   char *path = v[1]; /* this is the second argument (the first one, v[0], is the program's name): ./foo myfile.txt */
   fp = fopen(path, "your mode goes here");
   /* ... */
   }
}