问:
Superscript and Subscript in android
I want to get the superscript and subscript in textview in android. I have used the sup tag but still there is no effect.
Please tell me what's the problem since it was suggested on stackoverflow.</p>

答:
Try this way it will work for you

```<code>public class MainActivity extends AppCompatActivity {
    private Context mContext;
    private Activity mActivity;

    private CoordinatorLayout mCLayout;
    private TextView mTextView;

    private String mText;
    private SpannableStringBuilder mSSBuilder;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        // Get the application context
        mContext = getApplicationContext();
        mActivity = MainActivity.this;

        // Get the widget reference from XML layout
        mCLayout = (CoordinatorLayout) findViewById(R.id.coordinator_layout);
        mTextView = (TextView) findViewById(R.id.tv);

        // Initialize a new String variable
        mText = "Test text to show SubscriptSpan X2 and SuperscriptSpan Y5 example.";

        // Initialize a new SpannableStringBuilder instance
        mSSBuilder = new SpannableStringBuilder(mText);

        // Initialize a new SubscriptSpan instance
        SubscriptSpan subscriptSpan = new SubscriptSpan();

        // Initialize a new SuperscriptSpan instance
        SuperscriptSpan superscriptSpan = new SuperscriptSpan();

        // Apply the SubscriptSpan
        mSSBuilder.setSpan(
                subscriptSpan, // Span to add
                mText.indexOf("2"), // Start of the span (inclusive)
                mText.indexOf("2") + String.valueOf("2").length(), // End of the span (exclusive)
                Spanned.SPAN_EXCLUSIVE_EXCLUSIVE // Do not extend the span when text add later
        );

        // Apply the SuperscriptSpan
        mSSBuilder.setSpan(
                superscriptSpan,
                mText.indexOf("5"),
                mText.indexOf("5") + String.valueOf("5").length(),
                Spanned.SPAN_EXCLUSIVE_EXCLUSIVE
        );

        // Minimize the Subscript and Superscript text size
        showSmallSizeText("2");
        showSmallSizeText("5");

        // Display the spannable text to TextView
        mTextView.setText(mSSBuilder);
    }

    // Custom method to make text size small
    protected void showSmallSizeText(String textToSmall){
        // Initialize a new RelativeSizeSpan instance
        RelativeSizeSpan relativeSizeSpan = new RelativeSizeSpan(.5f);

        // Apply the RelativeSizeSpan to display small text
        mSSBuilder.setSpan(
                relativeSizeSpan,
                mText.indexOf(textToSmall),
                mText.indexOf(textToSmall) + String.valueOf(textToSmall).length(),
                Spanned.SPAN_EXCLUSIVE_EXCLUSIVE
        );
    }
}
</code>```

http://www.android--tutorials.com/2016/08/android-subscript-and-superscript.html

https://thinkandroid.wordpress.com/2009/12/28/quickly-add-superscript-subscript/

Title: Superscript and Subscript in android

Body:
Try this way it will work for you

public class MainActivity extends AppCompatActivity {
    private Context mContext;
    private Activity mActivity;

    private CoordinatorLayout mCLayout;
    private TextView mTextView;

    private String mText;
    private SpannableStringBuilder mSSBuilder;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        // Get the application context
        mContext = getApplicationContext();
        mActivity = MainActivity.this;

        // Get the widget reference from XML layout
        mCLayout = (CoordinatorLayout) findViewById(R.id.coordinator_layout);
        mTextView = (TextView) findViewById(R.id.tv);

        // Initialize a new String variable
        mText = "Test text to show SubscriptSpan X2 and SuperscriptSpan Y5 example.";

        // Initialize a new SpannableStringBuilder instance
        mSSBuilder = new SpannableStringBuilder(mText);

        // Initialize a new SubscriptSpan instance
        SubscriptSpan subscriptSpan = new SubscriptSpan();

        // Initialize a new SuperscriptSpan instance
        SuperscriptSpan superscriptSpan = new SuperscriptSpan();

        // Apply the SubscriptSpan
        mSSBuilder.setSpan(
                subscriptSpan, // Span to add
                mText.indexOf("2"), // Start of the span (inclusive)
                mText.indexOf("2") + String.valueOf("2").length(), // End of the span (exclusive)
                Spanned.SPAN_EXCLUSIVE_EXCLUSIVE // Do not extend the span when text add later
        );

        // Apply the SuperscriptSpan
        mSSBuilder.setSpan(
                superscriptSpan,
                mText.indexOf("5"),
                mText.indexOf("5") + String.valueOf("5").length(),
                Spanned.SPAN_EXCLUSIVE_EXCLUSIVE
        );

        // Minimize the Subscript and Superscript text size
        showSmallSizeText("2");
        showSmallSizeText("5");

        // Display the spannable text to TextView
        mTextView.setText(mSSBuilder);
    }

    // Custom method to make text size small
    protected void showSmallSizeText(String textToSmall){
        // Initialize a new RelativeSizeSpan instance
        RelativeSizeSpan relativeSizeSpan = new RelativeSizeSpan(.5f);

        // Apply the RelativeSizeSpan to display small text
        mSSBuilder.setSpan(
                relativeSizeSpan,
                mText.indexOf(textToSmall),
                mText.indexOf(textToSmall) + String.valueOf(textToSmall).length(),
                Spanned.SPAN_EXCLUSIVE_EXCLUSIVE
        );
    }
}

http://www.android--tutorials.com/2016/08/android-subscript-and-superscript.html

https://thinkandroid.wordpress.com/2009/12/28/quickly-add-superscript-subscript/


来源: stackexchange

问:
OpenCV python video capture Error(-215) size.width>0 && size.height>0
```<code>import cv2
import numpy as np

cap = cv2.VideoCapture(0)

while True:
    ret,frame = cap.read()
    cv2.imshow('frame',frame)
    k = cv2.waitKEy(10) & 0xff
    if k == 27:
        break

cap.release()
cv2.destroyAllWindows()
</code>```

Hi all I'm a beginner and I'm just trying to video capture using opencv but I'm just confused because I get:

error(-215) size.width>0 && size.height>0 in function imshow

and I cant find whats exactly wrong with it. Any help is greatly appreciated.

My exact error is

```<code>Traceback (most recent call last):
File "/home/pi/Desktop/videocapture.py", line 8,in <module>
  cv2.imshow('frame',frame)
Error: /home/pi/opencv-3.0.0/modules/highgui/src/window.cpp:271: error: (-215) size.width>0 && size.height>0 in function imshow
</code>```

And I tried a few other ways as well but and sometimes I will get scn == 3||scn == 4

答: i got the same problem when i first processed image,and i guess if the problem of python3 and then same problem came when turn to python2.7.Last,trying to use absolute image path replace relative path,fortunately, it works.

ContentLicense: CC BY-SA 3.0

Body:
import cv2
import numpy as np

cap = cv2.VideoCapture(0)

while True:
    ret,frame = cap.read()
    cv2.imshow('frame',frame)
    k = cv2.waitKEy(10) & 0xff
    if k == 27:
        break

cap.release()
cv2.destroyAllWindows()

Hi all I'm a beginner and I'm just trying to video capture using opencv but I'm just confused because I get:

error(-215) size.width>0 && size.height>0 in function imshow

and I cant find whats exactly wrong with it. Any help is greatly appreciated.

My exact error is

Traceback (most recent call last):
File "/home/pi/Desktop/videocapture.py", line 8,in <module>
  cv2.imshow('frame',frame)
Error: /home/pi/opencv-3.0.0/modules/highgui/src/window.cpp:271: error: (-215) size.width>0 && size.height>0 in function imshow

And I tried a few other ways as well but and sometimes I will get scn == 3||scn == 4


答:
You can use this, here the R.id.text is the ID of your textView

```<code>TextView tv = (TextView) findViewById(R.id.text);
tv.setText(Html.fromHtml("X<sup>2</sup>")); //for SuperScript

tv.setText(Html.fromHtml("X<sub>2</sub>")); //for SubScript
</code>```

Title: Superscript and Subscript in android

Body:
I want to get the superscript and subscript in textview in android. I have used the sup tag but still there is no effect.
Please tell me what's the problem since it was suggested on stackoverflow.

Body:
You can use this, here the R.id.text is the ID of your textView

TextView tv = (TextView) findViewById(R.id.text);
tv.setText(Html.fromHtml("X<sup>2</sup>")); //for SuperScript

tv.setText(Html.fromHtml("X<sub>2</sub>")); //for SubScript


问:
why does the method invoke() in InvocationHandler have an parameter Object proxy?
When you r checking out that the method invoke(Object proxy, Method method, Object[] args) declaration & the doc statement,you will find that the input parameter proxy

proxy - the proxy instance that the method was invoked on

when I am doing a test on java dynamic proxy,I find this proxy is produced by vm.So I do want to know why the method invoke has this param,which is surely nothing except that is just an object ($proxy0 )but don't have the actual action for our usage?

答: This very useful if you have single invocation handle for multiple proxy objects. So you can use hash map to store proxy states information. For example - Mokito test framework store proxy invocation history.</p>

ContentLicense: CC BY-SA 2.5


问:
In Node.js, res.render is returning a 404 error on router.get
I'm building my first Node application and having some trouble displaying the page that I want with a GET request. I have installed ejs (opinions welcome on that!) so my understanding is that I do not need to define the 'views' folder. Here is my routes file so far:

```<code>const express = require('express');
const router = express.Router();
const Event = require('../models/event')

router.get('/'), function(req, res, next){
   /* Event.find({}).then(function(events){
       res.send(events);
   });
    });*/
    res.render('../../index');
 };

router.post('/events', (req, res) => {
    Event.create(req.body);
    res.send({type: POST})
});

module.exports = router;
</code>```

The database is connecting just fine, which I can see with the code that I have commented out in the get request. But for some reason I can't render my index file. My file structure is as follows:

File tree:

So I need to go up two levels, correct? I tried index, index.ejs, ../index, views/index, nothing has worked. What am I doing wrong?

EDIT: this is my server.js:

```<code>const express = require('express');
const app = express();
const bodyParser = require('body-parser');
const mongoose = require('mongoose');
const routes = require('./routes/index');
var path = require("path");

app.set('view engine', 'ejs');
app.set('views', path.join(__dirname, 'views'));

app.use(bodyParser.json());
app.use(express.static('public'));
app.use(routes);
app.use(bodyParser.urlencoded({extended: true}))

mongoose.connect('mongodb://junk:junk@ds141242.mlab.com:41242/alaska-events');

app.listen(3000, () => {
    console.log('listening on 3000')
  });
</code>```

答:
views folder is placed directly in root folder, and using we app.set('views', path.join(__dirname, 'views')); point it to views folder. So in render directly mention the view name. </p>

```<code>router.get('/', function(req, res, next){
   res.render('index');
});
</code>```

Body:
I'm building my first Node application and having some trouble displaying the page that I want with a GET request. I have installed ejs (opinions welcome on that!) so my understanding is that I do not need to define the 'views' folder. Here is my routes file so far:

const express = require('express');
const router = express.Router();
const Event = require('../models/event')

router.get('/'), function(req, res, next){
   /* Event.find({}).then(function(events){
       res.send(events);
   });
    });*/
    res.render('../../index');
 };

router.post('/events', (req, res) => {
    Event.create(req.body);
    res.send({type: POST})
});

module.exports = router;

The database is connecting just fine, which I can see with the code that I have commented out in the get request. But for some reason I can't render my index file. My file structure is as follows:

File tree:

So I need to go up two levels, correct? I tried index, index.ejs, ../index, views/index, nothing has worked. What am I doing wrong?

EDIT: this is my server.js:

