问:
My Application Is crashing when I'm using Daily repeating Alarm
I am trying to fire alarm everyday on fix time but my application is crashing when click the button to fire alarm.
Please help to find solution. Thanks in Advance .

Here is my Main Activity code :-

```<code>import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.Intent;
import java.util.Calendar;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;

public class MainActivity extends AppCompatActivity {

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

        Button button = (Button) findViewById(R.id.button);
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                Calendar calendar = Calendar.getInstance();

                calendar.set(Calendar.HOUR_OF_DAY,15);
                calendar.set(Calendar.MINUTE,9);
                calendar.set(Calendar.SECOND,20);

                Intent intent = new Intent(getApplicationContext(), Notification_receiver.class);

                PendingIntent pendingIntent = PendingIntent.getBroadcast(getApplicationContext(),100,intent,PendingIntent.FLAG_UPDATE_CURRENT);

                AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);

                alarmManager.setInexactRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(),AlarmManager.INTERVAL_DAY,pendingIntent);

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

Here is my Notification_receiver.java file:-

```<code>import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.support.v4.app.NotificationCompat;

class Notification_receiver extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {

        NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);

        Intent repeating_intent = new Intent(context,Repeating_activity.class);
        repeating_intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);

        PendingIntent pendingIntent = PendingIntent .getActivity(context,100,repeating_intent,PendingIntent.FLAG_UPDATE_CURRENT);

        NotificationCompat.Builder builder = new NotificationCompat.Builder(context)
                .setContentIntent(pendingIntent)
                .setSmallIcon(android.R.drawable.sym_def_app_icon)
                .setContentTitle("Notification Tittle")
                .setContentText("Notification Text")
                .setAutoCancel(true);

        notificationManager.notify(100,builder.build());
    }
}
</code>```

Here is Manifest if needed :-

```<code><manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.hacker.timernotification">

    <uses-permission android:name="com.android.alarm.permission.SET_ALARM"/> //I tried with and without this but still crashing my app
    <uses-permission android:name="android.permission.WAKE_LOCK"/> // this is at the time of fire alarm

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

        <activity android:name=".Repeating_activity"/>
        <receiver android:name=".Notification_receiver"></receiver>
            <!--android:enabled="true"
            android:exported="true-->"/>
    </application>

</manifest>
</code>```

Here is Repeating_activity.java file :-

```<code>import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;

class Repeating_activity extends AppCompatActivity {
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.repeating_activity_layout);
    }
}
</code>```

activity_main.xml and repeating_activity_layout.xml I have in my projecte not pasting here because I don't think it's need.

Here is error getting after crashing my application :-

```<code>16297-16297/com.example.hacker.timernotification E/AndroidRuntime: FATAL EXCEPTION: main
                                                                                java.lang.RuntimeException: Unable to instantiate receiver com.example.hacker.timernotification.Notification_receiver: java.lang.IllegalAccessException: access to class not allowed
                                                                                at android.app.ActivityThread.handleReceiver(ActivityThread.java:2436)
                                                                                at android.app.ActivityThread.access$1600(ActivityThread.java:157)
                                                                                at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1365)
                                                                                at android.os.Handler.dispatchMessage(Handler.java:99)
                                                                                at android.os.Looper.loop(Looper.java:176)
                                                                                at android.app.ActivityThread.main(ActivityThread.java:5317)
                                                                                at java.lang.reflect.Method.invokeNative(Native Method)
                                                                                at java.lang.reflect.Method.invoke(Method.java:511)
                                                                                at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1102)
                                                                                at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:869)
                                                                                at dalvik.system.NativeStart.main(Native Method)
                                                                                Caused by: java.lang.IllegalAccessException: access to class not allowed
                                                                                at java.lang.Class.newInstanceImpl(Native Method)
                                                                                at java.lang.Class.newInstance(Class.java:1319)
                                                                                at android.app.ActivityThread.handleReceiver(ActivityThread.java:2431)
                                                                                at android.app.ActivityThread.access$1600(ActivityThread.java:157)
                                                                                at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1365)
                                                                                at android.os.Handler.dispatchMessage(Handler.java:99)
                                                                                at android.os.Looper.loop(Looper.java:176)
                                                                                at android.app.ActivityThread.main(ActivityThread.java:5317)
                                                                                at java.lang.reflect.Method.invokeNative(Native Method)
                                                                                at java.lang.reflect.Method.invoke(Method.java:511)
                                                                                at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1102)
                                                                                at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:869)
                                                                                at dalvik.system.NativeStart.main(Native Method)
</code>```

Please help to find solution . Any help will be Appreciated

答:
Make your "Notification_receiver" class  public like this

```<code>    public class Notification_receiver extends BroadcastReceiver
{
  // your code
}
</code>```

it should work.

Body:
I am trying to fire alarm everyday on fix time but my application is crashing when click the button to fire alarm.
Please help to find solution. Thanks in Advance .

Here is my Main Activity code :-

import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.Intent;
import java.util.Calendar;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;

public class MainActivity extends AppCompatActivity {

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

        Button button = (Button) findViewById(R.id.button);
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                Calendar calendar = Calendar.getInstance();

                calendar.set(Calendar.HOUR_OF_DAY,15);
                calendar.set(Calendar.MINUTE,9);
                calendar.set(Calendar.SECOND,20);

                Intent intent = new Intent(getApplicationContext(), Notification_receiver.class);

                PendingIntent pendingIntent = PendingIntent.getBroadcast(getApplicationContext(),100,intent,PendingIntent.FLAG_UPDATE_CURRENT);

                AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);

                alarmManager.setInexactRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(),AlarmManager.INTERVAL_DAY,pendingIntent);

            }
        });
    }
}

Here is my Notification_receiver.java file:-

import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.support.v4.app.NotificationCompat;

class Notification_receiver extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {

        NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);

        Intent repeating_intent = new Intent(context,Repeating_activity.class);
        repeating_intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);

        PendingIntent pendingIntent = PendingIntent .getActivity(context,100,repeating_intent,PendingIntent.FLAG_UPDATE_CURRENT);

        NotificationCompat.Builder builder = new NotificationCompat.Builder(context)
                .setContentIntent(pendingIntent)
                .setSmallIcon(android.R.drawable.sym_def_app_icon)
                .setContentTitle("Notification Tittle")
                .setContentText("Notification Text")
                .setAutoCancel(true);

        notificationManager.notify(100,builder.build());
    }
}

Here is Manifest if needed :-

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.hacker.timernotification">

    <uses-permission android:name="com.android.alarm.permission.SET_ALARM"/> //I tried with and without this but still crashing my app
    <uses-permission android:name="android.permission.WAKE_LOCK"/> // this is at the time of fire alarm

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

        <activity android:name=".Repeating_activity"/>
        <receiver android:name=".Notification_receiver"></receiver>
            "/>
    </application>

</manifest>

Here is Repeating_activity.java file :-

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;

class Repeating_activity extends AppCompatActivity {
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.repeating_activity_layout);
    }
}

activity_main.xml and repeating_activity_layout.xml I have in my projecte not pasting here because I don't think it's need.

Here is error getting after crashing my application :-

16297-16297/com.example.hacker.timernotification E/AndroidRuntime: FATAL EXCEPTION: main
                                                                                java.lang.RuntimeException: Unable to instantiate receiver com.example.hacker.timernotification.Notification_receiver: java.lang.IllegalAccessException: access to class not allowed
                                                                                at android.app.ActivityThread.handleReceiver(ActivityThread.java:2436)
                                                                                at android.app.ActivityThread.access$1600(ActivityThread.java:157)
                                                                                at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1365)
                                                                                at android.os.Handler.dispatchMessage(Handler.java:99)
                                                                                at android.os.Looper.loop(Looper.java:176)
                                                                                at android.app.ActivityThread.main(ActivityThread.java:5317)
                                                                                at java.lang.reflect.Method.invokeNative(Native Method)
                                                                                at java.lang.reflect.Method.invoke(Method.java:511)
                                                                                at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1102)
                                                                                at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:869)
                                                                                at dalvik.system.NativeStart.main(Native Method)
                                                                                Caused by: java.lang.IllegalAccessException: access to class not allowed
                                                                                at java.lang.Class.newInstanceImpl(Native Method)
                                                                                at java.lang.Class.newInstance(Class.java:1319)
                                                                                at android.app.ActivityThread.handleReceiver(ActivityThread.java:2431)
                                                                                at android.app.ActivityThread.access$1600(ActivityThread.java:157)
                                                                                at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1365)
                                                                                at android.os.Handler.dispatchMessage(Handler.java:99)
                                                                                at android.os.Looper.loop(Looper.java:176)
                                                                                at android.app.ActivityThread.main(ActivityThread.java:5317)
                                                                                at java.lang.reflect.Method.invokeNative(Native Method)
                                                                                at java.lang.reflect.Method.invoke(Method.java:511)
                                                                                at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1102)
                                                                                at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:869)
                                                                                at dalvik.system.NativeStart.main(Native Method)

Please help to find solution . Any help will be Appreciated

Body:
Make your "Notification_receiver" class  public like this

    public class Notification_receiver extends BroadcastReceiver
{
  // your code
}

it should work.


来源: stackexchange

问:
Gatling: check binary response not empty
I'm doing some tests with Gatling using Scala. I'm trying to check whether a response body that is returned is not empty.

I'm doing it like this:

```<code>def getImages: ChainBuilder = feed(credentials)
     .exec(http("Get Image")
     .get(GET_MY_URI)
     .queryParam("guid", "${branch}")
     .queryParam("t", "0.458654")
     .check(status.is(200))
     .check(bodyString.transform(_.size > 1).is(true)))
