问:
Download/Upload of Page Remarkup in Phabricator Wiki (Phriction)
The company I work for uses the "Phriction" wiki in Phabricator for a considerable amount of documentation. I'd like to be able do the following, programmatically, in order of importance:

Download (e.g., with curl or wget) the ReStructuredTExt (RST) to a local file where I can edit it, diff it, etc. Ideally I should be able to download either the latest version or any specific version.

Locally render (e.g., in a local graphical web browser) the markup as Phabricator would render it. If relative links can link correctly back to the original wiki, that's a bonus.

Upload new versions of the wiki page.

If you have don't know how to do exactly any of this, but have information or tool suggestions that would help me get started on writing software to do the above, please mention them. (If you're worried about too many answers that don't actually answer any of the questions above, try adding or editing a single community answer for this sort of information.)

答:
I would do the following in your situation:

Downloading the single phriction pages using the API (Conduit) methods in the phriction section.

Therefore you need a Conduit Api Token. You can create  in your profile settings of your phabricators intstance.

Then take a look at the phriction.info mehtod: This methods needs the page slug as parameter. In this example I use the /changelog/ page.

You can choose between arcanist, cURl or PHP to use the RestApi. Additionally you can use any other way to preform RestApi commands in the cURL syntax.

If you need some more examples how to run the conduit method you can toggle between some variations at the bottom of the output page.

Transform the page content as you like.

Upload the page again with the conduit methods (phriction.edit).

The way you downloaded the content you can edit the documents, too. But here you need some more parameter:

I personally, try first all conduit methods via the web interface first and then transform it to an a script.


来源: stackexchange

问:
Paypal as payment gateway?
i have to choose between several payment gateways. I heard that PayPal is quite a mess and there were several fraud-issues? Does some of you have experiences with PayPal?

Thanks in advance

答:
I have.

PayPal is, in my opinion, one of the best gateways around the world, if not the best.

Let me answer straight to your points:

"Quite a mess": actually not. PayPal's APIs are widely documented and PayPal offers you a sandbox mode to test your software with fake accounts and fake money to see if your software works or not (you might find, for example, your ecommerce application tries to deliver an order the customer didn't pay for after canceling the order, etc). I don't think this stands for quite a mess since you can perform deep software testing

Fraud issues. Let me tell you that Internet frauds occur often, and it's difficult (while not impossible) to protect from them. PayPal does a lot to protect both customers and sellers from frauds. Customers are mainly protected on eBay from fraudulent sellers, but sellers are protected from chargebacks too. If a fraudulent customer buys goods from your website, the chargeback protection applies. In all cases, PayPal might freeze part of your money during investigations.

By the way, PayPal as payment gateway enables your website to accept all credit cards, so you don't need to sign with another gateway.

Unfortunately,

PayPal is expensive IMHO. A little too expensive...

ContentLicense: CC BY-SA 2.5

Title: Paypal as payment gateway?


问:
tableviewcontroller not working when called from other viewcontroller
I have two tableViewControllers created in storyboard:
categories and stores.
When I select a category, it's supposed to show all stores that are in that category.
(I'm getting stores data from server, but I set a fixed category in the url so it should fetch the same two stores no matter what.)

The weird thing is that when I choose a category, storesController shows up empty,
but if I set it as initial controller, it works.

StoreTableViewController_as_initial.png

StoreTableViewController_from_categories.png

this is how I setup the cells in storeController.

```<code>   - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
StoresCell *cell = [tableView dequeueReusableCellWithIdentifier:@"storetile"];
if(cell == nil){
    cell = [[StoresCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"storetile"];
}

cell.storelabel.text = [[_results objectAtIndex:[indexPath row]]objectForKey:@"name"];
[cell.storelabel sizeToFit];
cell.subtitleOneLabel.text=[[_results objectAtIndex:[indexPath row]]objectForKey:@"neighborhood"];
cell.subtitleTwoLabel.text = [[_results objectAtIndex:[indexPath row]]objectForKey:@"city"];
NSString *distance = [NSString stringWithFormat:@"~%@ km",[[_results objectAtIndex:[indexPath row]]objectForKey:@"distance"]];
cell.distanceLabel.text = distance;
NSString *imgPath = [[_results objectAtIndex:[indexPath row]]objectForKey:@"imgUrl"];
UIImage *thumb = [[UIImage alloc] initWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:[NSString stringWithFormat:@"http://andrafterdevelopment.com.br/apps/buscaabc/img/%@",imgPath]]]];

[cell.thumbImage setImage:thumb];
return cell;
}
</code>```

I break at the return, the method is always called but when it's from categoriesController all labels in my cell are nil.

this is how I call storeController from categoriesController

```<code>-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:
    (NSIndexPath *)indexPath{

NSDictionary *item = [_results objectAtIndex:[indexPath row]];
BOOL hasSub = [[item objectForKey:@"hasSub"] boolValue];

    StoreTableViewController *storesTableViewController = [[StoreTableViewController alloc]init];

    //storesTableViewController.title = [item valueForKey:@"name"];
    //storesTableViewController.category = (int)[item valueForKey:@"id"];
    [storesTableViewController.tableView registerClass:[StoresCell class] forCellReuseIdentifier:@"storetile"];
    [self.navigationController pushViewController:storesTableViewController animated:YES];
}
</code>```

I'm guessing this has to do with custom cell or maybe I'm doing it wrong by calling it this way.

答:
Their are few things that i think you should check in your code.

When you are opening second view controller for selected category, did your service giving you data?

If you are getting data, then is it getting filled in array in right way?

And if everything above is fine, then had you called [tableView reloadData] method after filling data in array.

ContentLicense: CC BY-SA 3.0

Body:
I have two tableViewControllers created in storyboard:
categories and stores.
When I select a category, it's supposed to show all stores that are in that category.
(I'm getting stores data from server, but I set a fixed category in the url so it should fetch the same two stores no matter what.)

The weird thing is that when I choose a category, storesController shows up empty,
but if I set it as initial controller, it works.

StoreTableViewController_as_initial.png

StoreTableViewController_from_categories.png

this is how I setup the cells in storeController.

   - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
StoresCell *cell = [tableView dequeueReusableCellWithIdentifier:@"storetile"];
if(cell == nil){
    cell = [[StoresCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"storetile"];
}

cell.storelabel.text = [[_results objectAtIndex:[indexPath row]]objectForKey:@"name"];
[cell.storelabel sizeToFit];
cell.subtitleOneLabel.text=[[_results objectAtIndex:[indexPath row]]objectForKey:@"neighborhood"];
cell.subtitleTwoLabel.text = [[_results objectAtIndex:[indexPath row]]objectForKey:@"city"];
NSString *distance = [NSString stringWithFormat:@"~%@ km",[[_results objectAtIndex:[indexPath row]]objectForKey:@"distance"]];
cell.distanceLabel.text = distance;
NSString *imgPath = [[_results objectAtIndex:[indexPath row]]objectForKey:@"imgUrl"];
UIImage *thumb = [[UIImage alloc] initWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:[NSString stringWithFormat:@"http://andrafterdevelopment.com.br/apps/buscaabc/img/%@",imgPath]]]];

[cell.thumbImage setImage:thumb];
return cell;
}

I break at the return, the method is always called but when it's from categoriesController all labels in my cell are nil.

this is how I call storeController from categoriesController

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:
    (NSIndexPath *)indexPath{

NSDictionary *item = [_results objectAtIndex:[indexPath row]];
BOOL hasSub = [[item objectForKey:@"hasSub"] boolValue];

    StoreTableViewController *storesTableViewController = [[StoreTableViewController alloc]init];

    //storesTableViewController.title = [item valueForKey:@"name"];
    //storesTableViewController.category = (int)[item valueForKey:@"id"];
    [storesTableViewController.tableView registerClass:[StoresCell class] forCellReuseIdentifier:@"storetile"];
    [self.navigationController pushViewController:storesTableViewController animated:YES];
}

I'm guessing this has to do with custom cell or maybe I'm doing it wrong by calling it this way.


问:
line simplification algorithm: Visvalingam vs Douglas-Peucker
I am trying to implement a line simplification algorithm. The main 2 algorithms I found are:

Ramer-Douglas-Peucker

Visvalingam-Whyat

Currently I am running a few simulations of them on Matlab in order to determine which answers my needs better.

The main goal for the algorithm is to simlipfy polygons in a map.
My Input is a polygon\polyline and a threshold for mistake- epsilon.

I need the simplified polygon to be as close as possible to the original,
and I do not have a requirment for number of points to keep.

I am having difficulties in comparing the two algorithms because:
epsilon for RDP is a distance while epsilon for VW is an area.
I need help understanding how to compare between the two algorithms.
which can give me less points to keep within the threshold?

答:
I need the simlified polygon to be as close as possible to the
  original, and I do not have a requirment for number of points to keep.

DP method will give you better perceptible fit with lesser number of points - as its control parameter i.e the distance tolerance is captured by your requirement 'as close as possible'.

Having said that, the scale of the overall polygon or point-cloud relative to the pixel dimensions will have a bigger impact for smaller images. The exercise below can give you a 'feel' for how the two algorithms perform.

Here are some comparisons I ran between Visvalingam-Whyatt and Ramer-Douglas-Peucker for a few contours contained in what is around 100x100 bitmap originally. The images are screenshots of a ~ 10x zoom on the contours.

(you might want to download the images to appreciate the differences in performance)

Visvalingam-Whyatt method results : courtesy  Zach's implementation on github ported to opencv data types.

VSV simplification - with 0.55(white), 0.4(red), 0.25(magenta), 0.15(cyan) percentage tolerances

VSV - point reductions t : % tolerance . this directly determines n = t*orig/100. n is the final number of points

```<code>orig 88: [n=47 for t=0.55], [n=34 for t=0.4], [n=20 for t=0.25], [n=12 for t=0.15]
orig 133: [n=72 for t=0.55], [n=52 for t=0.4], [n=32 for t=0.25], [n=18 for t=0.15]
orig 118: [n=63 for t=0.55], [n=46 for t=0.4], [n=28 for t=0.25], [n=16 for t=0.15]
orig 107: [n=57 for t=0.55], [n=41 for t=0.4], [n=25 for t=0.25], [n=15 for t=0.15]
orig 107: [n=57 for t=0.55], [n=41 for t=0.4], [n=25 for t=0.25], [n=15 for t=0.15]
orig 268: [n=146 for t=0.55], [n=106 for t=0.4], [n=65 for t=0.25], [n=39 for t=0.15]
orig 158: [n=85 for t=0.55], [n=62 for t=0.4], [n=38 for t=0.25], [n=22 for t=0.15]
orig 158: [n=85 for t=0.55], [n=62 for t=0.4], [n=38 for t=0.25], [n=22 for t=0.15]
orig 109: [n=58 for t=0.55], [n=42 for t=0.4], [n=26 for t=0.25], [n=15 for t=0.15]
orig 192: [n=104 for t=0.55], [n=75 for t=0.4], [n=46 for t=0.25], [n=27 for t=0.15]
orig 132: [n=71 for t=0.55], [n=51 for t=0.4], [n=31 for t=0.25], [n=18 for t=0.15]
orig 89: [n=47 for t=0.55], [n=34 for t=0.4], [n=21 for t=0.25], [n=12 for t=0.15]
orig 110: [n=59 for t=0.55], [n=42 for t=0.4], [n=26 for t=0.25], [n=15 for t=0.15]
orig 40: [n=20 for t=0.55], [n=14 for t=0.4], [n=8 for t=0.25], [n=4 for t=0.15]
</code>```

DP method results using openCV approxPolyDP

Douglas-Peucker - point reductions t : pixel distance tolerance => no direct correlation to n - the final number of points