const express = require('express');
const app = express();
const bodyParser = require('body-parser');
const mongoose = require('mongoose');
const routes = require('./routes/index');
var path = require("path");

app.set('view engine', 'ejs');
app.set('views', path.join(__dirname, 'views'));

app.use(bodyParser.json());
app.use(express.static('public'));
app.use(routes);
app.use(bodyParser.urlencoded({extended: true}))

mongoose.connect('mongodb://junk:junk@ds141242.mlab.com:41242/alaska-events');

app.listen(3000, () => {
    console.log('listening on 3000')
  });

Body:
views folder is placed directly in root folder, and using we app.set('views', path.join(__dirname, 'views')); point it to views folder. So in render directly mention the view name.

router.get('/', function(req, res, next){
   res.render('index');
});


问:
Communication of two taskpanes
I am making an Office add-in which has two ribbon buttons. Each button is linked to a different TaskpaneId, and clicking on each button opens a different taskpane:

```<code><bt:Urls>
    <bt:Url id="Contoso.Taskpane1.Url" DefaultValue="https://localhost:3000/addin/page1" />
    <bt:Url id="Contoso.Taskpane2.Url" DefaultValue="https://localhost:3000/addin/page2" />
</bt:Urls>
</code>```

Now, I want to realise some communication between these two pages. For example, after some manipulations on page1, I want page2 to be automatically refreshed (to reload data from server or localStorage). As a result, when we click on page2, it is already up-to-date. At the moment, it is not systematically updated, and to refresh page2, we have to click on its ribbon button.

https://localhost:3000/ is built with mean-stack, so the pages use angularjs and have a server behind. One way of communication of two pages is to via server: page1 sends a message by socket.io to the server, and then the server emits a message by socket.io to page2. It is a little bit tedious.

Does anyone know if JavaScript API for Office has already any easy (and cross-platform) way to permit of such a communication between 2 taskpanes?

PS: using StorageEvent of localStorage is not a good idea, because it does not seem to work in Excel for Mac or for Windows.

答: There is no great solution at the moment. For Script Lab, we use local storage and a timer to check a time stamp a couple times a second on platforms/browsers that don't support events (IE 11).  The problem with local storage isn't so much the need for timers, but rather that you can't really scope it to just a particular set of task panes. Instead, it ends up impacting task panes on other documents as well.  For script lab, we decided to live with that behavior, instead of spending the energy on a server-based communication (I assume you mean socket.io or similar?)</p>

Title: Communication of two taskpanes

Body:
I am making an Office add-in which has two ribbon buttons. Each button is linked to a different TaskpaneId, and clicking on each button opens a different taskpane:

<bt:Urls>
    <bt:Url id="Contoso.Taskpane1.Url" DefaultValue="https://localhost:3000/addin/page1" />
    <bt:Url id="Contoso.Taskpane2.Url" DefaultValue="https://localhost:3000/addin/page2" />
</bt:Urls>

Now, I want to realise some communication between these two pages. For example, after some manipulations on page1, I want page2 to be automatically refreshed (to reload data from server or localStorage). As a result, when we click on page2, it is already up-to-date. At the moment, it is not systematically updated, and to refresh page2, we have to click on its ribbon button.

https://localhost:3000/ is built with mean-stack, so the pages use angularjs and have a server behind. One way of communication of two pages is to via server: page1 sends a message by socket.io to the server, and then the server emits a message by socket.io to page2. It is a little bit tedious.

Does anyone know if JavaScript API for Office has already any easy (and cross-platform) way to permit of such a communication between 2 taskpanes?

PS: using StorageEvent of localStorage is not a good idea, because it does not seem to work in Excel for Mac or for Windows.


问:
About pandas datareader
When I try to import pandas datareader, it throws me an error.

I tried following pattern because some one said it should be underscore pandas_datareader when you import it.

Please help.

Package

```<code>PS C:\Users\cris\Anaconda3> conda list | Select-String "pandas-datareader"

pandas-datareader         0.4.0                    py36_0

PS C:\Users\cris\Anaconda3>
</code>```

Python

```<code>>>> import pandas_datareader.data as web
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ModuleNotFoundError: No module named 'pandas_datareader'
>>>
>>> import pandas-datareader.data as web
  File "<stdin>", line 1
    import pandas-datareader.data as web
                 ^
SyntaxError: invalid syntax
>>>
>>> import pandas-datareader-0.4.0.data as web
  File "<stdin>", line 1
    import pandas-datareader-0.4.0.data as web
                 ^
SyntaxError: invalid syntax
>>>
</code>```

Title: About pandas datareader

Body:
When I try to import pandas datareader, it throws me an error.

I tried following pattern because some one said it should be underscore pandas_datareader when you import it.

Please help.

Package

PS C:\Users\cris\Anaconda3> conda list | Select-String "pandas-datareader"

pandas-datareader         0.4.0                    py36_0

PS C:\Users\cris\Anaconda3>

Python

>>> import pandas_datareader.data as web
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ModuleNotFoundError: No module named 'pandas_datareader'
>>>
>>> import pandas-datareader.data as web
  File "<stdin>", line 1
    import pandas-datareader.data as web
                 ^
SyntaxError: invalid syntax
>>>
>>> import pandas-datareader-0.4.0.data as web
  File "<stdin>", line 1
    import pandas-datareader-0.4.0.data as web
                 ^
SyntaxError: invalid syntax
>>>

Body:
import pandas_datareader as web

web.__version__

Output:

'0.4.0'

df = web.DataReader('MSFT','google')
df.head()

Output:

             Open   High    Low  Close    Volume
Date
2010-01-04  30.62  31.10  30.59  30.95  38414185
2010-01-05  30.85  31.10  30.64  30.96  49758862
2010-01-06  30.88  31.08  30.52  30.77  58182332
2010-01-07  30.63  30.70  30.19  30.45  50564285
2010-01-08  30.28  30.88  30.24  30.66  51201289


问:
Get filtered count of elements in array from $lookup along with the whole document
I have this query in MongoDB:

```<code>db.emailGroup.aggregate([
    {
        "$lookup":
        {
            "from": "link",
            "localField": "_id",
            "foreignField": "emailGroupId",
            "as": "link"
        },
    },
    {
        "$unwind": "$link"
    },
    {
        "$match": {
             'link.originalLink': ""
        }
    },
    {
        "$group" : {
            _id: '$_id',
            link: {
                $push: '$link'
            }
        }
    },
    {
        "$project": {
            "size": {
                "$sum": {
                    "$map": {
                        "input": "$link",
                        "as": "l",
                        "in": {
                            "$size": {
                                "$ifNull": [
                                    "$$l.linkHistory", []
                                ]
                            }
                        }
                    }
                }
            }
        }
    }
])
</code>```

EmailGroup has partId field. I use $lookup to "join" other collection for sum her fields. I need group by partId field and sum custom field "size" for partId groups. Is this possible? Extra question: How can I add emailGroup fields to query result?

Sample documents:

emailGroup:

```<code>{
    "_id" : ObjectId("594a6c47f51e075db713ccb6"),
    "partId" : "f56c7c71eb14a20e6129a667872f9c4f",
}
</code>```

link:

```<code>{
    "_id" : ObjectId("594b96d6f51e075db67c44c9"),
    "originalLink" : "",
    "emailGroupId" : ObjectId("594a6c47f51e075db713ccb6"),
    "linkHistory" : [
        {
            "_id" : ObjectId("594b96f5f51e075db713ccdf"),
        },
        {
            "_id" : ObjectId("594b971bf51e075db67c44ca"),
        }
    ]
}
</code>```

答:
Annotation for those looking for - Foreign Count

A bit better than was originally answered is to actually use the newer form of $lookup from MongoDB 3.6. This can actually do the "counting" within the "sub-pipeline" expression as opposed to returning an "array" for subsequent filtering and counting or even using $unwind

```<code>db.emailGroup.aggregate([
  { "$lookup": {
    "from": "link",
    "let": { "id": "$_id" },
    "pipeline": [
      { "$match": {
        "originalLink": "",
        "$expr": { "$eq": [ "$$id", "$_id" ] }
      }},
      { "$count": "count" }
    ],
    "as": "linkCount"
  }},
  { "$addFields": {
    "linkCount": { "$sum": "$linkCount.count" }
  }}
])
</code>```

Not what the original question was asking for but part of the below answer in the now most optimal form, as of course the result of $lookup is reduced to the "matched count" only instead of "all matched documents".

Original

The correct way to do this would be to add the "linkCount" to the $group stage as well as a $first on any additional fields of the parent document in order to get the "singular" form as was the state "before" the $unwind was processed on the array that was the result of $lookup:

All Detail

```<code>db.emailGroup.aggregate([
  { "$lookup": {
    "from": "link",
    "localField": "_id",
    "foreignField": "emailGroupId",
    "as": "link"
  }},
  { "$unwind": "$link" },
  { "$match": { "link.originalLink": "" } },
  { "$group": {
    "_id": "$_id",
    "partId": { "$first": "$partId" },
    "link": { "$push": "$link" },
    "linkCount": {
      "$sum": {
        "$size": {
          "$ifNull": [ "$link.linkHistory", [] ]
        }
      }
    }
  }}
])
</code>```

Produces:

```<code>{
    "_id" : ObjectId("594a6c47f51e075db713ccb6"),
    "partId" : "f56c7c71eb14a20e6129a667872f9c4f",
    "link" : [
        {
            "_id" : ObjectId("594b96d6f51e075db67c44c9"),
            "originalLink" : "",
            "emailGroupId" : ObjectId("594a6c47f51e075db713ccb6"),
            "linkHistory" : [
                {
                    "_id" : ObjectId("594b96f5f51e075db713ccdf")
                },
                {
                    "_id" : ObjectId("594b971bf51e075db67c44ca")
                }
            ]
        }
    ],
    "linkCount" : 2
}
</code>```

Group By partId

```<code>db.emailGroup.aggregate([
  { "$lookup": {
    "from": "link",
    "localField": "_id",
    "foreignField": "emailGroupId",
    "as": "link"
  }},
  { "$unwind": "$link" },
  { "$match": { "link.originalLink": "" } },
  { "$group": {
    "_id": "$partId",
    "linkCount": {
      "$sum": {
        "$size": {
          "$ifNull": [ "$link.linkHistory", [] ]
        }
      }
    }
  }}
])
</code>```

Produces

```<code>{
    "_id" : "f56c7c71eb14a20e6129a667872f9c4f",
    "linkCount" : 2
}
</code>```

The reason you do it this way with a $unwind and then a $match is because of how MongoDB actually handles the pipeline when issued in that order. This is what happens to the $lookup as is demonstrated the the "explain" output from the operation:

```<code>    {
        "$lookup" : {
            "from" : "link",
            "as" : "link",
            "localField" : "_id",
            "foreignField" : "emailGroupId",
            "unwinding" : {
                "preserveNullAndEmptyArrays" : false
            },
            "matching" : {
                "originalLink" : {
                    "$eq" : ""
                }
            }
        }
    },
    {
        "$group" : {
</code>```

I'm leaving the part with $group in that output to demonstrate that the other two pipeline stages "disappear". This is because they have been "rolled-up" into the $lookup pipeline stage as shown. This is in fact how MongoDB deals with the possibility that the BSON Limit can be exceeded by the result of "joining" results of $lookup into an array of the parent document.

You can alternately write the operation like this:

All Detail

