问:
How to refresh an ng-repeat list when $scope is not used?
$scope.$apply() is mostly used when $scope is defined.
But this kind of definition does not seem to refresh the list.

HTML :

```<code><div ng-repeat="feed in feedCtrl.feeds"></div>
</code>```

Controller :

```<code>this.feeds = response.data;
</code>```

答:
inject $scope in controller and use $scope.$apply() after retrieving data. No problem if you are using "this". ie

```<code>this.feeds = response.data;
$scope.$apply();
</code>```

However don't forget to inject $scope in controller

Body:
$scope.$apply() is mostly used when $scope is defined.
But this kind of definition does not seem to refresh the list.

HTML :

Controller :

this.feeds = response.data;

Body:
inject $scope in controller and use $scope.$apply() after retrieving data. No problem if you are using "this". ie

this.feeds = response.data;
$scope.$apply();

However don't forget to inject $scope in controller


来源: stackexchange

问:
Ionic : Image Cropping
I am new to ionic framework and cordova. I have learnt to use the camera plugin.
Now after getting the image, I want to crop a part of it. The cropping aspect ratio must not be static, i.e, the cropping box should be scalable ( in up, down, right, left directions).

I went through jeduan/cordova-plugin-crop but was not able to understand as it used Ionic v2, and I am working with ionic v1.

Please guide me to achieve this..

Is there any plugin to do so ?

答:
was not able to understand as it used Ionic v2

The main api for this plugin is provided for javascript. You are not have to manage it in angular way or a ngCordova module. Just use javascript syntax into your controller.

```<code>plugins.crop(function success () {

}, function fail () {

}, '/path/to/image', options)
</code>```

Note that you are included cordova.js in your index.html

ContentLicense: CC BY-SA 3.0

Title: Ionic : Image Cropping

Body:
was not able to understand as it used Ionic v2

The main api for this plugin is provided for javascript. You are not have to manage it in angular way or a ngCordova module. Just use javascript syntax into your controller.

plugins.crop(function success () {

}, function fail () {

}, '/path/to/image', options)

Note that you are included cordova.js in your index.html


问:
C: dup and close-on-exec
In a (German) book about C programming (Linux-UNIX-Programmierung, by Jürgen Wolf) I have found a statement, which translated to English would be as following (sentences numbered by me):

In some cases it can be necessary that you need to duplicate a file descriptor [1]. An example for this would be, if a parent process wants to exchange data with a child process and the child process is overlaid by a new process through the use of exec*() [2]. In such a case, without dup() or dup2(), the close-on-exec flag would be set [3]. When this flag is set, all file descriptors become invalid (since being overlaid by the new process) - that is, they are not present anymore [4]. The communication between the parent and child process would thus be stopped [5]. If on the other hand you duplicate the file descriptor with dup() or dup2(), then the close-on-exec flag is deleted, and the newly overlaid process can use this file descriptor to communicate [6].

I believe that the above paragraph contains several misleading statements or even errors.

In sentence [3], I do not understand why without the use of dup() or dup2() the close-on-exec flag would be set?

答:
The advice is wrong.  Close-on-exec is set only on file descriptors that your program has explicitly asked to be close-on-exec.

The reasons you may choose to use dup2 may be:

The process to be executed expects its I/O to be via particular file descriptors (usually 0, 1, and 2, corresponding to standard input, output and error streams respectively), or

the process will close some file descriptors, for whatever reason, and you need this fd to be outside the range to be closed.

The description is also slightly misleading - it's only the new descriptor (i.e. the return value from dup() or dup2()) which has close-on-exec unset.  The close-on-exec state of the original fd is unchanged.

Title: C: dup and close-on-exec


问:
How do I get basic jQuery tabs to work inside a .Net modal popup?
Really simple question: Am I missing something?  Seems like this should be all that is necessary for the basic setup...  currently I'm getting an un-stylized version (i.e. no tabs, just plain text/html).  So they don't look like tabs and when you click them nothing hides/shows as would be expected with tabs. Do I have to manually hook up javascript to show and hide the contents of the tabs or does the framework do this for me?

Update:

So I tested the code out and
  this works fine for basic tabs.
  However, I need to use this inside a
  .Net modal popup using their "Ajax"
  toolkit.  Essentially this is doing a
  postback which I've noticed tends to
  fight with jQuery.  In the past, I've
  used the jQuery live events, but
  I'm not sure what to bind it to...
  Usually you bind to an event on an
  object, like a click handler for a
  button.  Here, I need to attach the
  tab assignment/binding ( using .tabs()
  ) via a live event but I'm not sure
  which one.  I tried binding to the
  document load event but no luck with
  that:

```<code>$(document).live('load', bind_tabs);
</code>```

Any ideas?

Style sheet and Javascript links included on page:

```<code>https://ajax.googleapis.com/ajax/libs/jqueryui/1.8.6/themes/base/jquery-ui.css
https://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js
https://ajax.googleapis.com/ajax/libs/jqueryui/1.8.6/jquery-ui.min.js
</code>```

Added the following line to my stylesheet:

```<code>.ui-tabs .ui-tabs-hide { display: none; }
</code>```

Added the following script to the page:

```<code><script type="text/javascript">
  $(function () {
  $("#tabs2").tabs();
  $("#tabs").tabs();
  });
</script>
</code>```

HTML:

```<code><div id="tabs">
   <ul>
      <li><a href="#tabs-1">Nunc tincidunt</a></li>
      <li><a href="#tabs-2">Proin dolor</a></li>
      <li><a href="#tabs-3">Aenean lacinia</a></li>
   </ul>
   <div id="tabs-1">
      <p>Tab 1 content</p>
   </div>
   <div id="tabs-2">
      <p>Tab 2 content</p>
   </div>
   <div id="tabs-3">
      <p>Tab 3 content</p>
   </div>
</div>
</code>```

