问:
Algorithm in Python to store and search daily occurrence for thousands of numbered events?
I'm investigating solutions of storing and querying a historical record of event occurrences for a large number of items.

This is the simplified scenario: I'm getting a daily log of 200 000 streetlamps (labeled sl1 to sl200000) which shows if the lamp was operational on the day or not. It does not matter for how long the lamp was in service only that it was on a given calendar day.

Other bits of information are stored for each lamp as well and the beginning of the Python class looks something like this:

```<code>class Streetlamp(object):
    """Class for streetlamp record"""
    def __init__(self, **args):
        self.location = args['location']
        self.power = args['power']
        self.inservice = ???
</code>```

My py-foo is not too great and I would like to avoid a solution which is too greedy on disk/memory storage. So a solution with a dict of (year, month, day) tuples could be one solution, but I'm hoping to get pointers for a more efficient solution.

A record could be stored as a bit stream with each bit representing a day of a year starting with Jan 1. Hence, if a lamp was operational the first three days of 2010, then the record could be:

```<code>sl1000_up = dict('2010': '11100000000000...', '2011':'11111100100...')
</code>```

Search across year boundaries would need a merge, leap years are a special case, plus I'd need to code/decode a fair bit with this home grown solution. It seems not quiet right. speed-up-bitstring-bit-operations, how-do-i-find-missing-dates-in-a-list and finding-data-gaps-with-bit-masking where interesting postings I came across. I also investigated python-bitstring and did some googling, but nothing seems to really fit.

Additionally I'd like search for 'gaps' to be possible, e.g. 'three or more days out of action' and it is essential that a flagged day can be converted into a real calendar date.

I would appreciate ideas or pointers to possible solutions. To add further detail, it might be of interest that the back-end DB used is ZODB and pure Python objects which can be pickled are preferred.

答:
Create a 2D-array in Numpy:

```<code>import numpy as np

nbLamps = 200000
nbDays = 365

arr = np.array([nbLamps, nbDays], dtype=np.bool)
</code>```

It will be very memory-efficient and you can aggregate easily the days and lamps.

In order to manipulate the days even better, have a look at scikits.timeseries. They will allow you to access the dates with datetime objects.

Body:
I'm investigating solutions of storing and querying a historical record of event occurrences for a large number of items.

This is the simplified scenario: I'm getting a daily log of 200 000 streetlamps (labeled sl1 to sl200000) which shows if the lamp was operational on the day or not. It does not matter for how long the lamp was in service only that it was on a given calendar day.

Other bits of information are stored for each lamp as well and the beginning of the Python class looks something like this:

class Streetlamp(object):
    """Class for streetlamp record"""
    def __init__(self, **args):
        self.location = args['location']
        self.power = args['power']
        self.inservice = ???

My py-foo is not too great and I would like to avoid a solution which is too greedy on disk/memory storage. So a solution with a dict of (year, month, day) tuples could be one solution, but I'm hoping to get pointers for a more efficient solution.

A record could be stored as a bit stream with each bit representing a day of a year starting with Jan 1. Hence, if a lamp was operational the first three days of 2010, then the record could be:

sl1000_up = dict('2010': '11100000000000...', '2011':'11111100100...')

Search across year boundaries would need a merge, leap years are a special case, plus I'd need to code/decode a fair bit with this home grown solution. It seems not quiet right. speed-up-bitstring-bit-operations, how-do-i-find-missing-dates-in-a-list and finding-data-gaps-with-bit-masking where interesting postings I came across. I also investigated python-bitstring and did some googling, but nothing seems to really fit.

Additionally I'd like search for 'gaps' to be possible, e.g. 'three or more days out of action' and it is essential that a flagged day can be converted into a real calendar date.

I would appreciate ideas or pointers to possible solutions. To add further detail, it might be of interest that the back-end DB used is ZODB and pure Python objects which can be pickled are preferred.

Body:
Create a 2D-array in Numpy:

import numpy as np

nbLamps = 200000
nbDays = 365

arr = np.array([nbLamps, nbDays], dtype=np.bool)

It will be very memory-efficient and you can aggregate easily the days and lamps.

In order to manipulate the days even better, have a look at scikits.timeseries. They will allow you to access the dates with datetime objects.


来源: stackexchange

问:
Repeating Pictures for other items in the RecyclerView
First of all, Forgive me, my English is not good.

i have a RecyclerView with 9 items, But from the fourth item to the next, Pictures of the first 4 items are repeated for other items!
but other fields For all items in the RecyclerView, Have been completed correctly.

how to fix it problem?

this is my code:

My Model:

```<code>public class LocationsListModel {

final String DRAWABLE = "drawable/";
private String name,imageUrl, review, price;

public LocationsListModel(String name, String review, String price, String imageUrl) {
    this.name = name;
    this.review = review;
    this.price = price;
    this.imageUrl = imageUrl;
}

public String getName() {
    return name;
}
public String getReview() {
    return review;
}
public String getPrice() {
    return price;
}
public String getImageUrl() {
    return DRAWABLE + imageUrl;
}}
</code>```

My Adapter:

```<code>public class LocationsListAdapter extends RecyclerView.Adapter<LocationsListAdapter.LocationsListView> {

private static ArrayList<LocationsListModel> locationList;
private Context context;
private ImageView locationImage;

public void setItems(ArrayList<LocationsListModel> items) {
    this.locationList = items;
}

public class LocationsListView extends RecyclerView.ViewHolder {

    public CardView cardView;
    public TextView locationName;
    public TextView review;
    public TextView locationPrice;

    public LocationsListView(View itemView) {
        super(itemView);

        cardView = itemView.findViewById(R.id.cardView);

        locationName = itemView.findViewById(R.id.location_name);
        review = itemView.findViewById(R.id.review);
        locationPrice = itemView.findViewById(R.id.price);
        locationImage = itemView.findViewById(R.id.imageView2);
    }
}

@Override
public LocationsListAdapter.LocationsListView onCreateViewHolder(ViewGroup parent, int viewType) {

    View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.locations_list_item, parent, false);

    context = parent.getContext();

    return new LocationsListView(view);
}

@Override
public void onBindViewHolder(LocationsListAdapter.LocationsListView holder, int position) {
    final LocationsListModel locationsListModel = locationList.get(position);

    String uri = locationsListModel.getImageUrl();
    int resource = locationImage.getResources().getIdentifier(uri, null, locationImage.getContext().getPackageName());
    locationImage.setImageResource(resource);

    holder.locationName.setText(locationsListModel.getName());
    holder.review.setText(locationsListModel.getReview());
    holder.locationPrice.setText(locationsListModel.getPrice());

}

@Override
public int getItemCount() {
    return locationList.size();
}}
</code>```

My Fragment:

```<code>public class LocationsListFragment extends Fragment {

private final LocationsListAdapter locationsListAdapter = new LocationsListAdapter();
private RecyclerView locationsList;
SimpleRatingBar ratingBar;
ArrayList<LocationsListModel> locationsListModels = new ArrayList<>();

public LocationsListFragment() {
    // Required empty public constructor
}

// TODO: Rename and change types and number of parameters
public static LocationsListFragment newInstance() {
    LocationsListFragment fragment = new LocationsListFragment();
    return fragment;
}

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    final View view = inflater.inflate(R.layout.fragment_locations_list, container, false);

    ratingBar = view.findViewById(R.id.ratingBar);
    locationsList = view.findViewById(R.id.locations_lis);

    setRecyclerViewItems();

    return view;
}

private void setRecyclerViewItems() {

    SnapHelper snapHelper = new LinearSnapHelper();
    snapHelper.attachToRecyclerView(locationsList);

    locationsList.setLayoutManager(new LinearLayoutManager(getContext(),
            LinearLayoutManager.HORIZONTAL, true));

    locationsList.setAdapter(locationsListAdapter);

    locationsListModels.add(new LocationsListModel("Hotel 1","120 reviews","200$", "pic1"));
    locationsListModels.add(new LocationsListModel("Hotel 2","102 reviews","120$", "pic2"));
    locationsListModels.add(new LocationsListModel("Hotel 3","84 reviews","240$", "pic3"));
    locationsListModels.add(new LocationsListModel("Hotel 4","113 reviews","220$", "pic4"));
    locationsListModels.add(new LocationsListModel("Hotel 5","52 reviews","140$", "pic5"));
    locationsListModels.add(new LocationsListModel("Hotel 6","57 reviews","190$", "pic6"));
    locationsListModels.add(new LocationsListModel("Hotel 7","230 reviews","300$", "pic7"));
    locationsListModels.add(new LocationsListModel("Hotel 8","131 reviews","90$", "pic8"));
    locationsListModels.add(new LocationsListModel("Hotel 9","32 reviews","110$", "pic9"));

    locationsListAdapter.setItems(locationsListModels);
    locationsList.setHasFixedSize(true);

}}
</code>```

答:
In Gradle:

```<code>compile 'com.github.bumptech.glide:glide:3.5.2'
</code>```

Adapter:

```<code>Glide.with(context).load(imageurl).transform(new RoundImageTransform(context)).skipMemoryCache(true).into(ImageView);
</code>```

Note : Remove RoundImageTransform -- It's for making an imageview as round in shape

ContentLicense: CC BY-SA 3.0

Body:
First of all, Forgive me, my English is not good.

i have a RecyclerView with 9 items, But from the fourth item to the next, Pictures of the first 4 items are repeated for other items!
but other fields For all items in the RecyclerView, Have been completed correctly.

how to fix it problem?

this is my code:

My Model:

public class LocationsListModel {

final String DRAWABLE = "drawable/";
private String name,imageUrl, review, price;

public LocationsListModel(String name, String review, String price, String imageUrl) {
    this.name = name;
    this.review = review;
    this.price = price;
    this.imageUrl = imageUrl;
}

public String getName() {
    return name;
}
public String getReview() {
    return review;
}
public String getPrice() {
    return price;
}
public String getImageUrl() {
    return DRAWABLE + imageUrl;
}}

My Adapter:

public class LocationsListAdapter extends RecyclerView.Adapter<LocationsListAdapter.LocationsListView> {

private static ArrayList<LocationsListModel> locationList;
private Context context;
private ImageView locationImage;

public void setItems(ArrayList<LocationsListModel> items) {
    this.locationList = items;
}

public class LocationsListView extends RecyclerView.ViewHolder {

    public CardView cardView;
    public TextView locationName;
    public TextView review;
    public TextView locationPrice;

    public LocationsListView(View itemView) {
        super(itemView);

        cardView = itemView.findViewById(R.id.cardView);

        locationName = itemView.findViewById(R.id.location_name);
        review = itemView.findViewById(R.id.review);
        locationPrice = itemView.findViewById(R.id.price);
        locationImage = itemView.findViewById(R.id.imageView2);
    }
}

@Override
public LocationsListAdapter.LocationsListView onCreateViewHolder(ViewGroup parent, int viewType) {

    View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.locations_list_item, parent, false);

    context = parent.getContext();

    return new LocationsListView(view);
}

@Override
public void onBindViewHolder(LocationsListAdapter.LocationsListView holder, int position) {
    final LocationsListModel locationsListModel = locationList.get(position);

    String uri = locationsListModel.getImageUrl();
    int resource = locationImage.getResources().getIdentifier(uri, null, locationImage.getContext().getPackageName());
    locationImage.setImageResource(resource);

    holder.locationName.setText(locationsListModel.getName());
    holder.review.setText(locationsListModel.getReview());
    holder.locationPrice.setText(locationsListModel.getPrice());

}