```<code>db.emailGroup.aggregate([
  { "$lookup": {
    "from": "link",
    "localField": "_id",
    "foreignField": "emailGroupId",
    "as": "link"
  }},
  { "$addFields": {
    "link": {
      "$filter": {
        "input": "$link",
        "as": "l",
        "cond": { "$eq": [ "$$l.originalLink", "" ] }
      }
    },
    "linkCount": {
      "$sum": {
        "$map": {
          "input": {
            "$filter": {
              "input": "$link",
              "as": "l",
              "cond": { "$eq": [ "$$l.originalLink", "" ] }
            }
          },
          "as": "l",
          "in": { "$size": { "$ifNull": [ "$$l.linkHistory", [] ] } }
        }
      }
    }
  }}
])
</code>```

Group by partId

```<code>db.emailGroup.aggregate([
  { "$lookup": {
    "from": "link",
    "localField": "_id",
    "foreignField": "emailGroupId",
    "as": "link"
  }},
  { "$addFields": {
    "link": {
      "$filter": {
        "input": "$link",
        "as": "l",
        "cond": { "$eq": [ "$$l.originalLink", "" ] }
      }
    },
    "linkCount": {
      "$sum": {
        "$map": {
          "input": {
            "$filter": {
              "input": "$link",
              "as": "l",
              "cond": { "$eq": [ "$$l.originalLink", "" ] }
            }
          },
          "as": "l",
          "in": { "$size": { "$ifNull": [ "$$l.linkHistory", [] ] } }
        }
      }
    }
  }},
  { "$unwind": "$link" },
  { "$group": {
    "_id": "$partId",
    "linkCount": { "$sum": "$linkCount" }
  }}
])
</code>```

Which has the same output but "differs" from the first query in that the $filter here is applied "after" ALL results of the $lookup are returned into the new array of the parent document.

So in performance terms, it is actually more effective to do it the first way as well as being portable to possible large result sets "before filtering" which would otherwise break the 16MB BSON Limit.

Note: If you do not have $addFields available (added with MongoDB 3.4) then use $project and specify "ALL" of the fields you wish to return.

As a side-note for those who are interested, in future releases of MongoDB ( presumably 3.6 and up ) you can use $replaceRoot instead of an $addFields with usage of the new $mergeObjects pipeline operator. The advantage of this is as a "block", we can declare the "filtered" content as a variable via $let, which means you do not need to write the same $filter "twice":

```<code>db.emailGroup.aggregate([
  { "$lookup": {
    "from": "link",
    "localField": "_id",
    "foreignField": "emailGroupId",
    "as": "link"
  }},
  { "$replaceRoot": {
    "newRoot": {
      "$mergeObjects": [
        "$$ROOT",
        { "$let": {
          "vars": {
            "filtered": {
              "$filter": {
                "input": "$link",
                "as": "l",
                "cond": { "$eq": [ "$$l.originalLink", "" ] }
              }
            }
          },
          "in": {
            "link": "$$filtered",
            "linkCount": {
              "$sum": {
                "$map": {
                  "input": "$$filtered.linkHistory",
                  "as": "lh",
                  "in": { "$size": { "$ifNull": [ "$$lh", [] ] } }
                }
              }
            }
          }
        }}
      ]
    }
  }}
])
</code>```

Nonetheless the best way to do such "filtered" $lookup operations is "still" at this time using the $unwind then $match pattern, until such time as you can provide query arguments to $lookup directly.

Note: By "directly" here I do not mean the "non-correlated" form of $lookup which should also be in the MongoDB 3.6 release, as this would indeed issue another "pipeline" execution for each document in the parent collection. So that feature still does not replace the present "best effective" way of retrieving only the matched items.

Body:
I have this query in MongoDB:

db.emailGroup.aggregate([
    {
        "$lookup":
        {
            "from": "link",
            "localField": "_id",
            "foreignField": "emailGroupId",
            "as": "link"
        },
    },
    {
        "$unwind": "$link"
    },
    {
        "$match": {
             'link.originalLink': ""
        }
    },
    {
        "$group" : {
            _id: '$_id',
            link: {
                $push: '$link'
            }
        }
    },
    {
        "$project": {
            "size": {
                "$sum": {
                    "$map": {
                        "input": "$link",
                        "as": "l",
                        "in": {
                            "$size": {
                                "$ifNull": [
                                    "$$l.linkHistory", []
                                ]
                            }
                        }
                    }
                }
            }
        }
    }
])

EmailGroup has partId field. I use $lookup to "join" other collection for sum her fields. I need group by partId field and sum custom field "size" for partId groups. Is this possible? Extra question: How can I add emailGroup fields to query result?

Sample documents:

emailGroup:

{
    "_id" : ObjectId("594a6c47f51e075db713ccb6"),
    "partId" : "f56c7c71eb14a20e6129a667872f9c4f",
}

link:

{
    "_id" : ObjectId("594b96d6f51e075db67c44c9"),
    "originalLink" : "",
    "emailGroupId" : ObjectId("594a6c47f51e075db713ccb6"),
    "linkHistory" : [
        {
            "_id" : ObjectId("594b96f5f51e075db713ccdf"),
        },
        {
            "_id" : ObjectId("594b971bf51e075db67c44ca"),
        }
    ]
}

Body:
Annotation for those looking for - Foreign Count

A bit better than was originally answered is to actually use the newer form of $lookup from MongoDB 3.6. This can actually do the "counting" within the "sub-pipeline" expression as opposed to returning an "array" for subsequent filtering and counting or even using $unwind

db.emailGroup.aggregate([
  { "$lookup": {
    "from": "link",
    "let": { "id": "$_id" },
    "pipeline": [
      { "$match": {
        "originalLink": "",
        "$expr": { "$eq": [ "$$id", "$_id" ] }
      }},
      { "$count": "count" }
    ],
    "as": "linkCount"
  }},
  { "$addFields": {
    "linkCount": { "$sum": "$linkCount.count" }
  }}
])

Not what the original question was asking for but part of the below answer in the now most optimal form, as of course the result of $lookup is reduced to the "matched count" only instead of "all matched documents".

Original

The correct way to do this would be to add the "linkCount" to the $group stage as well as a $first on any additional fields of the parent document in order to get the "singular" form as was the state "before" the $unwind was processed on the array that was the result of $lookup:

All Detail

db.emailGroup.aggregate([
  { "$lookup": {
    "from": "link",
    "localField": "_id",
    "foreignField": "emailGroupId",
    "as": "link"
  }},
  { "$unwind": "$link" },
  { "$match": { "link.originalLink": "" } },
  { "$group": {
    "_id": "$_id",
    "partId": { "$first": "$partId" },
    "link": { "$push": "$link" },
    "linkCount": {
      "$sum": {
        "$size": {
          "$ifNull": [ "$link.linkHistory", [] ]
        }
      }
    }
  }}
])

Produces:

{
    "_id" : ObjectId("594a6c47f51e075db713ccb6"),
    "partId" : "f56c7c71eb14a20e6129a667872f9c4f",
    "link" : [
        {
            "_id" : ObjectId("594b96d6f51e075db67c44c9"),
            "originalLink" : "",
            "emailGroupId" : ObjectId("594a6c47f51e075db713ccb6"),
            "linkHistory" : [
                {
                    "_id" : ObjectId("594b96f5f51e075db713ccdf")
                },
                {
                    "_id" : ObjectId("594b971bf51e075db67c44ca")
                }
            ]
        }
    ],
    "linkCount" : 2
}

Group By partId

db.emailGroup.aggregate([
  { "$lookup": {
    "from": "link",
    "localField": "_id",
    "foreignField": "emailGroupId",
    "as": "link"
  }},
  { "$unwind": "$link" },
  { "$match": { "link.originalLink": "" } },
  { "$group": {
    "_id": "$partId",
    "linkCount": {
      "$sum": {
        "$size": {
          "$ifNull": [ "$link.linkHistory", [] ]
        }
      }
    }
  }}
])

Produces

{
    "_id" : "f56c7c71eb14a20e6129a667872f9c4f",
    "linkCount" : 2
}

