问:
Run-time error when executing SQL in VBA
I am getting Run-time error '-2147217900 (80040e14) Incorrect syntax new '11999999' when trying to pull data in from a SQL server database in to a Recordset in VBA, this is my first time using VBA so forgive the lack of perfection.

My code is as follows;

```<code>Set connection = New ADODB.Connection
Dim newData As ADODB.Recordset

connection.ConnectionString = "my connection string" 'not posting this for security reasons'
connection.Open

Set newData = connectionExecute(BSMARTOpenFaults )
</code>```

I have my query stored as a multiline string as I prefer it becuase it looks better with SQL statements.

```<code>Private Const BSMARTOpenFaults = "select count(*) from call" _
& "where (" _
& "   call_id between 11000000 and 11999999" _
& "or call_id between 12000000 and 12999999" _
& "or call_id between 14000000 and 14999999" _
& "or call_id between 16000000 and 19999999" _
& "or call_id between 26000000 and 26999999" _
& "or call_id between 31000000 and 31999999" _
& "or call_id between 73000000 and 73999999)" _
& "and call_status <> 2 -- all open calls" _
& "and call_type = 'FT'"
</code>```

Judging by the error its falling on the SQL query (or its just a coincedence that the two numbers are the same) but I am not sure on how to fix it because when I run the query on SQL Server Management Studio the query executes and returns a result (21 to be exact) so it is confusing me as to why it won't execute and returns an invalid syntax error when attempting in VBA, is this an incorrect way of formatting SQL statements in VBA?

答:
There are no newlines between the numbers and OR keywords. Your statement looks like :

```<code>and 11999999or call_id between 12000000 and 12999999or and
</code>```

Add a space after the number and/or before the keywords

Body:
I am getting Run-time error '-2147217900 (80040e14) Incorrect syntax new '11999999' when trying to pull data in from a SQL server database in to a Recordset in VBA, this is my first time using VBA so forgive the lack of perfection.

My code is as follows;

Set connection = New ADODB.Connection
Dim newData As ADODB.Recordset

connection.ConnectionString = "my connection string" 'not posting this for security reasons'
connection.Open

Set newData = connectionExecute(BSMARTOpenFaults )

I have my query stored as a multiline string as I prefer it becuase it looks better with SQL statements.

Private Const BSMARTOpenFaults = "select count(*) from call" _
& "where (" _
& "   call_id between 11000000 and 11999999" _
& "or call_id between 12000000 and 12999999" _
& "or call_id between 14000000 and 14999999" _
& "or call_id between 16000000 and 19999999" _
& "or call_id between 26000000 and 26999999" _
& "or call_id between 31000000 and 31999999" _
& "or call_id between 73000000 and 73999999)" _
& "and call_status <> 2 -- all open calls" _
& "and call_type = 'FT'"

Judging by the error its falling on the SQL query (or its just a coincedence that the two numbers are the same) but I am not sure on how to fix it because when I run the query on SQL Server Management Studio the query executes and returns a result (21 to be exact) so it is confusing me as to why it won't execute and returns an invalid syntax error when attempting in VBA, is this an incorrect way of formatting SQL statements in VBA?

Body:
There are no newlines between the numbers and OR keywords. Your statement looks like :

and 11999999or call_id between 12000000 and 12999999or and

Add a space after the number and/or before the keywords


来源: stackexchange

问:
Get rid of visual composer tags when sharing a wordpress page
I have created some pages in wordpress using Visual Composer Plugin. When I try to share those pages on social media sites it shows the visual composer tags as well. Is there any way to get rid of these tags ?

The tags come like

```<code>MY PAGE TITLE
[vc_row type=
my page text
</code>```

答:
The Visual Composer tags are simply arbitrary bits of text that the VS framework picks up and via JavaScript converts into the visual layout that you see.

To demonstrate this edit a page and click the 'Classic Mode' button and this will show you the 'real' content / markup of your page. As a result when sharing the page via social media that network looks for key info to grab for your page to then display.

All the major networks have some form of metadata that they look for first. They use these special tags to see what content you want them to use for your site. If these tags aren't present on your site, they will simply grab content from the page markup. Hence, the Visual Composer tags get picked up.

So, what you need to do is make your site use the necessary metadata / tags for each of the networks, and then populate these fields without these Vis Composer tags.

The easiest way to do this is to use an existing plugin which takes care of this for you. You typically find this in any decent SEO software. You'll in 99.9% of cases want an SEO plugin for WordPress anyway.

By far the most popular and in my experience the best SEO plugin is Yoast SEO. It's a free plugin which not only gives great easy to use SEO tools, it also allows you to set custom description fields for pages/ posts. This means that you can remove the VC tags, and so they will no longer show up on Search Engines and Social Networks. Plus depending on which version you use, you can also customise things on a per social network basis.

Facebook and Twitter etc all use heavy caching against shared content. So, if a page is shared and then edited, the same content will still be shared for a period of time. They don't actually grab live copies every time a page is shared. This can make it a little difficult when developing this side of your site.

Luckily, there is a tool to help with Facebook and here's the one for Twitter.

ContentLicense: CC BY-SA 3.0

Body:
I have created some pages in wordpress using Visual Composer Plugin. When I try to share those pages on social media sites it shows the visual composer tags as well. Is there any way to get rid of these tags ?

The tags come like