```<code>orig 88: [n=33 for t=0.1], [n=29 for t=0.5], [n=8 for t=1], [n=6 for t=2]
orig 133: [n=57 for t=0.1], [n=45 for t=0.5], [n=12 for t=1], [n=7 for t=2]
orig 118: [n=50 for t=0.1], [n=40 for t=0.5], [n=15 for t=1], [n=8 for t=2]
orig 107: [n=47 for t=0.1], [n=35 for t=0.5], [n=11 for t=1], [n=6 for t=2]
orig 107: [n=30 for t=0.1], [n=24 for t=0.5], [n=8 for t=1], [n=6 for t=2]
orig 268: [n=126 for t=0.1], [n=110 for t=0.5], [n=32 for t=1], [n=23 for t=2]
orig 158: [n=80 for t=0.1], [n=62 for t=0.5], [n=17 for t=1], [n=11 for t=2]
orig 158: [n=66 for t=0.1], [n=52 for t=0.5], [n=16 for t=1], [n=9 for t=2]
orig 109: [n=50 for t=0.1], [n=38 for t=0.5], [n=12 for t=1], [n=9 for t=2]
orig 192: [n=74 for t=0.1], [n=64 for t=0.5], [n=18 for t=1], [n=15 for t=2]
orig 132: [n=58 for t=0.1], [n=45 for t=0.5], [n=14 for t=1], [n=11 for t=2]
orig 89: [n=37 for t=0.1], [n=31 for t=0.5], [n=7 for t=1], [n=6 for t=2]
orig 110: [n=42 for t=0.1], [n=36 for t=0.5], [n=9 for t=1], [n=7 for t=2]
orig 40: [n=18 for t=0.1], [n=15 for t=0.5], [n=9 for t=1], [n=3 for t=2]
</code>```

Summary :

Both the methods degrade gracefully.

VSV lets you specify the number of approximated points (in this implementation)

VSV in this implementation lets you pick multiple approximate polygons in one shot.

VSV retains a lot of pixel level convexity inflections even for large curvature sections - this could be undesirable in some cases.

DP follows the convexities better and smooths out inflections more but by sacrificing 'closeness'.

As a result, DP gives lesser number of points for the same percieved tolerance - which is anyway hard to compare between the two methods

DP give a better feel for tolerance as its a linear distance specification.

For my application, I prefer the control offered by VWV in this implementation over the possible efficiency of DP method.

But overall I feel openCVs's DP implementation gives a smoother perception.

Though my conclusions of VSV performance are based on Zach's implementation alone, I doubt if other implementations will give characteristically different polygon subsets.

[UPDATE1] Here is the comparison for a worst case scenario. DP is visually more acceptable.

ContentLicense: CC BY-SA 4.0

Body:
I need the simlified polygon to be as close as possible to the
  original, and I do not have a requirment for number of points to keep.

DP method will give you better perceptible fit with lesser number of points - as its control parameter i.e the distance tolerance is captured by your requirement 'as close as possible'.

Having said that, the scale of the overall polygon or point-cloud relative to the pixel dimensions will have a bigger impact for smaller images. The exercise below can give you a 'feel' for how the two algorithms perform.

Here are some comparisons I ran between Visvalingam-Whyatt and Ramer-Douglas-Peucker for a few contours contained in what is around 100x100 bitmap originally. The images are screenshots of a ~ 10x zoom on the contours.

(you might want to download the images to appreciate the differences in performance)

Visvalingam-Whyatt method results : courtesy  Zach's implementation on github ported to opencv data types.

VSV simplification - with 0.55(white), 0.4(red), 0.25(magenta), 0.15(cyan) percentage tolerances

VSV - point reductions t : % tolerance . this directly determines n = t*orig/100. n is the final number of points

orig 88: [n=47 for t=0.55], [n=34 for t=0.4], [n=20 for t=0.25], [n=12 for t=0.15]
orig 133: [n=72 for t=0.55], [n=52 for t=0.4], [n=32 for t=0.25], [n=18 for t=0.15]
orig 118: [n=63 for t=0.55], [n=46 for t=0.4], [n=28 for t=0.25], [n=16 for t=0.15]
orig 107: [n=57 for t=0.55], [n=41 for t=0.4], [n=25 for t=0.25], [n=15 for t=0.15]
orig 107: [n=57 for t=0.55], [n=41 for t=0.4], [n=25 for t=0.25], [n=15 for t=0.15]
orig 268: [n=146 for t=0.55], [n=106 for t=0.4], [n=65 for t=0.25], [n=39 for t=0.15]
orig 158: [n=85 for t=0.55], [n=62 for t=0.4], [n=38 for t=0.25], [n=22 for t=0.15]
orig 158: [n=85 for t=0.55], [n=62 for t=0.4], [n=38 for t=0.25], [n=22 for t=0.15]
orig 109: [n=58 for t=0.55], [n=42 for t=0.4], [n=26 for t=0.25], [n=15 for t=0.15]
orig 192: [n=104 for t=0.55], [n=75 for t=0.4], [n=46 for t=0.25], [n=27 for t=0.15]
orig 132: [n=71 for t=0.55], [n=51 for t=0.4], [n=31 for t=0.25], [n=18 for t=0.15]
orig 89: [n=47 for t=0.55], [n=34 for t=0.4], [n=21 for t=0.25], [n=12 for t=0.15]
orig 110: [n=59 for t=0.55], [n=42 for t=0.4], [n=26 for t=0.25], [n=15 for t=0.15]
orig 40: [n=20 for t=0.55], [n=14 for t=0.4], [n=8 for t=0.25], [n=4 for t=0.15]

DP method results using openCV approxPolyDP

Douglas-Peucker - point reductions t : pixel distance tolerance => no direct correlation to n - the final number of points

orig 88: [n=33 for t=0.1], [n=29 for t=0.5], [n=8 for t=1], [n=6 for t=2]
orig 133: [n=57 for t=0.1], [n=45 for t=0.5], [n=12 for t=1], [n=7 for t=2]
orig 118: [n=50 for t=0.1], [n=40 for t=0.5], [n=15 for t=1], [n=8 for t=2]
orig 107: [n=47 for t=0.1], [n=35 for t=0.5], [n=11 for t=1], [n=6 for t=2]
orig 107: [n=30 for t=0.1], [n=24 for t=0.5], [n=8 for t=1], [n=6 for t=2]
orig 268: [n=126 for t=0.1], [n=110 for t=0.5], [n=32 for t=1], [n=23 for t=2]
orig 158: [n=80 for t=0.1], [n=62 for t=0.5], [n=17 for t=1], [n=11 for t=2]
orig 158: [n=66 for t=0.1], [n=52 for t=0.5], [n=16 for t=1], [n=9 for t=2]
orig 109: [n=50 for t=0.1], [n=38 for t=0.5], [n=12 for t=1], [n=9 for t=2]
orig 192: [n=74 for t=0.1], [n=64 for t=0.5], [n=18 for t=1], [n=15 for t=2]
orig 132: [n=58 for t=0.1], [n=45 for t=0.5], [n=14 for t=1], [n=11 for t=2]
orig 89: [n=37 for t=0.1], [n=31 for t=0.5], [n=7 for t=1], [n=6 for t=2]
orig 110: [n=42 for t=0.1], [n=36 for t=0.5], [n=9 for t=1], [n=7 for t=2]
orig 40: [n=18 for t=0.1], [n=15 for t=0.5], [n=9 for t=1], [n=3 for t=2]

Summary :

Both the methods degrade gracefully.

VSV lets you specify the number of approximated points (in this implementation)

VSV in this implementation lets you pick multiple approximate polygons in one shot.

VSV retains a lot of pixel level convexity inflections even for large curvature sections - this could be undesirable in some cases.

DP follows the convexities better and smooths out inflections more but by sacrificing 'closeness'.

As a result, DP gives lesser number of points for the same percieved tolerance - which is anyway hard to compare between the two methods

DP give a better feel for tolerance as its a linear distance specification.

For my application, I prefer the control offered by VWV in this implementation over the possible efficiency of DP method.

But overall I feel openCVs's DP implementation gives a smoother perception.

Though my conclusions of VSV performance are based on Zach's implementation alone, I doubt if other implementations will give characteristically different polygon subsets.

[UPDATE1] Here is the comparison for a worst case scenario. DP is visually more acceptable.


问:
WCF configuration
I have the following reference to my service  in my App.config:

```<code><system.serviceModel>
<bindings>
  <basicHttpBinding>
    <binding name="BasicHttpBinding_Statistics" />
  </basicHttpBinding>
</bindings>
<client>
  <endpoint address="http://Statistics-test.svc"
    binding="basicHttpBinding"
    bindingConfiguration="BasicHttpBinding_Statistics"
    contract="am.Statistics"
    name="BasicHttpBinding_Statistics" />
</client>
</system.serviceModel>
</code>```

So I was wondering what is the difference in consuming the service like the following two options.

Option 1:

this option will take as default the endpoint address that I have in the App.config "http://Statistics-test.svc"

```<code> using (StatisticsClient client = new  StatisticsClient())
        {
           var res = client.GetWhatever();
        }
</code>```

Option 2:
  Here would like to provide the URL for the service to point to  Production (both are the same), so I will provide the "endpointConfigurationName" and the "remote address" = "http://Statistics-prod.svc"

```<code>    string Url = "http://Statistics-prod.svc";

    using (StatisticsClient client = new StatisticsClient(BasicHttpBinding_Statistics,Url))
        {
           var res = client.GetWhatever();
        }
</code>```

I would like to know if there is any performance or any other issue in passing the parameters to the WCF in the Option 2. Good to mention that both ways work fine but the second option is just simpler since I can just change the URL dynamically as needed.

I appreciate your help.

答: The first approach allows you to change the endpoint without the need to rebuild the application. But the rest is performing the same way</p>

Title: WCF configuration

Body:
I have the following reference to my service  in my App.config:

<system.serviceModel>
<bindings>
  <basicHttpBinding>
    <binding name="BasicHttpBinding_Statistics" />
  </basicHttpBinding>
</bindings>
<client>
  <endpoint address="http://Statistics-test.svc"
    binding="basicHttpBinding"
    bindingConfiguration="BasicHttpBinding_Statistics"
    contract="am.Statistics"
    name="BasicHttpBinding_Statistics" />
</client>
</system.serviceModel>

So I was wondering what is the difference in consuming the service like the following two options.

Option 1:

this option will take as default the endpoint address that I have in the App.config "http://Statistics-test.svc"

 using (StatisticsClient client = new  StatisticsClient())
        {
           var res = client.GetWhatever();
        }

Option 2:
  Here would like to provide the URL for the service to point to  Production (both are the same), so I will provide the "endpointConfigurationName" and the "remote address" = "http://Statistics-prod.svc"

    string Url = "http://Statistics-prod.svc";

    using (StatisticsClient client = new StatisticsClient(BasicHttpBinding_Statistics,Url))
        {
           var res = client.GetWhatever();
        }

I would like to know if there is any performance or any other issue in passing the parameters to the WCF in the Option 2. Good to mention that both ways work fine but the second option is just simpler since I can just change the URL dynamically as needed.

I appreciate your help.


问:
Getting focus of EditText inside RecyclerView
I'm implementing an application in which user can store Debit Cards and later they can use it by just entering the CVV number of the same card. I have used RecyclerView for all the items(Debit Cards) stored by the user. Everything is working fine, view is rendering all good and I have used LinearLayoutManager to show Horizontal scroll.

Now the problem which I am facing is whenever I try to enter CVV of any card as soon as I click on it the view gets shifted towards the last item of the list of Stored Cards, So if I'm having three cards stored in my list and I try to enter CVV for the first one the view is shifting directly to the third card but the focus remains on the first cards EditText. I don't know what's going on with the same. I'm sharing some code part for the same.

Setting adapter and defining horizontal scroll :-