@Override
public int getItemCount() {
    return locationList.size();
}}

My Fragment:

public class LocationsListFragment extends Fragment {

private final LocationsListAdapter locationsListAdapter = new LocationsListAdapter();
private RecyclerView locationsList;
SimpleRatingBar ratingBar;
ArrayList<LocationsListModel> locationsListModels = new ArrayList<>();

public LocationsListFragment() {
    // Required empty public constructor
}

// TODO: Rename and change types and number of parameters
public static LocationsListFragment newInstance() {
    LocationsListFragment fragment = new LocationsListFragment();
    return fragment;
}

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    final View view = inflater.inflate(R.layout.fragment_locations_list, container, false);

    ratingBar = view.findViewById(R.id.ratingBar);
    locationsList = view.findViewById(R.id.locations_lis);

    setRecyclerViewItems();

    return view;
}

private void setRecyclerViewItems() {

    SnapHelper snapHelper = new LinearSnapHelper();
    snapHelper.attachToRecyclerView(locationsList);

    locationsList.setLayoutManager(new LinearLayoutManager(getContext(),
            LinearLayoutManager.HORIZONTAL, true));

    locationsList.setAdapter(locationsListAdapter);

    locationsListModels.add(new LocationsListModel("Hotel 1","120 reviews","200$", "pic1"));
    locationsListModels.add(new LocationsListModel("Hotel 2","102 reviews","120$", "pic2"));
    locationsListModels.add(new LocationsListModel("Hotel 3","84 reviews","240$", "pic3"));
    locationsListModels.add(new LocationsListModel("Hotel 4","113 reviews","220$", "pic4"));
    locationsListModels.add(new LocationsListModel("Hotel 5","52 reviews","140$", "pic5"));
    locationsListModels.add(new LocationsListModel("Hotel 6","57 reviews","190$", "pic6"));
    locationsListModels.add(new LocationsListModel("Hotel 7","230 reviews","300$", "pic7"));
    locationsListModels.add(new LocationsListModel("Hotel 8","131 reviews","90$", "pic8"));
    locationsListModels.add(new LocationsListModel("Hotel 9","32 reviews","110$", "pic9"));

    locationsListAdapter.setItems(locationsListModels);
    locationsList.setHasFixedSize(true);

}}

Body:
In Gradle:

compile 'com.github.bumptech.glide:glide:3.5.2'

Adapter:

Glide.with(context).load(imageurl).transform(new RoundImageTransform(context)).skipMemoryCache(true).into(ImageView);

Note : Remove RoundImageTransform -- It's for making an imageview as round in shape


问:
Scope of functions in package-scoped class
Say you have a package-scoped class:

```<code>class MyClass {
}
</code>```

What is the difference between

```<code>class MyClass {
    public f() { ... }
}
</code>```

and

```<code>class MyClass {
    protected f() { ... }
}
</code>```

and

```<code>class MyClass {
    f() { ... }
}
</code>```

?

Since the class is package scoped, what will making the function public or protected do or add?

My reasoning for a package-scoped class:

You can't use the class from outside the package since it is package scoped, so public has no additional effect.

Following the same reasoning, protected has no additional effect, as you must stay within the package anyway.

Therefore, only private has limiting effect as the other 3 modifiers (package, public, protected) are all the same.

Is this correct?

I don't see the difference between the modifies when the class is package scoped.

答:
Yes. Though public and protected are redundant in default classes, still private have some meaning for them.

As pointed out in comments, in a inheritance cycle, though not directly, indirect children may get access through some other public class and hence they come handy in cases.

Otherwise, you already decided to make the whole class as package protected, apparently the inner level accessibility goes meaningless anyway.

In short you have chosen upper level against lower lever in terms of accessibility.

Body:
Say you have a package-scoped class:

class MyClass {
}

What is the difference between

class MyClass {
    public f() { ... }
}

and

class MyClass {
    protected f() { ... }
}

and

class MyClass {
    f() { ... }
}

?

Since the class is package scoped, what will making the function public or protected do or add?

My reasoning for a package-scoped class:

You can't use the class from outside the package since it is package scoped, so public has no additional effect.

Following the same reasoning, protected has no additional effect, as you must stay within the package anyway.

Therefore, only private has limiting effect as the other 3 modifiers (package, public, protected) are all the same.

Is this correct?

I don't see the difference between the modifies when the class is package scoped.


问:
Nested Table Loop Laravel 5.4

I am having some trouble writing some nested HTML Tables from my Laravel Collection.

My Model

```<code>public static function offers($userId)
{
    return DB::table('users_vehicles')
    ->join('dealer_offers', 'users_vehicles.id', '=', 'dealer_offers.vehicle_id')
      ->where('user_id', '=', $userId)
      ->select('users_vehicles.*', 'dealer_offers.*');
}
</code>```

My Controller

```<code>public function dash()
{

    $userCars  = UserVehicles::offers(Auth::user()->id)->get();

    return view('customer.dash', compact('userCars'));
}
</code>```

My Collection Results

In My View blade Template

```<code>@foreach( $userCars->chunk(1) as $userCarChunk)
    <div id="no-more-tables">
        <table  class="table table-bordered table-hover">
            <caption>Offers for My Mazda 326 </caption>
            <thead>
                <tr>
                    <th class="numeric">DEALER RATING</th>
                    <th class="numeric">AMOUNT </th>
                    <th class="numeric"> 3 DAYS To Accept </th>
                </tr>
            </thead>
            <tbody>
            @foreach( $userCarChunk as $car)
                <tr>
                    <td data-title="First Name">
                        <div class="rating">
                            <label>
                                <input type="radio" name="rating" value="5" title="5 stars"> 5
                            </label>

                        </div>
                    </td>
                    <td data-title="Last Name"> 55 000 </td>
                    <td data-title="Username">
                        <a href="{{ route('customer.eval.show', 1) }}">Accept</a>
                    </td>
                </tr>
                @endforeach
            </tbody>
        </table>
    </div>
@endforeach
</code>```

Front-End View

Question

How can I create a nested HTML Table for all the user vehicles, so that I can write the vehicle name and all the offers for that particular vehicle?

I hope my question is clear.

答:
Answer

My Model UserVehicles.php

```<code>public function offers() {
    return $this->hasMany(DealerOffers::class, 'vehicle_id');
}
</code>```

My Controller CustomerController.php

```<code>$offersToCustomer = UserVehicles::with('offers')->get();
</code>```

Dashboard Blade template

```<code>@foreach( $offersToCustomer as $offer)
    <div id="no-more-tables_">
        <table  class="table table-bordered table-hover">
            <caption>Offers for My :: <b style="color: #00BFF0"> {{ $offer->vehicle_make }} {{ $offer->vehicle_model }}  </b> </caption>
            <thead>
                <tr>
                    <th class="numeric">DEALER RATING</th>
                    <th class="numeric">AMOUNT REQUESTED </th>
                    <th class="numeric">AMOUNT OFFERED </th>
                    <th class="numeric"> Expires :: {{ Carbon\Carbon::parse($offer->offer_expiry)->format('d-m-Y') }} </th>
                </tr>
            </thead>
                <tbody>
                @foreach( $offer->offers as $subOffer)
                    <tr>
                        <td data-title="DEALER RATING">
                            <input id="rating" name="rating" class="rating rating-loading" value="3" data-min="0" data-max="5" data-step="1"  />
                        </td>
                        <td data-title="AMOUNT REQUESTED">R  {{ number_format($offer->vehicle_amount_asked, 2, '.', ' ') }} </td>
                        <td data-title="AMOUNT OFFERED">R  {{ number_format($subOffer->offer_amount, 2, '.', ' ') }} </td>
                        <td data-title="ACTIONS">
                            <button data-offer_id="{{ $offer->id }} " data-vehicle_id="{{ $subOffer->vehicle_id }}"
                                            class="btn btn-xs btn-success accept-offer">Accept</button>
                        </td>
                    </tr>
                    @endforeach
                </tbody>
            </table>
        </div>
    @endforeach
</code>```

Output

Title: Nested Table Loop Laravel 5.4

Body:
I am having some trouble writing some nested HTML Tables from my Laravel Collection.

My Model

public static function offers($userId)
{
    return DB::table('users_vehicles')
    ->join('dealer_offers', 'users_vehicles.id', '=', 'dealer_offers.vehicle_id')
      ->where('user_id', '=', $userId)
      ->select('users_vehicles.*', 'dealer_offers.*');
}

My Controller

public function dash()
{

    $userCars  = UserVehicles::offers(Auth::user()->id)->get();

    return view('customer.dash', compact('userCars'));
}

My Collection Results

In My View blade Template

@foreach( $userCars->chunk(1) as $userCarChunk)

Offers for My Mazda 326

                    DEALER RATING
                    AMOUNT
                     3 DAYS To Accept

            @foreach( $userCarChunk as $car)

                                <input type="radio" name="rating" value="5" title="5 stars"> 5

                     55 000

                        Accept

                @endforeach

@endforeach

Front-End View

Question

How can I create a nested HTML Table for all the user vehicles, so that I can write the vehicle name and all the offers for that particular vehicle?

I hope my question is clear.

Body:
Answer

My Model UserVehicles.php

public function offers() {
    return $this->hasMany(DealerOffers::class, 'vehicle_id');
}

My Controller CustomerController.php

$offersToCustomer = UserVehicles::with('offers')->get();

Dashboard Blade template

@foreach( $offersToCustomer as $offer)
    <div id="no-more-tables_">
        <table  class="table table-bordered table-hover">
            <caption>Offers for My :: <b style="color: #00BFF0"> {{ $offer->vehicle_make }} {{ $offer->vehicle_model }}  </b> </caption>
            <thead>
                <tr>
                    <th class="numeric">DEALER RATING</th>
                    <th class="numeric">AMOUNT REQUESTED </th>
                    <th class="numeric">AMOUNT OFFERED </th>
                    <th class="numeric"> Expires :: {{ Carbon\Carbon::parse($offer->offer_expiry)->format('d-m-Y') }} </th>
                </tr>
            </thead>
                <tbody>
                @foreach( $offer->offers as $subOffer)
                    <tr>
                        <td data-title="DEALER RATING">
                            <input id="rating" name="rating" class="rating rating-loading" value="3" data-min="0" data-max="5" data-step="1"  />
                        </td>
                        <td data-title="AMOUNT REQUESTED">R  {{ number_format($offer->vehicle_amount_asked, 2, '.', ' ') }} </td>
                        <td data-title="AMOUNT OFFERED">R  {{ number_format($subOffer->offer_amount, 2, '.', ' ') }} </td>
                        <td data-title="ACTIONS">
                            <button data-offer_id="{{ $offer->id }} " data-vehicle_id="{{ $subOffer->vehicle_id }}"
                                            class="btn btn-xs btn-success accept-offer">Accept</button>
                        </td>
                    </tr>
                    @endforeach
                </tbody>
            </table>
        </div>
    @endforeach

Output


问:
Pentaho spoon is not starting
I'm just trying to open the GUI interface, but it is not opening and without any reason, any error message.
Any Idea?

C:\software\data-integration>Spoon.bat
DEBUG: Using JAVA_HOME
DEBUG: _PENTAHO_JAVA_HOME=C:\Program Files\Java\jre1.8.0_152
DEBUG: _PENTAHO_JAVA=C:\Program Files\Java\jre1.8.0_152\bin\javaw.exe