MY PAGE TITLE
[vc_row type=
my page text


问:
didSelectRowAtIndexPath in TableViewCell not working
I have TableViewCell.xib file where in each cell there can be summary of data like name, contact etc. Now if I touch the cell it will go to another ViewController where there will be details of that cell's data.(it does not matter what this ViewController shows). I want to go to another ViewController from this xib file's cell touch. how can I do that.

CallHistoryTableViewCell.h

```<code>@interface CallHistoryTableViewCell : UITableViewCell
@property(nonatomic, strong) IBOutlet UILabel *contactName;
@property(nonatomic, strong) IBOutlet UILabel *contactNumber;
@end
</code>```

this class has CallHistoryTableViewCell.xib file.

CallHistoryVC.h

```<code>@interface CallHistoryVC : UIViewController
@end
</code>```

CallHistoryVC.m

```<code>@interface CallHistoryVC ()<UITableViewDelegate, UITableViewDataSource,CallingViewControllerDelegate> {
AppDelegate *appDelegate;

}

@implementation CallHistoryVC

- (void)viewDidLoad {
[super viewDidLoad];
appDelegate = (AppDelegate *)[UIApplication sharedApplication].delegate;

[self defaultViewSetting];
_tView.delegate = self;
_tView.dataSource = self;
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return 1;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
return 75;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return _sortedEventArray.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellIdentifier = @"CallHistoryTableViewCell";

return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
UIStoryboard *mainStoryBoard = [UIStoryboard         storyboardWithName:@"MainStoryboard" bundle:nil];
DetailsOfHistory *storyViewController = [mainStoryBoard instantiateViewControllerWithIdentifier:@"DetailsOfHistory"];
//[self presentViewController:storyViewController animated:YES completion:nil]; //  present it
[self.navigationController pushViewController:storyViewController animated:YES];// or push it

NSLog(@"%ld",(long)indexPath.row);
}
</code>```

Everything works fine but in didSelectRowAtIndexPath indexPath.row is not showing that means touch not working. By click on the cell I want to go to another viewcontroller in stroyboard.

答:
Place a button inside the cell. For the button's action for the IndexPath, use the code below:</p>

```<code>var buttonPosition: CGPoint = sender.convertPoint(CGPointZero, toView: tableview)
let indexpath = tableview.indexPathForRowAtPoint(buttonPosition)
</code>```

Body:
I have TableViewCell.xib file where in each cell there can be summary of data like name, contact etc. Now if I touch the cell it will go to another ViewController where there will be details of that cell's data.(it does not matter what this ViewController shows). I want to go to another ViewController from this xib file's cell touch. how can I do that.

CallHistoryTableViewCell.h

@interface CallHistoryTableViewCell : UITableViewCell
@property(nonatomic, strong) IBOutlet UILabel *contactName;
@property(nonatomic, strong) IBOutlet UILabel *contactNumber;
@end

this class has CallHistoryTableViewCell.xib file.

CallHistoryVC.h

@interface CallHistoryVC : UIViewController
@end

CallHistoryVC.m

@interface CallHistoryVC ()<UITableViewDelegate, UITableViewDataSource,CallingViewControllerDelegate> {
AppDelegate *appDelegate;

}

@implementation CallHistoryVC

- (void)viewDidLoad {
[super viewDidLoad];
appDelegate = (AppDelegate *)[UIApplication sharedApplication].delegate;

[self defaultViewSetting];
_tView.delegate = self;
_tView.dataSource = self;
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return 1;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
return 75;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return _sortedEventArray.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellIdentifier = @"CallHistoryTableViewCell";

return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
UIStoryboard *mainStoryBoard = [UIStoryboard         storyboardWithName:@"MainStoryboard" bundle:nil];
DetailsOfHistory *storyViewController = [mainStoryBoard instantiateViewControllerWithIdentifier:@"DetailsOfHistory"];
//[self presentViewController:storyViewController animated:YES completion:nil]; //  present it
[self.navigationController pushViewController:storyViewController animated:YES];// or push it

NSLog(@"%ld",(long)indexPath.row);
}

Everything works fine but in didSelectRowAtIndexPath indexPath.row is not showing that means touch not working. By click on the cell I want to go to another viewcontroller in stroyboard.

Body:
Place a button inside the cell. For the button's action for the IndexPath, use the code below:

var buttonPosition: CGPoint = sender.convertPoint(CGPointZero, toView: tableview)
let indexpath = tableview.indexPathForRowAtPoint(buttonPosition)


问:
jquery if link = page url
ok pretty simple but i dont know how...

i just want to make an active state (probably just make it bold)

my menu is  ul-li

i cant figure out how to write it so if the url matches with one of the links, make the link bold

please help

thanks for your time

答:
Here's a short way to select links like that:

```<code>$('ul > li a[href$="' + window.location.pathname + '"]').css('font-weight','bold');
</code>```

Or perhaps better like this, which does an exact match of both pathname attributes:

```<code>$('ul > li a[href]').filter(function() {
    return this.href.pathname === window.location.pathname;
}).css('font-weight','bold');
</code>```

If you're using the full domain in the href, you could change it to:

```<code>return this.href === window.location;
</code>```

ContentLicense: CC BY-SA 2.5

Title: jquery if link = page url

Body:
Here's a short way to select links like that:

$('ul > li a[href$="' + window.location.pathname + '"]').css('font-weight','bold');

Or perhaps better like this, which does an exact match of both pathname attributes:

$('ul > li a[href]').filter(function() {
    return this.href.pathname === window.location.pathname;
}).css('font-weight','bold');

If you're using the full domain in the href, you could change it to:

return this.href === window.location;

ContentLicense: CC BY-SA 4.0


问:
How to add "and" before the last element of a list?
I'm making this program and it requires a list to be printed out, I would prefer if the list were a little more correct. I was wondering if it were possible to add an "and" before the last element of a list to make it look right. Thanks. </p>

```<code>  def inputEat(self):
        input('What would you like to eat? Your choices are {}.'.format(', '.join(healthItems)))
        Fighter.Health(x)
        if self.health >= 100:
            self.health = 100`
</code>```

答:
Try this:

Join all the items like you were doing, except the last one.

Explicitly concatenate the last item with and.

input('What would you liketo eat? Your choices are {}.'.format( ', '.join( healthItems[:-1]) + ' and '+healthItems[-1]))

Body:
I'm making this program and it requires a list to be printed out, I would prefer if the list were a little more correct. I was wondering if it were possible to add an "and" before the last element of a list to make it look right. Thanks.

  def inputEat(self):
        input('What would you like to eat? Your choices are {}.'.format(', '.join(healthItems)))
        Fighter.Health(x)
        if self.health >= 100:
            self.health = 100`


问:
How to reset unity accelerometer on Z?
someone can tell me how can I reset my accelerometer.
I have a 3D environment, and my ball bounce left-right correctly, my Y is ok, I don't need it, but my z is not ok, I use my device in landscape mode.
Pratically when my devide is 90° (landscape mode) with the floor is in neutral z position.
I need to have neutral position when user start game, I see other answer on unity blog with they don't work for me.
This is my code :

public float posZ;

```<code>// Use this for initialization
void Start () {
    Salvataggio.control.Load ();
    posZ = Input.acceleration.z;

}
</code>```

void Update () {

```<code>    trovaPallina = GameObject.FindGameObjectWithTag ("Pallina");

        if (trovaPallina) {
            trovaPallina.transform.position += new Vector3(Input.acceleration.x / 10, 0, (Input.acceleration.z - posZ) / 10) ;
        }
</code>```

}

答: Why not create some sort of calibration for it? So, you could create a calibration menu in which you click a button once you are satisfied with the zero position of the device. Store the x, y & z values as your zero values. That way, you can use the current values against your zero values to determine the offset in each direction.</p>

Title: How to reset unity accelerometer on Z?

Body:
someone can tell me how can I reset my accelerometer.
I have a 3D environment, and my ball bounce left-right correctly, my Y is ok, I don't need it, but my z is not ok, I use my device in landscape mode.
Pratically when my devide is 90° (landscape mode) with the floor is in neutral z position.
I need to have neutral position when user start game, I see other answer on unity blog with they don't work for me.
This is my code :

public float posZ;

// Use this for initialization
void Start () {
    Salvataggio.control.Load ();
    posZ = Input.acceleration.z;

}

void Update () {

    trovaPallina = GameObject.FindGameObjectWithTag ("Pallina");

        if (trovaPallina) {
            trovaPallina.transform.position += new Vector3(Input.acceleration.x / 10, 0, (Input.acceleration.z - posZ) / 10) ;
        }

}


答:
You could have a function to construct the joined list the way you want:

```<code>def join_and(items):
    return ', '.join(items[:-1]) + ' and '+items[-1]
</code>```

That is, join all the items except the last with a comma, and then add 'and' before the last item.
(Feel free to add an Oxford comma at your discretion.)

```<code>>>> join_and(['alpha', 'beta', 'gamma'])
'alpha, beta and gamma'
</code>```

If you want the function to give an appropriate result for a list of length 1 or 0, you could do something like this:

```<code>def join_and(items):
    if len(items)==0:
        return ''
    if len(items)==1:
        return items[0]
    return ', '.join(items[:-1]) + ' and '+items[-1]
</code>```

Title: How to add "and" before the last element of a list?

Body:
You could have a function to construct the joined list the way you want:

def join_and(items):
    return ', '.join(items[:-1]) + ' and '+items[-1]

That is, join all the items except the last with a comma, and then add 'and' before the last item.
(Feel free to add an Oxford comma at your discretion.)

>>> join_and(['alpha', 'beta', 'gamma'])
'alpha, beta and gamma'

If you want the function to give an appropriate result for a list of length 1 or 0, you could do something like this:

def join_and(items):
    if len(items)==0:
        return ''
    if len(items)==1:
        return items[0]
    return ', '.join(items[:-1]) + ' and '+items[-1]


问:
Outlook Email via a Webpage
I have a web application developed with ASP.net and C#  that is running on my companies' intranet.  Because all the users for this application are all using Microsoft Outlook without exception, I would like for the the application to open up an Outlook message on the client-side.  I understand that Office is designed to be run on the desktop and not from a server, however I have no trouble creating a Word or Excel document on the client-side.

I have code that instantiates the Outlook object using the Microsoft.Office.Interop.Outlook namespace and Outlook installed on the server.  When I try to run the code from the server, I get a DCOM source error message that states "The machine-default permission settings do not grant Local Activation permission for the COM Server application with CLSID {000C101C-0000-0000-C000-000000000046} to the user This security permission can be modified using the Component Services administrative tool."  I have modified the permissions using the Component Services tool, but still get this same error.

Is there a way to overcome this or is this a fruitless exercise because Outlook cannot be opened on the client side from the server-side code?

Mailto will not work due to the extreme length that the emails can obtain.  Also, the user that sends it needs add in eye-candy to the text for the recipients.

答:
You cannot open something on the client from server side code. You'd have to use script on the page to do what you're wanting (or something else client-side like ActiveX or embedded .NET or something)

Here's a sample Javascript that invokes an Outlook MailItem from an webpage. This could easily be injected into the page from your server-side code so it executes on the client.

http://www.codeproject.com/KB/aspnet/EmailUsingJavascript.aspx

OwnerDisplayName: Keng

Title: Outlook Email via a Webpage

LastEditorDisplayName: Keng

OwnerDisplayName: Ryan Farley

LastEditorDisplayName: Ryan Farley


问:
Database Design: Complex Voting System
I have three tables Feed, Vote and Event.

```<code>Feed
+id
+content
+voteCount  --> hold the number of votes on this feed

Vote
+id
+feedId --> FK to id in Feed
+eventId --> FK to id in Event

Event
+id
+name
+voteCount --> hold the number of votes on this event
</code>```

Both event and feed can be up-voted by user. The Vote table keep track of who has been voting on what since, each only allow to vote once on an event or feed. So here is my problem: when I create an event Y, I will aslo create a feed say X created event Y which will appear on the user X profile. If someone vote on either the feed or event Y, the vote of both the event Y and the vote of the feed that said X created event Y should both be 1.

a. What is the best way to achieve the above?

b. Also if X already vote on the feed that said X created event Y, then he cant vote on event Y anymore and vice versa (since each user can only vote once on an event, and in this case the feed and the event really is the same thing)

答: This data-model treats events and feeds separately, but can record the parent Candidate. The special (?) case of combined votes can be handled in the application layer, by allowing  votes only on the root Candidate WHERE ParentId is NULL.

Title: Database Design: Complex Voting System

Body:
I have three tables Feed, Vote and Event.

Feed
+id
+content
+voteCount  --> hold the number of votes on this feed

Vote
+id
+feedId --> FK to id in Feed
+eventId --> FK to id in Event

Event
+id
+name
+voteCount --> hold the number of votes on this event

Both event and feed can be up-voted by user. The Vote table keep track of who has been voting on what since, each only allow to vote once on an event or feed. So here is my problem: when I create an event Y, I will aslo create a feed say X created event Y which will appear on the user X profile. If someone vote on either the feed or event Y, the vote of both the event Y and the vote of the feed that said X created event Y should both be 1.

a. What is the best way to achieve the above?

b. Also if X already vote on the feed that said X created event Y, then he cant vote on event Y anymore and vice versa (since each user can only vote once on an event, and in this case the feed and the event really is the same thing)


问:
Trying to split array. Working but showing error
I want to split an array in php with explode. My array looks likes this:

```<code>C:\wamp64\www\SC New Skin\functions\get\userItems.php:21:
array (size=1)
  0 =>
    array (size=6)
      0 =>
        array (size=0)
          empty
      1 => string '1,1' (length=3)
      2 => string '2,11' (length=4)
      4 => string '1,8' (length=3)
      5 => string '2,10' (length=4)
      8 => string '1,6' (length=3)
</code>```

I want to split on the ",".

My code looks like this:

```<code>function getItems($array){
    $array = array_unique($array);
    foreach ($array as $key) {
        $var = explode(",", $key);
        echo $var[0];
        echo $var[1] . '<br/>';
    }
}
</code>```

This will work but gives two errors:

Notice: Array to string conversion in C:\wamp64\www\SC New Skin\functions\get\userItems.php on line 20 &
  Warning: explode() expects parameter 2 to be string, array given in C:\wamp64\www\SC New Skin\functions\get\userItems.php on line 22

答:
This may be because the first element of the internal array is also an array, not a string like the other elements:</p>

```<code>0 =>
   array (size=0)
        empty
</code>```

Body:
I want to split an array in php with explode. My array looks likes this:

C:\wamp64\www\SC New Skin\functions\get\userItems.php:21:
array (size=1)
  0 =>
    array (size=6)
      0 =>
        array (size=0)
          empty
      1 => string '1,1' (length=3)
      2 => string '2,11' (length=4)
      4 => string '1,8' (length=3)
      5 => string '2,10' (length=4)
      8 => string '1,6' (length=3)

I want to split on the ",".

My code looks like this:

function getItems($array){
    $array = array_unique($array);
    foreach ($array as $key) {
        $var = explode(",", $key);
        echo $var[0];
        echo $var[1] . '
';
    }
}

This will work but gives two errors:

Notice: Array to string conversion in C:\wamp64\www\SC New Skin\functions\get\userItems.php on line 20 &
  Warning: explode() expects parameter 2 to be string, array given in C:\wamp64\www\SC New Skin\functions\get\userItems.php on line 22

Body:
This may be because the first element of the internal array is also an array, not a string like the other elements:

0 =>
   array (size=0)
        empty


答:
Since there are only four time slots I used a series of nested ifelse statemenst and the hour function from lubridate package</p>

```<code>> data1=read.csv("data1.csv")
> library(lubridate)
> data1$hour=hour(data1$date)
> data1$timeslot=ifelse(data1$hour<6,"12am-6am",data1$hour)
> data1$timeslot=ifelse(6<=data1$hour&data1$hour<12,"6am-12pm",data1$timeslot)
> data1$timeslot=ifelse(12<=data1$hour&data1$hour<18,"12pm-6pm",data1$timeslot)
> data1$timeslot=ifelse(18<=data1$hour&data1$hour<=24,"6pm-12pm",data1$timeslot)
> data1
                     date hour timeslot
1 2016-03-21 16:18:00 IST   16 12pm-6pm
2 2016-04-01 03:12:00 IST    3 12am-6am
3 2016-04-01 14:58:00 IST   14 12pm-6pm
4 2016-04-02 03:24:00 IST    3 12am-6am
5 2016-04-02 19:00:00 IST   19 6pm-12pm
6 2016-04-02 20:40:00 IST   20 6pm-12pm
</code>```

Title: how to cut the time in R

Body:
I have following date time column in R dataframe

date
2016-03-21 16:18:00 IST
2016-04-01 03:12:00 IST
2016-04-01 14:58:00 IST
2016-04-02 03:24:00 IST
2016-04-02 19:00:00 IST
2016-04-02 20:40:00 IST

Date column is in POSIXct format

I want to bucket time in 12am-6am,6am-12pm,12pm-6pm and 6pm-12am

My desired data frame would be

date                        time_bucket
2016-03-21 16:18:00 IST     12pm-6pm
2016-04-01 03:12:00 IST     12am-6am
2016-04-01 14:58:00 IST     12pm-6pm
2016-04-02 03:24:00 IST     12pm-6pm
2016-04-02 19:00:00 IST     6pm-12am
2016-04-02 20:40:00 IST     6pm-12am

How can I do it in r ?

Body:
Since there are only four time slots I used a series of nested ifelse statemenst and the hour function from lubridate package

> data1=read.csv("data1.csv")
> library(lubridate)
> data1$hour=hour(data1$date)
> data1$timeslot=ifelse(data1$hour<6,"12am-6am",data1$hour)
> data1$timeslot=ifelse(6<=data1$hour&data1$hour<12,"6am-12pm",data1$timeslot)
> data1$timeslot=ifelse(12<=data1$hour&data1$hour<18,"12pm-6pm",data1$timeslot)
> data1$timeslot=ifelse(18<=data1$hour&data1$hour<=24,"6pm-12pm",data1$timeslot)
> data1
                     date hour timeslot
1 2016-03-21 16:18:00 IST   16 12pm-6pm
2 2016-04-01 03:12:00 IST    3 12am-6am
3 2016-04-01 14:58:00 IST   14 12pm-6pm
4 2016-04-02 03:24:00 IST    3 12am-6am
5 2016-04-02 19:00:00 IST   19 6pm-12pm
6 2016-04-02 20:40:00 IST   20 6pm-12pm


问:
Where Do I Create External API functions or Classes? Proper MVC Structure for Web Frameworks
I am looking to add multiple API's to my senior project on an MVC based framework (Laravel). I understand the basic concept of MVC, but want to make sure that I am doing things according to best practice.

Basically, I am going to have a class/function that takes a query and calls that query on a Amazon's Product API. I have seen an example of calling API's from directly within the Controller on Laravel (see http://www.phplab.info/categories/laravel/consume-external-api-from-laravel-5-using-guzzle-http-client).

Perhaps I don't understand MVC well enough. Should an external API call be in it's own class? And if so, should it be a Controller Class or a Model Class? I hope the Stack Overflow gurus can enlighten me. Let me know if I need to clarify anything!

答:
It depends to what you want to process with external API.

If it's a part of the business, it can be in Model (lot of people put
the business inside the model to follow the encapsulation principle
of OOP).

If it's the explicit process, it should be in Controller
(like most people do).

For example, if you have a model Transaction in bank transfer (that automatically convert the currency, it needs the external API to get the exchange rate), the external API call should be wrapped in model. So controller cannot modify the Transaction object and it will be safe.

In another hand, you can call to external API in controller, do some extra stuffs then set it back to Transaction object. It's also good because model always contains only properties. It makes application also clear enough.

They are 2 ways of use, none is absolutely right or wrong. But if you choose one, follow it, don't mix.

Another, both 2 are only ok. The better way is putting the external calls to other places (modules etc), then call it by single line in model or controller.


问:
Implementation of a queue in Azure service bus using python
I am an absolute beginner with Service Bus. I want to understand the implementation of a queue using python. The documentation tells me to install Azure Python SDK. I've done that.I made the python file as per instructions, yet I am getting syntax error. I ran the file on the python shell. Did I do that right?
 How do I know that the Azure Package is being used?</p>

答:
As you said, you got a syntax error, it sounds like the issue you got was caused by a Python usage problem, not be related to Azure Service Bus SDK for Python. Without your python code, I don't know what happended in your code. Just as reference, I post some steps for using Azure Python SDK to connect Azure Service Bus.

Install Azure Service Bus SDK for Python via pip in a console. Open a console like CMD on Windows or terminal on Linux, type & enter pip install azure-servicebus if you had installed Python environment and configure it within PATH environment variable. If you were using a linux distribution like Ubuntu, it may be necessary to first type sudo at the front of the pip command.

Copy the servicebus namespace & the primary key for the policy name RootManageSharedAccessKey on Azure portal to be ready for using it in your python script.

Write your python script to connect Service Bus as below.

```<code>from azure.servicebus import ServiceBusService

key_name = 'RootManageSharedAccessKey' # SharedAccessKeyName from Azure portal
key_value = '' # SharedAccessKey from Azure portal
sbs = ServiceBusService(service_namespace,
                    shared_access_key_name=key_name,
                    shared_access_key_value=key_value)
</code>```

Then you can use sbs to do other operations, such as create a queue via sbs.create_queue('taskqueue'), or send message via the code below.

```<code>from azure.servicebus import Message

msg = Message('Hello World!')
sbs.send_queue_message('taskqueue', msg)
</code>```

In the console, you can type python <your script name>.py to run it. If got any error, please update your post to let me know.

You can refer to the documents listed below to know the steps above.

How to use Service Bus queues in Python

How to use Service Bus topics and subscriptions in Python

Introduction for the usage of the service bus in Azure Python SDK

The usage of Python package azure-servicebus

Hope it helps. Any concern, please feel free to let me know.

Body:
As you said, you got a syntax error, it sounds like the issue you got was caused by a Python usage problem, not be related to Azure Service Bus SDK for Python. Without your python code, I don't know what happended in your code. Just as reference, I post some steps for using Azure Python SDK to connect Azure Service Bus.

Install Azure Service Bus SDK for Python via pip in a console. Open a console like CMD on Windows or terminal on Linux, type & enter pip install azure-servicebus if you had installed Python environment and configure it within PATH environment variable. If you were using a linux distribution like Ubuntu, it may be necessary to first type sudo at the front of the pip command.

Copy the servicebus namespace & the primary key for the policy name RootManageSharedAccessKey on Azure portal to be ready for using it in your python script.

Write your python script to connect Service Bus as below.

from azure.servicebus import ServiceBusService

key_name = 'RootManageSharedAccessKey' # SharedAccessKeyName from Azure portal
key_value = '' # SharedAccessKey from Azure portal
sbs = ServiceBusService(service_namespace,
                    shared_access_key_name=key_name,
                    shared_access_key_value=key_value)

Then you can use sbs to do other operations, such as create a queue via sbs.create_queue('taskqueue'), or send message via the code below.

from azure.servicebus import Message

msg = Message('Hello World!')
sbs.send_queue_message('taskqueue', msg)

In the console, you can type python <your script name>.py to run it. If got any error, please update your post to let me know.

You can refer to the documents listed below to know the steps above.

How to use Service Bus queues in Python

How to use Service Bus topics and subscriptions in Python

Introduction for the usage of the service bus in Azure Python SDK

The usage of Python package azure-servicebus

Hope it helps. Any concern, please feel free to let me know.


问:
How to remove the blue underline in TextView (Android)
How can I remove the blue underline that appears on a TextView - Android.

I'm ok with it on a TextField - but in a multi-line TextView - looks weird.

答: Set the color of TextView is the same as background </p>


问:
Is there any shortcut for // MARK: in Xcode like there is for /// <#Description#>?
Is there any keyboard shortcut for '<strong>// MARK:</strong>' in swift like there is for header doc '/// Description' ?  </p>

答:
No there isn't any shortcuts for the //MARK. However, you can create a code snippet for it and re-use whenever and wherever you want.

Steps:

Declare a //MARK statement on top of extension or method

Drag the //MARK into the code snippet section (it's to the left of object library section at bottom right part of Xcode)

You would be asked to create a name for the snippet. Label it appropriately. And that's it.

For usage, Drag and drop this snippet anywhere you want

Body: Is there any keyboard shortcut for '// MARK:' in swift like there is for header doc '/// Description' ?


问:
Vue - webpack vue-loader configuration
I keep getting error whenever I want to build a file. What is a reason of it?
It seems that .vue file is not recognizable by webpack, but webpack configuration file looks properly.
webpack error

```<code>bundle-app.js   189 kB       1  [emitted]  app
    + 12 hidden modules

ERROR in Unexpected token >
 @ ./app/application.js 7:11-31
</code>```

webpack.config.js

```<code>var path = require("path");

module.exports = {
  context: path.join(__dirname, 'src'),
  entry: {
    app: './app/application.js'
  },
  output: {
    path: path.join(__dirname, 'dist'),
    filename: 'bundle-[name].js'
  },
  module: {
    loaders: [
      {
        test: /\.js$/,
        loader: 'babel-loader',
        include: /src/,
        query: {
          presets: ["es2015"]
        }
      },
      {
        test: /\.vue$/,
        loader: 'vue',
      },
    ]
  },
  vue: {
    loaders: {
      js: 'babel'
    }
  }
}
</code>```

package.json

```<code>"devDependencies": {
    "webpack": "~2.2.1",
    "babel-core": "~6.23.1",
    "babel-loader": "~6.3.1",
    "babel-preset-es2015": "~6.22.0",
    "sass-loader": "~6.0.0",
    "node-sass": "~4.5.0",
    "extract-text-webpack-plugin": "~2.0.0-rc.3",
    "vue-template-compiler": "~2.2.4",
    "css-loader": "~0.27.3",
    "vue-loader": "~11.1.4"
  },
  "dependencies": {
    "vue": "~2.2.4"
  }
}
</code>```

app/application.js

```<code>import Vue from 'vue'
import App from './app.vue'

new Vue({
  el: 'body',
  component: { App }
})
</code>```

app/app.vue

```<code><template>
  <div id="app">
  </div>
</template>

<script>

    export default {
      data () {
        return {
          msg: 'Hello from vue-loader!'
        }
      }
    }
</code>```

答:
In projects that use vue, individuals do not recommend configuring webpack and vue-loader separately. You can directly use vue official scaffolding, vue-cli. Do not have to consider these configurations, automatically configured.vue-cli

If you just started learning Vue, here's an entry-level demo. Although it is only a small application, but it covers a lot of knowledge points (vue2.0 + vue-cli + vue-router + vuex + axios + mysql + express + pm2 + webpack), including front-end, back-end, database and other sites Some of the necessary elements, for me, learning great significance, would like to encourage each other!

Vue Demo

Title: Vue - webpack vue-loader configuration

Body:
I keep getting error whenever I want to build a file. What is a reason of it?
It seems that .vue file is not recognizable by webpack, but webpack configuration file looks properly.
webpack error

bundle-app.js   189 kB       1  [emitted]  app
    + 12 hidden modules

ERROR in Unexpected token >
 @ ./app/application.js 7:11-31

webpack.config.js

var path = require("path");

module.exports = {
  context: path.join(__dirname, 'src'),
  entry: {
    app: './app/application.js'
  },
  output: {
    path: path.join(__dirname, 'dist'),
    filename: 'bundle-[name].js'
  },
  module: {
    loaders: [
      {
        test: /\.js$/,
        loader: 'babel-loader',
        include: /src/,
        query: {
          presets: ["es2015"]
        }
      },
      {
        test: /\.vue$/,
        loader: 'vue',
      },
    ]
  },
  vue: {
    loaders: {
      js: 'babel'
    }
  }
}

package.json

"devDependencies": {
    "webpack": "~2.2.1",
    "babel-core": "~6.23.1",
    "babel-loader": "~6.3.1",
    "babel-preset-es2015": "~6.22.0",
    "sass-loader": "~6.0.0",
    "node-sass": "~4.5.0",
    "extract-text-webpack-plugin": "~2.0.0-rc.3",
    "vue-template-compiler": "~2.2.4",
    "css-loader": "~0.27.3",
    "vue-loader": "~11.1.4"
  },
  "dependencies": {
    "vue": "~2.2.4"
  }
}