Also noticed on the "theming" documentation on the page (http://jqueryui.com/demos/tabs/#theming) that it states the following. Should I manually put in all those styles (like ui-widget) or rely on the framework to do it?

Sample markup with jQuery UI CSS
  Framework classes

```<code><div class="ui-tabs ui-widget ui-widget-content ui-corner-all" id="tabs">
   <ul class="ui-tabs-nav ui-helper-reset ui-helper-clearfix ui-widget-header ui-corner-all">
     <li class="ui-state-default ui-corner-top ui-tabs-selected ui-state-active"><a href="#tabs-1">Nunc tincidunt</a></li>
      <li class="ui-state-default ui-corner-top"><a href="#tabs-2">Proin dolor</a></li>
   <div class="ui-tabs-panel ui-widget-content ui-corner-bottom" id="tabs-1">
      <p>Tab one content goes here.</p>
   </div>
    ...
</div>
</code>```

Note: This is a sample of markup
  generated by the tabs plugin, not
  markup you should use to create a
  tabs. The only markup needed for that
  is

```<code><div id="tabs">
   <ul>
      <li><a href="#tabs-1">Nunc tincidunt</a></li>
      <li><a href="#tabs-2">Proin dolor</a></li>
      <li><a href="#tabs-3">Aenean lacinia</a></li>
   </ul>
   <div id="tabs-1">
      <p>Tab 1 content</p>
   </div>
   <div id="tabs-2">
      <p>Tab 2 content</p>
   </div>
   <div id="tabs-3">
      <p>Tab 3 content</p>
   </div>
</div>
</code>```

答:
Try placing your script files after your css files and try the code below

```<code>  $(document).ready(function () {
      $("#tabs").tabs();
  });
</code>```

Note i removed this line as i didnt see anything with this id in your code:

```<code>  $("#tabs2").tabs();
</code>```

ContentLicense: CC BY-SA 2.5

Body:
Really simple question: Am I missing something?  Seems like this should be all that is necessary for the basic setup...  currently I'm getting an un-stylized version (i.e. no tabs, just plain text/html).  So they don't look like tabs and when you click them nothing hides/shows as would be expected with tabs. Do I have to manually hook up javascript to show and hide the contents of the tabs or does the framework do this for me?

Update:

So I tested the code out and
  this works fine for basic tabs.
  However, I need to use this inside a
  .Net modal popup using their "Ajax"
  toolkit.  Essentially this is doing a
  postback which I've noticed tends to
  fight with jQuery.  In the past, I've
  used the jQuery live events, but
  I'm not sure what to bind it to...
  Usually you bind to an event on an
  object, like a click handler for a
  button.  Here, I need to attach the
  tab assignment/binding ( using .tabs()
  ) via a live event but I'm not sure
  which one.  I tried binding to the
  document load event but no luck with
  that:

$(document).live('load', bind_tabs);

Any ideas?

Style sheet and Javascript links included on page:

https://ajax.googleapis.com/ajax/libs/jqueryui/1.8.6/themes/base/jquery-ui.css
https://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js
https://ajax.googleapis.com/ajax/libs/jqueryui/1.8.6/jquery-ui.min.js

Added the following line to my stylesheet:

.ui-tabs .ui-tabs-hide { display: none; }

Added the following script to the page:

HTML:

Nunc tincidunt

Proin dolor

Aenean lacinia

Tab 1 content

Tab 2 content

Tab 3 content

Also noticed on the "theming" documentation on the page (http://jqueryui.com/demos/tabs/#theming) that it states the following. Should I manually put in all those styles (like ui-widget) or rely on the framework to do it?

Sample markup with jQuery UI CSS
  Framework classes

Nunc tincidunt

Proin dolor

Tab one content goes here.

    ...

Note: This is a sample of markup
  generated by the tabs plugin, not
  markup you should use to create a
  tabs. The only markup needed for that
  is

Nunc tincidunt

Proin dolor

Aenean lacinia

Tab 1 content

Tab 2 content

Tab 3 content

Body:
Try placing your script files after your css files and try the code below

  $(document).ready(function () {
      $("#tabs").tabs();
  });

Note i removed this line as i didnt see anything with this id in your code:

  $("#tabs2").tabs();


问:
Error Importing MySQL with JSON Data as column
I have an error while I am importing a db structure in MySQL

Error:

[ERROR in query 14] You have an error in your SQL syntax; check the
  manual that corresponds to your MariaDB server version for the right
  syntax to use near 'json DEFAULT NULL,   account_name char(255)
  DEFAULT NULL,   account_user_id ' at line 3 Import cancelled!

The whole exact SQL command is as follows:

CREATE TABLE ees_account (   account_business_id int(32) NOT NULL
  AUTO_INCREMENT,   data json DEFAULT NULL,   account_name char(255)
  DEFAULT NULL,   account_user_id int(32) DEFAULT '0',   created_at
  timestamp NULL DEFAULT NULL,   updated_at timestamp NULL DEFAULT
  NULL,   account_status int(32) DEFAULT '1',   account_description
  text,   account_website char(255) DEFAULT NULL,   account_address
  char(255) DEFAULT NULL,   account_email char(255) DEFAULT NULL,

  account_country_id int(32) DEFAULT NULL,   business_reference_id
  char(255) DEFAULT NULL,   account_client_logo text,

  client_reference_id char(255) DEFAULT NULL,   PRIMARY KEY
  (account_business_id) ) ENGINE=InnoDB AUTO_INCREMENT=45 DEFAULT
  CHARSET=utf8;

Any idea what could be the potential cause ? I check the MySQL version which is same i.e. 5.7.17

答:
Faced a similar issue few months back and the issues was MySQL version. MariaDB 10.2 supported JSON. (Alpha version. Not recommended by Maria to production server. Only testing.)MariaDB 10.1 do not support JSON.

So if you have WAMP or XAMPP dev stack then most probably you have 10.1.16-MariaDB which doesn't support JSON. So upgrade your MySQL and it will be resolved.


问:
Support MvpConstraintLayout
I try to support MvpConstraintLayout myself, just copy code from MvpLinearLayout

```<code>public abstract class MvpConstraintLayout<V extends MvpView, P extends MvpPresenter<V>>
        extends ConstraintLayout implements MvpView, ViewGroupDelegateCallback<V, P> {
    protected P presenter;
    protected ViewGroupMvpDelegate<V, P> mvpDelegate;

    public MvpConstraintLayout(Context context) {
        super(context);
    }

    public MvpConstraintLayout(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public MvpConstraintLayout(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    /**
     * Get the mvp delegate. This is internally used for creating presenter, attaching and detaching
     * view from presenter etc.
     *
     * <p><b>Please note that only one instance of mvp delegate should be used per android.view.View
     * instance</b>.
     * </p>
     *
     * <p>
     * Only override this method if you really know what you are doing.
     * </p>
     *
     * @return {@link ViewGroupMvpDelegate}
     */
    @NonNull
    protected ViewGroupMvpDelegate<V, P> getMvpDelegate() {
        if (mvpDelegate == null) {
            mvpDelegate = new ViewGroupMvpDelegateImpl<>(this, true);
        }

        return mvpDelegate;
    }

    @Override protected void onAttachedToWindow() {
        super.onAttachedToWindow();
        getMvpDelegate().onAttachedToWindow();
    }

    @Override protected void onDetachedFromWindow() {
        super.onDetachedFromWindow();
        getMvpDelegate().onDetachedFromWindow();
    }

    @SuppressLint("MissingSuperCall") @Override protected Parcelable onSaveInstanceState() {
        return getMvpDelegate().onSaveInstanceState();
    }

    @SuppressLint("MissingSuperCall") @Override
    protected void onRestoreInstanceState(Parcelable state) {
        getMvpDelegate().onRestoreInstanceState(state);
    }

    /**
     * Instantiate a presenter instance
     *
     * @return The {@link MvpPresenter} for this view
     */
    public abstract P createPresenter();

    @Override public P getPresenter() {
        return presenter;
    }

    @Override public void setPresenter(P presenter) {
        this.presenter = presenter;
    }

    @Override public V getMvpView() {
        return (V) this;
    }

    @Override public final Parcelable superOnSaveInstanceState() {
        return super.onSaveInstanceState();
    }

    @Override public final void superOnRestoreInstanceState(Parcelable state) {
        super.onRestoreInstanceState(state);
    }
}
</code>```

Then, use it in code

```<code>public class StatusBarLayout extends MvpConstraintLayout<StatusView, StatusPresenter>
        implements StatusView {

    public StatusBarLayout(Context context) {
        super(context);

        init();
    }

    public StatusBarLayout(Context context, AttributeSet attrs) {
        super(context, attrs);
        init();
    }

    public StatusBarLayout(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init();
    }

    @Override
    protected void onFinishInflate() {
        super.onFinishInflate();
        ButterKnife.bind(this, this);
    }

    @Override
    public StatusPresenter createPresenter() {
        return DaggerStatusBarLayoutComponent.builder().build().presenter();
    }

    private void init() {
        View.inflate(getContext(), R.layout.layout_status, this);
    }
}
</code>```

In preview, the IDE said

```<code>java.lang.IllegalStateException: Could not find the surrounding Activity
    at com.hannesdorfmann.mosby3.PresenterManager.getActivity(PresenterManager.java:231)
    at com.hannesdorfmann.mosby3.mvp.delegate.ViewGroupMvpDelegateImpl.<init>(ViewGroupMvpDelegateImpl.java:70)
    at com.skybornecn.ifdive.widgets.MvpConstraintLayout.getMvpDelegate(MvpConstraintLayout.java:55)
    at com.skybornecn.ifdive.widgets.MvpConstraintLayout.onAttachedToWindow(MvpConstraintLayout.java:63)
    at android.view.View.dispatchAttachedToWindow(View.java:15395)
    at android.view.ViewGroup.dispatchAttachedToWindow(ViewGroup.java:2953)
    at android.view.ViewGroup.dispatchAttachedToWindow(ViewGroup.java:2960)
    at android.view.ViewGroup.dispatchAttachedToWindow(ViewGroup.java:2960)
    at android.view.ViewGroup.dispatchAttachedToWindow(ViewGroup.java:2960)
    at android.view.AttachInfo_Accessor.setAttachInfo(AttachInfo_Accessor.java:42)
    at com.android.layoutlib.bridge.impl.RenderSessionImpl.inflate(RenderSessionImpl.java:333)
    at com.android.layoutlib.bridge.Bridge.createSession(Bridge.java:429)
    at com.android.ide.common.rendering.LayoutLibrary.createSession(LayoutLibrary.java:368)
    at com.android.tools.idea.rendering.RenderTask$2.compute(RenderTask.java:567)
    at com.android.tools.idea.rendering.RenderTask$2.compute(RenderTask.java:549)
    at com.intellij.openapi.application.impl.ApplicationImpl.runReadAction(ApplicationImpl.java:863)
    at com.android.tools.idea.rendering.RenderTask.createRenderSession(RenderTask.java:549)
    at com.android.tools.idea.rendering.RenderTask.lambda$inflate$1(RenderTask.java:680)
    at java.util.concurrent.FutureTask.run(FutureTask.java:266)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
    at java.lang.Thread.run(Thread.java:745)
</code>```

I have read the mosby PresenterManager, but still not know why. In addition, install to phone, the layout displayed just ok.

答:
UPDATE:
This is fixed in Mosby 3.0.1.

This is just a android tooling issue with Mosby.
The android layout editor actually instantiates a Instance of MvpConstraintLayout to preview it in Android Studio. However, Android Studio doesn't do that by attaching a View like MvpContraintLayout to a real Activity, but internally uses some mocked "context" alike thing. Mosby's PresenterManager internally tries to find an Activity for your MvpConstraintLayout, but in Android Studio there is no real Activity used (as already explained) and therefore the UI editor displays this error message and when installed on the phone it works properly (because there is a real Activity used).

To fix that you have to use view.isInEditMode() before calling the delegate like this:

```<code>public abstract class MvpConstraintLayout<V extends MvpView, P extends MvpPresenter<V>>
        extends ConstraintLayout implements MvpView, ViewGroupDelegateCallback<V, P> {
    ...

    @Override protected void onAttachedToWindow() {
        super.onAttachedToWindow();
        if (!isInEditMode()) getMvpDelegate().onAttachedToWindow();
    }

    @Override protected void onDetachedFromWindow() {
        super.onDetachedFromWindow();
        if (!isInEditMode()) getMvpDelegate().onDetachedFromWindow();
    }

    @SuppressLint("MissingSuperCall") @Override protected Parcelable onSaveInstanceState() {
       if (!isInEditMode()) return getMvpDelegate().onSaveInstanceState();
       return super.onSaveInstanceState();
    }

    @SuppressLint("MissingSuperCall") @Override
    protected void onRestoreInstanceState(Parcelable state) {
        if (!isInEditMode()) getMvpDelegate().onRestoreInstanceState(state);
    }

    /**
     * Instantiate a presenter instance
     *
     * @return The {@link MvpPresenter} for this view
     */
    public abstract P createPresenter();

    @Override public P getPresenter() {
        return presenter;
    }

    @Override public void setPresenter(P presenter) {
        this.presenter = presenter;
    }

    @Override public V getMvpView() {
        return (V) this;
    }

    @Override public final Parcelable superOnSaveInstanceState() {
        return super.onSaveInstanceState();
    }

    @Override public final void superOnRestoreInstanceState(Parcelable state) {
        super.onRestoreInstanceState(state);
    }
}
</code>```

This is actually something ViewGroupMvpDelegate should take care of internally. This should be fixed with Mosby 3.0.1.

See https://github.com/sockeqwe/mosby/issues/229

Title: Support MvpConstraintLayout

Body:
I try to support MvpConstraintLayout myself, just copy code from MvpLinearLayout

public abstract class MvpConstraintLayout<V extends MvpView, P extends MvpPresenter<V>>
        extends ConstraintLayout implements MvpView, ViewGroupDelegateCallback<V, P> {
    protected P presenter;
    protected ViewGroupMvpDelegate<V, P> mvpDelegate;

    public MvpConstraintLayout(Context context) {
        super(context);
    }

    public MvpConstraintLayout(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public MvpConstraintLayout(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    /**
     * Get the mvp delegate. This is internally used for creating presenter, attaching and detaching
     * view from presenter etc.
     *
     *
Please note that only one instance of mvp delegate should be used per android.view.View
     * instance.
     *

     *
     *

     * Only override this method if you really know what you are doing.
     *

     *
     * @return {@link ViewGroupMvpDelegate}
     */
    @NonNull
    protected ViewGroupMvpDelegate<V, P> getMvpDelegate() {
        if (mvpDelegate == null) {
            mvpDelegate = new ViewGroupMvpDelegateImpl<>(this, true);
        }

        return mvpDelegate;
    }

    @Override protected void onAttachedToWindow() {
        super.onAttachedToWindow();
        getMvpDelegate().onAttachedToWindow();
    }

    @Override protected void onDetachedFromWindow() {
        super.onDetachedFromWindow();
        getMvpDelegate().onDetachedFromWindow();
    }

    @SuppressLint("MissingSuperCall") @Override protected Parcelable onSaveInstanceState() {
        return getMvpDelegate().onSaveInstanceState();
    }

    @SuppressLint("MissingSuperCall") @Override
    protected void onRestoreInstanceState(Parcelable state) {
        getMvpDelegate().onRestoreInstanceState(state);
    }

    /**
     * Instantiate a presenter instance
     *
     * @return The {@link MvpPresenter} for this view
     */
    public abstract P createPresenter();

    @Override public P getPresenter() {
        return presenter;
    }

    @Override public void setPresenter(P presenter) {
        this.presenter = presenter;
    }

    @Override public V getMvpView() {
        return (V) this;
    }

    @Override public final Parcelable superOnSaveInstanceState() {
        return super.onSaveInstanceState();
    }

    @Override public final void superOnRestoreInstanceState(Parcelable state) {
        super.onRestoreInstanceState(state);
    }
}

Then, use it in code

public class StatusBarLayout extends MvpConstraintLayout<StatusView, StatusPresenter>
        implements StatusView {

    public StatusBarLayout(Context context) {
        super(context);

        init();
    }

    public StatusBarLayout(Context context, AttributeSet attrs) {
        super(context, attrs);
        init();
    }

    public StatusBarLayout(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init();
    }

    @Override
    protected void onFinishInflate() {
        super.onFinishInflate();
        ButterKnife.bind(this, this);
    }

    @Override
    public StatusPresenter createPresenter() {
        return DaggerStatusBarLayoutComponent.builder().build().presenter();
    }

    private void init() {
        View.inflate(getContext(), R.layout.layout_status, this);
    }
}

In preview, the IDE said

java.lang.IllegalStateException: Could not find the surrounding Activity
    at com.hannesdorfmann.mosby3.PresenterManager.getActivity(PresenterManager.java:231)
    at com.hannesdorfmann.mosby3.mvp.delegate.ViewGroupMvpDelegateImpl.<init>(ViewGroupMvpDelegateImpl.java:70)
    at com.skybornecn.ifdive.widgets.MvpConstraintLayout.getMvpDelegate(MvpConstraintLayout.java:55)
    at com.skybornecn.ifdive.widgets.MvpConstraintLayout.onAttachedToWindow(MvpConstraintLayout.java:63)
    at android.view.View.dispatchAttachedToWindow(View.java:15395)
    at android.view.ViewGroup.dispatchAttachedToWindow(ViewGroup.java:2953)
    at android.view.ViewGroup.dispatchAttachedToWindow(ViewGroup.java:2960)
    at android.view.ViewGroup.dispatchAttachedToWindow(ViewGroup.java:2960)
    at android.view.ViewGroup.dispatchAttachedToWindow(ViewGroup.java:2960)
    at android.view.AttachInfo_Accessor.setAttachInfo(AttachInfo_Accessor.java:42)
    at com.android.layoutlib.bridge.impl.RenderSessionImpl.inflate(RenderSessionImpl.java:333)
    at com.android.layoutlib.bridge.Bridge.createSession(Bridge.java:429)
    at com.android.ide.common.rendering.LayoutLibrary.createSession(LayoutLibrary.java:368)
    at com.android.tools.idea.rendering.RenderTask$2.compute(RenderTask.java:567)
    at com.android.tools.idea.rendering.RenderTask$2.compute(RenderTask.java:549)
    at com.intellij.openapi.application.impl.ApplicationImpl.runReadAction(ApplicationImpl.java:863)
    at com.android.tools.idea.rendering.RenderTask.createRenderSession(RenderTask.java:549)
    at com.android.tools.idea.rendering.RenderTask.lambda$inflate$1(RenderTask.java:680)
    at java.util.concurrent.FutureTask.run(FutureTask.java:266)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
    at java.lang.Thread.run(Thread.java:745)

I have read the mosby PresenterManager, but still not know why. In addition, install to phone, the layout displayed just ok.

Body:
UPDATE:
This is fixed in Mosby 3.0.1.

This is just a android tooling issue with Mosby.
The android layout editor actually instantiates a Instance of MvpConstraintLayout to preview it in Android Studio. However, Android Studio doesn't do that by attaching a View like MvpContraintLayout to a real Activity, but internally uses some mocked "context" alike thing. Mosby's PresenterManager internally tries to find an Activity for your MvpConstraintLayout, but in Android Studio there is no real Activity used (as already explained) and therefore the UI editor displays this error message and when installed on the phone it works properly (because there is a real Activity used).

To fix that you have to use view.isInEditMode() before calling the delegate like this:

public abstract class MvpConstraintLayout<V extends MvpView, P extends MvpPresenter<V>>
        extends ConstraintLayout implements MvpView, ViewGroupDelegateCallback<V, P> {
    ...

    @Override protected void onAttachedToWindow() {
        super.onAttachedToWindow();
        if (!isInEditMode()) getMvpDelegate().onAttachedToWindow();
    }

    @Override protected void onDetachedFromWindow() {
        super.onDetachedFromWindow();
        if (!isInEditMode()) getMvpDelegate().onDetachedFromWindow();
    }

    @SuppressLint("MissingSuperCall") @Override protected Parcelable onSaveInstanceState() {
       if (!isInEditMode()) return getMvpDelegate().onSaveInstanceState();
       return super.onSaveInstanceState();
    }

    @SuppressLint("MissingSuperCall") @Override
    protected void onRestoreInstanceState(Parcelable state) {
        if (!isInEditMode()) getMvpDelegate().onRestoreInstanceState(state);
    }

    /**
     * Instantiate a presenter instance
     *
     * @return The {@link MvpPresenter} for this view
     */
    public abstract P createPresenter();

    @Override public P getPresenter() {
        return presenter;
    }

    @Override public void setPresenter(P presenter) {
        this.presenter = presenter;
    }

    @Override public V getMvpView() {
        return (V) this;
    }

    @Override public final Parcelable superOnSaveInstanceState() {
        return super.onSaveInstanceState();
    }

    @Override public final void superOnRestoreInstanceState(Parcelable state) {
        super.onRestoreInstanceState(state);
    }
}

This is actually something ViewGroupMvpDelegate should take care of internally. This should be fixed with Mosby 3.0.1.

See https://github.com/sockeqwe/mosby/issues/229


问:
How can I get the grid coordinates of a hexagon tile by a pixel point in Java?
I have a hexagon shaped grid of hexagons.  I need to find the grid coordinates of a tile that a user clicks on.  How can I do this if the code below calculates where the tiles are drawn?

```<code>private void CalcHexCoords() {

        Point origin = new Point(originX, originY);
        double ang30 = Math.toRadians(30);
        double xOff = Math.cos(ang30) * (radius + padding);
        double yOff = Math.sin(ang30) * (radius + padding);
        int half = size / 2;

        int i = 0; //total number of tiles
        for (int row = 0; row < size; row++) {

            int cols = size - Math.abs(row - half);

            for (int col = 0; col < cols; col++) {

                int xLbl = row < half ? col - row : col - half;
                int yLbl = row - half;
                int centerX = (int) (origin.x + xOff * (col * 2 + 1 - cols));
                int centerY = (int) (origin.y + yOff * (row - half) * 3);

                Hexagon hex = new Hexagon(centerX, centerY, radius);
                hexagons.add(hex);
                int[] coords = new int[]{xLbl, yLbl};
                Tile tile = new Tile(rsrc, hex.center, radius, diceSpaces.get(i), coords, i, hex);
                tiles.put(coords[0] + "," + coords[1], tile);
                i++;
            }
        }
    }
</code>```

This is the coordinate system I use:

答:
There's not much coding here but geometry at most.

You get hexagon's center xc,yc and radius r (radius equals side length).

To calculate where corners of particular hexagon lie you should:

```<code>North corner: xc , yc+r,
South:xc,yc-r,
NE:xc+r, yc+1/2r,
NW:xc-r,yc+1/2r,
SE:xc+r,yc-1/2r
SW:xc-r,yc-1/2r
</code>```

If you use screen coordinates then your y-axis is reverted so you switch signs when calculating y-coordinates.

If you also need to figure out which hexagon was clicked then you will need to calculate distance between mouse click and center of each hexagon. If it's lower than radius of given hexagon - you have your clicked hex and proceed as described above.

Body:
I have a hexagon shaped grid of hexagons.  I need to find the grid coordinates of a tile that a user clicks on.  How can I do this if the code below calculates where the tiles are drawn?

private void CalcHexCoords() {

        Point origin = new Point(originX, originY);
        double ang30 = Math.toRadians(30);
        double xOff = Math.cos(ang30) * (radius + padding);
        double yOff = Math.sin(ang30) * (radius + padding);
        int half = size / 2;

        int i = 0; //total number of tiles
        for (int row = 0; row < size; row++) {

            int cols = size - Math.abs(row - half);

            for (int col = 0; col < cols; col++) {

                int xLbl = row < half ? col - row : col - half;
                int yLbl = row - half;
                int centerX = (int) (origin.x + xOff * (col * 2 + 1 - cols));
                int centerY = (int) (origin.y + yOff * (row - half) * 3);

                Hexagon hex = new Hexagon(centerX, centerY, radius);
                hexagons.add(hex);
                int[] coords = new int[]{xLbl, yLbl};
                Tile tile = new Tile(rsrc, hex.center, radius, diceSpaces.get(i), coords, i, hex);
                tiles.put(coords[0] + "," + coords[1], tile);
                i++;
            }
        }
    }

This is the coordinate system I use:

Body:
There's not much coding here but geometry at most.

You get hexagon's center xc,yc and radius r (radius equals side length).

To calculate where corners of particular hexagon lie you should:

North corner: xc , yc+r,
South:xc,yc-r,
NE:xc+r, yc+1/2r,
NW:xc-r,yc+1/2r,
SE:xc+r,yc-1/2r
SW:xc-r,yc-1/2r

If you use screen coordinates then your y-axis is reverted so you switch signs when calculating y-coordinates.

If you also need to figure out which hexagon was clicked then you will need to calculate distance between mouse click and center of each hexagon. If it's lower than radius of given hexagon - you have your clicked hex and proceed as described above.


问:
tfidf.transform() function not returning correct values
I am trying to fit tfidf vectorizer on a certain text corpus and then use the same vectorizer to find the sum of tfidf values of the new text.However, the sum values are not as expected. Below is the example:

```<code>text = ["I am new to python and R , how can anyone help me","why is no one able to crack the python code without help"]
tf= TfidfVectorizer(stop_words='english',ngram_range =(1,1))
tf.fit_transform(text)
zip(tf.get_feature_names(),tf.idf_)

[(u'able', 1.4054651081081644),
 (u'code', 1.4054651081081644),
 (u'crack', 1.4054651081081644),
 (u'help', 1.0),
 (u'new', 1.4054651081081644),
 (u'python', 1.0)]
</code>```

Now when i try the same tf with new text:

```<code>new_text = "i am not able to code"
np.sum(tf.transform([new_text]))
1.4142135623730951
</code>```

I am expecting the output to be around 2.80.any suggestion on what might be going wrong here would be really helpful.

答:
This is because of the 'l2 normalization' (default in TfidfVectorizer).
As you expect, the first result of the transform() is:

```<code>array([[ 1.40546511,  1.40546511,  0.        ,  0.        ,  0.        ,
     0.        ]])
</code>```

But now the normalization is done. In this, the above vector is divided by the divider:

```<code>dividor = sqrt(sqr(1.40546511)+sqr(1.40546511)+sqr(0)+sqr(0)+sqr(0)+sqr(0))
        = sqrt(1.975332175+1.975332175+0+0+0+0)
        = 1.98762782
</code>```

So the resulting final array is:

```<code>array([[ 0.70710678,  0.70710678,  0.        ,  0.        ,  0.        ,
     0.        ]])
</code>```

And then you apply sum, its result is = 1.4142135623730951.

Hope it is clear now. You can refer to my answer here for complete working of TfidfVectorizer.

Body:
I am trying to fit tfidf vectorizer on a certain text corpus and then use the same vectorizer to find the sum of tfidf values of the new text.However, the sum values are not as expected. Below is the example:

text = ["I am new to python and R , how can anyone help me","why is no one able to crack the python code without help"]
tf= TfidfVectorizer(stop_words='english',ngram_range =(1,1))
tf.fit_transform(text)
zip(tf.get_feature_names(),tf.idf_)

[(u'able', 1.4054651081081644),
 (u'code', 1.4054651081081644),
 (u'crack', 1.4054651081081644),
 (u'help', 1.0),
 (u'new', 1.4054651081081644),
 (u'python', 1.0)]

Now when i try the same tf with new text:

new_text = "i am not able to code"
np.sum(tf.transform([new_text]))
1.4142135623730951

I am expecting the output to be around 2.80.any suggestion on what might be going wrong here would be really helpful.

Body:
This is because of the 'l2 normalization' (default in TfidfVectorizer).
As you expect, the first result of the transform() is:

array([[ 1.40546511,  1.40546511,  0.        ,  0.        ,  0.        ,
     0.        ]])

But now the normalization is done. In this, the above vector is divided by the divider:

dividor = sqrt(sqr(1.40546511)+sqr(1.40546511)+sqr(0)+sqr(0)+sqr(0)+sqr(0))
        = sqrt(1.975332175+1.975332175+0+0+0+0)
        = 1.98762782

So the resulting final array is:

array([[ 0.70710678,  0.70710678,  0.        ,  0.        ,  0.        ,
     0.        ]])

And then you apply sum, its result is = 1.4142135623730951.

Hope it is clear now. You can refer to my answer here for complete working of TfidfVectorizer.


问:
Ruby post title to slug
How should I convert a post title to a slug in Ruby?

The title can have any characters, but I only want the slug to allow [a-z0-9-_] (Should it allow any other characters?).

So basically:

downcase all letters

convert spaces to hyphens

delete extraneous characters

答:
Is this Rails? (works in Sinatra)

```<code>string.parameterize
</code>```

That's it. For even more sophisticated slugging, see ActsAsUrl. It can do the following:

```<code>"rock & roll".to_url => "rock-and-roll"
"$12 worth of Ruby power".to_url => "12-dollars-worth-of-ruby-power"
"10% off if you act now".to_url => "10-percent-off-if-you-act-now"
"kick it en Français".to_url => "kick-it-en-francais"
"rock it Español style".to_url => "rock-it-espanol-style"
"tell your readers 你好".to_url => "tell-your-readers-ni-hao"
</code>```

Title: Ruby post title to slug

Body:
Is this Rails? (works in Sinatra)

string.parameterize

That's it. For even more sophisticated slugging, see ActsAsUrl. It can do the following:

"rock & roll".to_url => "rock-and-roll"
"$12 worth of Ruby power".to_url => "12-dollars-worth-of-ruby-power"
"10% off if you act now".to_url => "10-percent-off-if-you-act-now"
"kick it en Français".to_url => "kick-it-en-francais"
"rock it Español style".to_url => "rock-it-espanol-style"
"tell your readers 你好".to_url => "tell-your-readers-ni-hao"

ContentLicense: CC BY-SA 4.0


问:
How to make TestNG show cucumber scenarios in the "Results of Running Suite"?
I've created a maven project and trying to run Cucumber+Selenium+Java tests using TestNG plugin. While some tutorials that use JUnit+Cucumber shows results with every scenario of a feature, my TestNG results tab shows only the feature name. what am i missing?

I have one feature Authentication
Inside that i have two scenarios Login and Logout.

I am expecting something like this in the "Results of Running Suite" tab of TestNG:
  From a JUnit tutorial

My current testng result is like this. 'Authentication' is the feature, but the 2 scenarios inside it are not appearing

答:
the previous answer is right but
instead of

```<code>scenarioList.add(new Object[]{scenario, scenario.getGherkinModel().getName()});
</code>```

use

```<code>scenarioList.add(new Object[]{scenario});
</code>```

else there is an error like that:
Selenium Webdriver, TestNG - data provider is trying to pass 2 parameter but the method take 3 and TestNG is unable in inject a suitable object

Body:
the previous answer is right but
instead of

scenarioList.add(new Object[]{scenario, scenario.getGherkinModel().getName()});

use

scenarioList.add(new Object[]{scenario});

else there is an error like that:
Selenium Webdriver, TestNG - data provider is trying to pass 2 parameter but the method take 3 and TestNG is unable in inject a suitable object


问:
Kafka consumer with new API not working
I found something very weird with Kafka.

I have a producer with 3 brokers :

```<code>bin/kafka-console-producer.sh --broker-list localhost:9093, localhost:9094, localhost:9095 --topic topic
</code>```

Then I try to run a consumer with the new API :

```<code>bin/kafka-console-consumer.sh --bootstrap-server localhost:9093,localhost:9094,localhost:9095 --topic topic --from-beginning
</code>```

I got nothing ! BUT if I use the old API :

```<code>bin/kafka-console-consumer.sh --zookeeper localhost:2181 --from-beginning --topic topic
</code>```

I got my messages !

What is wrong with me ?

PS : I am using Kafka 10

答:
I eventually resolved my problem thanks to this similar post : Kafka bootstrap-servers vs zookeeper in kafka-console-consumer

I believe it is a bug / wrong configuration of mine leading to a problem with zookeeper and kafka.

SOLUTION :

First be sure to have enable topic deleting in server.properties files of your brokers :

```<code># Switch to enable topic deletion or not, default value is false
delete.topic.enable=true
</code>```

Then delete the topic :

```<code>bin/kafka-topics.sh --zookeeper localhost:2181 --delete --topic myTopic
</code>```

Remove all the /tmp/log.dir directories of your brokers.

EDIT : I faced again the problem and I had to remove also the log files of zookeeper in /tmp/zookeeper/version-2/.

Finally delete the topic in /brokers/topics in zookeeper as follow :

```<code>$ kafka/bin/zookeeper-shell.sh localhost:2181
Connecting to localhost:2181
Welcome to ZooKeeper!
JLine support is disabled

rmr /broker/topics/mytopic
</code>```

And restart your brokers and create your topic again.

Title: Kafka consumer with new API not working

Body:
I found something very weird with Kafka.

I have a producer with 3 brokers :

bin/kafka-console-producer.sh --broker-list localhost:9093, localhost:9094, localhost:9095 --topic topic

Then I try to run a consumer with the new API :

bin/kafka-console-consumer.sh --bootstrap-server localhost:9093,localhost:9094,localhost:9095 --topic topic --from-beginning

I got nothing ! BUT if I use the old API :

bin/kafka-console-consumer.sh --zookeeper localhost:2181 --from-beginning --topic topic

I got my messages !

What is wrong with me ?

PS : I am using Kafka 10

Body:
I eventually resolved my problem thanks to this similar post : Kafka bootstrap-servers vs zookeeper in kafka-console-consumer

I believe it is a bug / wrong configuration of mine leading to a problem with zookeeper and kafka.

SOLUTION :

First be sure to have enable topic deleting in server.properties files of your brokers :

# Switch to enable topic deletion or not, default value is false
delete.topic.enable=true

Then delete the topic :

bin/kafka-topics.sh --zookeeper localhost:2181 --delete --topic myTopic

Remove all the /tmp/log.dir directories of your brokers.

EDIT : I faced again the problem and I had to remove also the log files of zookeeper in /tmp/zookeeper/version-2/.

Finally delete the topic in /brokers/topics in zookeeper as follow :

$ kafka/bin/zookeeper-shell.sh localhost:2181
Connecting to localhost:2181
Welcome to ZooKeeper!
JLine support is disabled

rmr /broker/topics/mytopic

And restart your brokers and create your topic again.


问:
How to update table2 from table1, into corresponding entry in table2?
I want to count the occurrences of banks in different tables, and update in corresponding columns of FinalTable.

BankTable:

```<code>  BankName  ErrorCode
    SBI         200
    ICICI       200
    SBI         400
    SBI         500
    SBI         503
</code>```

ATMTable:

```<code>BankName    ErrorCode
ICICI       200
ICICI       400
ICICI       400
SBI         500
SBI         503
</code>```

MitraTable:

```<code>BankName    ErrorCode
ICICI        200
ICICI        200
SBI          400
SBI          500
SBI          503
PNB          501
</code>```

FinalTable:

```<code>BankName    BankCount   ATMCount    MitraCount  TotalCount
ICICI            1         3           2          6
SBI              4         2           3          9
PNB              0         0           1          1
</code>```

I want to count the occurances of different banks and set the values in FinalTable.

答:
You can use UNION ALL together with conditional aggregation:

```<code>SELECT BankName,
       COUNT(CASE WHEN src = 'Bank' THEN 1 END) AS BankCount,
       COUNT(CASE WHEN src = 'ATM' THEN 1 END) AS ATMCount,
       COUNT(CASE WHEN src = 'Mitra' THEN 1 END) AS MitraCount,
       COUNT(*) AS TotalCount

FROM (
   SELECT BankName, 'Bank' AS src
   FROM BankTable

   UNION ALL

   SELECT BankName, 'ATM' AS src
   FROM ATMTable

   UNION ALL

   SELECT BankName, 'Mitra' AS src
   FROM MitraTable) AS t
GROUP BY BankName
</code>```

Field src is used to return the source table to the outer query consuming the results of the UNION ALL operations. Using this field we can perform conditional aggregation in order to count the occurence of each bank in each of the source tables.

Body:
I want to count the occurrences of banks in different tables, and update in corresponding columns of FinalTable.

BankTable:

  BankName  ErrorCode
    SBI         200
    ICICI       200
    SBI         400
    SBI         500
    SBI         503

ATMTable:

BankName    ErrorCode
ICICI       200
ICICI       400
ICICI       400
SBI         500
SBI         503

MitraTable:

BankName    ErrorCode
ICICI        200
ICICI        200
SBI          400
SBI          500
SBI          503
PNB          501

FinalTable:

BankName    BankCount   ATMCount    MitraCount  TotalCount
ICICI            1         3           2          6
SBI              4         2           3          9
PNB              0         0           1          1

I want to count the occurances of different banks and set the values in FinalTable.

Body:
You can use UNION ALL together with conditional aggregation:

SELECT BankName,
       COUNT(CASE WHEN src = 'Bank' THEN 1 END) AS BankCount,
       COUNT(CASE WHEN src = 'ATM' THEN 1 END) AS ATMCount,
       COUNT(CASE WHEN src = 'Mitra' THEN 1 END) AS MitraCount,
       COUNT(*) AS TotalCount

FROM (
   SELECT BankName, 'Bank' AS src
   FROM BankTable

   UNION ALL

   SELECT BankName, 'ATM' AS src
   FROM ATMTable

   UNION ALL

   SELECT BankName, 'Mitra' AS src
   FROM MitraTable) AS t
GROUP BY BankName

Field src is used to return the source table to the outer query consuming the results of the UNION ALL operations. Using this field we can perform conditional aggregation in order to count the occurence of each bank in each of the source tables.


问:
PHP calculate values from json or array
I am reading form a a file that print out of the following.

```<code>    {
   "draw":0,
   "recordsTotal":3995,
   "recordsFiltered":1,
   "data":[
      {
         "customer_id":"1",
         "channel":"2",
         "date":"2017-03\/21 ",
         "earnings":"2500"
      },
      {
         "customer_id":"2",
         "channel":"2",
         "date":"2017-03\/21 ",
         "earnings":"1500"
      }
   ]
}
</code>```

is it possible in a separate php file to read this and to calcualte the total earnings?

i.e 2500 + 1500 = 4000

答:
Try this:</p>

```<code>$decoded = json_decode($json, true); // Decode JSON to array

echo array_sum(array_column($decoded['data'], 'earnings')); // Calculate sum of 'earnings' index within 'data'
</code>```

Title: PHP calculate values from json or array

Body:
I am reading form a a file that print out of the following.

    {
   "draw":0,
   "recordsTotal":3995,
   "recordsFiltered":1,
   "data":[
      {
         "customer_id":"1",
         "channel":"2",
         "date":"2017-03\/21 ",
         "earnings":"2500"
      },
      {
         "customer_id":"2",
         "channel":"2",
         "date":"2017-03\/21 ",
         "earnings":"1500"
      }
   ]
}

is it possible in a separate php file to read this and to calcualte the total earnings?

i.e 2500 + 1500 = 4000

Body:
Try this:

$decoded = json_decode($json, true); // Decode JSON to array

echo array_sum(array_column($decoded['data'], 'earnings')); // Calculate sum of 'earnings' index within 'data'


问:
Cannot find Qt QML SpinBox minimumValue using QtQuick.Controls 2.1
I got this piece of code:

```<code>import QtQuick 2.7
import QtQuick.Controls 1.5

ApplicationWindow {
    visible: true
    width: 640
    height: 480
    title: qsTr("spinbox trouble")

    SpinBox{
        anchors.centerIn: parent
        value: 5
        minimumValue: 1
        maximumValue: 10
    }
}
</code>```

Everything is fine. Now I want to use SwipeView. To use it I need use QtQuick.Controls 2.1. But when I use version 2.1, I cannot find [minimum/maximum]Value in SpinBox.

Questions:

1. What is reason to drop this properties in QtQuick.Controls 2.1?

2. Is there any way to use both SwipeView and SpinBox with [minimum/maximum]Value property?

答: Looking at the Qt doc I'd say you can use the from and to properties instead of minimumValue and maximumValue!?

Body:
I got this piece of code:

import QtQuick 2.7
import QtQuick.Controls 1.5

ApplicationWindow {
    visible: true
    width: 640
    height: 480
    title: qsTr("spinbox trouble")

    SpinBox{
        anchors.centerIn: parent
        value: 5
        minimumValue: 1
        maximumValue: 10
    }
}

Everything is fine. Now I want to use SwipeView. To use it I need use QtQuick.Controls 2.1. But when I use version 2.1, I cannot find [minimum/maximum]Value in SpinBox.

Questions:

1. What is reason to drop this properties in QtQuick.Controls 2.1?

2. Is there any way to use both SwipeView and SpinBox with [minimum/maximum]Value property?


问:
In C programming make a Do-While loop to ask user if they want the program to run again
This program so far sweeps through the frequency range 0-20000 Hz and prints every 50 Hz on screen, it then stops when it reaches 20000 Hz. It also stops if I move a control on an on screen midi keyboard.

Now what I'm trying to do is to modify it so that when it has reached 2000 Hz, instead of stopping, the program gives the user an option, something like "Do you want to start this program again?", and if the user types 'Y' then it will start again, but if the user types 'N' the program will stop. I believe a do while is what I'm looking for, but I've tried and just can't seem to get it to work.

My Code:

```<code>#include "aservelibs/aservelib.h"
#include <stdio.h>
#include <math.h>

int main()
{
    int frequency = 0.0;
    int modulation = aserveGetControl(1);

    printf("aserve get note control is %d\n", modulation);

    do
    {
        while( frequency < 20000.0 && modulation == 0)
        {
            modulation = aserveGetControl(1);
            aserveOscillator(0,frequency,1.0,0);
            printf("The frequency is: %dHz\n", frequency);
            frequency = frequency + 50.0;
            aserveSleep(20);
        }

        char userInput;
        printf("enter 'y' if you would like to repeat: ");
        scanf(" %c", &userInput);
        while(userInput == 'y');
    }

    return(0);
}
</code>```

答:
Your concept is correct, but you have just missed the syntax of do while loop.

It should be

```<code>do {

} while(condition);
</code>```

So, modified code will be

```<code>#include "aservelibs/aservelib.h"
#include <stdio.h>
#include <math.h>

int main()
{
    int frequency = 0.0;
    int modulation = aserveGetControl(1);
    printf("aserve get note control is %d\n", modulation);
    char userInput;

    do
    {
        while( frequency < 20000.0 && modulation == 0)
        {
            modulation = aserveGetControl(1);
            aserveOscillator(0,frequency,1.0,0);
            printf("The frequency is: %dHz\n", frequency);
            frequency = frequency + 50.0;
            aserveSleep(20);
        }

        printf("enter 'y' if you would like to repeat:  ");
        scanf(" %c", &userInput);
    } while(userInput == 'y');

    return(0);
}
</code>```

Body:
This program so far sweeps through the frequency range 0-20000 Hz and prints every 50 Hz on screen, it then stops when it reaches 20000 Hz. It also stops if I move a control on an on screen midi keyboard.

Now what I'm trying to do is to modify it so that when it has reached 2000 Hz, instead of stopping, the program gives the user an option, something like "Do you want to start this program again?", and if the user types 'Y' then it will start again, but if the user types 'N' the program will stop. I believe a do while is what I'm looking for, but I've tried and just can't seem to get it to work.

My Code:

#include "aservelibs/aservelib.h"
#include <stdio.h>
#include <math.h>

int main()
{
    int frequency = 0.0;
    int modulation = aserveGetControl(1);

    printf("aserve get note control is %d\n", modulation);

    do
    {
        while( frequency < 20000.0 && modulation == 0)
        {
            modulation = aserveGetControl(1);
            aserveOscillator(0,frequency,1.0,0);
            printf("The frequency is: %dHz\n", frequency);
            frequency = frequency + 50.0;
            aserveSleep(20);
        }

        char userInput;
        printf("enter 'y' if you would like to repeat: ");
        scanf(" %c", &userInput);
        while(userInput == 'y');
    }

    return(0);
}

Body:
Your concept is correct, but you have just missed the syntax of do while loop.

It should be

do {

} while(condition);

So, modified code will be

#include "aservelibs/aservelib.h"
#include <stdio.h>
#include <math.h>

int main()
{
    int frequency = 0.0;
    int modulation = aserveGetControl(1);
    printf("aserve get note control is %d\n", modulation);
    char userInput;

    do
    {
        while( frequency < 20000.0 && modulation == 0)
        {
            modulation = aserveGetControl(1);
            aserveOscillator(0,frequency,1.0,0);
            printf("The frequency is: %dHz\n", frequency);
            frequency = frequency + 50.0;
            aserveSleep(20);
        }

        printf("enter 'y' if you would like to repeat:  ");
        scanf(" %c", &userInput);
    } while(userInput == 'y');

    return(0);
}


问:
SQLite doesn't report correct weekday with dataframe in R
I am trying to count the number of times each weekday occurs in a dataframe. My dataframe looks like this when printed on screen (assume the columns are labeled "x")

I am currently using

sqldf("SELECT x, strftime('%w', x) FROM maxkwpeakdates")

also, if I run the code

sqldf("SELECT strftime('%w', date('now'))")

I get the right weekday.

Knowing that strftime is from sqlite and that their datetime functions are 0 based, those numbers are off. Looking at the 1st line the result should be a 3 because April 6, 2011 occurred on a Wednesday. The 10th line should also result in a 3 because January 4th 2012 also occurred on a Wednesday.

My data is actually in a dataframe stored within a shiny app which is why I am not using something like RMySQL and am instead using sqldf. I want to be able to run SQL queries on my dataframe so that I can keep the data inside the app and so that I can calculate things like average number of specific weekdays in a time period. Here is an example of my dataframe which is called maxkwpeakdates:

I did another test with my data and compared the results of using

sqldf("SELECT x, strftime('%w', x) FROM maxkwpeakdates")

and

weekdays(as.Date(maxkwpeakdates$x))

Then I stored these results in a dataframe so I could compare the results.

Notice that using as.Date reported the correct weekdays but using strftime was almost always off. Is this a problem with R talking to sqlite through strftime? Is there a way to fix this so I get the correct result with strftime?

答:
1) SQLite SQLite does not have any date/time type so all R does is send the internal representation, seconds since the Epoch, to SQLite and then it is up to the SQL statement to interpret it somehow.  SQLite does have datetime functions but they don't assume R's internal representation and conversion is required like this:

```<code>dd <- data.frame(now = Sys.time()) # test data
dd
##                   now
## 1 2017-03-29 07:39:30

format(dd$now, "%A") # check
## [1] "Wednesday"

sqldf("select strftime('%w', now, 'unixepoch', 'localtime') dayno from dd")
##   dayno
## 1     3
</code>```

2) H2 An easier alternative is to use the H2 database back end to sqldf.  If the RH2 package is loaded sqldf will default to it.   H2 does have true date and datetime types making manpulation of such objects much easier.

```<code>library(RH2)
library(sqldf)

sqldf("select day_of_week(now)-1 dayno, dayname(now) dayname from dd")
##   dayno   dayname
## 1     3 Wednesday
</code>```

Body:
1) SQLite SQLite does not have any date/time type so all R does is send the internal representation, seconds since the Epoch, to SQLite and then it is up to the SQL statement to interpret it somehow.  SQLite does have datetime functions but they don't assume R's internal representation and conversion is required like this:

dd <- data.frame(now = Sys.time()) # test data
dd
##                   now
## 1 2017-03-29 07:39:30

format(dd$now, "%A") # check
## [1] "Wednesday"

sqldf("select strftime('%w', now, 'unixepoch', 'localtime') dayno from dd")
##   dayno
## 1     3

2) H2 An easier alternative is to use the H2 database back end to sqldf.  If the RH2 package is loaded sqldf will default to it.   H2 does have true date and datetime types making manpulation of such objects much easier.