C:\software\data-integration>start "Spoon" "C:\Program Files\Java\jre1.8.0_152\bin\javaw.exe"  "-Xms1024m" "-Xmx1024m" "-XX:MaxPermSize=256m" "-Dhttps.protocols=TLSv1,TLSv1.1,TLSv1.2" "-Djava.library.path=libswt\win64" "-DKETTLE_HOME=C:\software\data-integration\" "-DKETTLE_REPOSITORY=" "-DKETTLE_USER=" "-DKETTLE_PASSWORD=" "-DKETTLE_PLUGIN_PACKAGES=" "-DKETTLE_LOG_SIZE_LIMIT=" "-DKETTLE_JNDI_ROOT=" -jar launcher\pentaho-application-launcher-8.0.0.0-28.jar -lib ..\libswt\win64
```

答:
In the hidden directory C:\Users\.kettle, delete the file called db-cache-xxx. Do not touch to the kettle.property, repository.xml, shared.xml if you did define some connections or custom setup.

Remove unused plugins. Copy the folder named plugins elsewhere. Try to see if spoon launch quicker. Then copy back the plugins (=folders), you need one by one.

Be patient. Sometimes your OS needs quite a bit of time to find the required memory space. Windows did not think it was important to give you feedback of what was happening in the background.

ContentLicense: CC BY-SA 4.0

Title: Pentaho spoon is not starting


问:
MvvmCross 5.4 Custom Presenter: Method 'MvvmCross.Droid.Views.MvxAndroidViewPresenter..ctor' not found

I've seen this and the solution isn't working.

I've updated to the latest MvvmCross (well, latest everything actually) which is 5.4.2 at the time of this writing.

Here is my setup that registers my presenter:

```<code>public class Setup : MvxAppCompatSetup
{
    public Setup(Context applicationContext)
        : base(applicationContext)
    {
    }

    protected override IEnumerable<Assembly> AndroidViewAssemblies => new List<Assembly>(base.AndroidViewAssemblies)
    {
        typeof(global::Android.Support.V7.Widget.Toolbar).Assembly
    };

    protected override IMvxApplication CreateApp()
    {
        Mvx.RegisterSingleton<INetworkManager>(() => new NetworkManagerAndroid(this.ApplicationContext));

        return new App();
    }

    protected override void InitializeLastChance()
    {
        base.InitializeLastChance();
        Mvx.RegisterSingleton<IAnalyticsService>(() => GoogleAnalyticsService.GetInstance());
    }

    protected override IMvxAndroidViewPresenter CreateViewPresenter()
    {
        var presenter = new MyAndroidPresenter(AndroidViewAssemblies);
        Mvx.RegisterSingleton<IMvxAndroidViewPresenter>(presenter);

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

Here is my actual presenter:

```<code>public class MyAndroidPresenter : MvxFragmentsPresenter
{
    public MyAndroidPresenter(IEnumerable<Assembly> AndroidViewAssemblies)
        : base(AndroidViewAssemblies) // EXCEPTION HERE
    {
    }

    protected override void ShowFragment(MvxViewModelRequest request)
    {
        if (GoHomeHandled(request))
            return;

        if (ShowModalHandled(request))
            return;

        base.ShowFragment(request);
    }

    protected override void ShowActivity(MvxViewModelRequest request, MvxViewModelRequest fragmentRequest = null)
    {
        if (GoHomeHandled(request))
            return;

        if (ShowModalHandled(request))
            return;

        base.ShowActivity(request, fragmentRequest);
    }

    private bool ShowModalHandled(MvxViewModelRequest request)
    {
        if (request.PresentationValues == null)
            return false;

        var viewsContainer = Mvx.Resolve<IMvxViewsContainer>();
        var viewType = viewsContainer.GetViewType(request.ViewModelType);
        var intent = new Intent(Application.Context, viewType);

        if (request.PresentationValues.ContainsKey(Utilities.Constants.Navigation.ShowModal))
        {
            intent.AddFlags(ActivityFlags.NewTask | ActivityFlags.ClearTask);

            Application.Context.StartActivity(intent);
            return true;
        }
        else if (request.PresentationValues.ContainsKey(Utilities.Constants.Navigation.StayModal))
        {
            Application.Context.StartActivity(intent);
            return true;
        }
        else
        {
            return false;
        }
    }

    private bool GoHomeHandled(MvxViewModelRequest request)
    {
        if (request.PresentationValues == null)
            return false;

        if (request.PresentationValues.ContainsKey(Utilities.Constants.Navigation.ReturnHome))
        {
            var intent = new Intent(Application.Context, typeof(MainActivity));
            intent.AddFlags(ActivityFlags.NewTask | ActivityFlags.ClearTask | ActivityFlags.TaskOnHome);

            Application.Context.StartActivity(intent);

            return true;
        }

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

The exception I'm getting is the one in the title. I've tried cleaning, rebuilding, refreshing NuGet packages all to no avail.

I'm a bit frustrated and at a loss. I would appreciate any help.

答: The presenter name should be MvxAppCompatViewPresenter. If yours is still MvxFragmentsPresenter it means that one or more packages are outdated. Look at the Playground sample to see a full implementation: https://github.com/MvvmCross/MvvmCross/tree/develop/TestProjects/Playground

Body:
I've seen this and the solution isn't working.

I've updated to the latest MvvmCross (well, latest everything actually) which is 5.4.2 at the time of this writing.

Here is my setup that registers my presenter:

public class Setup : MvxAppCompatSetup
{
    public Setup(Context applicationContext)
        : base(applicationContext)
    {
    }

    protected override IEnumerable<Assembly> AndroidViewAssemblies => new List<Assembly>(base.AndroidViewAssemblies)
    {
        typeof(global::Android.Support.V7.Widget.Toolbar).Assembly
    };

    protected override IMvxApplication CreateApp()
    {
        Mvx.RegisterSingleton<INetworkManager>(() => new NetworkManagerAndroid(this.ApplicationContext));

        return new App();
    }

    protected override void InitializeLastChance()
    {
        base.InitializeLastChance();
        Mvx.RegisterSingleton<IAnalyticsService>(() => GoogleAnalyticsService.GetInstance());
    }

    protected override IMvxAndroidViewPresenter CreateViewPresenter()
    {
        var presenter = new MyAndroidPresenter(AndroidViewAssemblies);
        Mvx.RegisterSingleton<IMvxAndroidViewPresenter>(presenter);

        return presenter;
    }
}

Here is my actual presenter:

public class MyAndroidPresenter : MvxFragmentsPresenter
{
    public MyAndroidPresenter(IEnumerable<Assembly> AndroidViewAssemblies)
        : base(AndroidViewAssemblies) // EXCEPTION HERE
    {
    }

    protected override void ShowFragment(MvxViewModelRequest request)
    {
        if (GoHomeHandled(request))
            return;

        if (ShowModalHandled(request))
            return;

        base.ShowFragment(request);
    }

    protected override void ShowActivity(MvxViewModelRequest request, MvxViewModelRequest fragmentRequest = null)
    {
        if (GoHomeHandled(request))
            return;

        if (ShowModalHandled(request))
            return;

        base.ShowActivity(request, fragmentRequest);
    }

    private bool ShowModalHandled(MvxViewModelRequest request)
    {
        if (request.PresentationValues == null)
            return false;

        var viewsContainer = Mvx.Resolve<IMvxViewsContainer>();
        var viewType = viewsContainer.GetViewType(request.ViewModelType);
        var intent = new Intent(Application.Context, viewType);

        if (request.PresentationValues.ContainsKey(Utilities.Constants.Navigation.ShowModal))
        {
            intent.AddFlags(ActivityFlags.NewTask | ActivityFlags.ClearTask);

            Application.Context.StartActivity(intent);
            return true;
        }
        else if (request.PresentationValues.ContainsKey(Utilities.Constants.Navigation.StayModal))
        {
            Application.Context.StartActivity(intent);
            return true;
        }
        else
        {
            return false;
        }
    }

    private bool GoHomeHandled(MvxViewModelRequest request)
    {
        if (request.PresentationValues == null)
            return false;

        if (request.PresentationValues.ContainsKey(Utilities.Constants.Navigation.ReturnHome))
        {
            var intent = new Intent(Application.Context, typeof(MainActivity));
            intent.AddFlags(ActivityFlags.NewTask | ActivityFlags.ClearTask | ActivityFlags.TaskOnHome);

            Application.Context.StartActivity(intent);

            return true;
        }

        return false;
    }
}

The exception I'm getting is the one in the title. I've tried cleaning, rebuilding, refreshing NuGet packages all to no avail.

I'm a bit frustrated and at a loss. I would appreciate any help.


问:
Django: saving into model field
another django question. I have a edit form like this. Look at current_status in the code.

It has been updated:

```<code>def edit_item(request, client_id = 0, item_id = 0):
    client = None
    item = None
    status = None
    contact = None
    status_id = request.POST.get('status_id', None)
    contact_id = request.POST.get('contact_id', None)
    save_item = request.POST.get('save_item', None)
    save_status = request.POST.get('save_status', None)
    try:
        client = models.Client.objects.get(pk = client_id)
        item = models.StorageItem.objects.get(pk = item_id)
    except:
        return HttpResponseNotFound()
    try:
        status = models.Status.objects.get(pk = status_id)
        contact = models.Contact.objects.get(pk = contact_id)
    except:
        pass
    if request.method == 'POST':
        form = forms.ItemForm(request.POST, instance = item)
        if form.is_valid() and save_item is not None:
            form.save(True)
            request.user.message_set.create(message = "Item {0} has been updated successfully.".format(item.tiptop_id))
            return HttpResponse("<script language=\"javascript\" type=\"text/javascript\">window.opener.location = window.opener.location; window.close();</script>")

        if status is not None and contact is not None and save_status is not None:
            current_status = models.ItemStatusHistory(item = item, contact = contact, status = status,
                                                          user = request.user)
            item.current_item_status_date = date.today()
            item.save()
            current_status.save()
            request.user.message_set.create(message = "Item status has been updated successfully.")
    else:
        form = forms.ItemForm(instance = item)
        title = str(client) + ' : Edit Item'
    status_list = models.Status.objects.all()
    return render_to_response('edit_item.html', {'form':form, 'title':title, 'status_list':status_list, 'item':item}, context_instance = RequestContext(request))
</code>```

current_status save's the latest date of when the form is edited. What I ALSO want to do is to save this value into this models field.

```<code>  class StorageItem(models.Model):
       current_item_status_date = models.DateField()
</code>```

答:
Is ItemForm a ModelForm (see Django Model Forms)?

If so form.save() will return a model instance. Then you can edit its fields if you need to. For example.

```<code>my_obj = form.save()
my_obj.current_item_status_date = datetime.date.today()
my_obj.save()
</code>```

If not, then simply create a new instance of your model and save the field value.

```<code>my_obj = StorageItem(current_item_status_date=datetime.date.today())
my_obj.save()
</code>```

ContentLicense: CC BY-SA 2.5

Title: Django: saving into model field

Body:
another django question. I have a edit form like this. Look at current_status in the code.

It has been updated:

def edit_item(request, client_id = 0, item_id = 0):
    client = None
    item = None
    status = None
    contact = None
    status_id = request.POST.get('status_id', None)
    contact_id = request.POST.get('contact_id', None)
    save_item = request.POST.get('save_item', None)
    save_status = request.POST.get('save_status', None)
    try:
        client = models.Client.objects.get(pk = client_id)
        item = models.StorageItem.objects.get(pk = item_id)
    except:
        return HttpResponseNotFound()
    try:
        status = models.Status.objects.get(pk = status_id)
        contact = models.Contact.objects.get(pk = contact_id)
    except:
        pass
    if request.method == 'POST':
        form = forms.ItemForm(request.POST, instance = item)
        if form.is_valid() and save_item is not None:
            form.save(True)
            request.user.message_set.create(message = "Item {0} has been updated successfully.".format(item.tiptop_id))
            return HttpResponse("")

        if status is not None and contact is not None and save_status is not None:
            current_status = models.ItemStatusHistory(item = item, contact = contact, status = status,
                                                          user = request.user)
            item.current_item_status_date = date.today()
            item.save()
            current_status.save()
            request.user.message_set.create(message = "Item status has been updated successfully.")
    else:
        form = forms.ItemForm(instance = item)
        title = str(client) + ' : Edit Item'
    status_list = models.Status.objects.all()
    return render_to_response('edit_item.html', {'form':form, 'title':title, 'status_list':status_list, 'item':item}, context_instance = RequestContext(request))

current_status save's the latest date of when the form is edited. What I ALSO want to do is to save this value into this models field.

  class StorageItem(models.Model):
       current_item_status_date = models.DateField()

Body:
Is ItemForm a ModelForm (see Django Model Forms)?

If so form.save() will return a model instance. Then you can edit its fields if you need to. For example.

my_obj = form.save()
my_obj.current_item_status_date = datetime.date.today()
my_obj.save()

If not, then simply create a new instance of your model and save the field value.

my_obj = StorageItem(current_item_status_date=datetime.date.today())
my_obj.save()


问:
Access a file in the referencing dll
I have a c# class library project with name ExampleLibrary1 in which I have to access a text file in project folder. I tried all the below ways for get directory path.

```<code>string assemblyFolder = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
string assemblyFolder1 = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
string assemblyFolder2 = Assembly.GetExecutingAssembly().CodeBase;
string assemblyFolder3 = Directory.GetCurrentDirectory();
</code>```

I am referencing the dll in consoleapplication1 and invoking the code which accesses the text file. All the above methods give me the below output and unable to access the file.

```<code>C:\Users\Desktop\ConsoleApplication1\ConsoleApplication1\bin\x64\Debug
C:\Users\Desktop\ConsoleApplication1\ConsoleApplication1\bin\x64\Debug
file:///C:/Users/Desktop/ConsoleApplication1/ConsoleApplication1/bin/x64/Debug/ExampleLibrary1.DLL
C:\Users\shrallap\Desktop\ConsoleApplication1\ConsoleApplication1\bin\x64\Debug
</code>```

My requirement is I have to read a file in ExampleLibrary1 code, script is also in ExampleLibrary1. But the code invocation happens from ConsoleApplication1

答:
If I don't misunderstand your question, your have a text file, let's call it "yourtextfile.bat" in the project folder of ExampleLibrary1, in the same folder where the file ExampleLibrary1.csproj is.

You cannot access it from your code. Project folder is where you organise your source code on the dev machine, on users' environment, there is no project folder.

Of course, you can use relative path like this to access it

```<code>..\\..\\..\\..\\ExampleLibrary1\\yourtextfile.bat
</code>```

But it only works in debugging.

You have to copy the text file to the output folder at build, then it will be the same folder as the dll/exe, and you can access it without worrying about its actual path, just use relative path "yourtextfile.bat" to access it.

In .NET, relative path is relative to the Environment.CurrentDirectory at runtime, usually the folder where exe resides if you double click to launch the exe. It is NOT relative to the project folder.

Title: Access a file in the referencing dll

Body:
I have a c# class library project with name ExampleLibrary1 in which I have to access a text file in project folder. I tried all the below ways for get directory path.

string assemblyFolder = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
string assemblyFolder1 = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
string assemblyFolder2 = Assembly.GetExecutingAssembly().CodeBase;
string assemblyFolder3 = Directory.GetCurrentDirectory();

I am referencing the dll in consoleapplication1 and invoking the code which accesses the text file. All the above methods give me the below output and unable to access the file.

C:\Users\Desktop\ConsoleApplication1\ConsoleApplication1\bin\x64\Debug
C:\Users\Desktop\ConsoleApplication1\ConsoleApplication1\bin\x64\Debug
file:///C:/Users/Desktop/ConsoleApplication1/ConsoleApplication1/bin/x64/Debug/ExampleLibrary1.DLL
C:\Users\shrallap\Desktop\ConsoleApplication1\ConsoleApplication1\bin\x64\Debug

My requirement is I have to read a file in ExampleLibrary1 code, script is also in ExampleLibrary1. But the code invocation happens from ConsoleApplication1

Body:
If I don't misunderstand your question, your have a text file, let's call it "yourtextfile.bat" in the project folder of ExampleLibrary1, in the same folder where the file ExampleLibrary1.csproj is.

You cannot access it from your code. Project folder is where you organise your source code on the dev machine, on users' environment, there is no project folder.

Of course, you can use relative path like this to access it

..\\..\\..\\..\\ExampleLibrary1\\yourtextfile.bat

But it only works in debugging.

You have to copy the text file to the output folder at build, then it will be the same folder as the dll/exe, and you can access it without worrying about its actual path, just use relative path "yourtextfile.bat" to access it.

In .NET, relative path is relative to the Environment.CurrentDirectory at runtime, usually the folder where exe resides if you double click to launch the exe. It is NOT relative to the project folder.


问:
how to get multiple object json values and push to array using jquery
I am trying to get data from json and push to array but it is not working. it is possible or not getting multiple object values from json. anybody can tell it is possible or not? if it is possible how we can do it and where i stucked from my code?

html

```<code>        <link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
        <script src="https://code.jquery.com/jquery-1.12.4.js"></script>
        <script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
        <script type="text/javascript">

        $( document ).ready(function() {
              var searchVal = [];
            var optionVal = [];
            var autocompVal = [];
            $.getJSON( "datas.json", function( data ) {

          $.each( data, function( key, val ) {
            searchVal.push(  key.searchVal.searchname );
          });

           $.each( data, function( key, val ) {
            optionVal.push(  key.optionVal.optionname );
          });

           $.each( data, function( key, val ) {
            autocompVal.push(  key.autocompVal );
          });

        console.log("Show all Array value="+searchVal +"=="+ optionVal +"=="+autocompVal);

        });

        $("#autoComplete").autocomplete({
                source: autocompVal,
                select: function (event, ui) {//when we select something from the search box
                    this.value = ui.item.label;
                    alert(this.value);
                    return false;
                }
            });

        });

        </script>

        <input type="text" id="autoComplete">
</code>```

datas.json:

```<code>        {
            "searchVal": [
                 { "searchname":"test1"},
                 { "searchname":"test2"}
                 ],
            "optionVal": [
                 { "optionname":"test11"},
                 { "optionname":"test12"},
                 { "optionname":"test13"}
                 ],
           "autocompVal": [
                 { "test11"},
                 { "test12"} ,
                 { "test13"},
                 { "test14"}
                 ]
        }
</code>```

答:
I have used pure js for most parts; Pushing json value to arrays have been achieved;

$( document ).ready(function() {
            var searchVal = [];
            var optionVal = [];
            var autocompVal = [];

            var data = {
              "searchVal": [
                   { "searchname":"test1"},
                   { "searchname":"test2"}
                   ],
              "optionVal": [
                   { "optionname":"test11"},
                   { "optionname":"test12"},
                   { "optionname":"test13"}
                   ],
             "autocompVal": [
                   { "optionname" : "test11"},
                   { "optionname" : "test12"} ,
                   { "optionname" : "test13"},
                   { "optionname" : "test14"}
                   ]
              }

          let keysArray = Object.keys(data);
          let searchValArray = [];
          let optionValArray = [];
          let autocompValArray = [];
          keysArray.forEach((key) => {
            if(key=="searchVal") searchValArray = (data[key]);
            if(key=="optionVal") optionValArray = (data[key]);
            if(key=="autocompVal") autocompValArray = (data[key]);
          });

          iterateAndPush(searchValArray,"searchname",searchVal);
          iterateAndPush(optionValArray,"optionname",optionVal);
          iterateAndPush(autocompValArray,"optionname",autocompVal);

          function iterateAndPush(array,key,arrayToPush) {
            array.map((searchKey) => {
              arrayToPush.push(searchKey[key]);
            });
          }

        console.log("Show all Array value="+searchVal +"=="+ optionVal +"=="+autocompVal);

        $("#autoComplete").autocomplete({
                source: autocompVal,
                select: function (event, ui) {//when we select something from the search box
                    this.value = ui.item.label;
                    alert(this.value);
                    return false;
                }
        });
      });```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<div id="autoComplete"></div></code>```

Body:
I am trying to get data from json and push to array but it is not working. it is possible or not getting multiple object values from json. anybody can tell it is possible or not? if it is possible how we can do it and where i stucked from my code?

html

        <link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">

        <input type="text" id="autoComplete">

datas.json:

        {
            "searchVal": [
                 { "searchname":"test1"},
                 { "searchname":"test2"}
                 ],
            "optionVal": [
                 { "optionname":"test11"},
                 { "optionname":"test12"},
                 { "optionname":"test13"}
                 ],
           "autocompVal": [
                 { "test11"},
                 { "test12"} ,
                 { "test13"},
                 { "test14"}
                 ]
        }

Body:
I have used pure js for most parts; Pushing json value to arrays have been achieved;

$( document ).ready(function() {
            var searchVal = [];
            var optionVal = [];
            var autocompVal = [];

            var data = {
              "searchVal": [
                   { "searchname":"test1"},
                   { "searchname":"test2"}
                   ],
              "optionVal": [
                   { "optionname":"test11"},
                   { "optionname":"test12"},
                   { "optionname":"test13"}
                   ],
             "autocompVal": [
                   { "optionname" : "test11"},
                   { "optionname" : "test12"} ,
                   { "optionname" : "test13"},
                   { "optionname" : "test14"}
                   ]
              }

          let keysArray = Object.keys(data);
          let searchValArray = [];
          let optionValArray = [];
          let autocompValArray = [];
          keysArray.forEach((key) => {
            if(key=="searchVal") searchValArray = (data[key]);
            if(key=="optionVal") optionValArray = (data[key]);
            if(key=="autocompVal") autocompValArray = (data[key]);
          });

          iterateAndPush(searchValArray,"searchname",searchVal);
          iterateAndPush(optionValArray,"optionname",optionVal);
          iterateAndPush(autocompValArray,"optionname",autocompVal);

          function iterateAndPush(array,key,arrayToPush) {
            array.map((searchKey) => {
              arrayToPush.push(searchKey[key]);
            });
          }

        console.log("Show all Array value="+searchVal +"=="+ optionVal +"=="+autocompVal);

        $("#autoComplete").autocomplete({
                source: autocompVal,
                select: function (event, ui) {//when we select something from the search box
                    this.value = ui.item.label;
                    alert(this.value);
                    return false;
                }
        });
      });

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<div id="autoComplete"></div>


问:
Cannot access windows container from outside the Azure host vm
I have created a docker container in Azure on Windows 2016.
Here is my DOCKERFILE:

```<code>FROM microsoft/aspnet

COPY ./ /inetpub/wwwroot

EXPOSE 443
EXPOSE 80
</code>```

I run it up like so:

```<code>docker run -d --name myctr myimg -p 443:443
</code>```

I can browse to it via the a domain name, which I configure in the hosts file.  SUCCESS!

On a remote machine, outside of the Azure network, I configure my hosts file, using the IP address of the Azure VM (and have also tried using the IP address of the container - not sure which one to use!)

However, I can't browse to it from outside of Azure.

Windows Firewall

I have disabled the Windows firewall.

Azure NSG

I have set up a Network Security Group which allows traffic in on port 443 (I have another website running on this box, and can access it from outside of Azure, with success)

Netstat shows the following:

```<code>netstat -ano | findstr :443 | findstr ESTABLISHED
  TCP    10.0.0.4:49682         99.99.99.99:443       ESTABLISHED     1252
  TCP    10.0.0.4:49700         99.99.99.98:443       ESTABLISHED     2476
  TCP    10.0.0.4:49718         99.99.99.92:443       ESTABLISHED     5112
</code>```

How do I configure the container/host/Azure so that I can view the website hosted on the container from a remote machine outside of Azure?
Any ideas greatly appreciated!

答:
How do I configure the container/host/Azure so that I can view the
website hosted on the container from a remote machine outside of
Azure?

By default,-p 80:80 means we are mapping port 80 of container to host port 80. So now others can access port 80 of your host to hit port 80 of container.

Here a example:

```<code>PS C:\Users\jason> docker run -d -p 80:80 microsoft/iis
3bf999503cd3110ae8fb1c01cc5c8c6153645a0d533960339490a0ba50634d3a
</code>```

After add port 80 to NSG inbound rule, I can browse it via Internet:

I have set up a Network Security Group which allows traffic in on port
443 (I have another website running on this box, and can access it
from outside of Azure, with success)

In your scenario, your port 443 in use, we can't bind docker with port 443, please try another port.

Body:
I have created a docker container in Azure on Windows 2016.
Here is my DOCKERFILE:

FROM microsoft/aspnet

COPY ./ /inetpub/wwwroot

EXPOSE 443
EXPOSE 80

I run it up like so:

docker run -d --name myctr myimg -p 443:443

I can browse to it via the a domain name, which I configure in the hosts file.  SUCCESS!

On a remote machine, outside of the Azure network, I configure my hosts file, using the IP address of the Azure VM (and have also tried using the IP address of the container - not sure which one to use!)

However, I can't browse to it from outside of Azure.

Windows Firewall

I have disabled the Windows firewall.

Azure NSG

I have set up a Network Security Group which allows traffic in on port 443 (I have another website running on this box, and can access it from outside of Azure, with success)

Netstat shows the following:

netstat -ano | findstr :443 | findstr ESTABLISHED
  TCP    10.0.0.4:49682         99.99.99.99:443       ESTABLISHED     1252
  TCP    10.0.0.4:49700         99.99.99.98:443       ESTABLISHED     2476
  TCP    10.0.0.4:49718         99.99.99.92:443       ESTABLISHED     5112

How do I configure the container/host/Azure so that I can view the website hosted on the container from a remote machine outside of Azure?
Any ideas greatly appreciated!

Body:
How do I configure the container/host/Azure so that I can view the
website hosted on the container from a remote machine outside of
Azure?

By default,-p 80:80 means we are mapping port 80 of container to host port 80. So now others can access port 80 of your host to hit port 80 of container.

Here a example:

PS C:\Users\jason> docker run -d -p 80:80 microsoft/iis
3bf999503cd3110ae8fb1c01cc5c8c6153645a0d533960339490a0ba50634d3a

After add port 80 to NSG inbound rule, I can browse it via Internet:

I have set up a Network Security Group which allows traffic in on port
443 (I have another website running on this box, and can access it
from outside of Azure, with success)

In your scenario, your port 443 in use, we can't bind docker with port 443, please try another port.


问:
Type stability for a function involving case distinctions
I am writing a function which computes the weights for the barycentric interpolation formula. Ignoring type stability, that's easy enough:

```<code>function baryweights(x)
    n = length(x)
    if n == 1; return [1.0]; end # This is obviously not type stable

    xmin,xmax = extrema(x)
    x *= 4/(xmax-xmin)
    # ^ Multiply by capacity of interval to avoid overflow
    return [
        1/prod(x[i]-x[j] for j in 1:n if j != i)
        for i = 1:n
    ]
end
</code>```

The problem for type stability is to work out the return type of the n > 1 case so I can return an array of the correct type in the n == 1 case. Is there an easy trick to achieve this?

答:
Simply call the function recursively on a dummy argument:</p>

```<code>function baryweights(x)
    n = length(x)
    if n == 1
        T = eltype(baryweights(zeros(eltype(x),2)))
        return [one(T)]
    end

    xmin,xmax = extrema(x)
    let x = 4/(xmax-xmin) * x
        # ^ Multiply by capacity of interval to avoid overflow,
        #   and wrap in let to avoid another source of type instability
        #   (https://github.com/JuliaLang/julia/issues/15276)
        return [
            1/prod(x[i]-x[j] for j in 1:n if j != i)
            for i = 1:n
        ]
    end
end
</code>```

Body:
I am writing a function which computes the weights for the barycentric interpolation formula. Ignoring type stability, that's easy enough:

function baryweights(x)
    n = length(x)
    if n == 1; return [1.0]; end # This is obviously not type stable

    xmin,xmax = extrema(x)
    x *= 4/(xmax-xmin)
    # ^ Multiply by capacity of interval to avoid overflow
    return [
        1/prod(x[i]-x[j] for j in 1:n if j != i)
        for i = 1:n
    ]
end

The problem for type stability is to work out the return type of the n > 1 case so I can return an array of the correct type in the n == 1 case. Is there an easy trick to achieve this?

Body:
Simply call the function recursively on a dummy argument:

function baryweights(x)
    n = length(x)
    if n == 1
        T = eltype(baryweights(zeros(eltype(x),2)))
        return [one(T)]
    end

    xmin,xmax = extrema(x)
    let x = 4/(xmax-xmin) * x
        # ^ Multiply by capacity of interval to avoid overflow,
        #   and wrap in let to avoid another source of type instability
        #   (https://github.com/JuliaLang/julia/issues/15276)
        return [
            1/prod(x[i]-x[j] for j in 1:n if j != i)
            for i = 1:n
        ]
    end
end


问:
How to add GIN index using Knex.js
I have been trying to add a GIN index using Knex.js on one of the column in my table, but I can not achieve this. I am trying to do something like this-

```<code>exports.up = function(knex, Promise) {
    return knex.schema.createTable('prediction_models', function(table){
            table.increments('id');
            table.string('model_name').index();
            table.jsonb('model_params');
            table.timestamp('createdAt').defaultTo(knex.fn.now());
        })
        .then(createGinIndex());

    function createGinIndex() {
        return knex.raw('CREATE INDEX modelgin ON public.prediction_models USING GIN (model_params);');
    }
};

exports.down = function(knex, Promise) {
    return knex.schema.dropTable('prediction_models');
};
</code>```

I am using PostgreSQL database. Can anyone please tell me if this is the correct way to implement this? If yes what's wrong with my code and if not how to implement it? Thanks!

答:
Those looking for a more "knexy" solution to this problem: it's not necessary to use .raw, as in Mikael Lepistö's solution. The .index chainable accepts a 2nd parameter called indexType. It can be used like so:

```<code>knex.schema.createTable('table_name', table => {
  table.jsonb('column_name').index(null, 'GIN')
})
</code>```

(the null on the first parameter is me saying "name this index for me")

This piece of code will produce the following queries:

```<code>create table "table_name" ("column_name" jsonb);
create index "table_name_column_name_index" on "table_name" using GIN ("column_name")
</code>```

Currently I'm creating such an index but, for performance reasons, I want it to only support the jsonb_path_ops operator class (as per section 8.14.4 of the documentation). This requires a create index statement ending in using GIN ("column_name" jsonb_path_ops). As such, I'll need to use a raw but there are plenty of use-cases where .index is sufficient.

Title: How to add GIN index using Knex.js

Body:
I have been trying to add a GIN index using Knex.js on one of the column in my table, but I can not achieve this. I am trying to do something like this-

exports.up = function(knex, Promise) {
    return knex.schema.createTable('prediction_models', function(table){
            table.increments('id');
            table.string('model_name').index();
            table.jsonb('model_params');
            table.timestamp('createdAt').defaultTo(knex.fn.now());
        })
        .then(createGinIndex());

    function createGinIndex() {
        return knex.raw('CREATE INDEX modelgin ON public.prediction_models USING GIN (model_params);');
    }
};

exports.down = function(knex, Promise) {
    return knex.schema.dropTable('prediction_models');
};

I am using PostgreSQL database. Can anyone please tell me if this is the correct way to implement this? If yes what's wrong with my code and if not how to implement it? Thanks!

Body:
Those looking for a more "knexy" solution to this problem: it's not necessary to use .raw, as in Mikael Lepistö's solution. The .index chainable accepts a 2nd parameter called indexType. It can be used like so:

knex.schema.createTable('table_name', table => {
  table.jsonb('column_name').index(null, 'GIN')
})

(the null on the first parameter is me saying "name this index for me")

This piece of code will produce the following queries:

create table "table_name" ("column_name" jsonb);
create index "table_name_column_name_index" on "table_name" using GIN ("column_name")

Currently I'm creating such an index but, for performance reasons, I want it to only support the jsonb_path_ops operator class (as per section 8.14.4 of the documentation). This requires a create index statement ending in using GIN ("column_name" jsonb_path_ops). As such, I'll need to use a raw but there are plenty of use-cases where .index is sufficient.


问:
Configure xsl to append a text to a html tag element

<presentation>
   <rootText>
    <firstChild>
     Question

Sub Question

    </firstChild>
   </rootText>
   ...
</presentation>```
</div>
</div>
</p>

<p>Here is the xsl</p>

```    <xsl:template match="presentation">

         <xsl:apply-templates select="rootText"/>

  </xsl:template>
```

<p>I want the output as below</p>

```'

     1  Question

Sub Question

`
```

I have to modify Question to 1 Question. The questions will not be ordered all the time so the input xml will not contain question number. I am getting the random question number(qnum) but being stuck on how to modify Question to 1 Question.Any idea ?

答:
I think this code might help you with your problem. Just adjust your 'random number' you want to have. At least this should give you the output you described.</p>

```<code><xsl:template match="presentation">
    <div class="question">
        <xsl:apply-templates/>
    </div>
</xsl:template>

<xsl:template match="b">
    <xsl:value-of select="count(preceding::b) + 1"/>
    <xsl:text> </xsl:text>
    <xsl:value-of select="."/>
</xsl:template>

<xsl:template match="br">
    <xsl:copy/>
</xsl:template>
</code>```

Body:
<presentation>
   <rootText>
    <firstChild>
     Question

Sub Question

    </firstChild>
   </rootText>
   ...
</presentation>

Here is the xsl

    <xsl:template match="presentation">

         <xsl:apply-templates select="rootText"/>

  </xsl:template>

I want the output as below

'

     1  Question

Sub Question

`

I have to modify Question to 1 Question. The questions will not be ordered all the time so the input xml will not contain question number. I am getting the random question number(qnum) but being stuck on how to modify Question to 1 Question.Any idea ?

Body:
I think this code might help you with your problem. Just adjust your 'random number' you want to have. At least this should give you the output you described.

<xsl:template match="presentation">
    <div class="question">
        <xsl:apply-templates/>
    </div>
</xsl:template>

<xsl:template match="b">
    <xsl:value-of select="count(preceding::b) + 1"/>
    <xsl:text> </xsl:text>
    <xsl:value-of select="."/>
</xsl:template>

<xsl:template match="br">
    <xsl:copy/>
</xsl:template>


问:
c# linq to xml
I have an xml string that I wish to traverse using LINQ to XML (I have never used this, so wish to learn).  However when I try to use

```<code>XDocument xDoc = XDocument.Load(adminUsersXML);
        var users = from result in xDoc.Descendants("Result")
                    select new
                    {
                        test = result.Element("USER_ID").Value
                    };
</code>```

I get an error message saying illegal characters in path.  reading up on it, it's because I cannot pass a standard string in this way.  Is there a way to use XML LINQ qith a standard string?

Thanks.

答: As said in MSDN, you must use the Parse function to create a XDocument from a string.

Title: c# linq to xml

Body:
I have an xml string that I wish to traverse using LINQ to XML (I have never used this, so wish to learn).  However when I try to use

XDocument xDoc = XDocument.Load(adminUsersXML);
        var users = from result in xDoc.Descendants("Result")
                    select new
                    {
                        test = result.Element("USER_ID").Value
                    };

I get an error message saying illegal characters in path.  reading up on it, it's because I cannot pass a standard string in this way.  Is there a way to use XML LINQ qith a standard string?

Thanks.


问:
yii2 - How to make checkbox visible with conditional logic
I need help to make my checkbox visible if the status is 3.

Here my view code :

```<code>//Checkbox
            [
              'class' => 'yii\grid\CheckboxColumn',
              'contentOptions'=>['style'=>'width: 50px'],
              'checkboxOptions'=> function($model, $key, $index, $column) {
                return ["value" => $model->ACCOUNT_ID];
              },
              'visible' => $model->STATUS_INSTALLMENT == 3
            ],
</code>```

I run that code and it cause my checkbox disappear.

答:
```<code>['class' => '\yii\grid\CheckboxColumn',
   'checkboxOptions' => function ($model, $key, $index, $column) {
        if ($model->STATUS_INSTALLMENT == 3) {
            return ['value' => $key];
        }
        return ['style' => ['display' => 'none']]; // OR ['disabled' => true]
    },
],
</code>```

Body:
I need help to make my checkbox visible if the status is 3.

Here my view code :

//Checkbox
            [
              'class' => 'yii\grid\CheckboxColumn',
              'contentOptions'=>['style'=>'width: 50px'],
              'checkboxOptions'=> function($model, $key, $index, $column) {
                return ["value" => $model->ACCOUNT_ID];
              },
              'visible' => $model->STATUS_INSTALLMENT == 3
            ],

I run that code and it cause my checkbox disappear.


问:
Embed posting of social networks with Ionic Framework and AngularJS
I am having a problem when wanting to embed a post from Twitter, Instagram or Vine with Ionic Framework, all social networks using Blockquote to display the content, look bad, do not show all the elements nor display the correct styles...

This is the code in Twitter:

```<code><blockquote class="twitter-tweet" lang="en"><p>Web designers life by <a href="https://twitter.com/Monish_bansal">@Monish_bansal</a> CC <a href="https://twitter.com/CsharpCorner">@CsharpCorner</a> <a href="https://twitter.com/hashtag/webdeveloper?src=hash">#webdeveloper</a> <a href="https://twitter.com/hashtag/webdevelopment?src=hash">#webdevelopment</a> <a href="https://twitter.com/hashtag/developers?src=hash">#developers</a> <a href="https://twitter.com/hashtag/programmers?src=hash">#programmers</a> <a href="http://t.co/inTkoRpJ0k">pic.twitter.com/inTkoRpJ0k</a></p>— C# Corner (@CsharpCorner) <a href="https://twitter.com/CsharpCorner/status/560759820731445249">January 29, 2015</a></blockquote>
</code>```

This is in Vine:

```<code><iframe src="https://vine.co/v/bjHh0zHdgZT/embed/postcard" width="300" height="300" frameborder="0"></iframe><script src="https://platform.vine.co/static/scripts/embed.js"></script>
</code>```

And this is in Instagram:

```<code><blockquote class="instagram-media" data-instgrm-captioned data-instgrm-version="4" style=" background:#FFF; border:0; border-radius:3px; box-shadow:0 0 1px 0 rgba(0,0,0,0.5),0 1px 10px 0 rgba(0,0,0,0.15); margin: 1px; max-width:658px; padding:0; width:99.375%; width:-webkit-calc(100% - 2px); width:calc(100% - 2px);"><div style="padding:8px;"> <div style=" background:#F8F8F8; line-height:0; margin-top:40px; padding:50% 0; text-align:center; width:100%;"> <div style=" background:url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACwAAAAsCAMAAAApWqozAAAAGFBMVEUiIiI9PT0eHh4gIB4hIBkcHBwcHBwcHBydr+JQAAAACHRSTlMABA4YHyQsM5jtaMwAAADfSURBVDjL7ZVBEgMhCAQBAf//42xcNbpAqakcM0ftUmFAAIBE81IqBJdS3lS6zs3bIpB9WED3YYXFPmHRfT8sgyrCP1x8uEUxLMzNWElFOYCV6mHWWwMzdPEKHlhLw7NWJqkHc4uIZphavDzA2JPzUDsBZziNae2S6owH8xPmX8G7zzgKEOPUoYHvGz1TBCxMkd3kwNVbU0gKHkx+iZILf77IofhrY1nYFnB/lQPb79drWOyJVa/DAvg9B/rLB4cC+Nqgdz/TvBbBnr6GBReqn/nRmDgaQEej7WhonozjF+Y2I/fZou/qAAAAAElFTkSuQmCC); display:block; height:44px; margin:0 auto -44px; position:relative; top:-22px; width:44px;"></div></div> <p style=" margin:8px 0 0 0; padding:0 4px;"> <a href="https://instagram.com/p/0YwbCVpsq_/" style=" color:#000; font-family:Arial,sans-serif; font-size:14px; font-style:normal; font-weight:normal; line-height:17px; text-decoration:none; word-wrap:break-word;" target="_top">Tarde de proyectorista #cine #ushuaia #packewaia #proyector</a></p> <p style=" color:#c9c8cd; font-family:Arial,sans-serif; font-size:14px; line-height:17px; margin-bottom:0; margin-top:8px; overflow:hidden; padding:8px 0 7px; text-align:center; text-overflow:ellipsis; white-space:nowrap;">A photo posted by @gabfiocchi on <time style=" font-family:Arial,sans-serif; font-size:14px; line-height:17px;" datetime="2015-03-18T23:04:25+00:00">Mar 18, 2015 at 4:04pm PDT</time></p></div></blockquote>
</code>```

答:
You need run code after DOM  onload:

window['twttr'].widgets.load(); - for twitter

window['instgrm'].Embeds.process({hidecaption:false}); - insta

if it is cordova app then should add "http://" to src in index.html

```<code><script async defer src="http://platform.instagram.com/en_US/embeds.js"></script>
<script async defer src="http://platform.twitter.com/widgets.js"></script>
</code>```

Body:
I am having a problem when wanting to embed a post from Twitter, Instagram or Vine with Ionic Framework, all social networks using Blockquote to display the content, look bad, do not show all the elements nor display the correct styles...

This is the code in Twitter:

Web designers life by @Monish_bansal CC @CsharpCorner #webdeveloper #webdevelopment #developers #programmers pic.twitter.com/inTkoRpJ0k
— C# Corner (@CsharpCorner) January 29, 2015

This is in Vine:

And this is in Instagram:

 <div style=" background:url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACwAAAAsCAMAAAApWqozAAAAGFBMVEUiIiI9PT0eHh4gIB4hIBkcHBwcHBwcHBydr+JQAAAACHRSTlMABA4YHyQsM5jtaMwAAADfSURBVDjL7ZVBEgMhCAQBAf//42xcNbpAqakcM0ftUmFAAIBE81IqBJdS3lS6zs3bIpB9WED3YYXFPmHRfT8sgyrCP1x8uEUxLMzNWElFOYCV6mHWWwMzdPEKHlhLw7NWJqkHc4uIZphavDzA2JPzUDsBZziNae2S6owH8xPmX8G7zzgKEOPUoYHvGz1TBCxMkd3kwNVbU0gKHkx+iZILf77IofhrY1nYFnB/lQPb79drWOyJVa/DAvg9B/rLB4cC+Nqgdz/TvBbBnr6GBReqn/nRmDgaQEej7WhonozjF+Y2I/fZou/qAAAAAElFTkSuQmCC); display:block; height:44px; margin:0 auto -44px; position:relative; top:-22px; width:44px;">

 Tarde de proyectorista #cine #ushuaia #packewaia #proyector

A photo posted by @gabfiocchi on <time style=" font-family:Arial,sans-serif; font-size:14px; line-height:17px;" datetime="2015-03-18T23:04:25+00:00">Mar 18, 2015 at 4:04pm PDT</time>

Body:
You need run code after DOM  onload:

window['twttr'].widgets.load(); - for twitter

window['instgrm'].Embeds.process({hidecaption:false}); - insta

if it is cordova app then should add "http://" to src in index.html

<script async defer src="http://platform.instagram.com/en_US/embeds.js"></script>
<script async defer src="http://platform.twitter.com/widgets.js"></script>


问:
generalized ordered logit in R or python
I would like to fit a generalized ordered logit model to some data I have. I first tried to use the ordered logit model using the MASS package from R, but it seems that the proportional odds assumption is violated by the data. Indeed, not all independent variables do exert the same effect across all categories of the dependent variable. Hence I am a bit blocked. I say that I could use the generalized ordered logit model instead, but could not find how to use it. Indeed, I can not find any package on either R or python that coud help me on that.

If someone has any hints on packages I could use, it would be of great help!

Thank you very much!

答:
Try the oglmx package. In this link there is the vignette for that package.

For those who are interested in the method itself, here is some talk about that.


问:
How does kernel choose IP address if INADDR_ANY is used for joining a mcast group?
I am curious how kernel chooses the interface to join a mcast group when INADDR_ANY is used:

```<code>struct ip_mreq req;
req.imr_multiaddr.s_addr = inet_addr(someMcastIP);
req.imr_interface.s_addr = htonl(INADDR_ANY);

if ((setsockopt(sock, IPPROTO_IP, IP_ADD_MEMBERSHIP, (void*) &req, sizeof(req))) < 0) {
 ...
}
</code>```

Let's say there are few interfaces on the machine.  How does the kernel choose?

答: It uses the static IP routing tables to determine where the membership request is sent.</p>

Body:
I am curious how kernel chooses the interface to join a mcast group when INADDR_ANY is used:

struct ip_mreq req;
req.imr_multiaddr.s_addr = inet_addr(someMcastIP);
req.imr_interface.s_addr = htonl(INADDR_ANY);

if ((setsockopt(sock, IPPROTO_IP, IP_ADD_MEMBERSHIP, (void*) &req, sizeof(req))) < 0) {
 ...
}

Let's say there are few interfaces on the machine.  How does the kernel choose?


问:
Object class toString() combined with Widening
My code is below, i have three output and in three toString() method of Object class is called which gives output in form of class@hashcodeinhexadecimal form then why in output 1 in which autoboxing and widening happens internally the value of object get print ?</p>

```<code>public class AutoBoxingUn
{

    static Object pp= new Object ();

    public static void main(String[] args)
    {

        int q = 10;
        Object o=q;
        System.out.println("O"+"..."+o.toString());     \\ O...10    ( output 1 )

        System.out.println(pp.toString());          \\ java.lang.Object@ee7d9f1 ( output 2 )

        A aa= new A(11);
        System.out.println(aa);                 \\ A@1edf1c96   ( output 3 )
    }

}

class A extends AutoBoxingUn
{   int o;
    A(int o)
    {
        this.o=o;
    }
    void m2()
    {}
}
</code>```

答: if you that toString() method of Objetc class should get called then change   Object o=q; to Object o = new Object(); in your code</p>

Body:
My code is below, i have three output and in three toString() method of Object class is called which gives output in form of class@hashcodeinhexadecimal form then why in output 1 in which autoboxing and widening happens internally the value of object get print ?

public class AutoBoxingUn
{

    static Object pp= new Object ();

    public static void main(String[] args)
    {

        int q = 10;
        Object o=q;
        System.out.println("O"+"..."+o.toString());     \\ O...10    ( output 1 )

        System.out.println(pp.toString());          \\ java.lang.Object@ee7d9f1 ( output 2 )

        A aa= new A(11);
        System.out.println(aa);                 \\ A@1edf1c96   ( output 3 )
    }

}

class A extends AutoBoxingUn
{   int o;
    A(int o)
    {
        this.o=o;
    }
    void m2()
    {}
}


问:
How do I limit the number of rows in a datatable?
I generate a DataTable (from non-SQL data) and then use a DataView to filter the records.

I want to limit the number of records in the final record set but can't do this when I generate the DataTable.

I've resorted to deleting rows from the final result set, as per:

```<code>                DataView dataView = new DataView(dataTable);
                dataView.RowFilter = String.Format("EventDate > '{0}'", DateTime.Now);
                dataView.Sort = "EventDate";
                dataTable = dataView.ToTable();

                 while (dataTable.Rows.Count > _rowLimit)
                    dataTable.Rows[dataTable.Rows.Count - 1].Delete();

                 return dataTable;
</code>```

Is there a more efficient way to limit the results?

答:
Can you add a column which will be similar like rowcount 1,2,3
Something like incrementing as you add rows from your Non-SQL data to the datatable.
Probably after that you can use

```<code>DataRow[] rows1 = dTable.Select(" RowIncrement < 50", "EventDate ASC");
</code>```

RowIncrement is the column which would be something like ROWNUM

Body:
I generate a DataTable (from non-SQL data) and then use a DataView to filter the records.

I want to limit the number of records in the final record set but can't do this when I generate the DataTable.

I've resorted to deleting rows from the final result set, as per:

                DataView dataView = new DataView(dataTable);
                dataView.RowFilter = String.Format("EventDate > '{0}'", DateTime.Now);
                dataView.Sort = "EventDate";
                dataTable = dataView.ToTable();

                 while (dataTable.Rows.Count > _rowLimit)
                    dataTable.Rows[dataTable.Rows.Count - 1].Delete();

                 return dataTable;

Is there a more efficient way to limit the results?

Body:
Can you add a column which will be similar like rowcount 1,2,3
Something like incrementing as you add rows from your Non-SQL data to the datatable.
Probably after that you can use

DataRow[] rows1 = dTable.Select(" RowIncrement < 50", "EventDate ASC");

RowIncrement is the column which would be something like ROWNUM


问:
Winforms C# - Legacy Project Visual .NET 2003: Custom Extender Provider not shown in Toolbox
I have created a custom Extender Provider to apply to all my labels: a class that inherits from Component and implements IExtenderProvider.

It compiles correctly without errors. Then I go to Toolbox but it is not shown.

I have restarted VS and it does not work.
Also I have created this extender provider class within another separate assembly, compile it and then added a reference to the other assembly where I want to use it as explained here but without success, it says:

the class needs to be packaged into a separate assembly from the
  assembly using it.

Any ideas what's going on?

答:
Finally I have solved by following below steps:

In a separate assembly (not the same where you are using it), a class library project, create a class and implement your extender provider there. Make this class to inherit from System.ComponentModel.Component and implement IExtenderProvider.

Once implemented, compile it. You will obtain your dll.

Add a reference in the assembly where you are using it that points to the class library which contains your extender provider.

To make visible your extender provider in the Toolbox, do right button mouse click and in context menu select "Add/Remove Items...", Customize Toolbox dialog window will be shown.

In Customize Toolbox dialog window you will see two tabs ".Net Framework Components" and "COM Components". In ".Net Framework Components" click on browse button and navigate to the place where your dll (class library containing your extender provider) is and select it.

After that, you will see immediately your extender provider appears listed on ".Net Framework Components", select it and ensure it is checked, and click on 'OK' button. That's all, now your extender provider will be shown in toolbox under "Components" group.

Now, open a winform (in design view) from your assembly on which you want to insert your extender provider and drag and drop your extender provider to the form.

Select an object of your form, one that your extender provider is created for, and go to its properties, there you will see the new properties implemented in your extender provider for that component. If you did not specify a category attribute in your extender provider property, it will be shown under "Misc" category in the properties window.

That's all.

It seems like in older versions of Visual Studio, like Visual .NET 2003, extender providers are not automatically added to the toolbox and you must do manually. In newer versions of Visual Studio such as 2015 (I have tested), it is automatically done for you.


问:
Where Does LAB.js Keep Coming From In Safari?
I keep seeing an error in the JS console in safari, it seems to happen all over the place and not just on code i am writing. At the moment i see it on some code i have been writing but i never have included LAB.js in the code, so where is it coming from? Why is it showing the following error in the console if i have never even tried to use it?

```<code>TypeError: null is not an object (evaluating '/^[^?#]*\//.exec(location.href)[0]')
</code>```

Screenshot:

答: It's probably caused by an extension. Disable extensions one by one to see which one is causing the problem.

Body:
I keep seeing an error in the JS console in safari, it seems to happen all over the place and not just on code i am writing. At the moment i see it on some code i have been writing but i never have included LAB.js in the code, so where is it coming from? Why is it showing the following error in the console if i have never even tried to use it?

TypeError: null is not an object (evaluating '/^[^?#]*\//.exec(location.href)[0]')

Screenshot:


问:
Failed To Load Template Issue
Using AngularJS-1.6.5 & Angular-ui-router-1.0.6 && Gulp-3.9.1

I'm having this absolutely annoying issue.  I have an angular app that seems to build fine but when I run gulp-connect to run it, I keep getting failed to load template errors in this order:

vendor.js:14803 Error: [$compile:tpload] Failed to load template: app/auth/views/login.tpl.html (HTTP status: undefined undefined)

vendor.js:34081 Transition Rejection($id: 0 type: 6, message: The transition errored, detail: Error: [$compile:tpload] Failed to load template: app/auth/views/login.tpl.html (HTTP status: undefined undefined)

Error: [$compile:tpload] Failed to load template: app/auth/views/login.tpl.html (HTTP status: undefined undefined)

If I run my gulp build process and then use something like httpster to provide the server, the page comes up fine with no error.  However, when I add gulp-connect to my build process:

```<code>gulp.task("connect",["css", "vendor", "js", "watch", "webWorkers"], function
 () {
 connect.server({
port: 8888
});
});
</code>```

I get the errors above.

This was working just a day ago and for whatever reason, even previous versions that worked are no longer working either.  I've tried redirecting to another template, verified that all entries are in template cache, tried retrieving a  file that was on network instead of the template cache, uninstall/reinstalling gulp-connect and nothing has worked.  I'm just completely stumped at this point and need to figure something out soon for the sake of my sanity.

Any thoughts would be greatly appreciated.

答:
In my case, it it was a missed return config; statement when I add an interceptor to my app.

```<code>app.factory('loadingInterceptor', [
'$rootScope',
function ($rootScope)
{

    return {
        request: function (config)
        {
            var loadingEl = $(".loading-element");
            if (loadingEl)
            {
                showLoading(loadingEl, true);
            }
            // return config;
        },
        response: function (response)
        {
            var loadingEl = $(".loading-element");
            if (loadingEl) {
                showLoading(loadingEl, false);
            }
        }
    };
}
</code>```

]);

hope this will help someone.

Title: Failed To Load Template Issue

Body:
Using AngularJS-1.6.5 & Angular-ui-router-1.0.6 && Gulp-3.9.1

I'm having this absolutely annoying issue.  I have an angular app that seems to build fine but when I run gulp-connect to run it, I keep getting failed to load template errors in this order:

vendor.js:14803 Error: [$compile:tpload] Failed to load template: app/auth/views/login.tpl.html (HTTP status: undefined undefined)

vendor.js:34081 Transition Rejection($id: 0 type: 6, message: The transition errored, detail: Error: [$compile:tpload] Failed to load template: app/auth/views/login.tpl.html (HTTP status: undefined undefined)

Error: [$compile:tpload] Failed to load template: app/auth/views/login.tpl.html (HTTP status: undefined undefined)

If I run my gulp build process and then use something like httpster to provide the server, the page comes up fine with no error.  However, when I add gulp-connect to my build process:

gulp.task("connect",["css", "vendor", "js", "watch", "webWorkers"], function
 () {
 connect.server({
port: 8888
});
});

I get the errors above.

This was working just a day ago and for whatever reason, even previous versions that worked are no longer working either.  I've tried redirecting to another template, verified that all entries are in template cache, tried retrieving a  file that was on network instead of the template cache, uninstall/reinstalling gulp-connect and nothing has worked.  I'm just completely stumped at this point and need to figure something out soon for the sake of my sanity.

Any thoughts would be greatly appreciated.

Body:
In my case, it it was a missed return config; statement when I add an interceptor to my app.

app.factory('loadingInterceptor', [
'$rootScope',
function ($rootScope)
{

    return {
        request: function (config)
        {
            var loadingEl = $(".loading-element");
            if (loadingEl)
            {
                showLoading(loadingEl, true);
            }
            // return config;
        },
        response: function (response)
        {
            var loadingEl = $(".loading-element");
            if (loadingEl) {
                showLoading(loadingEl, false);
            }
        }
    };
}

]);

hope this will help someone.


问:
Using Elasticsearch Java REST API with self signed certificates
I want to use the Java REST API (RestHighLevelClient) to communicate with an Elasticsearch 5.6 server over HTTPS. However, the certificate for the server is self signed and when I try to connect it throws a SSLHandshakeException.

Is there a way of configuring the REST client to accept self signed certificates?

答:
I got this working using a custom Java Key Store. Here's my code:

```<code>CredentialsProvider credentialsProvider = new BasicCredentialsProvider(); credentialsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(username, password));

final SSLContext sslContext = SSLContexts.custom()
        .loadTrustMaterial(new File("my_keystore.jks"), keystorePassword.toCharArray(),
            new TrustSelfSignedStrategy())
        .build();

RestClient client = RestClient.builder(new HttpHost(host, port, scheme)).setHttpClientConfigCallback(httpClientBuilder -> httpClientBuilder
        .setDefaultCredentialsProvider(credentialsProvider)
        .setSSLContext(sslContext)
).build();
</code>```

To create the keystore, I downloaded the cert for the domain through Firefox, and used:

```<code>keytool -import -v -trustcacerts -file my_domain.crt -keystore my_keystore.jks -keypass password -storepass password
</code>```

Body:
I got this working using a custom Java Key Store. Here's my code:

CredentialsProvider credentialsProvider = new BasicCredentialsProvider(); credentialsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(username, password));

final SSLContext sslContext = SSLContexts.custom()
        .loadTrustMaterial(new File("my_keystore.jks"), keystorePassword.toCharArray(),
            new TrustSelfSignedStrategy())
        .build();

RestClient client = RestClient.builder(new HttpHost(host, port, scheme)).setHttpClientConfigCallback(httpClientBuilder -> httpClientBuilder
        .setDefaultCredentialsProvider(credentialsProvider)
        .setSSLContext(sslContext)
).build();

To create the keystore, I downloaded the cert for the domain through Firefox, and used:

keytool -import -v -trustcacerts -file my_domain.crt -keystore my_keystore.jks -keypass password -storepass password


问:
wso2 api manager throws exception Error in invoking validate key via thrift
I see this intermittent exception in my log file on unix server. My wso2 api manager is a standalone installation of 1.10.0. please help me understand this exception.

Stack trace below:

```<code>TID: [-1234] [] [2017-11-16 08:19:40,350]  INFO {org.apache.synapse.mediators.builtin.LogMediator} -  STATUS = Message dispat
ched to the main sequence. Invalid URL., RESOURCE = / {org.apache.synapse.mediators.builtin.LogMediator}
TID: [-1234] [] [2017-11-16 08:21:29,962]  INFO {org.apache.synapse.mediators.builtin.LogMediator} -  STATUS = Message dispat
ched to the main sequence. Invalid URL., RESOURCE = / {org.apache.synapse.mediators.builtin.LogMediator}
TID: [-1234] [] [2017-11-16 08:33:48,425]  WARN {org.wso2.carbon.apimgt.keymgt.service.thrift.APIKeyValidationServiceImpl} -
 Invalid session id for thrift authenticator. {org.wso2.carbon.apimgt.keymgt.service.thrift.APIKeyValidationServiceImpl}
TID: [-1234] [] [2017-11-16 08:33:48,425] ERROR {org.wso2.carbon.apimgt.keymgt.service.thrift.APIKeyValidationServiceImpl} -  Error in invoking validate key via thrift.. {org.wso2.carbon.apimgt.keymgt.service.thrift.APIKeyValidationServiceImpl}
TID: [-1234] [] [2017-11-16 08:33:48,426]  WARN {org.wso2.carbon.apimgt.gateway.handlers.security.thrift.ThriftKeyValidatorClientPool} -  Login failed.. Authenticating again.. {org.wso2.carbon.apimgt.gateway.handlers.security.thrift.ThriftKeyValidatorClientPool}
TID: [-1234] [] [2017-11-16 08:33:48,437]  INFO {org.wso2.carbon.core.services.util.CarbonAuthenticationUtil} -  'admin@carbon.super [-1234]' logged in at [2017-11-16 08:33:48,437-0500] from IP address  {org.wso2.carbon.core.services.util.CarbonAuthenticationUtil}
TID: [-1] [] [2017-11-16 08:33:48,476]  INFO {org.wso2.carbon.databridge.agent.thrift.internal.publisher.client.EventPublisher} -  Session timed out for TCP,localhost:7614,TCP,localhost:7714,Thrift Session Expired Exception  {org.wso2.carbon.databridge.agent.thrift.internal.publisher.client.EventPublisher}
</code>```

答:
From your above logs, I can see following error log related to thrift

```<code>TID: [-1234] [] [2017-11-16 08:33:48,425] ERROR {org.wso2.carbon.apimgt.keymgt.service.thrift.APIKeyValidationServiceImpl} -  Error in invoking validate key via thrift.. {org.wso2.carbon.apimgt.keymgt.service.thrift.APIKeyValidationServiceImpl}
</code>```

I don't really see a reason for above, but Can you please change to WSClient from ThriftClient. This configuration resides on api-manager.xml file.

There could be a connection issue related to thrift in your node.

Body:
I see this intermittent exception in my log file on unix server. My wso2 api manager is a standalone installation of 1.10.0. please help me understand this exception.

Stack trace below:

TID: [-1234] [] [2017-11-16 08:19:40,350]  INFO {org.apache.synapse.mediators.builtin.LogMediator} -  STATUS = Message dispat
ched to the main sequence. Invalid URL., RESOURCE = / {org.apache.synapse.mediators.builtin.LogMediator}
TID: [-1234] [] [2017-11-16 08:21:29,962]  INFO {org.apache.synapse.mediators.builtin.LogMediator} -  STATUS = Message dispat
ched to the main sequence. Invalid URL., RESOURCE = / {org.apache.synapse.mediators.builtin.LogMediator}
TID: [-1234] [] [2017-11-16 08:33:48,425]  WARN {org.wso2.carbon.apimgt.keymgt.service.thrift.APIKeyValidationServiceImpl} -
 Invalid session id for thrift authenticator. {org.wso2.carbon.apimgt.keymgt.service.thrift.APIKeyValidationServiceImpl}
TID: [-1234] [] [2017-11-16 08:33:48,425] ERROR {org.wso2.carbon.apimgt.keymgt.service.thrift.APIKeyValidationServiceImpl} -  Error in invoking validate key via thrift.. {org.wso2.carbon.apimgt.keymgt.service.thrift.APIKeyValidationServiceImpl}
TID: [-1234] [] [2017-11-16 08:33:48,426]  WARN {org.wso2.carbon.apimgt.gateway.handlers.security.thrift.ThriftKeyValidatorClientPool} -  Login failed.. Authenticating again.. {org.wso2.carbon.apimgt.gateway.handlers.security.thrift.ThriftKeyValidatorClientPool}
TID: [-1234] [] [2017-11-16 08:33:48,437]  INFO {org.wso2.carbon.core.services.util.CarbonAuthenticationUtil} -  'admin@carbon.super [-1234]' logged in at [2017-11-16 08:33:48,437-0500] from IP address  {org.wso2.carbon.core.services.util.CarbonAuthenticationUtil}
TID: [-1] [] [2017-11-16 08:33:48,476]  INFO {org.wso2.carbon.databridge.agent.thrift.internal.publisher.client.EventPublisher} -  Session timed out for TCP,localhost:7614,TCP,localhost:7714,Thrift Session Expired Exception  {org.wso2.carbon.databridge.agent.thrift.internal.publisher.client.EventPublisher}

Body:
From your above logs, I can see following error log related to thrift

TID: [-1234] [] [2017-11-16 08:33:48,425] ERROR {org.wso2.carbon.apimgt.keymgt.service.thrift.APIKeyValidationServiceImpl} -  Error in invoking validate key via thrift.. {org.wso2.carbon.apimgt.keymgt.service.thrift.APIKeyValidationServiceImpl}

I don't really see a reason for above, but Can you please change to WSClient from ThriftClient. This configuration resides on api-manager.xml file.

There could be a connection issue related to thrift in your node.


问:
How will JDK9 modules help for 'package-scoped sub-packages'?
I am wondering about JDK9 modules. Say you have the following 3 packages:

```<code>com.company.product
com.company.product.impl_a
com.company.product.impl_b
</code>```

Classes in package product.impl_a and product.impl_b can only be accessed by classes in package product. The user should only use classes from product package. You can imagine that passing certain flags or properties will decide whether impl_a or impl_b will be used, internally.

In JDK8-, you have to make these classes inside impl_a and impl_b public. This kinda sucks, because users can be tricked that they can use these classes. It's perfectly valid and allowed.

How can JDK9 help here? Will we declare a module for product.impl_a and another one for product.impl_b and declare that the exported classes are only to be accessed by a third module product, which will depend on the two modules product.impl_a and product.impl_b? In addition, it will be effectively impossible to declare a new module which will depend on product.impl_a or product.impl_b? Can other modules only depend on module product?

答:
You can let the classes within the packages impl_a and impl_b be public and to export packages to specific modules (qualified exports) further you can use the convention as :

```<code>exports com.company.product.impl_b to third.module;
</code>```

So, in your case consider these

```<code>module first.module {
    export com.company.product.impl_a to second.module;
    export com.company.product.impl_b to third.module;
}
</code>```

which means that the package com.company.product.impl_a is only exported to the second.module which now when reads first.module has access to the public types of the classes within impl_a package and similarly com.company.product.impl_b is only exported to third.module.

Body:
I am wondering about JDK9 modules. Say you have the following 3 packages:

com.company.product
com.company.product.impl_a
com.company.product.impl_b

Classes in package product.impl_a and product.impl_b can only be accessed by classes in package product. The user should only use classes from product package. You can imagine that passing certain flags or properties will decide whether impl_a or impl_b will be used, internally.

In JDK8-, you have to make these classes inside impl_a and impl_b public. This kinda sucks, because users can be tricked that they can use these classes. It's perfectly valid and allowed.

How can JDK9 help here? Will we declare a module for product.impl_a and another one for product.impl_b and declare that the exported classes are only to be accessed by a third module product, which will depend on the two modules product.impl_a and product.impl_b? In addition, it will be effectively impossible to declare a new module which will depend on product.impl_a or product.impl_b? Can other modules only depend on module product?

Body:
You can let the classes within the packages impl_a and impl_b be public and to export packages to specific modules (qualified exports) further you can use the convention as :

exports com.company.product.impl_b to third.module;

So, in your case consider these

module first.module {
    export com.company.product.impl_a to second.module;
    export com.company.product.impl_b to third.module;
}

which means that the package com.company.product.impl_a is only exported to the second.module which now when reads first.module has access to the public types of the classes within impl_a package and similarly com.company.product.impl_b is only exported to third.module.


问:
How to Save an HTML page layout into PDF
I am using core PHP having version 5.1.6 in procedural style

How can i save an HTML page into PDF containing exact layout information?

The major with me at currently that, whenever i am trying to save a_pahe.html to pdf by clicking "Save as PDF" link/button, it saves the HTML page but have lost all the layouts that i have needed.

My exact layout of an HTML page is

And the Generated PDF output is as like this

答:
Try using css media queries

```<code>@media print {
   /* styles go here */
}
</code>```

You can also do it on the link tag with external css

```<code><link rel="stylesheet" type="text/css" href="print.css" media="print">
</code>```

Body:
Try using css media queries

@media print {
   /* styles go here */
}

You can also do it on the link tag with external css

<link rel="stylesheet" type="text/css" href="print.css" media="print">


问:
How to save and retrieve Array of Objects value from Dictionary in Swift iOS?
I am newly to Swift programming. I am developing an app where I have an array of Objects that I need to save it into one Dictionary, means for Dictionary 'Array of Objects' should be my Value and 'ID' should be my Key.

Here 2 elements contains in my Array, how can I save and retrieve from Dictionary using any unique Key. Please suggest me. Thank you!

答:
Saving
    var dictionary =  Int:String

```<code>dictionary.updateValue(value: self.arrangeVideoInfo[0]!, forKey: 1)
dictionary.updateValue(value: self.arrangeVideoInfo[0]!, forKey: 2)
</code>```

Getting

```<code>let value1 = dictionary[1] as! VideoRangeInfo
let value2 = dictionary[2] as! VideoRangeInfo
</code>```

Body:
Saving
    var dictionary =  Int:String

dictionary.updateValue(value: self.arrangeVideoInfo[0]!, forKey: 1)
dictionary.updateValue(value: self.arrangeVideoInfo[0]!, forKey: 2)

Getting

let value1 = dictionary[1] as! VideoRangeInfo
let value2 = dictionary[2] as! VideoRangeInfo