</code>```

But it's not working. I get:

```<code>java.nio.charset.MalformedInputException: Input length = 1
</code>```

Does somebody know how to achieve what I'm trying?

答:
Replace

```<code>.check(bodyString.transform(_.size > 1).is(true)))
</code>```

with

```<code>.check(bodyBytes.exists)
</code>```

All the DSL is explained here: https://gatling.io/docs/current/cheat-sheet/

ContentLicense: CC BY-SA 3.0

Body:
I'm doing some tests with Gatling using Scala. I'm trying to check whether a response body that is returned is not empty.

I'm doing it like this:

def getImages: ChainBuilder = feed(credentials)
     .exec(http("Get Image")
     .get(GET_MY_URI)
     .queryParam("guid", "${branch}")
     .queryParam("t", "0.458654")
     .check(status.is(200))
     .check(bodyString.transform(_.size > 1).is(true)))

But it's not working. I get:

java.nio.charset.MalformedInputException: Input length = 1

Does somebody know how to achieve what I'm trying?

Body:
Replace

.check(bodyString.transform(_.size > 1).is(true)))

with

.check(bodyBytes.exists)

All the DSL is explained here: https://gatling.io/docs/current/cheat-sheet/


问:
Firefox 57+ legacy extensions nuked: how can I obtain multiple tab rows (which TabMixPlus enabled)
I am thinking maybe editing the prefs.js file?  See post here for why. Thanks. </p>

答:
I found a solution. It is not the same as Tab Mix and lacks a whole bunch of usefulness, but it does put the tabs on multiple rows.

First, locate your profile directory (see e.g. Mozilla Support), mine is at

```<code>~/.mozilla/firefox/xxxxxxxx.default
</code>```

(where xxxxxxxx is some random characters), on a typical Linux system.

If it does not exist yet, create a subfolder chrome and within that a file userChrome.css (I think the capitalization of the filename does matter, but I did not test that):

```<code>~/.mozilla/firefox/xxxxxxxx.default/chrome/userChrome.css
</code>```

In userChrome.css, add the following code, which I got from this source:

```<code>.tabbrowser-tab {
    flex-grow:1;
    min-width:150px;
}
.tabbrowser-tab,.tab-background {
    height:29px;
}
.tab-stack {
    width: 100%;
}
.tabbrowser-tabs .scrollbox-innerbox {
    display: flex;
    flex-wrap: wrap;
}
.tabbrowser-tabs .arrowscrollbox-scrollbox {
    overflow: visible;
    display: block;
}
.tabbrowser-tabs .scrollbutton-up,.tabbrowser-tabs .scrollbutton-down,#alltabs-button{
    display: none;
}
</code>```

After saving, you need to restart Firefox.

Bonus: another nice feature that Tab Mix brought, is the placement of a close button on each separate tab. This can be done by adding another piece of code to the same file (from this source)

```<code>.tab-close-button:not([pinned="true"]) {
    display: -moz-box !important;
}
</code>```

Body:
I found a solution. It is not the same as Tab Mix and lacks a whole bunch of usefulness, but it does put the tabs on multiple rows.

First, locate your profile directory (see e.g. Mozilla Support), mine is at

~/.mozilla/firefox/xxxxxxxx.default

(where xxxxxxxx is some random characters), on a typical Linux system.

If it does not exist yet, create a subfolder chrome and within that a file userChrome.css (I think the capitalization of the filename does matter, but I did not test that):

~/.mozilla/firefox/xxxxxxxx.default/chrome/userChrome.css

In userChrome.css, add the following code, which I got from this source:

.tabbrowser-tab {
    flex-grow:1;
    min-width:150px;
}
.tabbrowser-tab,.tab-background {
    height:29px;
}
.tab-stack {
    width: 100%;
}
.tabbrowser-tabs .scrollbox-innerbox {
    display: flex;
    flex-wrap: wrap;
}
.tabbrowser-tabs .arrowscrollbox-scrollbox {
    overflow: visible;
    display: block;
}
.tabbrowser-tabs .scrollbutton-up,.tabbrowser-tabs .scrollbutton-down,#alltabs-button{
    display: none;
}

After saving, you need to restart Firefox.

Bonus: another nice feature that Tab Mix brought, is the placement of a close button on each separate tab. This can be done by adding another piece of code to the same file (from this source)

.tab-close-button:not([pinned="true"]) {
    display: -moz-box !important;
}


问:
Wordpress - Modify WooCommerce Germanized Template
I'm working with WooCommerce including the WooCommerzce Germanized Plugin.
The Plugin changes a lot of WooCommerce to make it safe for usage in Germany.

Now I need to modify a template file of the plugin.  Whats the best way to make the changes? I don't want to modify the template itself to keep it safe for updates.

答:
In order to override any WooCommerce plugin template you should create a folder in your active theme named after the plugin you are going to modify. Then follow the template folders structure ignoring just the folder templates and copy the desired file there.

For example, I needed to modify the WooCommerce Germanized Pro template based in /plugins/woocommerce-germanized-pro/templates/checkout/multistep/data.php. To modify it I have copied it to my theme: /themename/woocommerce-germanized-pro/checkout/multistep/data.php -- this way it will override an original template file.

Good luck!


问:
In javascript, when creating properties, which is the right way or better syntax?
properties(keys) can be accessed and set using the dot notation as well as the square brackets. any advice when to use dot prototype syntax</p>

```<code>var myObj = {};
myObj.myProp1 = 'value1'; //works, an expando property
myObj[myProp2] = 'value2'; // FAILS, myProp2 is undefined
myObj["myProp2"] = 'value2'; // works, an expando property
myObj[2010]= 'value'; //note the key is number, still works, an expando property??
myObj.2010 = 'value'; // FAILS. to use dot notation, key must be a string

myObj.prototype.myProp3 = 'value3' // whats the advantage?
</code>```

答: The property addition should be either myObj.myProp or myObj["myProp"]. This is the ideally followed scenario and a good practice when used in javascript.

ContentLicense: CC BY-SA 2.5

Body:
properties(keys) can be accessed and set using the dot notation as well as the square brackets. any advice when to use dot prototype syntax

var myObj = {};
myObj.myProp1 = 'value1'; //works, an expando property
myObj[myProp2] = 'value2'; // FAILS, myProp2 is undefined
myObj["myProp2"] = 'value2'; // works, an expando property
myObj[2010]= 'value'; //note the key is number, still works, an expando property??
myObj.2010 = 'value'; // FAILS. to use dot notation, key must be a string

myObj.prototype.myProp3 = 'value3' // whats the advantage?


问:
How do I invalidate the old images when request for a new one is initiated in React?
Have a look my code below, I have create a pen for it too: https://codepen.io/segmentationfaulter/pen/YEEaxK

The problem is that when I click on change image button, the old image stays there for a while until the new image is loaded. What I want is that the old image is invalidated straight away and empty space is shown for the new image. How can I achieve this in react? If you can't spot the issue, try opening it in private mode so that caching doesn't affect it.

const images = [
  'http://via.placeholder.com/550x550',
  'http://via.placeholder.com/750x750'
]

class MyImage extends React.Component {
  constructor() {
    super()
    this.state = {
      currentImageIndex: 0
    }
  }
  changeImage() {
    this.setState((prevState) => {
      if (prevState.currentImageIndex) {
        return {
          currentImageIndex: 0
        }
      } else {
        return {
          currentImageIndex: 1
        }
      }
    })
  }
  render() {
    return ( <
      div >
      <
      img src = {
        this.props.images[this.state.currentImageIndex]
      }
      /> <
      button onClick = {
        this.changeImage.bind(this)
      } >
      change image <
      /button> <
      /div>
    )
  }
}

ReactDOM.render( < MyImage images = {
      images
    }
    />, document.getElementById('root'))```
<pre class="snippet-code-css lang-css prettyprint-override"><code>img {
  display: block;
}

button {
  margin-top: 15px;
}</code>```

```

答:
You could use, for example, onLoad prop from img where you toggle a loading in state so you can render the placeholder.

The strategy around it is:

display the placeholder and hide the image if loading is true

hide the loading when the image has been loaded.

PS: I added a timeout so you can see the placeholder in action.

const images = [
  'http://via.placeholder.com/550x550',
  'http://via.placeholder.com/750x750'
]

class Images extends React.Component {
  constructor() {
    super()

    this.state = {
      currentImageIndex: 0,
      loading: true,
    }
  }

  handleLoad() {
    setTimeout(() => {
      this.setState({ loading: false })
    }, 1000)
  }

  changeImage() {
    this.setState((prevState) => {
      if (prevState.currentImageIndex) {
        return {
          currentImageIndex: 0
        }
      }
      return {
        currentImageIndex: 1
      }
    })
  }

  render() {
    const { loading, currentImageIndex } = this.state

    return (

        {loading &&
placeholder comes here
}

        <button onClick={this.changeImage.bind(this)}>
          change image
        </button>

    )
  }
}

ReactDOM.render(
  <Images />,
  document.getElementById('root')
)```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>

<div id="root"></div></code>```

Body:
Have a look my code below, I have create a pen for it too: https://codepen.io/segmentationfaulter/pen/YEEaxK

The problem is that when I click on change image button, the old image stays there for a while until the new image is loaded. What I want is that the old image is invalidated straight away and empty space is shown for the new image. How can I achieve this in react? If you can't spot the issue, try opening it in private mode so that caching doesn't affect it.

const images = [
  'http://via.placeholder.com/550x550',
  'http://via.placeholder.com/750x750'
]

class MyImage extends React.Component {
  constructor() {
    super()
    this.state = {
      currentImageIndex: 0
    }
  }
  changeImage() {
    this.setState((prevState) => {
      if (prevState.currentImageIndex) {
        return {
          currentImageIndex: 0
        }
      } else {
        return {
          currentImageIndex: 1
        }
      }
    })
  }
  render() {
    return ( <
      div >
      <
      img src = {
        this.props.images[this.state.currentImageIndex]
      }
      /> <
      button onClick = {
        this.changeImage.bind(this)
      } >
      change image <
      /button> <
      /div>
    )
  }
}

ReactDOM.render( < MyImage images = {
      images
    }
    />, document.getElementById('root'))

img {
  display: block;
}

button {
  margin-top: 15px;
}

Body:
You could use, for example, onLoad prop from img where you toggle a loading in state so you can render the placeholder.

The strategy around it is:

display the placeholder and hide the image if loading is true

hide the loading when the image has been loaded.

PS: I added a timeout so you can see the placeholder in action.

const images = [
  'http://via.placeholder.com/550x550',
  'http://via.placeholder.com/750x750'
]

class Images extends React.Component {
  constructor() {
    super()

    this.state = {
      currentImageIndex: 0,
      loading: true,
    }
  }

  handleLoad() {
    setTimeout(() => {
      this.setState({ loading: false })
    }, 1000)
  }

  changeImage() {
    this.setState((prevState) => {
      if (prevState.currentImageIndex) {
        return {
          currentImageIndex: 0
        }
      }
      return {
        currentImageIndex: 1
      }
    })
  }

  render() {
    const { loading, currentImageIndex } = this.state

    return (
      <div>
        {loading && <div>placeholder comes here</div>}
        <img
          onLoad={this.handleLoad.bind(this)}
          src={images[currentImageIndex]}
          style={{ display: loading ? 'none' : 'block' }}
        />
        <button onClick={this.changeImage.bind(this)}>
          change image
        </button>
      </div>
    )
  }
}

ReactDOM.render(
  <Images />,
  document.getElementById('root')
)

<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>

<div id="root"></div>


问:
Laravel: How to update packages in storage/framework
I have removed a package with composer remove and it's now removed from composer.json and composer.lock files and also removed from vendor directory. But I noticed that it's still listed in these two files: storage/framework/packages.php and storage/framework/services.php. How can I update/rebuild these files?

Also, when I run php artisan in the root of my project, I get this error:

[Symfony\Component\Debug\Exception\FatalThrowableError]
    Class 'Morilog\Jalali\JalaliServiceProvider' not found

I searched in all the files of the project and found JalaliServiceProvider still listed only in the two above-mentioned files.

答:
According to this - https://getcomposer.org/doc/articles/scripts.md there is no post-remove-cmd event, therefore whatever you have in your post-update-cmd or post-install-cmd was not executed.