library(RH2)
library(sqldf)

sqldf("select day_of_week(now)-1 dayno, dayname(now) dayname from dd")
##   dayno   dayname
## 1     3 Wednesday


问:
Prevent click for Chocolat.js while dragging using slick.js
Right  now I have a draggable images container using slick and I want to preview full size when a single click happens using Chocolat.js,

The problem is that when I release the mouse (after dragg), still fires the full screen,

I tried to destroy the chocolat when the Dragg event begins, but it persists..

```<code>var $chocolat = $('.chocolat').Chocolat({
    imageSize: 'contain',
    loop: true
}).data('chocolat');

$('#bx-pager_builder').slick({
    dots: true,
    infinite: true,
    speed: 300,
    slidesToShow: 1,
    centerMode: true,
    variableWidth: true,
    beforeChange: function() {
        $chocolat.api().destroy();
    },
    afterChange: function() {
        $chocolat = $('.chocolat').Chocolat({
            imageSize: 'contain',
            loop: true
        }).data('chocolat');
    }
});
</code>```

The problem is that the Chocolat documentation doesn't provide examples..

Any idea if what i'm trying to do is posible? ( and how? ^^ )

答:
Do you have a demo somewhere so I can understand the bug ?

Anyway this page, is full of examples, you can open it in your browser :

