问:
Image in ScrollView not being scrollable
I was asked to help out in a project with swift and work in xcode on a short timescale, neither which I have worked with before.

The task is getting a picture to be "zoomable". And after some researched I found that putting a UIScrollView on top of the image will suffice. Now, since the image view already exists and is integrated in the code on a level I do not dare triffle with, with some constraits and what not.
I dont want to start the process all over with a new image view and later try to hook it into the code. Mostly because the image view is inside a table cell inside of a table view.

What I have done is:

On the storyboard

Put the image view inside the view on the storyboard.

Assigned the delegate of the scroll view to the table cell.

I couldnt quite figure out how to constraint these so I mostly use 'Add missing constraints'.

In code for the TableViewCell

Inherited the UIScrollViewDelegate

made a new var with @IBOutlet weak var scrollView: UIScrollView!

Since I am in a controller, i cannot override viewDidLoad function, so I implemented that and set minimum and maximumZoomScale to some values.

Implemented a viewForZooming function that returns the UIImageView

I figured out somewhat how I can use the constraints and properties of the ImageView to resize and stuff, but the regardless of what I try to do, I cannot get the "zoom" to work.

Is there any property that the ImageView could have that is messing this up, what should I check for?

答:
After reading and trying to figure out, what finally made it work was this:

The ScrollView was made parent in the Interface Builder to the ImageView

I magically made the constraints to fit the ScrollView aligned to everything around it mostly by Add missing constraints when prompted with constraint errors.

Rightclicked the ScrollView then for the delegate, clicked the + sign and dragged that to the UITableViewCell.

I also did the same for the Referencing Outlet

And code for the UITableViewCell is this:

```<code>class ClothesItemTableViewCell: UITableViewCell, UIScrollViewDelegate {
  @IBOutlet weak var scrollView: UIScrollView!
  var theImage: UIImage? {
     set {
        clothinhImageView.image = newValue
    } get {
       return clothingImageView.image
    }
  }

  func viewForZooming(in scrollView: UIScrollView) -> UIView? {
     return clothingImageView
  }
}
</code>```

Might not be perfectly clear, and I couldnt find the exact article that made the work done. But there are plenty that tries to solve this issue in different ways, and somehow this worked. Hopes it helpes somebody!

Body:
After reading and trying to figure out, what finally made it work was this:

The ScrollView was made parent in the Interface Builder to the ImageView

I magically made the constraints to fit the ScrollView aligned to everything around it mostly by Add missing constraints when prompted with constraint errors.

Rightclicked the ScrollView then for the delegate, clicked the + sign and dragged that to the UITableViewCell.

I also did the same for the Referencing Outlet

And code for the UITableViewCell is this:

class ClothesItemTableViewCell: UITableViewCell, UIScrollViewDelegate {
  @IBOutlet weak var scrollView: UIScrollView!
  var theImage: UIImage? {
     set {
        clothinhImageView.image = newValue
    } get {
       return clothingImageView.image
    }
  }

  func viewForZooming(in scrollView: UIScrollView) -> UIView? {
     return clothingImageView
  }
}

Might not be perfectly clear, and I couldnt find the exact article that made the work done. But there are plenty that tries to solve this issue in different ways, and somehow this worked. Hopes it helpes somebody!


来源: stackexchange

问:
Use Validation on class object without injection in Aurelia
I am facing one issue related to the injection(s) in Aurelia.
I was wondering how to implement Validation, EventAggregator and Router without injection.

Below you can find an example which may give you a clear picture about the implementation and where I am stuck.

class Profile interacts with the view, and object of AddressList is created in the profile class and this object(AddressList) interacts with the view.

For example:

```<code>@inject(EventAggregator, Validation, Router)
export class Profile{
      addressList: Array<AddressList> = [];
      eventAgg:any;
      _validation:any;
      _router:any;
      constructor(EventAggregator, Validation, Router )
                  {
                   this.eventAgg = EventAggregator;
                   this._validation = Validation;
                   this._router = Router;
                   this.addressList.push(new AddressList());
                  }
}

export class AddressList{
      street1:string = "street1";
      street2:string = "street2";
constructor(){
}
</code>```

Now I want to implement validations on the properties of AddressList without passing Validation in the construtor of AddressList

I don't want this

```<code>this.addressList.push(new AddressList(Valdiation));
</code>```

Because this will create issues when I want to pass arguments in the constructor of the AddressList.

I think this issue will also occur when we will try to compose one view-model in the other view-model and constructor expects some user defined arguments.

Thanks in advance,

Ankur

Updates/Changes in the questions

I done the changes as suggested by Matthew James Davis.
But I am unable to understand why AddressList is coming as undefined.

Updated Code

```<code>import { Factory } from 'aurelia-framework';
import { ObserverLocator } from 'aurelia-framework';
import { EventAggregator } from 'aurelia-event-aggregator';
import { Validation, ensure } from 'aurelia-validation';

@inject(EventAggregator, Validation, Factory.of(AddressList))
export class Profile{
   addressList: Array<AddressList> = [];
      eventAgg:any;
      _validation:any;
      _router:any;
      constructor(EventAggregator, Validation, AddressList)
                  {
                   this.eventAgg = EventAggregator;
                   this._validation = Validation;
                   this.addressList.push(AddressList(["street1","street2"]));
                  }
 }

@inject(Validation)
export class AddressList{
      street1:string = "street1";
      street2:string = "street2";
      constructor(Validation, args){
         this.street1=args[0];
         this.street2=args[1];
     }
}
</code>```

Error in the console

```<code>AddressList
function() {
        for (var _len = arguments.length, rest = Array(_len), _key = 0; _key < _len; _key++) {
        rest[_key] = arguments[_key];
        }

    return container.invoke(_this2._…
AddressList ()
</code>```

Error is due to this line in Container.prototype._createInvocationHandler:

```<code> if (fn.inject === undefined)
</code>```

fn in undefined.

I think it might help you, and I am still trying to figure out what can be the issue.

答:
I'm not sure if this is the problem, but as I'm using typescript, I know that you also need to import inject from aurelia-framework.

Another possibility would be to inject it like this:

private static inject = [EventAggregator, Validation, Factory.of(AddressList)]

But if you're not using typescript, I'm not sure if this is necessary.

ContentLicense: CC BY-SA 3.0

Body:
I am facing one issue related to the injection(s) in Aurelia.
I was wondering how to implement Validation, EventAggregator and Router without injection.

Below you can find an example which may give you a clear picture about the implementation and where I am stuck.

class Profile interacts with the view, and object of AddressList is created in the profile class and this object(AddressList) interacts with the view.

For example:

@inject(EventAggregator, Validation, Router)
export class Profile{
      addressList: Array<AddressList> = [];
      eventAgg:any;
      _validation:any;
      _router:any;
      constructor(EventAggregator, Validation, Router )
                  {
                   this.eventAgg = EventAggregator;
                   this._validation = Validation;
                   this._router = Router;
                   this.addressList.push(new AddressList());
                  }
}

