问:
DHTMLX Scheduler with Node JS
I have followed the DTHMLX Scheduler tutorial, but I haven't been able to get the db.event.insert() to work, because the route for it is not firing off. However, I am able to display data from my MongoDB when I insert data through the shell.

Like the tutorial, I used MongoSkin as the MongoDB driver. Both MongoSkin and Express are the same version "mongoskin": "~0.6.0" & "express": "~3.3.8"as it is in the tutorial.

```<code><!-- index.html -->
<!doctype html>
<head>
    <meta http-equiv="Content-type" content="text/html; charset=utf-8">
    <title>Basic initialization</title>
</head>
    <script src="codebase/dhtmlxscheduler.js" type="text/javascript" charset="utf-8"></script>
    <link rel="stylesheet" href="codebase/dhtmlxscheduler.css" type="text/css" media="screen" title="no title" charset="utf-8">

<style type="text/css" media="screen">
    html, body{
        margin:0px;
        padding:0px;
        height:100%;
        overflow:hidden;
    }
</style>

<script type="text/javascript" charset="utf-8">
    function init() {
        scheduler.config.xml_date="%Y-%m-%d %H:%i"; //changes date format
        scheduler.init('scheduler_here',new Date(),"month"); // when the calendar is initialized

        scheduler.templates.xml_date = function(value){ return new Date(value); };
        scheduler.load("/data", "json");

        var dp = new dataProcessor("/data");
        dp.init(scheduler);
        dp.setTransactionMode("POST", true);
        console.log('init on index finished');
    }
</script>

<body onload="init();">
    <div id="scheduler_here" class="dhx_cal_container" style='width:100%; height:100%;'>
        <div class="dhx_cal_navline">
            <div class="dhx_cal_prev_button"> </div>
            <div class="dhx_cal_next_button"> </div>
            <div class="dhx_cal_today_button"></div>
            <div class="dhx_cal_date"></div>
            <div class="dhx_cal_tab" name="day_tab" style="right:204px;"></div>
            <div class="dhx_cal_tab" name="week_tab" style="right:140px;"></div>
            <div class="dhx_cal_tab" name="month_tab" style="right:76px;"></div>
        </div>
        <div class="dhx_cal_header">
        </div>
        <div class="dhx_cal_data">
        </div>
    </div>
</body>
</code>```

The server file is pretty bare bones like the tutorial. The Server file is changed from app.js to server.js.

```<code>//server.js
var express = require('express');
var path = require('path');
var bodyParser = require('body-parser');

var db = require('mongoskin').db("mongodb://localhost:27017/testdb", { w: 0});
    db.bind('event');

var app = express();
app.use(express.static(path.join(__dirname, 'public')));
app.use(express.bodyParser());

app.get('/init', function(req, res){
    if (err) throw err;
    console.log('before object');
    db.event.insert({
        text:"My test event A",
        start_date: new Date(2017,5,1),
        end_date:   new Date(2017,5,5)
    }, console.log('first object run'));
    db.event.insert({
        text:"My test event B",
        start_date: new Date(2017,5,19),
        end_date:   new Date(2017,5,24)
    });
    db.event.insert({
        text:"Morning event",
        start_date: new Date(2017,5,4),
        end_date:   new Date(2017,5,4)
    });
    db.event.insert({
        text:"One more test event",
        start_date: new Date(2017,5,3),
        end_date:   new Date(2017,5,8),
        color: "#DD8616"
    });
    res.send("Test events were added to the database");
    console.log('events inserted?')
});

app.get('/data', function(req, res){
    db.event.find().toArray(function(err, data){
        //set id property for all records
        for (var i = 0; i < data.length; i++)
            // console.log('in for loop');
            data[i].id = data[i]._id;

        //output response
        res.send(data);
        console.log('data sent');
    });
});

app.listen(3000);
console.log('listening on port 3000');
</code>```