https://github.com/nicolas-t/Chocolat/blob/master/dist/index.html

These lines in particular :
https://github.com/nicolas-t/Chocolat/blob/master/dist/index.html#L142L240
show you how to use the API

Body:
Right  now I have a draggable images container using slick and I want to preview full size when a single click happens using Chocolat.js,

The problem is that when I release the mouse (after dragg), still fires the full screen,

I tried to destroy the chocolat when the Dragg event begins, but it persists..

var $chocolat = $('.chocolat').Chocolat({
    imageSize: 'contain',
    loop: true
}).data('chocolat');

$('#bx-pager_builder').slick({
    dots: true,
    infinite: true,
    speed: 300,
    slidesToShow: 1,
    centerMode: true,
    variableWidth: true,
    beforeChange: function() {
        $chocolat.api().destroy();
    },
    afterChange: function() {
        $chocolat = $('.chocolat').Chocolat({
            imageSize: 'contain',
            loop: true
        }).data('chocolat');
    }
});

The problem is that the Chocolat documentation doesn't provide examples..

Any idea if what i'm trying to do is posible? ( and how? ^^ )


问:
JS Promises: is there a neat way to resolve multiple promises as object properties?
I wrote the below code then realised it was resolving early (logging before all promises resolve):

```<code>readDirPromise
.then(categoriseFiles)
.then(({movies, series}) => ({
  movies: Promise.all(movies.map(movieTasks)),
  series: Promise.all(series.map(seriesTasks))
}))
.then((res) => {
  console.log(' done!', res)
})
</code>```