export class AddressList{
      street1:string = "street1";
      street2:string = "street2";
constructor(){
}

Now I want to implement validations on the properties of AddressList without passing Validation in the construtor of AddressList

I don't want this

this.addressList.push(new AddressList(Valdiation));

Because this will create issues when I want to pass arguments in the constructor of the AddressList.

I think this issue will also occur when we will try to compose one view-model in the other view-model and constructor expects some user defined arguments.

Thanks in advance,

Ankur

Updates/Changes in the questions

I done the changes as suggested by Matthew James Davis.
But I am unable to understand why AddressList is coming as undefined.

Updated Code

import { Factory } from 'aurelia-framework';
import { ObserverLocator } from 'aurelia-framework';
import { EventAggregator } from 'aurelia-event-aggregator';
import { Validation, ensure } from 'aurelia-validation';

@inject(EventAggregator, Validation, Factory.of(AddressList))
export class Profile{
   addressList: Array<AddressList> = [];
      eventAgg:any;
      _validation:any;
      _router:any;
      constructor(EventAggregator, Validation, AddressList)
                  {
                   this.eventAgg = EventAggregator;
                   this._validation = Validation;
                   this.addressList.push(AddressList(["street1","street2"]));
                  }
 }

@inject(Validation)
export class AddressList{
      street1:string = "street1";
      street2:string = "street2";
      constructor(Validation, args){
         this.street1=args[0];
         this.street2=args[1];
     }
}

Error in the console

AddressList
function() {
        for (var _len = arguments.length, rest = Array(_len), _key = 0; _key < _len; _key++) {
        rest[_key] = arguments[_key];
        }

    return container.invoke(_this2._…
AddressList ()

Error is due to this line in Container.prototype._createInvocationHandler:

 if (fn.inject === undefined)

fn in undefined.

I think it might help you, and I am still trying to figure out what can be the issue.


问:
I want to subtract values from one column to another column in the same table with Specific id
```<code>Proc Id       Start_time             end_time                Status
111           7/4/2017 9:08:43 AM    7/4/2017 9:35:54 AM     Success
</code>```

<p>I want to find the time duration(in Mins) between the star_time and end_time.
Please help me how to do it? </p>

答:
You can try with this one...</p>

```<code>SELECT TIMESTAMPDIFF(MINUTE,tmp.start_time,tmp.end_time) FROM (select start_time,end_time from table_name where id=?) as tmp;
</code>```

Body:
Proc Id       Start_time             end_time                Status
111           7/4/2017 9:08:43 AM    7/4/2017 9:35:54 AM     Success

I want to find the time duration(in Mins) between the star_time and end_time.
Please help me how to do it?

Body:
You can try with this one...

SELECT TIMESTAMPDIFF(MINUTE,tmp.start_time,tmp.end_time) FROM (select start_time,end_time from table_name where id=?) as tmp;


问:
How to isolate space delimited values that may contain a space?
I have an input where a user will enter a class schedule in the following format

```<code>[time] [days] [room]
</code>```

e.g:

```<code>7-8 am MWF ROOM1 | 7:30-9:30 am TTH Room2 | 11:30 am-12:30 pm MWF Room3)
</code>```

So I tried exploding the input using space then get the last two values of the returned array and make the as $room and $days, then I subtracted the two in the original $schedule to get the remaining and make it my $time.

```<code>$sched = explode(" ", $schedule);
if(count($sched) <= 3){
    echo 'please check schedule format!';
}else{
   $room  = array_values(array_slice($sched, -1))[0];
   $days  = array_values(array_slice($sched, -2))[0];
   $times = str_replace($days." ".$room, "" ,$schedule);
}
</code>```

using the code above I'm getting the result I want, but the problem is when the user does not put DAYS or ROOM the text adjusts so I'm not getting the right value.

For example this input value

```<code>11:30 am-12:30 pm mwf (no room)
</code>```

I'm getting this result: (room:mwf) (days:pm) (times:11:30 am-12:30 )

Is there better way to this?

答:
This pattern will process the full string and spit out a multi-dimensional array.  How do you want to handle the results?

Test Code:  (Demo)

```<code>//$sched='7-8 am MWF ROOM1 | 7:30-9:30 am TTH Room2 | 11:30 am-12:30 pm MWF Room3';
$sched='MWF ROOM1 | 7:30-9:30 am Room2 | 11:30 am-12:30 pm MWF';
//$sched='ROOM1 | 7:30-9:30 am | MWF | MTWTHFS';

if(preg_match_all('/(?:^|\| )([^|]*?m)? ?([MTWHFS]*) ?([Rr][Oo]{2}[Mm]\d+)?(?: |$)/',$sched,$out,PREG_SET_ORDER)){
    foreach($out as $a){
        if(empty($a[1])){
            echo "Missing/Invalid Time\n";
        }
        if(empty($a[2])){
            echo "Missing/Invalid Days\n";
        }
        if(empty($a[3])){
            echo "Missing/Invalid Room\n";
        }
        var_export(array_slice($a,1));
        echo"\n\n";
    }
}
</code>```

Output:

```<code>Missing/Invalid Time
array (
  0 => '',
  1 => 'MWF',
  2 => 'ROOM1',
)

Missing/Invalid Days
array (
  0 => '7:30-9:30 am',
  1 => '',
  2 => 'Room2',
)

Missing/Invalid Room
array (
  0 => '11:30 am-12:30 pm',
  1 => 'MWF',
)
</code>```

Body:
I have an input where a user will enter a class schedule in the following format

[time] [days] [room]

e.g:

7-8 am MWF ROOM1 | 7:30-9:30 am TTH Room2 | 11:30 am-12:30 pm MWF Room3)

So I tried exploding the input using space then get the last two values of the returned array and make the as $room and $days, then I subtracted the two in the original $schedule to get the remaining and make it my $time.

$sched = explode(" ", $schedule);
if(count($sched) <= 3){
    echo 'please check schedule format!';
}else{
   $room  = array_values(array_slice($sched, -1))[0];
   $days  = array_values(array_slice($sched, -2))[0];
   $times = str_replace($days." ".$room, "" ,$schedule);
}

using the code above I'm getting the result I want, but the problem is when the user does not put DAYS or ROOM the text adjusts so I'm not getting the right value.

For example this input value

11:30 am-12:30 pm mwf (no room)

I'm getting this result: (room:mwf) (days:pm) (times:11:30 am-12:30 )

Is there better way to this?

Body:
This pattern will process the full string and spit out a multi-dimensional array.  How do you want to handle the results?

Test Code:  (Demo)

//$sched='7-8 am MWF ROOM1 | 7:30-9:30 am TTH Room2 | 11:30 am-12:30 pm MWF Room3';
$sched='MWF ROOM1 | 7:30-9:30 am Room2 | 11:30 am-12:30 pm MWF';
//$sched='ROOM1 | 7:30-9:30 am | MWF | MTWTHFS';

if(preg_match_all('/(?:^|\| )([^|]*?m)? ?([MTWHFS]*) ?([Rr][Oo]{2}[Mm]\d+)?(?: |$)/',$sched,$out,PREG_SET_ORDER)){
    foreach($out as $a){
        if(empty($a[1])){
            echo "Missing/Invalid Time\n";
        }
        if(empty($a[2])){
            echo "Missing/Invalid Days\n";
        }
        if(empty($a[3])){
            echo "Missing/Invalid Room\n";
        }
        var_export(array_slice($a,1));
        echo"\n\n";
    }
}

Output:

Missing/Invalid Time
array (
  0 => '',
  1 => 'MWF',
  2 => 'ROOM1',
)

Missing/Invalid Days
array (
  0 => '7:30-9:30 am',
  1 => '',
  2 => 'Room2',
)

Missing/Invalid Room
array (
  0 => '11:30 am-12:30 pm',
  1 => 'MWF',
)


问:
Replace particular text after the page is loaded with jquery
Is it possible to replace exact text with other text after the page has loaded with jquery?

For example, my data is being generated dynamically within a php loop. Once it finishes outputting the information, I'd like to do a find and replace, replacing the phrase "test phrase 1" with "test phrase 2" throughout the page. Is this possible?

答: I think you will find jquery-translate useful. It even has method that you need, namely: $().nodesContainingText(...)</p>

ContentLicense: CC BY-SA 2.5

OwnerDisplayName: Marko Dumic


问:
Unable to build gRPC ManagedChannel with scala
I try to create a gRPC client. For

```<code>val channel = ManagedChannelBuilder.forAddress(host, port).usePlaintext(true).build
</code>```

I get this compile time error

```<code>Error:(18, 87) value build is not a member of ?0
    val channel = ManagedChannelBuilder.forAddress(host, port).usePlaintext(true).build
</code>```

gRPC is built for Java. My project is multi-module maven project, where for protobuf files and generated code is in a separate module.

答: Did you try '.build()'? I'm not too familiar with scala but perhaps the parentheses are required for a library written in Java. If it's recognizing up to usePlaintext, then .build() should indeed be valid for the returned ManagedChannelBuilder: http://www.grpc.io/grpc-java/javadoc/io/grpc/ManagedChannelBuilder.html#build--</p>

Body:
I try to create a gRPC client. For

val channel = ManagedChannelBuilder.forAddress(host, port).usePlaintext(true).build

I get this compile time error

Error:(18, 87) value build is not a member of ?0
    val channel = ManagedChannelBuilder.forAddress(host, port).usePlaintext(true).build

gRPC is built for Java. My project is multi-module maven project, where for protobuf files and generated code is in a separate module.


问:
coloring wpf checkbox box C#
I want to coloring the CheckBox box in a WPF app. I tried to type this in XAML:

```<code><CheckBox x:Name="topintegral" Content="TOP Integral" `enter code here`
          RenderTransformOrigin="0.5,0.5" Width="188" Margin="94,105,68,86"
          FontWeight="Bold" FontSize="15" Background="Black"
          MouseEnter="MouseFocus" MouseLeave="MouseLeave" BorderBrush="#FFE6FFFF">
</code>```

and in the .cs file:

```<code>private void MouseFocus(object sender, MouseEventArgs e)
{
    topintegral.Background = new SolidColorBrush(Colors.White);
}
</code>```

but it shows like:

enter image description here

答:
If you want it back in the previous state(black color) then do it in the MouseLeave event.

```<code>    private void MouseLeave(object sender, MouseEventArgs e)
    {
        topintegral.Background = new SolidColorBrush(Colors.Black);
    }
</code>```

otherwise, your code is working fine.

The MouseFocus method is the event handler of MouseEnter event, so when cursor enters in the checkbox it turns into white. But if you want it back into the previous color just write the event handler of the MouseLeave event.

Title: coloring wpf checkbox box C#

Body:
I want to coloring the CheckBox box in a WPF app. I tried to type this in XAML:

<CheckBox x:Name="topintegral" Content="TOP Integral" `enter code here`
          RenderTransformOrigin="0.5,0.5" Width="188" Margin="94,105,68,86"
          FontWeight="Bold" FontSize="15" Background="Black"
          MouseEnter="MouseFocus" MouseLeave="MouseLeave" BorderBrush="#FFE6FFFF">

and in the .cs file:

private void MouseFocus(object sender, MouseEventArgs e)
{
    topintegral.Background = new SolidColorBrush(Colors.White);
}

but it shows like:

enter image description here

Body:
If you want it back in the previous state(black color) then do it in the MouseLeave event.

    private void MouseLeave(object sender, MouseEventArgs e)
    {
        topintegral.Background = new SolidColorBrush(Colors.Black);
    }

otherwise, your code is working fine.

The MouseFocus method is the event handler of MouseEnter event, so when cursor enters in the checkbox it turns into white. But if you want it back into the previous color just write the event handler of the MouseLeave event.


问:
Python for starters - TypeError: '<' not supported between instances of 'str' and 'int'
Thank you so much for reading my first post.

Started learning Python 3.6.1 - got stuck at the starter - what's wrong with following code:

```<code>print('Hi there! What is your name?')
myName = input()
print("Hello "   +  myName +  ' its good to met you. My name is Kendo.')

print('how old are you?')
myAge = input()
if myAge < 15:
    print('go to bed, kiddo')
elif myAge > 95:
    print('Sup, grandma')
elif myAge > 1000:
    print('Lol, stop kidding me')
</code>```

答:
The problem is that you need an integer but the input() returns a string.
You can convert the input to int using somrthing like the following:

For Python 3.x:

```<code>myAge  = int(input("Enter a number: "))
</code>```

For Python 2.x:

```<code>myAge = input("Enter a number: ")
>>>Enter a number: 5 + 17

myAge, type(myAge)
(22, <type 'int'>)
</code>```

Body:
Thank you so much for reading my first post.

Started learning Python 3.6.1 - got stuck at the starter - what's wrong with following code:

print('Hi there! What is your name?')
myName = input()
print("Hello "   +  myName +  ' its good to met you. My name is Kendo.')

print('how old are you?')
myAge = input()
if myAge < 15:
    print('go to bed, kiddo')
elif myAge > 95:
    print('Sup, grandma')
elif myAge > 1000:
    print('Lol, stop kidding me')

Body:
The problem is that you need an integer but the input() returns a string.
You can convert the input to int using somrthing like the following:

For Python 3.x:

myAge  = int(input("Enter a number: "))

For Python 2.x:

myAge = input("Enter a number: ")
>>>Enter a number: 5 + 17

myAge, type(myAge)
(22, <type 'int'>)


问:
Smooth Scroll Not Working on Initial Scroll for Android RecyclerView
I am working on an Android app that runs on only one devicerunning KitKat.

The smooth scrolling feature for a RecylerView I used that was working on other physical tablets and genymotion has unfortunately stopped working on the one device it needs to work on.

Instead of scrolling to a certain position it passes over the target position and scrolls all the way to the bottom and looks really bad.

I am able to track down the error to the abstract SmoothScroller in the RecyclerView class.

```<code>           if (getChildPosition(mTargetView) == mTargetPosition) {
                onTargetFound(mTargetView, recyclerView.mState, mRecyclingAction);
                mRecyclingAction.runIfNecessary(recyclerView);
                stop();
            } else {
                Log.e(TAG, "Passed over target position while smooth scrolling.");
                mTargetView = null;
            }
</code>```

I was using a SnappingLinearLayoutManager that I found online, but swapped it out with the normal LinearLayoutManager from Android, and still am having the same problem.

The list is 7 items long (user can see 4 at a time) and I scroll to the 5th item (position 4) item.

When I scroll to the 3rd I don't receive this error.

Also after I scroll the list up and down once, the error stops happening.

EDIT:
I am able to use layoutManager.scrollToPositionWithOffset(); But I am trying to do this with the smooth scroll animation.

Here is some of my code and details:

```<code>private void setupMainRecyclerViewWithAdapter() {
    mainLayoutManager = new SnappingLinearLayoutManager(this, LinearLayoutManager.VERTICAL, false);
    mainListRecyclerView.setLayoutManager(mainLayoutManager);

    settingsMainListAdapter = new SettingsListAdapter(SettingsActivity.this,
            settingsPresenter.getSettingsItems(),
            settingsPresenter);

    mainListRecyclerView.setAdapter(settingsMainListAdapter);

    mainListRecyclerView.addItemDecoration(new BottomOffsetDecoration(EXTRA_VERTICAL_SCROLLING_SPACE));
}

@Override
public void scrollMainList(boolean listAtTop) {
    if(listAtTop) {
        mainListRecyclerView.smoothScrollToPosition(4);
        moveMainMoreButtonAboveList();
    } else {
        mainListRecyclerView.smoothScrollToPosition(0);
        moveMainMoreButtonBelowList();
    }
}
</code>```

答:
Well, I realize it's too late, however I tried some different solutions and found one...

in custom LinearSmoothScroller I override updateActionForInterimTarget

@Override
 protected void updateActionForInterimTarget(Action action) {
      action.jumpTo(position);
 }

It's appears not very smooth, but not instant in contrast with scrollToPositionWithOffset.

Body:
I am working on an Android app that runs on only one devicerunning KitKat.

The smooth scrolling feature for a RecylerView I used that was working on other physical tablets and genymotion has unfortunately stopped working on the one device it needs to work on.

Instead of scrolling to a certain position it passes over the target position and scrolls all the way to the bottom and looks really bad.

I am able to track down the error to the abstract SmoothScroller in the RecyclerView class.

           if (getChildPosition(mTargetView) == mTargetPosition) {
                onTargetFound(mTargetView, recyclerView.mState, mRecyclingAction);
                mRecyclingAction.runIfNecessary(recyclerView);
                stop();
            } else {
                Log.e(TAG, "Passed over target position while smooth scrolling.");
                mTargetView = null;
            }

I was using a SnappingLinearLayoutManager that I found online, but swapped it out with the normal LinearLayoutManager from Android, and still am having the same problem.

The list is 7 items long (user can see 4 at a time) and I scroll to the 5th item (position 4) item.

When I scroll to the 3rd I don't receive this error.

Also after I scroll the list up and down once, the error stops happening.

EDIT:
I am able to use layoutManager.scrollToPositionWithOffset(); But I am trying to do this with the smooth scroll animation.

Here is some of my code and details:

private void setupMainRecyclerViewWithAdapter() {
    mainLayoutManager = new SnappingLinearLayoutManager(this, LinearLayoutManager.VERTICAL, false);
    mainListRecyclerView.setLayoutManager(mainLayoutManager);

    settingsMainListAdapter = new SettingsListAdapter(SettingsActivity.this,
            settingsPresenter.getSettingsItems(),
            settingsPresenter);

    mainListRecyclerView.setAdapter(settingsMainListAdapter);

    mainListRecyclerView.addItemDecoration(new BottomOffsetDecoration(EXTRA_VERTICAL_SCROLLING_SPACE));
}

@Override
public void scrollMainList(boolean listAtTop) {
    if(listAtTop) {
        mainListRecyclerView.smoothScrollToPosition(4);
        moveMainMoreButtonAboveList();
    } else {
        mainListRecyclerView.smoothScrollToPosition(0);
        moveMainMoreButtonBelowList();
    }
}


问:
ADT plugin install sticks at 49% on Eclipse Classic 3.6
I am having a strange problem that the ADT plugin installation sticks at 49% on Eclipse Classic 3.6 for infinite time, as shown below...

Please help me out to solve this problem...

Thanks..

答:
As its said in android developer resource ADT plugin has still have some bugs , so its better to use ADT plugin with 3.5 Galileo.

I had try to use ADT plugin with Eclipse Helios under Ubuntu but i come across lots of problems , so i switch back to Galileo similar problem never occured...


问:
RStudio does not see packages after update to R 3.4
I have Ubuntu 16.04 and after update of R to 3.4.1 version it does not see my packages even though they have also been updated:

```<code>> library(dplyr)
Error in library(dplyr) : there is no package called ‘dplyr’
</code>```

Packages are there:

```<code>$ ls ~/R/x86_64-pc-linux-gnu-library/3.4/ | grep plyr
dplyr
plyr
</code>```

My .libPaths:

```<code>> .libPaths()
[1] "/usr/local/lib/R/site-library" "/usr/lib/R/site-library"       "/usr/lib/R/library"
</code>```

Setting .libPaths to desired path does the thing just for one session. I'd like it to be permanent.

I also tried to set the variables R_LIBS, R_LIBS_SITE and R_LIBS_USER to desired path as indicated here but it worked only in the console (didn't work in RStudio).

答:
Found the solution:
In the file /usr/lib/R/etc/Renviron there is a configuration of R.

In lines 43-45 there is:

```<code># edd Jun 2017  Comment-out R_LIBS_USER
#R_LIBS_USER=${R_LIBS_USER-'~/R/x86_64-pc-linux-gnu-library/3.4'}
##R_LIBS_USER=${R_LIBS_USER-'~/Library/R/3.4/library'}
</code>```

I have uncommented R_LIBS_USER=${R_LIBS_USER-'~/R/x86_64-pc-linux-gnu-library/3.4'}, restarted RStudio and now it works.

EDIT: Looking at the comments, it seems like a planned behaviour. Here is another solution.

Body:
I have Ubuntu 16.04 and after update of R to 3.4.1 version it does not see my packages even though they have also been updated:

> library(dplyr)
Error in library(dplyr) : there is no package called ‘dplyr’

Packages are there:

$ ls ~/R/x86_64-pc-linux-gnu-library/3.4/ | grep plyr
dplyr
plyr

My .libPaths:

> .libPaths()
[1] "/usr/local/lib/R/site-library" "/usr/lib/R/site-library"       "/usr/lib/R/library"

Setting .libPaths to desired path does the thing just for one session. I'd like it to be permanent.

I also tried to set the variables R_LIBS, R_LIBS_SITE and R_LIBS_USER to desired path as indicated here but it worked only in the console (didn't work in RStudio).

Body:
Found the solution:
In the file /usr/lib/R/etc/Renviron there is a configuration of R.

In lines 43-45 there is:

# edd Jun 2017  Comment-out R_LIBS_USER
#R_LIBS_USER=${R_LIBS_USER-'~/R/x86_64-pc-linux-gnu-library/3.4'}
##R_LIBS_USER=${R_LIBS_USER-'~/Library/R/3.4/library'}

I have uncommented R_LIBS_USER=${R_LIBS_USER-'~/R/x86_64-pc-linux-gnu-library/3.4'}, restarted RStudio and now it works.

EDIT: Looking at the comments, it seems like a planned behaviour. Here is another solution.


问:
node 7.10 - does it support await?
I am on node 7.10:

```<code>$ node --version
v7.10.0
</code>```

I thought it supports await.

```<code> let result = await Weather.findOne(options, function(err, weather) {

    if (err) {
        res.set('Content-Type', 'application/json');
        return res.status(200).send('Error occurs: ' + err);
    }

    if (weather) {
        res.set('Content-Type', 'application/json');
        return res.status(200).send(key + ' already exist.');
    }

    return weather;
});

console.log(result);
</code>```

Error message:

```<code>let result = await Weather.findOne(options, function(err, weather) {
                       ^^^^^^^
SyntaxError: Unexpected identifier
    at createScript (vm.js:53:10)
    at Object.runInThisContext (vm.js:95:10)
    at Module._compile (module.js:543:28)
    at Object.Module._extensions..js (module.js:580:10)
    at Module.load (module.js:488:32)
    at tryModuleLoad (module.js:447:12)
    at Function.Module._load (module.js:439:3)
    at Module.require (module.js:498:17)
    at require (internal/module.js:20:19)
    at Object.<anonymous> (/var/www/html/projects/citizen-sense-dustbox-data-streams/es5/v4/app.js:33:15)
    at Module._compile (module.js:571:32)
    at Object.Module._extensions..js (module.js:580:10)
    at Module.load (module.js:488:32)
    at tryModuleLoad (module.js:447:12)
    at Function.Module._load (module.js:439:3)
    at Module.require (module.js:498:17)
    at require (internal/module.js:20:19)
    at Object.<anonymous> (/var/www/html/projects/citizen-sense-dustbox-data-streams/es5/v4/bin/www:7:11)
    at Module._compile (module.js:571:32)
    at Object.Module._extensions..js (module.js:580:10)
    at Module.load (module.js:488:32)
    at tryModuleLoad (module.js:447:12)
    at Function.Module._load (module.js:439:3)
    at Module.runMain (module.js:605:10)
    at run (bootstrap_node.js:427:7)
    at startup (bootstrap_node.js:151:9)
    at bootstrap_node.js:542:3
</code>```

It does not seem supported in node 7.10? Or am I doing something wrong?

Any ideas?

答:
From https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/await:

The await operator is used to wait for a Promise. It can only be used inside an async function.

```<code>async function doAwait() {
    let result = await Weather.findOne(options, function(err, weather) {

       if (err) {
            res.set('Content-Type', 'application/json');
           return res.status(200).send('Error occurs: ' + err);
       }

       if (weather) {
           res.set('Content-Type', 'application/json');
           return res.status(200).send(key + ' already exist.');
       }

       return weather;
   });

   console.log(result);
}
</code>```

Title: node 7.10 - does it support await?

Body:
I am on node 7.10:

$ node --version
v7.10.0

I thought it supports await.

 let result = await Weather.findOne(options, function(err, weather) {

    if (err) {
        res.set('Content-Type', 'application/json');
        return res.status(200).send('Error occurs: ' + err);
    }

    if (weather) {
        res.set('Content-Type', 'application/json');
        return res.status(200).send(key + ' already exist.');
    }

    return weather;
});

console.log(result);

Error message:

let result = await Weather.findOne(options, function(err, weather) {
                       ^^^^^^^
SyntaxError: Unexpected identifier
    at createScript (vm.js:53:10)
    at Object.runInThisContext (vm.js:95:10)
    at Module._compile (module.js:543:28)
    at Object.Module._extensions..js (module.js:580:10)
    at Module.load (module.js:488:32)
    at tryModuleLoad (module.js:447:12)
    at Function.Module._load (module.js:439:3)
    at Module.require (module.js:498:17)
    at require (internal/module.js:20:19)
    at Object.<anonymous> (/var/www/html/projects/citizen-sense-dustbox-data-streams/es5/v4/app.js:33:15)
    at Module._compile (module.js:571:32)
    at Object.Module._extensions..js (module.js:580:10)
    at Module.load (module.js:488:32)
    at tryModuleLoad (module.js:447:12)
    at Function.Module._load (module.js:439:3)
    at Module.require (module.js:498:17)
    at require (internal/module.js:20:19)
    at Object.<anonymous> (/var/www/html/projects/citizen-sense-dustbox-data-streams/es5/v4/bin/www:7:11)
    at Module._compile (module.js:571:32)
    at Object.Module._extensions..js (module.js:580:10)
    at Module.load (module.js:488:32)
    at tryModuleLoad (module.js:447:12)
    at Function.Module._load (module.js:439:3)
    at Module.runMain (module.js:605:10)
    at run (bootstrap_node.js:427:7)
    at startup (bootstrap_node.js:151:9)
    at bootstrap_node.js:542:3

It does not seem supported in node 7.10? Or am I doing something wrong?

Any ideas?

Body:
From https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/await:

The await operator is used to wait for a Promise. It can only be used inside an async function.

async function doAwait() {
    let result = await Weather.findOne(options, function(err, weather) {

       if (err) {
            res.set('Content-Type', 'application/json');
           return res.status(200).send('Error occurs: ' + err);
       }

       if (weather) {
           res.set('Content-Type', 'application/json');
           return res.status(200).send(key + ' already exist.');
       }

       return weather;
   });

   console.log(result);
}


问:
Numpy's float32 and float comparisons
Continuing from Difference between Python float and numpy float32:

```<code>import numpy as np

a = 58682.7578125
print(type(a), a)
float_32 = np.float32(a)
print(type(float_32), float_32)
print(float_32 == a)
</code>```

Prints:

```<code><class 'float'> 58682.7578125
<class 'numpy.float32'> 58682.8
True
</code>```

I fully understand that comparing floats for equality is not a good idea but still shouldn't this be False (we're talking about differences in the first decimal digit, not in 0.000000001) ? Is it system dependent ? Is this behavior somewhere documented ?

EDIT: Well it's the third decimal:

```<code>print(repr(float_32), repr(a))
# 58682.758 58682.7578125
</code>```

but can I trust repr ? How are those stored internally in the final end ?

EDIT2: people insist that printing float_32 with more precision will give me its representation. However as I already commented according to nympy's docs:

the % formatting operator requires its arguments to be converted to standard python types

and:

```<code>print(repr(float(float_32)))
</code>```

prints

58682.7578125

An interesting insight is given by @MarkDickinson here, apparently repr should be faithful (then he says it's not faithful for np.float32).

So let me reiterate my question as follows:

How can I get at the exact internal representation of float_32 and a in the example ? If these are the same, then problem solved if not,

What are the exact rules for up/downcasting in a comparison between python's float and np.float32 ? I 'd guess that it upcasts float_32 to float although @WillemVanOnsem suggests in the comments it's the other way round

My python version:

Python 3.5.2 (v3.5.2:4def2a2901a5, Jun 25 2016, 22:18:55) [MSC v.1900 64 bit (AMD64)] on win32

答:
 58682.8

My machine shows 58682.758 for this line.

I fully understand that comparing floats for equality is not a good idea

It is "not a good idea" if they calculated independently. On the other hand, it is a good idea if you get the same number and check its conversion.

Is it system dependent ? Is this behavior somewhere documented ?

It's fully dependent on conversion to text. According to comments, float32 is essential. If so, the guaranteed accuracy for float32 is 7 decimal digits, unlike Python's internal float that is float64 (at least on x86). That is why the value is truncated in print. The recommended way to print float values in decimal is to stop when output form is that converts back to the same internal value. So it reduces 58682.7578125 to 58682.758: the difference is less than ULP.

The same value printed as internal "float" or numpy float64 will have more significant digits because their omission will result in another internal value:

```<code>>>> 58682.758 == 58682.7578125
False
>>> numpy.float32(58682.758) == numpy.float32(58682.7578125)
True
>>> print(repr(numpy.float32(58682.758).data[0:4]))
'\xc2:eG'
>>> print(repr(numpy.float32(58682.7578125).data[0:4]))
'\xc2:eG'
>>> numpy.float64(58682.758) == numpy.float64(58682.7578125)
False
>>> print(numpy.float64(58682.758).hex(), numpy.float64(58682.7578125).hex())
('0x1.ca7584189374cp+15', '0x1.ca75840000000p+15')
</code>```

You are lucky these two values are equal in float32 with this concrete value (was this intentional?) but it might be different with other one.

Title: Numpy's float32 and float comparisons

Body:
Continuing from Difference between Python float and numpy float32:

import numpy as np

a = 58682.7578125
print(type(a), a)
float_32 = np.float32(a)
print(type(float_32), float_32)
print(float_32 == a)

Prints:

<class 'float'> 58682.7578125
<class 'numpy.float32'> 58682.8
True

I fully understand that comparing floats for equality is not a good idea but still shouldn't this be False (we're talking about differences in the first decimal digit, not in 0.000000001) ? Is it system dependent ? Is this behavior somewhere documented ?

EDIT: Well it's the third decimal:

print(repr(float_32), repr(a))
# 58682.758 58682.7578125

but can I trust repr ? How are those stored internally in the final end ?

EDIT2: people insist that printing float_32 with more precision will give me its representation. However as I already commented according to nympy's docs:

the % formatting operator requires its arguments to be converted to standard python types

and:

print(repr(float(float_32)))

prints

58682.7578125

An interesting insight is given by @MarkDickinson here, apparently repr should be faithful (then he says it's not faithful for np.float32).

So let me reiterate my question as follows:

How can I get at the exact internal representation of float_32 and a in the example ? If these are the same, then problem solved if not,

What are the exact rules for up/downcasting in a comparison between python's float and np.float32 ? I 'd guess that it upcasts float_32 to float although @WillemVanOnsem suggests in the comments it's the other way round

My python version:

Python 3.5.2 (v3.5.2:4def2a2901a5, Jun 25 2016, 22:18:55) [MSC v.1900 64 bit (AMD64)] on win32

Body:
 58682.8

My machine shows 58682.758 for this line.

I fully understand that comparing floats for equality is not a good idea

It is "not a good idea" if they calculated independently. On the other hand, it is a good idea if you get the same number and check its conversion.

Is it system dependent ? Is this behavior somewhere documented ?

It's fully dependent on conversion to text. According to comments, float32 is essential. If so, the guaranteed accuracy for float32 is 7 decimal digits, unlike Python's internal float that is float64 (at least on x86). That is why the value is truncated in print. The recommended way to print float values in decimal is to stop when output form is that converts back to the same internal value. So it reduces 58682.7578125 to 58682.758: the difference is less than ULP.

The same value printed as internal "float" or numpy float64 will have more significant digits because their omission will result in another internal value:

>>> 58682.758 == 58682.7578125
False
>>> numpy.float32(58682.758) == numpy.float32(58682.7578125)
True
>>> print(repr(numpy.float32(58682.758).data[0:4]))
'\xc2:eG'
>>> print(repr(numpy.float32(58682.7578125).data[0:4]))
'\xc2:eG'
>>> numpy.float64(58682.758) == numpy.float64(58682.7578125)
False
>>> print(numpy.float64(58682.758).hex(), numpy.float64(58682.7578125).hex())
('0x1.ca7584189374cp+15', '0x1.ca75840000000p+15')

You are lucky these two values are equal in float32 with this concrete value (was this intentional?) but it might be different with other one.


问:
Check for element in AutoFilter before trying to deselect it
I want to refresh my pivot table as the data within the range it is looking at does change. Then I need to be able to unselect any blanks from the filter.

My code below does this, however if there is not a blank present (In the form of "" or (blank)) then it will throw up an error.
I guess I need it to check for the presence of these elements in the filter before trying to  hide them...

How do I achieve this?

```<code>   Dim pt As PivotTable: Set pt = ActiveSheet.PivotTables("BarSummary")
    pt.RefreshTable
    With ActiveSheet.PivotTables("BarSummary").PivotFields("Shape Codes")
       .PivotItems("").Visible = False
       .PivotItems("(blank)").Visible = False
    End With
End If
</code>```

答:
This would be a case where On Error Resume Next is simplest:

```<code>On Error Resume Next
.PivotItems("").Visible = False
.PivotItems("(blank)").Visible = False
On Error Goto 0
</code>```

Body:
I want to refresh my pivot table as the data within the range it is looking at does change. Then I need to be able to unselect any blanks from the filter.

My code below does this, however if there is not a blank present (In the form of "" or (blank)) then it will throw up an error.
I guess I need it to check for the presence of these elements in the filter before trying to  hide them...

How do I achieve this?

   Dim pt As PivotTable: Set pt = ActiveSheet.PivotTables("BarSummary")
    pt.RefreshTable
    With ActiveSheet.PivotTables("BarSummary").PivotFields("Shape Codes")
       .PivotItems("").Visible = False
       .PivotItems("(blank)").Visible = False
    End With
End If

Body:
This would be a case where On Error Resume Next is simplest:

On Error Resume Next
.PivotItems("").Visible = False
.PivotItems("(blank)").Visible = False
On Error Goto 0


问:
SAPUI5 Expand the model in the manifest
I want to add a new model to the manifest.json.
The model is supposed to be expanded.

```<code>https://myPath/services/myService.xsodata/SubPath?$expand=CustomerRef
</code>```

So the Datasource is defined:

```<code>"dataSources": {
    "mainService": {
        "uri": "/myPath/services/myService.xsodata/",
        "type": "OData",
        "settings": {
            "odataVersion": "2.0",
            "localUri": "localService/myService.xsodata/metadata.xml"
        }
    }
</code>```

And the model is defined:

```<code>"models": {
    "Customer": {
        "type": "sap.ui.model.odata.v2.ODataModel",
        "settings": {
            "useBatch": "false"
        },
        "dataSource": "mainService"
    }
</code>```

How can I add the expand to the model?

答:
The data cannot be expanded in the model definition itself. The expand parameter is to be used where the binding between the view and data is defined as mentioned in the documentation:

Some of the parameters must not be included in every request, but should only be added to specific aggregation or element bindings, such as $expand or $select. For this, the binding methods provide the option to pass a map of parameters, which are then included in all requests for this specific binding.

Here is an excerpt from the example https://embed.plnkr.co/wAlrHB/:

<List items="{
  path: 'odataModel>/Products',
  parameters: {
    expand: 'Category, Supplier',
    select: 'ProductName, UnitsInStock, Category/CategoryName, Supplier/Country'
  },
  sorter: [
    {
      path: 'Category/CategoryName',
      group: true
    }
  ],
  filters: [
    {
      path: 'Supplier/Country',
      operator: 'EQ',
      value1: 'UK'
    }
  ]
}">
  <ObjectListItem title="{odataModel>ProductName}" number="{odataModel>UnitsInStock}"/>
</List>
```
<p>The <strong>binding</strong> (not the model) will then send a request ...</p>
<blockquote>
<p>Requests to the back end are triggered by list bindings (ODataListBinding)</p>
</blockquote>
<p>... with the respective parameters appended by UI5:</p>
<pre class="lang-xml prettyprint-override"><code>https://services.odata.org/V2/Northwind/Northwind.svc/Products?$format=json&$skip=0&$top=100&$orderby=Category/CategoryName%20asc&$filter=Supplier/Country%20eq%20%27UK%27&$expand=Category%2c%20Supplier&$select=ProductName%2c%20UnitsInStock%2c%20Category%2fCategoryName%2c%20Supplier%2fCountry</code>```

⇒ JSON response

Title: SAPUI5 Expand the model in the manifest

Body:
I want to add a new model to the manifest.json.
The model is supposed to be expanded.

https://myPath/services/myService.xsodata/SubPath?$expand=CustomerRef

So the Datasource is defined:

"dataSources": {
    "mainService": {
        "uri": "/myPath/services/myService.xsodata/",
        "type": "OData",
        "settings": {
            "odataVersion": "2.0",
            "localUri": "localService/myService.xsodata/metadata.xml"
        }
    }

And the model is defined:

"models": {
    "Customer": {
        "type": "sap.ui.model.odata.v2.ODataModel",
        "settings": {
            "useBatch": "false"
        },
        "dataSource": "mainService"
    }

How can I add the expand to the model?

Body:
The data cannot be expanded in the model definition itself. The expand parameter is to be used where the binding between the view and data is defined as mentioned in the documentation:

Some of the parameters must not be included in every request, but should only be added to specific aggregation or element bindings, such as $expand or $select. For this, the binding methods provide the option to pass a map of parameters, which are then included in all requests for this specific binding.

Here is an excerpt from the example https://embed.plnkr.co/wAlrHB/:

<List items="{
  path: 'odataModel>/Products',
  parameters: {
    expand: 'Category, Supplier',
    select: 'ProductName, UnitsInStock, Category/CategoryName, Supplier/Country'
  },
  sorter: [
    {
      path: 'Category/CategoryName',
      group: true
    }
  ],
  filters: [
    {
      path: 'Supplier/Country',
      operator: 'EQ',
      value1: 'UK'
    }
  ]
}">
  <ObjectListItem title="{odataModel>ProductName}" number="{odataModel>UnitsInStock}"/>
</List>

The binding (not the model) will then send a request ...

Requests to the back end are triggered by list bindings (ODataListBinding)

... with the respective parameters appended by UI5:

https://services.odata.org/V2/Northwind/Northwind.svc/Products?$format=json&$skip=0&$top=100&$orderby=Category/CategoryName%20asc&$filter=Supplier/Country%20eq%20%27UK%27&$expand=Category%2c%20Supplier&$select=ProductName%2c%20UnitsInStock%2c%20Category%2fCategoryName%2c%20Supplier%2fCountry

⇒ JSON response

ContentLicense: CC BY-SA 4.0


问:
Linq - Is there are way to build up a linq statement from several snippets of linq
I have several methods that use similar linq statements but different enough for them to be in their own methods. So say, for the sake of arguemnt, I had the following linq snippet which is repeated across all methods (the real snippets would be much longer than this):

```<code>        where su.ObjId == serviceUserId
        where cl.StaffMemberId == staffMemberId
</code>```

If I was working in SQL I could just contatenate the repeated SQL as follows:

```<code>private string GetRepeatedSql()
{
 return "where su.ObjId = serviceUserId and cl.StaffMemberId = staffMemberId";
}

private void DoSomething()
{
 string mySql = "Select * from ...... lots of sql .." + GetRepeatedSql() + ".. some more sql";
}
</code>```

(Usual health warnings around contatenating SQL string together noted).

Is there something equivalent in Linq? I'm sick of having to make changes in several places - this seems to contravene the DRY principle.

Thanks!

答:
Correct me if I'm wrong but I always thought LINQ statements weren't executed until you actually used them. (Coming from LINQ to NHibernate)

If that is actually the case you could simply just add whatever you need to the existing statement. For example:

```<code>var temp=from x in Sometable select x;
</code>```

Then adding a where clause:

```<code>temp = from x in temp where x.ID==1234 select x;
</code>```

Then order by

```<code>temp=from x in temp order by x.ID select x;
</code>```

I won't lie I have never done it this way but I assume it should work. If someone knows this won't work please explain why. Thanks.

Found this on msdn: http://msdn.microsoft.com/en-us/library/bb397906.aspx

In LINQ the execution of the query is
  distinct from the query itself; in
  other words you have not retrieved any
  data just by creating a query
  variable.

So by creating the variable you have not retrieved any data. Although maybe the way I'm doing it above would return data because I am calling from  x in temp to change the query.

Body:
I have several methods that use similar linq statements but different enough for them to be in their own methods. So say, for the sake of arguemnt, I had the following linq snippet which is repeated across all methods (the real snippets would be much longer than this):

        where su.ObjId == serviceUserId
        where cl.StaffMemberId == staffMemberId

If I was working in SQL I could just contatenate the repeated SQL as follows:

private string GetRepeatedSql()
{
 return "where su.ObjId = serviceUserId and cl.StaffMemberId = staffMemberId";
}

private void DoSomething()
{
 string mySql = "Select * from ...... lots of sql .." + GetRepeatedSql() + ".. some more sql";
}

(Usual health warnings around contatenating SQL string together noted).

Is there something equivalent in Linq? I'm sick of having to make changes in several places - this seems to contravene the DRY principle.

Thanks!

Body:
Correct me if I'm wrong but I always thought LINQ statements weren't executed until you actually used them. (Coming from LINQ to NHibernate)

If that is actually the case you could simply just add whatever you need to the existing statement. For example:

var temp=from x in Sometable select x;

Then adding a where clause:

temp = from x in temp where x.ID==1234 select x;

Then order by

temp=from x in temp order by x.ID select x;

I won't lie I have never done it this way but I assume it should work. If someone knows this won't work please explain why. Thanks.

Found this on msdn: http://msdn.microsoft.com/en-us/library/bb397906.aspx

In LINQ the execution of the query is
  distinct from the query itself; in
  other words you have not retrieved any
  data just by creating a query
  variable.

So by creating the variable you have not retrieved any data. Although maybe the way I'm doing it above would return data because I am calling from  x in temp to change the query.


问:
Using $gt in mongodb
I want to select all the documents in a collection that have 'age' property greater than a given age value.

Not working,

age: {
    $gt: given_age_value
}
```

<p>Working fine,</p>

<pre class="lang-js prettyprint-override"><code>age: {
    $gt: +given_age_value
}
</code>```

What difference does the plus sign make? I can't find it in docs.

答:
because the given_age_value is not a number (string may be) and adding + before makes it to a number.

{$gt: "1"} doesn't work

{$gt: 1} will work

{$gt: +"1"}  will work

Title: Using $gt in mongodb

Body:
I want to select all the documents in a collection that have 'age' property greater than a given age value.

Not working,

age: {
    $gt: given_age_value
}

Working fine,

age: {
    $gt: +given_age_value
}

What difference does the plus sign make? I can't find it in docs.


问:
Subset df on string condition
I want to subset df on an unknown condition (say, randomly defined as in the example below):

```<code>df <- data.frame(a=1:10, b = 10:1)
condition <- paste0(sample(letters[1:2],1), sample(c("<",">"),1), sample(1:10,1))
</code>```

I can do this with eval, which, vox populi, is suboptimal:

```<code>subset(df, eval(parse(text=condition)))
</code>```

Is there an alternative to eval(parse)?

答:
With a slight adaptation to your script if becomes more feasible:

```<code>condition  <- list(value1 = sample(letters[1:2], 1),
                   comp =   sample(c(`<`, `>`), 1)[[1]],
                   value2 = sample(1:10, 1))

subset(df, condition$comp(df[, condition$value1], condition$value2))
</code>```

So it depends on the constraints on how your condition is passed.

(Note that using subset might be a bad idea)

Title: Subset df on string condition

Body:
I want to subset df on an unknown condition (say, randomly defined as in the example below):

df <- data.frame(a=1:10, b = 10:1)
condition <- paste0(sample(letters[1:2],1), sample(c("<",">"),1), sample(1:10,1))

I can do this with eval, which, vox populi, is suboptimal:

subset(df, eval(parse(text=condition)))

Is there an alternative to eval(parse)?

Body:
With a slight adaptation to your script if becomes more feasible:

condition  <- list(value1 = sample(letters[1:2], 1),
                   comp =   sample(c(`<`, `>`), 1)[[1]],
                   value2 = sample(1:10, 1))

subset(df, condition$comp(df[, condition$value1], condition$value2))

So it depends on the constraints on how your condition is passed.

(Note that using subset might be a bad idea)


答:
```<code>SELECT TIMESTAMPDIFF(MINUTE,STR_TO_DATE(Start_time,'%d/%m/%Y %H:%i:%s),STR_TO_DATE(end_time,'%d/%m/%Y %H:%i:%s)) from TABLENAME;
</code>```

Try above query.Hope this will help you.

Title: I want to subtract values from one column to another column in the same table with Specific id

Body:
Proc Id       Start_time             end_time                Status
111           7/4/2017 9:08:43 AM    7/4/2017 9:35:54 AM     Success

I want to find the time duration(in Mins) between the star_time and end_time.
Please help me how to do it?

Body:
SELECT TIMESTAMPDIFF(MINUTE,STR_TO_DATE(Start_time,'%d/%m/%Y %H:%i:%s),STR_TO_DATE(end_time,'%d/%m/%Y %H:%i:%s)) from TABLENAME;

Try above query.Hope this will help you.


问:
How to connect to remote SQL Server from Visual Studio for Mac?
This piece of code executes just fine on Visual Studio 2017 and .NET Core v1.1, but the connection times out on Visual Studio for Mac.

```<code>using System;
using System.Data.SqlClient;
using System.Data;

namespace test_console_app
{
    class Program
    {
        static void Main(string[] args)
        {
            using (SqlConnection connection = new SqlConnection(@"Server=xxxx,1433\xxxx;Database=xxxx;User Id=xxxx;Password=xxxx"))
            {
                using (SqlCommand command = new SqlCommand("Select * from UserAccounts", connection))
                {
                    connection.Open();
                    SqlDataReader reader = command.ExecuteReader();
                    while (reader.Read())
                    {
                        Console.WriteLine(((IDataRecord)reader)[1]);
                    }
                }
            }
        }
    }
}
</code>```

The exception that is thrown is the following:

"System.Data.SqlClient.SqlException: A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible. Verify that the instance name is correct and that SQL Server is configured to allow remote connections. (provider: TCP Provider, error: 25 - Connection string is not valid)"

Anyone know what the issue might be? Thanks.

答:
can you change this SqlConnection(@"Server=xxxx,1433\xxxx;Database=xxxx;User Id=xxxx;Password=xxxx"))
to this SqlConnection(@"Server=xxxx\xxxx,1433;Database=xxxx;User Id=xxxx;Password=xxxx"))

I think you put instance name after port, instead of ip.

Body:
This piece of code executes just fine on Visual Studio 2017 and .NET Core v1.1, but the connection times out on Visual Studio for Mac.

using System;
using System.Data.SqlClient;
using System.Data;

namespace test_console_app
{
    class Program
    {
        static void Main(string[] args)
        {
            using (SqlConnection connection = new SqlConnection(@"Server=xxxx,1433\xxxx;Database=xxxx;User Id=xxxx;Password=xxxx"))
            {
                using (SqlCommand command = new SqlCommand("Select * from UserAccounts", connection))
                {
                    connection.Open();
                    SqlDataReader reader = command.ExecuteReader();
                    while (reader.Read())
                    {
                        Console.WriteLine(((IDataRecord)reader)[1]);
                    }
                }
            }
        }
    }
}

The exception that is thrown is the following:

"System.Data.SqlClient.SqlException: A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible. Verify that the instance name is correct and that SQL Server is configured to allow remote connections. (provider: TCP Provider, error: 25 - Connection string is not valid)"

Anyone know what the issue might be? Thanks.


问:
React-Navigation StackNavigator header not showing
I'm trying to get the StackNavigator to work from react-navigation.org

I have another app that I'm successfully using TabNavigator which shows up fine.

Things I've tried so far to try and get this to work..

Copied the code literally line by line, no change

Checked each package version with yarn, no change

Moved the AppRegistry, no change

Not sure what to try next...

index.ios.js

```<code>import App from './src/App'
</code>```

/src/App.js

```<code>/* @flow */

import {AppRegistry} from 'react-native'
import QuestionList from './questionRow/QuestionList'
import React from 'react'
import {StackNavigator} from 'react-navigation'

export default class App extends React.Component {
    static navigationOptions = {
        title: 'Questions',
    }

    state = {}

    render() {
        return <QuestionList />
    }
}

const AIBUApp = StackNavigator({
    Home: {screen: App},
})

AppRegistry.registerComponent('aibu', () => App)
</code>```

Any ideas?

答:
I wasn't doing the correct App Registry.

Should have been...

```<code>AppRegistry.registerComponent('aibu', () => AIBUApp)
</code>```

Doesn't matter where you place this, can either be in the App.js or the index.ios/android.js

Body:
I'm trying to get the StackNavigator to work from react-navigation.org

I have another app that I'm successfully using TabNavigator which shows up fine.

Things I've tried so far to try and get this to work..

Copied the code literally line by line, no change

Checked each package version with yarn, no change

Moved the AppRegistry, no change

Not sure what to try next...

index.ios.js

import App from './src/App'

/src/App.js

/* @flow */

import {AppRegistry} from 'react-native'
import QuestionList from './questionRow/QuestionList'
import React from 'react'
import {StackNavigator} from 'react-navigation'

export default class App extends React.Component {
    static navigationOptions = {
        title: 'Questions',
    }

    state = {}

    render() {
        return <QuestionList />
    }
}

const AIBUApp = StackNavigator({
    Home: {screen: App},
})

AppRegistry.registerComponent('aibu', () => App)

Any ideas?

Body:
I wasn't doing the correct App Registry.

Should have been...

AppRegistry.registerComponent('aibu', () => AIBUApp)

Doesn't matter where you place this, can either be in the App.js or the index.ios/android.js


问:
Hide and show of kendo ui editor toolbar
I am using kendo ui editor control. Initially i am showing only editable area and hiding editor tool bar like

```<code><style>
  .k-editor-toolbar
    {
       display:none;
    }
</style>
</code>```

I am showing that in select function of kendo ui editor like

```<code> $("#editor").kendoEditor({
     select: function(e){
         $(".k-editor-toolbar").show();
      }
 });
</code>```

I want to hide the tool bar on body except the editable area in the kendo ui editor. I have tried like

```<code>    $('body').on('click', ':not(#editor)', function () {
           $(".k-editor-toolbar").hide();
       });
</code>```

But this is not working. on select of Dropdowns in the toolbar also it is hiding. I don't want to hide the tool bar when i click any thing on the toolbar. How can i able to do that

答:
```<code>$scope.$on('kendoWidgetCreated', function(event, widget) {
    $('.k-editor-toolbar').hide();
}
</code>```

Body:
I am using kendo ui editor control. Initially i am showing only editable area and hiding editor tool bar like

I am showing that in select function of kendo ui editor like

 $("#editor").kendoEditor({
     select: function(e){
         $(".k-editor-toolbar").show();
      }
 });

I want to hide the tool bar on body except the editable area in the kendo ui editor. I have tried like

    $('body').on('click', ':not(#editor)', function () {
           $(".k-editor-toolbar").hide();
       });

But this is not working. on select of Dropdowns in the toolbar also it is hiding. I don't want to hide the tool bar when i click any thing on the toolbar. How can i able to do that


问:
Memory leak using google charts with ajax
I'm fairly new to javascript and I'm having trouble finding a memory leak in some code which updates a google chart each second with ajax data.

My code (simplified to a small test case):

```<code>function TimeLine(id, max) {
    this.chart = new google.visualization.LineChart(document.getElementById(id));
    this.vals = new google.visualization.DataTable();
    this.vals.addColumn('number', 'Index');

    for (var i = 2; i < arguments.length; i++) {
        this.vals.addColumn('number', arguments[i]);
    }

    this.numCols = arguments.length - 2;
    this.max = max;
    this.index = 0;

    this.resourceOptions = {
        'title': 'Memory allocation',
            'width': 360,
        'height': 300
    };
}

TimeLine.prototype.Add = function () {

    if (this.vals.getNumberOfRows() > this.max) {
        this.vals.removeRow(0);
    }

    var row = [this.index];

    for (var i = 0; i < arguments.length; i++) {
        row.push(arguments[i]);
    }

    this.vals.addRow(row);

    this.chart.draw(this.vals, this.options);

    this.index++;
};

function onLoad() {
    window.Timeline = new TimeLine('gauges', 15, 'Alloc');
    drawCharts();
}

function drawCharts() {
    window.Timeline.Add(window.Timeline.index%3);

    setTimeout(drawCharts, 1000);
}

google.load('visualization', '1.0', {
    'packages': ['corechart']
});

google.setOnLoadCallback(onLoad);
</code>```

I'm using chrome Version 29.0.1547.62 on 64 bit Ubuntu.

I wrapped the chart in an object to (hopefully) make it easier for me to reason about scope and garbage collection since I'm not quite used to the JS scoping rules. I've seen many questions on SO which are similar, but as far as I can tell my code shouldn't produce a leak. Using the memory timeline I can see the memory climb each time drawCharts is called and most of that memory seems to be gc'd, but after around an hour I'm up to 300 MB for that tab, and it just keeps climbing until the tab crashes. The goal is to be able to keep this tab up for extended periods as a monitoring system for the current load on one of our servers, but currently I can only keep it up for a few hours before it gets killed.

I tried using the heap snapshot in the profile tab, and if I compare the snapshot before and after a few calls to drawCharts it seems like the leaked objects are SVG elements from the chart itself, but it's possible I'm interpreting those results incorrectly.

I've reproduced the problem:

http://jsfiddle.net/dv5nK/4/

After about 20 mins, the about:memory page in chrome will start to show high memory consumption around 150 MB for me. This effect can be seen faster by shortening the setTimeout to 100 ms.

EDIT: fixed memory usage stat

答:
If you are building a new chart for each update (with new
  google.visualization.SomeChart()) then when you are done with the
  previous instance, you must call clearChart() on it,  otherwise memory
  will accumulate.  Google Charts can't tell that the chart has been
  garbage collected, and it needs an explicit clearChart() call to
  unlink event handlers from the DOM.

source: https://github.com/google/google-visualization-issues/issues/1021

Body:
I'm fairly new to javascript and I'm having trouble finding a memory leak in some code which updates a google chart each second with ajax data.

My code (simplified to a small test case):

function TimeLine(id, max) {
    this.chart = new google.visualization.LineChart(document.getElementById(id));
    this.vals = new google.visualization.DataTable();
    this.vals.addColumn('number', 'Index');

    for (var i = 2; i < arguments.length; i++) {
        this.vals.addColumn('number', arguments[i]);
    }

    this.numCols = arguments.length - 2;
    this.max = max;
    this.index = 0;

    this.resourceOptions = {
        'title': 'Memory allocation',
            'width': 360,
        'height': 300
    };
}

TimeLine.prototype.Add = function () {

    if (this.vals.getNumberOfRows() > this.max) {
        this.vals.removeRow(0);
    }

    var row = [this.index];

    for (var i = 0; i < arguments.length; i++) {
        row.push(arguments[i]);
    }

    this.vals.addRow(row);

    this.chart.draw(this.vals, this.options);

    this.index++;
};

function onLoad() {
    window.Timeline = new TimeLine('gauges', 15, 'Alloc');
    drawCharts();
}

function drawCharts() {
    window.Timeline.Add(window.Timeline.index%3);

    setTimeout(drawCharts, 1000);
}

google.load('visualization', '1.0', {
    'packages': ['corechart']
});

google.setOnLoadCallback(onLoad);

I'm using chrome Version 29.0.1547.62 on 64 bit Ubuntu.

I wrapped the chart in an object to (hopefully) make it easier for me to reason about scope and garbage collection since I'm not quite used to the JS scoping rules. I've seen many questions on SO which are similar, but as far as I can tell my code shouldn't produce a leak. Using the memory timeline I can see the memory climb each time drawCharts is called and most of that memory seems to be gc'd, but after around an hour I'm up to 300 MB for that tab, and it just keeps climbing until the tab crashes. The goal is to be able to keep this tab up for extended periods as a monitoring system for the current load on one of our servers, but currently I can only keep it up for a few hours before it gets killed.

I tried using the heap snapshot in the profile tab, and if I compare the snapshot before and after a few calls to drawCharts it seems like the leaked objects are SVG elements from the chart itself, but it's possible I'm interpreting those results incorrectly.

I've reproduced the problem:

http://jsfiddle.net/dv5nK/4/

After about 20 mins, the about:memory page in chrome will start to show high memory consumption around 150 MB for me. This effect can be seen faster by shortening the setTimeout to 100 ms.

EDIT: fixed memory usage stat


问:
drawing dashed line using CALayer
I was able to draw a dashed box, using the following code:

```<code>CAShapeLayer *shapeLayer = [CAShapeLayer layer];
CGRect shapeRect = CGRectMake(0.0f, 0.0f, 200.0f, 100.0f);
[shapeLayer setBounds:shapeRect];
[shapeLayer setPosition:CGPointMake(self.coreImageView_.frameX, self.coreImageView_.frameBottom - self.coreImageView_.frameHeight/2)];
[shapeLayer setFillColor:[[UIColor clearColor] CGColor]];
[shapeLayer setStrokeColor:[[UIColor whiteColor] CGColor]];
[shapeLayer setLineWidth:2.0f];
[shapeLayer setLineJoin:kCALineJoinRound];
[shapeLayer setLineDashPattern:
[NSArray arrayWithObjects:[NSNumber numberWithInt:5],
[NSNumber numberWithInt:5],
  nil]];
</code>```

Now if I want to just draw a dashed line from point X to point B, how should I modify this code?

答:
```<code>CAShapeLayer *shaplayer = [CAShapeLayer layer];
    shaplayer.frame = CGRectMake(100, 100, 100, 100);
    [self.view.layer addSublayer:shaplayer];
    UIBezierPath *uipath = [UIBezierPath bezierPath];
    [uipath moveToPoint:CGPointMake(50, 200)];
    [uipath addLineToPoint:CGPointMake(250, 200)];
    shaplayer.path = uipath.CGPath;
    shaplayer.strokeColor = [UIColor redColor].CGColor;
    shaplayer.lineDashPattern = @[@4];
</code>```

Title: drawing dashed line using CALayer

Body:
I was able to draw a dashed box, using the following code:

CAShapeLayer *shapeLayer = [CAShapeLayer layer];
CGRect shapeRect = CGRectMake(0.0f, 0.0f, 200.0f, 100.0f);
[shapeLayer setBounds:shapeRect];
[shapeLayer setPosition:CGPointMake(self.coreImageView_.frameX, self.coreImageView_.frameBottom - self.coreImageView_.frameHeight/2)];
[shapeLayer setFillColor:[[UIColor clearColor] CGColor]];
[shapeLayer setStrokeColor:[[UIColor whiteColor] CGColor]];
[shapeLayer setLineWidth:2.0f];
[shapeLayer setLineJoin:kCALineJoinRound];
[shapeLayer setLineDashPattern:
[NSArray arrayWithObjects:[NSNumber numberWithInt:5],
[NSNumber numberWithInt:5],
  nil]];

Now if I want to just draw a dashed line from point X to point B, how should I modify this code?


问:
java.time.DateTimeException: Hijrah date out of range
today I was discovering Java's 8 Hijrah Date, and I am trying to convert from Hijri date to gregorian date; I have been getting this error:

java.time.DateTimeException: Hijrah date out of range

```<code>    String repayDate = date.substring(0, 4)+"-"+date.substring(4, 6)+"-"+date.substring(6, 8);
        DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        Date inputDate = dateFormat.parse(repayDate);
        Calendar cl=Calendar.getInstance();
        cl.setTime(inputDate);

        HijrahDate hDate=    HijrahChronology.INSTANCE.date(LocalDate.of(cl.get(1),cl.get(Calendar.MONTH)+1, cl.get(Calendar.DATE)));

        return IsoChronology.INSTANCE.date(hDate).toString() ;
</code>```

the content of date is : 1400-01-01

Thanks

答:
There is no need to use a DateFormat and a Calendar at all - if you can use the Java time API you should refrain from using the legacy API.

Here is a simple example that "works" with your input:

```<code>String date = "14000101";

TemporalAccessor ta = DateTimeFormatter.ofPattern("uuuuMMdd")
                                       .withChronology(HijrahChronology.INSTANCE)
                                       .parse(date);
HijrahDate hDate = HijrahDate.from(ta);

System.out.println("hDate = " + hDate);
System.out.println("Gregorian date = " + IsoChronology.INSTANCE.date(hDate).toString());
</code>```

Body:
today I was discovering Java's 8 Hijrah Date, and I am trying to convert from Hijri date to gregorian date; I have been getting this error:

java.time.DateTimeException: Hijrah date out of range

    String repayDate = date.substring(0, 4)+"-"+date.substring(4, 6)+"-"+date.substring(6, 8);
        DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        Date inputDate = dateFormat.parse(repayDate);
        Calendar cl=Calendar.getInstance();
        cl.setTime(inputDate);

        HijrahDate hDate=    HijrahChronology.INSTANCE.date(LocalDate.of(cl.get(1),cl.get(Calendar.MONTH)+1, cl.get(Calendar.DATE)));

        return IsoChronology.INSTANCE.date(hDate).toString() ;

the content of date is : 1400-01-01

Thanks

Body:
There is no need to use a DateFormat and a Calendar at all - if you can use the Java time API you should refrain from using the legacy API.

Here is a simple example that "works" with your input:

String date = "14000101";

TemporalAccessor ta = DateTimeFormatter.ofPattern("uuuuMMdd")
                                       .withChronology(HijrahChronology.INSTANCE)
                                       .parse(date);
HijrahDate hDate = HijrahDate.from(ta);

System.out.println("hDate = " + hDate);
System.out.println("Gregorian date = " + IsoChronology.INSTANCE.date(hDate).toString());


问:
React Event Bubbling: Finding the target Component
I have a
 Component wrapping some
 Components. I want to avoid adding an onClick handler to each li and instead use a single handler on the ul and capture the bubbled events.

What is the correct way of determining / assigning the clicked Component from the bubbled event?

```<code>class ListItemComponent extends React.Component {
    public render() {
        return (
            <li>Foo</li>
        )
    }
}

class ListComponent extends React.Component {
    private handleClick(event) {
        const target = event.target;
        // Determine clicked component, or index etc … ?
    }

    public render() {
        const items = this.props.items.map((x, i) => {
            <ListItemComponent active=“false” key={i} />
        })
        return (
            <ul onClick={this.handleClick} />
                { items }
            </ul>
        )
    }
}
</code>```

答:
My solution was to add a data-index attribute to each child which can be used to identify the component.

This avoids adding multiple event listeners while also avoiding the overhead of multiple ref callbacks to obtain the child DOM elements:

```<code>class ListItemComponent extends React.Component {
    public render() {
        return (
            <li data-index={this.props.index}>Foo</li>
        )
    }
}

class ListComponent extends React.Component {
    private handleClick(event) {
        const activeIndex = event.target.getAttribute('data-index');
        this.setState({ activeIndex });
    }

    public render() {
        const active = this.state.activeIndex;
        const items = this.props.items.map((x, i) => {
            <ListItemComponent active={i === active} key={i} index={i} />
        })
        return (
            <ul onClick={this.handleClick} />
                { items }
            </ul>
        )
    }
}
</code>```

Body:
I have a
 Component wrapping some
 Components. I want to avoid adding an onClick handler to each li and instead use a single handler on the ul and capture the bubbled events.

What is the correct way of determining / assigning the clicked Component from the bubbled event?

class ListItemComponent extends React.Component {
    public render() {
        return (

Foo

        )
    }
}

class ListComponent extends React.Component {
    private handleClick(event) {
        const target = event.target;
        // Determine clicked component, or index etc … ?
    }

    public render() {
        const items = this.props.items.map((x, i) => {
            <ListItemComponent active=“false” key={i} />
        })
        return (

                { items }

        )
    }
}

Body:
My solution was to add a data-index attribute to each child which can be used to identify the component.

This avoids adding multiple event listeners while also avoiding the overhead of multiple ref callbacks to obtain the child DOM elements:

class ListItemComponent extends React.Component {
    public render() {
        return (
            <li data-index={this.props.index}>Foo</li>
        )
    }
}

class ListComponent extends React.Component {
    private handleClick(event) {
        const activeIndex = event.target.getAttribute('data-index');
        this.setState({ activeIndex });
    }

    public render() {
        const active = this.state.activeIndex;
        const items = this.props.items.map((x, i) => {
            <ListItemComponent active={i === active} key={i} index={i} />
        })
        return (
            <ul onClick={this.handleClick} />
                { items }
            </ul>
        )
    }
}


问:
Where to find mono-service2 after mono installed?
I have installed mono on ubuntu 16.04 as the doc:

http://www.mono-project.com/download/#download-lin-ubuntu

but I can't run mono-service2

the system told me it can't been find

I run

find / -name mono-service2

got error:find: ./run/user/1000/gvfs:not have permission

so how can I use mono-service2

答:
you get this error because you did not run find command with sudo attributes

try like this to search only executables

```<code>sudo find / -executable -name mono-service2
</code>```

otherwise, you can try also with

```<code>whereis mono-service2
</code>```

or

```<code>which mono-service2
</code>```

Body:
you get this error because you did not run find command with sudo attributes

try like this to search only executables

sudo find / -executable -name mono-service2

otherwise, you can try also with

whereis mono-service2

or

which mono-service2


问:
Static variable to change in a child class from a parent
I want to create a child class of Dog, Cat, Lion, etc. I want each animal to create an object of itself. When it creates on object of itself I want it to keep track of how many total types of animals there are. So for example if there are 3 dogs then the dog class knows it has 4 dogs. The same for all the others.

Example code for Dog:

```<code>class Dog {
    static int numberOfDogs = 0;

    public Dog() {
    }

    public void AddDog() {
        numberOfDogs++;
    }

    public void MinusDog() {
        numberOfDogs--;
    }
}
</code>```

Now if I want to do the same thing for a cat I would need to rewrite all that code and replace dog with cat and so on.

What I want to do is create a parent class that has all that repeated code in one spot but as I create a Dog it will add to the dog variable and the same with the cat and so on. My idea of the parent class:

```<code>class Animal {
    public static int NumberOfAnimals;

    public void AddAnimal() {
        NumberOfAnimals++;
    }

    public void MinusAnimal() {
        NumberOfAnimals--;
    }
}
</code>```

If I derive Dog from Animal and call dog.AddAnimal() it will add to all the Animal's static variable. How can I make to so that I have a static variable in Dog that can be changed using the parent class Animal?

Or if I'm asking the wrong question, how can I get the desired result of having many animals with many static variables?

答:
This is not a good design but I preferred to stick to your main idea.
Please notice that a generic class would be a perfect solution for you.

Take a look at this :

Abstract animal class

```<code>public abstract class Animal
    {
        public static List<Type> AnimalList=new List<Type>();

        protected Animal(Type animalType)
        {

            AnimalList.Add(animalType);
        }
    }
</code>```

Dog as a child class

```<code> public class Dog : Animal
  {
    public Dog(Type animalType) : base(animalType)
    {

    }
    public static int CountDogs
    {
        get { return AnimalList.Count(x => x == typeof (Dog)); }
    }
  }
</code>```

Main Method :

```<code>Animal a =new Dog(typeof(Dog));
Animal a1=new Dog(typeof(Dog));
var c = Dog.CountDogs;
</code>```

Body:
I want to create a child class of Dog, Cat, Lion, etc. I want each animal to create an object of itself. When it creates on object of itself I want it to keep track of how many total types of animals there are. So for example if there are 3 dogs then the dog class knows it has 4 dogs. The same for all the others.

Example code for Dog:

class Dog {
    static int numberOfDogs = 0;

    public Dog() {
    }

    public void AddDog() {
        numberOfDogs++;
    }

    public void MinusDog() {
        numberOfDogs--;
    }
}

Now if I want to do the same thing for a cat I would need to rewrite all that code and replace dog with cat and so on.

What I want to do is create a parent class that has all that repeated code in one spot but as I create a Dog it will add to the dog variable and the same with the cat and so on. My idea of the parent class:

class Animal {
    public static int NumberOfAnimals;

    public void AddAnimal() {
        NumberOfAnimals++;
    }

    public void MinusAnimal() {
        NumberOfAnimals--;
    }
}

If I derive Dog from Animal and call dog.AddAnimal() it will add to all the Animal's static variable. How can I make to so that I have a static variable in Dog that can be changed using the parent class Animal?

Or if I'm asking the wrong question, how can I get the desired result of having many animals with many static variables?

Body:
This is not a good design but I preferred to stick to your main idea.
Please notice that a generic class would be a perfect solution for you.

Take a look at this :

Abstract animal class

public abstract class Animal
    {
        public static List<Type> AnimalList=new List<Type>();

        protected Animal(Type animalType)
        {

            AnimalList.Add(animalType);
        }
    }

Dog as a child class

 public class Dog : Animal
  {
    public Dog(Type animalType) : base(animalType)
    {

    }
    public static int CountDogs
    {
        get { return AnimalList.Count(x => x == typeof (Dog)); }
    }
  }

Main Method :

Animal a =new Dog(typeof(Dog));
Animal a1=new Dog(typeof(Dog));
var c = Dog.CountDogs;


问:
Error: Aesthetics must be either length 1 or the same as the data (2): x, y
I'm preparing one of the most simple barplots with ggplot2 and I am stuck :(

I want to generate a barplot and I want to add significant asterisk and line but I having problems with the line, here's my code:

```<code>p <- ggplot(data=AIG_samples, aes(x=X1, y=Colony_number, fill=X1)) +
  geom_bar(stat="identity", color="black")+
  geom_errorbar(aes(ymin=Colony_number-sd, ymax=Colony_number+sd), width=.1) +
  labs(y="Colony number",x="")+
  theme_minimal()

p + theme(legend.title = element_blank()) +
  scale_fill_manual(values=c("#999999","#333333"))+
  #Change the square proportion
  coord_fixed(ratio = .008) +
  #Remove X axis labels
  theme(axis.title.x=element_blank(),
        axis.text.x=element_blank(),
        axis.ticks.x=element_blank()) +
  #Adding asterisks
  geom_path(x=c(1,1,2,2),y=c(480,490,490,480)) +
  annotate("text",x=1.5,y=440,label="*", cex=7)
</code>```

And this is my data:

```<code>X1 | Colony_number | sd

Control|210.5|22.52

sh|387.5|33.96
</code>```

I know that the error is given by the following line geom_path(x=c(1,1,2,2),y=c(480,490,490,480))

I guess that's kind of stupid issue but I am new in ggplot2 :)

答:
```<code>p <- ggplot(data=df, aes(x=X1, y=Colony_number)) +
  geom_bar(aes(fill=X1), stat="identity", color="black")+
  geom_errorbar(aes(ymin=Colony_number-sd, ymax=Colony_number+sd), width=.1) +
  labs(y="Colony number",x="")+
  theme_minimal()

path = data.frame(x=c(1,1,2,2),y=c(480,490,490,480))

p + theme(legend.title = element_blank()) +
  scale_fill_manual(values=c("#999999","#333333"))+
  #Change the square proportion
  coord_fixed(ratio = .008) +
  #Remove X axis labels
  theme(axis.title.x=element_blank(),
        axis.text.x=element_blank(),
        axis.ticks.x=element_blank()) +
  #Adding asterisks
  geom_path(data = path, aes(x = x,y = y)) +
  annotate("text",x = 1.5, y = 440, label="*", cex=7)
</code>```

Body:
I'm preparing one of the most simple barplots with ggplot2 and I am stuck :(

I want to generate a barplot and I want to add significant asterisk and line but I having problems with the line, here's my code:

p <- ggplot(data=AIG_samples, aes(x=X1, y=Colony_number, fill=X1)) +
  geom_bar(stat="identity", color="black")+
  geom_errorbar(aes(ymin=Colony_number-sd, ymax=Colony_number+sd), width=.1) +
  labs(y="Colony number",x="")+
  theme_minimal()

p + theme(legend.title = element_blank()) +
  scale_fill_manual(values=c("#999999","#333333"))+
  #Change the square proportion
  coord_fixed(ratio = .008) +
  #Remove X axis labels
  theme(axis.title.x=element_blank(),
        axis.text.x=element_blank(),
        axis.ticks.x=element_blank()) +
  #Adding asterisks
  geom_path(x=c(1,1,2,2),y=c(480,490,490,480)) +
  annotate("text",x=1.5,y=440,label="*", cex=7)

And this is my data:

X1 | Colony_number | sd

Control|210.5|22.52

sh|387.5|33.96

I know that the error is given by the following line geom_path(x=c(1,1,2,2),y=c(480,490,490,480))

I guess that's kind of stupid issue but I am new in ggplot2 :)


问:
Is it possible to access the FTP deployment site logs for my account
We are needing to see the FTP transfer logs for one of our azure web sites.
Is this possible?</p>

答:
Unfortunately, in Azure App Service, the FTP logs are not exposed to the end users. The access is restricted to Microsoft.

You may want to raise a feedback here for the Azure app services team: Azure Web Apps User Voice


问:
Timestamp time mismatch because of the different time zone
My team received a new project. The project has a bunch of tests which do not pass. By their words, all the tests should pass. After investigating the problem I discovered that there is a common issue. Most of the failing tests create Timestamp and work with it but the expected and the actual date is not the same. The difference is exactly one hour. The old dev team has been working from a zone which is GMT + 1 and we are working from GMT + 2.

Why this may happen?

EDIT:

I have a test which creates entity Rating and sets a bunch of properties. For example:

```<code>rating.setValidFromDate(new Timestamp(1459841866798L));
</code>```

then the test assert an expected String constant and rating.toString()

As I said the difference is exactly 1 hour

EDIT 2:

```<code>@Test
public void testToString() {
    Rating rating = new Rating();
    rating.setValidFromDate(new Timestamp(1459841866798L));

    assertEquals("Rating{validFromDate='2016-04-05 09:37:46'}", rating.toString());
}

@Override
public String toString() {
    StringBuilder builder = new StringBuilder();
    builder.append(Rating.class.getSimpleName());
    builder.append("{");
    builder.append("validFromDate='" + DateHelper.getStringFromDate(validFromDate) + "'");
    builder.append("}");
    return builder.toString();
}

public static String getStringFromDate(Date dateValue) {
    String strDate = "";
    if (dateValue != null) {
        DateFormat dateFormat = new SimpleDateFormat(Constants.DATETIME_FORMAT);
        strDate = dateFormat.format(dateValue);
    }
    return strDate;
}
</code>```

Solved

I decided to give you my solution to this problem.

After reading this: java.sql.Timestamp: changing timezone of Timestamp I found a way to manipulate time zone of the tests. So I decided to write a JUnit rule which will do this to all of my tests.

I have written the following Statement:

```<code>public class GermanTimeZoneStatement extends Statement {

    private final Statement base;

    public GermanTimeZoneStatement(Statement base) {
        super();
        this.base = base;
    }

    @Override
    public void evaluate() throws Throwable {
        TimeZone.setDefault(TimeZone.getTimeZone("Europe/Berlin"));
        base.evaluate();
    }
}
</code>```

After that I've written this rule:

```<code>public class GermanTimeZoneRule implements TestRule {

    public static GermanTimeZoneRule getInstance() {
        return new GermanTimeZoneRule();
    }

    @Override
    public Statement apply(Statement base, Description description) {
        return new GermanTimeZoneStatement(base);
    }
}
</code>```

Finally I've include the rule in my tests like this:

```<code>    @Rule
    public GermanTimeZoneRule germanTimeZoneRule = GermanTimeZoneRule.getInstance();
</code>```

答:
The code that you're testing is time-zone dependent.  It outputs a particular date according to what time it is in the user's default time-zone.  That's why it gives you different output from what it gives your colleagues.

You need to go back to the specification for that code, and check whether that's the intended behaviour.  If it is, you'll need to modify the test to take the time-zone into account.  If it's not the intended behaviour, then congratulations, your test has exposed a bug!

Body:
My team received a new project. The project has a bunch of tests which do not pass. By their words, all the tests should pass. After investigating the problem I discovered that there is a common issue. Most of the failing tests create Timestamp and work with it but the expected and the actual date is not the same. The difference is exactly one hour. The old dev team has been working from a zone which is GMT + 1 and we are working from GMT + 2.

Why this may happen?

EDIT:

I have a test which creates entity Rating and sets a bunch of properties. For example:

rating.setValidFromDate(new Timestamp(1459841866798L));

then the test assert an expected String constant and rating.toString()

As I said the difference is exactly 1 hour

EDIT 2:

@Test
public void testToString() {
    Rating rating = new Rating();
    rating.setValidFromDate(new Timestamp(1459841866798L));

    assertEquals("Rating{validFromDate='2016-04-05 09:37:46'}", rating.toString());
}

@Override
public String toString() {
    StringBuilder builder = new StringBuilder();
    builder.append(Rating.class.getSimpleName());
    builder.append("{");
    builder.append("validFromDate='" + DateHelper.getStringFromDate(validFromDate) + "'");
    builder.append("}");
    return builder.toString();
}

public static String getStringFromDate(Date dateValue) {
    String strDate = "";
    if (dateValue != null) {
        DateFormat dateFormat = new SimpleDateFormat(Constants.DATETIME_FORMAT);
        strDate = dateFormat.format(dateValue);
    }
    return strDate;
}

Solved

I decided to give you my solution to this problem.

After reading this: java.sql.Timestamp: changing timezone of Timestamp I found a way to manipulate time zone of the tests. So I decided to write a JUnit rule which will do this to all of my tests.

I have written the following Statement:

public class GermanTimeZoneStatement extends Statement {

    private final Statement base;

    public GermanTimeZoneStatement(Statement base) {
        super();
        this.base = base;
    }

    @Override
    public void evaluate() throws Throwable {
        TimeZone.setDefault(TimeZone.getTimeZone("Europe/Berlin"));
        base.evaluate();
    }
}

After that I've written this rule:

public class GermanTimeZoneRule implements TestRule {

    public static GermanTimeZoneRule getInstance() {
        return new GermanTimeZoneRule();
    }

    @Override
    public Statement apply(Statement base, Description description) {
        return new GermanTimeZoneStatement(base);
    }
}

Finally I've include the rule in my tests like this:

    @Rule
    public GermanTimeZoneRule germanTimeZoneRule = GermanTimeZoneRule.getInstance();


问:
iOS: How to get a proper Month name from a number?
I know that the NSDateformatter suite of functionality is a boon for mankind, but at the same time it is very confusing to me. I hope you can help me out.

Somewhere in my code, there is an int representing a month. So: 1 would be January, 2 February, etc.

In my user interface, I would like to display this integer as proper month name. Moreover, it should adhere to the locale of the device.

Thank you for your insights

In the mean time, I have done the following:

```<code>int monthNumber = 11
NSString * dateString = [NSString stringWithFormat: @"%d", monthNumber];

NSDateFormatter* dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"MM"];
NSDate* myDate = [dateFormatter dateFromString:dateString];
[dateFormatter release];

NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:@"MMMM"];
NSString *stringFromDate = [formatter stringFromDate:myDate];
[formatter release];
</code>```

is this the way to do it? It seems a bit wordy.

答:
Another option is to use the monthSymbols method:

```<code>int monthNumber = 11;   //November
NSDateFormatter *df = [[[NSDateFormatter alloc] init] autorelease];
NSString *monthName = [[df monthSymbols] objectAtIndex:(monthNumber-1)];
</code>```

Note that you'll need to subtract 1 from your 1..12 monthNumber since monthSymbols is zero-based.

Body:
I know that the NSDateformatter suite of functionality is a boon for mankind, but at the same time it is very confusing to me. I hope you can help me out.

Somewhere in my code, there is an int representing a month. So: 1 would be January, 2 February, etc.

In my user interface, I would like to display this integer as proper month name. Moreover, it should adhere to the locale of the device.

Thank you for your insights

In the mean time, I have done the following:

int monthNumber = 11
NSString * dateString = [NSString stringWithFormat: @"%d", monthNumber];

NSDateFormatter* dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"MM"];
NSDate* myDate = [dateFormatter dateFromString:dateString];
[dateFormatter release];

NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:@"MMMM"];
NSString *stringFromDate = [formatter stringFromDate:myDate];
[formatter release];

is this the way to do it? It seems a bit wordy.

Body:
Another option is to use the monthSymbols method:

int monthNumber = 11;   //November
NSDateFormatter *df = [[[NSDateFormatter alloc] init] autorelease];
NSString *monthName = [[df monthSymbols] objectAtIndex:(monthNumber-1)];

Note that you'll need to subtract 1 from your 1..12 monthNumber since monthSymbols is zero-based.


问:
grep invert match on two files
I have two text files containing one column each, for example -

File_A       File_B

1              1

2              2

3              8

If I do grep -f File_A File_B > File_C, I get File_C containing 1 and 2. I want to know how to use grep -v on two files so that I can get the non-matching values, 3 and 8 in the above example.

Thanks.

答:
```<code>awk 'NR==FNR{a[$0]=$0;next} !($0 in a) {print a[(FNR)], $0}' f1 f2
3 8
</code>```

To Understand the meaning of NR and FNR check below output of their print.

```<code>awk '{print NR,FNR}' f1 f2
1 1
2 2
3 3
4 4
5 1
6 2
7 3
8 4
</code>```

Condition NR==FNR is used to extract the data from first file as both NR and FNR would be same for first file only.

Title: grep invert match on two files

Body:
awk 'NR==FNR{a[$0]=$0;next} !($0 in a) {print a[(FNR)], $0}' f1 f2
3 8

To Understand the meaning of NR and FNR check below output of their print.

awk '{print NR,FNR}' f1 f2
1 1
2 2
3 3
4 4
5 1
6 2
7 3
8 4

Condition NR==FNR is used to extract the data from first file as both NR and FNR would be same for first file only.