app/application.js

import Vue from 'vue'
import App from './app.vue'

new Vue({
  el: 'body',
  component: { App }
})

app/app.vue

<template>

</template>


问:
how to append the table body by ajax
I want to Append the tbody of table to already existing table how can i append the table.Actually I want to search the word from whole table .BY javascript and ajax.How can I append the table tbody in search.php page,please get me over this.
 search.php

```<code>   <div >
      <table id="table">
        <thead>
        <th>
        Email
        </th>
        <th>
        Firstname
        </th>
        <th>
        Lastname
        </th>
        <th>
        Companyname
        </th>
        <th>
        Title
        </th>
        <th>
        LinkedinURL
        </th>
        <th>
        Domain
        </th>
        <th>
        Companylocation
        </th>
        <th>
        Companysizecategory
        </th>
        <th>
       Companyfunding
        </th>
        <th>
        Companyindustry
        </th>
        <th>
        Companywebtech
        </th>
        <th>
        DateDownloaded
        </th>
        <th>
        ElucifyAccountID
        </th>
        </thead>

      </table>
      </div>
    </form>
      </div>
    </form>
      </body>
    </html>
    <script>
    $("#search").keyup(function()
    {
     var search=$(this).val();
     $.ajax({
         type:"POST",
         url:"searchajax.php",
         data:{
          ajaxsearch:search,
         },
         success:function(data){

          alert("success");
         },
         error:function(){
          alert('error');
         }

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

ajax.php

```<code>if (!empty($_POST['ajaxsearch']))
{
       $search=$_POST['ajaxsearch'];
$sql="SELECT * from company";
$sql_query=mysql_query($sql);
$logicStr="WHERE ";
$count=mysql_num_fields($sql_query);
for($i=0 ; $i < mysql_num_fields($sql_query) ; $i++){
 if($i == ($count-1) )
$logicStr=$logicStr."".mysql_field_name($sql_query,$i)." LIKE '%".$search."%' ";
else
$logicStr=$logicStr."".mysql_field_name($sql_query,$i)." LIKE '%".$search."%' OR ";
}

$sql="SELECT * from company ".$logicStr;
//echo "SELECT * from company ".$logicStr;
$get=mysql_query($sql);

$i=0;
while($getresult=mysql_fetch_array($get))
  {

    echo '<tbody>';
    echo'<tr>';
    echo '<td>';
     echo $getresult['Email'];
    echo '</td>';
    echo'<td>';
     echo $getresult['Firstname'];
    echo '</td>';
    echo '<td>';
     echo $getresult['Lastname'];
    echo '</td>';
    echo'<td>';
     echo $getresult['Companyname'];
     echo '</td>';
    echo'<td>';
    echo $getresult['Title'];
    echo'</td>';
    echo'<td>';
     echo $getresult['LinkedinURL'];
     echo'</td>';
    echo '<td>';
     echo $getresult['Domain'];
     echo'</td>';
    echo'<td>';
     echo $getresult['CompanyLocation'];
     echo '</td>';
    echo '<td>';
     echo $getresult['Companysizecategory'];
     echo '</td>';
    echo '<td>';
     echo $getresult['Companyfunding']
     echo'</td>';
   echo'<td>';
    echo $getresult['Companyindustry'];
    echo '</td>';
    echo '<td>';
     echo $getresult['companywebtech'];
     echo'</td>';
    echo '<td>';
    echo $getresult['Datedownloaded'];
    echo'</td>';
    echo '<td>';
     echo $getresult['ElucifyAccountID'];
     echo'</td>';
     echo'</tr>';
     echo'</tbody>';

   $i++;
   }
   }
   else
   {
    echo'<script>window.alert("enter valid Data")</script>';
   }
 ?>