Which suggests it might be the problem with php artisan optimize.


答:
Remove or comment below line from config/app.php

```<code>   Morilog\Jalali\JalaliServiceProvider::class
</code>```

Title: Laravel: How to update packages in storage/framework

Body:
I have removed a package with composer remove and it's now removed from composer.json and composer.lock files and also removed from vendor directory. But I noticed that it's still listed in these two files: storage/framework/packages.php and storage/framework/services.php. How can I update/rebuild these files?

Also, when I run php artisan in the root of my project, I get this error:

[Symfony\Component\Debug\Exception\FatalThrowableError]
    Class 'Morilog\Jalali\JalaliServiceProvider' not found

I searched in all the files of the project and found JalaliServiceProvider still listed only in the two above-mentioned files.

Body:
Remove or comment below line from config/app.php

   Morilog\Jalali\JalaliServiceProvider::class


问:
Spring scheduler: start at 12:25PM and run every 15 minutes after that
I have 2 server, and on both scheduler runs:
1) Main server
2) Disaster recovery server

I want Fist scheduler to run at 12:15 and after 12:15 it should run every 15 minutes.
and second scheduler to start running at 12:25 and after that every 15 minutes it should run.

so both will not collide with each other.

答:
Unfortunately you cannot encode start at 12:25pm and then every 15 minutes using @Scheduled(initialDelay = X, fixedDelay = Y, fixedRate = 15 * 60 * 1000) nor using CRON expressions.

Fortunately you just need to encode every 15 minutes starting at 25 (or 15) minutes past the hour, every hour, every day, every year

Using an online cron expression generator we have (please note discussion around 5, 6 or 7 fields cron expressions below):

@Scheduled(cron="0 25/15 * ? * *") for every 15 min starting at 25 min past the hour and
@Scheduled(cron="0 15/15 * ? * *") for every 15 min starting at 15 min past the hour.

Please don't forget @EnableScheduling annotation on your config.

*cron expressions discussion*

Please note that cron expressions can have 5 (no seconds) as per crontab which Spring says it supports, however it fails with 5, 6 (seconds, and days of the month) which is the only option supported as far as my crude tests went, or 7 fields(seconds, days of month and days of week). Spring has rejected originally pasted 7 fields expression; I have tested with 6 and it worked correctly (but days and years were stars, i.e. ALL


问:
How to enable proguard for only one module
I have a payment application with payumoney integration. It was working fine until i added the proguard. Recently I have added Proguard to my build.gradle file (Module: app)

```<code>  ` buildTypes {
    release {
        minifyEnabled true
        shrinkResources true
        proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        signingConfig signingConfigs.config
    }
}`
</code>```

After this App gets closed when i proceed to payment. It is working fine when i Changed minifyEnabled to false.

Following is my  Module:PayuMoneySdk Build.gradle File

```<code>`buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }`
</code>```

How can I solve this issue? I can't disable proguard.

Can I enable proguard to only Module:app? And will it solve the issue?

I am new to programming. Please help!!

答:
```<code>add below lines in proguard-rule.pro file

 -dontwarn okio.**
 # Platform calls Class.forName on types which do not exist on Android to determine platform.
 -dontnote retrofit2.Platform
 # Platform used when running on Java 8 VMs. Will not be used at runtime.
 -dontwarn retrofit2.Platform$Java8
 # Retain generic type information for use by reflection by converters and adapters.
 -keepattributes Signature
 # Retain declared checked exceptions for use by a Proxy instance.
 -keepattributes Exceptions

-keep class com.** { *; }
</code>```

Body:
I have a payment application with payumoney integration. It was working fine until i added the proguard. Recently I have added Proguard to my build.gradle file (Module: app)

  ` buildTypes {
    release {
        minifyEnabled true
        shrinkResources true
        proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        signingConfig signingConfigs.config
    }
}`

After this App gets closed when i proceed to payment. It is working fine when i Changed minifyEnabled to false.

Following is my  Module:PayuMoneySdk Build.gradle File

`buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }`

How can I solve this issue? I can't disable proguard.

Can I enable proguard to only Module:app? And will it solve the issue?

I am new to programming. Please help!!


问:
Does it make sense to modify an object as a whole using one of its behavior? Say inside the assignment operator overloading using this pointer?
I see a question on this operator (What does assignment to *this do (*this = val)?)

but is it logical to modify an object as a whole from within one of its behavior? Does it makes sense in OOP world?

答:
I don't know if it makes sense in OOP, but C++ isn't pure OOP, it's a multi paradigm language and in order to correctly use C++ you must understand it, not OOP or other paradigms.

A member function, in C++, is just a function whit an implicit this parameter. (A function member of class A has got an A *this implicit parameter.) Then it implicitly passes this to the other functions in the same class.

A function can then use this as it wants to, and this makes sense in C++.


问:
distinguish include_directories with and without the 'SYSTEM' option in cmake
I am using get_property( … PROPERTY INCLUDE_DIRECTORIES) for debugging in a CMake project. Is there a way to tell which of the include directories have been done with and without the SYSTEM option?

In the following example I see no difference

```<code>include_directories("../B")
include_directories(SYSTEM "../A")

get_property( reqs TARGET main PROPERTY INCLUDE_DIRECTORIES)
message(STATUS "main requires ${reqs}")
</code>```

prints:

```<code>-- main requires /home/pseyfert/coding/system/C/../B;/home/pseyfert/coding/system/C/../A
</code>```

答:
There is target property INTERFACE_SYSTEM_INCLUDE_DIRECTORIES, which contains those of include directories, which has been marked as SYSTEM.

As the property's name suggests (and as noted in docs), INTERFACE_SYSTEM_INCLUDE_DIRECTORIES contains only INTERFACE directories, which are propagated to the targets linked with given one. It is unclear from CMake docs, how PRIVATE include directories should be distinguished.

Body:
I am using get_property( … PROPERTY INCLUDE_DIRECTORIES) for debugging in a CMake project. Is there a way to tell which of the include directories have been done with and without the SYSTEM option?

In the following example I see no difference

include_directories("../B")
include_directories(SYSTEM "../A")

get_property( reqs TARGET main PROPERTY INCLUDE_DIRECTORIES)
message(STATUS "main requires ${reqs}")

prints:

-- main requires /home/pseyfert/coding/system/C/../B;/home/pseyfert/coding/system/C/../A


问:
ng serve error - typescript mismatch version (maybe)
aspnetboilerplate core template 3.3.2

"ng serve" issues this output (below)

additional information:

is the error generated from the typescritp mismatch version?

my   typescript should be 2.6.1 (npm view typescript version)

i've tried to: npm install typescript@2.4.0

there is another problem?

[ng serve output]

```<code>@angular/compiler-cli@4.4.6 requires typescript@'>=2.1.0 <2.4.0' but 2.4.0 was found instead.
Using this version can result in undefined behaviour and difficult to debug problems.

Please run the following command to install a compatible version of TypeScript.

    npm install typescript@'>=2.1.0 <2.4.0'

To disable this warning run "ng set warnings.typescriptMismatch=false".

** NG Live Development Server is listening on localhost:4200, open your browser on http://localhost:4200/ **
Date: 2017-11-16T09:52:15.693Z
Hash: f55af8b09fa2b7f58749
Time: 32705ms
chunk {inline} inline.bundle.js (inline) 5.79 kB [entry] [rendered]
chunk {main} main.bundle.js (main) 483 kB [initial] [rendered]
chunk {polyfills} polyfills.bundle.js (polyfills) 1.09 MB [initial] [rendered]
chunk {styles} styles.bundle.js (styles) 1.61 MB [initial] [rendered]
chunk {vendor} vendor.bundle.js (vendor) 14.7 MB [initial] [rendered]

WARNING in ./node_modules/abp-ng2-module/node_modules/@angular/core/esm5/core.js
6438:15-36 Critical dependency: the request of a dependency is an expression
    at ImportLazyContextDependency.getWarnings (C:\angular\AbpCore\3.3.2\angular\node_modules\webpack\lib\dependencies\ContextDependency.js:39:18)
    at Compilation.reportDependencyErrorsAndWarnings (C:\angular\AbpCore\3.3.2\angular\node_modules\webpack\lib\Compilation.js:703:24)
    at Compilation.finish (C:\angular\AbpCore\3.3.2\angular\node_modules\webpack\lib\Compilation.js:561:9)
    at applyPluginsParallel.err (C:\angular\AbpCore\3.3.2\angular\node_modules\webpack\lib\Compiler.js:506:17)
    at C:\angular\AbpCore\3.3.2\angular\node_modules\tapable\lib\Tapable.js:289:11
    at _addModuleChain (C:\angular\AbpCore\3.3.2\angular\node_modules\webpack\lib\Compilation.js:507:11)
    at processModuleDependencies.err (C:\angular\AbpCore\3.3.2\angular\node_modules\webpack\lib\Compilation.js:477:14)
    at _combinedTickCallback (internal/process/next_tick.js:73:7)
    at process._tickCallback (internal/process/next_tick.js:104:9)
 @ ./node_modules/abp-ng2-module/node_modules/@angular/core/esm5/core.js
 @ ./node_modules/abp-ng2-module/src/multi-tenancy/abp-multi-tenancy.service.ts
 @ ./src/shared/session/app-session.service.ts
 @ ./src/root.module.ts
 @ ./src/main.ts
 @ multi webpack-dev-server/client?http://0.0.0.0:0 ./src/main.ts

WARNING in ./node_modules/abp-ng2-module/node_modules/@angular/core/esm5/core.js
6458:15-102 Critical dependency: the request of a dependency is an expression
    at ImportLazyContextDependency.getWarnings (C:\angular\AbpCore\3.3.2\angular\node_modules\webpack\lib\dependencies\ContextDependency.js:39:18)
    at Compilation.reportDependencyErrorsAndWarnings (C:\angular\AbpCore\3.3.2\angular\node_modules\webpack\lib\Compilation.js:703:24)
    at Compilation.finish (C:\angular\AbpCore\3.3.2\angular\node_modules\webpack\lib\Compilation.js:561:9)
    at applyPluginsParallel.err (C:\angular\AbpCore\3.3.2\angular\node_modules\webpack\lib\Compiler.js:506:17)
    at C:\angular\AbpCore\3.3.2\angular\node_modules\tapable\lib\Tapable.js:289:11
    at _addModuleChain (C:\angular\AbpCore\3.3.2\angular\node_modules\webpack\lib\Compilation.js:507:11)
    at processModuleDependencies.err (C:\angular\AbpCore\3.3.2\angular\node_modules\webpack\lib\Compilation.js:477:14)
    at _combinedTickCallback (internal/process/next_tick.js:73:7)
    at process._tickCallback (internal/process/next_tick.js:104:9)
 @ ./node_modules/abp-ng2-module/node_modules/@angular/core/esm5/core.js
 @ ./node_modules/abp-ng2-module/src/multi-tenancy/abp-multi-tenancy.service.ts
 @ ./src/shared/session/app-session.service.ts
 @ ./src/root.module.ts
 @ ./src/main.ts
 @ multi webpack-dev-server/client?http://0.0.0.0:0 ./src/main.ts

ERROR in Error: Metadata version mismatch for module C:/angular/AbpCore/3.3.2/angular/node_modules/abp-ng2-module/node_modules/@angular/http/http.d.ts, found version 4, expected 3, resolving symbol ABP_HTTP_PROVIDER in C:/angular/AbpCore/3.3.2/angular/node_modules/abp-ng2-module/src/abp.module.ts, resolving symbol RootModule in C:/angular/AbpCore/3.3.2/angular/src/root.module.ts, resolving symbol RootModule in C:/angular/AbpCore/3.3.2/angular/src/root.module.ts
    at Error (native)
    at syntaxError (C:\angular\AbpCore\3.3.2\angular\node_modules\@angular\compiler\bundles\compiler.umd.js:1729:34)
    at simplifyInContext (C:\angular\AbpCore\3.3.2\angular\node_modules\@angular\compiler\bundles\compiler.umd.js:24979:23)
    at StaticReflector.simplify (C:\angular\AbpCore\3.3.2\angular\node_modules\@angular\compiler\bundles\compiler.umd.js:24991:13)
    at StaticReflector.annotations (C:\angular\AbpCore\3.3.2\angular\node_modules\@angular\compiler\bundles\compiler.umd.js:24418:41)
    at _getNgModuleMetadata (C:\angular\AbpCore\3.3.2\angular\node_modules\@angular\compiler-cli\src\ngtools_impl.js:138:31)
    at _extractLazyRoutesFromStaticModule (C:\angular\AbpCore\3.3.2\angular\node_modules\@angular\compiler-cli\src\ngtools_impl.js:109:26)
    at Object.listLazyRoutesOfModule (C:\angular\AbpCore\3.3.2\angular\node_modules\@angular\compiler-cli\src\ngtools_impl.js:53:22)
    at Function.NgTools_InternalApi_NG_2.listLazyRoutes (C:\angular\AbpCore\3.3.2\angular\node_modules\@angular\compiler-cli\src\ngtools_api.js:91:39)
    at AotPlugin._getLazyRoutesFromNgtools (C:\angular\AbpCore\3.3.2\angular\node_modules\@ngtools\webpack\src\plugin.js:241:66)
    at _donePromise.Promise.resolve.then.then.then.then.then (C:\angular\AbpCore\3.3.2\angular\node_modules\@ngtools\webpack\src\plugin.js:495:24)
    at process._tickCallback (internal/process/next_tick.js:109:7)

webpack: Failed to compile.
</code>```