I've managed to rewrite it to resolve in the correct order:

```<code>readDirPromise
.then(categoriseFiles)
.then((cats) => Promise.all(cats.movies.map(movieTasks)).then((movies) => {
  cats.movies = movies
  return cats
}))
.then((cats) => Promise.all(cats.series.map(seriesTasks)).then((series) => {
  cats.series = series
  return cats
}))
.then((res) => {
  console.log(' done!', res)
})
</code>```

but I can't help but think... is there a neater, more extensible way?

答:
For what it's worth, I believe the async/await version of this would be something like:</p>

```<code>async function generateResponse() {
  const {movies, series} = await readDirPromise.then(categoriseFiles);
  return {
    movies: await Promise.all(movies.map(movieTasks)),
    series: await Promise.all(series.map(seriesTasks))
  }
}
</code>```

Body:
I wrote the below code then realised it was resolving early (logging before all promises resolve):

readDirPromise
.then(categoriseFiles)
.then(({movies, series}) => ({
  movies: Promise.all(movies.map(movieTasks)),
  series: Promise.all(series.map(seriesTasks))
}))
.then((res) => {
  console.log(' done!', res)
})

I've managed to rewrite it to resolve in the correct order:

readDirPromise
.then(categoriseFiles)
.then((cats) => Promise.all(cats.movies.map(movieTasks)).then((movies) => {
  cats.movies = movies
  return cats
}))
.then((cats) => Promise.all(cats.series.map(seriesTasks)).then((series) => {
  cats.series = series
  return cats
}))
.then((res) => {
  console.log(' done!', res)
})