I am able to use the app.get('/data' route and callback function and get my collection printed onto the calendar, but only after inserting it in the MongoDB's shell command line.

The same can be said from inserting data, as db.event.insert method is missed because the app.get('/init' route never gets fired off. I found from testing, using console.logs.

I read through the DHTMLX Scheduler tutorial, the website's documentation, MongoDB documentation, and the MongoSkin docs. I could be completely missing an obvious solution, but I can't seem to find what I'm missing here so any help would be appreciated. Thanks.

答:
but I haven't been able to get the db.event.insert() to work, because the route for it is not firing off.

Seems like your code doesn't have a route for POST /data request, which is called when you insert/update/delete item on the client-side. Here is related code in the sample https://github.com/DHTMLX/node-scheduler-demo/blob/master/app.js#L52

Regarding GET /init route - it's only used to insert some test data into db,  and is called manually. You can remove it without any effect to the rest of the app

Title: DHTMLX Scheduler with Node JS

Body:
I have followed the DTHMLX Scheduler tutorial, but I haven't been able to get the db.event.insert() to work, because the route for it is not firing off. However, I am able to display data from my MongoDB when I insert data through the shell.

Like the tutorial, I used MongoSkin as the MongoDB driver. Both MongoSkin and Express are the same version "mongoskin": "~0.6.0" & "express": "~3.3.8"as it is in the tutorial.

<!doctype html>

    <meta http-equiv="Content-type" content="text/html; charset=utf-8">
    <title>Basic initialization</title>

    <link rel="stylesheet" href="codebase/dhtmlxscheduler.css" type="text/css" media="screen" title="no title" charset="utf-8">

The server file is pretty bare bones like the tutorial. The Server file is changed from app.js to server.js.

//server.js
var express = require('express');
var path = require('path');
var bodyParser = require('body-parser');

var db = require('mongoskin').db("mongodb://localhost:27017/testdb", { w: 0});
    db.bind('event');

var app = express();
app.use(express.static(path.join(__dirname, 'public')));
app.use(express.bodyParser());

app.get('/init', function(req, res){
    if (err) throw err;
    console.log('before object');
    db.event.insert({
        text:"My test event A",
        start_date: new Date(2017,5,1),
        end_date:   new Date(2017,5,5)
    }, console.log('first object run'));
    db.event.insert({
        text:"My test event B",
        start_date: new Date(2017,5,19),
        end_date:   new Date(2017,5,24)
    });
    db.event.insert({
        text:"Morning event",
        start_date: new Date(2017,5,4),
        end_date:   new Date(2017,5,4)
    });
    db.event.insert({
        text:"One more test event",
        start_date: new Date(2017,5,3),
        end_date:   new Date(2017,5,8),
        color: "#DD8616"
    });
    res.send("Test events were added to the database");
    console.log('events inserted?')
});

app.get('/data', function(req, res){
    db.event.find().toArray(function(err, data){
        //set id property for all records
        for (var i = 0; i < data.length; i++)
            // console.log('in for loop');
            data[i].id = data[i]._id;

        //output response
        res.send(data);
        console.log('data sent');
    });
});

app.listen(3000);
console.log('listening on port 3000');

I am able to use the app.get('/data' route and callback function and get my collection printed onto the calendar, but only after inserting it in the MongoDB's shell command line.

The same can be said from inserting data, as db.event.insert method is missed because the app.get('/init' route never gets fired off. I found from testing, using console.logs.

I read through the DHTMLX Scheduler tutorial, the website's documentation, MongoDB documentation, and the MongoSkin docs. I could be completely missing an obvious solution, but I can't seem to find what I'm missing here so any help would be appreciated. Thanks.


来源: stackexchange

问:
Lua: dynamically determine if object is "class" or "instance"
I am doing a remote procedure call from another language where I do not know whether the Lua function I am calling is a 'class' or 'member' function. This is important because I need to know whether to pass in self as an argument. Is there a way to determine whether the function I am calling is a member function or class function?

Lua Server

```<code>function obj.get_sum(a, b, c)
    return a + b + c
end
function obj:get_name()
    return self.name
end
</code>```

Python Client

```<code>objClass.get_sum(1, 2, 3)
objInstance.get_name()
</code>```

In the case of objInstance.get_name(), I need to pass self as an argument to the Lua function.

答:
There's no difference between functions in Lua.

It could be stored in a 'class', or it could be global function, or 'class member' function could be copied into local variable - there's no way to determine if function is a part of a class or a free function, because there's no classes in Lua. You can construct a system that behaves just like class system, but it's not the class in the Java/C++ meaning. You can call that function on any other unrelated table, and it will work just fine, provided all needed data is found in that table.

You can make a guess by looking at function's first local variable with debug.getlocal(), as arguments counts as local variables. If you see "self" as a name - there's a chance that this function was declared with colon syntax (function obj:method()), but that's just a syntactic sugar for explicit function obj.method(self) declaration, and not a guarantee for function-class relations. Even if you get "self" as first argument, it could be a free function with first argument named "self", or "member" function was declared with dot syntax and explicit "self" argument. You may not see "self" argument in a "member" function if it was declared with dot syntax and some other name for object to run on, or debug.getlocal() may even fail to find argument name because Lua source file was precompiled into bytecode with debug info stripped out.

For example:

```<code>-- "free" function that is not related to any class
local generic_func = function(table, x)
    return table.pos + x
end

-- object of some class
local obj = { pos = 1}

-- some unrelated table with "pos" element of string type
local unrelated = { pos = "42" }

-- define "method" with colon syntax, implicit "self" argument
function obj:func1(x)
    return self.pos + x
end

-- define "method" with dot syntax, explicitly naming first argument
function obj.func2(object, x)
    -- no "self" at all
    return object.pos + x
end

-- put a "free function" in a "class"
obj.func3 = generic_func

-- identical results, no matter how you call it
print(obj:func1(2))
print(obj.func1(obj, 2))
print(obj:func2(2))
print(obj.func2(obj, 2))
print(obj:func3(2))
print(obj.func3(obj, 2))
print(generic_func(obj, 2))

-- "method" function from "obj" runs on unrelated table
print(obj.func1(unrelated, 2))
</code>```

See here: http://ideone.com/qRby6s

ContentLicense: CC BY-SA 3.0

Body:
I am doing a remote procedure call from another language where I do not know whether the Lua function I am calling is a 'class' or 'member' function. This is important because I need to know whether to pass in self as an argument. Is there a way to determine whether the function I am calling is a member function or class function?

Lua Server

function obj.get_sum(a, b, c)
    return a + b + c
end
function obj:get_name()
    return self.name
end

Python Client

objClass.get_sum(1, 2, 3)
objInstance.get_name()

In the case of objInstance.get_name(), I need to pass self as an argument to the Lua function.

Body:
There's no difference between functions in Lua.

It could be stored in a 'class', or it could be global function, or 'class member' function could be copied into local variable - there's no way to determine if function is a part of a class or a free function, because there's no classes in Lua. You can construct a system that behaves just like class system, but it's not the class in the Java/C++ meaning. You can call that function on any other unrelated table, and it will work just fine, provided all needed data is found in that table.

You can make a guess by looking at function's first local variable with debug.getlocal(), as arguments counts as local variables. If you see "self" as a name - there's a chance that this function was declared with colon syntax (function obj:method()), but that's just a syntactic sugar for explicit function obj.method(self) declaration, and not a guarantee for function-class relations. Even if you get "self" as first argument, it could be a free function with first argument named "self", or "member" function was declared with dot syntax and explicit "self" argument. You may not see "self" argument in a "member" function if it was declared with dot syntax and some other name for object to run on, or debug.getlocal() may even fail to find argument name because Lua source file was precompiled into bytecode with debug info stripped out.

For example:

-- "free" function that is not related to any class
local generic_func = function(table, x)
    return table.pos + x
end

-- object of some class
local obj = { pos = 1}

-- some unrelated table with "pos" element of string type
local unrelated = { pos = "42" }

-- define "method" with colon syntax, implicit "self" argument
function obj:func1(x)
    return self.pos + x
end

-- define "method" with dot syntax, explicitly naming first argument
function obj.func2(object, x)
    -- no "self" at all
    return object.pos + x
end

-- put a "free function" in a "class"
obj.func3 = generic_func

-- identical results, no matter how you call it
print(obj:func1(2))
print(obj.func1(obj, 2))
print(obj:func2(2))
print(obj.func2(obj, 2))
print(obj:func3(2))
print(obj.func3(obj, 2))
print(generic_func(obj, 2))

-- "method" function from "obj" runs on unrelated table
print(obj.func1(unrelated, 2))

See here: http://ideone.com/qRby6s


问:
Google SignIn CocoaPods deprecated
How to implement Google SignIn in iOS app as now Google pod is deprecated?

Using the deprecated pod is giving
: Framework not found GoogleAppUtilities

答:
The pod install is indeed 'GoogleSignIn' . However this also means adjusting the bridging header to

```<code>#import <GoogleSignin/GoogleSignIn.h>
</code>```

And instead of using :

```<code>GGLContext.sharedInstance().configureWithError(&configureError)
</code>```

You need to use :

```<code>GIDSignIn.sharedInstance().clientID = kClientID
</code>```

And replace kClientID with your client id (You can/need to remove some other lines also regarding the &configureError).

You can find the info here : Google Sign-In

The Pod install now follows the manually install method mentioned in the blue notes.

Title: Google SignIn CocoaPods deprecated

Body:
The pod install is indeed 'GoogleSignIn' . However this also means adjusting the bridging header to

#import <GoogleSignin/GoogleSignIn.h>

And instead of using :

GGLContext.sharedInstance().configureWithError(&configureError)

You need to use :

GIDSignIn.sharedInstance().clientID = kClientID

And replace kClientID with your client id (You can/need to remove some other lines also regarding the &configureError).

You can find the info here : Google Sign-In

The Pod install now follows the manually install method mentioned in the blue notes.


问:
GeoJson data in R
I want to work on GeoJson data having below mentioned format;

```<code>    { "id": 1,
      "geometry":
    { "type": "Point",
    "coordinates": [
        -3.706,
        40.3],
     "properties": {"appuserid": "5b46-7d3c-48a6-9c08-cc894",
     "eventtype": "location",
     "devicedate": "2016-06-08T07:25:21",
     "date": "2016-06-08T07:25:06.507",
     "location": {
        "building": "2",
        "floor": "0",
        "elevation": ""
      }}}
</code>```

The problem is i want to use a "Where" clause to "appuserid" and select the selected records for processing. I dont know how to do it ? I have already saved data from a Mongodb in a dataframe.

Right now i am trying to do it as follow;

```<code>  library(sqldf)
  sqldf("SELECT * FROM d WHERE d$properties$appuserid  = '0000-0000-0000-0000'")
</code>```

But it gives an error.

```<code>Error: Only lists of raw vectors are currently supported
</code>```

code is below;

```<code>   library(jsonlite);
   con <- mongo(collection = "geodata", db = "MongoDb", url = "mongodb://192.168.26.18:27017", verbose = FALSE, options = ssl_options());
   d <- con$find();

   library(jqr)
   jq(d, '.features[] | select(d$properties$appuserid == "5b46-7d3c-48a6-9c08-cc894")')

   Error :  Error in jq.default(d, ".features[] | select(d$properties$appuserid == \"5b46-7d3c-48a6-9c08-cc894\")") :
   jq method not implemented for data.frame.
</code>```

答:
jqr is one option, an R client for jq https://stedolan.github.io/jq/

```<code>    x <- '{
        "type": "FeatureCollection",
        "features": [
            {
                "type": "Feature",
                "properties": {
                    "population": 200
                },
                "geometry": {
                    "type": "Point",
                    "coordinates": [
                        10.724029,
                        59.926807
                    ],
                   "properties": {
                      "appuserid": "5b46-7d3c-48a6-9c08-cc894"
                   }
                }
            },
            {
                "type": "Feature",
                "properties": {
                    "population": 600
                },
                "geometry": {
                    "type": "Point",
                    "coordinates": [
                        10.715789,
                        59.904778
                    ],
                   "properties": {
                      "appuserid": "c7e866a7-e32d-4dc2-adfd-c2ca065b25ce"
                    }
                }
            }
        ]
    }'

    library(jqr)
    jq(x, '.features[] | select(.geometry.properties.appuserid == "5b46-7d3c-48a6-9c08-cc894")')
</code>```

returns

```<code>    {
        "type": "Feature",
        "properties": {
            "population": 200
        },
        "geometry": {
            "type": "Point",
            "coordinates": [
                10.724029,
                59.926807
            ],
            "properties": {
                "appuserid": "5b46-7d3c-48a6-9c08-cc894"
            }
        }
    }
</code>```

Title: GeoJson data in R

Body:
I want to work on GeoJson data having below mentioned format;

    { "id": 1,
      "geometry":
    { "type": "Point",
    "coordinates": [
        -3.706,
        40.3],
     "properties": {"appuserid": "5b46-7d3c-48a6-9c08-cc894",
     "eventtype": "location",
     "devicedate": "2016-06-08T07:25:21",
     "date": "2016-06-08T07:25:06.507",
     "location": {
        "building": "2",
        "floor": "0",
        "elevation": ""
      }}}

The problem is i want to use a "Where" clause to "appuserid" and select the selected records for processing. I dont know how to do it ? I have already saved data from a Mongodb in a dataframe.

Right now i am trying to do it as follow;

  library(sqldf)
  sqldf("SELECT * FROM d WHERE d$properties$appuserid  = '0000-0000-0000-0000'")

But it gives an error.

Error: Only lists of raw vectors are currently supported

code is below;

   library(jsonlite);
   con <- mongo(collection = "geodata", db = "MongoDb", url = "mongodb://192.168.26.18:27017", verbose = FALSE, options = ssl_options());
   d <- con$find();

   library(jqr)
   jq(d, '.features[] | select(d$properties$appuserid == "5b46-7d3c-48a6-9c08-cc894")')

   Error :  Error in jq.default(d, ".features[] | select(d$properties$appuserid == \"5b46-7d3c-48a6-9c08-cc894\")") :
   jq method not implemented for data.frame.

Body:
jqr is one option, an R client for jq https://stedolan.github.io/jq/

    x <- '{
        "type": "FeatureCollection",
        "features": [
            {
                "type": "Feature",
                "properties": {
                    "population": 200
                },
                "geometry": {
                    "type": "Point",
                    "coordinates": [
                        10.724029,
                        59.926807
                    ],
                   "properties": {
                      "appuserid": "5b46-7d3c-48a6-9c08-cc894"
                   }
                }
            },
            {
                "type": "Feature",
                "properties": {
                    "population": 600
                },
                "geometry": {
                    "type": "Point",
                    "coordinates": [
                        10.715789,
                        59.904778
                    ],
                   "properties": {
                      "appuserid": "c7e866a7-e32d-4dc2-adfd-c2ca065b25ce"
                    }
                }
            }
        ]
    }'

    library(jqr)
    jq(x, '.features[] | select(.geometry.properties.appuserid == "5b46-7d3c-48a6-9c08-cc894")')

returns

    {
        "type": "Feature",
        "properties": {
            "population": 200
        },
        "geometry": {
            "type": "Point",
            "coordinates": [
                10.724029,
                59.926807
            ],
            "properties": {
                "appuserid": "5b46-7d3c-48a6-9c08-cc894"
            }
        }
    }


问:
Setting up Python on Windows/ Apache?
I want to get a simple Python "hello world" web page script to run on Windows Vista/ Apache but hit different walls. I'm using WAMP. I've installed mod_python and the module shows, but I'm not quite sure what I'm supposed to do in e.g. http.conf (things like AddHandler mod_python .py either bring me to a file not found, or a forbidden, or module not found errors when accessing http://localhost/myfolder/index.py). I can get mod_python.publisher to work but do I "want" this/ need this?

Can anyone help?

Thanks!

答:
You do not NEED mod_python to run Python code on the web, you could use simple CGI programming to run your python code, with the instructions in the following link: http://www.imladris.com/Scripts/PythonForWindows.html

That should give you some of the configuration options you need to enable Python with CGI, and a google search should give you reams of other info on how to program in it and such.

Mod_python is useful if you want a slightly more "friendly" interface, or more control over the request itself. You can use it to create request filters and other things for the Apache server, and with the publisher handler you get a simpler way of handling webpage requests via python.

The publisher handler works by mapping URLs to Python objects/functions. This means you can define a function named 'foo' in your python file, and any request to http://localhost/foo would call that function automatically. More info here: http://www.modpython.org/live/current/doc-html/hand-pub-alg-trav.html

As for the Apache config to make things work, something like this should serve you well

```<code><Directory /var/www/html/python/>
  SetHandler mod_python
  PythonHandler mod_python.publisher
  PythonDebug On
</Directory>
</code>```

If you have /var/www/html/ set up as your web server's root and have a file called index.py in the python/ directory in there, then any request to http://localhost/python/foo should call the foo() function in index.py, or fail with a 404 if it doesn't exist.

OwnerDisplayName: Philipp Lenssen

ContentLicense: CC BY-SA 2.5

Title: Setting up Python on Windows/ Apache?

Body:
You do not NEED mod_python to run Python code on the web, you could use simple CGI programming to run your python code, with the instructions in the following link: http://www.imladris.com/Scripts/PythonForWindows.html

That should give you some of the configuration options you need to enable Python with CGI, and a google search should give you reams of other info on how to program in it and such.

Mod_python is useful if you want a slightly more "friendly" interface, or more control over the request itself. You can use it to create request filters and other things for the Apache server, and with the publisher handler you get a simpler way of handling webpage requests via python.

The publisher handler works by mapping URLs to Python objects/functions. This means you can define a function named 'foo' in your python file, and any request to http://localhost/foo would call that function automatically. More info here: http://www.modpython.org/live/current/doc-html/hand-pub-alg-trav.html

As for the Apache config to make things work, something like this should serve you well

<Directory /var/www/html/python/>
  SetHandler mod_python
  PythonHandler mod_python.publisher
  PythonDebug On
</Directory>

If you have /var/www/html/ set up as your web server's root and have a file called index.py in the python/ directory in there, then any request to http://localhost/python/foo should call the foo() function in index.py, or fail with a 404 if it doesn't exist.

OwnerDisplayName: Daniel Bruce

LastEditorDisplayName: Daniel Bruce


问:
How to use fetch with wordpress rest API
I have this code and I wanna login using the link in the fetch of this below code but I'm getting this error while clicking on the login button: JSON Parse Error: Unexpected EOF. I'm trying to use rest API for this login app.</p>

```<code>var React = require('react');
var ReactNative = require('react-native');
var t = require('tcomb-form-native');

var {
  AppRegistry,
  AsyncStorage,
  StyleSheet,
  Text,
  View,
  TouchableHighlight,
  AlertIOS,
  Image,
} = ReactNative;

var STORAGE_KEY = 'id_token';

var Form = t.form.Form;

var Person = t.struct({
  username: t.String,
  password: t.String
});

const options = {};

var AwesomeProject = React.createClass({

  async _onValueChange(item, selectedValue) {
    try {
      await AsyncStorage.setItem(item, selectedValue);
    } catch (error) {
      console.log('AsyncStorage error: ' + error.message);
    }
  },

  componentDidMount: function() {
    this._userLogin();
  },

  _userLogin: function() {
    var value = this.refs.form.getValue();
    if (value) { // if validation fails, value will be null

      fetch("http://vowelserver.com/trades/test_autheticate/", {
    method: "POST",
    headers: {
      'Accept': 'application/json',
      'Content-Type': 'application/json'
    },
    body: JSON.stringify({
      username: value.username,
      password: value.password,
    })
      }).then((response) => response.json())
      .then((responseData) => {

    this._onValueChange(STORAGE_KEY, responseData.id_token)
      }).done();
    }
  },

  render() {
    return (
      <View style={styles.container}>
       <View style={styles.container}>
    <Image
     resizeMode="contain"
     source={{uri: 'http://res.cloudinary.com/vowelweb/image/upload/v1498114115/Logo_mqzlgt.png'}}
     style={styles.image}
    />
       </View>
    <View style={styles.row}>
      <Form
        ref="form"
        type={Person}
        options={options}
      />
    </View>
    <View style={styles.row}>
      <TouchableHighlight style={styles.button} onPress={this._userLogin} underlayColor='#99d9f4'>
        <Text style={styles.buttonText}>Login</Text>
      </TouchableHighlight>
    </View>
      </View>
    );
  }
});

var styles = StyleSheet.create({
  container: {
    justifyContent: 'center',
    marginTop: 50,
    padding: 20,
    backgroundColor: '#ffffff',
  },
 containers: {
   flex: 1,
   justifyContent: 'flex-start',
   alignItems: 'center',
   backgroundColor: 'white',
   position: 'relative',
   borderBottomWidth: 1,
 },
  title: {
    fontSize: 30,
    alignSelf: 'center',
    marginBottom: 30
  },
  buttonText: {
    fontSize: 18,
    color: 'white',
    alignSelf: 'center'
  },
  button: {
    height: 36,
    backgroundColor: '#48BBEC',
    borderColor: '#48BBEC',
    borderWidth: 1,
    borderRadius: 8,
    marginBottom: 10,
    alignSelf: 'stretch',
    justifyContent: 'center'
  },
 login: {
   flex: 1,
   backgroundColor: '#efeff2',
   alignItems: 'center',
   justifyContent: 'center',
 },
 image: {
  position: 'absolute',
  top: 0,
  bottom: 0,
  left: 30,`enter code here`
  right: 30,
 },
});

AppRegistry.registerComponent('FirstRun', () => AwesomeProject);
</code>```

答:
Pleas find the code snippet for the simple fetch api call in react.make sure you have valid url which will return you the response</p>

```<code>getMoviesFromApiAsync = () => {
    return fetch('http://droidtute.com/reactexample/sample_api/getMovieList.php')
      .then((response) => response.json())
      .then((responseJson) => {
       // alert(JSON.stringify(responseJson))
        this.setState({ moviesList: responseJson.movieList }) // this will update state to re-render ui
        return responseJson.movieList;
      })
      .catch((error) => {
        console.error(error);
      });
  }
</code>```

Body:
I have this code and I wanna login using the link in the fetch of this below code but I'm getting this error while clicking on the login button: JSON Parse Error: Unexpected EOF. I'm trying to use rest API for this login app.

var React = require('react');
var ReactNative = require('react-native');
var t = require('tcomb-form-native');

var {
  AppRegistry,
  AsyncStorage,
  StyleSheet,
  Text,
  View,
  TouchableHighlight,
  AlertIOS,
  Image,
} = ReactNative;

var STORAGE_KEY = 'id_token';

var Form = t.form.Form;

var Person = t.struct({
  username: t.String,
  password: t.String
});

const options = {};

var AwesomeProject = React.createClass({

  async _onValueChange(item, selectedValue) {
    try {
      await AsyncStorage.setItem(item, selectedValue);
    } catch (error) {
      console.log('AsyncStorage error: ' + error.message);
    }
  },

  componentDidMount: function() {
    this._userLogin();
  },

  _userLogin: function() {
    var value = this.refs.form.getValue();
    if (value) { // if validation fails, value will be null

      fetch("http://vowelserver.com/trades/test_autheticate/", {
    method: "POST",
    headers: {
      'Accept': 'application/json',
      'Content-Type': 'application/json'
    },
    body: JSON.stringify({
      username: value.username,
      password: value.password,
    })
      }).then((response) => response.json())
      .then((responseData) => {

    this._onValueChange(STORAGE_KEY, responseData.id_token)
      }).done();
    }
  },

  render() {
    return (
      <View style={styles.container}>
       <View style={styles.container}>
    <Image
     resizeMode="contain"
     source={{uri: 'http://res.cloudinary.com/vowelweb/image/upload/v1498114115/Logo_mqzlgt.png'}}
     style={styles.image}
    />
       </View>
    <View style={styles.row}>
      <Form
        ref="form"
        type={Person}
        options={options}
      />
    </View>
    <View style={styles.row}>
      <TouchableHighlight style={styles.button} onPress={this._userLogin} underlayColor='#99d9f4'>
        <Text style={styles.buttonText}>Login</Text>
      </TouchableHighlight>
    </View>
      </View>
    );
  }
});

var styles = StyleSheet.create({
  container: {
    justifyContent: 'center',
    marginTop: 50,
    padding: 20,
    backgroundColor: '#ffffff',
  },
 containers: {
   flex: 1,
   justifyContent: 'flex-start',
   alignItems: 'center',
   backgroundColor: 'white',
   position: 'relative',
   borderBottomWidth: 1,
 },
  title: {
    fontSize: 30,
    alignSelf: 'center',
    marginBottom: 30
  },
  buttonText: {
    fontSize: 18,
    color: 'white',
    alignSelf: 'center'
  },
  button: {
    height: 36,
    backgroundColor: '#48BBEC',
    borderColor: '#48BBEC',
    borderWidth: 1,
    borderRadius: 8,
    marginBottom: 10,
    alignSelf: 'stretch',
    justifyContent: 'center'
  },
 login: {
   flex: 1,
   backgroundColor: '#efeff2',
   alignItems: 'center',
   justifyContent: 'center',
 },
 image: {
  position: 'absolute',
  top: 0,
  bottom: 0,
  left: 30,`enter code here`
  right: 30,
 },
});

AppRegistry.registerComponent('FirstRun', () => AwesomeProject);

Body:
Pleas find the code snippet for the simple fetch api call in react.make sure you have valid url which will return you the response

getMoviesFromApiAsync = () => {
    return fetch('http://droidtute.com/reactexample/sample_api/getMovieList.php')
      .then((response) => response.json())
      .then((responseJson) => {
       // alert(JSON.stringify(responseJson))
        this.setState({ moviesList: responseJson.movieList }) // this will update state to re-render ui
        return responseJson.movieList;
      })
      .catch((error) => {
        console.error(error);
      });
  }


问:
My loop isn't drawing anything to the screen
I'm having difficulty with a simple while loop.

```<code>size(500,500);
background(255);
rectMode(CENTER);
noCursor();

int x1 = mouseX;
int y1 = mouseY;
int count = 0;
fill(0);
rect(250,250,50,50); //this is drawn
while (count == 0); {
  fill(0);
  rect(250,250,50,50); //this is not
}
</code>```

Its written in Processing.
Anything I have in the while loop isn't drawn, while anything after it isn't either. Anything before it, not in a loop, is drawn. What am I missing here?

答:
The other answer is half right. Your while loop ends with a ; semicolon, so it's just going to continually loop without doing anything.

We have been using the draw() function, but this time it was required to draw an object to the screen by using our own loops. Why is it that I shouldn't use an infinite loop? Doesn't it accomplish the same thing?

No. Even if you fix the semicolon problem, you'll still never see anything on the screen. That's because stuff is only shown on the screen when the code completes! If you have a draw() function, it's only shown at the end of the draw() function. If you don't, then it's only shown at the end of the program. Having an infinite loop prevents anything from being shown on the screen.

However, you don't have to have a setup() and draw() function. You just can't have an infinite loop. (The same thing is true if you do have a draw() function, btw.)

Note that the code in your while loop doesn't actually change, so you can just get rid of the while part. But also note that running your code without a draw() function means that mouseX and mouseY will always be 0.

Body:
I'm having difficulty with a simple while loop.

size(500,500);
background(255);
rectMode(CENTER);
noCursor();

int x1 = mouseX;
int y1 = mouseY;
int count = 0;
fill(0);
rect(250,250,50,50); //this is drawn
while (count == 0); {
  fill(0);
  rect(250,250,50,50); //this is not
}

Its written in Processing.
Anything I have in the while loop isn't drawn, while anything after it isn't either. Anything before it, not in a loop, is drawn. What am I missing here?


问:
Actionscript file not found when trying to compile a flash movie
I am using a PC and my consultant is on a Mac.  I have sent her my working files along with a folder of referenced .as files.  For some reason, when she goes to compile her movie it gives an error that the referenced .as file cannot be found.  It works fine on my machine.

I have double and triple checked to ensure she has all the correct files within the correct local directories so I am completely stumped.  I am using Flash CS4 and she is on CS5 - does anyone have any ideas for us?

答: Are you using capital letters in your filenames and referencing them incorrectly, as windows ignores them and as osx is a unix based operating system doesnt.</p>


问:
iOS - comparing app versions
I want to update my app on the App Store. When the app is first opened after the update, I want it to sync some stuff. Therefore I need a way to see if it's the first launch after the update.

The solution I thought of is: storing the app version in the NSUserDefaults like this:

```<code>NSString *oldVersion = [[NSUserDefaults standardUserDefaults] objectForKey:@"appVersion"];
NSString *currentVersion = [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleShortVersionString"];
[[NSUserDefaults standardUserDefaults] setObject:currentVersion forKey:@"appVersion"];
[[NSUserDefaults standardUserDefaults] synchronize];
</code>```

now I have the oldVersion and the currentVersion and all I need to do is to compare them. I want to know if the oldVersion is smaller the currentVersion. But they are strings. how can I check if oldVersion < currentVersion?

I know I can just check if they are not equal. But I want to be prepared for future updates. Because maybe the syncing I want to perform for this 2 will be different for version 3 and so on.

答:
Code in Swift 3.0 as String extension, that works with versions that contains extra zeros.(Ex: 1.0.0 & 1.0)

```</p>

```/// Inner comparison utility to handle same versions with different length. (Ex: 1.0.0 & 1.0)
private func compare(toVersion targetVersion: String) -> ComparisonResult {

    let versionDelimiter = "."
    var result: ComparisonResult = .orderedSame
    var versionComponents = components(separatedBy: versionDelimiter)
    var targetComponents = targetVersion.components(separatedBy: versionDelimiter)
    let spareCount = versionComponents.count - targetComponents.count

    if spareCount == 0 {
        result = compare(targetVersion, options: .numeric)
    } else {
        let spareZeros = repeatElement("0", count: abs(spareCount))
        if spareCount > 0 {
            targetComponents.append(contentsOf: spareZeros)
        } else {
            versionComponents.append(contentsOf: spareZeros)
        }
        result = versionComponents.joined(separator: versionDelimiter)
            .compare(targetComponents.joined(separator: versionDelimiter), options: .numeric)
    }
    return result
}

public func isVersion(equalTo targetVersion: String) -> Bool { return compare(toVersion: targetVersion) == .orderedSame }
public func isVersion(greaterThan targetVersion: String) -> Bool { return compare(toVersion: targetVersion) == .orderedDescending }
public func isVersion(greaterThanOrEqualTo targetVersion: String) -> Bool { return compare(toVersion: targetVersion) != .orderedAscending }
public func isVersion(lessThan targetVersion: String) -> Bool { return compare(toVersion: targetVersion) == .orderedAscending }
public func isVersion(lessThanOrEqualTo targetVersion: String) -> Bool { return compare(toVersion: targetVersion) != .orderedDescending }
```

<p>```

Title: iOS - comparing app versions

Body:
I want to update my app on the App Store. When the app is first opened after the update, I want it to sync some stuff. Therefore I need a way to see if it's the first launch after the update.

The solution I thought of is: storing the app version in the NSUserDefaults like this:

NSString *oldVersion = [[NSUserDefaults standardUserDefaults] objectForKey:@"appVersion"];
NSString *currentVersion = [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleShortVersionString"];
[[NSUserDefaults standardUserDefaults] setObject:currentVersion forKey:@"appVersion"];
[[NSUserDefaults standardUserDefaults] synchronize];

now I have the oldVersion and the currentVersion and all I need to do is to compare them. I want to know if the oldVersion is smaller the currentVersion. But they are strings. how can I check if oldVersion < currentVersion?

I know I can just check if they are not equal. But I want to be prepared for future updates. Because maybe the syncing I want to perform for this 2 will be different for version 3 and so on.

Body:
Code in Swift 3.0 as String extension, that works with versions that contains extra zeros.(Ex: 1.0.0 & 1.0)

```</p>

<pre><code>/// Inner comparison utility to handle same versions with different length. (Ex: 1.0.0 & 1.0)
private func compare(toVersion targetVersion: String) -> ComparisonResult {

    let versionDelimiter = "."
    var result: ComparisonResult = .orderedSame
    var versionComponents = components(separatedBy: versionDelimiter)
    var targetComponents = targetVersion.components(separatedBy: versionDelimiter)
    let spareCount = versionComponents.count - targetComponents.count

    if spareCount == 0 {
        result = compare(targetVersion, options: .numeric)
    } else {
        let spareZeros = repeatElement("0", count: abs(spareCount))
        if spareCount > 0 {
            targetComponents.append(contentsOf: spareZeros)
        } else {
            versionComponents.append(contentsOf: spareZeros)
        }
        result = versionComponents.joined(separator: versionDelimiter)
            .compare(targetComponents.joined(separator: versionDelimiter), options: .numeric)
    }
    return result
}

public func isVersion(equalTo targetVersion: String) -> Bool { return compare(toVersion: targetVersion) == .orderedSame }
public func isVersion(greaterThan targetVersion: String) -> Bool { return compare(toVersion: targetVersion) == .orderedDescending }
public func isVersion(greaterThanOrEqualTo targetVersion: String) -> Bool { return compare(toVersion: targetVersion) != .orderedAscending }
public func isVersion(lessThan targetVersion: String) -> Bool { return compare(toVersion: targetVersion) == .orderedAscending }
public func isVersion(lessThanOrEqualTo targetVersion: String) -> Bool { return compare(toVersion: targetVersion) != .orderedDescending }
</code></pre>

<p>```


问:
How to set k-Means clustering labels from highest to lowest with Python?
I have a dataset of 38 apartments and their electricity consumption in the morning, afternoon and evening. I am trying to clusterize this dataset using the k-Means implementation from scikit-learn, and am getting some interesting results.

First clustering results:

This is all very well, and with 4 clusters I obviously get 4 labels associated to each apartment - 0, 1, 2 and 3. Using the random_state parameter of KMeans method, I can fix the seed in which the centroids are randomly initialized, so consistently I get the same labels attributed to the same apartments.

However, as this specific case is in regards of energy consumption, a measurable classification between the highest and the lowest consumers can be performed. I would like, thus, to assign the label 0 to the apartments with lowest consumption level, label 1 to apartments that consume a bit more and so on.

As of now, my labels are [2 1 3 0], or ["black", "green", "blue", "red"]; I would like them to be [0 1 2 3] or ["red", "green", "black", "blue"]. How should I proceed to do so, while still keeping the centroid initialization random (with fixed seed)?

Thank you very much for the help!

答:
Transforming the labels through a lookup table is a straightforward way to achieve what you want.

To begin with I generate some mock data:

```<code>import numpy as np

np.random.seed(1000)

n = 38
X_morning = np.random.uniform(low=.02, high=.18, size=38)
X_afternoon = np.random.uniform(low=.05, high=.20, size=38)
X_night = np.random.uniform(low=.025, high=.175, size=38)
X = np.vstack([X_morning, X_afternoon, X_night]).T
</code>```

Then I perform clustering on data:

```<code>from sklearn.cluster import KMeans
k = 4
kmeans = KMeans(n_clusters=k, random_state=0).fit(X)
</code>```

And finally I use NumPy's argsort to create a lookup table like this:

```<code>idx = np.argsort(kmeans.cluster_centers_.sum(axis=1))
lut = np.zeros_like(idx)
lut[idx] = np.arange(k)
</code>```

Sample run:

```<code>In [70]: kmeans.cluster_centers_.sum(axis=1)
Out[70]: array([ 0.3214523 ,  0.40877735,  0.26911353,  0.25234873])

In [71]: idx
Out[71]: array([3, 2, 0, 1], dtype=int64)

In [72]: lut
Out[72]: array([2, 3, 1, 0], dtype=int64)

In [73]: kmeans.labels_
Out[73]: array([1, 3, 1, ..., 0, 1, 0])

In [74]: lut[kmeans.labels_]
Out[74]: array([3, 0, 3, ..., 2, 3, 2], dtype=int64)
</code>```

idx shows the cluster center labels ordered from lowest to highest consumption level. The appartments for which lut[kmeans.labels_] is 0 / 3 belong to the cluster with the lowest / highest consumption levels.

Body:
Transforming the labels through a lookup table is a straightforward way to achieve what you want.

To begin with I generate some mock data:

import numpy as np

np.random.seed(1000)

n = 38
X_morning = np.random.uniform(low=.02, high=.18, size=38)
X_afternoon = np.random.uniform(low=.05, high=.20, size=38)
X_night = np.random.uniform(low=.025, high=.175, size=38)
X = np.vstack([X_morning, X_afternoon, X_night]).T

Then I perform clustering on data:

from sklearn.cluster import KMeans
k = 4
kmeans = KMeans(n_clusters=k, random_state=0).fit(X)

And finally I use NumPy's argsort to create a lookup table like this:

idx = np.argsort(kmeans.cluster_centers_.sum(axis=1))
lut = np.zeros_like(idx)
lut[idx] = np.arange(k)

Sample run:

In [70]: kmeans.cluster_centers_.sum(axis=1)
Out[70]: array([ 0.3214523 ,  0.40877735,  0.26911353,  0.25234873])

In [71]: idx
Out[71]: array([3, 2, 0, 1], dtype=int64)

In [72]: lut
Out[72]: array([2, 3, 1, 0], dtype=int64)

In [73]: kmeans.labels_
Out[73]: array([1, 3, 1, ..., 0, 1, 0])

In [74]: lut[kmeans.labels_]
Out[74]: array([3, 0, 3, ..., 2, 3, 2], dtype=int64)

idx shows the cluster center labels ordered from lowest to highest consumption level. The appartments for which lut[kmeans.labels_] is 0 / 3 belong to the cluster with the lowest / highest consumption levels.


问:
Duplicate values Error on Non-Index, Non-Unique property change
I ask a similar question here, but this is a different situation that results in the same error message.

I am updating an NON-index, NON-unique property, PageNumber.

And I am receiving the following error

OleDbException: The changes you requested to the table were not successful because they would create duplicate values in the index, primary key, or relationship. Change the data in the field or fields that contain duplicate data, remove the index, or redefine the index to permit duplicate entries and try again.

```<code>public void DoRenumberPages(object blah)
{

    var hiddenPages = projectDB.Pages.AsEnumerable().Where(x => !IsVisibleDrawing(x.DrawingType) && x.DrawingType != 3001).ToList();

    for (int i = 0; i < hiddenPages.Count(); i++)
    {
        hiddenPages[i].PageNumber = i + 1000;
    }

    var TOCPages = projectDB.Pages.AsEnumerable().Where(x => x.DrawingType == 3001).OrderBy(x => x.BookNumber).ToList();

    for (int i = 0; i < TOCPages.Count(); i++)
    {
        TOCPages[i].PageNumber = i + 1;
    }

    var visiblePagesNotTOC = projectDB.Pages.AsEnumerable().Where(x => IsVisibleDrawing(x.DrawingType) && x.DrawingType != 3001).OrderBy(x => x.BookNumber).ToList();

    for (int i = 0; i < visiblePagesNotTOC.Count(); i++)
    {
        visiblePagesNotTOC[i].PageNumber = i + TOCPages.Count() + 1;
    }

    projectDB.SaveChanges();

    RenumberPages.EnableExecute();

}
</code>```

Page Model Class

```<code>[Table("Content")]
public class Page
{
    //** Primary Key
    [Column("Counter")]
    public int Id { get; set; }

    public int ProjectCounter { get; set; }

    public short Version { get; set; }
    public short Revision { get; set; }
    public bool Locked { get; set; }

    public int DrawingType { get; set; }
    //** Forign Key?
    public int DeviceLocationCounter { get; set; }
    //** Forign Key?
    public int FolderID { get; set; }

    [Column("Page")]
    public int PageNumber { get; set; }
    //** Indexed, Unique
    public int BookNumber { get; set; }

    public string PageIndex { get; set; }

    //** Product
    //** DrawingObject is not here

    public bool Update { get; set; }
    public short Flag { get; set; }
}
</code>```

ETA:

I have change public int BookNumber { get; set; } to public int? BookNumber { get; set; } This doesn't solve the issue.

答:
Ok, I could start the project.

The problem is the one I wrote here duplicate values in the index, primary key, or relationship. If you enable query printing setting JetEntityFrameworkProvider.JetConnection.ShowSqlStatements = true; somewhere (I did it in your Test.Program.Main) you can see the statements that EF runs. The first update query is

```<code>update [Content]
set [Page] = @p0
where ([Counter] = @p1)

@p0 = 3
@p1 = 2
</code>```

If you look at the database, the time you run the query the Page = 3 is already contained in the record with Counter = 3. You can't solve this problem also inside a transaction and also with other (next to all) DBMSs you have the same problem.

The only solution (if you need the unique index on Page) is to update in 2 different SaveChanges. For example:

1. Set Page = null then SaveChanges()

2. Set Page = number then SaveChanges()

Microsoft Access permits duplicated null values in unique indexes. If you will permit to use different databases you could have problems.

Body:
I ask a similar question here, but this is a different situation that results in the same error message.

I am updating an NON-index, NON-unique property, PageNumber.

And I am receiving the following error

OleDbException: The changes you requested to the table were not successful because they would create duplicate values in the index, primary key, or relationship. Change the data in the field or fields that contain duplicate data, remove the index, or redefine the index to permit duplicate entries and try again.

public void DoRenumberPages(object blah)
{

    var hiddenPages = projectDB.Pages.AsEnumerable().Where(x => !IsVisibleDrawing(x.DrawingType) && x.DrawingType != 3001).ToList();

    for (int i = 0; i < hiddenPages.Count(); i++)
    {
        hiddenPages[i].PageNumber = i + 1000;
    }

    var TOCPages = projectDB.Pages.AsEnumerable().Where(x => x.DrawingType == 3001).OrderBy(x => x.BookNumber).ToList();

    for (int i = 0; i < TOCPages.Count(); i++)
    {
        TOCPages[i].PageNumber = i + 1;
    }

    var visiblePagesNotTOC = projectDB.Pages.AsEnumerable().Where(x => IsVisibleDrawing(x.DrawingType) && x.DrawingType != 3001).OrderBy(x => x.BookNumber).ToList();

    for (int i = 0; i < visiblePagesNotTOC.Count(); i++)
    {
        visiblePagesNotTOC[i].PageNumber = i + TOCPages.Count() + 1;
    }

    projectDB.SaveChanges();

    RenumberPages.EnableExecute();

}

Page Model Class

[Table("Content")]
public class Page
{
    //** Primary Key
    [Column("Counter")]
    public int Id { get; set; }

    public int ProjectCounter { get; set; }

    public short Version { get; set; }
    public short Revision { get; set; }
    public bool Locked { get; set; }

    public int DrawingType { get; set; }
    //** Forign Key?
    public int DeviceLocationCounter { get; set; }
    //** Forign Key?
    public int FolderID { get; set; }

    [Column("Page")]
    public int PageNumber { get; set; }
    //** Indexed, Unique
    public int BookNumber { get; set; }

    public string PageIndex { get; set; }

    //** Product
    //** DrawingObject is not here

    public bool Update { get; set; }
    public short Flag { get; set; }
}

ETA:

I have change public int BookNumber { get; set; } to public int? BookNumber { get; set; } This doesn't solve the issue.

Body:
Ok, I could start the project.

The problem is the one I wrote here duplicate values in the index, primary key, or relationship. If you enable query printing setting JetEntityFrameworkProvider.JetConnection.ShowSqlStatements = true; somewhere (I did it in your Test.Program.Main) you can see the statements that EF runs. The first update query is

update [Content]
set [Page] = @p0
where ([Counter] = @p1)

@p0 = 3
@p1 = 2

If you look at the database, the time you run the query the Page = 3 is already contained in the record with Counter = 3. You can't solve this problem also inside a transaction and also with other (next to all) DBMSs you have the same problem.

The only solution (if you need the unique index on Page) is to update in 2 different SaveChanges. For example:

1. Set Page = null then SaveChanges()

2. Set Page = number then SaveChanges()

Microsoft Access permits duplicated null values in unique indexes. If you will permit to use different databases you could have problems.


问:
Distinct values with multiple Sum aggregations on reverse relation
According to the Django docs combining multiple aggregations with annotate() will yield the wrong results because joins are used instead of subqueries. They furthermore note, that Count has a distinct parameter that may help.

Is there something similiar to Sum? I end up with wrong results in this stripped down example. The resulting amount values are too high for most projects.

```<code>qs = Client.filter('project__date__year=2017').annotate(
    isum=Sum('project__intoffer__amount', distinct=True),
    esum=Sum('project__extoffer__amount', distinct=True)
)
</code>```

The distinct=True parameters don't make any difference.

Simplified models.py:

```<code>class Client(models.Model):
    title = models.CharField('Title', max_length=50)

class Project(models.Model):
    title = models.CharField('Title', max_length=100)
    client = models.ForeignKey('Client', verbose_name='Client')
    date = models.DateField('Date', blank=True, null=True)

class IntOffer(models.Model):
    project = models.ForeignKey(Project, verbose_name='Project')
    amount = models.DecimalField('Amount', max_digits=19, decimal_places=2)

class ExtOffer(models.Model):
    project = models.ForeignKey(Project, verbose_name='Project')
    amount = models.DecimalField('Amount', max_digits=19, decimal_places=2)
</code>```

答:
You can try to use django Subquery expression. In your case your query look like this:

```<code>from django.db.models import Sum, OuterRef, Subquery

qs = Client.filter('project__date__year=2017').annotate(
    isum=Subquery(Project.objects.filter(client=OuterRef('pk')).values('client_id').annotate(sum=Sum('intoffer__amount')).values('sum')[:1]),
    esum=Subquery(Project.objects.filter(client=OuterRef('pk')).values('client_id').annotate(sum=Sum('extoffer__amount')).values('sum')[:1])
)
</code>```

Note that it can be slow on large tables, in this case probably better to use RawSQL.

Body:
According to the Django docs combining multiple aggregations with annotate() will yield the wrong results because joins are used instead of subqueries. They furthermore note, that Count has a distinct parameter that may help.

Is there something similiar to Sum? I end up with wrong results in this stripped down example. The resulting amount values are too high for most projects.

qs = Client.filter('project__date__year=2017').annotate(
    isum=Sum('project__intoffer__amount', distinct=True),
    esum=Sum('project__extoffer__amount', distinct=True)
)

The distinct=True parameters don't make any difference.

Simplified models.py:

class Client(models.Model):
    title = models.CharField('Title', max_length=50)

class Project(models.Model):
    title = models.CharField('Title', max_length=100)
    client = models.ForeignKey('Client', verbose_name='Client')
    date = models.DateField('Date', blank=True, null=True)

class IntOffer(models.Model):
    project = models.ForeignKey(Project, verbose_name='Project')
    amount = models.DecimalField('Amount', max_digits=19, decimal_places=2)

class ExtOffer(models.Model):
    project = models.ForeignKey(Project, verbose_name='Project')
    amount = models.DecimalField('Amount', max_digits=19, decimal_places=2)

Body:
You can try to use django Subquery expression. In your case your query look like this:

from django.db.models import Sum, OuterRef, Subquery

qs = Client.filter('project__date__year=2017').annotate(
    isum=Subquery(Project.objects.filter(client=OuterRef('pk')).values('client_id').annotate(sum=Sum('intoffer__amount')).values('sum')[:1]),
    esum=Subquery(Project.objects.filter(client=OuterRef('pk')).values('client_id').annotate(sum=Sum('extoffer__amount')).values('sum')[:1])
)

Note that it can be slow on large tables, in this case probably better to use RawSQL.


问:
Not getting dynamic variable names PHP
I want to print the values of variable but it prints 12 only</p>

```<code>$str1="abhishek";
$str2="ashish";
for($i=1;$i<=2;$i++)
{
echo $str.$i;
}
</code>```

答:
This is a better practice:</p>

```<code><?php
$str = array("abhishek","ashish");

for($i=0; $i <= 2; $i++)
{
echo $str[$i].'<br>';
}
?>
</code>```

Title: Not getting dynamic variable names PHP

Body:
I want to print the values of variable but it prints 12 only

$str1="abhishek";
$str2="ashish";
for($i=1;$i<=2;$i++)
{
echo $str.$i;
}

Body:
This is a better practice:

<?php
$str = array("abhishek","ashish");

for($i=0; $i <= 2; $i++)
{
echo $str[$i].'<br>';
}
?>


问:
Error Sigabrt with Google Sign In Xcode
I am experiencing an error on build in the AppDelegate file which is a sigabrt error. I have already read many other threads on sigabrt, but I am asking how to fix this sigabrt error because of how it is related to the Google Sign In.

ViewController.swift code:

```<code>import UIKit
import GoogleSignIn
import Firebase
class ViewController: UIViewController, GIDSignInUIDelegate {
    override func viewDidLoad() {
        super.viewDidLoad()
        setupGoogleButtons()
    }

    fileprivate func setupGoogleButtons(){
        //default google sign in button
        let googleButton = GIDSignInButton()
        googleButton.frame = CGRect(x: 16, y: 116 + 80, width: view.frame.width - 32, height: 50)
        view.addSubview(googleButton)

        //custom google sign in button
        let customButton = UIButton(type: .system)
        customButton.frame = CGRect(x: 16, y: 116 + 80 + 66, width: view.frame.width - 32, height: 50)
        customButton.backgroundColor = .blue
        customButton.setTitleColor(.white, for: .normal)
        customButton.titleLabel?.font = UIFont.boldSystemFont(ofSize: 14)
        customButton.setTitle("Google Sign In #2", for: .normal)
        customButton.addTarget(self, action: #selector(handleCustomGoogleSignIn), for: .touchUpInside)
        view.addSubview(customButton)
    }

    func handleCustomGoogleSignIn() {
        GIDSignIn.sharedInstance().signIn()
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
}
</code>```

AppDelegate file code:

```<code>import UIKit
import Firebase
import GoogleSignIn

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate, GIDSignInDelegate {
    var window: UIWindow?

    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
        FIRApp.configure()

        GIDSignIn.sharedInstance().clientID = FIRApp.defaultApp()?.options.clientID
        GIDSignIn.sharedInstance().delegate = self

        return true
    }

    func sign(_ signIn: GIDSignIn!, didSignInFor user: GIDGoogleUser!, withError error: Error!) {
        if let err = error {
            print("Failed to log into Google: ", err)
            return
        }

        print("Successfully logged into Google", user)

        guard let idToken = user.authentication.idToken else { return }
        guard let accessToken = user.authentication.accessToken else { return }
        let credentials = FIRGoogleAuthProvider.credential(withIDToken: idToken, accessToken: accessToken)

        FIRAuth.auth()?.signIn(with: credentials, completion: { (user, error) in
            if let err = error {
                print("Failed to create a Firebase User with Google account: ", err)
                return
            }

            guard let uid = user?.uid else { return }
            print("Successfully logged into Firebase with Google", uid)
        })
    }

    func application(_ application: UIApplication, open url: URL, options: [UIApplicationOpenURLOptionsKey: Any] = [:]) -> Bool {
        GIDSignIn.sharedInstance().handle(url,
                                             sourceApplication: options[UIApplicationOpenURLOptionsKey.sourceApplication] as? String,
                                             annotation: options[UIApplicationOpenURLOptionsKey.annotation])
        return true
    }
}
</code>```

Console Error message:

```
objc[12677]: Class PLBuildVersion is implemented in both /Users/tarunaarora/Downloads/Xcode-beta.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator.sdk/System/Library/PrivateFrameworks/AssetsLibraryServices.framework/AssetsLibraryServices (0x119012998) and /Users/tarunaarora/Downloads/Xcode-beta.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator.sdk/System/Library/PrivateFrameworks/PhotoLibraryServices.framework/PhotoLibraryServices (0x118e34880). One of the two will be used. Which one is undefined.
2016-11-21 21:44:27.647 GunnOracleGoogleSignIn[12677:470666] Firebase automatic screen reporting is enabled. Call +[FIRAnalytics setScreenName:setScreenClass:] to set the screen name or override the default screen class name. To disable automatic screen reporting, set the flag FirebaseAutomaticScreenReportingEnabled to NO in the Info.plist
2016-11-21 21:44:27.929: <FIRInstanceID/WARNING> FIRInstanceID AppDelegate proxy enabled, will swizzle app delegate remote notification handlers. To disable add "FirebaseAppDelegateProxyEnabled" to your Info.plist and set it to NO
2016-11-21 21:44:27.928 GunnOracleGoogleSignIn[12677] <Debug> [Firebase/Core][I-COR000001] Configuring the default app.
2016-11-21 21:44:28.330 GunnOracleGoogleSignIn[12677:] <FIRAnalytics/INFO> Firebase Analytics v.3501000 started
2016-11-21 21:44:28.542 GunnOracleGoogleSignIn[12677:] <FIRAnalytics/INFO> To enable debug logging set the following application argument: -FIRAnalyticsDebugEnabled (see (google url//can't show because it is goo.gl))
2016-11-21 21:44:28.637 GunnOracleGoogleSignIn[12677:] <FIRAnalytics/INFO> Successfully created Firebase Analytics App Delegate Proxy automatically. To disable the proxy, set the flag FirebaseAppDelegateProxyEnabled to NO in the Info.plist
2016-11-21 21:44:28.782 GunnOracleGoogleSignIn[12677] <Debug> [Firebase/Core][I-COR000019] Clearcut post completed.
2016-11-21 21:44:30.143 GunnOracleGoogleSignIn[12677:] <FIRAnalytics/WARNING> The AdSupport Framework is not currently linked. Some features will not function properly. Learn more at (Can't show goo.gl url)
2016-11-21 21:44:31.086 GunnOracleGoogleSignIn[12677:] <FIRAnalytics/INFO> Firebase Analytics enabled
2016-11-21 21:44:31.841 GunnOracleGoogleSignIn[12677:470666] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'uiDelegate must either be a |UIViewController| or implement the |signIn:presentViewController:| and |signIn:dismissViewController:| methods from |GIDSignInUIDelegate|.'
*** First throw call stack:
(
    0   CoreFoundation                      0x00000001076ffd4b __exceptionPreprocess + 171
    1   libobjc.A.dylib                     0x000000010716121e objc_exception_throw + 48
    2   CoreFoundation                      0x00000001077692b5 +[NSException raise:format:] + 197
    3   GunnOracleGoogleSignIn              0x000000010619df7e -[GIDSignIn signInWithOptions:] + 88
    4   GunnOracleGoogleSignIn              0x00000001061a1c13 -[GIDSignInButton pressed] + 242
    5   UIKit                               0x000000010823845c -[UIApplication sendAction:to:from:forEvent:] + 83
    6   UIKit                               0x00000001083be344 -[UIControl sendAction:to:forEvent:] + 67
    7   UIKit                               0x00000001083be65d -[UIControl _sendActionsForEvents:withEvent:] + 444
    8   UIKit                               0x00000001083bd559 -[UIControl touchesEnded:withEvent:] + 668
    9   UIKit                               0x00000001082a5d5d -[UIWindow _sendTouchesForEvent:] + 2747
    10  UIKit                               0x00000001082a744b -[UIWindow sendEvent:] + 4011
    11  UIKit                               0x000000010825454b -[UIApplication sendEvent:] + 371
    12  UIKit                               0x0000000108a3fa0f __dispatchPreprocessedEventFromEventQueue + 3248
    13  UIKit                               0x0000000108a38745 __handleEventQueue + 4879
    14  CoreFoundation                      0x00000001076a48e1 __CFRUNLOOP_IS_CALLING_OUT_TO_A_SOURCE0_PERFORM_FUNCTION__ + 17
    15  CoreFoundation                      0x0000000107689b0c __CFRunLoopDoSources0 + 556
    16  CoreFoundation                      0x0000000107688ff6 __CFRunLoopRun + 918
    17  CoreFoundation                      0x0000000107688a04 CFRunLoopRunSpecific + 420
    18  GraphicsServices                    0x000000010bad6a6f GSEventRunModal + 161
    19  UIKit                               0x0000000108236808 UIApplicationMain + 159
    20  GunnOracleGoogleSignIn              0x00000001060f669f main + 111
    21  libdyld.dylib                       0x000000010a4a368d start + 1
    22  ???                                 0x0000000000000001 0x0 + 1
)
libc++abi.dylib: terminating with uncaught exception of type NSException
```

Let me know if there is anything else that needs to be included.

答:
In my case the reason was this error:

```<code>Unable to correctly configure subspec Analytics
</code>```

which is fixed by setting a correct tracking id to GoogleService-Info.plist. See for more info: App Delegate crashes because of Firebase initialization

Title: Error Sigabrt with Google Sign In Xcode

Body:
I am experiencing an error on build in the AppDelegate file which is a sigabrt error. I have already read many other threads on sigabrt, but I am asking how to fix this sigabrt error because of how it is related to the Google Sign In.

ViewController.swift code:

import UIKit
import GoogleSignIn
import Firebase
class ViewController: UIViewController, GIDSignInUIDelegate {
    override func viewDidLoad() {
        super.viewDidLoad()
        setupGoogleButtons()
    }

    fileprivate func setupGoogleButtons(){
        //default google sign in button
        let googleButton = GIDSignInButton()
        googleButton.frame = CGRect(x: 16, y: 116 + 80, width: view.frame.width - 32, height: 50)
        view.addSubview(googleButton)

        //custom google sign in button
        let customButton = UIButton(type: .system)
        customButton.frame = CGRect(x: 16, y: 116 + 80 + 66, width: view.frame.width - 32, height: 50)
        customButton.backgroundColor = .blue
        customButton.setTitleColor(.white, for: .normal)
        customButton.titleLabel?.font = UIFont.boldSystemFont(ofSize: 14)
        customButton.setTitle("Google Sign In #2", for: .normal)
        customButton.addTarget(self, action: #selector(handleCustomGoogleSignIn), for: .touchUpInside)
        view.addSubview(customButton)
    }

    func handleCustomGoogleSignIn() {
        GIDSignIn.sharedInstance().signIn()
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
}

AppDelegate file code:

import UIKit
import Firebase
import GoogleSignIn

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate, GIDSignInDelegate {
    var window: UIWindow?

    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
        FIRApp.configure()

        GIDSignIn.sharedInstance().clientID = FIRApp.defaultApp()?.options.clientID
        GIDSignIn.sharedInstance().delegate = self

        return true
    }

    func sign(_ signIn: GIDSignIn!, didSignInFor user: GIDGoogleUser!, withError error: Error!) {
        if let err = error {
            print("Failed to log into Google: ", err)
            return
        }

        print("Successfully logged into Google", user)

        guard let idToken = user.authentication.idToken else { return }
        guard let accessToken = user.authentication.accessToken else { return }
        let credentials = FIRGoogleAuthProvider.credential(withIDToken: idToken, accessToken: accessToken)

        FIRAuth.auth()?.signIn(with: credentials, completion: { (user, error) in
            if let err = error {
                print("Failed to create a Firebase User with Google account: ", err)
                return
            }

            guard let uid = user?.uid else { return }
            print("Successfully logged into Firebase with Google", uid)
        })
    }

    func application(_ application: UIApplication, open url: URL, options: [UIApplicationOpenURLOptionsKey: Any] = [:]) -> Bool {
        GIDSignIn.sharedInstance().handle(url,
                                             sourceApplication: options[UIApplicationOpenURLOptionsKey.sourceApplication] as? String,
                                             annotation: options[UIApplicationOpenURLOptionsKey.annotation])
        return true
    }
}

Console Error message:

objc[12677]: Class PLBuildVersion is implemented in both /Users/tarunaarora/Downloads/Xcode-beta.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator.sdk/System/Library/PrivateFrameworks/AssetsLibraryServices.framework/AssetsLibraryServices (0x119012998) and /Users/tarunaarora/Downloads/Xcode-beta.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator.sdk/System/Library/PrivateFrameworks/PhotoLibraryServices.framework/PhotoLibraryServices (0x118e34880). One of the two will be used. Which one is undefined.
2016-11-21 21:44:27.647 GunnOracleGoogleSignIn[12677:470666] Firebase automatic screen reporting is enabled. Call +[FIRAnalytics setScreenName:setScreenClass:] to set the screen name or override the default screen class name. To disable automatic screen reporting, set the flag FirebaseAutomaticScreenReportingEnabled to NO in the Info.plist
2016-11-21 21:44:27.929: <FIRInstanceID/WARNING> FIRInstanceID AppDelegate proxy enabled, will swizzle app delegate remote notification handlers. To disable add "FirebaseAppDelegateProxyEnabled" to your Info.plist and set it to NO
2016-11-21 21:44:27.928 GunnOracleGoogleSignIn[12677] <Debug> [Firebase/Core][I-COR000001] Configuring the default app.
2016-11-21 21:44:28.330 GunnOracleGoogleSignIn[12677:] <FIRAnalytics/INFO> Firebase Analytics v.3501000 started
2016-11-21 21:44:28.542 GunnOracleGoogleSignIn[12677:] <FIRAnalytics/INFO> To enable debug logging set the following application argument: -FIRAnalyticsDebugEnabled (see (google url//can't show because it is goo.gl))
2016-11-21 21:44:28.637 GunnOracleGoogleSignIn[12677:] <FIRAnalytics/INFO> Successfully created Firebase Analytics App Delegate Proxy automatically. To disable the proxy, set the flag FirebaseAppDelegateProxyEnabled to NO in the Info.plist
2016-11-21 21:44:28.782 GunnOracleGoogleSignIn[12677] <Debug> [Firebase/Core][I-COR000019] Clearcut post completed.
2016-11-21 21:44:30.143 GunnOracleGoogleSignIn[12677:] <FIRAnalytics/WARNING> The AdSupport Framework is not currently linked. Some features will not function properly. Learn more at (Can't show goo.gl url)
2016-11-21 21:44:31.086 GunnOracleGoogleSignIn[12677:] <FIRAnalytics/INFO> Firebase Analytics enabled
2016-11-21 21:44:31.841 GunnOracleGoogleSignIn[12677:470666] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'uiDelegate must either be a |UIViewController| or implement the |signIn:presentViewController:| and |signIn:dismissViewController:| methods from |GIDSignInUIDelegate|.'
*** First throw call stack:
(
    0   CoreFoundation                      0x00000001076ffd4b __exceptionPreprocess + 171
    1   libobjc.A.dylib                     0x000000010716121e objc_exception_throw + 48
    2   CoreFoundation                      0x00000001077692b5 +[NSException raise:format:] + 197
    3   GunnOracleGoogleSignIn              0x000000010619df7e -[GIDSignIn signInWithOptions:] + 88
    4   GunnOracleGoogleSignIn              0x00000001061a1c13 -[GIDSignInButton pressed] + 242
    5   UIKit                               0x000000010823845c -[UIApplication sendAction:to:from:forEvent:] + 83
    6   UIKit                               0x00000001083be344 -[UIControl sendAction:to:forEvent:] + 67
    7   UIKit                               0x00000001083be65d -[UIControl _sendActionsForEvents:withEvent:] + 444
    8   UIKit                               0x00000001083bd559 -[UIControl touchesEnded:withEvent:] + 668
    9   UIKit                               0x00000001082a5d5d -[UIWindow _sendTouchesForEvent:] + 2747
    10  UIKit                               0x00000001082a744b -[UIWindow sendEvent:] + 4011
    11  UIKit                               0x000000010825454b -[UIApplication sendEvent:] + 371
    12  UIKit                               0x0000000108a3fa0f __dispatchPreprocessedEventFromEventQueue + 3248
    13  UIKit                               0x0000000108a38745 __handleEventQueue + 4879
    14  CoreFoundation                      0x00000001076a48e1 __CFRUNLOOP_IS_CALLING_OUT_TO_A_SOURCE0_PERFORM_FUNCTION__ + 17
    15  CoreFoundation                      0x0000000107689b0c __CFRunLoopDoSources0 + 556
    16  CoreFoundation                      0x0000000107688ff6 __CFRunLoopRun + 918
    17  CoreFoundation                      0x0000000107688a04 CFRunLoopRunSpecific + 420
    18  GraphicsServices                    0x000000010bad6a6f GSEventRunModal + 161
    19  UIKit                               0x0000000108236808 UIApplicationMain + 159
    20  GunnOracleGoogleSignIn              0x00000001060f669f main + 111
    21  libdyld.dylib                       0x000000010a4a368d start + 1
    22  ???                                 0x0000000000000001 0x0 + 1
)
libc++abi.dylib: terminating with uncaught exception of type NSException

Let me know if there is anything else that needs to be included.

Body:
In my case the reason was this error:

Unable to correctly configure subspec Analytics

which is fixed by setting a correct tracking id to GoogleService-Info.plist. See for more info: App Delegate crashes because of Firebase initialization


问:
WordPress generated files edited with HTML
After basic knowledge of HTML/CSS/JS and Jquery, I got myself into WordPress. In order to save time and not build things from zero, I would use pre-made templates, and modify them according to the built of the desired future webpage. There might be a huge misconception in my head, but so far I havent found reply for this solution.

I have a locally running WordPress webpage with the help of WAMP. My webpage would consist 3 separate HTML files, lets say "index.html, contact.html, about.html". My issue is that after generating those pages in WordPress, I dont find any way to modify the HTML file of those sites. Nor locally in my computer, nor in the surface of WordPress. I found the "editor" function in WP, but apparently it lets me to edit only the CSS file.

My main goal is to generate the file with a template, than import it to BRACKETS / ATOM / etc and custom-shape the HTML and CSS on it. What am I missing ?

Thanks,

答:
Wordpress only has templates it uses according to the type of content (page, blog post or any other custom post type you define in the theme) requested. All your actual data is stored in the mysql database. This data is retrieved and inserted into the template and then the generated file is sent to the client. So, you wont find any .html files in the wordpress core.

My suggestion is to view the source in the browser, copy, paste and edit in your favourite editor.


问:
Combine 2 arrays into 1 in all possible ways in JavaScript
My goal is to merge 2 arrays in all possible ways, in a way that, the 1st array will always be the first part of the cell, and the 2nd array will always be in the 2nd part of the cell.

My last attempt, which is the closest but not exactly what I need:

```<code>function combineArrays(array1, array2) {
    let arr = [];
    for (let i = 0; i < array1.length; i++) {
        arr[i] = array1[i];
    }
    for (let i = 0, j = 0; i < array1.length; i++) {
        arr[i] += array2[j];
        if (array2[j + 1]) {
            j++;
        }
        else {
            j = 0;
        }
    }
    return arr;
}
</code>```

Edit:

For example, array A and array B:

A: [ "I", "You", "He", "She" ]

B: [ "am", "is", "are" ]

Expected result:

[

"I am", "You am", "He am", "She am",

"I is", "You is', "He is", "She is",

"I are", "You are", "He are", "She are"

]

答:
```<code>var arr1 = ['a', 'b', 'c'];
var arr2 = ['d', 'e', 'f'];

var arr3 = arr1.concat(arr2);

// arr3 is a new array [ "a", "b", "c", "d", "e", "f" ]
</code>```

but you seem you want to sum array that you achieve like this:

```<code>var array1 = [1,2,3,4];
var array2 = [5,6,7,8];

var sum = array1.map(function (num, idx) {
  return num + array2[idx];
});
// [6,8,10,12]
</code>```

Body:
My goal is to merge 2 arrays in all possible ways, in a way that, the 1st array will always be the first part of the cell, and the 2nd array will always be in the 2nd part of the cell.

My last attempt, which is the closest but not exactly what I need:

function combineArrays(array1, array2) {
    let arr = [];
    for (let i = 0; i < array1.length; i++) {
        arr[i] = array1[i];
    }
    for (let i = 0, j = 0; i < array1.length; i++) {
        arr[i] += array2[j];
        if (array2[j + 1]) {
            j++;
        }
        else {
            j = 0;
        }
    }
    return arr;
}

Edit:

For example, array A and array B:

A: [ "I", "You", "He", "She" ]

B: [ "am", "is", "are" ]

Expected result:

[

"I am", "You am", "He am", "She am",

"I is", "You is', "He is", "She is",

"I are", "You are", "He are", "She are"

]

Body:
var arr1 = ['a', 'b', 'c'];
var arr2 = ['d', 'e', 'f'];

var arr3 = arr1.concat(arr2);

// arr3 is a new array [ "a", "b", "c", "d", "e", "f" ]

but you seem you want to sum array that you achieve like this:

var array1 = [1,2,3,4];
var array2 = [5,6,7,8];

var sum = array1.map(function (num, idx) {
  return num + array2[idx];
});
// [6,8,10,12]


问:
Open Login component as Separate Page
I want to open login page in separate. But its opening in inside routeroutlet page. Please help.

PFB below screenshot for your reference.

Please refer my code below.

App.Routing.ts :

```<code>import { Routes } from '@angular/router';
import { DashboardComponent } from './components/dashboard/dashboard.component';
import { LoginComponent } from './components/login/login.component';
import { HomeComponent } from './components/home/home.component';

export const AppRoute: Routes = [
    { path: '', redirectTo: 'HomeComponent', pathMatch: 'full' },
    { path: 'login', component: LoginCoHomeComponentmponent },
    { path: 'home', component: HomeComponent },

];
</code>```

App.Component.html

```<code><div id="wrapper">
   <app-top-bar></app-top-bar>
   <router-outlet></router-outlet>
</div>
</code>```

App.Module.ts

```<code>import { BrowserModule } from '@angular/platform-browser';
import { APP_BASE_HREF, LocationStrategy, HashLocationStrategy } from '@angular/common';
import { NgModule } from '@angular/core';
import { FormsModule, ReactiveFormsModule } from '@angular/forms';
import { HttpModule } from '@angular/http';
import { SelectModule } from 'ng2-select';
import { Ng2Bs3ModalModule } from 'ng2-bs3-modal/ng2-bs3-modal';

import { AppComponent } from './app.component';
import { SideBarComponent } from './components/side-bar/side-bar.component';
import { TopBarComponent } from './components/top-bar/top-bar.component';
import { DashboardComponent } from './components/dashboard/dashboard.component';

import { AppRoute } from './app.routing';
import { RouterModule } from '@angular/router';
import { Service } from './Service/service';
import { ConfigService } from './Service/config.service';
import { HomeComponent } from './components/home/home.component';

@NgModule({
  declarations: [
    AppComponent,
    SideBarComponent,
    TopBarComponent,
    DashboardComponent,
    RoleManagementComponent,
    UserManagementComponent,
    UserListComponent,
    LoginComponent,
    HomeComponent,

  ],
  imports: [
    BrowserModule,
    FormsModule,
    ReactiveFormsModule,
    HttpModule,
    RouterModule.forRoot(AppRoute),
    SelectModule,
    Ng2Bs3ModalModule,
    MyDatePickerModule
  ],
  providers: [{ provide: LocationStrategy, useValue: '/AAA', useClass: HashLocationStrategy }, Service, ConfigService],
  bootstrap: [AppComponent]
})
export class AppModule { }
</code>```

App.Componenet.html: Modified

```<code> <div id="wrapper">
   <router-outlet></router-outlet>
 </div>
</code>```

Home.component.html Modified

```<code><app-top-bar></app-top-bar>
</code>```

app-top-bar contains top menu and side bar user menus. Its is static component.

Thanks in advance.

答:
In your App.Component.html :
change to this :
<router-outlet></router-outlet> so remove <app-top-bar></app-top-bar>

In App.Routing.ts :
change { path: '', redirectTo: 'HomeComponent', pathMatch: 'full' }

To:

```<code>{ path: '', component: LoginComponent},
{ path: 'dashboard', component: DashboardComponent,
          children: [
             { path: 'page1', component: Page1Component},
             { path: 'page2', component: Page2Component}
          ]
}
</code>```

In dashboard.component.html : (Home)

```<code><header-bar>
<side-bar>
<router-outlet></router-outlet>
</code>```

Title: Open Login component as Separate Page

Body:
I want to open login page in separate. But its opening in inside routeroutlet page. Please help.

PFB below screenshot for your reference.

Please refer my code below.

App.Routing.ts :

import { Routes } from '@angular/router';
import { DashboardComponent } from './components/dashboard/dashboard.component';
import { LoginComponent } from './components/login/login.component';
import { HomeComponent } from './components/home/home.component';

export const AppRoute: Routes = [
    { path: '', redirectTo: 'HomeComponent', pathMatch: 'full' },
    { path: 'login', component: LoginCoHomeComponentmponent },
    { path: 'home', component: HomeComponent },

];

App.Component.html

   <app-top-bar></app-top-bar>
   <router-outlet></router-outlet>

App.Module.ts

import { BrowserModule } from '@angular/platform-browser';
import { APP_BASE_HREF, LocationStrategy, HashLocationStrategy } from '@angular/common';
import { NgModule } from '@angular/core';
import { FormsModule, ReactiveFormsModule } from '@angular/forms';
import { HttpModule } from '@angular/http';
import { SelectModule } from 'ng2-select';
import { Ng2Bs3ModalModule } from 'ng2-bs3-modal/ng2-bs3-modal';

import { AppComponent } from './app.component';
import { SideBarComponent } from './components/side-bar/side-bar.component';
import { TopBarComponent } from './components/top-bar/top-bar.component';
import { DashboardComponent } from './components/dashboard/dashboard.component';

import { AppRoute } from './app.routing';
import { RouterModule } from '@angular/router';
import { Service } from './Service/service';
import { ConfigService } from './Service/config.service';
import { HomeComponent } from './components/home/home.component';

@NgModule({
  declarations: [
    AppComponent,
    SideBarComponent,
    TopBarComponent,
    DashboardComponent,
    RoleManagementComponent,
    UserManagementComponent,
    UserListComponent,
    LoginComponent,
    HomeComponent,

  ],
  imports: [
    BrowserModule,
    FormsModule,
    ReactiveFormsModule,
    HttpModule,
    RouterModule.forRoot(AppRoute),
    SelectModule,
    Ng2Bs3ModalModule,
    MyDatePickerModule
  ],
  providers: [{ provide: LocationStrategy, useValue: '/AAA', useClass: HashLocationStrategy }, Service, ConfigService],
  bootstrap: [AppComponent]
})
export class AppModule { }

App.Componenet.html: Modified

   <router-outlet></router-outlet>

Home.component.html Modified

<app-top-bar></app-top-bar>

app-top-bar contains top menu and side bar user menus. Its is static component.

Thanks in advance.

Body:
In your App.Component.html :
change to this :
<router-outlet></router-outlet> so remove <app-top-bar></app-top-bar>

In App.Routing.ts :
change { path: '', redirectTo: 'HomeComponent', pathMatch: 'full' }

To:

{ path: '', component: LoginComponent},
{ path: 'dashboard', component: DashboardComponent,
          children: [
             { path: 'page1', component: Page1Component},
             { path: 'page2', component: Page2Component}
          ]
}

In dashboard.component.html : (Home)

<header-bar>
<side-bar>
<router-outlet></router-outlet>


问:
index 1 is out of bounds for axis 0 with size 1 in matrix
So his code was for a 3xN dimensional matrix where the past present and future were the 3 rows. I have changed it to a one dimensional array for faster computation. where am I going wrong

```<code>psi_past_real = np.zeros((1,domain)) #  real part 3xN matrix
psi_past_imaginary = np.zeros((1,domain))
psi_present_real = np.zeros((1,domain))
psi_present_imaginary = np.zeros((1,domain))
psi_future_real = np.zeros((1,domain))
psi_future_imaginary = np.zeros((1,domain))
psi_probability = np.zeros(domain,)   # Probability

xn = range(1,domain/2)
x = X[xn]/dx    #  Normalized position coordinate
gg = Gaussian(x,x0,sigma)
cx = np.cos(k0*x)
sx = np.sin(k0*x)
psi_present_real[xn] = cx*gg
psi_present_imaginary[xn] = sx*gg
psi_past_real[xn] = cx*gg
psi_past_imaginary[xn] = sx*gg
</code>```

the gaussian function is

```<code>def Gaussian(x,t,sigma):
    np.exp(-(x-t)**2/(2*sigma**2))

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/Applications/Spyder 2.7.app/Contents/Resources/lib/python2.7/spyderlib/widgets/externalshell/sitecustomize.py", line 586, in runfile
    execfile(filename, namespace)
  File "/Users/kabirthakur/Desktop/untitled1.py", line 73, in <module>
    psi_present_real[xn] = cx*gg
IndexError: index 1 is out of bounds for axis 0 with size 1
</code>```

答:
The shape of psi_present_real is (1, domain). If you want to index it by the second coordinate, you need to indicate this by using a colon in the first coordinate:</p>

```<code>psi_present_real[:, xn] = cx*gg
</code>```

Body:
So his code was for a 3xN dimensional matrix where the past present and future were the 3 rows. I have changed it to a one dimensional array for faster computation. where am I going wrong

psi_past_real = np.zeros((1,domain)) #  real part 3xN matrix
psi_past_imaginary = np.zeros((1,domain))
psi_present_real = np.zeros((1,domain))
psi_present_imaginary = np.zeros((1,domain))
psi_future_real = np.zeros((1,domain))
psi_future_imaginary = np.zeros((1,domain))
psi_probability = np.zeros(domain,)   # Probability

xn = range(1,domain/2)
x = X[xn]/dx    #  Normalized position coordinate
gg = Gaussian(x,x0,sigma)
cx = np.cos(k0*x)
sx = np.sin(k0*x)
psi_present_real[xn] = cx*gg
psi_present_imaginary[xn] = sx*gg
psi_past_real[xn] = cx*gg
psi_past_imaginary[xn] = sx*gg

the gaussian function is

def Gaussian(x,t,sigma):
    np.exp(-(x-t)**2/(2*sigma**2))

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/Applications/Spyder 2.7.app/Contents/Resources/lib/python2.7/spyderlib/widgets/externalshell/sitecustomize.py", line 586, in runfile
    execfile(filename, namespace)
  File "/Users/kabirthakur/Desktop/untitled1.py", line 73, in <module>
    psi_present_real[xn] = cx*gg
IndexError: index 1 is out of bounds for axis 0 with size 1

Body:
The shape of psi_present_real is (1, domain). If you want to index it by the second coordinate, you need to indicate this by using a colon in the first coordinate:

psi_present_real[:, xn] = cx*gg


问:
Sending file descriptor over UNIX domain socket, and select()
I'm using a UNIX domain socket to transfer a file descriptor to another process. This works fine, but when I first try to see if socket is writeable using select(), the sendmsg() call fails with a Bad File Descriptor error.

The sendmsg() function does work fine in combination with select() if I don't add the file descriptor info to the msghdr struct, so the conflict seems to be between select() and transferring file descriptors.

I couldn't find any info on this in the man pages for select(), recvmsg(), or any other. Since this needs to become a server which hands out file descriptors to multiple processes, I'd still like to be able to use select().

Is there anything I can do to make this work, or does anyone know of alternative solutions?

Platform is Ubuntu 10.4.

This is the code that initializes the structures:

```<code>

struct cmsghdr_fd : public cmsghdr
{
  int fd;
};

int sendfd(int sock, int fd)
{
  struct msghdr hdr;
  struct iovec data;
  struct cmsghdr_fd msgdata;

  char dummy = '*';
  data.iov_base = &dummy;
  data.iov_len = sizeof(dummy);

  hdr.msg_name = NULL;
  hdr.msg_namelen = 0;
  hdr.msg_iov = &data;
  hdr.msg_iovlen = 1;
  hdr.msg_flags = 0;

  hdr.msg_control = &msgdata;
  hdr.msg_controllen = sizeof(msgdata);

  struct cmsghdr* cmsg = CMSG_FIRSTHDR(&hdr);
  cmsg->cmsg_len   = hdr.msg_controllen;
  cmsg->cmsg_level = SOL_SOCKET;
  cmsg->cmsg_type  = SCM_RIGHTS;

  *(int*)CMSG_DATA(cmsg) = fd;

  int n = sendmsg(sock, &hdr, 0);

  if(n == -1)
    printf("sendmsg() failed: %s (socket fd = %d)\n", strerror(errno), sock);

  return n;
}
</code>```

Again, this works, as long as I don't call select() first to check whether the socket is ready for writing.

答:
I tried the sendfd code at this page, which was kindly provided by nos, and even though it's only slightly different, it works even when I use it in combination with select(). This is what the code looks like now:</p>

```<code>

    int sendfd(int sock, int fd)
    {
      struct msghdr hdr;
      struct iovec data;

      char cmsgbuf[CMSG_SPACE(sizeof(int))];

      char dummy = '*';
      data.iov_base = &dummy;
      data.iov_len = sizeof(dummy);

      memset(&hdr, 0, sizeof(hdr));
      hdr.msg_name = NULL;
      hdr.msg_namelen = 0;
      hdr.msg_iov = &data;
      hdr.msg_iovlen = 1;
      hdr.msg_flags = 0;

      hdr.msg_control = cmsgbuf;
      hdr.msg_controllen = CMSG_LEN(sizeof(int));

      struct cmsghdr* cmsg = CMSG_FIRSTHDR(&hdr);
      cmsg->cmsg_len   = CMSG_LEN(sizeof(int));
      cmsg->cmsg_level = SOL_SOCKET;
      cmsg->cmsg_type  = SCM_RIGHTS;

      *(int*)CMSG_DATA(cmsg) = fd;

      int n = sendmsg(sock, &hdr, 0);

      if(n == -1)
        printf("sendmsg() failed: %s (socket fd = %d)\n", strerror(errno), sock);

      return n;
        }

</code>```

Body:
I'm using a UNIX domain socket to transfer a file descriptor to another process. This works fine, but when I first try to see if socket is writeable using select(), the sendmsg() call fails with a Bad File Descriptor error.

The sendmsg() function does work fine in combination with select() if I don't add the file descriptor info to the msghdr struct, so the conflict seems to be between select() and transferring file descriptors.

I couldn't find any info on this in the man pages for select(), recvmsg(), or any other. Since this needs to become a server which hands out file descriptors to multiple processes, I'd still like to be able to use select().

Is there anything I can do to make this work, or does anyone know of alternative solutions?

Platform is Ubuntu 10.4.

This is the code that initializes the structures:

struct cmsghdr_fd : public cmsghdr
{
  int fd;
};

int sendfd(int sock, int fd)
{
  struct msghdr hdr;
  struct iovec data;
  struct cmsghdr_fd msgdata;

  char dummy = '*';
  data.iov_base = &dummy;
  data.iov_len = sizeof(dummy);

  hdr.msg_name = NULL;
  hdr.msg_namelen = 0;
  hdr.msg_iov = &data;
  hdr.msg_iovlen = 1;
  hdr.msg_flags = 0;

  hdr.msg_control = &msgdata;
  hdr.msg_controllen = sizeof(msgdata);

  struct cmsghdr* cmsg = CMSG_FIRSTHDR(&hdr);
  cmsg->cmsg_len   = hdr.msg_controllen;
  cmsg->cmsg_level = SOL_SOCKET;
  cmsg->cmsg_type  = SCM_RIGHTS;

  *(int*)CMSG_DATA(cmsg) = fd;

  int n = sendmsg(sock, &hdr, 0);

  if(n == -1)
    printf("sendmsg() failed: %s (socket fd = %d)\n", strerror(errno), sock);

  return n;
}

Again, this works, as long as I don't call select() first to check whether the socket is ready for writing.

Body:
I tried the sendfd code at this page, which was kindly provided by nos, and even though it's only slightly different, it works even when I use it in combination with select(). This is what the code looks like now:

    int sendfd(int sock, int fd)
    {
      struct msghdr hdr;
      struct iovec data;

      char cmsgbuf[CMSG_SPACE(sizeof(int))];

      char dummy = '*';
      data.iov_base = &dummy;
      data.iov_len = sizeof(dummy);

      memset(&hdr, 0, sizeof(hdr));
      hdr.msg_name = NULL;
      hdr.msg_namelen = 0;
      hdr.msg_iov = &data;
      hdr.msg_iovlen = 1;
      hdr.msg_flags = 0;

      hdr.msg_control = cmsgbuf;
      hdr.msg_controllen = CMSG_LEN(sizeof(int));

      struct cmsghdr* cmsg = CMSG_FIRSTHDR(&hdr);
      cmsg->cmsg_len   = CMSG_LEN(sizeof(int));
      cmsg->cmsg_level = SOL_SOCKET;
      cmsg->cmsg_type  = SCM_RIGHTS;

      *(int*)CMSG_DATA(cmsg) = fd;

      int n = sendmsg(sock, &hdr, 0);

      if(n == -1)
        printf("sendmsg() failed: %s (socket fd = %d)\n", strerror(errno), sock);

      return n;
        }


问:
Getting and removing a part of a string by first and last occurance of character
I have a string like this:

```<code>{something:something}Some data will be here
</code>```

Heres how its setup:

```<code>{username:password}data
</code>```

How can I get the {username:password} part and remove it from the full string? I need to check the username and password then send the data (everything after {something:something}) to the user.

Preferably I would like to get the username:password without the {} so I can just split by :

答:
Here is a regex solution :</p>

```<code>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            string input = "{something:something}Some data will be here";

            string pattern = @"\{(?'username'[^:]+):(?'password'[^\}]+)\}(?'data'.*)";

            Match match = Regex.Match(input,pattern);

            Console.WriteLine("Username : '{0}', Password : '{1}', Data : '{2}'",
                match.Groups["username"].Value, match.Groups["password"].Value, match.Groups["data"].Value);
           Console.ReadLine();
        }
    }
}
</code>```

Body:
I have a string like this:

{something:something}Some data will be here

Heres how its setup:

{username:password}data

How can I get the {username:password} part and remove it from the full string? I need to check the username and password then send the data (everything after {something:something}) to the user.

Preferably I would like to get the username:password without the {} so I can just split by :

Body:
Here is a regex solution :

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            string input = "{something:something}Some data will be here";

            string pattern = @"\{(?'username'[^:]+):(?'password'[^\}]+)\}(?'data'.*)";

            Match match = Regex.Match(input,pattern);

            Console.WriteLine("Username : '{0}', Password : '{1}', Data : '{2}'",
                match.Groups["username"].Value, match.Groups["password"].Value, match.Groups["data"].Value);
           Console.ReadLine();
        }
    }
}


问:
SSRS 2016 Webservice LoadReport : The item cannot be found
SSRS report does not load when attempt to call via ReportService2005.asmx. Stacktrace below received even though it seems thatthe path is valid. We don't have this issue on a 2014 SsRS box. Any help appreciated?

System.Web.Services.Protocols.S
oapException: The item '/ZambaReportsBLU/FORMALQUOTATION' cannot be found. ---> M
icrosoft.ReportingServices.Diagnostics.Utilities.ItemNotFoundException: The item
 '/ZambaReportsBLU/FORMALQUOTATION' cannot be found.
   at Microsoft.ReportingServices.Library.ReportExecution2005Impl.LoadReport(Str
ing Report, String HistoryID, ExecutionInfo2& executionInfo)
   at Microsoft.ReportingServices.WebServer.ReportExecutionService.LoadReport(St
ring Report, String HistoryID, ExecutionInfo& executionInfo)
System.Web.Services.Protocols.SoapException: System.Web.Services.Protocols.SoapE
xception: The item '/ZambaReportsBLU/FORMALQUOTATION' cannot be found. ---> Micro
soft.ReportingServices.Diagnostics.Utilities.ItemNotFoundException: The item '/ZambaReportsBLU/FORMALQUOTATION' cannot be found.
   at Microsoft.ReportingServices.Library.ReportExecution2005Impl.LoadReport(Str
ing Report, String HistoryID, ExecutionInfo2& executionInfo)
   at Microsoft.ReportingServices.WebServer.ReportExecutionService.LoadReport(St
ring Report, String HistoryID, ExecutionInfo& executionInfo)
   at System.Web.Services.Protocols.SoapHttpClientProtocol.ReadResponse(SoapClie
ntMessage message, WebResponse response, Stream responseStream, Boolean asyncCal
l)
   at System.Web.Services.Protocols.SoapHttpClientProtocol.Invoke(String methodN
ame, Object[] parameters)

答: We installed a different instance of SSRS and this solved the problem. Not sure what the issue was really</p>


答:
If your goal is to merge two arrays, here is the ES6 way:

```<code>const arr1 = ['a', 'b', 'c'];
const arr2 = ['d', 'e', 'f'];

const arr3 = [...arr1, ...arr2]; // Output: [ "a", "b", "c", "d", "e", "f" ]
</code>```

But, in your case (after your edit), you want to do more!

```<code>const arr1 = [ "I", "You", "He", "She" ];
const arr2 = [ "am", "is", "are" ];

arr2.map(eltB => arr1.map(eltA => `${eltA} ${eltB}`))
    .reduce((newArray, arr) => newArray.concat(arr), []);
</code>```

Title: Combine 2 arrays into 1 in all possible ways in JavaScript

Body:
If your goal is to merge two arrays, here is the ES6 way:

const arr1 = ['a', 'b', 'c'];
const arr2 = ['d', 'e', 'f'];

const arr3 = [...arr1, ...arr2]; // Output: [ "a", "b", "c", "d", "e", "f" ]

But, in your case (after your edit), you want to do more!

const arr1 = [ "I", "You", "He", "She" ];
const arr2 = [ "am", "is", "are" ];

arr2.map(eltB => arr1.map(eltA => `${eltA} ${eltB}`))
    .reduce((newArray, arr) => newArray.concat(arr), []);