</code>```

答:
Try below code:</p>

```<code>$.ajax({
    type:"POST",
    url:"searchajax.php",
    data:{
        ajaxsearch:search,
    },
    success:function(data){
        $('#table thead').insertAfter(data);
    },
    error:function(){
        alert('error');
    }
});
</code>```

Title: how to append the table body by ajax

Body:
I want to Append the tbody of table to already existing table how can i append the table.Actually I want to search the word from whole table .BY javascript and ajax.How can I append the table tbody in search.php page,please get me over this.
 search.php

        Email

        Firstname

        Lastname

        Companyname

        Title

        LinkedinURL

        Domain

        Companylocation

        Companysizecategory

       Companyfunding

        Companyindustry

        Companywebtech

        DateDownloaded

        ElucifyAccountID

    </form>

    </form>

ajax.php

if (!empty($_POST['ajaxsearch']))
{
       $search=$_POST['ajaxsearch'];
$sql="SELECT * from company";
$sql_query=mysql_query($sql);
$logicStr="WHERE ";
$count=mysql_num_fields($sql_query);
for($i=0 ; $i < mysql_num_fields($sql_query) ; $i++){
 if($i == ($count-1) )
$logicStr=$logicStr."".mysql_field_name($sql_query,$i)." LIKE '%".$search."%' ";
else
$logicStr=$logicStr."".mysql_field_name($sql_query,$i)." LIKE '%".$search."%' OR ";
}

$sql="SELECT * from company ".$logicStr;
//echo "SELECT * from company ".$logicStr;
$get=mysql_query($sql);

$i=0;
while($getresult=mysql_fetch_array($get))
  {

    echo '
';
    echo'
';
    echo '';
     echo $getresult['Email'];
    echo '	';
    echo'';
     echo $getresult['Firstname'];
    echo '	';
    echo '';
     echo $getresult['Lastname'];
    echo '	';
    echo'';
     echo $getresult['Companyname'];
     echo '	';
    echo'';
    echo $getresult['Title'];
    echo'	';
    echo'';
     echo $getresult['LinkedinURL'];
     echo'	';
    echo '';
     echo $getresult['Domain'];
     echo'	';
    echo'';
     echo $getresult['CompanyLocation'];
     echo '	';
    echo '';
     echo $getresult['Companysizecategory'];
     echo '	';
    echo '';
     echo $getresult['Companyfunding']
     echo'	';
   echo'';
    echo $getresult['Companyindustry'];
    echo '	';
    echo '';
     echo $getresult['companywebtech'];
     echo'	';
    echo '';
    echo $getresult['Datedownloaded'];
    echo'	';
    echo '';
     echo $getresult['ElucifyAccountID'];
     echo'	';
     echo'
';
     echo'
';

   $i++;
   }
   }
   else
   {
    echo'';
   }
 ?>

Body:
Try below code:

$.ajax({
    type:"POST",
    url:"searchajax.php",
    data:{
        ajaxsearch:search,
    },
    success:function(data){
        $('#table thead').insertAfter(data);
    },
    error:function(){
        alert('error');
    }
});


问:
Sort DRF serializer output of DictField by key
I have a Django Rest Framework serializer that uses a DictField:

```<code>class FlatArticleSerializer(Serializer):
    attributes = DictField(child=FlatArticleAttributeSerializer())
</code>```

The output is all the time different, since the attributes are a dictionary, which is by definition not sorted. Is there a way to sort these in the output nevertheless, alphabetically on string for instance?

答:
Use

```<code>class Meta:
  order_by = (('attributes',))
</code>```

This will sort the data as per the attributes field

Body:
I have a Django Rest Framework serializer that uses a DictField:

class FlatArticleSerializer(Serializer):
    attributes = DictField(child=FlatArticleAttributeSerializer())

The output is all the time different, since the attributes are a dictionary, which is by definition not sorted. Is there a way to sort these in the output nevertheless, alphabetically on string for instance?

Body:
Use

class Meta:
  order_by = (('attributes',))

This will sort the data as per the attributes field


问:
When training seq2seq model with bucketing method do we keep separate RNNs for each bucket?
Let's say we have 3 buckets of different lengths. So do we train 3 different nets?
Can't we keep a dynamic RNN. Where it will add units according to the length of input sequence in the encoder. Then encoder will pass the last hidden state to the decoder. Will it work?

答:
I went through this. Bucketing is help to speed up the training process. We first divide examples in to buckets. Then we can reduce the number of units we have to pad.
In the training iterations we select one bucket at a time and train the whole network.
In the validation we  check the perplexity of the test examples in each bucket.
Tensorflow support this bucketing.

Dynamic RNN is different here we don't have a bucketing mechanism. It we input data as a tensor with the shape of [batch_size,hidden size,max_seq_length].

Here sequences shorter than the maximum length should padded with zeros.

Then it will create dynamic RNNs that their length equal to actual inputs (without padded zeros). This uses a while loop in the tensorflow.


问:
How to render page inside a folder in WPF?
Sorry if my question is confusing what im trying to ask is how can i render a page that is located in a folder

for example:

my MainWindow.xaml is located in the root folder

i want to render a page located in "ProjectName/Pages" inside a

In case you are still confused this

```<code>ProjectName
-- Pages          <--- The page i want to render is in this folder
-- App.config
-- App.xaml
-- MainWndow.xaml <--- i want to render the page here
</code>```

i dont want to have both page and window in the root of the folder, it will look too messy

答:
Add a new Page to your "Pages" folder. Right-click on the folder in the Solution Explorer in Visual Studio and select Add->New Item and then choose a Page and call it "Page1.xaml" or whatever.

You could then display the Page in your window using a Frame like this:

```<code><Window x:Class="WpfApplication1.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        mc:Ignorable="d"
        Title="Window12" Height="300" Width="300">
    <StackPanel>
        <Frame x:Name="frame" Source="/Pages/Page1.xaml" />
    </StackPanel>