```<code>  recyclerAdapter = new RecyclerStoredCardAdapter(mContext, storedCards);
                LinearLayoutManager layoutManager
                        = new LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, false);
                storedCardListRecycler.setLayoutManager(layoutManager);
                storedCardListRecycler.setVisibility(View.VISIBLE);
                storedCardListRecycler.setAdapter(recyclerAdapter);
</code>```

Sharing the screenshots with this so it will get clear. Any help would be appreciable. Thanks.

答:
Not able to reproduce this issue. Let me know if the following code does what you are facing. If not, can provide more feedback if you share you Adapter's Code.

```<code>MainActivity.java
public class MainActivity
  extends AppCompatActivity {

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

    RecyclerView recyclerView = (RecyclerView) findViewById(R.id.recycler_view);
    MyAdapter adapter = new MyAdapter();
    recyclerView.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, false));
    recyclerView.setAdapter(adapter);
}
}

public class MyAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {

@Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
    View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.recycler_ite, parent);
    return new MyViewHolder(view);
}

@Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
    ((EditText)((MyViewHolder)holder).mBinding.findViewById(R.id.editText)).setHint(position + " ");
}

@Override
public int getItemCount() {
    return 100;
}

public class MyViewHolder extends RecyclerView.ViewHolder {
    View mBinding;
    public MyViewHolder(View binding) {
        super(binding);
        this.mBinding = binding;
    }
}
}
</code>```

The 2xml layouts:

```<code><EditText
    android:id="@+id/editText"
    android:layout_height="200dp"
    android:layout_width="300dp"/>

</android.support.v7.widget.CardView>
</code>```

My main_activity.xml is as follows:

```<code><RelativeLayout
android:layout_height="match_parent"
android:layout_width="match_parent"
xmlns:android="http://schemas.android.com/apk/res/android">

<android.support.v7.widget.RecyclerView
    android:id="@+id/recycler_view"
    android:layout_height="wrap_content"
    android:layout_width="match_parent"/>
</RelativeLayout>
</code>```

As you can see this is the simplest case. Let me know if I missed anything.

Body:
I'm implementing an application in which user can store Debit Cards and later they can use it by just entering the CVV number of the same card. I have used RecyclerView for all the items(Debit Cards) stored by the user. Everything is working fine, view is rendering all good and I have used LinearLayoutManager to show Horizontal scroll.

Now the problem which I am facing is whenever I try to enter CVV of any card as soon as I click on it the view gets shifted towards the last item of the list of Stored Cards, So if I'm having three cards stored in my list and I try to enter CVV for the first one the view is shifting directly to the third card but the focus remains on the first cards EditText. I don't know what's going on with the same. I'm sharing some code part for the same.

Setting adapter and defining horizontal scroll :-

  recyclerAdapter = new RecyclerStoredCardAdapter(mContext, storedCards);
                LinearLayoutManager layoutManager
                        = new LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, false);
                storedCardListRecycler.setLayoutManager(layoutManager);
                storedCardListRecycler.setVisibility(View.VISIBLE);
                storedCardListRecycler.setAdapter(recyclerAdapter);

Sharing the screenshots with this so it will get clear. Any help would be appreciable. Thanks.

Body:
Not able to reproduce this issue. Let me know if the following code does what you are facing. If not, can provide more feedback if you share you Adapter's Code.

MainActivity.java
public class MainActivity
  extends AppCompatActivity {

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

    RecyclerView recyclerView = (RecyclerView) findViewById(R.id.recycler_view);
    MyAdapter adapter = new MyAdapter();
    recyclerView.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, false));
    recyclerView.setAdapter(adapter);
}
}

public class MyAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {

@Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
    View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.recycler_ite, parent);
    return new MyViewHolder(view);
}

@Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
    ((EditText)((MyViewHolder)holder).mBinding.findViewById(R.id.editText)).setHint(position + " ");
}

@Override
public int getItemCount() {
    return 100;
}

public class MyViewHolder extends RecyclerView.ViewHolder {
    View mBinding;
    public MyViewHolder(View binding) {
        super(binding);
        this.mBinding = binding;
    }
}
}

The 2xml layouts:

<EditText
    android:id="@+id/editText"
    android:layout_height="200dp"
    android:layout_width="300dp"/>

</android.support.v7.widget.CardView>

My main_activity.xml is as follows:

<RelativeLayout
android:layout_height="match_parent"
android:layout_width="match_parent"
xmlns:android="http://schemas.android.com/apk/res/android">

<android.support.v7.widget.RecyclerView
    android:id="@+id/recycler_view"
    android:layout_height="wrap_content"
    android:layout_width="match_parent"/>
</RelativeLayout>

As you can see this is the simplest case. Let me know if I missed anything.


问:
Laravel 5.4 : Get logged in user id inside __construct()
I am trying to access Auth::user()->id; inside constructor but it always return the error Trying to get property of non-object. I study in the laravel documentation that Session is not accessible inside constructor and also search on SO for this. I need logged in user id inside constructor because I have to fetch data from database and make it available for all its method. My current code is :

```<code>public function __construct(){
    $this->middleware('auth');
    $induction_status = TrainingStatusRecord::where('user_id',Auth::user()->id)->where('training','=','induction')->get();
    View::share('ind_status',$induction_status);
}
</code>```

Is there any way (easy way) to get logged in user id inside constructor.

I will appreciate any help.

Thank You

答:
To share a variable in view AppServiceProvider is a good approach

Go to App\Providers\AppServiceProvider.php

Include facade on top of the page

```<code>use Illuminate\Support\Facades\Auth;

use App\TrainingStatusRecord;
</code>```

and paste below code in boot method

```<code>view()->composer('*', function($view){
        if(Auth::user()){
            $induction_status = TrainingStatusRecord::where('user_id',Auth::user()->id)->where('training','=','induction')->get();
            View::share('induction_status',$induction_status);
        }
    });
</code>```

Now you will be able to get your variable $induction_status in your app.

Reference https://laravel.com/docs/5.4/providers#the-boot-method

Hope it will help you.

Body:
I am trying to access Auth::user()->id; inside constructor but it always return the error Trying to get property of non-object. I study in the laravel documentation that Session is not accessible inside constructor and also search on SO for this. I need logged in user id inside constructor because I have to fetch data from database and make it available for all its method. My current code is :

public function __construct(){
    $this->middleware('auth');
    $induction_status = TrainingStatusRecord::where('user_id',Auth::user()->id)->where('training','=','induction')->get();
    View::share('ind_status',$induction_status);
}

Is there any way (easy way) to get logged in user id inside constructor.

I will appreciate any help.

Thank You

Body:
To share a variable in view AppServiceProvider is a good approach

Go to App\Providers\AppServiceProvider.php

Include facade on top of the page

use Illuminate\Support\Facades\Auth;

use App\TrainingStatusRecord;

and paste below code in boot method

view()->composer('*', function($view){
        if(Auth::user()){
            $induction_status = TrainingStatusRecord::where('user_id',Auth::user()->id)->where('training','=','induction')->get();
            View::share('induction_status',$induction_status);
        }
    });

Now you will be able to get your variable $induction_status in your app.

Reference https://laravel.com/docs/5.4/providers#the-boot-method

Hope it will help you.


问:
Binary search of a Matrix

Write an efficient algorithm that searches for a value in an m x n
  matrix.

This matrix has the following properties:

-Integers in each row are sorted from left to right.
-The first integer
  of each row is greater than or equal to the last integer of the
  previous row.

Example:

Consider the following matrix:

[

    [1,   3,  5,  7],

[10, 11, 16, 20],
   [23, 30, 34, 50]
]
Given
  target = 3, return 1 ( 1 corresponds to true )

Return 0 / 1 ( 0 if the element is not present, 1 if the element is
  present ) for this problem

My solution works on NetBeans but fails on the website. Any help will be appreciated.
https://www.interviewbit.com/problems/matrix-search/

```<code>public class Solution {

    public int searchMatrix(ArrayList<ArrayList<Integer>> a, int b) {
        int r = a.size();
        int c = a.get(0).size();

        int start = 0;
        int end = r - 1;
        // default value is last row for edge case
        int biRow = r -1; // row to search column

        //binary search 1st value of rows
        while (start <= end) {
            int mid = (start + end) / 2;
            if (b == a.get(mid).get(0)) {
                return 1;
            }

            if (a.get(mid).get(0) < b && b < a.get(end).get(0)) {
                if (mid + 1 >= end) {
                    biRow = mid;
                    break;
                }
            } if (b < a.get(mid).get(0)) {
                end = mid - 1;
            } else {
                start = mid + 1;
            }
        }
        //binary search column of biRow
        start = 0;
        end = c-1;
        while (start <= end) {
            int mid = (start + end) / 2;
            if (b == a.get(biRow).get(mid)) {
                return 1;
            }
            if (b < a.get(biRow).get(mid)) {
                end = mid - 1;
            } else {
                start = mid + 1;
            }
        }
        return 0;
    }
}
</code>```

答:
You can first convert your 2D array into 1D array and perform binary search operation. You can refer the code given below:

```<code>void search(int a[][10],int search,int m,int n)
{
    int arr[100],i=0,j=0,k=-1;
    for(i=0;i<m;i++)
    for(j=0;j<n;j++)
        arr[++k] = a[i][j];

    int first = 0 , last = k-1 , middle = (first+last)/2;

    while (first <= last)
    {
        if(arr[middle] < search)
        {
            first = middle + 1;

        }
        else if(arr[middle] == search)
        {
            printf("\n Element found at position:( %d , %d")",(middle/n)+1,(middle%n)+1);
            printf(" \n Row : %d",(middle/n)+1);
            printf("\n column : %d",(middle%n)+1);
            break;
        }
        else
        {
             last = middle - 1;
        }
        middle = (first + last)/2;
    }
    if(first > last)
    {
        printf("\n Element not found! ");
    }
}
</code>```

This function prints the row and column of element to be searched if it exists.You can modify this code, if You want the function to return a value depending on the search operation.

Title: Binary search of a Matrix

Body:
Write an efficient algorithm that searches for a value in an m x n
  matrix.

This matrix has the following properties:

-Integers in each row are sorted from left to right.
-The first integer
  of each row is greater than or equal to the last integer of the
  previous row.

Example:

Consider the following matrix:

[

    [1,   3,  5,  7],

[10, 11, 16, 20],
   [23, 30, 34, 50]
]
Given
  target = 3, return 1 ( 1 corresponds to true )

Return 0 / 1 ( 0 if the element is not present, 1 if the element is
  present ) for this problem

My solution works on NetBeans but fails on the website. Any help will be appreciated.
https://www.interviewbit.com/problems/matrix-search/

public class Solution {

    public int searchMatrix(ArrayList<ArrayList<Integer>> a, int b) {
        int r = a.size();
        int c = a.get(0).size();

        int start = 0;
        int end = r - 1;
        // default value is last row for edge case
        int biRow = r -1; // row to search column

        //binary search 1st value of rows
        while (start <= end) {
            int mid = (start + end) / 2;
            if (b == a.get(mid).get(0)) {
                return 1;
            }

            if (a.get(mid).get(0) < b && b = end) {
                    biRow = mid;
                    break;
                }
            } if (b < a.get(mid).get(0)) {
                end = mid - 1;
            } else {
                start = mid + 1;
            }
        }
        //binary search column of biRow
        start = 0;
        end = c-1;
        while (start <= end) {
            int mid = (start + end) / 2;
            if (b == a.get(biRow).get(mid)) {
                return 1;
            }
            if (b < a.get(biRow).get(mid)) {
                end = mid - 1;
            } else {
                start = mid + 1;
            }
        }
        return 0;
    }
}

Body:
You can first convert your 2D array into 1D array and perform binary search operation. You can refer the code given below:

void search(int a[][10],int search,int m,int n)
{
    int arr[100],i=0,j=0,k=-1;
    for(i=0;i<m;i++)
    for(j=0;j<n;j++)
        arr[++k] = a[i][j];

    int first = 0 , last = k-1 , middle = (first+last)/2;

    while (first <= last)
    {
        if(arr[middle] < search)
        {
            first = middle + 1;

        }
        else if(arr[middle] == search)
        {
            printf("\n Element found at position:( %d , %d")",(middle/n)+1,(middle%n)+1);
            printf(" \n Row : %d",(middle/n)+1);
            printf("\n column : %d",(middle%n)+1);
            break;
        }
        else
        {
             last = middle - 1;
        }
        middle = (first + last)/2;
    }
    if(first > last)
    {
        printf("\n Element not found! ");
    }
}

This function prints the row and column of element to be searched if it exists.You can modify this code, if You want the function to return a value depending on the search operation.


问:
What is the best application I can use for testing webservice?
Can any one suggest an application to test my webservices. Basically I am developing my webservice in java.(All my webservices are signed and encrypted.)

Thanks,

Narendra

答: If you use SOAP, try SoapUI</p>

Body: If you use SOAP, try SoapUI


问:
Images not found on devices
I have an ionic/cordova app I am building. When developing in the browser I have no issues but when I build and run on devices or emulators they can't find my images. I have verified that the images are getting copied over to the platform projects, but do I have to do something special to be able to use them? For android, they are getting copied into assets/www/images and I am trying to reference them in my css using something like:

```<code>.myImage{
    height: 20px;
    width: 20px;
    background: url('/images/my_image.png') no-repeat;
}
</code>```

but in the console I get a 404 Not Found error on both ios and android. What am I doing wrong?

答:
What is working for me both when running off the local ionic serve or from the content of www copied to my web host is to use relative notation
../assets/img/
like so

```<code>.AMSView-background {
  background: url(../assets/img/UMSViewBGTile.png)  center center fixed;
  background-size: 50px;
  background-repeat: repeat;

}
</code>```

I just did a ionic run android --prod
and the above relative specification fixed the issue as well on Android.

I have never built for iOS so I can't comment there.

Note: the above ../assets/img/ is working from my .scss files which I believe are getting compiled into build/main.css, thus it explains why we have to up one parent.

However, my reference from html which from my observation also gets transpiled into main.js using

```<code>../assets/img
</code>```

but forcing current folder like so

```<code>./assets/img
</code>```

as in

```<code>    <button ion-button (click)="AMSController.Loop()"> <img src="./assets/img/PC_LOOP.png" width="30px" height="30px"/> </button>
</div>
</code>```

works in 2 areas, on local ionic serve and anywhere installed on my web host.  I can't explain why it works.

However it does not work on Android.

Perhaps someone can show me how to convert the image nested above inside an ion-button but from a .css so that I can take advantage of the '../assets/img/" path specification which is already working in 3 cases

Local

Hosted on my web folder

Android

Don't forget to accept the answer if works for you.
Thank you.

UPDATE: I have a fix for Android as well.

Using nothing as in "assets/img/PC_Loop.png"

Pay attention to your filename extension case PC_Loop.png and not PC_LOOP.png. I happen to host on Windows which does not care, but Android is a stupid Unix machine.  So on Unix hosting you also observe issue with casing.

I dislike very much anything case-sensitive, including sensitive programmers :), but I like case aware environments (language, OS, ...)

So why use nothing from .HTML and "../" from .CSS is totally absurd.

Hope this helps the next person.

Title: Images not found on devices

Body:
I have an ionic/cordova app I am building. When developing in the browser I have no issues but when I build and run on devices or emulators they can't find my images. I have verified that the images are getting copied over to the platform projects, but do I have to do something special to be able to use them? For android, they are getting copied into assets/www/images and I am trying to reference them in my css using something like:

.myImage{
    height: 20px;
    width: 20px;
    background: url('/images/my_image.png') no-repeat;
}

but in the console I get a 404 Not Found error on both ios and android. What am I doing wrong?

Body:
What is working for me both when running off the local ionic serve or from the content of www copied to my web host is to use relative notation
../assets/img/
like so

.AMSView-background {
  background: url(../assets/img/UMSViewBGTile.png)  center center fixed;
  background-size: 50px;
  background-repeat: repeat;

}

I just did a ionic run android --prod
and the above relative specification fixed the issue as well on Android.

I have never built for iOS so I can't comment there.

Note: the above ../assets/img/ is working from my .scss files which I believe are getting compiled into build/main.css, thus it explains why we have to up one parent.

However, my reference from html which from my observation also gets transpiled into main.js using

../assets/img

but forcing current folder like so

./assets/img

as in

    <button ion-button (click)="AMSController.Loop()"> <img src="./assets/img/PC_LOOP.png" width="30px" height="30px"/> </button>
</div>

works in 2 areas, on local ionic serve and anywhere installed on my web host.  I can't explain why it works.

However it does not work on Android.

Perhaps someone can show me how to convert the image nested above inside an ion-button but from a .css so that I can take advantage of the '../assets/img/" path specification which is already working in 3 cases

Local

Hosted on my web folder

Android

Don't forget to accept the answer if works for you.
Thank you.

UPDATE: I have a fix for Android as well.

Using nothing as in "assets/img/PC_Loop.png"

Pay attention to your filename extension case PC_Loop.png and not PC_LOOP.png. I happen to host on Windows which does not care, but Android is a stupid Unix machine.  So on Unix hosting you also observe issue with casing.

I dislike very much anything case-sensitive, including sensitive programmers :), but I like case aware environments (language, OS, ...)

So why use nothing from .HTML and "../" from .CSS is totally absurd.

Hope this helps the next person.


问:
Secondary Sort using Apache Spark 1.6
I am referring web link http://codingjunkie.net/spark-secondary-sort/
to implement secondary sort in my spark job.

```<code>import org.apache.spark.SparkContext
import org.apache.spark.SparkContext._
import org.apache.spark.SparkConf
import org.apache.spark.Partitioner

package Ssort {
case class DeviceKey(serialNum: String, eventDate: String, EventTs: Long) {
      implicit def orderingBySerialNum[A <: DeviceKey] : Ordering[A] = {
       Ordering.by(fk => (fk.serialNum, fk.eventDate, fk.EventTs * -1))
    }
}

class DeviceKeyPartitioner(partitions: Int) extends Partitioner {
    require(partitions >= 0, s"Number of partitions ($partitions) cannot be negative.")

    override def numPartitions: Int = partitions

    override def getPartition(key: Any): Int = {
      val k = key.asInstanceOf[DeviceKey]
      k.serialNum.hashCode() % numPartitions
    }
}

object SparkApp {
  def main(args: Array[String]) {
    val conf = new SparkConf().setAppName("Spark Application").setMaster("local[2]")
    val sc = new SparkContext(conf)
    val t = sc.parallelize(List(((DeviceKey("2","100",1),1)),(DeviceKey("2","100",3),1)), 1)
     t.repartitionAndSortWithinPartitions(partitioner)

  }
}
}
</code>```

I am getting error as -
value repartitionAndSortWithinPartitions is not a member of org.apache.spark.rdd.RDD[(DeviceKey, Int)]

Can somebody have a look?

Thanks & Regards
Pari

答:
This answer is shared by Yong Zhang through spark user email group.

ANSWER

The error message indeed is not very clear.

What you did wrong is that the repartitionAndSortWithinPartitions not only requires PairRDD, but also OrderedRDD. Your case class as key is NOT Ordered.

Either you extends it from Ordered, or provide a companion object to do the implicit Ordering.

```<code>scala> spark.version
res1: String = 2.1.0

scala> case class DeviceKey(serialNum: String, eventDate: String, EventTs: Long)
extends Ordered[DeviceKey] {
     |   import scala.math.Ordered.orderingToOrdered
     |   def compare(that: DeviceKey): Int =
     |      (this.serialNum, this.eventDate, this.EventTs * -1) compare
     |      (that.serialNum, that.eventDate, that.EventTs * -1)
     | }
defined class DeviceKey

scala>

scala> val t = sc.parallelize(List(((DeviceKey("2","100",1),1)),
(DeviceKey("2","100",3),1)), 1)
t: org.apache.spark.rdd.RDD[(DeviceKey, Int)] = ParallelCollectionRDD[0] at parallelize at <console>:26

scala>

scala> class DeviceKeyPartitioner(partitions: Int) extends org.apache.spark.Partitioner {
     |     require(partitions >= 0, s"Number of partitions ($partitions) cannot be negative.")
     |
     |     override def numPartitions: Int = partitions
     |
     |     override def getPartition(key: Any): Int = {
     |       val k = key.asInstanceOf[DeviceKey]
     |       k.serialNum.hashCode() % numPartitions
     |     }
     | }
defined class DeviceKeyPartitioner

scala>

scala> t.repartitionAndSortWithinPartitions(new DeviceKeyPartitioner(2))
res0: org.apache.spark.rdd.RDD[(DeviceKey, Int)] = ShuffledRDD[1] at repartitionAndSortWithinPartitions at <console>:30
</code>```

Title: Secondary Sort using Apache Spark 1.6

Body:
I am referring web link http://codingjunkie.net/spark-secondary-sort/
to implement secondary sort in my spark job.

import org.apache.spark.SparkContext
import org.apache.spark.SparkContext._
import org.apache.spark.SparkConf
import org.apache.spark.Partitioner

package Ssort {
case class DeviceKey(serialNum: String, eventDate: String, EventTs: Long) {
      implicit def orderingBySerialNum[A <: DeviceKey] : Ordering[A] = {
       Ordering.by(fk => (fk.serialNum, fk.eventDate, fk.EventTs * -1))
    }
}

class DeviceKeyPartitioner(partitions: Int) extends Partitioner {
    require(partitions >= 0, s"Number of partitions ($partitions) cannot be negative.")

    override def numPartitions: Int = partitions

    override def getPartition(key: Any): Int = {
      val k = key.asInstanceOf[DeviceKey]
      k.serialNum.hashCode() % numPartitions
    }
}

object SparkApp {
  def main(args: Array[String]) {
    val conf = new SparkConf().setAppName("Spark Application").setMaster("local[2]")
    val sc = new SparkContext(conf)
    val t = sc.parallelize(List(((DeviceKey("2","100",1),1)),(DeviceKey("2","100",3),1)), 1)
     t.repartitionAndSortWithinPartitions(partitioner)

  }
}
}

I am getting error as -
value repartitionAndSortWithinPartitions is not a member of org.apache.spark.rdd.RDD[(DeviceKey, Int)]

Can somebody have a look?

Thanks & Regards
Pari

Body:
This answer is shared by Yong Zhang through spark user email group.

ANSWER

The error message indeed is not very clear.

What you did wrong is that the repartitionAndSortWithinPartitions not only requires PairRDD, but also OrderedRDD. Your case class as key is NOT Ordered.

Either you extends it from Ordered, or provide a companion object to do the implicit Ordering.

scala> spark.version
res1: String = 2.1.0

scala> case class DeviceKey(serialNum: String, eventDate: String, EventTs: Long)
extends Ordered[DeviceKey] {
     |   import scala.math.Ordered.orderingToOrdered
     |   def compare(that: DeviceKey): Int =
     |      (this.serialNum, this.eventDate, this.EventTs * -1) compare
     |      (that.serialNum, that.eventDate, that.EventTs * -1)
     | }
defined class DeviceKey

scala>

scala> val t = sc.parallelize(List(((DeviceKey("2","100",1),1)),
(DeviceKey("2","100",3),1)), 1)
t: org.apache.spark.rdd.RDD[(DeviceKey, Int)] = ParallelCollectionRDD[0] at parallelize at <console>:26

scala>

scala> class DeviceKeyPartitioner(partitions: Int) extends org.apache.spark.Partitioner {
     |     require(partitions >= 0, s"Number of partitions ($partitions) cannot be negative.")
     |
     |     override def numPartitions: Int = partitions
     |
     |     override def getPartition(key: Any): Int = {
     |       val k = key.asInstanceOf[DeviceKey]
     |       k.serialNum.hashCode() % numPartitions
     |     }
     | }