答:
I had the same issue. Seems that will be a problem with "abp-ng2-module".

So force npm to install abp-ng2-module v1.2.0.

In package.json dependencies replace "abp-ng2-module": "^1.2.0" with "abp-ng2-module": "1.2.0"

Delete node_modules folder and package.json.lock file

Run npm install

Run ng serve

Body:
aspnetboilerplate core template 3.3.2

"ng serve" issues this output (below)

additional information:

is the error generated from the typescritp mismatch version?

my   typescript should be 2.6.1 (npm view typescript version)

i've tried to: npm install typescript@2.4.0

there is another problem?

[ng serve output]

@angular/compiler-cli@4.4.6 requires typescript@'>=2.1.0 <2.4.0' but 2.4.0 was found instead.
Using this version can result in undefined behaviour and difficult to debug problems.

Please run the following command to install a compatible version of TypeScript.

    npm install typescript@'>=2.1.0 <2.4.0'

To disable this warning run "ng set warnings.typescriptMismatch=false".

** NG Live Development Server is listening on localhost:4200, open your browser on http://localhost:4200/ **
Date: 2017-11-16T09:52:15.693Z
Hash: f55af8b09fa2b7f58749
Time: 32705ms
chunk {inline} inline.bundle.js (inline) 5.79 kB [entry] [rendered]
chunk {main} main.bundle.js (main) 483 kB [initial] [rendered]
chunk {polyfills} polyfills.bundle.js (polyfills) 1.09 MB [initial] [rendered]
chunk {styles} styles.bundle.js (styles) 1.61 MB [initial] [rendered]
chunk {vendor} vendor.bundle.js (vendor) 14.7 MB [initial] [rendered]

WARNING in ./node_modules/abp-ng2-module/node_modules/@angular/core/esm5/core.js
6438:15-36 Critical dependency: the request of a dependency is an expression
    at ImportLazyContextDependency.getWarnings (C:\angular\AbpCore\3.3.2\angular\node_modules\webpack\lib\dependencies\ContextDependency.js:39:18)
    at Compilation.reportDependencyErrorsAndWarnings (C:\angular\AbpCore\3.3.2\angular\node_modules\webpack\lib\Compilation.js:703:24)
    at Compilation.finish (C:\angular\AbpCore\3.3.2\angular\node_modules\webpack\lib\Compilation.js:561:9)
    at applyPluginsParallel.err (C:\angular\AbpCore\3.3.2\angular\node_modules\webpack\lib\Compiler.js:506:17)
    at C:\angular\AbpCore\3.3.2\angular\node_modules\tapable\lib\Tapable.js:289:11
    at _addModuleChain (C:\angular\AbpCore\3.3.2\angular\node_modules\webpack\lib\Compilation.js:507:11)
    at processModuleDependencies.err (C:\angular\AbpCore\3.3.2\angular\node_modules\webpack\lib\Compilation.js:477:14)
    at _combinedTickCallback (internal/process/next_tick.js:73:7)
    at process._tickCallback (internal/process/next_tick.js:104:9)
 @ ./node_modules/abp-ng2-module/node_modules/@angular/core/esm5/core.js
 @ ./node_modules/abp-ng2-module/src/multi-tenancy/abp-multi-tenancy.service.ts
 @ ./src/shared/session/app-session.service.ts
 @ ./src/root.module.ts
 @ ./src/main.ts
 @ multi webpack-dev-server/client?http://0.0.0.0:0 ./src/main.ts

WARNING in ./node_modules/abp-ng2-module/node_modules/@angular/core/esm5/core.js
6458:15-102 Critical dependency: the request of a dependency is an expression
    at ImportLazyContextDependency.getWarnings (C:\angular\AbpCore\3.3.2\angular\node_modules\webpack\lib\dependencies\ContextDependency.js:39:18)
    at Compilation.reportDependencyErrorsAndWarnings (C:\angular\AbpCore\3.3.2\angular\node_modules\webpack\lib\Compilation.js:703:24)
    at Compilation.finish (C:\angular\AbpCore\3.3.2\angular\node_modules\webpack\lib\Compilation.js:561:9)
    at applyPluginsParallel.err (C:\angular\AbpCore\3.3.2\angular\node_modules\webpack\lib\Compiler.js:506:17)
    at C:\angular\AbpCore\3.3.2\angular\node_modules\tapable\lib\Tapable.js:289:11
    at _addModuleChain (C:\angular\AbpCore\3.3.2\angular\node_modules\webpack\lib\Compilation.js:507:11)
    at processModuleDependencies.err (C:\angular\AbpCore\3.3.2\angular\node_modules\webpack\lib\Compilation.js:477:14)
    at _combinedTickCallback (internal/process/next_tick.js:73:7)
    at process._tickCallback (internal/process/next_tick.js:104:9)
 @ ./node_modules/abp-ng2-module/node_modules/@angular/core/esm5/core.js
 @ ./node_modules/abp-ng2-module/src/multi-tenancy/abp-multi-tenancy.service.ts
 @ ./src/shared/session/app-session.service.ts
 @ ./src/root.module.ts
 @ ./src/main.ts
 @ multi webpack-dev-server/client?http://0.0.0.0:0 ./src/main.ts

ERROR in Error: Metadata version mismatch for module C:/angular/AbpCore/3.3.2/angular/node_modules/abp-ng2-module/node_modules/@angular/http/http.d.ts, found version 4, expected 3, resolving symbol ABP_HTTP_PROVIDER in C:/angular/AbpCore/3.3.2/angular/node_modules/abp-ng2-module/src/abp.module.ts, resolving symbol RootModule in C:/angular/AbpCore/3.3.2/angular/src/root.module.ts, resolving symbol RootModule in C:/angular/AbpCore/3.3.2/angular/src/root.module.ts
    at Error (native)
    at syntaxError (C:\angular\AbpCore\3.3.2\angular\node_modules\@angular\compiler\bundles\compiler.umd.js:1729:34)
    at simplifyInContext (C:\angular\AbpCore\3.3.2\angular\node_modules\@angular\compiler\bundles\compiler.umd.js:24979:23)
    at StaticReflector.simplify (C:\angular\AbpCore\3.3.2\angular\node_modules\@angular\compiler\bundles\compiler.umd.js:24991:13)
    at StaticReflector.annotations (C:\angular\AbpCore\3.3.2\angular\node_modules\@angular\compiler\bundles\compiler.umd.js:24418:41)
    at _getNgModuleMetadata (C:\angular\AbpCore\3.3.2\angular\node_modules\@angular\compiler-cli\src\ngtools_impl.js:138:31)
    at _extractLazyRoutesFromStaticModule (C:\angular\AbpCore\3.3.2\angular\node_modules\@angular\compiler-cli\src\ngtools_impl.js:109:26)
    at Object.listLazyRoutesOfModule (C:\angular\AbpCore\3.3.2\angular\node_modules\@angular\compiler-cli\src\ngtools_impl.js:53:22)
    at Function.NgTools_InternalApi_NG_2.listLazyRoutes (C:\angular\AbpCore\3.3.2\angular\node_modules\@angular\compiler-cli\src\ngtools_api.js:91:39)
    at AotPlugin._getLazyRoutesFromNgtools (C:\angular\AbpCore\3.3.2\angular\node_modules\@ngtools\webpack\src\plugin.js:241:66)
    at _donePromise.Promise.resolve.then.then.then.then.then (C:\angular\AbpCore\3.3.2\angular\node_modules\@ngtools\webpack\src\plugin.js:495:24)
    at process._tickCallback (internal/process/next_tick.js:109:7)

webpack: Failed to compile.


问:
How does kotlin's htmlx builder works under the hood exactly?
This is a fragment that explains some part of htmlx builder (from documentation):

```<code>protected fun <T : Element> initTag(tag: T, init: T.() -> Unit): T {
    tag.init()
    children.add(tag)
    return tag
}
</code>```

The main point is children.add(tag) , so we can then declare :

```<code>html {
    head {}
    body {}
}
</code>```

because head and body are member functions of html.
But what about DIV tag ? I can declare div everywhere, furthermore i can write something like this :

```<code>someEnclosingTag { (1..3).forEach { div {+"MyCustomDivFromEverywhere"}  }}
</code>```