but I can't help but think... is there a neater, more extensible way?

Body:
For what it's worth, I believe the async/await version of this would be something like:

async function generateResponse() {
  const {movies, series} = await readDirPromise.then(categoriseFiles);
  return {
    movies: await Promise.all(movies.map(movieTasks)),
    series: await Promise.all(series.map(seriesTasks))
  }
}


问:
html file page not showing in wordpress webpage?
If i add the following tag in wordpress page,

```<code><iframe src="file:///var/www/html/wordpress/wp-content/themes/codium-dn/fund.html" name="frame1" width="100%" height="100%" frameborder="no" scrolling="auto" align="center">
</iframe>
</code>```

it doesnt show that html file in wordpress webpage,

can anyone help me solve this. Is there any way to do it

Also help me if is there any way to convert that html file into shortcode

答:
It should be working.

But, you have to put this code in the plain text or html, not in the default text editor wordpress uses.

It is located in the right upper corner of the text field when you are editing this page.

See the image below

Body:
If i add the following tag in wordpress page,

it doesnt show that html file in wordpress webpage,

can anyone help me solve this. Is there any way to do it

Also help me if is there any way to convert that html file into shortcode


答:
At very first, you have a syntax error: The while clause has to be placed outside of the loop body:

do
{
}
while(someCondition); // here!
```

<p>Variables defined inside the loop body are not accessible outside of it - so you need to declare them before:</p>

<pre class="lang-cpp prettyprint-override"><code>char userInput;
do
{
}
while(userInput == 'y');
</code>```

Apart from that, your code should work fine.

Title: In C programming make a Do-While loop to ask user if they want the program to run again

Body:
At very first, you have a syntax error: The while clause has to be placed outside of the loop body:

do
{
}
while(someCondition); // here!

Variables defined inside the loop body are not accessible outside of it - so you need to declare them before:

char userInput;
do
{
}
while(userInput == 'y');

Apart from that, your code should work fine.


问:
Not able to load Application Context in Spring Boot app
I am working on a Spring Boot application wherein I am using that application to expose a SOAP webservice. I am using Apache CFX framework for SOAP impl in Spring boot app. I am using Annotation based approach.

I am facing issue in setting the Application Context from the Spring Boot Configuration file in one of the Beans. Below is my code.

```<code>@SpringBootApplication
@ComponentScan("com.test")
public class Application {

    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
   }
}
</code>```

The configuration file is as below.

```<code>@Configuration
public class WebServiceConfiguration {

//All individual bean definitions should go here
@Autowired
ApplicationContext appContext;

@Bean
public ServletRegistrationBean cxfServlet() {
    return new ServletRegistrationBean(new CXFServlet(), "/soap-api/*");
}

@Bean(name = Bus.DEFAULT_BUS_ID)
public SpringBus springBus() {
    return new SpringBus();
}

@Bean(name="IValidator")
public IValidator getValidator(){
    return new Validator();
}

@Bean(name="SOAPprocessImpl")
public IPSoap getService() {
    return new SOAPprocessImpl();
}

@Bean
public Endpoint endpoint() {
    EndpointImpl endpoint = new EndpointImpl(springBus(), getService());
    endpoint.publish("/WS_1.0");
    endpoint.setWsdlLocation("process.wsdl");
    return endpoint;
}
</code>```

Now I have the bean SOAPprocessImpl implementation in which I need to get the Application Context so that I can get handle to the Validator bean. I have declared SOAPprocessImpl as a bean in the configuraton file. The code is as below

```<code>@javax.jws.WebService (endpointInterface="com.test.IPSoap")
public class SOAPprocessImpl implements IPSoap, ApplicationContextAware {

private static ApplicationContext context;

public static ApplicationContext getApplicationContext() {
    return context;
}

@Override
public void setApplicationContext(ApplicationContext ac)
        throws BeansException {
    context = ac;
}

private static final Logger logger = Logger.getLogger(SOAPprocessImpl.class.getName());

private IValidator validator = (IValidator) context.getBean("IValidator"); // context is NULL here

public IRResponse GetBalance(TSSearchParams SearchParams) {

    // Some processing logic
    }
</code>```

}

So the issue is that when I run the boot application by deploying to the embedded Tomcat then the Application Context is not getting set in the SOAPprocessImpl class even after implementing the ApplicationContextAware. I also tried Autowiring but that also is not working.

Strangely I tried to see if I can get the ApplicationContext in the Configuration file where all the bean are defined. Here it is getting setting properly.

Can anyone help me how to solve this issue. I am new to Spring Boot and may have missed some configutaion. Thanks in advance.

答:
Option(1): To fix the issue, you need to use @Configuration to register your SOAPprocessImpl bean to the Spring container as shown below so that ApplicationContext object can be injected :

```<code>@Configuration
@javax.jws.WebService (endpointInterface="com.test.IPSoap")
public class SOAPprocessImpl implements IPSoap, ApplicationContextAware {

   private static ApplicationContext context;

   private IValidator validator;

   public static ApplicationContext getApplicationContext() {
     return context;
   }

   @Override
   public void setApplicationContext(ApplicationContext ac)
      throws BeansException {
      SOAPprocessImpl.context = ac;
   }

   @PostConstruct//use PostConstruct
   public void init() {
     validator = (IValidator) context.getBean("IValidator");
   }

   //add your current code
}
</code>```

The important point is that you can't use the context object until the bean is prepared by the container, so you need to use @PostConstruct method as shown above to initialise your variables.

Option2 (recommended):
The best approach is that you can use @Autowired to inject IValidator object into SOAPprocessImpl as shown below so that you don't need your SOAPprocessImpl bean to be aware of ApplicationContextAware. Spring container will inject the instance for the implementation provided for the IValidator class (provided it is under the packages of @Componentscan).

```<code>@Component
@javax.jws.WebService (endpointInterface="com.test.IPSoap")
public class SOAPprocessImpl implements IPSoap {

     private static final Logger logger = Logger.getLogger(SOAPprocessImpl.class.getName());

     @Autowired //spring directly injects this object
     private IValidator validator;

     public IRResponse GetBalance(TSSearchParams SearchParams) {
        // Some processing logic
    }
}
</code>```

Body:
I am working on a Spring Boot application wherein I am using that application to expose a SOAP webservice. I am using Apache CFX framework for SOAP impl in Spring boot app. I am using Annotation based approach.

I am facing issue in setting the Application Context from the Spring Boot Configuration file in one of the Beans. Below is my code.

@SpringBootApplication
@ComponentScan("com.test")
public class Application {

    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
   }
}

The configuration file is as below.

@Configuration
public class WebServiceConfiguration {

//All individual bean definitions should go here
@Autowired
ApplicationContext appContext;

@Bean
public ServletRegistrationBean cxfServlet() {
    return new ServletRegistrationBean(new CXFServlet(), "/soap-api/*");
}

@Bean(name = Bus.DEFAULT_BUS_ID)
public SpringBus springBus() {
    return new SpringBus();
}

@Bean(name="IValidator")
public IValidator getValidator(){
    return new Validator();
}

@Bean(name="SOAPprocessImpl")
public IPSoap getService() {
    return new SOAPprocessImpl();
}

@Bean
public Endpoint endpoint() {
    EndpointImpl endpoint = new EndpointImpl(springBus(), getService());
    endpoint.publish("/WS_1.0");
    endpoint.setWsdlLocation("process.wsdl");
    return endpoint;
}

Now I have the bean SOAPprocessImpl implementation in which I need to get the Application Context so that I can get handle to the Validator bean. I have declared SOAPprocessImpl as a bean in the configuraton file. The code is as below

@javax.jws.WebService (endpointInterface="com.test.IPSoap")
public class SOAPprocessImpl implements IPSoap, ApplicationContextAware {

private static ApplicationContext context;

public static ApplicationContext getApplicationContext() {
    return context;
}

@Override
public void setApplicationContext(ApplicationContext ac)
        throws BeansException {
    context = ac;
}

private static final Logger logger = Logger.getLogger(SOAPprocessImpl.class.getName());

private IValidator validator = (IValidator) context.getBean("IValidator"); // context is NULL here

public IRResponse GetBalance(TSSearchParams SearchParams) {

    // Some processing logic
    }

}

So the issue is that when I run the boot application by deploying to the embedded Tomcat then the Application Context is not getting set in the SOAPprocessImpl class even after implementing the ApplicationContextAware. I also tried Autowiring but that also is not working.

Strangely I tried to see if I can get the ApplicationContext in the Configuration file where all the bean are defined. Here it is getting setting properly.

Can anyone help me how to solve this issue. I am new to Spring Boot and may have missed some configutaion. Thanks in advance.

Body:
Option(1): To fix the issue, you need to use @Configuration to register your SOAPprocessImpl bean to the Spring container as shown below so that ApplicationContext object can be injected :

@Configuration
@javax.jws.WebService (endpointInterface="com.test.IPSoap")
public class SOAPprocessImpl implements IPSoap, ApplicationContextAware {