defined class DeviceKeyPartitioner

scala>

scala> t.repartitionAndSortWithinPartitions(new DeviceKeyPartitioner(2))
res0: org.apache.spark.rdd.RDD[(DeviceKey, Int)] = ShuffledRDD[1] at repartitionAndSortWithinPartitions at <console>:30


问:
Data are not shown in BroadcastReceiver using Android
I want to use Firebase in my application and show the token when calling the service and Broadcast! I write the below codes, but it didn't show any more in the textview!

MyFCMInstance :

```<code>public class MyFCMInstance extends FirebaseInstanceIdService {

    public static final String TOKEN_BROADCAST = "fcmtokenbroadcast";

    @Override
    public void onCreate() {
        super.onCreate();
        String CurrentToken = FirebaseInstanceId.getInstance().getToken();
        if (CurrentToken != null) {
            Intent intent = new Intent("Token");
            LocalBroadcastManager.getInstance(this).sendBroadcast(intent);
            Log.d("token", "Refreshed token: " + CurrentToken);
            storeToken(CurrentToken);
            getApplicationContext().sendBroadcast(new Intent(TOKEN_BROADCAST));

        } else {
            onTokenRefresh();
        }
    }

    @Override
    public void onTokenRefresh() {

        String refreshedToken = FirebaseInstanceId.getInstance().getToken();
        Log.e("FCM Instance", "Token : " + refreshedToken);

        // store token
        storeToken(refreshedToken);

        // send broadcast
        getApplicationContext().sendBroadcast(new Intent(TOKEN_BROADCAST));
    }

    private void storeToken(String token) {
        SharedPrefsManager.getInstance(getApplicationContext()).storeToken(token);
    }
}
</code>```

SharedPrefsManager codes:

```<code>public class SharedPrefsManager {

    private static final String SHARED_PREF_NAME = "FCMPrefs";
    private static final String KEY_ACCESS_TOKEN = "Token";
    private static Context mContext;
    private static SharedPrefsManager mInstance;

    public SharedPrefsManager(Context context) {
        mContext = context;
    }

    public static synchronized SharedPrefsManager getInstance(Context context) {
        if (mInstance == null) {
            mInstance = new SharedPrefsManager(context);
        }
        return mInstance;
    }

    public boolean storeToken(String token) {
        SharedPreferences preferences = mContext.getSharedPreferences(SHARED_PREF_NAME, Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = preferences.edit();
        editor.putString(KEY_ACCESS_TOKEN, token);
        editor.apply();

        return true;
    }

    public String getToken() {
        SharedPreferences preferences = mContext.getSharedPreferences(SHARED_PREF_NAME, Context.MODE_PRIVATE);
        String token = preferences.getString(KEY_ACCESS_TOKEN, null);

        return token;
    }
}
</code>```

MainActivity codes:

```<code>public class MainActivity extends AppCompatActivity {

    private TextView tokenTV;
    private BroadcastReceiver broadcastReceiver;
    private Context context;

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

        tokenTV = (TextView) findViewById(R.id.tokenText);
        context = MainActivity.this;
        broadcastReceiver = new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                tokenTV.setText(SharedPrefsManager.getInstance(context).getToken());
            }
        };
        registerReceiver(broadcastReceiver, new IntentFilter(MyFCMInstance.TOKEN_BROADCAST));
    }
}
</code>```

How can I fix it and show the token in TextView ?

答:
onTokenRefresh() method is only called once after you install your application. SO in your code it will only show token once and that too only first time.
Override onCreate() method in your fcm service class and do something like this

```<code> @Override
    public void onCreate() {
        super.onCreate();
        String CurrentToken = FirebaseInstanceId.getInstance().getToken();
        if (CurrentToken!=null){
            Intent intent = new Intent("device_id");
            LocalBroadcastManager.getInstance(this).sendBroadcast(intent);
            Log.d("token", "Refreshed token: " + CurrentToken);
            appSharedPreferences.putString("device_id",CurrentToken);
            getApplicationContext().sendBroadcast(new Intent(TOKEN_BROADCAST));

        }
        else {
          onTokenRefresh();

                   }
}
</code>```

Body:
I want to use Firebase in my application and show the token when calling the service and Broadcast! I write the below codes, but it didn't show any more in the textview!

MyFCMInstance :

public class MyFCMInstance extends FirebaseInstanceIdService {

    public static final String TOKEN_BROADCAST = "fcmtokenbroadcast";

    @Override
    public void onCreate() {
        super.onCreate();
        String CurrentToken = FirebaseInstanceId.getInstance().getToken();
        if (CurrentToken != null) {
            Intent intent = new Intent("Token");
            LocalBroadcastManager.getInstance(this).sendBroadcast(intent);
            Log.d("token", "Refreshed token: " + CurrentToken);
            storeToken(CurrentToken);
            getApplicationContext().sendBroadcast(new Intent(TOKEN_BROADCAST));

        } else {
            onTokenRefresh();
        }
    }

    @Override
    public void onTokenRefresh() {

        String refreshedToken = FirebaseInstanceId.getInstance().getToken();
        Log.e("FCM Instance", "Token : " + refreshedToken);

        // store token
        storeToken(refreshedToken);

        // send broadcast
        getApplicationContext().sendBroadcast(new Intent(TOKEN_BROADCAST));
    }

    private void storeToken(String token) {
        SharedPrefsManager.getInstance(getApplicationContext()).storeToken(token);
    }
}

SharedPrefsManager codes:

public class SharedPrefsManager {

    private static final String SHARED_PREF_NAME = "FCMPrefs";
    private static final String KEY_ACCESS_TOKEN = "Token";
    private static Context mContext;
    private static SharedPrefsManager mInstance;

    public SharedPrefsManager(Context context) {
        mContext = context;
    }

    public static synchronized SharedPrefsManager getInstance(Context context) {
        if (mInstance == null) {
            mInstance = new SharedPrefsManager(context);
        }
        return mInstance;
    }

    public boolean storeToken(String token) {
        SharedPreferences preferences = mContext.getSharedPreferences(SHARED_PREF_NAME, Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = preferences.edit();
        editor.putString(KEY_ACCESS_TOKEN, token);
        editor.apply();

        return true;
    }

    public String getToken() {
        SharedPreferences preferences = mContext.getSharedPreferences(SHARED_PREF_NAME, Context.MODE_PRIVATE);
        String token = preferences.getString(KEY_ACCESS_TOKEN, null);

        return token;
    }
}

MainActivity codes:

public class MainActivity extends AppCompatActivity {

    private TextView tokenTV;
    private BroadcastReceiver broadcastReceiver;
    private Context context;

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

        tokenTV = (TextView) findViewById(R.id.tokenText);
        context = MainActivity.this;
        broadcastReceiver = new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                tokenTV.setText(SharedPrefsManager.getInstance(context).getToken());
            }
        };
        registerReceiver(broadcastReceiver, new IntentFilter(MyFCMInstance.TOKEN_BROADCAST));
    }
}

How can I fix it and show the token in TextView ?

Body:
onTokenRefresh() method is only called once after you install your application. SO in your code it will only show token once and that too only first time.
Override onCreate() method in your fcm service class and do something like this

 @Override
    public void onCreate() {
        super.onCreate();
        String CurrentToken = FirebaseInstanceId.getInstance().getToken();
        if (CurrentToken!=null){
            Intent intent = new Intent("device_id");
            LocalBroadcastManager.getInstance(this).sendBroadcast(intent);
            Log.d("token", "Refreshed token: " + CurrentToken);
            appSharedPreferences.putString("device_id",CurrentToken);
            getApplicationContext().sendBroadcast(new Intent(TOKEN_BROADCAST));

        }
        else {
          onTokenRefresh();

                   }
}


问:
Swift 3 Send Location as iMessage
I have made a classic "find-my-car-app" which saves a map location and navigates back there. I now want to implement a share button, to send a saved location via iMessage.

I have set up a MFMessageComposeViewController, in order to send a message body with the coordinates.

Using the URL method like: http://maps.apple.com/?ll=40.730610,-73.935242" does work, and opens the Maps app. What I'm missing is the map thumbnail in the message.

When sharing my location from iMessage or Maps, I get a nifty little map preview with the red pin in the message.
Copying the iMessage link on the Mac shows, that it's sent as a VCF card, but I found no way of sending a link in VCF format via iMessage.

Does anybody know how to get that map preview working?

Hope my question is clear enough!

Thanks

答:
Use this to create a VCF file: https://gist.github.com/naturaln0va/e1fed3f1d32ecf951aac

Than:

```<code>MFMessageComposeViewController ().addAttachmentURL(Global.locationVCardURLFromCoordinate(coordinate: CLLocationCoordinate2D(latitude: 30, longitude: 40))!, withAlternateFilename: "vCard.loc.vcf")
</code>```

Title: Swift 3 Send Location as iMessage

Body:
Use this to create a VCF file: https://gist.github.com/naturaln0va/e1fed3f1d32ecf951aac

Than:

MFMessageComposeViewController ().addAttachmentURL(Global.locationVCardURLFromCoordinate(coordinate: CLLocationCoordinate2D(latitude: 30, longitude: 40))!, withAlternateFilename: "vCard.loc.vcf")


问:
REST API : Passing Colon (:) in url using attribute Routing doesn't work
I am using swagger ui to test a POST method. I am passing the parameter in URL but it doesn't work.

swagger-ui:

I enter this
 Date: 2017-03-03T12:12:12
 this is how it goes
  in
 url: https://servername/Results/2017-03-03T12%3A12%3A12

 This doesn't work. it return 404 error

but when i pass just the date it works.

Date: 2017-03-03

my method:

[Route("{Results/{date}"), HttpPost]
 public
  Common.CallDetails StartTCISCall(DateTime date)

I have tried this also but it doesn't even catch it as a string.

[Route("{Results/{*date}"), HttpPost]
 public
  Common.CallDetails StartTCISCall(string date)

as soon as i take the colons out it starts to work. What can i do?

Also, for my friend it works locally on VS but when he publishes to IIS it doesn't work and we tried 3 different servers. Why is this?

Many thanks, Please help.

答:
First of all it seems like encoded URLs only work, after the ? for global variables, according to this: URL encoding. So it won't work for routing in c#.

For encoded strings after the question mark u have to decode the string like this:

```<code>string result = Server.UrlDecode(date);
</code>```

Your URL should be build like this:

```<code>https://servername/Results?2017-03-03T12%3A12%3A12
</code>```

Body:
First of all it seems like encoded URLs only work, after the ? for global variables, according to this: URL encoding. So it won't work for routing in c#.

For encoded strings after the question mark u have to decode the string like this:

string result = Server.UrlDecode(date);

Your URL should be build like this:

https://servername/Results?2017-03-03T12%3A12%3A12


问:
what is IMPORT alternative in arm gnu assembler?
I am reading the book for learning ARM and ARM assembly.. examples in book is based on armcc compiler but I am using arm-none-eabi-gcc. so how can change this peace of code to gnu assembler??

```<code>IMPORT |Lib$$Request$$armlib|,WEAK.
</code>```

whole example is :

```<code>    AREA |.text|, CODE , READONLY
    EXPORT main
    IMPORT |Lib$$Request$$armlib|,WEAK
    IMPORT __main ;C library entry
    IMPORT printf ; prints to stdout
i   RN 4
    ;int main(void)
main
    STMFD sp!,{i,lr}
    MOV i,#0
loop
   ADR r0, print_string
   MOV r1,i
   MUL r2,i,i
   BL printf
   ADD i,i,#1
   CMP i,#10
   BLT loop
   LDMFD sp!,{i,pc}
print_string
   DCB "Square of %d is %d\n",0
   END
</code>```

so I converted it to