How does enclosing lambda knows about "child" lambdas (and respectively, add's 'child' tag to whole html) that can be declared everywhere ?

Please, correct me, if i'm wrong somewhere.

UPDATE

based on answer, i ended with the following dirty-dummy code, that shows function scopes (some aspects of closure's) and implicit receiver omission (Hope it can somehow help someone):

```<code>fun main(args: Array<String>) {
    Child().childFun {
        /*childFun lambda receiver implements parent1Fun lambda receiver, so the receiver can be omitted*/
        parent1Fun {
            /*call from Child.() -> Unit receiver*/
            someIntrestingFun()
        }
        /*same as with parent1Fun*/
        parent2Fun {
            /*call from Child.() -> Unit receiver*/
            someIntrestingFun()
        }
    }
}

fun Child.childFun(lambda: Child.() -> Unit): Child = genericFun(Child(), lambda)

fun ParentInt1.parent1Fun(lambda: ParentInt1.() -> Unit): ParentInt1 = genericFun(Child(), lambda)

fun ParentInt2.parent2Fun(lambda: ParentInt2.() -> Unit): ParentInt2 = genericFun(Child(), lambda)

fun <T> genericFun(instance:T, lambda:T.() -> Unit): T {
    instance.lambda()
    return instance
}

interface ParentInt1
interface ParentInt2

class Child : ParentInt1, ParentInt2 {
    fun someIntrestingFun() { println(this) }
}
</code>```

答:
You can find more about the techniques of building such DSLs in the language reference, see: Type-Safe Builders, and that page gives an example HTML builder (though kotlinx.html is more complicated).

How does enclosing lambda knows about "child" lambdas that can be declared everywhere?

It's how the function resolution works: when you have nested lambdas, with receiver or not, in the inner ones you can call member/extension functions on the receivers of the outer ones(*), here's a very synthetic example:

```<code>with(arrayListOf<String>()) {
    with(hashMapOf<Int, String>()) {
        // You can call both functions of `ArrayList` and `HashMap`:
        add("foo")
        put(1, "bar")

        // Even in the nested lambdas with no receiver:
        baz.forEach { put(it, "it = $it") }
    }
}
</code>```

(*): In advanced DSLs, the scope can be restricted with @DslMarker, to avoid accidentally calling a function on a receiver from the outer scope.

Body:
This is a fragment that explains some part of htmlx builder (from documentation):

protected fun <T : Element> initTag(tag: T, init: T.() -> Unit): T {
    tag.init()
    children.add(tag)
    return tag
}

The main point is children.add(tag) , so we can then declare :

html {
    head {}
    body {}
}

because head and body are member functions of html.
But what about DIV tag ? I can declare div everywhere, furthermore i can write something like this :

someEnclosingTag { (1..3).forEach { div {+"MyCustomDivFromEverywhere"}  }}

How does enclosing lambda knows about "child" lambdas (and respectively, add's 'child' tag to whole html) that can be declared everywhere ?

Please, correct me, if i'm wrong somewhere.

UPDATE

based on answer, i ended with the following dirty-dummy code, that shows function scopes (some aspects of closure's) and implicit receiver omission (Hope it can somehow help someone):

fun main(args: Array<String>) {
    Child().childFun {
        /*childFun lambda receiver implements parent1Fun lambda receiver, so the receiver can be omitted*/
        parent1Fun {
            /*call from Child.() -> Unit receiver*/
            someIntrestingFun()
        }
        /*same as with parent1Fun*/
        parent2Fun {
            /*call from Child.() -> Unit receiver*/
            someIntrestingFun()
        }
    }
}

fun Child.childFun(lambda: Child.() -> Unit): Child = genericFun(Child(), lambda)

fun ParentInt1.parent1Fun(lambda: ParentInt1.() -> Unit): ParentInt1 = genericFun(Child(), lambda)

fun ParentInt2.parent2Fun(lambda: ParentInt2.() -> Unit): ParentInt2 = genericFun(Child(), lambda)

fun <T> genericFun(instance:T, lambda:T.() -> Unit): T {
    instance.lambda()
    return instance
}

interface ParentInt1
interface ParentInt2

class Child : ParentInt1, ParentInt2 {
    fun someIntrestingFun() { println(this) }
}

Body:
You can find more about the techniques of building such DSLs in the language reference, see: Type-Safe Builders, and that page gives an example HTML builder (though kotlinx.html is more complicated).

How does enclosing lambda knows about "child" lambdas that can be declared everywhere?

It's how the function resolution works: when you have nested lambdas, with receiver or not, in the inner ones you can call member/extension functions on the receivers of the outer ones(*), here's a very synthetic example:

with(arrayListOf<String>()) {
    with(hashMapOf<Int, String>()) {
        // You can call both functions of `ArrayList` and `HashMap`:
        add("foo")
        put(1, "bar")

        // Even in the nested lambdas with no receiver:
        baz.forEach { put(it, "it = $it") }
    }
}

(*): In advanced DSLs, the scope can be restricted with @DslMarker, to avoid accidentally calling a function on a receiver from the outer scope.


问:
JS Client doesn't invoke Method on SignalR Hub
I have a MVC project which has 2 button and 6 textbox. I want to call different methods on a Hub.

Client :

```<code>$(document).ready(function () {
            var bitcoinHub = $.connection.bitcoinHub;

            $("#btnBuy").click(function () {
                var tl = document.getElementById("bitcoinBuy").value;
                var btc = document.getElementById("aBitcoin").value;
                var total = document.getElementById("aTotal").value;
                bitcoinHub.server.trade("buy",@Model.user,tl,btc,total);
            });

            bitcoinHub.client.broadcastSell = function (model) {
                //   $("#sellGrid").append("<li>"+model.Sell+"</li>");
            };

            $("#btnSell").click(function () {
                var tl = document.getElementById("bitcoinSell").value;
                var btc = document.getElementById("sBitcoin").value;
                var total = document.getElementById("sTotal").value;
                bitcoinHub.server.trade("sell",@Model.user,tl,btc,total);
            });

            bitcoinHub.client.broadcastPurchase = function (model) {
                // $("#buyGrid").append("<li>"+model.Buy+"</li>");
            };
            $.connection.hub.start();   });
</code>```

In the case I press "btnBuy" or "btnCell" it should invoke the trade methode on the server with different parameters.

Server:

BitcoinHub(name) Class Method

```<code> public void trade(string parametre, Users cUser, string tl, string btc, string total)
    {
        switch (parametre)
        {
            case "sell":
                // Do something not important here
                break;
            case "buy":
                // Do something not important here
                break;
        }
    }
</code>```

In the case I press "btnBuy" or "btnCell" it goes trough the clickeventhandler. The problem is that the method on the hub will not be called.

答:
You can't use the model in JS like that @Model.user. See Accessing MVC's model property from Javascript for details

Additional rearrange your code. Do not invoke a method on server until connection is established:

```<code>$(document).ready(function () {
                var bitcoinHub = $.connection.bitcoinHub;

                bitcoinHub.client.broadcastSell = function (model) {
                    //   $("#sellGrid").append("<li>"+model.Sell+"</li>");
                };

                bitcoinHub.client.broadcastPurchase = function (model) {
                    // $("#buyGrid").append("<li>"+model.Buy+"</li>");
                };
                $.connection.hub.start().done(function(){
                    // DO not call methods on server until connection is established.
                    $("#btnBuy").click(function () {
                        var tl = document.getElementById("bitcoinBuy").value;
                        var btc = document.getElementById("aBitcoin").value;
                        var total = document.getElementById("aTotal").value;
                        bitcoinHub.server.trade("buy",@Model.user,tl,btc,total);
                    });
                    $("#btnSell").click(function () {
                        var tl = document.getElementById("bitcoinSell").value;
                        var btc = document.getElementById("sBitcoin").value;
                        var total = document.getElementById("sTotal").value;
                        bitcoinHub.server.trade("sell",@Model.user,tl,btc,total);
                });
    });   });
</code>```

Body:
I have a MVC project which has 2 button and 6 textbox. I want to call different methods on a Hub.

Client :

$(document).ready(function () {
            var bitcoinHub = $.connection.bitcoinHub;

            $("#btnBuy").click(function () {
                var tl = document.getElementById("bitcoinBuy").value;
                var btc = document.getElementById("aBitcoin").value;
                var total = document.getElementById("aTotal").value;
                bitcoinHub.server.trade("buy",@Model.user,tl,btc,total);
            });

            bitcoinHub.client.broadcastSell = function (model) {
                //   $("#sellGrid").append("
"+model.Sell+"
");
            };

            $("#btnSell").click(function () {
                var tl = document.getElementById("bitcoinSell").value;
                var btc = document.getElementById("sBitcoin").value;
                var total = document.getElementById("sTotal").value;
                bitcoinHub.server.trade("sell",@Model.user,tl,btc,total);
            });

            bitcoinHub.client.broadcastPurchase = function (model) {
                // $("#buyGrid").append("
"+model.Buy+"
");
            };
            $.connection.hub.start();   });

In the case I press "btnBuy" or "btnCell" it should invoke the trade methode on the server with different parameters.

Server:

BitcoinHub(name) Class Method

 public void trade(string parametre, Users cUser, string tl, string btc, string total)
    {
        switch (parametre)
        {
            case "sell":
                // Do something not important here
                break;
            case "buy":
                // Do something not important here
                break;
        }
    }

In the case I press "btnBuy" or "btnCell" it goes trough the clickeventhandler. The problem is that the method on the hub will not be called.

Body:
You can't use the model in JS like that @Model.user. See Accessing MVC's model property from Javascript for details

Additional rearrange your code. Do not invoke a method on server until connection is established:

$(document).ready(function () {
                var bitcoinHub = $.connection.bitcoinHub;

                bitcoinHub.client.broadcastSell = function (model) {
                    //   $("#sellGrid").append("<li>"+model.Sell+"</li>");
                };

                bitcoinHub.client.broadcastPurchase = function (model) {
                    // $("#buyGrid").append("<li>"+model.Buy+"</li>");
                };
                $.connection.hub.start().done(function(){
                    // DO not call methods on server until connection is established.
                    $("#btnBuy").click(function () {
                        var tl = document.getElementById("bitcoinBuy").value;
                        var btc = document.getElementById("aBitcoin").value;
                        var total = document.getElementById("aTotal").value;
                        bitcoinHub.server.trade("buy",@Model.user,tl,btc,total);
                    });
                    $("#btnSell").click(function () {
                        var tl = document.getElementById("bitcoinSell").value;
                        var btc = document.getElementById("sBitcoin").value;
                        var total = document.getElementById("sTotal").value;
                        bitcoinHub.server.trade("sell",@Model.user,tl,btc,total);
                });
    });   });


问:
One line bash command to find N oldest and newest files in a directory
I have the following command:

```<code>files=$(ls -lhrt dirname) && echo $files | head -5 && echo $files | tail -5
</code>```

The idea is to return the oldest and newest 5 files in a directory dirname. This returns the requested data - however, the lines are jumbled together.

Is there a way to better format the output? (or perhaps a better way to write this functionality)?

答:
What about adding linebreaks like so:

files=$(ls -lhrt dirname) && echo -e "${files}\n" | head -5 && echo -e "${files}\n" | tail -5
```

Explanation:

The -e flag enables echo to interpret escapes such as \n in this example.

\n itself is the escape sequence for "new line". So all it does is adding a new line after the echoed variable.

${ } is called Brace Expansion. Since I put the string in quotes, ${} will expand the variable to the string.

Body:
I have the following command:

files=$(ls -lhrt dirname) && echo $files | head -5 && echo $files | tail -5

The idea is to return the oldest and newest 5 files in a directory dirname. This returns the requested data - however, the lines are jumbled together.

Is there a way to better format the output? (or perhaps a better way to write this functionality)?

Body:
What about adding linebreaks like so:

files=$(ls -lhrt dirname) && echo -e "${files}\n" | head -5 && echo -e "${files}\n" | tail -5

Explanation:

The -e flag enables echo to interpret escapes such as \n in this example.

\n itself is the escape sequence for "new line". So all it does is adding a new line after the echoed variable.

${ } is called Brace Expansion. Since I put the string in quotes, ${} will expand the variable to the string.


问:
Filter for the List<List<String>>
I am trying to write a method that would filter the duplicate inputs in a list of lists of Strings. The problem is that by duplicates I mean also the lists that have the same elemets buts in a different order. So I would like that if the input list is :

```<code>[["1", "2","3"], ["2","1","3"],["3","1","2"]]
</code>```

it would return only

```<code>[["1","2","3"]]
</code>```

I tried to do something like:

```<code>public List<List<String>> filter (List<List<String>> list){
    List<List<String>> filteredList = new LinkedList<>();
    filteredList.addAll(list);
    for(List<String> i:list){
        for(List<String> j:list){
            if (!i.equals(j)&&i.containsAll(j)){
                filteredList.remove(j);
            }
        }
    }
    return filteredList;
}
</code>```

but it would remove too much cause it would still iterate through the whole original list and would find that element "a" is duplicate of element "b" and vice versa. On the other side when I try to do that on the same list (without a temp) I get ConcurrentModificationException cause I can't modify and iterate over the same collection at the same time. Adding the list to a Set would not solve the issue because they are not exact duplicates (.equals would return false). Is there any possible solution to achieve at?

答:
I suggest you start by sorting each list, which makes it easier to identify when they're equal. Once that's done, an easy way to eliminate duplicates is to add them to a Set.

One approach could look like this:

```<code>List<List<String>> lists = new ArrayList<>();
lists.add(Arrays.asList("1", "2", "3"));
lists.add(Arrays.asList("2", "1", "3"));
lists.add(Arrays.asList("3", "1", "2"));

lists.forEach(Collections::sort);
Set<List<String>> collect = lists.stream().collect(Collectors.toSet());
System.out.println(collect);
</code>```

Results in the output [[1, 2, 3]].

Title: Filter for the List<List<String>>

Body:
I am trying to write a method that would filter the duplicate inputs in a list of lists of Strings. The problem is that by duplicates I mean also the lists that have the same elemets buts in a different order. So I would like that if the input list is :

[["1", "2","3"], ["2","1","3"],["3","1","2"]]

it would return only

[["1","2","3"]]

I tried to do something like:

public List<List<String>> filter (List<List<String>> list){
    List<List<String>> filteredList = new LinkedList<>();
    filteredList.addAll(list);
    for(List<String> i:list){
        for(List<String> j:list){
            if (!i.equals(j)&&i.containsAll(j)){
                filteredList.remove(j);
            }
        }
    }
    return filteredList;
}

but it would remove too much cause it would still iterate through the whole original list and would find that element "a" is duplicate of element "b" and vice versa. On the other side when I try to do that on the same list (without a temp) I get ConcurrentModificationException cause I can't modify and iterate over the same collection at the same time. Adding the list to a Set would not solve the issue because they are not exact duplicates (.equals would return false). Is there any possible solution to achieve at?

Body:
I suggest you start by sorting each list, which makes it easier to identify when they're equal. Once that's done, an easy way to eliminate duplicates is to add them to a Set.

One approach could look like this:

List<List<String>> lists = new ArrayList<>();
lists.add(Arrays.asList("1", "2", "3"));
lists.add(Arrays.asList("2", "1", "3"));
lists.add(Arrays.asList("3", "1", "2"));

lists.forEach(Collections::sort);
Set<List<String>> collect = lists.stream().collect(Collectors.toSet());
System.out.println(collect);

Results in the output [[1, 2, 3]].


问:
where can i find (edit) the jobs that are going to run in cron.php of drupal?
How can i edit the list of jobs that are going to run at running time of /DocRoot/cron.php in drupal??

in other words, where can i edit the list of drupal jobs that return from drupal_cron_run?

Thanks for your help

答:
Caution: As of Jan, 2012 the below mentioned module is abandoned due to a security issue the maintainer never fixed. See SA-2012-006 for details.

From the Drupal project page:

Maintenance status: Unsupported
Development status: No further development

Here you go http://drupal.org/project/supercron

I guess this fits your need. Just found it.

SuperCron is a complete replacement
  for Drupal's built-in Cron
  functionality. It allows you to:

See the list of all Cron hooks found
  in the enabled modules Change the
  order in which cron hooks are called
  Disable certain hooks
  (...)


问:
Is it possible to share the same realm database file between two platforms?
If let's say on iOS app a realm database is created, can it then be sent as the realm file to macOS app and be used there? </p>

答: The offical solution for synching between devices is to use Realm Platform (expensive).  There is no explicit guarantee that the fileformat is going to be the same between platforms and especially between versions.  Of course you can also just serialize all of your tables to JSON and deserialize them on the other client and use something else like icloud or firebase to synch the data in between.</p>


问:
alert after php-formular has send
I have a E-Mail formular on my Webside. After the Mail is send i will give the user a feedback. How can i give the alert on my side with the formular?
Now I will be forwarded to sendMail.php with the alerttext writen on the page.

html-code (in index.html):

```<code><form ... action="sendMail.php">
   ...
</form>
</code>```

php-code (in sendMail.php):

```<code>$mail_senden = mail($empfaenger,$betreff,$msg,$header);

if($mail_senden){
  echo "nachricht1";
  exit();
} else{
  echo "nachricht2";
  exit();
}
</code>```

答:
You can merge index.html and sendMail.php so create index.php file

```<code><?php
if(isset($_POST['SubmitButton'])){ //check if form was submitted
    $input = $_POST['inputText']; //get input text
    $message = "Success! You entered: ".$input;
}
?>

<html>
    <body>
        <form action="" method="post">
            <?php echo $message; ?>
            <input type="text" name="inputText"/>
            <input type="submit" name="SubmitButton"/>
        </form>
    </body>
</html>
</code>```

Title: alert after php-formular has send

Body:
I have a E-Mail formular on my Webside. After the Mail is send i will give the user a feedback. How can i give the alert on my side with the formular?
Now I will be forwarded to sendMail.php with the alerttext writen on the page.

html-code (in index.html):

<form ... action="sendMail.php">
   ...
</form>

php-code (in sendMail.php):

$mail_senden = mail($empfaenger,$betreff,$msg,$header);

if($mail_senden){
  echo "nachricht1";
  exit();
} else{
  echo "nachricht2";
  exit();
}

Body:
You can merge index.html and sendMail.php so create index.php file

<?php
if(isset($_POST['SubmitButton'])){ //check if form was submitted
    $input = $_POST['inputText']; //get input text
    $message = "Success! You entered: ".$input;
}
?>

<html>
    <body>
        <form action="" method="post">
            <?php echo $message; ?>
            <input type="text" name="inputText"/>
            <input type="submit" name="SubmitButton"/>
        </form>
    </body>
</html>


问:
How to retrieve only AS400 Enabled Users using jt400 API
is there a possibility to retrieve only the Enabled Users -to add a filter- to the getUsers method of UserList of jt400?

I did the following implementation but it does not have a good performance,
so I am trying to find a better way and if there is a possibility to filter the users and to get only the Enabled users.

```<code>Set<String> as400Users = new HashSet();
AS400 as400 = new AS400(host, username, password);

//Retrieving Users
UserList users = new UserList(as400);
Enumeration io = users.getUsers();

  while (io.hasMoreElements()) {
            com.ibm.as400.access.User u = (com.ibm.as400.access.User)io.nextElement();
            String userName = u.getName();

            if (u.getStatus().equalsIgnoreCase("*ENABLED")) {
                as400Users.add(userName);
            }

        }
</code>```

答:
You could query the USER_INFO view like this:

```<code>select *
from qsys2.user_info
where status = '*ENABLED'
</code>```

This became available at v7.1. Note that this only provides users that you have authority to.

You also might want to move the getName() call inside the filter:

```<code>Set<String> as400Users = new HashSet();
AS400 as400 = new AS400(host, username, password);

//Retrieving Users
UserList users = new UserList(as400);
Enumeration io = users.getUsers();

while (io.hasMoreElements()) {
    com.ibm.as400.access.User u = (com.ibm.as400.access.User)io.nextElement();

    if (u.getStatus().equalsIgnoreCase("*ENABLED")) {
        as400Users.add(u.getName());
    }

}
</code>```

Or you could use the newer foreach syntax with getUsers(-1,0)

```<code>Set<String> as400Users = new HashSet();
AS400 as400 = new AS400(host, username, password);

//Retrieving Users
UserList users = new UserList(as400);
for (com.ibm.as400.access.User u: users.getUser(-1,0)) {
    if (u.getStatus().equalsIgnoreCase("*ENABLED")) {
        as400Users.add(u.getName());
    }
}
</code>```

Now just choose the fastest method.

Body:
is there a possibility to retrieve only the Enabled Users -to add a filter- to the getUsers method of UserList of jt400?

I did the following implementation but it does not have a good performance,
so I am trying to find a better way and if there is a possibility to filter the users and to get only the Enabled users.

Set<String> as400Users = new HashSet();
AS400 as400 = new AS400(host, username, password);

//Retrieving Users
UserList users = new UserList(as400);
Enumeration io = users.getUsers();

  while (io.hasMoreElements()) {
            com.ibm.as400.access.User u = (com.ibm.as400.access.User)io.nextElement();
            String userName = u.getName();

            if (u.getStatus().equalsIgnoreCase("*ENABLED")) {
                as400Users.add(userName);
            }

        }

Body:
You could query the USER_INFO view like this:

select *
from qsys2.user_info
where status = '*ENABLED'

This became available at v7.1. Note that this only provides users that you have authority to.

You also might want to move the getName() call inside the filter:

Set<String> as400Users = new HashSet();
AS400 as400 = new AS400(host, username, password);

//Retrieving Users
UserList users = new UserList(as400);
Enumeration io = users.getUsers();

while (io.hasMoreElements()) {
    com.ibm.as400.access.User u = (com.ibm.as400.access.User)io.nextElement();

    if (u.getStatus().equalsIgnoreCase("*ENABLED")) {
        as400Users.add(u.getName());
    }

}

Or you could use the newer foreach syntax with getUsers(-1,0)

Set<String> as400Users = new HashSet();
AS400 as400 = new AS400(host, username, password);

//Retrieving Users
UserList users = new UserList(as400);
for (com.ibm.as400.access.User u: users.getUser(-1,0)) {
    if (u.getStatus().equalsIgnoreCase("*ENABLED")) {
        as400Users.add(u.getName());
    }
}

Now just choose the fastest method.


问:
How to iterate through json object and form a new object with concatenated values using Javascript?
I have been working on  api which gives data in JSON object and i have no control with it at all. I need to pull data on select box. I have managed to populate it but it allows single value binding only. ie firstName or lastName or middleName and not both. Here is my current JSON Object:

```<code>.employeesList = [
  {
    id: 1,
    firstName: 'firstName',
    middleName: 'middleName',
    lastName: 'lastName',
  },
  {
    id: 2,
    firstName: 'firstName2',
    middleName: 'middleName2',
    lastName: 'lastName2',
  },
  {
    id: 3,
    firstName: 'firstName3',
    middleName: 'middleName3',
    lastName: 'lastName3',
  },
  {
    id: 4,
    firstName: 'firstName4',
    middleName: 'middleName4',
    lastName: 'lastName4',
  },
  {
    id: 5,
    firstName: 'firstName5',
    middleName: 'middleName5',
    lastName: 'lastName5',
  }
]
</code>```

I would like to merge firstName, middleName and lastName in each data and form a new JSON Object having only ids and fullNames like so:

```<code>.employeesList = [
  {
    id: 1,
    fullName: 'firstName MiddleName LastName'
  },
  {
    id: 2,
    fullName: 'firstName2 MiddleName2 LastName2'
  },
  {
    id: 3,
    fullName: 'firstName3 MiddleName3 LastName3'
  },
  {
    id: 4,
    fullName: 'firstName4 MiddleName4 LastName4'
  },
  {
    id: 5,
    fullName: 'firstName5 MiddleName5 LastName5'
  }
]
</code>```

How can i achieve that using Javascript?

答:
Use array.prototype.map:

var employeesList = [
  {
    id: 1,
    firstName: 'firstName',
    middleName: 'middleName',
    lastName: 'lastName',
  },
  {
    id: 2,
    firstName: 'firstName2',
    middleName: 'middleName2',
    lastName: 'lastName2',
  },
  {
    id: 3,
    firstName: 'firstName3',
    middleName: 'middleName3',
    lastName: 'lastName3',
  },
  {
    id: 4,
    firstName: 'firstName4',
    middleName: 'middleName4',
    lastName: 'lastName4',
  },
  {
    id: 5,
    firstName: 'firstName5',
    middleName: 'middleName5',
    lastName: 'lastName5',
  }
];

var newEmployeesList = employeesList.map(e => ({id: e.id, fullName: `${e.firstName} ${e.middleName} ${e.lastName}`}));
console.log(newEmployeesList);```

Body:
I have been working on  api which gives data in JSON object and i have no control with it at all. I need to pull data on select box. I have managed to populate it but it allows single value binding only. ie firstName or lastName or middleName and not both. Here is my current JSON Object:

.employeesList = [
  {
    id: 1,
    firstName: 'firstName',
    middleName: 'middleName',
    lastName: 'lastName',
  },
  {
    id: 2,
    firstName: 'firstName2',
    middleName: 'middleName2',
    lastName: 'lastName2',
  },
  {
    id: 3,
    firstName: 'firstName3',
    middleName: 'middleName3',
    lastName: 'lastName3',
  },
  {
    id: 4,
    firstName: 'firstName4',
    middleName: 'middleName4',
    lastName: 'lastName4',
  },
  {
    id: 5,
    firstName: 'firstName5',
    middleName: 'middleName5',
    lastName: 'lastName5',
  }
]

I would like to merge firstName, middleName and lastName in each data and form a new JSON Object having only ids and fullNames like so:

.employeesList = [
  {
    id: 1,
    fullName: 'firstName MiddleName LastName'
  },
  {
    id: 2,
    fullName: 'firstName2 MiddleName2 LastName2'
  },
  {
    id: 3,
    fullName: 'firstName3 MiddleName3 LastName3'
  },
  {
    id: 4,
    fullName: 'firstName4 MiddleName4 LastName4'
  },
  {
    id: 5,
    fullName: 'firstName5 MiddleName5 LastName5'
  }
]

How can i achieve that using Javascript?


问:
Textview disappears when typing in landscape mode
I have a basic form with some Textviews on the left and Edittexts on the right.

When I try to type in portrait mode everything looks fine.

However, when trying to type in landscape mode, I can't see the Textview beside the Edittext.

Here is my xml code

```<code><ScrollView
        android:layout_width="match_parent"
        android:layout_height="match_parent">

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

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

    <TextView
    android:text="Name:"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:textSize="22dp"
    android:layout_marginTop="20dp"
    android:id="@+id/textView_name"
    android:layout_below="@+id/editText_pass"
    android:layout_alignParentLeft="true"
    android:layout_alignParentStart="true" />

        <EditText
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:inputType="textPersonName"
            android:textSize="22dp"
            android:ems="10"
            android:layout_marginTop="10dp"
            android:layout_alignTop="@+id/textView_name"
            android:layout_alignLeft="@+id/editText_pass"
            android:layout_alignStart="@+id/editText_pass"
            android:id="@+id/editText_name" />

    </LinearLayout>
    </LinearLayout>
</ScrollView>
</code>```

Edit:
The question is indeed a duplicate of Disabling the fullscreen editing view for soft keyboard input in landscape?

The title could also be considered a bit vague.

However, both answers given produced the desired result (though with limitations to the view), so I leave up to a moderator to decide if the question is worth deleting or not.

答:
In your xml where you are creating your textView add this line:</p>

```<code>android:imeOptions="flagNoFullscreen"
</code>```

Body:
I have a basic form with some Textviews on the left and Edittexts on the right.

When I try to type in portrait mode everything looks fine.

However, when trying to type in landscape mode, I can't see the Textview beside the Edittext.

Here is my xml code

<ScrollView
        android:layout_width="match_parent"
        android:layout_height="match_parent">

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

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

    <TextView
    android:text="Name:"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:textSize="22dp"
    android:layout_marginTop="20dp"
    android:id="@+id/textView_name"
    android:layout_below="@+id/editText_pass"
    android:layout_alignParentLeft="true"
    android:layout_alignParentStart="true" />

        <EditText
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:inputType="textPersonName"
            android:textSize="22dp"
            android:ems="10"
            android:layout_marginTop="10dp"
            android:layout_alignTop="@+id/textView_name"
            android:layout_alignLeft="@+id/editText_pass"
            android:layout_alignStart="@+id/editText_pass"
            android:id="@+id/editText_name" />

    </LinearLayout>
    </LinearLayout>
</ScrollView>

Edit:
The question is indeed a duplicate of Disabling the fullscreen editing view for soft keyboard input in landscape?

The title could also be considered a bit vague.

However, both answers given produced the desired result (though with limitations to the view), so I leave up to a moderator to decide if the question is worth deleting or not.

Body:
In your xml where you are creating your textView add this line:

android:imeOptions="flagNoFullscreen"


问:
How to find the information from google search result
I want to get the information from google search result. I have some keywords and want to extract information from keywords related pages by python script.</p>

答:
well you can always use tools like scrapy to crawl through the page, but, google also offers APIs for search. have you seen https://developers.google.com/custom-search/json-api/v1/overview ?

complete your question and add more details about what you exactly need, you'll get more accurate answers.


答:
The example given in the question you linked to is simply defining an assignment operator in terms of another one i.e. it allows one to assign a GUID to a QUuid and does so by simply constructing a QUuid and the using the "regular" assigment operator for QUuid that takes another QUuid as an argument.

So, yes, it makes perfect sense. One would expect an assignment operator to change the whole instance. For other member functions, unless they are appropriately named to suggest that they are performing a function similar to assignment, I would not expect to see *this =.

Title: Does it make sense to modify an object as a whole using one of its behavior? Say inside the assignment operator overloading using this pointer?

Body:
I see a question on this operator (What does assignment to *this do (*this = val)?)

but is it logical to modify an object as a whole from within one of its behavior? Does it makes sense in OOP world?


问:
Angular 2: Inject Service to another service. (No provider error)
I want to inject a service to another service:

```<code>@Injectable()

export class Dispatcher {
}

@Injectable()

export class TodoStore {

    constructor(@Inject(Dispatcher) dispatcher:Dispatcher){

    }
}
</code>```

But I always get Error:  No provider for Dispatcher!

Thanks.

答:
A providers array is available in @NgModule. You can provide your service by declaring your service in that array.</p>

```<code>@NgModule({
    declarations:[...],
    imports:[...],
    providers: [MyCustomService],
    bootstrap:[AppComponent]
})
</code>```

Body:
I want to inject a service to another service:

@Injectable()

export class Dispatcher {
}

@Injectable()

export class TodoStore {

    constructor(@Inject(Dispatcher) dispatcher:Dispatcher){

    }
}

But I always get Error:  No provider for Dispatcher!

Thanks.

Body:
A providers array is available in @NgModule. You can provide your service by declaring your service in that array.

@NgModule({
    declarations:[...],
    imports:[...],
    providers: [MyCustomService],
    bootstrap:[AppComponent]
})


问:
UIBezierPath intersect
I've been searching for an answer for hours but have trouble finding anything on the topic.

I have a question related to Objective-c. I'm making an application in which a UIView checks for touches from the user and if the user touches and moves his/her finger, a path using UIBezierPath is drawn. If the user draws so that the path intersects itself it should disappear from the screen. When the user is done drawing the pattern, a line from the last point in the path should connect with the first point in the path automatically (I'm using the method "closePath" for this), if this line intersects with another "line" in the path the path should also disappear from the screen.

I store every touch point in a CGPoint that I store in another class called Line as point A and point B. I'm then saving the "line" to an NSMutableArray called "lines". Every time a point is added to the path I check to see if the line between that point and the point drawn before it intersects with any of the "lines" in lines by using a method (-(BOOL)checkLineIntersection:(CGPoint)p1 :(CGPoint)p2 :(CGPoint)p3 :(CGPoint)p4) I got from this tutorial "http://www.iossourcecode.com/2012/08/02/how-to-make-a-game-like-cut-the-rope-part-2/".

The problem

The problem is that when I run the application it works sometimes but sometimes when I draw so the lines intersect the path doesn't disappear. I can't figure out why... It seems as it happens more often when I draw slowly.

The code:

MyView.h:

```<code>#import <UIKit/UIKit.h>
#import "Line.h"
@interface MyView : UIView {

NSMutableArray *pathArray;
UIBezierPath *myPath;
NSMutableArray *lines;
Line *line;
}

@end
</code>```

MyView.m:

```<code>#import "MyView.h"

@implementation MyView

- (id)initWithFrame:(CGRect)frame
{
self = [super initWithFrame:frame];
if (self) {
    // Initialization code
    pathArray=[[NSMutableArray alloc]init];

}
return self;
}

- (void)drawRect:(CGRect)rect
{
[[UIColor redColor] setStroke];
[[UIColor blueColor] setFill];

for (UIBezierPath *_path in pathArray) {
    //[_path fill];

    [_path strokeWithBlendMode:kCGBlendModeNormal alpha:1.0];
}
}

#pragma mark - Touch Methods
-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
myPath = [[UIBezierPath alloc]init];
lines = [[NSMutableArray alloc]init];
myPath.lineWidth=1;

UITouch *mytouch = [[event allTouches] anyObject];
[myPath moveToPoint:[mytouch locationInView:mytouch.view]];

[pathArray addObject:myPath];

}

-(void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event
{

if(myPath.isEmpty) {

} else {

    UITouch *mytouch = [[event allTouches] anyObject];
    [myPath addLineToPoint:[mytouch locationInView:mytouch.view]];

    CGPoint pointA = [mytouch previousLocationInView:mytouch.view];
    CGPoint pointB = [mytouch locationInView:mytouch.view];

    line = [[Line alloc]init];
    [line setPointA:pointA];
    [line setPointB:pointB];

    [lines addObject:line];

    for(Line *l in lines) {

        CGPoint pa = l.pointA;
        CGPoint pb = l.pointB;

        //NSLog(@"Point A: %@", NSStringFromCGPoint(pa));
        //NSLog(@"Point B: %@", NSStringFromCGPoint(pb));

        if ([self checkLineIntersection:pointA :pointB :pa :pb])
        {
            [pathArray removeLastObject];
            [myPath removeAllPoints];
            [self setNeedsDisplay];
            NSLog(@"Removed path!");
            return;
        }
    }
}
[self setNeedsDisplay];
}

-(void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event
{
if(myPath.isEmpty) {

} else if ([lines count] != 0){
    line = [[Line alloc]init];
    line = [lines lastObject];
    CGPoint pointA = line.pointA;
    line = [[Line alloc]init];
    line = [lines objectAtIndex:0];
    CGPoint pointB = line.pointA;

    [myPath closePath];
    for(Line *l in lines) {

        CGPoint pa = l.pointA;
        CGPoint pb = l.pointB;

        if ([self checkLineIntersection:pointA :pointB :pa :pb])
        {
            [pathArray removeLastObject];
            [myPath removeAllPoints];
            [self setNeedsDisplay];
            NSLog(@"Removed path!");
            return;
        }
    }
}
[self setNeedsDisplay];
}

-(BOOL)checkLineIntersection:(CGPoint)p1 :(CGPoint)p2 :(CGPoint)p3 :(CGPoint)p4
{
CGFloat denominator = (p4.y - p3.y) * (p2.x - p1.x) - (p4.x - p3.x) * (p2.y - p1.y);

/*
// In this case the lines are parallel so you assume they don't intersect
if (denominator == 0.0f)
    return NO;
*/

CGFloat ua = ((p4.x - p3.x) * (p1.y - p3.y) - (p4.y - p3.y) * (p1.x - p3.x)) / denominator;
CGFloat ub = ((p2.x - p1.x) * (p1.y - p3.y) - (p2.y - p1.y) * (p1.x - p3.x)) / denominator;

if (ua > 0.0 && ua < 1.0 && ub > 0.0 && ub < 1.0)
{
    return YES;
}

return NO;
}

@end
</code>```

Line.h:

```<code>#import <UIKit/UIKit.h>

@interface Line : UIView

@property (nonatomic, assign) CGPoint pointA;
@property (nonatomic, assign) CGPoint pointB;

@end
</code>```

Line.m:

```<code>#import "Line.h"

@implementation Line

@synthesize pointA;
@synthesize pointB;

- (id)initWithFrame:(CGRect)frame
{
self = [super initWithFrame:frame];
if (self) {
    // Initialization code
}
return self;
}

/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect
{
// Drawing code
}
*/

@end
</code>```

I hope someone might be able to answer this. Sorry if it's something obvious. Thank you in advance!

答:
I've found another workaround to check if the line intersect it self.
With SceneKit framework it possible to create shape from UIBezierPath. But if the path intersects then bounding box of the node will be zeroed.</p>

```<code>   let path = UIBezierPath()

    //...

    let testGeometry = SCNShape(path:path, extrusionDepth: 0.5)
    let testNode = SCNNode(geometry: testGeometry)

    if (testNode.boundingBox.max - testNode.boundingBox.min).length() > 0 {
    // No intersection (or empty)
   }
</code>```

Title: UIBezierPath intersect

Body:
I've been searching for an answer for hours but have trouble finding anything on the topic.

I have a question related to Objective-c. I'm making an application in which a UIView checks for touches from the user and if the user touches and moves his/her finger, a path using UIBezierPath is drawn. If the user draws so that the path intersects itself it should disappear from the screen. When the user is done drawing the pattern, a line from the last point in the path should connect with the first point in the path automatically (I'm using the method "closePath" for this), if this line intersects with another "line" in the path the path should also disappear from the screen.

I store every touch point in a CGPoint that I store in another class called Line as point A and point B. I'm then saving the "line" to an NSMutableArray called "lines". Every time a point is added to the path I check to see if the line between that point and the point drawn before it intersects with any of the "lines" in lines by using a method (-(BOOL)checkLineIntersection:(CGPoint)p1 :(CGPoint)p2 :(CGPoint)p3 :(CGPoint)p4) I got from this tutorial "http://www.iossourcecode.com/2012/08/02/how-to-make-a-game-like-cut-the-rope-part-2/".

The problem

The problem is that when I run the application it works sometimes but sometimes when I draw so the lines intersect the path doesn't disappear. I can't figure out why... It seems as it happens more often when I draw slowly.

The code:

MyView.h:

#import <UIKit/UIKit.h>
#import "Line.h"
@interface MyView : UIView {

NSMutableArray *pathArray;
UIBezierPath *myPath;
NSMutableArray *lines;
Line *line;
}

@end

MyView.m:

#import "MyView.h"

@implementation MyView

- (id)initWithFrame:(CGRect)frame
{
self = [super initWithFrame:frame];
if (self) {
    // Initialization code
    pathArray=[[NSMutableArray alloc]init];

}
return self;
}

- (void)drawRect:(CGRect)rect
{
[[UIColor redColor] setStroke];
[[UIColor blueColor] setFill];

for (UIBezierPath *_path in pathArray) {
    //[_path fill];

    [_path strokeWithBlendMode:kCGBlendModeNormal alpha:1.0];
}
}

#pragma mark - Touch Methods
-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
myPath = [[UIBezierPath alloc]init];
lines = [[NSMutableArray alloc]init];
myPath.lineWidth=1;

UITouch *mytouch = [[event allTouches] anyObject];
[myPath moveToPoint:[mytouch locationInView:mytouch.view]];

[pathArray addObject:myPath];

}

-(void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event
{

if(myPath.isEmpty) {

} else {

    UITouch *mytouch = [[event allTouches] anyObject];
    [myPath addLineToPoint:[mytouch locationInView:mytouch.view]];

    CGPoint pointA = [mytouch previousLocationInView:mytouch.view];
    CGPoint pointB = [mytouch locationInView:mytouch.view];

    line = [[Line alloc]init];
    [line setPointA:pointA];
    [line setPointB:pointB];

    [lines addObject:line];

    for(Line *l in lines) {

        CGPoint pa = l.pointA;
        CGPoint pb = l.pointB;

        //NSLog(@"Point A: %@", NSStringFromCGPoint(pa));
        //NSLog(@"Point B: %@", NSStringFromCGPoint(pb));

        if ([self checkLineIntersection:pointA :pointB :pa :pb])
        {
            [pathArray removeLastObject];
            [myPath removeAllPoints];
            [self setNeedsDisplay];
            NSLog(@"Removed path!");
            return;
        }
    }
}
[self setNeedsDisplay];
}

-(void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event
{
if(myPath.isEmpty) {

} else if ([lines count] != 0){
    line = [[Line alloc]init];
    line = [lines lastObject];
    CGPoint pointA = line.pointA;
    line = [[Line alloc]init];
    line = [lines objectAtIndex:0];
    CGPoint pointB = line.pointA;

    [myPath closePath];
    for(Line *l in lines) {

        CGPoint pa = l.pointA;
        CGPoint pb = l.pointB;

        if ([self checkLineIntersection:pointA :pointB :pa :pb])
        {
            [pathArray removeLastObject];
            [myPath removeAllPoints];
            [self setNeedsDisplay];
            NSLog(@"Removed path!");
            return;
        }
    }
}
[self setNeedsDisplay];
}

-(BOOL)checkLineIntersection:(CGPoint)p1 :(CGPoint)p2 :(CGPoint)p3 :(CGPoint)p4
{
CGFloat denominator = (p4.y - p3.y) * (p2.x - p1.x) - (p4.x - p3.x) * (p2.y - p1.y);

/*
// In this case the lines are parallel so you assume they don't intersect
if (denominator == 0.0f)
    return NO;
*/

CGFloat ua = ((p4.x - p3.x) * (p1.y - p3.y) - (p4.y - p3.y) * (p1.x - p3.x)) / denominator;
CGFloat ub = ((p2.x - p1.x) * (p1.y - p3.y) - (p2.y - p1.y) * (p1.x - p3.x)) / denominator;

if (ua > 0.0 && ua < 1.0 && ub > 0.0 && ub < 1.0)
{
    return YES;
}

return NO;
}

@end

Line.h:

#import <UIKit/UIKit.h>

@interface Line : UIView

@property (nonatomic, assign) CGPoint pointA;
@property (nonatomic, assign) CGPoint pointB;

@end

Line.m:

#import "Line.h"

@implementation Line

@synthesize pointA;
@synthesize pointB;

- (id)initWithFrame:(CGRect)frame
{
self = [super initWithFrame:frame];
if (self) {
    // Initialization code
}
return self;
}

/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect
{
// Drawing code
}
*/

@end

I hope someone might be able to answer this. Sorry if it's something obvious. Thank you in advance!

Body:
I've found another workaround to check if the line intersect it self.
With SceneKit framework it possible to create shape from UIBezierPath. But if the path intersects then bounding box of the node will be zeroed.

   let path = UIBezierPath()

    //...

    let testGeometry = SCNShape(path:path, extrusionDepth: 0.5)
    let testNode = SCNNode(geometry: testGeometry)

    if (testNode.boundingBox.max - testNode.boundingBox.min).length() > 0 {
    // No intersection (or empty)
   }