   private static ApplicationContext context;

   private IValidator validator;

   public static ApplicationContext getApplicationContext() {
     return context;
   }

   @Override
   public void setApplicationContext(ApplicationContext ac)
      throws BeansException {
      SOAPprocessImpl.context = ac;
   }

   @PostConstruct//use PostConstruct
   public void init() {
     validator = (IValidator) context.getBean("IValidator");
   }

   //add your current code
}

The important point is that you can't use the context object until the bean is prepared by the container, so you need to use @PostConstruct method as shown above to initialise your variables.

Option2 (recommended):
The best approach is that you can use @Autowired to inject IValidator object into SOAPprocessImpl as shown below so that you don't need your SOAPprocessImpl bean to be aware of ApplicationContextAware. Spring container will inject the instance for the implementation provided for the IValidator class (provided it is under the packages of @Componentscan).

@Component
@javax.jws.WebService (endpointInterface="com.test.IPSoap")
public class SOAPprocessImpl implements IPSoap {

     private static final Logger logger = Logger.getLogger(SOAPprocessImpl.class.getName());

     @Autowired //spring directly injects this object
     private IValidator validator;

     public IRResponse GetBalance(TSSearchParams SearchParams) {
        // Some processing logic
    }
}


问:
Branches for Every Little Change?
We have a client (who has a client, who has a client) who is driving us mad with change requests to a code base (in PHP). Our first response was to just work in a main trunk in SVN, but the client often comes back and requests that a certain change needs to get pushed to the live servers ASAP. On the other hand, other changes get reduced in priority suddenly, which originally came grouped with other changes (seemingly).

We are thinking of using a branch for every change request. Is this mad? What other solutions might work?

Thanks!

Edit: This is a really hard question to choose the correct answer for. Thanks to everybody for your great answers.

Edit: I know that the best answer I chose was not particularly popular. I too wanted to find a technical solution to this problem. But now I think that if the client wants software with features that can be deployed in a modular fashion... this problem should not be solved in our use of the version control system. It would have to be designed into the software.

Edit: Now it's almost a month later and my coworker/client has convinced me that multiple branches is the way to go. This is not just due to the client's insanity, but also based on our need to be able to determine if a feature is "ready to go" or "needs more work" or whatever. I don't have the SVN with me, but we merge using the advice from the SVN Cookbook: you merge the branch from the revision it was branched to the head revision.

Also, using this system, we merge all branches at some point and that becomes the new QA and then live build. Then we branch from that.

Last Edit (Perhaps): Months later, this system is still working out for us. We create branches for every ticket and rarely have problems. On the other hand, we do try to keep things separate as far as what people are working on...

Two Years Later: We use GIT now, and now this system is actually quite reasonable.

答: When estimated hours are more than 8, use a branch.</p>

OwnerDisplayName: Daniel Rosenstark

Title: Branches for Every Little Change?

LastEditorDisplayName: Daniel Rosenstark

OwnerDisplayName: Ludwig Wensauer


问:
How to pass data from an activity to a fragment in TabHost?
I have a page divided like this: there is the "Main" layout which holds a fragment

```<code><fragment
    android:name="com.x.x.FirstFragment"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:id="@+id/firstFragment"
    tools:layout="@layout/first_fragment" />
</code>```

Inside that fragment in an external layout I've created a TabHost like this:

```<code><TabHost
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:id="@+id/tabHost">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical">

        <TabWidget
            android:id="@android:id/tabs"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:visibility="visible" />

        <FrameLayout
            android:id="@android:id/tabcontent"
            android:layout_width="match_parent"
            android:layout_height="match_parent">

            <fragment
                android:id="@+id/first"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:name="com.x.x.First"
                tools:layout="@layout/first" />

            <fragment
                android:id="@+id/second"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:name="com.x.x.Second"
                tools:layout="@layout/second" />

        </FrameLayout>
    </LinearLayout>
</TabHost>
</code>```

The problem is that I need to run a method inside the "First" class when a button inside the "Main" class has been clicked.

I've been struggling with this problem since yesterday, is there any solution?

Thank you.

答:
From your Activity, get the Fragment and call the method.</p>

```<code>Fragment fragment = getSupportFragmentManager().findFragmentById(R.id.first);
if(fragment != null){
  ((First)fragment).yourMethod();
}
</code>```

Body:
I have a page divided like this: there is the "Main" layout which holds a fragment

<fragment
    android:name="com.x.x.FirstFragment"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:id="@+id/firstFragment"
    tools:layout="@layout/first_fragment" />

Inside that fragment in an external layout I've created a TabHost like this:

<TabHost
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:id="@+id/tabHost">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical">

        <TabWidget
            android:id="@android:id/tabs"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:visibility="visible" />

        <FrameLayout
            android:id="@android:id/tabcontent"
            android:layout_width="match_parent"
            android:layout_height="match_parent">

            <fragment
                android:id="@+id/first"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:name="com.x.x.First"
                tools:layout="@layout/first" />

            <fragment
                android:id="@+id/second"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:name="com.x.x.Second"
                tools:layout="@layout/second" />

        </FrameLayout>
    </LinearLayout>
</TabHost>

The problem is that I need to run a method inside the "First" class when a button inside the "Main" class has been clicked.

I've been struggling with this problem since yesterday, is there any solution?

Thank you.

Body:
From your Activity, get the Fragment and call the method.

Fragment fragment = getSupportFragmentManager().findFragmentById(R.id.first);
if(fragment != null){
  ((First)fragment).yourMethod();
}


问:
Is it possible to inherit css class?
I have two css classes:

```<code>magrin{
    margin-top:35px;
    background-color:red;
}

#MainContent {
    margin: 0 .3em;
    font-size: .8em;
}
</code>```

Is it possible to make #MainContent class inherit magrin class?

答:
There is no such thing as far as I know. But you make magrin a class by adding a . to the beginning of the rule, you can add it to your element with the ID MainContent.
IDs must be unique, but an element can have both an ID and one (or several) class(es).

Title: Is it possible to inherit css class?

Body:
I have two css classes:

magrin{
    margin-top:35px;
    background-color:red;
}

#MainContent {
    margin: 0 .3em;
    font-size: .8em;
}

Is it possible to make #MainContent class inherit magrin class?


问:
Laravel get file content
```<code>Route::get('marquee', function(){
    echo  File::get('\storage\app\marquee.json');
});
</code>```

I have a json file place inside storage/app

My question is how can I read this content from controller or route?

答:
You can store files in your storage folder in Laravel:</p>

```<code>$path = storage_path() . "/json/${filename}.json";

$json = json_decode(file_get_contents($path), true);
</code>```

Title: Laravel get file content

Body:
Route::get('marquee', function(){
    echo  File::get('\storage\app\marquee.json');
});

I have a json file place inside storage/app

My question is how can I read this content from controller or route?

Body:
You can store files in your storage folder in Laravel:

$path = storage_path() . "/json/${filename}.json";

$json = json_decode(file_get_contents($path), true);


问:
Call a soap webservice in android
I need to make a call to a soap webservice in an android device. I have been reading a lot of articles in stackoverflow and on other pages, watching videos... But I've tried everythin and I can't make it work in my android device, and I can't test in on an emulator, because my computer can't handle any of them, so I don't know if the error is on the code or if it's a problem of my android device.

The layout xml are only an EditText, a Button, and a TextView.

In this link you can see the request xml I need to send to the webservice (should I use SOAP 1.1 or SOAP 1.2 ?)
http://www.webservicex.net/globalweather.asmx?op=GetCitiesByCountry