```<code> .section .text
    .weak Lib$$Request$$armlib
    .global main
    i .req r4
main:
    STMFD sp!,{i,lr}
    MOV i,#0
loop:
    ADR r0,print_string
    MOV r1,i
    MUL r2,i,i
    BL printf
    ADD i,i,#1
    CMP i,#10
    BLT loop
    LDMFD sp!,{i,pc}
print_string:
    .ascii "Square of %d is %d\n"
    .end
</code>```

I am using ARMSim for simulating ... but I get some error:

Undefined symbol printf
address is not in text section
so how can include "stdio.h" for using printf or what is wrong generally??

答:
In the GNU assembler, you do not need to declare symbols you use. If you use a symbol and that symbol isn't defined anywhere, it will be entered as an undefined symbol into your object file.

To define a symbol as a weak symbol, write:

```<code>.weak sym
</code>```

where sym is the name of the symbol.

Body:
I am reading the book for learning ARM and ARM assembly.. examples in book is based on armcc compiler but I am using arm-none-eabi-gcc. so how can change this peace of code to gnu assembler??

IMPORT |Lib$$Request$$armlib|,WEAK.

whole example is :

    AREA |.text|, CODE , READONLY
    EXPORT main
    IMPORT |Lib$$Request$$armlib|,WEAK
    IMPORT __main ;C library entry
    IMPORT printf ; prints to stdout
i   RN 4
    ;int main(void)
main
    STMFD sp!,{i,lr}
    MOV i,#0
loop
   ADR r0, print_string
   MOV r1,i
   MUL r2,i,i
   BL printf
   ADD i,i,#1
   CMP i,#10
   BLT loop
   LDMFD sp!,{i,pc}
print_string
   DCB "Square of %d is %d\n",0
   END

so I converted it to

 .section .text
    .weak Lib$$Request$$armlib
    .global main
    i .req r4
main:
    STMFD sp!,{i,lr}
    MOV i,#0
loop:
    ADR r0,print_string
    MOV r1,i
    MUL r2,i,i
    BL printf
    ADD i,i,#1
    CMP i,#10
    BLT loop
    LDMFD sp!,{i,pc}
print_string:
    .ascii "Square of %d is %d\n"
    .end

I am using ARMSim for simulating ... but I get some error:

Undefined symbol printf
address is not in text section
so how can include "stdio.h" for using printf or what is wrong generally??

Body:
In the GNU assembler, you do not need to declare symbols you use. If you use a symbol and that symbol isn't defined anywhere, it will be entered as an undefined symbol into your object file.

To define a symbol as a weak symbol, write:

.weak sym

where sym is the name of the symbol.


问:
What is "this" in javascript when calling a method on a calculated object?
I know this is probably the second most asked-about thing in javascript, right after floating point arithmetic.

I generally know how this works, and how it's affected by arrow functions, .call(), .apply(), and .bind().  I thought I understood everything about it.  But I do not.

In a web browser, document.createElement("div").classList.add("c") yields undefined as expected.  However, this expression surprisingly is an error.

```<code>(true && document.createElement("div").classList.add)("c")
</code>```

I expected it to be the same, but it's

```<code>Uncaught TypeError: Illegal invocation
    at <anonymous>:1:54
</code>```

答:
Your statement

(true && document.createElement("div").classList.add)("c")  can also be rewritten as following:

```<code>var add = (true && document.createElement("div").classList.add)
add("c")
</code>```

[Logical AND (&&) expr1 && expr2 : Returns expr1 if it can be converted to false; otherwise, returns expr2.]

You see that function add is now part of window and loses reference of actual classList object and hence cannot be called correctly.

add's this now points to global object.

If you do following (if the new div is the only div on your page), it again has reference to the original object:

```<code>(true && document.createElement("div").classList.add).bind(document.getElementsByTagName("div")[0].classList)("c")
</code>```

Body:
I know this is probably the second most asked-about thing in javascript, right after floating point arithmetic.

I generally know how this works, and how it's affected by arrow functions, .call(), .apply(), and .bind().  I thought I understood everything about it.  But I do not.

In a web browser, document.createElement("div").classList.add("c") yields undefined as expected.  However, this expression surprisingly is an error.

(true && document.createElement("div").classList.add)("c")

I expected it to be the same, but it's

Uncaught TypeError: Illegal invocation
    at <anonymous>:1:54

Body:
Your statement

(true && document.createElement("div").classList.add)("c")  can also be rewritten as following:

var add = (true && document.createElement("div").classList.add)
add("c")

[Logical AND (&&) expr1 && expr2 : Returns expr1 if it can be converted to false; otherwise, returns expr2.]

You see that function add is now part of window and loses reference of actual classList object and hence cannot be called correctly.

add's this now points to global object.

If you do following (if the new div is the only div on your page), it again has reference to the original object:

(true && document.createElement("div").classList.add).bind(document.getElementsByTagName("div")[0].classList)("c")


问:
Can't clone gitlab repo via ssh on aws ec2
It seems that this problem is usual, but after a lot of searching, I didn't find any solutions.

I can't clone repositories on a gitlab instance hosted on aws ec2.

```<code>Clonage dans 'angular2'...
Permission denied (publickey).
fatal: Could not read from remote repository.

Please make sure you have the correct access rights
and the repository exists.
</code>```

I tried to use a config file for my ssh without result.

Here is the output of ssh -vT command

```<code>OpenSSH_7.2p2 Ubuntu-4ubuntu2.1, OpenSSL 1.0.2g  1 Mar 2016
debug1: Reading configuration data /etc/ssh/ssh_config
debug1: /etc/ssh/ssh_config line 19: Applying options for *
debug1: Connecting to gitlab.com [52.167.219.168] port 22.
debug1: Connection established.
debug1: identity file /home/chd/.ssh/id_rsa type 1
debug1: key_load_public: No such file or directory
debug1: identity file /home/chd/.ssh/id_rsa-cert type -1
debug1: key_load_public: No such file or directory
debug1: identity file /home/chd/.ssh/id_dsa type -1
debug1: key_load_public: No such file or directory
debug1: identity file /home/chd/.ssh/id_dsa-cert type -1
debug1: key_load_public: No such file or directory
debug1: identity file /home/chd/.ssh/id_ecdsa type -1
debug1: key_load_public: No such file or directory
debug1: identity file /home/chd/.ssh/id_ecdsa-cert type -1
debug1: key_load_public: No such file or directory
debug1: identity file /home/chd/.ssh/id_ed25519 type -1
debug1: key_load_public: No such file or directory
debug1: identity file /home/chd/.ssh/id_ed25519-cert type -1
debug1: Enabling compatibility mode for protocol 2.0
debug1: Local version string SSH-2.0-OpenSSH_7.2p2 Ubuntu-4ubuntu2.1
debug1: Remote protocol version 2.0, remote software version
OpenSSH_7.2p2 Ubuntu-4ubuntu2.1
debug1: match: OpenSSH_7.2p2 Ubuntu-4ubuntu2.1 pat OpenSSH* compat 0x04000000
debug1: Authenticating to gitlab.com:22 as 'git'
debug1: SSH2_MSG_KEXINIT sent
debug1: SSH2_MSG_KEXINIT received
debug1: kex: algorithm: curve25519-sha256@libssh.org
debug1: kex: host key algorithm: ecdsa-sha2-nistp256
debug1: kex: server->client cipher: chacha20-poly1305@openssh.com MAC: <implicit> compression: none
debug1: kex: client->server cipher: chacha20-poly1305@openssh.com MAC: <implicit> compression: none
debug1: expecting SSH2_MSG_KEX_ECDH_REPLY
debug1: Server host key: ecdsa-sha2-nistp256 SHA256:HbW3g8zUjNSksFbqTiUWPWg2Bq1x8xdGUrliXFzSnUw
debug1: Host 'gitlab.com' is known and matches the ECDSA host key.
debug1: Found key in /home/chd/.ssh/known_hosts:3
debug1: rekey after 134217728 blocks
debug1: SSH2_MSG_NEWKEYS sent
debug1: expecting SSH2_MSG_NEWKEYS
debug1: rekey after 134217728 blocks
debug1: SSH2_MSG_NEWKEYS received
debug1: SSH2_MSG_EXT_INFO received
debug1: kex_input_ext_info: server-sig-algs=<rsa-sha2-256,rsa-sha2-512>
debug1: SSH2_MSG_SERVICE_ACCEPT received
debug1: Authentications that can continue: publickey
debug1: Next authentication method: publickey
debug1: Offering RSA public key: /home/chd/.ssh/id_rsa
debug1: Authentications that can continue: publickey
debug1: Trying private key: /home/chd/.ssh/id_dsa
debug1: Trying private key: /home/chd/.ssh/id_ecdsa
debug1: Trying private key: /home/chd/.ssh/id_ed25519
debug1: No more authentication methods to try.
Permission denied (publickey).
</code>```

I precise I don't have the hand on aws instance.

Thanks for helping.

答:
change the remote url from ssh to https

use git remote origin set-url <your https url> to change in the directory where you initialized the git repo

Body:
It seems that this problem is usual, but after a lot of searching, I didn't find any solutions.

I can't clone repositories on a gitlab instance hosted on aws ec2.

Clonage dans 'angular2'...
Permission denied (publickey).
fatal: Could not read from remote repository.

Please make sure you have the correct access rights
and the repository exists.

I tried to use a config file for my ssh without result.

Here is the output of ssh -vT command

OpenSSH_7.2p2 Ubuntu-4ubuntu2.1, OpenSSL 1.0.2g  1 Mar 2016
debug1: Reading configuration data /etc/ssh/ssh_config
debug1: /etc/ssh/ssh_config line 19: Applying options for *
debug1: Connecting to gitlab.com [52.167.219.168] port 22.
debug1: Connection established.
debug1: identity file /home/chd/.ssh/id_rsa type 1
debug1: key_load_public: No such file or directory
debug1: identity file /home/chd/.ssh/id_rsa-cert type -1
debug1: key_load_public: No such file or directory
debug1: identity file /home/chd/.ssh/id_dsa type -1
debug1: key_load_public: No such file or directory
debug1: identity file /home/chd/.ssh/id_dsa-cert type -1
debug1: key_load_public: No such file or directory
debug1: identity file /home/chd/.ssh/id_ecdsa type -1
debug1: key_load_public: No such file or directory
debug1: identity file /home/chd/.ssh/id_ecdsa-cert type -1
debug1: key_load_public: No such file or directory
debug1: identity file /home/chd/.ssh/id_ed25519 type -1
debug1: key_load_public: No such file or directory
debug1: identity file /home/chd/.ssh/id_ed25519-cert type -1
debug1: Enabling compatibility mode for protocol 2.0
debug1: Local version string SSH-2.0-OpenSSH_7.2p2 Ubuntu-4ubuntu2.1
debug1: Remote protocol version 2.0, remote software version
OpenSSH_7.2p2 Ubuntu-4ubuntu2.1
debug1: match: OpenSSH_7.2p2 Ubuntu-4ubuntu2.1 pat OpenSSH* compat 0x04000000
debug1: Authenticating to gitlab.com:22 as 'git'
debug1: SSH2_MSG_KEXINIT sent
debug1: SSH2_MSG_KEXINIT received
debug1: kex: algorithm: curve25519-sha256@libssh.org
debug1: kex: host key algorithm: ecdsa-sha2-nistp256
debug1: kex: server->client cipher: chacha20-poly1305@openssh.com MAC: <implicit> compression: none
debug1: kex: client->server cipher: chacha20-poly1305@openssh.com MAC: <implicit> compression: none
debug1: expecting SSH2_MSG_KEX_ECDH_REPLY
debug1: Server host key: ecdsa-sha2-nistp256 SHA256:HbW3g8zUjNSksFbqTiUWPWg2Bq1x8xdGUrliXFzSnUw
debug1: Host 'gitlab.com' is known and matches the ECDSA host key.
debug1: Found key in /home/chd/.ssh/known_hosts:3
debug1: rekey after 134217728 blocks
debug1: SSH2_MSG_NEWKEYS sent
debug1: expecting SSH2_MSG_NEWKEYS
debug1: rekey after 134217728 blocks
debug1: SSH2_MSG_NEWKEYS received
debug1: SSH2_MSG_EXT_INFO received
debug1: kex_input_ext_info: server-sig-algs=<rsa-sha2-256,rsa-sha2-512>
debug1: SSH2_MSG_SERVICE_ACCEPT received
debug1: Authentications that can continue: publickey
debug1: Next authentication method: publickey
debug1: Offering RSA public key: /home/chd/.ssh/id_rsa
debug1: Authentications that can continue: publickey
debug1: Trying private key: /home/chd/.ssh/id_dsa
debug1: Trying private key: /home/chd/.ssh/id_ecdsa
debug1: Trying private key: /home/chd/.ssh/id_ed25519
debug1: No more authentication methods to try.
Permission denied (publickey).