</Window>
</code>```

Body:
Sorry if my question is confusing what im trying to ask is how can i render a page that is located in a folder

for example:

my MainWindow.xaml is located in the root folder

i want to render a page located in "ProjectName/Pages" inside a

In case you are still confused this

ProjectName
-- Pages          <--- The page i want to render is in this folder
-- App.config
-- App.xaml
-- MainWndow.xaml <--- i want to render the page here

i dont want to have both page and window in the root of the folder, it will look too messy

Body:
Add a new Page to your "Pages" folder. Right-click on the folder in the Solution Explorer in Visual Studio and select Add->New Item and then choose a Page and call it "Page1.xaml" or whatever.

You could then display the Page in your window using a Frame like this:

<Window x:Class="WpfApplication1.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        mc:Ignorable="d"
        Title="Window12" Height="300" Width="300">
    <StackPanel>
        <Frame x:Name="frame" Source="/Pages/Page1.xaml" />
    </StackPanel>
</Window>


问:
How to I Pull to refresh in webview
I am new learning.

I made a UIWebView on Xcode.

Refresh Code simulator is working but not working on the phone.
How to ı can run?

Here is code

```<code>-(void)viewDidLoad {
     NSString *fullURL = @"http://mysite.com.tr/report";
     NSURL *url = [NSURL URLWithString:fullURL];
     NSURLRequest *requestObj = [NSURLRequest requestWithURL:url];
     webView.delegate = (id)self;
     [webView loadRequest:requestObj];

     UIRefreshControl *refreshControl = [[UIRefreshControl alloc] init];
     [refreshControl addTarget:self action:@selector(handleRefresh:) forControlEvents:UIControlEventValueChanged];
     [webView.scrollView addSubview:refreshControl];
}

-(void)handleRefresh:(UIRefreshControl *)refresh {

    // Reload my data

    NSString *fullURL = @"http://mysite.com.tr/report";
    NSURL *url = [NSURL URLWithString:fullURL];
    NSURLRequest *requestObj = [NSURLRequest requestWithURL:url];
    [webView loadRequest:requestObj];
    [refresh endRefreshing];
    [super viewDidLoad];

}
</code>```

答:
Your code is working fine.
remove

```<code> [super viewDidLoad];
</code>```

And in info.plist file add a property.

Note: Allow arbitrary Loads to YES is not recommended though.Hope you'll figure it out by yourself.

Title: How to I Pull to refresh in webview

Body:
I am new learning.

I made a UIWebView on Xcode.

Refresh Code simulator is working but not working on the phone.
How to ı can run?

Here is code

-(void)viewDidLoad {
     NSString *fullURL = @"http://mysite.com.tr/report";
     NSURL *url = [NSURL URLWithString:fullURL];
     NSURLRequest *requestObj = [NSURLRequest requestWithURL:url];
     webView.delegate = (id)self;
     [webView loadRequest:requestObj];

     UIRefreshControl *refreshControl = [[UIRefreshControl alloc] init];
     [refreshControl addTarget:self action:@selector(handleRefresh:) forControlEvents:UIControlEventValueChanged];
     [webView.scrollView addSubview:refreshControl];
}

-(void)handleRefresh:(UIRefreshControl *)refresh {

    // Reload my data

    NSString *fullURL = @"http://mysite.com.tr/report";
    NSURL *url = [NSURL URLWithString:fullURL];
    NSURLRequest *requestObj = [NSURLRequest requestWithURL:url];
    [webView loadRequest:requestObj];
    [refresh endRefreshing];
    [super viewDidLoad];

}

Body:
Your code is working fine.
remove

 [super viewDidLoad];

And in info.plist file add a property.

Note: Allow arbitrary Loads to YES is not recommended though.Hope you'll figure it out by yourself.


问:
Java libraries for converting between character encodings
The problem I am looking to solve is converting between unicode storage types. As I understand it, one character in UTF-8 can be represented by 1 to 4 bytes of data whereas a character in UTF-16 can be represented in 1-2, two bytes blocks of data. This variable length means it's a pain to convert between the two and produce something that is sensible in the english language. </p>

<p>What I am looking for is a library that would let me specify a language or locale, and a storage mechanism (utf-8 etc.) and have it produce a more sensible result. Am I dreaming in the clouds?  </p>

答:
Is String.getBytes(String charsetname) not sufficient?

http://download.oracle.com/javase/1.5.0/docs/api/java/lang/String.html#getBytes(java.lang.String)

It lets you get the raw bytes of a String in a particular encoding.

String has a [constructor][2] that will take a byte array and charset name as well, so you can use that for decoding.

[2]: http://download.oracle.com/javase/1.5.0/docs/api/java/lang/String.html#String(byte[], java.lang.String)

Body:
The problem I am looking to solve is converting between unicode storage types. As I understand it, one character in UTF-8 can be represented by 1 to 4 bytes of data whereas a character in UTF-16 can be represented in 1-2, two bytes blocks of data. This variable length means it's a pain to convert between the two and produce something that is sensible in the english language.

What I am looking for is a library that would let me specify a language or locale, and a storage mechanism (utf-8 etc.) and have it produce a more sensible result. Am I dreaming in the clouds?


问:
How do I apply border bottom to more than one line of text?
I'm using border-bottom for all the CATs on my website. Great when it a word or two. On trying to apply it to a CTA that's more than a sentence, the words break on mobile and the border-bottom only affects the last line of the sentence. How do I make the border-bottom affect the lines of text? I don't want to use underline for the sake of transition on hover, and the fact that underlines does not give my the 1px border I want.

See images for desktop, mobile and tab here

答:
That transition may be applied on the pseudo element  ::before or ::after that is not underline for text.

div
{
text-decoration:underline;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div>
Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an</div></code>```

underline for all words... hope this works

Body:
That transition may be applied on the pseudo element  ::before or ::after that is not underline for text.

div
{
text-decoration:underline;
}

<div>
Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an</div>

underline for all words... hope this works


问:
@Mention using Multiautocompletetextview

What i want to do

i want to mention both people and group in a chat activity.when the user types @ i want populate the list which contains no of user and channels
so that he can mention both people and channels

What i have done

i took help from this question Android: Autocomplete TextView Similar To The Facebook App
here i have included my code

1.Arraylist which has users

```<code>   ArrayList<People> users = new ArrayList<User>();
        for (People user : SocketSingleton.userMap.values()) {
            if (user.getId() != loggedUserId) {
                users.add(user);
            }
        }
</code>```

2.Arraylist which has groups list

```<code>ArrayList<Group> groups = new ArrayList<Group>();
        for (Group channel : SocketSingleton.listgroups.values()) {
            groups.add(channel);
        }
</code>```

3.Adapters for view

```<code>final UserAdapter Adapter = new UserAdapter(getActivity(), R.layout.all_user_list_item, users);

final GroupAdapter Adapter1 = new GroupAdapter(getActivity(), R.layout.all_groups_list_item, Groups);
</code>```

4.MultiAutocompletetextview

```<code>textinput = (MultiAutoCompleteTextView) view.findViewById(R.id.message_input);
        textinput.setAdapter(Adapter);
        textinput.setThreshold(0);

        textinput.setTokenizer(new MultiAutoCompleteTextView.Tokenizer() {

            @Override
            public CharSequence terminateToken(CharSequence text) {
                int i = text.length();

                while (i > 0 && text.charAt(i - 1) == ' ') {
                    i--;
                }

                if (i > 0 && text.charAt(i - 1) == ' ') {
                    return text;
                } else {
                    if (text instanceof Spanned) {
                        SpannableString sp = new SpannableString(text + " ");
                        TextUtils.copySpansFrom((Spanned) text, 0, text.length(), Object.class, sp, 0);
                        return sp;
                    } else {
                        return text + " ";
                    }
                }
            }

            @Override
            public int findTokenStart(CharSequence text, int cursor) {
                int i = cursor;

                while (i > 0 && text.charAt(i - 1) != '@') {
                    i--;
                }

                //Check if token really started with @, else we don't have a valid token
                if (i < 1 || text.charAt(i - 1) != '@') {
                    return cursor;
                }

                return i;
            }

            @Override
            public int findTokenEnd(CharSequence text, int cursor) {
                int i = cursor;
                int len = text.length();

                while (i < len) {
                    if (text.charAt(i) == ' ') {
                        return i;
                    } else {
                        i++;
                    }
                }

                return len;
            }
        });
        textinput.addTextChangedListener(new TextWatcher() {

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                Layout layout = textinput.getLayout();
                int pos = textinput.getSelectionStart();
                int line = layout.getLineForOffset(pos);
                int baseline = layout.getLineBaseline(line);

                int bottom = textinput.getHeight();

                textinput.setDropDownVerticalOffset(baseline - bottom);

            }

            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void afterTextChanged(Editable s) {
            }
        });
        textinput.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int id, KeyEvent event) {
                if (id == R.id.send || id == EditorInfo.IME_NULL) {
                    messageSend();
                    return true;
                }
                return false;
            }
        });
</code>```

Problem i have

with this code i can able to mention only people. i can only set either adapter1 or adapter2 for Autocomplete tectview. So it is only displaying either users or groups.
i want to display all list in single adapter so that the user can mention peoples and groups
i am new to this please help me to find a way

答:
There is no built in support for multiple data types with MultiAutoCompleteTextView. However there are several open source libraries that allow you to do just that.
I've had the same requirement in the project I'm working on and here is our open source solution, feel free to check it out:
https://github.com/Teamwork/android-multiautocomplete

You can achieve that by doing this:

```<code>MultiAutoComplete autoComplete = new MultiAutoComplete.Builder()
    ...
    .addTypeAdapter(typeAdapter1)
    .addTypeAdapter(typeAdapter2)
    .build();
</code>```