The reason you do it this way with a $unwind and then a $match is because of how MongoDB actually handles the pipeline when issued in that order. This is what happens to the $lookup as is demonstrated the the "explain" output from the operation:

    {
        "$lookup" : {
            "from" : "link",
            "as" : "link",
            "localField" : "_id",
            "foreignField" : "emailGroupId",
            "unwinding" : {
                "preserveNullAndEmptyArrays" : false
            },
            "matching" : {
                "originalLink" : {
                    "$eq" : ""
                }
            }
        }
    },
    {
        "$group" : {

I'm leaving the part with $group in that output to demonstrate that the other two pipeline stages "disappear". This is because they have been "rolled-up" into the $lookup pipeline stage as shown. This is in fact how MongoDB deals with the possibility that the BSON Limit can be exceeded by the result of "joining" results of $lookup into an array of the parent document.

You can alternately write the operation like this:

All Detail

db.emailGroup.aggregate([
  { "$lookup": {
    "from": "link",
    "localField": "_id",
    "foreignField": "emailGroupId",
    "as": "link"
  }},
  { "$addFields": {
    "link": {
      "$filter": {
        "input": "$link",
        "as": "l",
        "cond": { "$eq": [ "$$l.originalLink", "" ] }
      }
    },
    "linkCount": {
      "$sum": {
        "$map": {
          "input": {
            "$filter": {
              "input": "$link",
              "as": "l",
              "cond": { "$eq": [ "$$l.originalLink", "" ] }
            }
          },
          "as": "l",
          "in": { "$size": { "$ifNull": [ "$$l.linkHistory", [] ] } }
        }
      }
    }
  }}
])

Group by partId

db.emailGroup.aggregate([
  { "$lookup": {
    "from": "link",
    "localField": "_id",
    "foreignField": "emailGroupId",
    "as": "link"
  }},
  { "$addFields": {
    "link": {
      "$filter": {
        "input": "$link",
        "as": "l",
        "cond": { "$eq": [ "$$l.originalLink", "" ] }
      }
    },
    "linkCount": {
      "$sum": {
        "$map": {
          "input": {
            "$filter": {
              "input": "$link",
              "as": "l",
              "cond": { "$eq": [ "$$l.originalLink", "" ] }
            }
          },
          "as": "l",
          "in": { "$size": { "$ifNull": [ "$$l.linkHistory", [] ] } }
        }
      }
    }
  }},
  { "$unwind": "$link" },
  { "$group": {
    "_id": "$partId",
    "linkCount": { "$sum": "$linkCount" }
  }}
])

Which has the same output but "differs" from the first query in that the $filter here is applied "after" ALL results of the $lookup are returned into the new array of the parent document.

So in performance terms, it is actually more effective to do it the first way as well as being portable to possible large result sets "before filtering" which would otherwise break the 16MB BSON Limit.

Note: If you do not have $addFields available (added with MongoDB 3.4) then use $project and specify "ALL" of the fields you wish to return.

As a side-note for those who are interested, in future releases of MongoDB ( presumably 3.6 and up ) you can use $replaceRoot instead of an $addFields with usage of the new $mergeObjects pipeline operator. The advantage of this is as a "block", we can declare the "filtered" content as a variable via $let, which means you do not need to write the same $filter "twice":

db.emailGroup.aggregate([
  { "$lookup": {
    "from": "link",
    "localField": "_id",
    "foreignField": "emailGroupId",
    "as": "link"
  }},
  { "$replaceRoot": {
    "newRoot": {
      "$mergeObjects": [
        "$$ROOT",
        { "$let": {
          "vars": {
            "filtered": {
              "$filter": {
                "input": "$link",
                "as": "l",
                "cond": { "$eq": [ "$$l.originalLink", "" ] }
              }
            }
          },
          "in": {
            "link": "$$filtered",
            "linkCount": {
              "$sum": {
                "$map": {
                  "input": "$$filtered.linkHistory",
                  "as": "lh",
                  "in": { "$size": { "$ifNull": [ "$$lh", [] ] } }
                }
              }
            }
          }
        }}
      ]
    }
  }}
])

Nonetheless the best way to do such "filtered" $lookup operations is "still" at this time using the $unwind then $match pattern, until such time as you can provide query arguments to $lookup directly.

Note: By "directly" here I do not mean the "non-correlated" form of $lookup which should also be in the MongoDB 3.6 release, as this would indeed issue another "pipeline" execution for each document in the parent collection. So that feature still does not replace the present "best effective" way of retrieving only the matched items.

ContentLicense: CC BY-SA 4.0


问:
dynamic variables attached to specific divs
I have several divs with one class on a page.

    ...

I need to attach a variable to each div with a boolean true or false, depending on the click on this div. All these variables should have a default false value, and if I click on a certain div the value of a variable attached to this div should become true. I don't know how much divs there will be as they appear dynamically on a page, so the variables should be attached according to the number of these divs on a page, and they must have a global scope so I could modify them in future. Appreciate all your ideas. Thanks!

答:
Solution:

```<code>   $("div.main").click(function(){
    if($(this).html()=='false')
    {
    $("this").html('true');
    }
    else
   {
   $("this").html('false');
   }

    });
</code>```

Body:
Solution:

   $("div.main").click(function(){
    if($(this).html()=='false')
    {
    $("this").html('true');
    }
    else
   {
   $("this").html('false');
   }

    });


问:
Reduce the vibration
I am using a vibrator to vibrate every time you click on any key on the layout, but camera shake is too strong, no way to vibrator gently as clicking on the virtual keyboard on the phone?</p>

答: The only way to vibrate more gentle - decrease vibration time to 25-40 milliseconds. Vibrator it self doesn't have "vibration power" option.</p>

Title: Reduce the vibration


问:
Priority queue for user-defined types
I have the below struct:

struct node {
   float val;
   int count;
}
```

I have several objects of this struct. Now, I want to insert these objects into a priority queue of STL such that the priority queue orders the items by count. Any idea on how to do so? Preferably a min-heap is preferred. I know how to do the above for primitive data types, not structs

答:
We can define user defined comparator class:

Code Snippet :

```<code>#include<bits/stdc++.h>
using namespace std;

struct man
{
  string name;
  int priority;
};

class comparator
{
 public:
   bool operator()(const man& a, const man& b)
   {
        return a.priority<b.priority;
   }
};

int main()
{
   man arr[5];
   priority_queue<man, vector<man>, comparator> pq;

   for(int i=0; i<3; i++)
   {
     cin>>arr[i].name>>arr[i].priority;
     pq.push(arr[i]);
   }

   while (!pq.empty())
   {
     cout<<pq.top().name<<" "<<pq.top().priority;
     pq.pop();
     cout<<endl;
   }
   return 0;
}
</code>```

Title: Priority queue for user-defined types

Body:
I have the below struct:

struct node {
   float val;
   int count;
}

I have several objects of this struct. Now, I want to insert these objects into a priority queue of STL such that the priority queue orders the items by count. Any idea on how to do so? Preferably a min-heap is preferred. I know how to do the above for primitive data types, not structs

Body:
We can define user defined comparator class:

Code Snippet :

#include<bits/stdc++.h>
using namespace std;

struct man
{
  string name;
  int priority;
};

class comparator
{
 public:
   bool operator()(const man& a, const man& b)
   {
        return a.priority<b.priority;
   }
};

int main()
{
   man arr[5];
   priority_queue<man, vector<man>, comparator> pq;

   for(int i=0; i<3; i++)
   {
     cin>>arr[i].name>>arr[i].priority;
     pq.push(arr[i]);
   }

   while (!pq.empty())
   {
     cout<<pq.top().name<<" "<<pq.top().priority;
     pq.pop();
     cout<<endl;
   }
   return 0;
}


问:
Angular 4 NgOnInitReference Error
I'm trying to open a new page upon the page startup but I keep getting a

Reference Error: Window not defined.

I've only started working with TypeScript and Angular4 recently, so I'm not so sure which one of the two this problem really falls under.

```<code>export class HomeComponent implements OnInit {

testCall: Window;

constructor() {
  this.testCall = new Window();
  this.testCall.open(
    "https://static.pexels.com/photos/104827/cat-pet-animal-domestic-104827.jpeg");
}

ngOnInit(): void {
  console.log("function read");

  window.open("https://static.pexels.com/photos/104827/cat-pet-animal-domestic-104827.jpeg");
}
</code>```

Even if I use the this.testCall.open inside the OnInit(), I'll only get a Reference Error, but on the open method.

I know it's a simple page open when the first page opens but its been a week already and I really have no idea how to do this in the typescript/angular4 setup.

答:
Did you try declaring the window object in the file that contains HomeComponent?. if not, try declaring it as;

```<code>declare var window: any;
</code>```

on the top of the file (after imports).

TypeScript doesn't know about window as we are not providing any typing info on that. In that case, we can declare those to tell the typescript compiler that the window reference in the global namespace didn't originate from a typescript file.

Read more about this scenario here

Title: Angular 4 NgOnInitReference Error

Body:
I'm trying to open a new page upon the page startup but I keep getting a

Reference Error: Window not defined.

I've only started working with TypeScript and Angular4 recently, so I'm not so sure which one of the two this problem really falls under.

export class HomeComponent implements OnInit {

testCall: Window;

constructor() {
  this.testCall = new Window();
  this.testCall.open(
    "https://static.pexels.com/photos/104827/cat-pet-animal-domestic-104827.jpeg");
}

ngOnInit(): void {
  console.log("function read");

  window.open("https://static.pexels.com/photos/104827/cat-pet-animal-domestic-104827.jpeg");
}

Even if I use the this.testCall.open inside the OnInit(), I'll only get a Reference Error, but on the open method.

I know it's a simple page open when the first page opens but its been a week already and I really have no idea how to do this in the typescript/angular4 setup.

Body:
Did you try declaring the window object in the file that contains HomeComponent?. if not, try declaring it as;

declare var window: any;

on the top of the file (after imports).

TypeScript doesn't know about window as we are not providing any typing info on that. In that case, we can declare those to tell the typescript compiler that the window reference in the global namespace didn't originate from a typescript file.

Read more about this scenario here


问:
jQuery Set Select Index
I have an select box:

```<code><select id="selectBox">
  <option value="0">Number 0</option>
  <option value="1">Number 1</option>
  <option value="2">Number 2</option>
  <option value="3">Number 3</option>
  <option value="4">Number 4</option>
  <option value="5">Number 5</option>
  <option value="6">Number 6</option>
  <option value="7">Number 7</option>
</select>
</code>```

I'd like to set one of the options as "selected" based on it's selected index.

For example, if I am trying to set "Number 3", I'm trying this:

```<code>$('#selectBox')[3].attr('selected', 'selected');
</code>```

But this doesn't work.  How can I set an option as selected based on it's index using jQuery?

Thanks!

答:
In 1.4.4 you get an error:  $("#selectBox option")[3].attr is not a function

This works: $('#name option:eq(idx)').attr('selected', true);

Where #name is select id and idx is the option value you want selected.

OwnerDisplayName: Dodinas

Title: jQuery Set Select Index

Body:
I have an select box:

<select id="selectBox">
  <option value="0">Number 0</option>
  <option value="1">Number 1</option>
  <option value="2">Number 2</option>
  <option value="3">Number 3</option>
  <option value="4">Number 4</option>
  <option value="5">Number 5</option>
  <option value="6">Number 6</option>
  <option value="7">Number 7</option>
</select>

I'd like to set one of the options as "selected" based on it's selected index.

For example, if I am trying to set "Number 3", I'm trying this:

$('#selectBox')[3].attr('selected', 'selected');

But this doesn't work.  How can I set an option as selected based on it's index using jQuery?

Thanks!


问:
Delete data from Cassandra with part of the partition key
Let's say that I have the following table in Cassandra:

```<code>customer_bought_product (
    store_id uuid,
    product_id text,
    order_time timestamp,
    email text,
    first_name text,
    last_name text,
    PRIMARY KEY ((store_id, product_id), order_time, email)
</code>```

The partition keys are store_id and order_id and it is used in order to store time series data.

The data does not have a TTL, as it should be accessible at all times.

In some cases we may require to delete all of the data for a given store_id.
What is the best practice to do it?

So far I have thought of the following solutions:

Write a program, that will select all of the data from the table and delete the records with the given store_id. - The downside is that this will take more and more time as we insert more data in the table.

Leave the data in the table. - The only problem with doing this, is that we will have useless data.

Store the table name with the available partition keys in a different table, that can be queried by store_id, get the keys from it and create a delete statement for each or those keys. - I do not like this concept, because I have to maintain the records.

Has anyone encountered this problem? What is the best practice to clear unused records from Cassandra (excluding TTL)?

答:
Delete by part of partition key is not possible.

Here is one approach:

Create a separate table that will have all product_id's for a given store.

```<code>CREATE TABLE product_by_store(
store_id uuid,
product_id set<text>,
PRIMARY KEY(store_id)
);
</code>```

Now wile writing to customer_bought_product, also update to product_by_store, something Like

UPDATE product_by_store SET product_id=product_id + 'someValue' WHERE store_id=GIVEN_STORE_ID

You can use BATCH statement while writing,this way you will get atomicity.

Now while deleting you can get all product_id for given store_id and then use

DELETE FROM customer_bought_product WHERE store_id=GIVEN_STORE_ID and product_id in (PRODUCT_ID YOU GET from product_by_store table)

Also delete corresponding record from customer_bought_product

Body:
Let's say that I have the following table in Cassandra:

customer_bought_product (
    store_id uuid,
    product_id text,
    order_time timestamp,
    email text,
    first_name text,
    last_name text,
    PRIMARY KEY ((store_id, product_id), order_time, email)

The partition keys are store_id and order_id and it is used in order to store time series data.

The data does not have a TTL, as it should be accessible at all times.

In some cases we may require to delete all of the data for a given store_id.
What is the best practice to do it?

So far I have thought of the following solutions:

Write a program, that will select all of the data from the table and delete the records with the given store_id. - The downside is that this will take more and more time as we insert more data in the table.

Leave the data in the table. - The only problem with doing this, is that we will have useless data.

Store the table name with the available partition keys in a different table, that can be queried by store_id, get the keys from it and create a delete statement for each or those keys. - I do not like this concept, because I have to maintain the records.

Has anyone encountered this problem? What is the best practice to clear unused records from Cassandra (excluding TTL)?

Body:
Delete by part of partition key is not possible.

Here is one approach:

Create a separate table that will have all product_id's for a given store.

CREATE TABLE product_by_store(
store_id uuid,
product_id set<text>,
PRIMARY KEY(store_id)
);

Now wile writing to customer_bought_product, also update to product_by_store, something Like

UPDATE product_by_store SET product_id=product_id + 'someValue' WHERE store_id=GIVEN_STORE_ID

You can use BATCH statement while writing,this way you will get atomicity.

Now while deleting you can get all product_id for given store_id and then use

DELETE FROM customer_bought_product WHERE store_id=GIVEN_STORE_ID and product_id in (PRODUCT_ID YOU GET from product_by_store table)

Also delete corresponding record from customer_bought_product


问:
How to get the inner array from json in android?
```<code>{"Suggestions":[{"Itinerary_1":[{"Cities":"Madurai - Pazhamudir Cholai (Madurai) - Pillayarpatti - Chennai","Citieids":"14-85-114-2","Kms":595}],"Itinerary_2":[{"Cities":"Madurai - Pillayarpatti - Pillayarpatti - Chennai","Citieids":"14-114-114-2","Kms":560}],"Itinerary_3":[{"Cities":"Madurai - Pillayarpatti - Pillayarpatti - Chennai","Citieids":"14-114-114-2","Kms":560}]}]}
</code>```

This my json response.This json have a inner array how can i get the value

This my code:

```<code>class itinerarydetails extends AsyncTask<String, String, String> {

        /**
         * Before starting background thread Show Progress Dialog
         */
        boolean failure = false;

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
        }

        @Override
        protected String doInBackground(String... args) {
            // TODO Auto-generated method stub
            // Check for success tag
            int success;

            List<NameValuePair> params = new ArrayList<NameValuePair>();
            params.add(new BasicNameValuePair("orgin", "14"));
            params.add(new BasicNameValuePair("destination", "2"));
            params.add(new BasicNameValuePair("orgin_date", "28/06/2017"));
            params.add(new BasicNameValuePair("destination_date", "07/07/2017"));

             json = jsonParser.makeHttpRequest(itineraryurl, "GET",
                    params);
            try {

                //Suggestions
                jsonarray = json.getJSONArray("Suggestions");
               // JSONArray list = mainObj.getJSONArray("prodCat_list");

                String check;
                if(jsonarray != null) {
                   // Toast.makeText(getApplicationCon                                                                                text(), "MAIN ARRAY IS NOT EMPTY ITS HAVE A VALUE",
                    //  Toast.LENGTH_SHORT).show();

                    Log.d("check","MAIN ARRAY IS NOT EMPTY ITS HAVE A VALUE");

                    for (int i = 0; i < jsonarray.length(); i++) {
                        //   JSONObject elem = list.getJSONObject(i);

                        JSONObject object = jsonarray.getJSONObject(i);

                        //JSONArray prods = elem.getJSONArray("prods");

                        jsoninsidearray = object.getJSONArray("Itinerary_1");

                        if(jsoninsidearray != null) {

                            Log.d("check","INSIDE ARRAY IS NOT EMPTY ITS HAVE A VALUE");

                            for (int j = 0; j < jsoninsidearray.length(); j++) {
                                JSONObject innerElem = jsoninsidearray.getJSONObject(j);

                                if(innerElem != null) {

                                    Log.d("check","innerElement ARRAY IS NOT EMPTY ITS HAVE A VALUE");
                                    cityjson = innerElem.getString("Cities");
                                    itinerary = innerElem.getString("Citieids");
                                    totalkms = innerElem.getString("Kms");

                                }
                               else
                                {
                                    Log.d("check","innerElement ARRAY IS EMPTY");

                                }

                            }
                        }
                        else
                        {
                           Toast.makeText(getApplicationContext(), "INSIDE ARRAY IS EMPTY",
                                   Toast.LENGTH_SHORT).show();

                            Log.d("check","INSIDE ARRAY IS EMPTY");
                        }

                    }
                }
                else
                {
                    Toast.makeText(getApplicationContext(), "MAIN ARRAY IS EMPTY",
                            Toast.LENGTH_SHORT).show();

                    Log.d("check","MAIN ARRAY IS EMPTY");
                }
            } catch (JSONException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

            return null;
        }

        protected void onPostExecute(String file_url) {

            Toast.makeText(getApplicationContext(), "hai",
                    Toast.LENGTH_SHORT).show();
            Toast.makeText(getApplicationContext(), cityjson, Toast.LENGTH_SHORT).show();

        }

    }
</code>```

I am Vignesh i have a doubt so pls help in this below
but empty values has displayed.how can i get the values from inner array from json.

答:
Just Change this line  jsoninsidearray = object.getJSONArray("Itinerary_1");

to

```<code>jsoninsidearray = object.getJSONArray("Itinerary_"+i);
</code>```

Body:
{"Suggestions":[{"Itinerary_1":[{"Cities":"Madurai - Pazhamudir Cholai (Madurai) - Pillayarpatti - Chennai","Citieids":"14-85-114-2","Kms":595}],"Itinerary_2":[{"Cities":"Madurai - Pillayarpatti - Pillayarpatti - Chennai","Citieids":"14-114-114-2","Kms":560}],"Itinerary_3":[{"Cities":"Madurai - Pillayarpatti - Pillayarpatti - Chennai","Citieids":"14-114-114-2","Kms":560}]}]}

This my json response.This json have a inner array how can i get the value

This my code:

class itinerarydetails extends AsyncTask<String, String, String> {

        /**
         * Before starting background thread Show Progress Dialog
         */
        boolean failure = false;

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
        }

        @Override
        protected String doInBackground(String... args) {
            // TODO Auto-generated method stub
            // Check for success tag
            int success;

            List<NameValuePair> params = new ArrayList<NameValuePair>();
            params.add(new BasicNameValuePair("orgin", "14"));
            params.add(new BasicNameValuePair("destination", "2"));
            params.add(new BasicNameValuePair("orgin_date", "28/06/2017"));
            params.add(new BasicNameValuePair("destination_date", "07/07/2017"));

             json = jsonParser.makeHttpRequest(itineraryurl, "GET",
                    params);
            try {

                //Suggestions
                jsonarray = json.getJSONArray("Suggestions");
               // JSONArray list = mainObj.getJSONArray("prodCat_list");

                String check;
                if(jsonarray != null) {
                   // Toast.makeText(getApplicationCon                                                                                text(), "MAIN ARRAY IS NOT EMPTY ITS HAVE A VALUE",
                    //  Toast.LENGTH_SHORT).show();

                    Log.d("check","MAIN ARRAY IS NOT EMPTY ITS HAVE A VALUE");

                    for (int i = 0; i < jsonarray.length(); i++) {
                        //   JSONObject elem = list.getJSONObject(i);

                        JSONObject object = jsonarray.getJSONObject(i);

                        //JSONArray prods = elem.getJSONArray("prods");

                        jsoninsidearray = object.getJSONArray("Itinerary_1");

                        if(jsoninsidearray != null) {

                            Log.d("check","INSIDE ARRAY IS NOT EMPTY ITS HAVE A VALUE");

                            for (int j = 0; j < jsoninsidearray.length(); j++) {
                                JSONObject innerElem = jsoninsidearray.getJSONObject(j);

                                if(innerElem != null) {

                                    Log.d("check","innerElement ARRAY IS NOT EMPTY ITS HAVE A VALUE");
                                    cityjson = innerElem.getString("Cities");
                                    itinerary = innerElem.getString("Citieids");
                                    totalkms = innerElem.getString("Kms");

                                }
                               else
                                {
                                    Log.d("check","innerElement ARRAY IS EMPTY");

                                }

                            }
                        }
                        else
                        {
                           Toast.makeText(getApplicationContext(), "INSIDE ARRAY IS EMPTY",
                                   Toast.LENGTH_SHORT).show();

                            Log.d("check","INSIDE ARRAY IS EMPTY");
                        }

                    }
                }
                else
                {
                    Toast.makeText(getApplicationContext(), "MAIN ARRAY IS EMPTY",
                            Toast.LENGTH_SHORT).show();

                    Log.d("check","MAIN ARRAY IS EMPTY");
                }
            } catch (JSONException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

            return null;
        }

        protected void onPostExecute(String file_url) {

            Toast.makeText(getApplicationContext(), "hai",
                    Toast.LENGTH_SHORT).show();
            Toast.makeText(getApplicationContext(), cityjson, Toast.LENGTH_SHORT).show();

        }

    }

I am Vignesh i have a doubt so pls help in this below
but empty values has displayed.how can i get the values from inner array from json.

Body:
Just Change this line  jsoninsidearray = object.getJSONArray("Itinerary_1");

to

jsoninsidearray = object.getJSONArray("Itinerary_"+i);


问:
I'm trying to use hamburger menu on bulma css, but it doesn't work. What is wrong?
I'm new on bulma css http://bulma.io/

I'm trying to use hamburger menu for mobile user.
I just followed instruction on this page: http://bulma.io/documentation/components/nav/

But it doesn't work. What should I add ?

Actually, I can see hamburger menu, but it doesn't work when I am click it.

Thank you.

```<code><!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1">
        <title>test</title>

        <link rel="stylesheet" href="css/bulma.min.css">
        <link rel="stylesheet" href="css/custom.css">
    </head>
    <body>
        <section class="hero is-fullheight is-primary is-bold">
            <!-- Hero header: will stick at the top -->
            <div class="hero-head">
                <header class="nav">
                    <div class="container">
                        <div class="nav-left">
                            <a class="nav-item" href="/">
                                <img src="img/logo.png" alt="Logo">
                            </a>
                        </div>
                        <span class="nav-toggle">
                            <span></span>
                            <span></span>
                            <span></span>
                        </span>
                        <div class="nav-right nav-menu">
                            <a class="nav-item" href="/about">
                                About
                            </a>
                            <a class="nav-item" href="/path">
                                Path
                            </a>
                            <a class="nav-item" href="/blog">
                                Blog
                            </a>
                        </div>
                    </div>
                </header>
            </div>
            <!-- Hero content: will be in the middle -->
            <div class="hero-body">
                <div class="container has-text-centered">
                </div>
            </div>
        </section>
    </body>
</html>
</code>```

答:
```<code>(function() {
    var burger = document.querySelector('.nav-toggle');
    var menu = document.querySelector('.nav-menu');
    burger.addEventListener('click', function() {
        burger.classList.toggle('is-active');
        menu.classList.toggle('is-active');
    });
})();
</code>```

Body:
I'm new on bulma css http://bulma.io/

I'm trying to use hamburger menu for mobile user.
I just followed instruction on this page: http://bulma.io/documentation/components/nav/

But it doesn't work. What should I add ?

Actually, I can see hamburger menu, but it doesn't work when I am click it.

Thank you.

<!DOCTYPE html>

        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1">
        <title>test</title>

        <link rel="stylesheet" href="css/bulma.min.css">
        <link rel="stylesheet" href="css/custom.css">

                                About

                                Path

                                Blog


问:
HSQLDB: Caused by: Using MAX, but not Group By, and getting java.sql.SQLSyntaxErrorException: expression not in aggregate or GROUP BY columns:
I am getting a JPQL syntax error message, and I am not sure how to fix the statement to get what I need.  I am using HSQLDB 2.4.0, and Hibernate 5.2.7.

For a given date, I am attempting to find the "SudokuPuzzleModel" with the largest sudokuPuzzleID.  Hence, the following Java/JPQL code:

```<code>static final private String queryByDateString =
     "SELECT p FROM SudokuPuzzleModel p " +
     "WHERE p.sudokuPuzzleID = (" +
         "SELECT MAX(p.sudokuPuzzleID) FROM SudokuPuzzleModel pp " +
         "WHERE pp.publicationDate LIKE :publicationDate" +
     ")";

static protected String getQueryByDate() { return queryByDateString; }

static public SudokuPuzzleModel getPuzzleByDate(LocalDate publicationDate) {
    EntityManager entityManager = RootModel.getEntityManagerFactory().createEntityManager();
    SudokuPuzzleModel results = null;

    String queryString = getQueryByDate();
    String jpaParameter = "publicationDate";
    Query query = entityManager.createQuery(queryString).setParameter(jpaParameter, publicationDate);
    results = (SudokuPuzzleModel) query.getSingleResult();

    entityManager.close();
    return results;
}
</code>```

I am not using a GROUP BY clause.  So any suggestions on how to modify the JPQL statement to get what I am after?

What I am after, the SudokuPuzzleModel, with the largest sudokuPuzzleID, that was published on the date that is being passed in.

FYI: The initial error message was "ERROR org.hibernate.engine.jdbc.spi.SqlExceptionHelper - A problem occurred while trying to acquire a cached PreparedStatement in a background thread."
But, I believe that this is being caused by the syntax error.

答: Looks like typo in your sql. Looks like you need MAX(pp.sudokuPuzzleID) instead of MAX(p.sudokuPuzzleID)?</p>

Body:
I am getting a JPQL syntax error message, and I am not sure how to fix the statement to get what I need.  I am using HSQLDB 2.4.0, and Hibernate 5.2.7.

For a given date, I am attempting to find the "SudokuPuzzleModel" with the largest sudokuPuzzleID.  Hence, the following Java/JPQL code:

static final private String queryByDateString =
     "SELECT p FROM SudokuPuzzleModel p " +
     "WHERE p.sudokuPuzzleID = (" +
         "SELECT MAX(p.sudokuPuzzleID) FROM SudokuPuzzleModel pp " +
         "WHERE pp.publicationDate LIKE :publicationDate" +
     ")";

static protected String getQueryByDate() { return queryByDateString; }

static public SudokuPuzzleModel getPuzzleByDate(LocalDate publicationDate) {
    EntityManager entityManager = RootModel.getEntityManagerFactory().createEntityManager();
    SudokuPuzzleModel results = null;

    String queryString = getQueryByDate();
    String jpaParameter = "publicationDate";
    Query query = entityManager.createQuery(queryString).setParameter(jpaParameter, publicationDate);
    results = (SudokuPuzzleModel) query.getSingleResult();

    entityManager.close();
    return results;
}

I am not using a GROUP BY clause.  So any suggestions on how to modify the JPQL statement to get what I am after?

What I am after, the SudokuPuzzleModel, with the largest sudokuPuzzleID, that was published on the date that is being passed in.

FYI: The initial error message was "ERROR org.hibernate.engine.jdbc.spi.SqlExceptionHelper - A problem occurred while trying to acquire a cached PreparedStatement in a background thread."
But, I believe that this is being caused by the syntax error.


问:
XPATH for dialog input text field?
IMAGE
Jquery
Could you help me to show xpath of the below html code?

Thanks you!

HTML code:

```<code><div class="p-ui-textinputinputdata" style="display: none;"/>
<input class="p-ui-textinputinputobject inputwidget-inputobject p-ui-inputlimiter" style="display: inline-block;" tabindex="201"/>
</code>```

答:
try this:

```<code>//input[contains(@class, 'p-ui-textinputinputobject')]/@value
</code>```

or you can use JQUERY:

```<code>$("input.p-ui-textinputinputobject").val();
</code>```

OPTION 2:

```<code>js.ExecuteScript(@"jQuery('input.p-ui-textinputinputobject').val('Test')");
</code>```

Title: XPATH for dialog input text field?

Body:
IMAGE
Jquery
Could you help me to show xpath of the below html code?

Thanks you!

HTML code:

<input class="p-ui-textinputinputobject inputwidget-inputobject p-ui-inputlimiter" style="display: inline-block;" tabindex="201"/>

Body:
try this:

//input[contains(@class, 'p-ui-textinputinputobject')]/@value

or you can use JQUERY:

$("input.p-ui-textinputinputobject").val();

OPTION 2:

js.ExecuteScript(@"jQuery('input.p-ui-textinputinputobject').val('Test')");


问:
How to keep transparency of PNG image for ScaleImageLabel?
I've added a PNG with transparent background as MultiImage to a theme and tried to use it for ScaleImageLabel:

```<code>ScaleImageLabel logoLabel = new ScaleImageLabel(theme.getImage("sign-up--logo.png 1"));
</code>```

The Codename One Designer shows the image as it should be, with transparency:

But simulator paints the transparent area white:

What should be done to keep the background of the PNG image transparent?

答:
```<code>logoLabel.setUIID("Container");
</code>```

Generally the opacity comes from the Label UIID so you can style Label to have a transparency value of 0.

Body:
I've added a PNG with transparent background as MultiImage to a theme and tried to use it for ScaleImageLabel:

ScaleImageLabel logoLabel = new ScaleImageLabel(theme.getImage("sign-up--logo.png 1"));

The Codename One Designer shows the image as it should be, with transparency:

But simulator paints the transparent area white:

What should be done to keep the background of the PNG image transparent?

Body:
logoLabel.setUIID("Container");

Generally the opacity comes from the Label UIID so you can style Label to have a transparency value of 0.


问:
The multi-part identifier could not be bound on cross apply
I am getting this error while joining a table with Cross Apply from a table returned from a function. I tried many solutions online but not a single worked for me.

```<code>Select LTRIM(RTRIM(i.block_num)) as block_num,LTRIM(RTRIM(i.type_code)) as type_code,LTRIM(RTRIM(i.wire_side)) as wire_side,LTRIM(RTRIM(i.grade_spec_made)) as Grade_spec,LTRIM(RTRIM(i.Order_Id)) as Order_Id,LTRIM(RTRIM(i.item_num)) as item_num,CAST(LTRIM(RTRIM(i.width_ord)) AS Decimal(15,2)) as width_ord,LTRIM(RTRIM(i.len_sheet_ord)) as len_sheet_ord,
CAST(LTRIM(RTRIM(i.diam_min)) AS Decimal(15,2)) as diam_min,CAST(LTRIM(RTRIM(i.diam_ord)) AS Decimal(15,2)) as diam_ord,CAST(LTRIM(RTRIM(i.diam_max)) AS Decimal(15,2)) as diam_max,LTRIM(RTRIM(i.core_id)) as core_id,
CAST(LTRIM(RTRIM(i.diam_core)) AS Decimal(15,2)) as diam_core,LTRIM(RTRIM(i.wire_side)) as wire_side,LTRIM(RTRIM(i.rolls_per_pack)) as rolls_per_pack,LTRIM(RTRIM(i.roll_non_edge)) as roll_non_edge,
LTRIM(RTRIM(i.make_to_len_flag)) as make_to_len_flag,LTRIM(RTRIM(i.roll_wgt_flag)) as roll_wgt_flag,LTRIM(RTRIM(i.rolls_ord)) as rolls_ord,LTRIM(RTRIM(i.length_ord)) as length_ord,
CAST(LTRIM(RTRIM(i.wgt_ord)) AS Decimal(15,2)) as wgt_ord,LTRIM(RTRIM(i.ts_ship_prom)) as ts_ship_prom,LTRIM(RTRIM(i.length_min)) as length_min,LTRIM(RTRIM(i.length_max)) as length_max,
LTRIM(RTRIM(i.perc_over)) as perc_over,LTRIM(RTRIM(i.perc_under)) as perc_under,CAST(LTRIM(RTRIM(i.length_nominal)) AS Decimal(15,2)) as length_nominal,LTRIM(RTRIM(i.type_code_trades)) as type_code_trades,
LTRIM(RTRIM(i.width_conv)) as width_conv, LTRIM(RTRIM(i.Mill_id)) as mill_id, LTRIM(RTRIM(i.machine_type)) as machine_type, LTRIM(RTRIM(CAST(ROUND (i.wgt_sched , 2 , 1 ) as decimal(18,2)))) as wgt_sched,LTRIM(RTRIM( i.machine_id)) as Machine_id, dateadd(s,ts_ship_plan,'19700101 05:00:00:000') as ShipDate,
LTRIM(RTRIM(i.article_id)) as article_id, LTRIM(RTRIM(i.grain_direction)) as grain_direction ,
(SELECT TOP 1 LTRIM(RTRIM(intertrim_num))  FROM grade_spec WHERE grade_spec.grade_spec = i.grade_spec) AS intertrim_num,
(SELECT TOP 1 cons_name  FROM consignee WHERE consignee.consignee_id = i.consignee_id) AS cons_name_full,
(SELECT TOP 1 CASE WHEN Len(LTRIM(RTRIM(cons_name))) > 10 THEN SUBSTRING ( LTRIM(RTRIM(cons_name))  ,0 , 10 ) + '..' ELSE LTRIM(RTRIM(cons_name)) END  FROM consignee WHERE consignee.consignee_id = i.consignee_id) AS cons_name
,s.wgt_trim_plan,
(i.wgt_ord-s.wgt_trim_plan) as wgt_untrim
,w.wgt_select,w.max_wgt,w.min_wgt,w.misc_loss
from order_blocks b, order_item i, order_status s, mach_sched m
left join unit_status u on u.stat=m.stat and table_name = 'mach_sched'
CROSS APPLY
GetOrderWeightsTest('MX1','WD','02','MX1','PM','01',i.block_num,i.Order_Id,i.item_num,i.grade_spec_made ,i.perc_over,i.perc_under,i.type_code_trades,i.type_code) w
where b.order_id = i.order_id and b.item_num = i.item_num and b.machine_type=i.machine_type and i.order_id = s.order_id and i.item_num = s.item_num and i.wgt_ord>s.wgt_trim_plan and b.mill_id=m.mill_id and b.machine_type=m.machine_type and b.machine_id=m.machine_id and b.block_num=m.block_num and i.type_code='R'
</code>```

Error Log:

```<code>Msg 4104, Level 16, State 1, Line 18
The multi-part identifier "i.block_num" could not be bound.
Msg 4104, Level 16, State 1, Line 18
The multi-part identifier "i.Order_Id" could not be bound.
Msg 4104, Level 16, State 1, Line 18
The multi-part identifier "i.item_num" could not be bound.
Msg 4104, Level 16, State 1, Line 18
The multi-part identifier "i.grade_spec_made" could not be bound.
Msg 4104, Level 16, State 1, Line 18
The multi-part identifier "i.perc_over" could not be bound.
Msg 4104, Level 16, State 1, Line 18
The multi-part identifier "i.perc_under" could not be bound.
Msg 4104, Level 16, State 1, Line 18
The multi-part identifier "i.type_code_trades" could not be bound.
Msg 4104, Level 16, State 1, Line 18
The multi-part identifier "i.type_code" could not be bound.
</code>```

答:
Use INNER JOIN syntax to solve the issue. It is the preferred way to join tables than the old style comma separated join

```<code>Select
...
FROM   order_blocks b
       INNER JOIN order_item i
               ON b.order_id = i.order_id
                  AND b.item_num = i.item_num
                  AND b.machine_type = i.machine_type
       INNER JOIN order_status s
               ON i.order_id = s.order_id
                  AND i.item_num = s.item_num
                  AND i.wgt_ord > s.wgt_trim_plan
       INNER JOIN mach_sched m
               ON b.mill_id = m.mill_id
                  AND b.machine_type = m.machine_type
                  AND b.machine_id = m.machine_id
                  AND b.block_num = m.block_num
       LEFT JOIN unit_status u
              ON u.stat = m.stat
                 AND table_name = 'mach_sched'
       CROSS APPLY Getorderweightstest('MX1', 'WD', '02', 'MX1', 'PM', '01', i.block_num, i.Order_Id, i.item_num, i.grade_spec_made, i.perc_over, i.perc_under, i.type_code_trades, i.type_code) w
WHERE  i.type_code = 'R'
</code>```

Body:
I am getting this error while joining a table with Cross Apply from a table returned from a function. I tried many solutions online but not a single worked for me.

Select LTRIM(RTRIM(i.block_num)) as block_num,LTRIM(RTRIM(i.type_code)) as type_code,LTRIM(RTRIM(i.wire_side)) as wire_side,LTRIM(RTRIM(i.grade_spec_made)) as Grade_spec,LTRIM(RTRIM(i.Order_Id)) as Order_Id,LTRIM(RTRIM(i.item_num)) as item_num,CAST(LTRIM(RTRIM(i.width_ord)) AS Decimal(15,2)) as width_ord,LTRIM(RTRIM(i.len_sheet_ord)) as len_sheet_ord,
CAST(LTRIM(RTRIM(i.diam_min)) AS Decimal(15,2)) as diam_min,CAST(LTRIM(RTRIM(i.diam_ord)) AS Decimal(15,2)) as diam_ord,CAST(LTRIM(RTRIM(i.diam_max)) AS Decimal(15,2)) as diam_max,LTRIM(RTRIM(i.core_id)) as core_id,
CAST(LTRIM(RTRIM(i.diam_core)) AS Decimal(15,2)) as diam_core,LTRIM(RTRIM(i.wire_side)) as wire_side,LTRIM(RTRIM(i.rolls_per_pack)) as rolls_per_pack,LTRIM(RTRIM(i.roll_non_edge)) as roll_non_edge,
LTRIM(RTRIM(i.make_to_len_flag)) as make_to_len_flag,LTRIM(RTRIM(i.roll_wgt_flag)) as roll_wgt_flag,LTRIM(RTRIM(i.rolls_ord)) as rolls_ord,LTRIM(RTRIM(i.length_ord)) as length_ord,
CAST(LTRIM(RTRIM(i.wgt_ord)) AS Decimal(15,2)) as wgt_ord,LTRIM(RTRIM(i.ts_ship_prom)) as ts_ship_prom,LTRIM(RTRIM(i.length_min)) as length_min,LTRIM(RTRIM(i.length_max)) as length_max,
LTRIM(RTRIM(i.perc_over)) as perc_over,LTRIM(RTRIM(i.perc_under)) as perc_under,CAST(LTRIM(RTRIM(i.length_nominal)) AS Decimal(15,2)) as length_nominal,LTRIM(RTRIM(i.type_code_trades)) as type_code_trades,
LTRIM(RTRIM(i.width_conv)) as width_conv, LTRIM(RTRIM(i.Mill_id)) as mill_id, LTRIM(RTRIM(i.machine_type)) as machine_type, LTRIM(RTRIM(CAST(ROUND (i.wgt_sched , 2 , 1 ) as decimal(18,2)))) as wgt_sched,LTRIM(RTRIM( i.machine_id)) as Machine_id, dateadd(s,ts_ship_plan,'19700101 05:00:00:000') as ShipDate,
LTRIM(RTRIM(i.article_id)) as article_id, LTRIM(RTRIM(i.grain_direction)) as grain_direction ,
(SELECT TOP 1 LTRIM(RTRIM(intertrim_num))  FROM grade_spec WHERE grade_spec.grade_spec = i.grade_spec) AS intertrim_num,
(SELECT TOP 1 cons_name  FROM consignee WHERE consignee.consignee_id = i.consignee_id) AS cons_name_full,
(SELECT TOP 1 CASE WHEN Len(LTRIM(RTRIM(cons_name))) > 10 THEN SUBSTRING ( LTRIM(RTRIM(cons_name))  ,0 , 10 ) + '..' ELSE LTRIM(RTRIM(cons_name)) END  FROM consignee WHERE consignee.consignee_id = i.consignee_id) AS cons_name
,s.wgt_trim_plan,
(i.wgt_ord-s.wgt_trim_plan) as wgt_untrim
,w.wgt_select,w.max_wgt,w.min_wgt,w.misc_loss
from order_blocks b, order_item i, order_status s, mach_sched m
left join unit_status u on u.stat=m.stat and table_name = 'mach_sched'
CROSS APPLY
GetOrderWeightsTest('MX1','WD','02','MX1','PM','01',i.block_num,i.Order_Id,i.item_num,i.grade_spec_made ,i.perc_over,i.perc_under,i.type_code_trades,i.type_code) w
where b.order_id = i.order_id and b.item_num = i.item_num and b.machine_type=i.machine_type and i.order_id = s.order_id and i.item_num = s.item_num and i.wgt_ord>s.wgt_trim_plan and b.mill_id=m.mill_id and b.machine_type=m.machine_type and b.machine_id=m.machine_id and b.block_num=m.block_num and i.type_code='R'

Error Log:

Msg 4104, Level 16, State 1, Line 18
The multi-part identifier "i.block_num" could not be bound.
Msg 4104, Level 16, State 1, Line 18
The multi-part identifier "i.Order_Id" could not be bound.
Msg 4104, Level 16, State 1, Line 18
The multi-part identifier "i.item_num" could not be bound.
Msg 4104, Level 16, State 1, Line 18
The multi-part identifier "i.grade_spec_made" could not be bound.
Msg 4104, Level 16, State 1, Line 18
The multi-part identifier "i.perc_over" could not be bound.
Msg 4104, Level 16, State 1, Line 18
The multi-part identifier "i.perc_under" could not be bound.
Msg 4104, Level 16, State 1, Line 18
The multi-part identifier "i.type_code_trades" could not be bound.
Msg 4104, Level 16, State 1, Line 18
The multi-part identifier "i.type_code" could not be bound.

Body:
Use INNER JOIN syntax to solve the issue. It is the preferred way to join tables than the old style comma separated join

Select
...
FROM   order_blocks b
       INNER JOIN order_item i
               ON b.order_id = i.order_id
                  AND b.item_num = i.item_num
                  AND b.machine_type = i.machine_type
       INNER JOIN order_status s
               ON i.order_id = s.order_id
                  AND i.item_num = s.item_num
                  AND i.wgt_ord > s.wgt_trim_plan
       INNER JOIN mach_sched m
               ON b.mill_id = m.mill_id
                  AND b.machine_type = m.machine_type
                  AND b.machine_id = m.machine_id
                  AND b.block_num = m.block_num
       LEFT JOIN unit_status u
              ON u.stat = m.stat
                 AND table_name = 'mach_sched'
       CROSS APPLY Getorderweightstest('MX1', 'WD', '02', 'MX1', 'PM', '01', i.block_num, i.Order_Id, i.item_num, i.grade_spec_made, i.perc_over, i.perc_under, i.type_code_trades, i.type_code) w
WHERE  i.type_code = 'R'


问:
Extracting Latitude and longitude in imacros
I just started with imacros and have a query, like how do I extract Latitude and longitude from a  tag

```<code><div class="iconMap" onclick="stopPage=true;">
<a class='stop-propagation' href="javascript:void(0);" data-link="/propertyDetails/poiOnMap.html?lat=19.2412011&longt=73.1290596&projectOrProp=Project&city=Thane&includeJs=y&type=poiMap2017&address=Thane, Maharashtra" id="map_link_27774907" onclick="stopPage=true; showPhotoMap('/propertyDetails/poiOnMap.html?lat=19.2412011&longt=73.1290596&projectOrProp=Project&city=Thane&includeJs=y&type=poiMap2017&address=Thane, Maharashtra');"><span class="icoMap"></span>Map</a>
</div>
</code>```

I want to extract lat=19.2412011 longt=73.1290596

This is what I have tried

```<code>TAG POS=1 TYPE=a ATTR=CLASS:stop-propagation&&TXT:* EXTRACT=TXT
</code>```

But I get the text as Map
Any help on this would be much appreciated. Thanks in advance

答:
So I finally got the above problem solved, This is the working code

```<code>TAG POS=2 TYPE=a ATTR=class:stop-propagation&&TXT:* EXTRACT=HTM
SET lat EVAL("'{{!EXTRACT}}'.match(/\?(lat=.+?)&/)[1];")
SET longt EVAL("var regex = /longt=(\\d+(?:\\.\\d+)?)/g; var str = '{{!EXTRACT}}';str.match(regex)[1];")

PROMPT "{{lat}} {{longt}}"
</code>```

Thanks.

Body:
I just started with imacros and have a query, like how do I extract Latitude and longitude from a  tag

Map

I want to extract lat=19.2412011 longt=73.1290596

This is what I have tried

TAG POS=1 TYPE=a ATTR=CLASS:stop-propagation&&TXT:* EXTRACT=TXT

But I get the text as Map
Any help on this would be much appreciated. Thanks in advance

Body:
So I finally got the above problem solved, This is the working code

TAG POS=2 TYPE=a ATTR=class:stop-propagation&&TXT:* EXTRACT=HTM
SET lat EVAL("'{{!EXTRACT}}'.match(/\?(lat=.+?)&/)[1];")
SET longt EVAL("var regex = /longt=(\\d+(?:\\.\\d+)?)/g; var str = '{{!EXTRACT}}';str.match(regex)[1];")

PROMPT "{{lat}} {{longt}}"

Thanks.


问:
How to write a SQL DB Backup script with format: Demo_YYYYMMDD_XX.bak
how to write a daily backup script with unique name format: Demo_YYYYMMDD_XX
where XX is an incremental number based on the backup history.

Example as below.

1st Backup: Demo_20170704_01.bak

2nd Backup: Demo_20170704_02.bak

3rd Backup: Demo_20170704_03.bak

XX will increase +1 every time the backup process is run on the same day and same folder(path).

Managed to come out with the script below. Any improvement needed? thanks

```<code>DECLARE @path VARCHAR(500)
DECLARE @name VARCHAR(500)
DECLARE @pathwithname VARCHAR(500)
DECLARE @time DATETIME
DECLARE @year VARCHAR(4)
DECLARE @month VARCHAR(2)
DECLARE @day VARCHAR(2)
DECLARE @counter varchar(10)

SET @path = 'C:\Backup Path\'

SELECT @time = GETDATE()
SELECT @year = (SELECT CONVERT(VARCHAR(4), DATEPART(yy, @time)))
SELECT @month = (SELECT CONVERT(VARCHAR(2), FORMAT(DATEPART(mm,@time),'00')))
SELECT @day = (SELECT CONVERT(VARCHAR(2), FORMAT(DATEPART(dd,@time),'00')))
SELECT @counter = (
select format(count(A.database_name),'000')
from msdb.dbo.backupset A join msdb.dbo.backupmediafamily B
on A.media_set_id = B.media_set_id
where A.database_name = 'Demo'
and (select convert(date,A.backup_start_date, 120))  = (select convert(date,getdate(), 120))
)

SELECT @name ='Demo' + '_' + @year + @month + @day + '_' + @counter
SET @pathwithname = @path + @name + '.bak'

BACKUP DATABASE Demo
TO DISK = @pathwithname WITH NOFORMAT, NOINIT, SKIP, REWIND, NOUNLOAD, STATS = 10
</code>```

答:
You have two choices.

list files in directory that match your pattern (date), count and increment

keep a count of how many backups you make each day (increment)

Since you have a database and are backing up that database, why not just do the latter? And record your daily backups to a table that has,

```<code>create table backups (
    dbback DATE NOT NULL DEFAULT GETDATE()
   ,dbname varchar(99) NOT NULL
   ,name   varchar(99) NOT NULL
   ,index  int NOT NULL
   ,primary key(db,backdb)
) ;
</code>```

You can record the pair (db,backdb) to record entries for multiple databases (dbname, dbback).

```<code>WITH t as ( select (backups.index+1) as nextnum
from backups where dbname = 'database_name' and dbback = CAST(GETDATE() AS DATE)
union select 1 as nextnum from dual )
insert into backups (dbback,dbname,name,index)
values (CAST(GETDATE() AS DATE),'database_name','yourname',t.nextnum) ;
</code>```

Note that by using union you ensure that you get the base (first) row in the temporary table

Body:
how to write a daily backup script with unique name format: Demo_YYYYMMDD_XX
where XX is an incremental number based on the backup history.

Example as below.

1st Backup: Demo_20170704_01.bak

2nd Backup: Demo_20170704_02.bak

3rd Backup: Demo_20170704_03.bak

XX will increase +1 every time the backup process is run on the same day and same folder(path).

Managed to come out with the script below. Any improvement needed? thanks

DECLARE @path VARCHAR(500)
DECLARE @name VARCHAR(500)
DECLARE @pathwithname VARCHAR(500)
DECLARE @time DATETIME
DECLARE @year VARCHAR(4)
DECLARE @month VARCHAR(2)
DECLARE @day VARCHAR(2)
DECLARE @counter varchar(10)

SET @path = 'C:\Backup Path\'

SELECT @time = GETDATE()
SELECT @year = (SELECT CONVERT(VARCHAR(4), DATEPART(yy, @time)))
SELECT @month = (SELECT CONVERT(VARCHAR(2), FORMAT(DATEPART(mm,@time),'00')))
SELECT @day = (SELECT CONVERT(VARCHAR(2), FORMAT(DATEPART(dd,@time),'00')))
SELECT @counter = (
select format(count(A.database_name),'000')
from msdb.dbo.backupset A join msdb.dbo.backupmediafamily B
on A.media_set_id = B.media_set_id
where A.database_name = 'Demo'
and (select convert(date,A.backup_start_date, 120))  = (select convert(date,getdate(), 120))
)

SELECT @name ='Demo' + '_' + @year + @month + @day + '_' + @counter
SET @pathwithname = @path + @name + '.bak'

BACKUP DATABASE Demo
TO DISK = @pathwithname WITH NOFORMAT, NOINIT, SKIP, REWIND, NOUNLOAD, STATS = 10

Body:
You have two choices.

list files in directory that match your pattern (date), count and increment

keep a count of how many backups you make each day (increment)

Since you have a database and are backing up that database, why not just do the latter? And record your daily backups to a table that has,

create table backups (
    dbback DATE NOT NULL DEFAULT GETDATE()
   ,dbname varchar(99) NOT NULL
   ,name   varchar(99) NOT NULL
   ,index  int NOT NULL
   ,primary key(db,backdb)
) ;

You can record the pair (db,backdb) to record entries for multiple databases (dbname, dbback).

WITH t as ( select (backups.index+1) as nextnum
from backups where dbname = 'database_name' and dbback = CAST(GETDATE() AS DATE)
union select 1 as nextnum from dual )
insert into backups (dbback,dbname,name,index)
values (CAST(GETDATE() AS DATE),'database_name','yourname',t.nextnum) ;

Note that by using union you ensure that you get the base (first) row in the temporary table


问:
android monitor throw E/HW-JPEG-DEC after update to android 7
after update phone to android 7 when i build app again Android Monitor throw error:

E/HW-JPEG-DEC: HME_JPEG_DEC_Delete: HME_JPEG_DEC_Delete: decoder_ctx=null

答: Your resource images most likely contain meta/exif data that is not properly handled by the built-in image viewer. You may either ignore those errors or remove the meta data from your images.</p>


问:
How do you make a star rating as a visualisation
I have a simple dataframe.

```<code>name    Rating
George     2
Henry      4
</code>```

In either python or R, I want to make a star rating visualization like in Amazon.

```<code>name     Rating
George     **
Henry      ****
</code>```

答:
In R:</p>

```<code>df$Rating <- strrep("*", df$Rating)
</code>```

Body:
I have a simple dataframe.

name    Rating
George     2
Henry      4

In either python or R, I want to make a star rating visualization like in Amazon.

name     Rating
George     **
Henry      ****

Body:
In R:

df$Rating <- strrep("*", df$Rating)


问:
Ios Swift making font toggle bold, italic, boldItalic, normal without change other attributes
I am surprised, that simply setting bold and italic for existing font is so complicated in Swift.

I just want to simplify things by having following methods on font class.

I want the below methods to be added to existing font which has font-family and font-size set. I need to preserve these and change only the following.

setBold : Shud preserve italic

setItalic : Shud preserve bold

setBoldItalic

setNormal : remove both bold and italic

removeBold : Shud preserve italic

removeitalic : Shud preserve bold

I tried the below, and it's feeling like a nightmare for me using fontDescriptorWithSymbolicTraits.

Is there a simpler way of doing these in a few lines of code?

```<code>extension UIFont
{
    var isBold: Bool
    {
        return fontDescriptor().symbolicTraits.contains(.TraitBold)
    }

    var isItalic: Bool
    {
        return fontDescriptor().symbolicTraits.contains(.TraitItalic)
    }

    func setBold() -> UIFont
    {
        var fontDescriptorVar: UIFontDescriptor
        if(isBold){
            return self
        }
        else
        {
            fontDescriptorVar = fontDescriptor().fontDescriptorWithSymbolicTraits(.TraitBold)
        }
        return UIFont(descriptor: fontDescriptorVar, size: 0)
    }

    func setItalic()-> UIFont
    {
        var fontDescriptorVar: UIFontDescriptor
        if(isItalic) {
            return self
        }
        else
        {
            fontDescriptorVar = fontDescriptor().fontDescriptorWithSymbolicTraits(.TraitItalic)
        }
        return UIFont(descriptor: fontDescriptorVar, size: 0)
    }

    func setBoldItalic()-> UIFont
    {
        let fontDescriptorVar = fontDescriptor().fontDescriptorWithSymbolicTraits(UIFontDescriptorSymbolicTraits(arrayLiteral: .TraitBold, .TraitItalic))
        return UIFont(descriptor: fontDescriptorVar, size: 0)
    }

    // Things I need are

    // To set back to normal

    func setNormal()-> UIFont
    {

    }

    // Remove only bold if it's both bold and Italic

    func removeBold()-> UIFont
    {

    }

    // Remove only italic if it's both bold and Italic

    func removeitalic()-> UIFont
    {

    }
}
</code>```

I don't want to use this which asks me the size and font as input:

```<code>UIFont(name "namFontFamily", size: 16)

UIFont.systemFontOfSize(16, weight: UIFontWeightLight)
</code>```

I searched everywhere and found no simple solution matching my needs.

答:
Swift 3.1</p>

```<code>extension UIFont{
var isBold: Bool
{
    return fontDescriptor.symbolicTraits.contains(.traitBold)
}

var isItalic: Bool
{
    return fontDescriptor.symbolicTraits.contains(.traitItalic)
}

func setBold() -> UIFont
{
    if(isBold)
    {
        return self
    }
    else
    {
        var fontAtrAry = fontDescriptor.symbolicTraits
        fontAtrAry.insert([.traitBold])
        let fontAtrDetails = fontDescriptor.withSymbolicTraits(fontAtrAry)
        return UIFont(descriptor: fontAtrDetails!, size: pointSize)
    }
}

func setItalic()-> UIFont
{
    if(isItalic)
    {
        return self
    }
    else
    {
        var fontAtrAry = fontDescriptor.symbolicTraits
        fontAtrAry.insert([.traitItalic])
        let fontAtrDetails = fontDescriptor.withSymbolicTraits(fontAtrAry)
        return UIFont(descriptor: fontAtrDetails!, size: pointSize)
    }
}
func desetBold() -> UIFont
{
    if(!isBold)
    {
        return self
    }
    else
    {
        var fontAtrAry = fontDescriptor.symbolicTraits
        fontAtrAry.remove([.traitBold])
        let fontAtrDetails = fontDescriptor.withSymbolicTraits(fontAtrAry)
        return UIFont(descriptor: fontAtrDetails!, size: pointSize)
    }
}

func desetItalic()-> UIFont
{
    if(!isItalic)
    {
        return self
    }
    else
    {
        var fontAtrAry = fontDescriptor.symbolicTraits
        fontAtrAry.remove([.traitItalic])
        let fontAtrDetails = fontDescriptor.withSymbolicTraits(fontAtrAry)
        return UIFont(descriptor: fontAtrDetails!, size: pointSize)
    }
}
}
</code>```

Body:
I am surprised, that simply setting bold and italic for existing font is so complicated in Swift.

I just want to simplify things by having following methods on font class.

I want the below methods to be added to existing font which has font-family and font-size set. I need to preserve these and change only the following.

setBold : Shud preserve italic

setItalic : Shud preserve bold

setBoldItalic

setNormal : remove both bold and italic

removeBold : Shud preserve italic

removeitalic : Shud preserve bold

I tried the below, and it's feeling like a nightmare for me using fontDescriptorWithSymbolicTraits.

Is there a simpler way of doing these in a few lines of code?

extension UIFont
{
    var isBold: Bool
    {
        return fontDescriptor().symbolicTraits.contains(.TraitBold)
    }

    var isItalic: Bool
    {
        return fontDescriptor().symbolicTraits.contains(.TraitItalic)
    }

    func setBold() -> UIFont
    {
        var fontDescriptorVar: UIFontDescriptor
        if(isBold){
            return self
        }
        else
        {
            fontDescriptorVar = fontDescriptor().fontDescriptorWithSymbolicTraits(.TraitBold)
        }
        return UIFont(descriptor: fontDescriptorVar, size: 0)
    }

    func setItalic()-> UIFont
    {
        var fontDescriptorVar: UIFontDescriptor
        if(isItalic) {
            return self
        }
        else
        {
            fontDescriptorVar = fontDescriptor().fontDescriptorWithSymbolicTraits(.TraitItalic)
        }
        return UIFont(descriptor: fontDescriptorVar, size: 0)
    }

    func setBoldItalic()-> UIFont
    {
        let fontDescriptorVar = fontDescriptor().fontDescriptorWithSymbolicTraits(UIFontDescriptorSymbolicTraits(arrayLiteral: .TraitBold, .TraitItalic))
        return UIFont(descriptor: fontDescriptorVar, size: 0)
    }

    // Things I need are

    // To set back to normal

    func setNormal()-> UIFont
    {

    }

    // Remove only bold if it's both bold and Italic

    func removeBold()-> UIFont
    {

    }

    // Remove only italic if it's both bold and Italic

    func removeitalic()-> UIFont
    {

    }
}

I don't want to use this which asks me the size and font as input:

UIFont(name "namFontFamily", size: 16)

UIFont.systemFontOfSize(16, weight: UIFontWeightLight)

I searched everywhere and found no simple solution matching my needs.

Body:
Swift 3.1

extension UIFont{
var isBold: Bool
{
    return fontDescriptor.symbolicTraits.contains(.traitBold)
}

var isItalic: Bool
{
    return fontDescriptor.symbolicTraits.contains(.traitItalic)
}

func setBold() -> UIFont
{
    if(isBold)
    {
        return self
    }
    else
    {
        var fontAtrAry = fontDescriptor.symbolicTraits
        fontAtrAry.insert([.traitBold])
        let fontAtrDetails = fontDescriptor.withSymbolicTraits(fontAtrAry)
        return UIFont(descriptor: fontAtrDetails!, size: pointSize)
    }
}

func setItalic()-> UIFont
{
    if(isItalic)
    {
        return self
    }
    else
    {
        var fontAtrAry = fontDescriptor.symbolicTraits
        fontAtrAry.insert([.traitItalic])
        let fontAtrDetails = fontDescriptor.withSymbolicTraits(fontAtrAry)
        return UIFont(descriptor: fontAtrDetails!, size: pointSize)
    }
}
func desetBold() -> UIFont
{
    if(!isBold)
    {
        return self
    }
    else
    {
        var fontAtrAry = fontDescriptor.symbolicTraits
        fontAtrAry.remove([.traitBold])
        let fontAtrDetails = fontDescriptor.withSymbolicTraits(fontAtrAry)
        return UIFont(descriptor: fontAtrDetails!, size: pointSize)
    }
}

func desetItalic()-> UIFont
{
    if(!isItalic)
    {
        return self
    }
    else
    {
        var fontAtrAry = fontDescriptor.symbolicTraits
        fontAtrAry.remove([.traitItalic])
        let fontAtrDetails = fontDescriptor.withSymbolicTraits(fontAtrAry)
        return UIFont(descriptor: fontAtrDetails!, size: pointSize)
    }
}
}