I precise I don't have the hand on aws instance.

Thanks for helping.


问:
How do i set the cursor in a html editor using IE (7-8)
Actually i am trying to set the cursor to a specific node inside a html editor (which uses a contenteditable iframe). For example i have several paragraphs and want the cursor to move to the start of the previous paragraph.
Unfortunatly, the Internet Explorers range object does not support setStartBefore and setStartAfter. The ierange project is not an option - the solution i am looking for needs to work with IE out of the box.

How do i set the cursor in IE?

In Firefox the solution is straight forward:

```<code>// sets the cursor position (start defines, if cursor is needed at the start or end of the node)
function setCursor(editor, node, start){

var tn = editor.getDoc().createTextNode("."); // gets the editors document
  if (start){
    node.insertBefore(tn, node.firstChild);
  }
  else node.appendChild(tn);

  rng = editor.selection.getRng();  // gets the browsers range object for the users selection
  rng.selectNode(tn);
  rng.setStartBefore(tn);
  rng.setStartAfter(tn);

  ed.selection.setRng(rng);
  node.removeChild(tn);  // removes the caret node - curser is placed now
}
</code>```

答:
Working with the Cursor Position
(This solution works for me in IE, Firefox and Opera)

Body:
Actually i am trying to set the cursor to a specific node inside a html editor (which uses a contenteditable iframe). For example i have several paragraphs and want the cursor to move to the start of the previous paragraph.
Unfortunatly, the Internet Explorers range object does not support setStartBefore and setStartAfter. The ierange project is not an option - the solution i am looking for needs to work with IE out of the box.

How do i set the cursor in IE?

In Firefox the solution is straight forward:

// sets the cursor position (start defines, if cursor is needed at the start or end of the node)
function setCursor(editor, node, start){

var tn = editor.getDoc().createTextNode("."); // gets the editors document
  if (start){
    node.insertBefore(tn, node.firstChild);
  }
  else node.appendChild(tn);

  rng = editor.selection.getRng();  // gets the browsers range object for the users selection
  rng.selectNode(tn);
  rng.setStartBefore(tn);
  rng.setStartAfter(tn);

  ed.selection.setRng(rng);
  node.removeChild(tn);  // removes the caret node - curser is placed now
}


问:
Element width decreasing in one direction
I ran into situation earlier where I have a position relative container with a position absolute element inside. The element inside contains an image that has a max width of 100%. If I move this element which I have called "item" in the fiddle below using "left" the width of the element decreases the further I go to the right (does not happen if moving to the left with negative values). This happens the opposite way if use the css rule "right". If I take the width declaration off the image this no longer occurs. Does anyone know why this is the case. Here is a fiddle I created to show the issue.

```<code>.container {
  position:relative;
  overflow:hidden;
  padding-bottom:32%;
}

.item {
  position:absolute;
}

.content {
  width:400px;
  margin:auto;

}

img {
  max-width:100%;
}

<div class="content">
<div class = "container">
  <div class = "item">
    <a href='https://postimg.org/image/h3h0e82rx/' target='_blank'><img src='https://s22.postimg.org/kabjxun81/banner.jpg' border='0' alt='banner'/><br /><a target='_blank' href='https://postimage.org/'></a><br /><br />
  </div>
</div>
</div>
</code>```

https://jsfiddle.net/rv9wcqh2/

An explanation would be greatly appreciated.

答:
You can achieve your desired behaviour setting a width of 100% to element

The positive values for the left and right properties constrain the width, but negative ones don't.

As a side note, your  elements in the fiddle are miss matched

.container {
  position:relative;
  overflow:hidden;
  padding-bottom:32%;
}

.item {
  position:absolute;
  width: 100%;  /* added */
}

.content {
  width:400px;
  margin:auto;

}