You can also specify the type of filter and handle ('@' or '#' or any other) you want to use for each type adapter.

Body:
What i want to do

i want to mention both people and group in a chat activity.when the user types @ i want populate the list which contains no of user and channels
so that he can mention both people and channels

What i have done

i took help from this question Android: Autocomplete TextView Similar To The Facebook App
here i have included my code

1.Arraylist which has users

   ArrayList<People> users = new ArrayList<User>();
        for (People user : SocketSingleton.userMap.values()) {
            if (user.getId() != loggedUserId) {
                users.add(user);
            }
        }

2.Arraylist which has groups list

ArrayList<Group> groups = new ArrayList<Group>();
        for (Group channel : SocketSingleton.listgroups.values()) {
            groups.add(channel);
        }

3.Adapters for view

final UserAdapter Adapter = new UserAdapter(getActivity(), R.layout.all_user_list_item, users);

final GroupAdapter Adapter1 = new GroupAdapter(getActivity(), R.layout.all_groups_list_item, Groups);

4.MultiAutocompletetextview

textinput = (MultiAutoCompleteTextView) view.findViewById(R.id.message_input);
        textinput.setAdapter(Adapter);
        textinput.setThreshold(0);

        textinput.setTokenizer(new MultiAutoCompleteTextView.Tokenizer() {

            @Override
            public CharSequence terminateToken(CharSequence text) {
                int i = text.length();

                while (i > 0 && text.charAt(i - 1) == ' ') {
                    i--;
                }

                if (i > 0 && text.charAt(i - 1) == ' ') {
                    return text;
                } else {
                    if (text instanceof Spanned) {
                        SpannableString sp = new SpannableString(text + " ");
                        TextUtils.copySpansFrom((Spanned) text, 0, text.length(), Object.class, sp, 0);
                        return sp;
                    } else {
                        return text + " ";
                    }
                }
            }

            @Override
            public int findTokenStart(CharSequence text, int cursor) {
                int i = cursor;

                while (i > 0 && text.charAt(i - 1) != '@') {
                    i--;
                }

                //Check if token really started with @, else we don't have a valid token
                if (i < 1 || text.charAt(i - 1) != '@') {
                    return cursor;
                }

                return i;
            }

            @Override
            public int findTokenEnd(CharSequence text, int cursor) {
                int i = cursor;
                int len = text.length();

                while (i < len) {
                    if (text.charAt(i) == ' ') {
                        return i;
                    } else {
                        i++;
                    }
                }

                return len;
            }
        });
        textinput.addTextChangedListener(new TextWatcher() {

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                Layout layout = textinput.getLayout();
                int pos = textinput.getSelectionStart();
                int line = layout.getLineForOffset(pos);
                int baseline = layout.getLineBaseline(line);

                int bottom = textinput.getHeight();

                textinput.setDropDownVerticalOffset(baseline - bottom);

            }

            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void afterTextChanged(Editable s) {
            }
        });
        textinput.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int id, KeyEvent event) {
                if (id == R.id.send || id == EditorInfo.IME_NULL) {
                    messageSend();
                    return true;
                }
                return false;
            }
        });

Problem i have

with this code i can able to mention only people. i can only set either adapter1 or adapter2 for Autocomplete tectview. So it is only displaying either users or groups.
i want to display all list in single adapter so that the user can mention peoples and groups
i am new to this please help me to find a way

Body:
There is no built in support for multiple data types with MultiAutoCompleteTextView. However there are several open source libraries that allow you to do just that.
I've had the same requirement in the project I'm working on and here is our open source solution, feel free to check it out:
https://github.com/Teamwork/android-multiautocomplete

You can achieve that by doing this:

MultiAutoComplete autoComplete = new MultiAutoComplete.Builder()
    ...
    .addTypeAdapter(typeAdapter1)
    .addTypeAdapter(typeAdapter2)
    .build();

You can also specify the type of filter and handle ('@' or '#' or any other) you want to use for each type adapter.


问:
Date and time in UTC - how to store them in postgres?
I am getting my data: date and time in UTC, in a csv file format in separate columns. Since I will need to convert this zone to date and time of the place where I live, currently in summer to UTC+2, and maybe some other zones I was wondering what is the best practice to insert data in postgres when we are talking about type of data. Should I place both of my data in a single column or keep them separate as types: date and time, and if not should I use timestamp or timestampz (or something else).</p>

答:
use timestamptz it will store your time stamp in UTC. and will display it to the client according to it's locale.

https://www.postgresql.org/docs/current/static/datatype-datetime.html

For timestamp with time zone, the internally stored value is always in
  UTC (Universal Coordinated Time, traditionally known as Greenwich Mean
  Time, GMT). An input value that has an explicit time zone specified is
  converted to UTC using the appropriate offset for that time zone. If
  no time zone is stated in the input string, then it is assumed to be
  in the time zone indicated by the system's TimeZone parameter, and is
  converted to UTC using the offset for the timezone zone.

When a timestamp with time zone value is output, it is always
  converted from UTC to the current timezone zone, and displayed as
  local time in that zone. To see the time in another time zone, either
  change timezone or use the AT TIME ZONE construct (see Section 9.9.3).

updated with another good point from Lukasz, I had to mention:

Also in favor of single column is the fact that if you would store
  both date and time in separate columns you would still need to combine
  them and convert to timestamp if you wanted to change time zone of
  date.

Not doing that would lead to date '2017-12-31' with time '23:01:01' would in other time zone in fact be not only different time, but different date with all YEAR and MONTH and DAY different

another update As per Laurenz notice, don't forget the above docs quote
An input value that has an explicit time zone specified is converted to UTC using the appropriate offset for that time zone. Which means you have to manage the input dates carefully. Eg:

```<code>t=# create table t(t timestamptz);
CREATE TABLE
t=# set timezone to 'GMT+5';
SET
t=# insert into t select '2017-01-01 00:00:00';
INSERT 0 1
t=# insert into t select '2017-01-01 00:00:00' at time zone 'UTC';
INSERT 0 1
t=# insert into t select '2017-01-01 00:00:00+02';
INSERT 0 1
t=# select * from t;
           t
------------------------
 2017-01-01 00:00:00-05
 2017-01-01 05:00:00-05
 2016-12-31 17:00:00-05
(3 rows)
</code>```

Body:
use timestamptz it will store your time stamp in UTC. and will display it to the client according to it's locale.

https://www.postgresql.org/docs/current/static/datatype-datetime.html

For timestamp with time zone, the internally stored value is always in
  UTC (Universal Coordinated Time, traditionally known as Greenwich Mean
  Time, GMT). An input value that has an explicit time zone specified is
  converted to UTC using the appropriate offset for that time zone. If
  no time zone is stated in the input string, then it is assumed to be
  in the time zone indicated by the system's TimeZone parameter, and is
  converted to UTC using the offset for the timezone zone.

When a timestamp with time zone value is output, it is always
  converted from UTC to the current timezone zone, and displayed as
  local time in that zone. To see the time in another time zone, either
  change timezone or use the AT TIME ZONE construct (see Section 9.9.3).

updated with another good point from Lukasz, I had to mention:

Also in favor of single column is the fact that if you would store
  both date and time in separate columns you would still need to combine
  them and convert to timestamp if you wanted to change time zone of
  date.

Not doing that would lead to date '2017-12-31' with time '23:01:01' would in other time zone in fact be not only different time, but different date with all YEAR and MONTH and DAY different

another update As per Laurenz notice, don't forget the above docs quote
An input value that has an explicit time zone specified is converted to UTC using the appropriate offset for that time zone. Which means you have to manage the input dates carefully. Eg:

t=# create table t(t timestamptz);
CREATE TABLE
t=# set timezone to 'GMT+5';
SET
t=# insert into t select '2017-01-01 00:00:00';
INSERT 0 1
t=# insert into t select '2017-01-01 00:00:00' at time zone 'UTC';
INSERT 0 1
t=# insert into t select '2017-01-01 00:00:00+02';
INSERT 0 1
t=# select * from t;
           t
------------------------
 2017-01-01 00:00:00-05
 2017-01-01 05:00:00-05
 2016-12-31 17:00:00-05
(3 rows)


问:
Linux CSV - Add a colum from a CSV file to another CSV File
I'm struggling to create a CSV file from two other ones

Here's what I need

File I want (lot of others lines)

"AB";"A";"B";"C";"D";"E"

Files I have:

File 1:
"A";"B";"C";"D";"E"

File 2:
"AB";"C";"D";"E"

How can I simply add "AB" from File to the 1st position of 1st one, adding one ";" ?

Thanks for your help

答:
You can use awk as below. This assumes that you have only ; character as the field separator. And it is not used anywhere else in the CSV file.

```<code>$ awk -F\; '{print $2}' file.csv
</code>```

Body:
You can use awk as below. This assumes that you have only ; character as the field separator. And it is not used anywhere else in the CSV file.

$ awk -F\; '{print $2}' file.csv


问:
Guarantee that flycheck-mode appears in first position in the mode line
When coding in not too wide buffer flycheck errors tally that should be visible in line-mode gets truncated. How do I guarantee that flycheck mode tally comes first in the order of major/minor modes in line-mode?</p>

答:
The minor modes are displayed in the order of minor-mode-alist.  By default this simply reflects the load order (hence the kind-of-workaround you noted, but noting that the workaround would fail once additional minor modes were loaded).

Manipulating the list after libraries are loaded lets you maintain a desired display order on an ongoing basis.