This is my actual code, and I have tried many other ways, and none of them have worked for me. Any help? (url, namespace, soap_action and method_name values are okey, aren't they?)

```<code>package com.example.doazdoas.webservice_prueba;

    import android.app.Activity;
    import android.os.Bundle;
    import android.util.Log;
    import android.view.View;
    import android.widget.Button;
    import android.widget.TextView;

    import org.ksoap2.SoapEnvelope;
    import org.ksoap2.serialization.SoapObject;
    import org.ksoap2.serialization.SoapSerializationEnvelope;
    import org.ksoap2.transport.HttpTransportSE;

    import android.os.AsyncTask;
    import android.widget.Toast;

    import static android.content.ContentValues.TAG;

   public class MainActivity extends Activity{
    private TextView textResult;
    private Button buttonSend;

    String NAMESPACE = "http://www.webserviceX.NET/";
    String METHOD_NAME = "GetCitiesByCountry";
    String SOAP_ACTION = NAMESPACE + METHOD_NAME;
    String URL = "http://www.webservicex.net/globalweather.asmx?WSDL";

    private Object resultsRequestSOAP = null;

    HttpTransportSE androidHttpTransport;

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

        textResult = (TextView)findViewById(R.id.textResultado);
        buttonSend = (Button)findViewById(R.id.buttonEnviar);
        //setContentView(tv);
    }

    public void onClickEnviar(View view){
        AsyncCallWS task = new AsyncCallWS();
        task.execute();
    }

    private class AsyncCallWS extends AsyncTask<Void, Void, Void> {

        @Override
        protected void onPreExecute() {
            Log.i(TAG, "onPreExecute");
        }

        @Override
        protected Void doInBackground(Void... params) {
            Log.i(TAG, "doInBackground");
            sendRequest();
            return null;
        }

        @Override
        protected void onPostExecute(Void result) {
            Log.i(TAG, "onPostExecute");
            Log.d("dump Request: " ,androidHttpTransport.requestDump);
            Log.d("dump response: " ,androidHttpTransport.responseDump);
        }

    }

    public void sendRequest(){
        SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME);

        //SoapObject
        request.addProperty("@CountryName", "SPAIN");
        SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
        envelope.setOutputSoapObject(request);

        androidHttpTransport = new HttpTransportSE(URL);
        try
        {
            androidHttpTransport.call(SOAP_ACTION, envelope);
            resultsRequestSOAP =  envelope.getResponse();
            String[] results = (String[])  resultsRequestSOAP;
            textResult.setText( results[0]);
        }
        catch (Exception aE)
        {
            aE.printStackTrace ();
        }
    }
}
</code>```

答:
Have you considered making the soap requests without use of libraries? I had the same problem earlier and it led me to discovering that libraries will make your work harder, especially when it comes to making changes in the structure of the request. This is how you make a soap request without use of libraries:
First of all you will need to know how to make use of SOAP Ui which is a windows application. You can import your wsdl file here and if it's syntax us correct, then you will get a screen showing the request body for your webservice. You can enter test values and you will get a response structure. This link will guide you on how to use soap ui https://www.soapui.org/soap-and-wsdl/working-with-wsdls.html

Now on to the android code :

We will create a class named runTask which extends async task and use http to send the request body and get request response :

```<code> private class runTask extends AsyncTask<String, String, String> {

        private String response;
        String string = "your string parameter"
        String SOAP_ACTION = "your soap action here";

        String stringUrl = "http://your_url_here";
        //if you experience a problem with url remove the '?wsdl' ending

        @Override
        protected String doInBackground(String... params) {

            try {

                        //paste your request structure here as the String body(copy it exactly as it is in soap ui)
                        //assuming that this is your request body

                String body = "<soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">" +
                                "<soap:Body>"+
                                "<GetCitiesByCountryResponse xmlns="http://www.webserviceX.NET">"+
                                "<GetCitiesByCountryResult>"+string+"</GetCitiesByCountryResult>"+
                                "</GetCitiesByCountryResponse>"+
                                "</soap:Body>"+
                                "</soap:Envelope>";

                try {
                    URL url = new URL(stringUrl);
                    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
                    conn.setRequestMethod("POST");
                    conn.setDoOutput(true);
                    conn.setDefaultUseCaches(false);
                    conn.setRequestProperty("Accept", "text/xml");
                    conn.setRequestProperty("SOAPAction", SOAP_ACTION);

                    //push the request to the server address

                    OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
                    wr.write(body);
                    wr.flush();

                    //get the server response

                    BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
                    StringBuilder builder = new StringBuilder();
                    String line = null;

                    while ((line = reader.readLine()) != null) {

                        builder.append(line);
                        response = builder.toString();//this is the response, parse it in onPostExecute

                    }

                } catch (Exception e) {

                    e.printStackTrace();
                } finally {

                    try {

                        reader.close();
                    } catch (Exception e) {

                        e.printStackTrace();
                    }
                }

            } catch (Exception e) {

                e.printStackTrace();
            }

            return response;
        }

        /**
         * @see AsyncTask#onPostExecute(Object)
         */
        @Override
        protected void onPostExecute(String result) {

           try {

              Toast.makeText(this,"Response "+ result,Toast.LENGTH_LONG).show();

            } catch (Exception e) {
                e.printStackTrace();
            }
        }
</code>```

Now just execute the class and watch the magic happen:

```<code>runTask runner = new runTask();
runner.execute();
</code>```

You can parse the response using a DOM or SAX parser to get desired values.
Feel free to ask for further clarification.

Title: Call a soap webservice in android

Body:
I need to make a call to a soap webservice in an android device. I have been reading a lot of articles in stackoverflow and on other pages, watching videos... But I've tried everythin and I can't make it work in my android device, and I can't test in on an emulator, because my computer can't handle any of them, so I don't know if the error is on the code or if it's a problem of my android device.

The layout xml are only an EditText, a Button, and a TextView.

In this link you can see the request xml I need to send to the webservice (should I use SOAP 1.1 or SOAP 1.2 ?)
http://www.webservicex.net/globalweather.asmx?op=GetCitiesByCountry

This is my actual code, and I have tried many other ways, and none of them have worked for me. Any help? (url, namespace, soap_action and method_name values are okey, aren't they?)

package com.example.doazdoas.webservice_prueba;

    import android.app.Activity;
    import android.os.Bundle;
    import android.util.Log;
    import android.view.View;
    import android.widget.Button;
    import android.widget.TextView;

    import org.ksoap2.SoapEnvelope;
    import org.ksoap2.serialization.SoapObject;
    import org.ksoap2.serialization.SoapSerializationEnvelope;
    import org.ksoap2.transport.HttpTransportSE;

    import android.os.AsyncTask;
    import android.widget.Toast;

    import static android.content.ContentValues.TAG;

   public class MainActivity extends Activity{
    private TextView textResult;
    private Button buttonSend;

    String NAMESPACE = "http://www.webserviceX.NET/";
    String METHOD_NAME = "GetCitiesByCountry";
    String SOAP_ACTION = NAMESPACE + METHOD_NAME;
    String URL = "http://www.webservicex.net/globalweather.asmx?WSDL";

    private Object resultsRequestSOAP = null;

    HttpTransportSE androidHttpTransport;

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

        textResult = (TextView)findViewById(R.id.textResultado);
        buttonSend = (Button)findViewById(R.id.buttonEnviar);
        //setContentView(tv);
    }

    public void onClickEnviar(View view){
        AsyncCallWS task = new AsyncCallWS();
        task.execute();
    }

    private class AsyncCallWS extends AsyncTask<Void, Void, Void> {

        @Override
        protected void onPreExecute() {
            Log.i(TAG, "onPreExecute");
        }

        @Override
        protected Void doInBackground(Void... params) {
            Log.i(TAG, "doInBackground");
            sendRequest();
            return null;
        }

        @Override
        protected void onPostExecute(Void result) {
            Log.i(TAG, "onPostExecute");
            Log.d("dump Request: " ,androidHttpTransport.requestDump);
            Log.d("dump response: " ,androidHttpTransport.responseDump);
        }

    }

    public void sendRequest(){
        SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME);

        //SoapObject
        request.addProperty("@CountryName", "SPAIN");
        SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
        envelope.setOutputSoapObject(request);

        androidHttpTransport = new HttpTransportSE(URL);
        try
        {
            androidHttpTransport.call(SOAP_ACTION, envelope);
            resultsRequestSOAP =  envelope.getResponse();
            String[] results = (String[])  resultsRequestSOAP;
            textResult.setText( results[0]);
        }
        catch (Exception aE)
        {
            aE.printStackTrace ();
        }
    }
}

Body:
Have you considered making the soap requests without use of libraries? I had the same problem earlier and it led me to discovering that libraries will make your work harder, especially when it comes to making changes in the structure of the request. This is how you make a soap request without use of libraries:
First of all you will need to know how to make use of SOAP Ui which is a windows application. You can import your wsdl file here and if it's syntax us correct, then you will get a screen showing the request body for your webservice. You can enter test values and you will get a response structure. This link will guide you on how to use soap ui https://www.soapui.org/soap-and-wsdl/working-with-wsdls.html

Now on to the android code :

We will create a class named runTask which extends async task and use http to send the request body and get request response :

 private class runTask extends AsyncTask<String, String, String> {

        private String response;
        String string = "your string parameter"
        String SOAP_ACTION = "your soap action here";

        String stringUrl = "http://your_url_here";
        //if you experience a problem with url remove the '?wsdl' ending

        @Override
        protected String doInBackground(String... params) {

            try {

                        //paste your request structure here as the String body(copy it exactly as it is in soap ui)
                        //assuming that this is your request body

                String body = "<soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">" +
                                "<soap:Body>"+
                                "<GetCitiesByCountryResponse xmlns="http://www.webserviceX.NET">"+
                                "<GetCitiesByCountryResult>"+string+"</GetCitiesByCountryResult>"+
                                "</GetCitiesByCountryResponse>"+
                                "</soap:Body>"+
                                "</soap:Envelope>";

                try {
                    URL url = new URL(stringUrl);
                    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
                    conn.setRequestMethod("POST");
                    conn.setDoOutput(true);
                    conn.setDefaultUseCaches(false);
                    conn.setRequestProperty("Accept", "text/xml");
                    conn.setRequestProperty("SOAPAction", SOAP_ACTION);

                    //push the request to the server address

                    OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
                    wr.write(body);
                    wr.flush();

                    //get the server response

                    BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
                    StringBuilder builder = new StringBuilder();
                    String line = null;

                    while ((line = reader.readLine()) != null) {

                        builder.append(line);
                        response = builder.toString();//this is the response, parse it in onPostExecute

                    }

                } catch (Exception e) {

                    e.printStackTrace();
                } finally {

                    try {

                        reader.close();
                    } catch (Exception e) {

                        e.printStackTrace();
                    }
                }

            } catch (Exception e) {

                e.printStackTrace();
            }

            return response;
        }

        /**
         * @see AsyncTask#onPostExecute(Object)
         */
        @Override
        protected void onPostExecute(String result) {

           try {

              Toast.makeText(this,"Response "+ result,Toast.LENGTH_LONG).show();

            } catch (Exception e) {
                e.printStackTrace();
            }
        }

Now just execute the class and watch the magic happen:

runTask runner = new runTask();
runner.execute();

You can parse the response using a DOM or SAX parser to get desired values.
Feel free to ask for further clarification.


问:
use cocoapods with xamarin
is this really to use cocoacontrols with xamarin? For example this one:
http://www.cocoacontrols.com/platforms/ios/controls/kycirclemenu
I know that I can create something like circle menu with UICollectionView (http://docs.xamarin.com/guides/ios/user_interface/introduction_to_collection_views)
But anyway wondering is this really use cocoapods.

Thanks,
Yaro

答:
You can bind Objective C based Cocoapods to xamarin and its officially supported (https://developer.xamarin.com/guides/ios/advanced_topics/binding_objective-c/walkthrough/)

you have to find the github repo of the cocoapod and convert that into a static library(.a) file

you have to use that static library to create binding library in Xam studio

then you are good to use in xamarin.ios

But swift based library is not officially supported in Xamarin.So you can't use Swift based cocoapods directly in xamarin as you do But there are workarounds

You can bridge the Swift framework to C# using Objective C i.e expose the Swift APIs using Objective C and convert that into .a static library and then binding library

Try porting the Swift to C# and it should be faster as well

As Stephane Delcroix quoted

Look if there are any existing monotouch bindings available here before starting to port

Title: use cocoapods with xamarin


问:
Intercept "git commit -a(m)"
I like the fine-grained commits that the git index allow, i.e. the staging of individual files or even hunks through git add before the final commit. Unfortunately, sometimes after spending some time staging a particular commit, muscle-memory kicks in so that I git commit -a -m "msg". Then I either have to live with it, or jump through some reset or --amend hoops.

Is there a way for me to (ideally, globally) configure Git so that if I issue a git commit -a, it gets intercepted? Maybe a script asking me to confirm if I really want to commit all? I've thought about delegating the commit operation to a wrapper script (e.g., "gitcommit"), but do not think that will work very well as it does not stop me from doing a git commit -a -m "msg", which is the problem in the first place.

答:
One way would be to make git an alias that runs a script you create that looks at the command line arguments and lets you know if you typed commit followed by -a on the command line.

Personally, I never use commit -a and instead always use git add -u plus git commit.

Title: Intercept "git commit -a(m)"


答:
Class inheritance is possible with SASS. You may want to check it out, works like this:

```<code>.magrin{
    margin-top:35px;
    background-color:red;
}

.MainContent {
    @extend .magrin;
    margin: 0 .3em;
    font-size: .8em;
}
</code>```

Read more in http://sass-lang.com/guide

Title: Is it possible to inherit css class?

Body:
Class inheritance is possible with SASS. You may want to check it out, works like this:

.magrin{
    margin-top:35px;
    background-color:red;
}

.MainContent {
    @extend .magrin;
    margin: 0 .3em;
    font-size: .8em;
}

Read more in http://sass-lang.com/guide


答:
you can apply magrin styles on #MainContent like this

```<code>magrin, #MainContent {
    margin-top:35px;
    background-color:red;
}

#MainContent {
    margin: 0 .3em;
    font-size: .8em;
}
</code>```

Title: Is it possible to inherit css class?

Body:
you can apply magrin styles on #MainContent like this

magrin, #MainContent {
    margin-top:35px;
    background-color:red;
}

#MainContent {
    margin: 0 .3em;
    font-size: .8em;
}