img {
  max-width:100%;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="content">
<div class = "container">
  <div class = "item">
  <img src='https://s22.postimg.org/kabjxun81/banner.jpg' border='0' alt='banner'/>
  <br />
  <br><br>
  </div>
</div>
</div></code>```

Body:
I ran into situation earlier where I have a position relative container with a position absolute element inside. The element inside contains an image that has a max width of 100%. If I move this element which I have called "item" in the fiddle below using "left" the width of the element decreases the further I go to the right (does not happen if moving to the left with negative values). This happens the opposite way if use the css rule "right". If I take the width declaration off the image this no longer occurs. Does anyone know why this is the case. Here is a fiddle I created to show the issue.

.container {
  position:relative;
  overflow:hidden;
  padding-bottom:32%;
}

.item {
  position:absolute;
}

.content {
  width:400px;
  margin:auto;

}

img {
  max-width:100%;
}

https://jsfiddle.net/rv9wcqh2/

An explanation would be greatly appreciated.

Body:
You can achieve your desired behaviour setting a width of 100% to element

The positive values for the left and right properties constrain the width, but negative ones don't.

As a side note, your  elements in the fiddle are miss matched

.container {
  position:relative;
  overflow:hidden;
  padding-bottom:32%;
}

.item {
  position:absolute;
  width: 100%;  /* added */
}

.content {
  width:400px;
  margin:auto;

}

img {
  max-width:100%;
}

<div class="content">
<div class = "container">
  <div class = "item">
  <a href='https://postimg.org/image/h3h0e82rx/' target='_blank'><img src='https://s22.postimg.org/kabjxun81/banner.jpg' border='0' alt='banner'/></a>
  <br />
  <a target='_blank' href='https://postimage.org/'></a><br><br>
  </div>
</div>
</div>


问:
How to use Web Scraping After login using MVC .net, If API to login is not available
I have to achieve Web Scraping using MVC .net, But firstly i have to login to second site to fetch data (Like login to Admin) where API to login is not available.

For example i have to Scrape data from https://talent.stackoverflow.com/users/login
but after login i want to fetch data from user page. Is it possible to Scrape data from this url after login through MVC .Net, if i have credentials.

答:
If you are going to make a crawler than you need to go ahead with any client side scripting.

I suggest you, If you have any idea of data crawling than go ahead with PhantomJs or CasperJs because its provide many functions especially for scraping.

As an example, CasperJs identify the process execution one by one.
Lets say You are login into any website and you need to wait for response than CasperJs provide "then" function to determine for response.

Lets take another example, If you hits many request and web site might be gives captcha screen to enter captcha code in this circumstances you can take screenshot of that and handle captcha at runtime.


问:
How can I transform a string into an abbreviated form?
I want to fit strings into a specific width. Example, "Hello world" -> "...world", "Hello...", "He...rld".

Do you know where I can find code for that? It's a neat trick, very useful for representing information, and I'd like to add it in my applications (of course).

Edit: Sorry, I forgot to mention the Font part. Not just for fixed width strings but according to the font face.

答:
If you just want the "standard" ellipsis format, ("Hello...") you can use the
DrawText (or the equivalient MFC function) function passing DT_END_ELLIPSIS.

Check out also DT_WORD_ELLIPSIS (it truncates any word that does not fit in the rectangle and adds ellipses) or DT_PATH_ELLIPSIS (what Explorer does to display long paths).


问:
Django 1.8 migrate is not creating tables
```<code>yekabathula-macbookair2:roster yekabathula$ python manage.py migrate
Operations to perform:
  Synchronize unmigrated apps: staticfiles, messages
  Apply all migrations: admin, contenttypes, api, auth, sessions
Synchronizing apps without migrations:
  Creating tables...
    Running deferred SQL...
  Installing custom SQL...
Running migrations:
  Rendering model states... DONE
  Applying contenttypes.0001_initial... OK
  Applying auth.0001_initial... OK
  Applying admin.0001_initial... OK
  Applying api.0001_initial... OK
  Applying contenttypes.0002_remove_content_type_name... OK
  Applying auth.0002_alter_permission_name_max_length... OK
  Applying auth.0003_alter_user_email_max_length... OK
  Applying auth.0004_alter_user_username_opts... OK
  Applying auth.0005_alter_user_last_login_null... OK
  Applying auth.0006_require_contenttypes_0002... OK
  Applying sessions.0001_initial... OK
yekabathula-macbookair2:roster yekabathula$ python manage.py syncdb
/Library/Python/2.7/site-packages/django/core/management/commands/syncdb.py:24: RemovedInDjango19Warning: The syncdb command will be removed in Django 1.9
  warnings.warn("The syncdb command will be removed in Django 1.9", RemovedInDjango19Warning)

Operations to perform:
  Synchronize unmigrated apps: staticfiles, messages
  Apply all migrations: admin, contenttypes, api, auth, sessions
Synchronizing apps without migrations:
  Creating tables...
    Running deferred SQL...
  Installing custom SQL...
Running migrations:
  No migrations to apply.
</code>```

After doing python manage.py migrate, tables are not created in database from my models.py it is able to create other tables from django_session etc. Is there anything else that I need to follow here ?

答:
Delete existing tables of the models in MySQL database.

Delete migration folder under app folder.

Delete all relative migration records in the table

"django_migrations" from MySQL.

Now you get clear model and database. Use
python manage.py makemigrations and python manage.py migrate
to create tables.

Hope to help you.

Body:
yekabathula-macbookair2:roster yekabathula$ python manage.py migrate
Operations to perform:
  Synchronize unmigrated apps: staticfiles, messages
  Apply all migrations: admin, contenttypes, api, auth, sessions
Synchronizing apps without migrations:
  Creating tables...
    Running deferred SQL...
  Installing custom SQL...
Running migrations:
  Rendering model states... DONE
  Applying contenttypes.0001_initial... OK
  Applying auth.0001_initial... OK
  Applying admin.0001_initial... OK
  Applying api.0001_initial... OK
  Applying contenttypes.0002_remove_content_type_name... OK
  Applying auth.0002_alter_permission_name_max_length... OK
  Applying auth.0003_alter_user_email_max_length... OK
  Applying auth.0004_alter_user_username_opts... OK
  Applying auth.0005_alter_user_last_login_null... OK
  Applying auth.0006_require_contenttypes_0002... OK
  Applying sessions.0001_initial... OK
yekabathula-macbookair2:roster yekabathula$ python manage.py syncdb
/Library/Python/2.7/site-packages/django/core/management/commands/syncdb.py:24: RemovedInDjango19Warning: The syncdb command will be removed in Django 1.9
  warnings.warn("The syncdb command will be removed in Django 1.9", RemovedInDjango19Warning)

Operations to perform:
  Synchronize unmigrated apps: staticfiles, messages
  Apply all migrations: admin, contenttypes, api, auth, sessions
Synchronizing apps without migrations:
  Creating tables...
    Running deferred SQL...
  Installing custom SQL...
Running migrations:
  No migrations to apply.

After doing python manage.py migrate, tables are not created in database from my models.py it is able to create other tables from django_session etc. Is there anything else that I need to follow here ?


问:
The constructor TransportClient() is undefined?
I am working on elastic search using mongo db. When importing transport client it shows

The constructor TransportClient() is undefined.

I configured it as follows:

```<code>package com.appointment.api.mobile.config;

import javax.annotation.Resource;

import org.elasticsearch.client.Client;
import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.common.transport.InetSocketTransportAddress;
import org.elasticsearch.common.transport.TransportAddress;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.core.env.Environment;
import org.springframework.data.elasticsearch.core.ElasticsearchOperations;
import org.springframework.data.elasticsearch.core.ElasticsearchTemplate;
import org.springframework.data.elasticsearch.repository.config.EnableElasticsearchRepositories;

@Configuration
@PropertySource(value = "classpath:elasticsearch.properties")
@EnableElasticsearchRepositories(basePackages = "com.appointment.api")
public class ElasticsearchConfiguration {

    @Resource
    private Environment environment;

    @Bean
    public Client client() {
        TransportClient client = new TransportClient();
     /*   TransportAddress address = new InetSocketTransportAddress(environment.getProperty("elasticsearch.host"), Integer.parseInt(environment.getProperty("elasticsearch.port")));
        client.addTransportAddress(address); */
        return client;
    }

    @Bean
    public ElasticsearchOperations elasticsearchTemplate() {
        return new ElasticsearchTemplate(client());
    }

}
</code>```

dependencies:

```<code><dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-data-elasticsearch</artifactId>
</dependency>
</code>```

Project:

```<code>Spring boot maven project.
</code>```

答:
According to the doc here, there is no public default constructor for the TransportClient , you need to do something like:</p>

```<code>TransportClient client = new PreBuiltTransportClient(Settings.EMPTY)
</code>```

Body:
I am working on elastic search using mongo db. When importing transport client it shows

The constructor TransportClient() is undefined.

I configured it as follows:

package com.appointment.api.mobile.config;

import javax.annotation.Resource;

import org.elasticsearch.client.Client;
import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.common.transport.InetSocketTransportAddress;
import org.elasticsearch.common.transport.TransportAddress;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.core.env.Environment;
import org.springframework.data.elasticsearch.core.ElasticsearchOperations;
import org.springframework.data.elasticsearch.core.ElasticsearchTemplate;
import org.springframework.data.elasticsearch.repository.config.EnableElasticsearchRepositories;

@Configuration
@PropertySource(value = "classpath:elasticsearch.properties")
@EnableElasticsearchRepositories(basePackages = "com.appointment.api")
public class ElasticsearchConfiguration {

    @Resource
    private Environment environment;

    @Bean
    public Client client() {
        TransportClient client = new TransportClient();
     /*   TransportAddress address = new InetSocketTransportAddress(environment.getProperty("elasticsearch.host"), Integer.parseInt(environment.getProperty("elasticsearch.port")));
        client.addTransportAddress(address); */
        return client;
    }

    @Bean
    public ElasticsearchOperations elasticsearchTemplate() {
        return new ElasticsearchTemplate(client());
    }

}

dependencies:

<dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-data-elasticsearch</artifactId>
</dependency>

Project:

Spring boot maven project.

Body:
According to the doc here, there is no public default constructor for the TransportClient , you need to do something like:

TransportClient client = new PreBuiltTransportClient(Settings.EMPTY)


问:
Remove duplicate rows from joined table
I have following sql query

```<code>SELECT m.School, c.avgscore
FROM postswithratings c
join ZEntrycriteria on c.fk_postID= m.schoolcode
</code>```

Which provide following result

```<code>School| avgscore
xyz   |  5
xyz   |  5
xyz   |  5
abc   |  3
abc   |  3
kkk   |  1
</code>```

My question is how to remove those duplicates and get only following.

```<code> School| avgscore
    xyz   |  5
    abc   |  3
    kkk   |  1
</code>```

I tried with

```<code>   SELECT m.School, c.avgscore
   FROM postswithratings c
   join ZEntrycriteria on c.fk_postID= m.schoolcode
   group by m.School
</code>```

But it gives me following error

"Column 'postswithratings.avgscore' is invalid in the select list
  because it is not contained in either an aggregate function or the
  GROUP BY clause."

答:
This will delete the Duplicate rows (Only Duplicate)

Schema:

```<code>CREATE TABLE #TAB (School varchar(5) , avgscore int)
INSERT INTO #TAB
SELECT 'xyz', 5
UNION ALL
SELECT 'xyz', 5
UNION ALL
SELECT 'xyz', 5
UNION ALL
SELECT 'abc', 3
UNION ALL
SELECT 'abc', 3
UNION ALL
SELECT 'kkk', 1
</code>```

Now use CTE as your Tempprary View and delete the data.

```<code>;WITH CTE AS(
SELECT ROW_NUMBER() OVER (PARTITION BY School,avgscore  ORDER BY (SELECT 1)) DUP_C,
School,  avgscore FROM #TAB
)

DELETE FROM CTE WHERE DUP_C>1
</code>```

Now do check #TAB, the data will be

```<code>+--------+----------+
| School | avgscore |
+--------+----------+
| xyz    |        5 |
| abc    |        3 |
| kkk    |        1 |
+--------+----------+
</code>```

Title: Remove duplicate rows from joined table

Body:
I have following sql query

SELECT m.School, c.avgscore
FROM postswithratings c
join ZEntrycriteria on c.fk_postID= m.schoolcode

Which provide following result

School| avgscore
xyz   |  5
xyz   |  5
xyz   |  5
abc   |  3
abc   |  3
kkk   |  1

My question is how to remove those duplicates and get only following.

 School| avgscore
    xyz   |  5
    abc   |  3
    kkk   |  1

I tried with

   SELECT m.School, c.avgscore
   FROM postswithratings c
   join ZEntrycriteria on c.fk_postID= m.schoolcode
   group by m.School

But it gives me following error

"Column 'postswithratings.avgscore' is invalid in the select list
  because it is not contained in either an aggregate function or the
  GROUP BY clause."

Body:
This will delete the Duplicate rows (Only Duplicate)

Schema:

CREATE TABLE #TAB (School varchar(5) , avgscore int)
INSERT INTO #TAB
SELECT 'xyz', 5
UNION ALL
SELECT 'xyz', 5
UNION ALL
SELECT 'xyz', 5
UNION ALL
SELECT 'abc', 3
UNION ALL
SELECT 'abc', 3
UNION ALL
SELECT 'kkk', 1

Now use CTE as your Tempprary View and delete the data.

;WITH CTE AS(
SELECT ROW_NUMBER() OVER (PARTITION BY School,avgscore  ORDER BY (SELECT 1)) DUP_C,
School,  avgscore FROM #TAB
)

DELETE FROM CTE WHERE DUP_C>1

Now do check #TAB, the data will be

+--------+----------+
| School | avgscore |
+--------+----------+
| xyz    |        5 |
| abc    |        3 |
| kkk    |        1 |
+--------+----------+


问:
I need to iterate over text file and print specific text starting from and end fulfilling condition in python 3
example txt file :

```<code>vrf X.x.X
hello
!
how are you
!
vrf y.y.y.
hi
!
</code>```

I want to run through above provided text and print the output starting from matching string "vrf" till matching string "!".
As per above text , I should get output as

```<code>vrf X.x.X
hello
vrf y.y.y.
hi
</code>```

答:
The solution using re.findall() function:

```<code>import re

with open('lines.txt', 'r') as fh:
    result = re.findall(r'vrf[^!]+(?=!)', fh.read(), re.M)

print(''.join(result))
</code>```

The output:

```<code>vrf X.x.X
hello
vrf y.y.y.
hi
</code>```

Body:
example txt file :

vrf X.x.X
hello
!
how are you
!
vrf y.y.y.
hi
!

I want to run through above provided text and print the output starting from matching string "vrf" till matching string "!".
As per above text , I should get output as

vrf X.x.X
hello
vrf y.y.y.
hi

Body:
The solution using re.findall() function:

import re

with open('lines.txt', 'r') as fh:
    result = re.findall(r'vrf[^!]+(?=!)', fh.read(), re.M)

print(''.join(result))

The output:

vrf X.x.X
hello
vrf y.y.y.
hi


问:
Polygon selection
I'm using the WPF version of GMaps.net.  Certain functionalities such as polygon selection is not that obvious.

What I need to do is detect a polygon click on the map, and then change properties of the polygon (opacity etc) to show that it is selected.  A custom way to achieve this is by getting the mouse coordinates with a mouse click event, and do a polygon intersection test with some vector maths, however I'm sure there must be a built-in way to do this?

For clarity sake, this is how I create my polygons:

```<code>        GMapPolygon polygon = new GMapPolygon(polyPointList);
        polygon.RegenerateShape(gMapControl1);
        (polygon.Shape as Path).Stroke = Brushes.DarkBlue;
        (polygon.Shape as Path).Opacity = 0.5;
        gMapControl1.Markers.Add(polygon);
</code>```

答:
I believe you're right, the WPF version of the polygon doesn't offer it right out of the box.

Think you could use the PointLatLng of your click and check if that's within the bounds of the polygon. Take the WinForms version of it and adapt it. In the end it's just that bit of math that's lacking.

Title: Polygon selection

Body:
I'm using the WPF version of GMaps.net.  Certain functionalities such as polygon selection is not that obvious.

What I need to do is detect a polygon click on the map, and then change properties of the polygon (opacity etc) to show that it is selected.  A custom way to achieve this is by getting the mouse coordinates with a mouse click event, and do a polygon intersection test with some vector maths, however I'm sure there must be a built-in way to do this?

For clarity sake, this is how I create my polygons:

        GMapPolygon polygon = new GMapPolygon(polyPointList);
        polygon.RegenerateShape(gMapControl1);
        (polygon.Shape as Path).Stroke = Brushes.DarkBlue;
        (polygon.Shape as Path).Opacity = 0.5;
        gMapControl1.Markers.Add(polygon);


答:
```<code>CREATE TABLE #Table2
    ([School] varchar(3), [avgscore] int)

INSERT INTO #Table2
    ([School], [avgscore])
VALUES
    ('xyz', 5),
    ('xyz', 5),
    ('xyz', 5),
    ('abc', 3),
    ('abc', 3),
    ('kkk', 1)
;
SELECT  SCHOOL,AVGSCORE FROM (SELECT *,ROW_NUMBER() OVER( PARTITION BY [AVGSCORE] ORDER BY (SELECT NULL)) AS RN FROM #TABLE2)A
WHERE RN=1
ORDER BY AVGSCORE
-------
;WITH CTE AS
(SELECT *,ROW_NUMBER() OVER( PARTITION BY [AVGSCORE] ORDER BY (SELECT NULL)) AS RN FROM #TABLE2)
SELECT SCHOOL,AVGSCORE  FROM CTE WHERE RN=1
</code>```

output

```<code>SCHOOL  AVGSCORE
kkk      1
abc      3
xyz      5
</code>```

Title: Remove duplicate rows from joined table

Body:
CREATE TABLE #Table2
    ([School] varchar(3), [avgscore] int)

INSERT INTO #Table2
    ([School], [avgscore])
VALUES
    ('xyz', 5),
    ('xyz', 5),
    ('xyz', 5),
    ('abc', 3),
    ('abc', 3),
    ('kkk', 1)
;
SELECT  SCHOOL,AVGSCORE FROM (SELECT *,ROW_NUMBER() OVER( PARTITION BY [AVGSCORE] ORDER BY (SELECT NULL)) AS RN FROM #TABLE2)A
WHERE RN=1
ORDER BY AVGSCORE
-------
;WITH CTE AS
(SELECT *,ROW_NUMBER() OVER( PARTITION BY [AVGSCORE] ORDER BY (SELECT NULL)) AS RN FROM #TABLE2)
SELECT SCHOOL,AVGSCORE  FROM CTE WHERE RN=1

output

SCHOOL  AVGSCORE
kkk      1
abc      3
xyz      5