(defun my-promote-flycheck (&optional _file)
  "Give `flycheck-mode' priority position in `minor-mode-alist'.

Called via `after-load-functions', as well as `after-init-hook'."
  (unless (eq (caar minor-mode-alist) 'flycheck-mode)
    (let ((found (assq 'flycheck-mode minor-mode-alist)))
      (when found
        (assq-delete-all 'flycheck-mode minor-mode-alist)
        (push found minor-mode-alist)))))

(add-hook 'after-load-functions 'my-promote-flycheck)
(add-hook 'after-init-hook 'my-promote-flycheck)
```


问:
Composer Authentication with DataPower as OAuth Provider
I have been reviewing this Hyperledger Composer tutorial https://hyperledger.github.io/composer/integrating/enabling-rest-authentication.html. Is it possible to use the IBM DataPower Gateway as the OAuth provider?</p>

答: it should be possible to use IBM DataPower Gateway as the OAuth Provider</p>


问:
How to solve the object issue in clickable state field in odoo10?
I have a model with clickable selection field

*****py*****

```<code>state = fields.Selection([('new', 'New'), ('in_progress', 'In Progress'), ('done', 'Done')], default='new')
</code>```

*****xml*****

```<code>field name="state" widget="statusbar" clickable="True"
</code>```

****function****

```<code>@api.onchange('state')
def onchange_state(self):
    print self
</code>```

****notes****

it  printes like this

****** odoo.models.NewId object at 0x7f624b7b7b90******

questions

is it possible to get the id of the record based on this clickable
  selection field in onchange event?

答:
If statusbar is clickable then onchange method won't call. It will
  directly call write method.

In onchange method, you will get id of record from "_origin" parameter, if record is already created.

Try following:

```<code>@api.onchange('state')
def onchange_state(self):
    record_id = self._origin.id
    #your code
</code>```

Body:
I have a model with clickable selection field

*****py*****

state = fields.Selection([('new', 'New'), ('in_progress', 'In Progress'), ('done', 'Done')], default='new')

*****xml*****

field name="state" widget="statusbar" clickable="True"

****function****

@api.onchange('state')
def onchange_state(self):
    print self

****notes****

it  printes like this

****** odoo.models.NewId object at 0x7f624b7b7b90******

questions

is it possible to get the id of the record based on this clickable
  selection field in onchange event?

Body:
If statusbar is clickable then onchange method won't call. It will
  directly call write method.

In onchange method, you will get id of record from "_origin" parameter, if record is already created.

Try following:

@api.onchange('state')
def onchange_state(self):
    record_id = self._origin.id
    #your code


问:
Realistic use case for cursors?
I read both the Microsoft Docs and this article. I however can't seem to find where I could only use cursors and not something else so I'd appreciate If someone could give a few examples.

I also came across this answer on stackoverflow and Jeffrey Hantin gave me more doubts.

答:
Imagine a command which must get a literal parameter like BCP.

Try to read 100 XML files living somewhere on your disc and you have their path and filenames in a table.

In this case you will create the statements dynamically and use EXEC to run each separately.

This might be any kind of loop, but a CURSOR seems to be the closest.

The general answer is: Avoid loops, most needs can be solved without using a loop. With SQL one should use set-based approaches over procedural approaches.

Title: Realistic use case for cursors?


问:
Run-time error when executing SQL in VBA
I am getting Run-time error '-2147217900 (80040e14) Incorrect syntax new '11999999' when trying to pull data in from a SQL server database in to a Recordset in VBA, this is my first time using VBA so forgive the lack of perfection.

My code is as follows;

```<code>Set connection = New ADODB.Connection
Dim newData As ADODB.Recordset

connection.ConnectionString = "my connection string" 'not posting this for security reasons'
connection.Open

Set newData = connectionExecute(BSMARTOpenFaults )
</code>```

I have my query stored as a multiline string as I prefer it becuase it looks better with SQL statements.

```<code>Private Const BSMARTOpenFaults = "select count(*) from call" _
& "where (" _
& "   call_id between 11000000 and 11999999" _
& "or call_id between 12000000 and 12999999" _
& "or call_id between 14000000 and 14999999" _
& "or call_id between 16000000 and 19999999" _
& "or call_id between 26000000 and 26999999" _
& "or call_id between 31000000 and 31999999" _
& "or call_id between 73000000 and 73999999)" _
& "and call_status <> 2 -- all open calls" _
& "and call_type = 'FT'"
</code>```

Judging by the error its falling on the SQL query (or its just a coincedence that the two numbers are the same) but I am not sure on how to fix it because when I run the query on SQL Server Management Studio the query executes and returns a result (21 to be exact) so it is confusing me as to why it won't execute and returns an invalid syntax error when attempting in VBA, is this an incorrect way of formatting SQL statements in VBA?

答:
Don't skip the spaces at the end of each section of the string. At the moment your string returns:

```<code>select count(*) from callwhere (...
</code>```

And callwhere is probably not a table in your schema. Same issue is there for the OR clauses. Try this:

```<code>Private Const BSMARTOpenFaults = "select count(*) from call " _
& "where (" _
& "   call_id between 11000000 and 11999999 " _
& "or call_id between 12000000 and 12999999 " _
& "or call_id between 14000000 and 14999999 " _
& "or call_id between 16000000 and 19999999 " _
& "or call_id between 26000000 and 26999999 " _
& "or call_id between 31000000 and 31999999 " _
& "or call_id between 73000000 and 73999999) " _
& "and call_status <> 2 " _
& "and call_type = 'FT'"
</code>```

Body:
I am getting Run-time error '-2147217900 (80040e14) Incorrect syntax new '11999999' when trying to pull data in from a SQL server database in to a Recordset in VBA, this is my first time using VBA so forgive the lack of perfection.

My code is as follows;

Set connection = New ADODB.Connection
Dim newData As ADODB.Recordset

connection.ConnectionString = "my connection string" 'not posting this for security reasons'
connection.Open

Set newData = connectionExecute(BSMARTOpenFaults )

I have my query stored as a multiline string as I prefer it becuase it looks better with SQL statements.

Private Const BSMARTOpenFaults = "select count(*) from call" _
& "where (" _
& "   call_id between 11000000 and 11999999" _
& "or call_id between 12000000 and 12999999" _
& "or call_id between 14000000 and 14999999" _
& "or call_id between 16000000 and 19999999" _
& "or call_id between 26000000 and 26999999" _
& "or call_id between 31000000 and 31999999" _
& "or call_id between 73000000 and 73999999)" _
& "and call_status <> 2 -- all open calls" _
& "and call_type = 'FT'"

Judging by the error its falling on the SQL query (or its just a coincedence that the two numbers are the same) but I am not sure on how to fix it because when I run the query on SQL Server Management Studio the query executes and returns a result (21 to be exact) so it is confusing me as to why it won't execute and returns an invalid syntax error when attempting in VBA, is this an incorrect way of formatting SQL statements in VBA?

Body:
Don't skip the spaces at the end of each section of the string. At the moment your string returns:

select count(*) from callwhere (...

And callwhere is probably not a table in your schema. Same issue is there for the OR clauses. Try this:

Private Const BSMARTOpenFaults = "select count(*) from call " _
& "where (" _
& "   call_id between 11000000 and 11999999 " _
& "or call_id between 12000000 and 12999999 " _
& "or call_id between 14000000 and 14999999 " _
& "or call_id between 16000000 and 19999999 " _
& "or call_id between 26000000 and 26999999 " _
& "or call_id between 31000000 and 31999999 " _
& "or call_id between 73000000 and 73999999) " _
& "and call_status <> 2 " _
& "and call_type = 'FT'"


问:
Token in permissions dissapears using documentdb and xamarin forms
I am trying to send permissions for documentdb for a specific user from my azure server to my client app, which are xamarin forms.

On server side everything looks good and I can see users specific permissions and token.

But when permissions are received in the client, the token is stripped away, why?
I am new with documentdb so hopefully it is just me.

I am using an Azure Mobile App service as backend.
My backend controller returns an object holding properties for documentdb database including a list of permissions for the user.

```<code>    public class DbConfig
{
    public string DatabaseName { get; set; }
    public string CollectionId { get; set; }
    public string EndpointUri { get; set; }
    public IList<Permission> Permissions { get; set; }

}
</code>```

I create a permission for a user for the entire collection if not already created.

```<code>        public async Task<Permission> CreatePermissionAsync(string resourceLink, string userLink, PermissionMode mode, string resourcePartitionKey = null)
    {
        try
        {

            Permission permission = new Permission
            {
                Id = Guid.NewGuid().ToString("N"),
                PermissionMode = mode,
                ResourceLink = resourceLink
            };

            if (resourcePartitionKey != null)
            {
                permission.ResourcePartitionKey = new PartitionKey(resourcePartitionKey);
            }

            var result = await client.CreatePermissionAsync(userLink, permission);
            DbConfig.Permissions.Add(result);
            return result;
        }
        catch (Exception e)
        {
            Trace.WriteLine($"##### Exception: {e}");
            throw;
        }
    }
</code>```

I retrieve permissions for a user with this method.

```<code>        public List<Permission> GetPermissionsForUserPermissionLink(User user)
    {
        var permFeed = client.CreatePermissionQuery(user.PermissionsLink);
        List<Permission> permList = new List<Permission>();

        foreach (Permission perm in permFeed)
        {
            permList.Add(perm);
            DbConfig.Permissions.Add(perm);
        }

        return permList;
    }
</code>```

On the client side in my Xamarin forms app i use this call to my custom controller in the backend.

```<code>var parameters = new Dictionary<string, string> { { "userid", Settings.AzureUserId } };
dbConfig = await client.InvokeApiAsync<DbConfig>("Settings", HttpMethod.Get, parameters);
</code>```

When i look at the permissionlist in the dbConfig object the token for a permission is null. My thought was that I could instantiate a documentdb client based on the permissionslist but it fails.

```<code>        public void CreateDocumentDbClient(DbConfig config)
    {
        client = new DocumentClient(new Uri(config.EndPointUri), config.Permissions);
        collectionLink = UriFactory.CreateDocumentCollectionUri(config.DatabaseName, config.CollectionId);
        IsInitialized = true;
    }
</code>```

EDITS MADE FROM ANSWER

Just for finish up upon question.
I created a custom class holding both Permission and Token

```<code>    public class PermissionCustom
{
    public Permission  Permission { get; set; }
    public string Token { get; set; }
}
</code>```

This makes it possible to create a documentdb client like this:

```<code>client = new DocumentClient(new Uri(config.EndPointUri), config.Permissions[0].Token);
</code>```

So far so good :-) but it doesn't makes it easier to secure your database considering users could have many permissions for different resources. Even though it is properly to make it more secure, the token is readonly in the first place.

答:
According to your code, I have checked this issue and found I could encounter the same issue. When you invoke client.InvokeApiAsync<DbConfig>("Settings", HttpMethod.Get, parameters);, you would send request with the following link:

https://{your-app-name}.azurewebsites.net/api/settings?userid={Settings.AzureUserId}

By using fiddler you could find that the token has been sent to your mobile client as follows:

But when deserialize it to Permission, the token has not been initialized correctly. I found that the token property is read only as follows:

In summary, I recommend that you need to define your custom Permission class and refer to the Permission class provided by DocumentDB client SDK for defining the properties you need within your custom permission class in your mobile client.

Body:
I am trying to send permissions for documentdb for a specific user from my azure server to my client app, which are xamarin forms.

On server side everything looks good and I can see users specific permissions and token.

But when permissions are received in the client, the token is stripped away, why?
I am new with documentdb so hopefully it is just me.

I am using an Azure Mobile App service as backend.
My backend controller returns an object holding properties for documentdb database including a list of permissions for the user.

    public class DbConfig
{
    public string DatabaseName { get; set; }
    public string CollectionId { get; set; }
    public string EndpointUri { get; set; }
    public IList<Permission> Permissions { get; set; }

}

I create a permission for a user for the entire collection if not already created.

        public async Task<Permission> CreatePermissionAsync(string resourceLink, string userLink, PermissionMode mode, string resourcePartitionKey = null)
    {
        try
        {

            Permission permission = new Permission
            {
                Id = Guid.NewGuid().ToString("N"),
                PermissionMode = mode,
                ResourceLink = resourceLink
            };

            if (resourcePartitionKey != null)
            {
                permission.ResourcePartitionKey = new PartitionKey(resourcePartitionKey);
            }

            var result = await client.CreatePermissionAsync(userLink, permission);
            DbConfig.Permissions.Add(result);
            return result;
        }
        catch (Exception e)
        {
            Trace.WriteLine($"##### Exception: {e}");
            throw;
        }
    }

I retrieve permissions for a user with this method.

        public List<Permission> GetPermissionsForUserPermissionLink(User user)
    {
        var permFeed = client.CreatePermissionQuery(user.PermissionsLink);
        List<Permission> permList = new List<Permission>();

        foreach (Permission perm in permFeed)
        {
            permList.Add(perm);
            DbConfig.Permissions.Add(perm);
        }

        return permList;
    }

On the client side in my Xamarin forms app i use this call to my custom controller in the backend.

var parameters = new Dictionary<string, string> { { "userid", Settings.AzureUserId } };
dbConfig = await client.InvokeApiAsync<DbConfig>("Settings", HttpMethod.Get, parameters);

When i look at the permissionlist in the dbConfig object the token for a permission is null. My thought was that I could instantiate a documentdb client based on the permissionslist but it fails.

        public void CreateDocumentDbClient(DbConfig config)
    {
        client = new DocumentClient(new Uri(config.EndPointUri), config.Permissions);
        collectionLink = UriFactory.CreateDocumentCollectionUri(config.DatabaseName, config.CollectionId);
        IsInitialized = true;
    }

EDITS MADE FROM ANSWER

Just for finish up upon question.
I created a custom class holding both Permission and Token

    public class PermissionCustom
{
    public Permission  Permission { get; set; }
    public string Token { get; set; }
}

This makes it possible to create a documentdb client like this:

client = new DocumentClient(new Uri(config.EndPointUri), config.Permissions[0].Token);

So far so good :-) but it doesn't makes it easier to secure your database considering users could have many permissions for different resources. Even though it is properly to make it more secure, the token is readonly in the first place.


问:
angular2 and nested nested routes - how to construct routerLink
I am trying to do a nested nested route....
I have a tab in a tab using dynamic loading of tabs wth angular2 material tab component.

My first nested tab does work.  But my second does not.

```<code>{ path: 'output',component: OutputComponent, canActivate: [AuthGuard], children: [
        { path: 'details',component: OutputDetailsComponent, canActivate: [AuthGuard], outlet:'output',children: [
            { path: 'distributions',component: OutputDistributionsComponent, canActivate: [AuthGuard], outlet:'data'},
        ]}
       ]
     }
</code>```

So I can get to http://localhost:4200/#/output/(output:details)

but I cant get to distributions

http://localhost:4200/#/output/(output:details/(data:distributions))

```<code>ERROR Error: Uncaught (in promise): Error: Cannot match any routes. URL Segment: 'output'
</code>```

So I have:

```<code><router-outlet></router-outlet> -->app.component.html
      <router-outlet name="output"></router-outlet> -- output.componenbt.html
          <router-outlet name="data"></router-outlet> --outpuyt.data.component.html
</code>```

So in ts I can load the first tab like this:

```<code>['/output', {outlets: {'output': ['details']}}]
</code>```

In the nested nested I tried this:

```<code>['/output', {outlets: {'output': [{outlets: {'data': ['distributions']}}]}}]}
</code>```

What is the proper way to handle this?

This will correctly get me to the route if I paste in the browser:
    http://localhost:4200/#/output/(output:details/(data:distributions))

I just don't know how to construct using routerLink..

I also tried this to no avail:

```<code>  ['/output', {outlets: {'output': ['details/(data:distributions)']}}]
</code>```

答:
Actually Nested routes need to be loaded inside the nested outlets

```<code><router-outlet>
    <router-outlet>
        <router-outlet></router-outlet>
    </router-outlet>
</router-outlet>
</code>```

Better to create root route for every child route

```<code>{
    path: 'output',
    canActivate: [AuthGuard],
    children: [
        {
            path: "",
            component: "OutputComponent"
        },
        {
            path: 'details',
            canActivate: [AuthGuard],
            children: [
                {
                    path: "",
                    component: "OutputDetailsComponent"
                },
                {
                    path: 'distributions',
                    component: OutputDistributionsComponent,
                    canActivate: [AuthGuard], outlet:'data'
                 }
             ]
         }
     ]
 }
</code>```

Body:
I am trying to do a nested nested route....
I have a tab in a tab using dynamic loading of tabs wth angular2 material tab component.

My first nested tab does work.  But my second does not.

{ path: 'output',component: OutputComponent, canActivate: [AuthGuard], children: [
        { path: 'details',component: OutputDetailsComponent, canActivate: [AuthGuard], outlet:'output',children: [
            { path: 'distributions',component: OutputDistributionsComponent, canActivate: [AuthGuard], outlet:'data'},
        ]}
       ]
     }

So I can get to http://localhost:4200/#/output/(output:details)

but I cant get to distributions

http://localhost:4200/#/output/(output:details/(data:distributions))

ERROR Error: Uncaught (in promise): Error: Cannot match any routes. URL Segment: 'output'

So I have:

<router-outlet></router-outlet> -->app.component.html
      <router-outlet name="output"></router-outlet> -- output.componenbt.html
          <router-outlet name="data"></router-outlet> --outpuyt.data.component.html

So in ts I can load the first tab like this:

['/output', {outlets: {'output': ['details']}}]

In the nested nested I tried this:

['/output', {outlets: {'output': [{outlets: {'data': ['distributions']}}]}}]}

What is the proper way to handle this?

This will correctly get me to the route if I paste in the browser:
    http://localhost:4200/#/output/(output:details/(data:distributions))

I just don't know how to construct using routerLink..

I also tried this to no avail:

  ['/output', {outlets: {'output': ['details/(data:distributions)']}}]

Body:
Actually Nested routes need to be loaded inside the nested outlets

<router-outlet>
    <router-outlet>
        <router-outlet></router-outlet>
    </router-outlet>
</router-outlet>

Better to create root route for every child route

{
    path: 'output',
    canActivate: [AuthGuard],
    children: [
        {
            path: "",
            component: "OutputComponent"
        },
        {
            path: 'details',
            canActivate: [AuthGuard],
            children: [
                {
                    path: "",
                    component: "OutputDetailsComponent"
                },
                {
                    path: 'distributions',
                    component: OutputDistributionsComponent,
                    canActivate: [AuthGuard], outlet:'data'
                 }
             ]
         }
     ]
 }


问:
Create a directly-executable cross-platform GUI app using Python
Python works on multiple platforms and can be used for desktop and web applications, thus I conclude that there is some way to compile it into an executable for Mac, Windows and Linux.

The problem being I have no idea where to start or how to write a GUI with it, can anybody shed some light on this and point me in the right direction please?

答:
You can use appJar for basic GUI development.

```<code>from appJar import gui

num=1

def myfcn(btnName):
    global num
    num +=1
    win.setLabel("mylabel", num)

win = gui('Test')

win.addButtons(["Set"],  [myfcn])
win.addLabel("mylabel", "Press the Button")

win.go()
</code>```

See documentation at appJar site.

Installation is made with pip install appjar from command line.

LastEditorDisplayName: lubos hasko

Body:
You can use appJar for basic GUI development.

from appJar import gui

num=1

def myfcn(btnName):
    global num
    num +=1
    win.setLabel("mylabel", num)

win = gui('Test')

win.addButtons(["Set"],  [myfcn])
win.addLabel("mylabel", "Press the Button")

win.go()

See documentation at appJar site.

Installation is made with pip install appjar from command line.


问:
Print Label in two columns - Qweb report OdooV10
I'm trying to create a Qweb report into Odoo Version 10, My requirement is to Print the for-each values in two columns in row,

```<code><t t-call="report.html_container">
            <t t-foreach="docs" t-as="doc">
           <!-- Here i need to print the doc data in two columns , then proceed to next row -->
             </t>
 </t>
</code>```

Please anybody help me to print the data in two columns and then proceed to row

答:
Try This

In your report template, add this code

```<code><div class="row">
    <div class="col-xs-6">
        <p t-field="enter your name"/>
    </div>
    <div class="col-xs-6" >
        <p t-field="enter your name"/>
    </div>
</div>
</code>```

Body:
I'm trying to create a Qweb report into Odoo Version 10, My requirement is to Print the for-each values in two columns in row,

<t t-call="report.html_container">
            <t t-foreach="docs" t-as="doc">

             </t>
 </t>

Please anybody help me to print the data in two columns and then proceed to row

Body:
Try This

In your report template, add this code

<div class="row">
    <div class="col-xs-6">
        <p t-field="enter your name"/>
    </div>
    <div class="col-xs-6" >
        <p t-field="enter your name"/>
    </div>
</div>


问:
Gulp - how to collect images without `dir`and place in one folder?
I am trying to collect the only images and placing in to dest folder. my images all are spreads across bower_components - so, I am getting no.of folder created. how to prevent this?

here is my code :

```<code>gulp.task('copy-images', function() {
    return gulp.src('./WebContent/bower_components/**/*.{gif,jpg,png,svg}')
    .pipe(gulp.dest('./dist/css/images')); //creates no.of folders.
});
</code>```

I am getting all images, but all are nested inside of it's parent folders like where it was in original.

答:
use gulp-flatten

e.g.

```<code>gulp.src('bower_components/**/*.min.js')
  .pipe(flatten())
  .pipe(gulp.dest('build/js'));
</code>```

it will copy all files in a single directory without creating subdirectories

Body:
I am trying to collect the only images and placing in to dest folder. my images all are spreads across bower_components - so, I am getting no.of folder created. how to prevent this?

here is my code :

gulp.task('copy-images', function() {
    return gulp.src('./WebContent/bower_components/**/*.{gif,jpg,png,svg}')
    .pipe(gulp.dest('./dist/css/images')); //creates no.of folders.
});

I am getting all images, but all are nested inside of it's parent folders like where it was in original.

Body:
use gulp-flatten

e.g.

gulp.src('bower_components/**/*.min.js')
  .pipe(flatten())
  .pipe(gulp.dest('build/js'));

it will copy all files in a single directory without creating subdirectories