问:
Error inflating class ImageView - android.view.InflateException: Binary XML file line #10: Error inflating class ImageView
I'm designing an app that has a xml file for the list items (list_item.xml),
and an adapter for the listView (NewsAdapter.java).

My app encounters this error when running:

```<code>09-22 20:26:29.595 10387-10387/com.example.rh.newsapp E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.rh.newsapp, PID: 10387
android.view.InflateException: Binary XML file line #10: Binary XML file line #10: Error inflating class ImageView
    at android.view.LayoutInflater.inflate(LayoutInflater.java:539)
    at android.view.LayoutInflater.inflate(LayoutInflater.java:423)
    at com.example.rh.newsapp.NewsAdapter.getView(NewsAdapter.java:38)
    at android.widget.AbsListView.obtainView(AbsListView.java:2346)
    at android.widget.ListView.measureHeightOfChildren(ListView.java:1280)
    at android.widget.ListView.onMeasure(ListView.java:1188)
    at android.view.View.measure(View.java:18788)
    at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5951)
    at android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1465)
    at android.widget.LinearLayout.measureHorizontal(LinearLayout.java:1112)
    at android.widget.LinearLayout.onMeasure(LinearLayout.java:632)
    at android.view.View.measure(View.java:18788)
    at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5951)
    at android.widget.FrameLayout.onMeasure(FrameLayout.java:194)
    at android.support.v7.widget.ContentFrameLayout.onMeasure(ContentFrameLayout.java:139)
    at android.view.View.measure(View.java:18788)
    at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5951)
    at android.support.v7.widget.ActionBarOverlayLayout.onMeasure(ActionBarOverlayLayout.java:391)
    at android.view.View.measure(View.java:18788)
    at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5951)
    at android.widget.FrameLayout.onMeasure(FrameLayout.java:194)
    at android.view.View.measure(View.java:18788)
    at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5951)
    at android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1465)
    at android.widget.LinearLayout.measureVertical(LinearLayout.java:748)
    at android.widget.LinearLayout.onMeasure(LinearLayout.java:630)
    at android.view.View.measure(View.java:18788)
    at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5951)
    at android.widget.FrameLayout.onMeasure(FrameLayout.java:194)
    at com.android.internal.policy.PhoneWindow$DecorView.onMeasure(PhoneWindow.java:2643)
    at android.view.View.measure(View.java:18788)
    at android.view.ViewRootImpl.performMeasure(ViewRootImpl.java:2100)
    at android.view.ViewRootImpl.measureHierarchy(ViewRootImpl.java:1216)
    at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:1452)
    at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1107)
    at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:6013)
    at android.view.Choreographer$CallbackRecord.run(Choreographer.java:858)
    at android.view.Choreographer.doCallbacks(Choreographer.java:670)
    at android.view.Choreographer.doFrame(Choreographer.java:606)
    at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:844)
    at android.os.Handler.handleCallback(Handler.java:739)
    at android.os.Handler.dispatchMessage(Handler.java:95)
    at android.os.Looper.loop(Looper.java:148)
    at android.app.ActivityThread.main(ActivityThread.java:5417)
    at java.lang.reflect.Method.invoke(Native Method)
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
 Caused by: android.view.InflateException: Binary XML file line #10: Error inflating class ImageView
    at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:782)
    at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:704)
    at android.view.LayoutInflater.rInflate(LayoutInflater.java:835)
    at android.view.LayoutInflater.rInflateChildren(LayoutInflater.java:798)
    at android.view.LayoutInflater.inflate(LayoutInflater.java:515)
    at android.view.LayoutInflater.inflate(LayoutInflater.java:423)
    at com.example.rh.newsapp.NewsAdapter.getView(NewsAdapter.java:38)
    at android.widget.AbsListView.obtainView(AbsListView.java:2346)
    at android.widget.ListView.measureHeightOfChildren(ListView.java:1280)
    at android.widget.ListView.onMeasure(ListView.java:1188)
    at android.view.View.measure(View.java:18788)
    at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5951)
    at android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1465)
    at android.widget.LinearLayout.measureHorizontal(LinearLayout.java:1112)
    at android.widget.LinearLayout.onMeasure(LinearLayout.java:632)
    at android.view.View.measure(View.java:18788)
    at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5951)
    at android.widget.FrameLayout.onMeasure(FrameLayout.java:194)
    at android.support.v7.widget.ContentFrameLayout.onMeasure(ContentFrameLayout.java:139)
    at android.view.View.measure(View.java:18788)
    at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5951)
    at android.support.v7.widget.ActionBarOverlayLayout.onMeasure(ActionBarOverlayLayout.java:391)
    at android.view.View.measure(View.java:18788)
    at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5951)
    at android.widget.FrameLayout.onMeasure(FrameLayout.java:194)
    at android.view.View.measure(View.java:18788)
    at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5951)
    at android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1465)
    at android.widget.LinearLayout.measureVertical(LinearLayout.java:748)
    at android.widget.LinearLayout.onMeasure(LinearLayout.java:630)
    at android.view.View.measure(View.java:18788)
    at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5951)
    at android.widget.FrameLayout.onMeasure(FrameLayout.java:194)
    at com.android.internal.policy.PhoneWindow$DecorView.onMeasure(PhoneWindow.java:2643)
    at android.view.View.measure(View.java:18788)
    at android.view.ViewRootImpl.performMeasure(ViewRootImpl.java:2100)
    at android.view.ViewRootImpl.measureHierarchy(ViewRootImpl.java:1216)
    at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:1452)
    at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1107)
    at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:6013)
    at android.view.Choreographer$CallbackRecord.run(Choreographer.java:858)
    at android.view.Choreographer.doCallbacks(Choreographer.java:670)
    at android.view.Choreographer.doFrame(Choreographer.java:606)
    at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:844)
    at android.os.Handler.handleCallback(Handler.java:739)
    at android.os.Handler.dispatchMessage(Handler.java:95)
    at android.os.Looper.loop(Looper.java:148)
    at android.app.ActivityThread.main(ActivityThread.java:5417)
    at java.lang.reflect.Method.invoke(Native Method)
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
 Caused by: java.lang.UnsupportedOperationException: Can't convert to dimension: type=0x12
    at android.content.res.TypedArray.getDimensionPixelSize(TypedArray.java:666)
    at android.widget.ImageView.<init>(ImageView.java:160)
    at android.widget.ImageView.<init>(ImageView.java:140)
    at android.suppor
</code>```

My list_item file has an ImageView:

```<code><ImageView
    android:id="@+id/thumbnail"
    android:layout_width="40dp"
    android:layout_height="wrap_content"
    android:baseline="@id/title"
    app:srcCompat="@android:drawable/ic_lock_lock"
    tools:ignore="NotSibling" />
</code>```

When I delete ImageView from the list_item.xml, The app runs well!

What should I do?!

NewsAdapter.java:

```<code>public class NewsAdapter extends ArrayAdapter {
    Context context;
    List<News> newsList;

    public NewsAdapter(@NonNull Context context, @LayoutRes int resource, @NonNull List objects) {
        super(context, resource, objects);
        this.context = context;
        this.newsList = objects;
    }

    @NonNull
    @Override
    public View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent) {
        News current_news = (News) getItem(position);
        View list_view = convertView;
        if(list_view == null) {
            list_view = LayoutInflater.from(context).inflate(R.layout.list_item, parent, false);
        }

        TextView title = list_view.findViewById(R.id.title);
        TextView publicationDate = list_view.findViewById(R.id.publicationDate);
        TextView publication = list_view.findViewById(R.id.publication);

        title.setText(current_news.getTitle());
        publicationDate.setText(current_news.getPublication_date());
        publication.setText(current_news.getPublication());

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

list_item.xml:

```<code><ImageView
    android:id="@+id/thumbnail"
    android:layout_width="40dp"
    android:layout_height="wrap_content"
    android:baseline="@id/title"
    app:srcCompat="@android:drawable/ic_lock_lock"
    tools:ignore="NotSibling" />

<RelativeLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_marginLeft="16dp">

    <TextView
        android:id="@+id/title"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentTop="true"
        android:ellipsize="end"
        android:maxLines="3"
        tools:text="Is technology delivering in schools? Our panel debates" />

    <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/title"
        android:layout_alignParentLeft="true"
        android:orientation="horizontal">

        <TextView
            android:id="@+id/publicationDate"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            tools:text="27 Nov, 2016" />

        <TextView
            android:id="@+id/pipe_icon"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="@string/separator_icon" />

        <TextView
            android:id="@+id/publication"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:ellipsize="end"
            android:maxLines="1"
            tools:text="The Guardian" />
    </LinearLayout>

</RelativeLayout>
</code>```

答:
I had the same problem with my application but finally i SOLVED it.
Just put your image file in ic_launcher_background.xml file instead of ic_launcher_foreground.xml file.Hope it helps.</p>

Body:
I'm designing an app that has a xml file for the list items (list_item.xml),
and an adapter for the listView (NewsAdapter.java).

My app encounters this error when running:

09-22 20:26:29.595 10387-10387/com.example.rh.newsapp E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.rh.newsapp, PID: 10387
android.view.InflateException: Binary XML file line #10: Binary XML file line #10: Error inflating class ImageView
    at android.view.LayoutInflater.inflate(LayoutInflater.java:539)
    at android.view.LayoutInflater.inflate(LayoutInflater.java:423)
    at com.example.rh.newsapp.NewsAdapter.getView(NewsAdapter.java:38)
    at android.widget.AbsListView.obtainView(AbsListView.java:2346)
    at android.widget.ListView.measureHeightOfChildren(ListView.java:1280)
    at android.widget.ListView.onMeasure(ListView.java:1188)
    at android.view.View.measure(View.java:18788)
    at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5951)
    at android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1465)
    at android.widget.LinearLayout.measureHorizontal(LinearLayout.java:1112)
    at android.widget.LinearLayout.onMeasure(LinearLayout.java:632)
    at android.view.View.measure(View.java:18788)
    at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5951)
    at android.widget.FrameLayout.onMeasure(FrameLayout.java:194)
    at android.support.v7.widget.ContentFrameLayout.onMeasure(ContentFrameLayout.java:139)
    at android.view.View.measure(View.java:18788)
    at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5951)
    at android.support.v7.widget.ActionBarOverlayLayout.onMeasure(ActionBarOverlayLayout.java:391)
    at android.view.View.measure(View.java:18788)
    at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5951)
    at android.widget.FrameLayout.onMeasure(FrameLayout.java:194)
    at android.view.View.measure(View.java:18788)
    at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5951)
    at android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1465)
    at android.widget.LinearLayout.measureVertical(LinearLayout.java:748)
    at android.widget.LinearLayout.onMeasure(LinearLayout.java:630)
    at android.view.View.measure(View.java:18788)
    at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5951)
    at android.widget.FrameLayout.onMeasure(FrameLayout.java:194)
    at com.android.internal.policy.PhoneWindow$DecorView.onMeasure(PhoneWindow.java:2643)
    at android.view.View.measure(View.java:18788)
    at android.view.ViewRootImpl.performMeasure(ViewRootImpl.java:2100)
    at android.view.ViewRootImpl.measureHierarchy(ViewRootImpl.java:1216)
    at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:1452)
    at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1107)
    at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:6013)
    at android.view.Choreographer$CallbackRecord.run(Choreographer.java:858)
    at android.view.Choreographer.doCallbacks(Choreographer.java:670)
    at android.view.Choreographer.doFrame(Choreographer.java:606)
    at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:844)
    at android.os.Handler.handleCallback(Handler.java:739)
    at android.os.Handler.dispatchMessage(Handler.java:95)
    at android.os.Looper.loop(Looper.java:148)
    at android.app.ActivityThread.main(ActivityThread.java:5417)
    at java.lang.reflect.Method.invoke(Native Method)
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
 Caused by: android.view.InflateException: Binary XML file line #10: Error inflating class ImageView
    at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:782)
    at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:704)
    at android.view.LayoutInflater.rInflate(LayoutInflater.java:835)
    at android.view.LayoutInflater.rInflateChildren(LayoutInflater.java:798)
    at android.view.LayoutInflater.inflate(LayoutInflater.java:515)
    at android.view.LayoutInflater.inflate(LayoutInflater.java:423)
    at com.example.rh.newsapp.NewsAdapter.getView(NewsAdapter.java:38)
    at android.widget.AbsListView.obtainView(AbsListView.java:2346)
    at android.widget.ListView.measureHeightOfChildren(ListView.java:1280)
    at android.widget.ListView.onMeasure(ListView.java:1188)
    at android.view.View.measure(View.java:18788)
    at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5951)
    at android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1465)
    at android.widget.LinearLayout.measureHorizontal(LinearLayout.java:1112)
    at android.widget.LinearLayout.onMeasure(LinearLayout.java:632)
    at android.view.View.measure(View.java:18788)
    at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5951)
    at android.widget.FrameLayout.onMeasure(FrameLayout.java:194)
    at android.support.v7.widget.ContentFrameLayout.onMeasure(ContentFrameLayout.java:139)
    at android.view.View.measure(View.java:18788)
    at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5951)
    at android.support.v7.widget.ActionBarOverlayLayout.onMeasure(ActionBarOverlayLayout.java:391)
    at android.view.View.measure(View.java:18788)
    at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5951)
    at android.widget.FrameLayout.onMeasure(FrameLayout.java:194)
    at android.view.View.measure(View.java:18788)
    at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5951)
    at android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1465)
    at android.widget.LinearLayout.measureVertical(LinearLayout.java:748)
    at android.widget.LinearLayout.onMeasure(LinearLayout.java:630)
    at android.view.View.measure(View.java:18788)
    at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5951)
    at android.widget.FrameLayout.onMeasure(FrameLayout.java:194)
    at com.android.internal.policy.PhoneWindow$DecorView.onMeasure(PhoneWindow.java:2643)
    at android.view.View.measure(View.java:18788)
    at android.view.ViewRootImpl.performMeasure(ViewRootImpl.java:2100)
    at android.view.ViewRootImpl.measureHierarchy(ViewRootImpl.java:1216)
    at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:1452)
    at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1107)
    at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:6013)
    at android.view.Choreographer$CallbackRecord.run(Choreographer.java:858)
    at android.view.Choreographer.doCallbacks(Choreographer.java:670)
    at android.view.Choreographer.doFrame(Choreographer.java:606)
    at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:844)
    at android.os.Handler.handleCallback(Handler.java:739)
    at android.os.Handler.dispatchMessage(Handler.java:95)
    at android.os.Looper.loop(Looper.java:148)
    at android.app.ActivityThread.main(ActivityThread.java:5417)
    at java.lang.reflect.Method.invoke(Native Method)
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
 Caused by: java.lang.UnsupportedOperationException: Can't convert to dimension: type=0x12
    at android.content.res.TypedArray.getDimensionPixelSize(TypedArray.java:666)
    at android.widget.ImageView.<init>(ImageView.java:160)
    at android.widget.ImageView.<init>(ImageView.java:140)
    at android.suppor

My list_item file has an ImageView:

<ImageView
    android:id="@+id/thumbnail"
    android:layout_width="40dp"
    android:layout_height="wrap_content"
    android:baseline="@id/title"
    app:srcCompat="@android:drawable/ic_lock_lock"
    tools:ignore="NotSibling" />

When I delete ImageView from the list_item.xml, The app runs well!

What should I do?!

NewsAdapter.java:

public class NewsAdapter extends ArrayAdapter {
    Context context;
    List<News> newsList;

    public NewsAdapter(@NonNull Context context, @LayoutRes int resource, @NonNull List objects) {
        super(context, resource, objects);
        this.context = context;
        this.newsList = objects;
    }

    @NonNull
    @Override
    public View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent) {
        News current_news = (News) getItem(position);
        View list_view = convertView;
        if(list_view == null) {
            list_view = LayoutInflater.from(context).inflate(R.layout.list_item, parent, false);
        }

        TextView title = list_view.findViewById(R.id.title);
        TextView publicationDate = list_view.findViewById(R.id.publicationDate);
        TextView publication = list_view.findViewById(R.id.publication);

        title.setText(current_news.getTitle());
        publicationDate.setText(current_news.getPublication_date());
        publication.setText(current_news.getPublication());

        return list_view;
    }
}

list_item.xml:

<ImageView
    android:id="@+id/thumbnail"
    android:layout_width="40dp"
    android:layout_height="wrap_content"
    android:baseline="@id/title"
    app:srcCompat="@android:drawable/ic_lock_lock"
    tools:ignore="NotSibling" />

<RelativeLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_marginLeft="16dp">

    <TextView
        android:id="@+id/title"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentTop="true"
        android:ellipsize="end"
        android:maxLines="3"
        tools:text="Is technology delivering in schools? Our panel debates" />

    <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/title"
        android:layout_alignParentLeft="true"
        android:orientation="horizontal">

        <TextView
            android:id="@+id/publicationDate"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            tools:text="27 Nov, 2016" />

        <TextView
            android:id="@+id/pipe_icon"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="@string/separator_icon" />

        <TextView
            android:id="@+id/publication"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:ellipsize="end"
            android:maxLines="1"
            tools:text="The Guardian" />
    </LinearLayout>

</RelativeLayout>


来源: stackexchange

问:
Error when opening the extensions manager from Xul app
When I open the extensions manager in my Xul app using:

```<code>app = "chrome://mozapps/content/extensions/extensions.xul";
window.open(app,'Test','chrome, width=640, height=480').moveTo(0,0);
</code>```

I get the following error in the javascript console:

Error: uncaught exception:
  [Exception... "Component returned
  failure code: 0x8000ffff
  (NS_ERROR_UNEXPECTED)
  [nsIPrefBranch2.getBoolPref]"
  nsresult: "0x8000ffff
  (NS_ERROR_UNEXPECTED)"  location: "JS
  frame ::
  chrome://mozapps/content/extensions/extensions.js
  :: updateGlobalCommands :: line 2388"
  data: no]

Any idea what's this?

ps. The extensions manager opens and works well, but I'm worried with this error message.

答:
Lines 2387-2388 of extensions.js are:

```<code>if (!gInstalling &&
    (gPendingActions || gPref.getBoolPref(PREF_EXTENSIONS_DSS_SWITCHPENDING)))
</code>```

So I guess that your application doesn't have the extensions.dss.switchPending preference set. For some reason this doesn't live in all.js so you have to set it to false in your application's default preferences.

ContentLicense: CC BY-SA 2.5

Body:
When I open the extensions manager in my Xul app using:

app = "chrome://mozapps/content/extensions/extensions.xul";
window.open(app,'Test','chrome, width=640, height=480').moveTo(0,0);

I get the following error in the javascript console:

Error: uncaught exception:
  [Exception... "Component returned
  failure code: 0x8000ffff
  (NS_ERROR_UNEXPECTED)
  [nsIPrefBranch2.getBoolPref]"
  nsresult: "0x8000ffff
  (NS_ERROR_UNEXPECTED)"  location: "JS
  frame ::
  chrome://mozapps/content/extensions/extensions.js
  :: updateGlobalCommands :: line 2388"
  data: no]

Any idea what's this?

ps. The extensions manager opens and works well, but I'm worried with this error message.

Body:
Lines 2387-2388 of extensions.js are:

if (!gInstalling &&
    (gPendingActions || gPref.getBoolPref(PREF_EXTENSIONS_DSS_SWITCHPENDING)))

So I guess that your application doesn't have the extensions.dss.switchPending preference set. For some reason this doesn't live in all.js so you have to set it to false in your application's default preferences.


问:
Is there a .NET equivalent to SQL Server's newsequentialid()
We use GUIDs for primary key, which you know is clustered by default.

When inserting a new row into a table it is inserted at a random page in the table (because GUIDs are random). This has a measurable performance impact because the DB will split data pages all the time (fragmentation). But the main reason I what a sequential GUID is because I want new rows to be inserted as the last row in the table... which will help when debugging.

I could make a clustered index on CreateDate, but our DB is auto-generated and in development, we need to do something extra to facilitate this. Also, CreateDate is not a good candidate for a clustered index.

Back in the day, I used Jimmy Nielsons COMB's, but I was wondering if there is something in the .NET framework for this. In SQL 2005 Microsoft introduced newsequentialid() as an alternative to newid(), so I was hoping that they made a .NET equivalent because we generate the ID in the code.

PS: Please don't start discussing if this is right or wrong, because GUIDs should be unique etc.

答:
It's important to note that the UUIDs generated by UuidCreateSequential will not be sequential when ordered by SQL Server.

SQL Server follows the RFC when it comes to sorting UUIDs

the RFC got it wrong

UuidCreateSequential did it right

but UuidCreateSequential creates something different from what SQL Server expects

Background

The Type 1 UUIDs created by UuidCreateSequential don't sort in SQL Server.

SQL Server's NewSequentialID uses UuidCreateSequential, with some byte shuffling applied. From the Books Online:

NEWSEQUENTIALID (Transact-SQL)

NEWSEQUENTIALID is a wrapper over the Windows UuidCreateSequential function, with some byte shuffling applied

which then references an MSDN blog post:

How to Generate Sequential GUIDs for SQL Server in .NET  (archive)

```<code>public static Guid NewSequentialId()
{
   Guid guid;
   UuidCreateSequential(out guid);
   var s = guid.ToByteArray();
   var t = new byte[16];

   t[3] = s[0];
   t[2] = s[1];
   t[1] = s[2];
   t[0] = s[3];

   t[5] = s[4];
   t[4] = s[5];
   t[7] = s[6];
   t[6] = s[7];
   t[8] = s[8];
   t[9] = s[9];
   t[10] = s[10];
   t[11] = s[11];
   t[12] = s[12];
   t[13] = s[13];
   t[14] = s[14];
   t[15] = s[15];

   return new Guid(t);
}
</code>```

It all starts with the number of ticks since 1582-10-15 00:00:00 (October 15, 1592, the date of
Gregorian reform to the Christian calendar). Ticks is the number of 100 ns intervals.

For example:

12/6/2017 4:09:39 PM UTC

= 137,318,693,794,503,714 ticks

= 0x01E7DA9FDCA45C22 ticks

The RFC says that we should split this value into three chunks:

UInt32 low (4 bytes)

Uint16 mid (2 bytes)

UInt32 hi (2 bytes)

So we split it up:

```<code>0x01E7DA9FDCA45C22

|   Hi   |   Mid  |    Low     |
|--------|--------|------------|
| 0x01E7 | 0xDA9F | 0xDCA45C22 |
</code>```

And then the RFC says that these three integers should be written out in the order of:

Low: 0xDCA45C22

Mid: 0xDA9F

High: 0x01E7

If you follow the RFC, these values must be written in big-endian (aka "network byte order"):

```<code>DC A4 5C 22 DA 9F x1 E7 xx xx xx xx xx xx xx xx
</code>```

This was a bad design, because you cannot take the first 8 bytes of the UUID and treat them either as a big-endian UInt64, nor as a little-endian UInt64. It's a totally dumb encoding.

UuidCreateSequential gets it right

Microsoft followed all the same rules so far:

Low: 0xDCA45C22

Mid: 0xDA9F

High: 0x1E7

But they write it out in Intel little-endian order:

```<code>22 5C A4 DC 9F DA E7 x1 xx xx xx xx xx xx xx xx
</code>```

If you look at that, you've just written out a little-endian Int64:

```<code>225CA4DC9FDAE701
</code>```

Meaning:

if you wanted to extract the timestamp

or sort by the timestamp

it's trivial; just treat the first 8 bytes as a UInt64.

With the RFC, you have no choice but to perform all kinds of bit fiddling. Even on big-endian machines, you can't treat the 64-bit timestamp as a 64-bit timestamp.

How to reverse it

Given a little-endian guid from UuidCreateSequential:

```<code>DCA45C22-DA9F-11E7-DDDD-FFFFFFFFFFFF
</code>```

with the raw bytes of:

```<code>22 5C A4 DC 9F DA E7 11 DD DD FF FF FF FF FF FF
</code>```

This decodes into:

```<code>Low      Mid  Version High
-------- ---- ------- ---- -----------------
DCA45C22-DA9F-1       1E7 -DDDD-FFFFFFFFFFFF
</code>```

Low: 0xDCA45C22

Mid: 0xDA9F

High: 0x1E7

Version: 1 (type 1)

We can write this back out in RFC big-endian order:

```<code>DC A4 5C 22 DA 9F 11 E7 DD DD FF FF FF FF FF FF
</code>```

Short version

```<code>               |   Swap      | Swap  | Swap  | Copy as-is
Start index    |  0  1  2  3 |  4  5 |  6  7 |
End index      |  3  2  1  0 |  5  4 |  7  6 |
---------------|-------------|-------|-------|------------------------
Little-endian: | 22 5C A4 DC | 9F DA | E7 11 | DD DD FF FF FF FF FF FF
Big-endian:    | DC A4 5C 22 | DA 9F | 11 E7 | DD DD FF FF FF FF FF FF
</code>```

OwnerDisplayName: Thomas Jespersen

ContentLicense: CC BY-SA 4.0

LastEditorDisplayName: Mark Brady

Body:
It's important to note that the UUIDs generated by UuidCreateSequential will not be sequential when ordered by SQL Server.

SQL Server follows the RFC when it comes to sorting UUIDs

the RFC got it wrong

UuidCreateSequential did it right

but UuidCreateSequential creates something different from what SQL Server expects

Background

The Type 1 UUIDs created by UuidCreateSequential don't sort in SQL Server.

SQL Server's NewSequentialID uses UuidCreateSequential, with some byte shuffling applied. From the Books Online:

NEWSEQUENTIALID (Transact-SQL)

NEWSEQUENTIALID is a wrapper over the Windows UuidCreateSequential function, with some byte shuffling applied

which then references an MSDN blog post:

How to Generate Sequential GUIDs for SQL Server in .NET  (archive)

public static Guid NewSequentialId()
{
   Guid guid;
   UuidCreateSequential(out guid);
   var s = guid.ToByteArray();
   var t = new byte[16];

   t[3] = s[0];
   t[2] = s[1];
   t[1] = s[2];
   t[0] = s[3];

   t[5] = s[4];
   t[4] = s[5];
   t[7] = s[6];
   t[6] = s[7];
   t[8] = s[8];
   t[9] = s[9];
   t[10] = s[10];
   t[11] = s[11];
   t[12] = s[12];
   t[13] = s[13];
   t[14] = s[14];
   t[15] = s[15];

   return new Guid(t);
}

It all starts with the number of ticks since 1582-10-15 00:00:00 (October 15, 1592, the date of
Gregorian reform to the Christian calendar). Ticks is the number of 100 ns intervals.

For example:

12/6/2017 4:09:39 PM UTC

= 137,318,693,794,503,714 ticks

= 0x01E7DA9FDCA45C22 ticks

The RFC says that we should split this value into three chunks:

UInt32 low (4 bytes)

Uint16 mid (2 bytes)

UInt32 hi (2 bytes)

So we split it up:

0x01E7DA9FDCA45C22

|   Hi   |   Mid  |    Low     |
|--------|--------|------------|
| 0x01E7 | 0xDA9F | 0xDCA45C22 |

And then the RFC says that these three integers should be written out in the order of:

Low: 0xDCA45C22

Mid: 0xDA9F

High: 0x01E7

If you follow the RFC, these values must be written in big-endian (aka "network byte order"):

DC A4 5C 22 DA 9F x1 E7 xx xx xx xx xx xx xx xx

This was a bad design, because you cannot take the first 8 bytes of the UUID and treat them either as a big-endian UInt64, nor as a little-endian UInt64. It's a totally dumb encoding.

UuidCreateSequential gets it right

Microsoft followed all the same rules so far:

Low: 0xDCA45C22

Mid: 0xDA9F

High: 0x1E7

But they write it out in Intel little-endian order:

22 5C A4 DC 9F DA E7 x1 xx xx xx xx xx xx xx xx

If you look at that, you've just written out a little-endian Int64:

225CA4DC9FDAE701

Meaning:

if you wanted to extract the timestamp

or sort by the timestamp

it's trivial; just treat the first 8 bytes as a UInt64.

With the RFC, you have no choice but to perform all kinds of bit fiddling. Even on big-endian machines, you can't treat the 64-bit timestamp as a 64-bit timestamp.

How to reverse it

Given a little-endian guid from UuidCreateSequential:

DCA45C22-DA9F-11E7-DDDD-FFFFFFFFFFFF

with the raw bytes of:

22 5C A4 DC 9F DA E7 11 DD DD FF FF FF FF FF FF

This decodes into:

Low      Mid  Version High
-------- ---- ------- ---- -----------------
DCA45C22-DA9F-1       1E7 -DDDD-FFFFFFFFFFFF

Low: 0xDCA45C22

Mid: 0xDA9F

High: 0x1E7

Version: 1 (type 1)

We can write this back out in RFC big-endian order:

DC A4 5C 22 DA 9F 11 E7 DD DD FF FF FF FF FF FF

Short version

               |   Swap      | Swap  | Swap  | Copy as-is
Start index    |  0  1  2  3 |  4  5 |  6  7 |
End index      |  3  2  1  0 |  5  4 |  7  6 |
---------------|-------------|-------|-------|------------------------
Little-endian: | 22 5C A4 DC | 9F DA | E7 11 | DD DD FF FF FF FF FF FF
Big-endian:    | DC A4 5C 22 | DA 9F | 11 E7 | DD DD FF FF FF FF FF FF

ContentLicense: CC BY-SA 3.0


问:
How do I set up Python 3 with IntelliJ IDEA on OSX?
I'm highly confused about this. Python3 is installed per default on the MacBook.

which python3 will output /Library/Frameworks/Python.framework/Versions/3.6/bin/python3

Great, so that's my SDK to put into IntelliJ IDEA, one should think.

I have the Python plugin for IDEA. However, I can't run Python files. So I try to change the configuration and set it to the above PATH for the Python interpreter.

However, still nothing. Trying to run the Python file inside IDEA will prompt a new configuration?

I can run the script just file doing python3 script.py in the terminal? I know the path for the Python3 library, yet, IDEA doesn't recognise it at all and doesn't save the configuration.

What am I doing wrong in this process? This should be fairly easy to set up but turns out it isn't :)

I even tried to create a Python 3.6.2 virtual environment with the IDEA internal tool - same thing? It doesn't allow me to run the Python3 script from inside IDEA.

Should I use python from usr/bin/python? If I cd there, I can see Python3. But inside IDEA, i only have access to Python2..

答:
After installing Python 3.8.1 via pyenv which I now recommend over using Homebrew (see https://github.com/pyenv/pyenv), I did the following to add this version to IntelliJ IDEA.

Close all open projects. This will display the Welcome to IntelliJ IDEA window listing recent projects along the left.

Click on Configure -> Structure for New Projects

Click on SDKs under Platform Settings along the left

Click on the + sign above the SDK list and select Python SDK

From the Add Python Interpreter window, select System Interpreter

Click on the ... button to the right of the Interpreter drop down and browse to $HOME/.pyenv/versions/3.8.1/bin/python. Replace 3.8.1 with the desired Python version if you want to configure another version.

Updated for IntelliJ IDEA 2019.3.3


问:
How to switch the orientation of the Card when printing?
I am using the Zebra Technologies - Card ID Printing – Zebra Card SDK for ZXP Series 3 Printers – C#  sample code. I am having trouble setting the Orientation of the card being printed to Portrait. I set the orientation to be portrait in the Printer Preferences for the printer and clicked Print Test Page and a test card came out correctly in portrait orientation. However, when I print a card from the sample application code from the link above it only prints the card in Landscape orientation. I even dived into the code, there is nothing that even uses or sets the orientation of the card anywhere. The only thing I see is in the ZBRUtil.cs it has a enum called Orientation that is never even set or used throughout the entire solution.

Any advice? I am thinking maybe I need to actually take a look in the ZBRGraphics.dll / ZBRPrinter.dll 's next (if it will even let me open them)

答:
You can't.

Via - Zebra Support Staff

Body:
You can't.

Via - Zebra Support Staff


问:
convert a simple maven websocket tyrus project to javac command line
Out of curiosity I'd like to build a simple websockets tyrus server chat project with javac and libraries in -classpath.

Yes, I know that this is not the standard way (mvn is), but I'm doing it as a proof of concept. I manage to get project built but it throws a NullPointerException

Code is:

ChatMain.java:

```<code>package chat;

import java.io.IOException;
import java.util.Collections;
import java.util.Map;

import javax.websocket.DeploymentException;

import org.glassfish.tyrus.server.Server;

public class ChatMain {

    public static void main(String[] args) throws DeploymentException,
            IOException {
        Map<String, Object> properties = Collections.emptyMap();
        Server server = new Server("localhost", 8080, "/ws", properties,
                ChatEndPoint.class);
        System.out.println(server);
        try {
            server.start();
            System.in.read();
        } finally {
            server.stop();
        }
    }
}
</code>```

ChatEndPoint.java:

```<code>package chat;

import java.io.IOException;
import java.util.Map;
import java.util.HashMap;
import java.util.Collections;
import javax.websocket.OnClose;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.ServerEndpoint;
import org.json.*;

@ServerEndpoint("/chat")
public class ChatEndPoint {

    private static Map<String, Session> peers = Collections.synchronizedMap(new HashMap<String, Session>());

    @OnOpen
    public void onOpen(Session peer) {
        System.out.println("onOpen");
    }

    @OnMessage
    public void onMessage(String message, Session peer) throws IOException {
        System.out.println("onMessage");
        JSONObject json = new JSONObject(message);
        String nick = (String) json.get("nick");
        boolean newClient = json.has("action") && ((String) json.get("action")).equals("add");
        synchronized(peers) {
            // Iterate over the connected sessions
            // and broadcast the received message
            for (Map.Entry<String, Session> entry : peers.entrySet()) {
                if (newClient) {
                    JSONObject json1 = new JSONObject(json, new String[] { "action" }).put("nick", entry.getKey());
                    peer.getBasicRemote().sendText(json1.toString());
                }
                entry.getValue().getBasicRemote().sendText(message);
            }
        }
        if (newClient)
            peers.put(nick, peer);
    }

    @OnClose
    public void onClose(Session peer) {
        System.out.println("onClose");
        peers.values().remove(peer);
    }
}
</code>```

javac line:

javac -cp chat/javax.websocket-api-1.1.jar:chat/tyrus-server-1.12.jar:chat/tyrus-spi-1.12.jar:chat/tyrus-core-1.12.jar:chat/grizzly-framework-2.3.22.jar:chat/grizzly-http-server-2.3.22.jar:chat/tyrus-container-grizzly-server-1.12.jar:chat/json.jar: chat/ChatMain.java

java line:

java -cp chat/javax.websocket-api-1.1.jar:chat/tyrus-server-1.12.jar:chat/tyrus-spi-1.12.jar:chat/tyrus-core-1.12.jar:chat/grizzly-framework-2.3.22.jar:chat/grizzly-http-server-2.3.22.jar:chat/tyrus-container-grizzly-server-1.12.jar:chat/json.jar: chat.ChatMain

runtime error:

Exception in thread "main" java.lang.NullPointerException
    at org.glassfish.tyrus.container.grizzly.server.GrizzlyServerContainer$1.stop(GrizzlyServerContainer.java:228)
    at org.glassfish.tyrus.server.Server.stop(Server.java:231)
    at chat.ChatMain.main(ChatMain.java:23)

I understand that this can be done

答: Interestingly, more libraries are needed. If I include all libraries in websocket-ri-archive-1.12.zip bundle, it works well. Definitely, a builder is the way to go

Body:
Out of curiosity I'd like to build a simple websockets tyrus server chat project with javac and libraries in -classpath.

Yes, I know that this is not the standard way (mvn is), but I'm doing it as a proof of concept. I manage to get project built but it throws a NullPointerException

Code is:

ChatMain.java:

package chat;

import java.io.IOException;
import java.util.Collections;
import java.util.Map;

import javax.websocket.DeploymentException;

import org.glassfish.tyrus.server.Server;

public class ChatMain {

    public static void main(String[] args) throws DeploymentException,
            IOException {
        Map<String, Object> properties = Collections.emptyMap();
        Server server = new Server("localhost", 8080, "/ws", properties,
                ChatEndPoint.class);
        System.out.println(server);
        try {
            server.start();
            System.in.read();
        } finally {
            server.stop();
        }
    }
}

ChatEndPoint.java:

package chat;

import java.io.IOException;
import java.util.Map;
import java.util.HashMap;
import java.util.Collections;
import javax.websocket.OnClose;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.ServerEndpoint;
import org.json.*;

@ServerEndpoint("/chat")
public class ChatEndPoint {

    private static Map<String, Session> peers = Collections.synchronizedMap(new HashMap<String, Session>());

    @OnOpen
    public void onOpen(Session peer) {
        System.out.println("onOpen");
    }

    @OnMessage
    public void onMessage(String message, Session peer) throws IOException {
        System.out.println("onMessage");
        JSONObject json = new JSONObject(message);
        String nick = (String) json.get("nick");
        boolean newClient = json.has("action") && ((String) json.get("action")).equals("add");
        synchronized(peers) {
            // Iterate over the connected sessions
            // and broadcast the received message
            for (Map.Entry<String, Session> entry : peers.entrySet()) {
                if (newClient) {
                    JSONObject json1 = new JSONObject(json, new String[] { "action" }).put("nick", entry.getKey());
                    peer.getBasicRemote().sendText(json1.toString());
                }
                entry.getValue().getBasicRemote().sendText(message);
            }
        }
        if (newClient)
            peers.put(nick, peer);
    }

    @OnClose
    public void onClose(Session peer) {
        System.out.println("onClose");
        peers.values().remove(peer);
    }
}

javac line:

javac -cp chat/javax.websocket-api-1.1.jar:chat/tyrus-server-1.12.jar:chat/tyrus-spi-1.12.jar:chat/tyrus-core-1.12.jar:chat/grizzly-framework-2.3.22.jar:chat/grizzly-http-server-2.3.22.jar:chat/tyrus-container-grizzly-server-1.12.jar:chat/json.jar: chat/ChatMain.java

java line:

java -cp chat/javax.websocket-api-1.1.jar:chat/tyrus-server-1.12.jar:chat/tyrus-spi-1.12.jar:chat/tyrus-core-1.12.jar:chat/grizzly-framework-2.3.22.jar:chat/grizzly-http-server-2.3.22.jar:chat/tyrus-container-grizzly-server-1.12.jar:chat/json.jar: chat.ChatMain

runtime error:

Exception in thread "main" java.lang.NullPointerException
    at org.glassfish.tyrus.container.grizzly.server.GrizzlyServerContainer$1.stop(GrizzlyServerContainer.java:228)
    at org.glassfish.tyrus.server.Server.stop(Server.java:231)
    at chat.ChatMain.main(ChatMain.java:23)

I understand that this can be done


问:
How can I convert char pointer to __uint8_t array in C?
I need to convert a string (char*) to an array of __uint8_t. I know the latter is an alias of unsigned char but I can't figure it out how to proper convert it.

Example:

```<code>char *ssid = "XXXXX";
</code>```

This is need cause I have to call an API that accepts only an array of __uint8_t and not char*.

```<code>struct WifiConfig {
    uint8_t ssid[32];
    uint8_t password[64];
};

struct WifiConfig wifi_config;
wifi_config.ssid = ???
</code>```

If I try to cast:

```<code>wifi_config.ssid = (__uint8_t *) ssid;
</code>```

I get the follow error:

```<code>error: assignment to expression with array type
     wifi_config.ssid = (__uint8_t *) ssid;
</code>```

Sorry if that's a silly question, last time I've played with C I was a teen.

Thanks in advance!

答:
Just cast:

```<code>const char *name = "My Full Name";
yourAPIFunction((__uint8_t *) name);
</code>```

Note: this violates const-correctness. You have to make sure yourAPIFunction doesn't mutate name. If it does, then you'll need to memcpy (and free!) it to a local variable, and provide it that, so its mutations don't effect the pooled-string used by any other users of "My Full Name".

Response to your (completely different) updated question:

Those arrays have their storage in-line, they're not pointers to the heap like a typical char *.. You need to copy the contents of your string into them:

```<code>// ssid must be at most 31 chars (plus NUL terminator)
// password must be at most 63 chars (plus NUL terminator)
struct WifiConfig new_wifi_config(char *ssid, char *password) {
    struct WifiConfig wifi_config;
    memcpy(wifi_config.ssid, ssid, strlen(ssid)+1)
    memcpy(wifi_config.password, ssid, strlen(ssid)+1)
    return wifi_config;
}
</code>```

Body:
I need to convert a string (char*) to an array of __uint8_t. I know the latter is an alias of unsigned char but I can't figure it out how to proper convert it.

Example:

char *ssid = "XXXXX";

This is need cause I have to call an API that accepts only an array of __uint8_t and not char*.

struct WifiConfig {
    uint8_t ssid[32];
    uint8_t password[64];
};

struct WifiConfig wifi_config;
wifi_config.ssid = ???

If I try to cast:

wifi_config.ssid = (__uint8_t *) ssid;

I get the follow error:

error: assignment to expression with array type
     wifi_config.ssid = (__uint8_t *) ssid;

Sorry if that's a silly question, last time I've played with C I was a teen.

Thanks in advance!

Body:
Just cast:

const char *name = "My Full Name";
yourAPIFunction((__uint8_t *) name);

Note: this violates const-correctness. You have to make sure yourAPIFunction doesn't mutate name. If it does, then you'll need to memcpy (and free!) it to a local variable, and provide it that, so its mutations don't effect the pooled-string used by any other users of "My Full Name".

Response to your (completely different) updated question:

Those arrays have their storage in-line, they're not pointers to the heap like a typical char *.. You need to copy the contents of your string into them:

// ssid must be at most 31 chars (plus NUL terminator)
// password must be at most 63 chars (plus NUL terminator)
struct WifiConfig new_wifi_config(char *ssid, char *password) {
    struct WifiConfig wifi_config;
    memcpy(wifi_config.ssid, ssid, strlen(ssid)+1)
    memcpy(wifi_config.password, ssid, strlen(ssid)+1)
    return wifi_config;
}


问:
strncpy documentation question
At the following regarding strncpy: http://www.cplusplus.com/reference/clibrary/cstring/strncpy/, it mentions the following:

No null-character is implicitly appended to the end of destination, so destination will only be null-terminated if the length of the C string in source is less than num.

What is meant by this sentence?

答: That means that it copies the terminating null of the source string, but doesnt add a terminating null if the source string doesnt fit into the destination.</p>

Title: strncpy documentation question


问:
Function that check if letters and or whole word is a contained in a given string
I want to solve the following problem through regular expression

All 5 letters 'g', 'o', 'l', 'd','e','n' are included (in any
sequence) and

The string 'golden' is a substring of the given string.

If 1 holds (but 2 does not), return 1.

If both 1 and 2 hold, return 2.
Otherwise return 0.

here is my code.

```<code>function checkstrling($input, $substring)
{
    $voodoo = preg_match("(".implode("(.*?)",array_map('preg_quote',str_split($substring))).")",$input,$matches);
    if( !$voodoo) return 0; // no match
    $pieces = implode("",array_slice($matches,1)); // in-between bits
    if( $pieces !=="") return 1; // there was stuff in between
    return 2; // substring found without interruption
}

var_dump(checkstrling("xgolensssx","golden"));
var_dump(checkstrling("abcgxyommlgdqqesn","golden"));
var_dump(checkstrling("xgoldensssx","golden"));
</code>```

The function work find when i call and provide the following parameter it work fine.

```<code>var_dump(checkstrling("xgolensssx","golden"));
var_dump(checkstrling("abcgxyommlgdqqesn","golden"));
var_dump(checkstrling("xgoldensssx","golden"));
</code>```

But does not work properly when i call the function again with the following paramenter.

```<code>var_dump(checkstrling("somegxoxdxlxnmme","golden"));
var_dump(checkstrling("somegxoxlxdxemnmgoldenv","golden"));
</code>```

答:
Brief

No need for regex here, it'll just complicate things.

Code

See code in use here

```<code>function checkstrling($input, $substring)
{
    if (strpos($input, $substring) !== false) {
       return 2;
    }
    foreach (str_split($substring) as $char) {
        if (strpos($input, $char) === false) {
            return 0;
        }
    }
    return 1;
}

print checkstrling("xgolensssx","golden");              // 0
print checkstrling("abcgxyommlgdqqesn","golden");       // 1
print checkstrling("xgoldensssx","golden");             // 2

print checkstrling("somegxoxdxlxnmme","golden");        // 1
print checkstrling("somegxoxlxdxemnmgoldenv","golden"); // 2
</code>```

Sidenote: You can change str_split($substring) to array_unique(str_split($substring)) to remove duplicates before going through the loop. This may improve performance for larger $substrings that contain duplicate letters (such as the word goldenrod: goldenr would be the resulting array).

Explanation

If word exists in string, return 2, otherwise, continue

Loop over each character in $substring

If the character is not found, return 0

This point is only reached if the loop was completed successfully, return 1

Body:
I want to solve the following problem through regular expression

All 5 letters 'g', 'o', 'l', 'd','e','n' are included (in any
sequence) and

The string 'golden' is a substring of the given string.

If 1 holds (but 2 does not), return 1.

If both 1 and 2 hold, return 2.
Otherwise return 0.

here is my code.

function checkstrling($input, $substring)
{
    $voodoo = preg_match("(".implode("(.*?)",array_map('preg_quote',str_split($substring))).")",$input,$matches);
    if( !$voodoo) return 0; // no match
    $pieces = implode("",array_slice($matches,1)); // in-between bits
    if( $pieces !=="") return 1; // there was stuff in between
    return 2; // substring found without interruption
}

var_dump(checkstrling("xgolensssx","golden"));
var_dump(checkstrling("abcgxyommlgdqqesn","golden"));
var_dump(checkstrling("xgoldensssx","golden"));

The function work find when i call and provide the following parameter it work fine.

var_dump(checkstrling("xgolensssx","golden"));
var_dump(checkstrling("abcgxyommlgdqqesn","golden"));
var_dump(checkstrling("xgoldensssx","golden"));

But does not work properly when i call the function again with the following paramenter.

var_dump(checkstrling("somegxoxdxlxnmme","golden"));
var_dump(checkstrling("somegxoxlxdxemnmgoldenv","golden"));

Body:
Brief

No need for regex here, it'll just complicate things.

Code

See code in use here

function checkstrling($input, $substring)
{
    if (strpos($input, $substring) !== false) {
       return 2;
    }
    foreach (str_split($substring) as $char) {
        if (strpos($input, $char) === false) {
            return 0;
        }
    }
    return 1;
}

print checkstrling("xgolensssx","golden");              // 0
print checkstrling("abcgxyommlgdqqesn","golden");       // 1
print checkstrling("xgoldensssx","golden");             // 2

print checkstrling("somegxoxdxlxnmme","golden");        // 1
print checkstrling("somegxoxlxdxemnmgoldenv","golden"); // 2

Sidenote: You can change str_split($substring) to array_unique(str_split($substring)) to remove duplicates before going through the loop. This may improve performance for larger $substrings that contain duplicate letters (such as the word goldenrod: goldenr would be the resulting array).

Explanation

If word exists in string, return 2, otherwise, continue

Loop over each character in $substring

If the character is not found, return 0

This point is only reached if the loop was completed successfully, return 1


问:
Ansible: specify inventory file inside playbook
So from what I gather, we can use ansible.cfg to set the default inventory file that ansible looks for when running a playbook.

We can also override that inventory by using the -i parameter when running an ansible playbook via the command line.

Is there a way for me to specify a specific special inventory file inside a playbook without using the command line or changing the ansible.cfg file?

答:
You can form a dynamic inventory from inside your playbook using add_host module.

But you will have to write some inventory files parsers to feed correct parameters to add_host.

In general this is the wrong way to go. You should have playbooks and inventories separated.


问:
Visual Studio 2015 RC intellisense does not display parameter list
I have been using Visual Studio 2015 since CTP 6 and I have noticed that the IDE does not show the parameter list when I type the opening parenthesis "(".

This is what I am expecting to see:

In the screenshot above you see the the Create method has two overloads and this displays when I type the open parenthesis. But in Visual Studio CTP 6 and RC, nothing happens. I cannot see the overloads or the parameter list.

Is this a bug? Is there anyway to fix this issue?

答: I had to go to suggested Go to Tools, Options, Text Editor, All Languages, General - and UN-check "Hide advanced members" check box under checked-on "Auto List Members." Then when I would type ( after class name it would show me all possible signatures in Intellisense. Hope it helps some.</p>


问:
Density distributions in R
An assignment has tasked us with creating a series of variables: normal1, normal2, normal3, chiSquared1 and 2, t, and F. They are defined as follows:

```<code>library(tibble)
Normal.Frame <- data_frame(normal1 = rnorm(5000, 0, 1),
    normal2 = rnorm(5000, 0, 1),
    normal3 = rnorm(5000, 0, 1),
    chiSquared1 = normal1^2,
    chiSquared2 = normal2^2,
    F = sum(chiSquared1/chiSquared2),
    t = sum(normal3/sqrt(chiSquared1 )))
</code>```

We then have to make histograms of the distributions for normal1, chiSquared1 and 2, t, and F, which is simple enough for normal1 and the chiSquared variables, but when I try to plot F and t, the plot space is blank.

Our lecturer recommended limiting the range of F to 0-10, and t to -5 to 5. To do this, I use:

```<code>HistT <- hist(Normal.Frame$t, xlim = c(-5, 5))

HistF <- hist(Normal.Frame$F, xlim = c(0, 10))
</code>```

Like I mentioned, this yields blank plots.

答: Your t and F are defined as sums; they will be single values. If those values are outside your range, the histogram will be empty. If you remove the sum() function you should get the desired results.</p>

Title: Density distributions in R

Body:
An assignment has tasked us with creating a series of variables: normal1, normal2, normal3, chiSquared1 and 2, t, and F. They are defined as follows:

library(tibble)
Normal.Frame <- data_frame(normal1 = rnorm(5000, 0, 1),
    normal2 = rnorm(5000, 0, 1),
    normal3 = rnorm(5000, 0, 1),
    chiSquared1 = normal1^2,
    chiSquared2 = normal2^2,
    F = sum(chiSquared1/chiSquared2),
    t = sum(normal3/sqrt(chiSquared1 )))

We then have to make histograms of the distributions for normal1, chiSquared1 and 2, t, and F, which is simple enough for normal1 and the chiSquared variables, but when I try to plot F and t, the plot space is blank.

Our lecturer recommended limiting the range of F to 0-10, and t to -5 to 5. To do this, I use:

HistT <- hist(Normal.Frame$t, xlim = c(-5, 5))

HistF <- hist(Normal.Frame$F, xlim = c(0, 10))

Like I mentioned, this yields blank plots.


问:
MySQL index sign of decimal
Is there an efficient way to index the sign of a DECIMAL column with MySQL (InnoDB)?

I've a query with the condition where amount > 0 (and visa versa) and I'm wondering if there's a fancy way to make it speedy. In the same way that indexing the first character of a string can speed up a query like select distinct left(some_string_column, 1).

答:
Indexing the Decimal column will help MySQL to return result where column > 0.

```<code>  CREATE INDEX signindex ON table(deccolumn);
</code>```

Besides, in order to allow MySQL to use indexes effectively, and avoid the use of a function in where, you can add a new column that has the pre-calculated data, and index that new column

```<code> ALTER TABLE table ADD leftchar char(1);
 UPDATE table SET leftchar=left(some_string_column, 1);
 CREATE INDEX charindex ON table(leftchar);
 SELECT DISTINCT leftchar FROM table;
</code>```

Title: MySQL index sign of decimal

Body:
Indexing the Decimal column will help MySQL to return result where column > 0.

  CREATE INDEX signindex ON table(deccolumn);

Besides, in order to allow MySQL to use indexes effectively, and avoid the use of a function in where, you can add a new column that has the pre-calculated data, and index that new column

 ALTER TABLE table ADD leftchar char(1);
 UPDATE table SET leftchar=left(some_string_column, 1);
 CREATE INDEX charindex ON table(leftchar);
 SELECT DISTINCT leftchar FROM table;


问:
SQLite: full outer join with four tables with 30+ columns
This question is an extension to this post

 I want to join four different tables with SQLite which have just two columns in common. However, assume that there are 30+ columns, i.e more than just columns a - h. Please take a look at following example

Table1:

```<code>a   b   lon lat
---------------
22  33  11  22
</code>```

Table2:

```<code>c   d   lon lat
---------------
1   2   44  45
</code>```

Table3

```<code>e       f       lon lat
-----------------------
NULL    NULL    100 101
</code>```

Table4

```<code>g       h       lon lat
-----------------------
NULL    NULL    200 201
</code>```

The current solution is the following

```<code>SELECT a,b,NULL AS c, NULL AS d,NULL AS e, NULL AS f, NULL AS g, NULL AS h,
lon,lat
FROM table1
UNION ALL
SELECT NULL, NULL,c,d,NULL AS e, NULL AS f, NULL AS g, NULL AS h, lon,lat
FROM table2
UNION ALL
SELECT NULL, NULL,NULL,NULL,e,f, NULL AS g, NULL AS h, lon,lat
FROM table3
UNION ALL
SELECT NULL, NULL,NULL,NULL,NULL,NULL,g,h, lon,lat
from table4
</code>```

Result:

```<code>+------+------+------+------+------+------+------+------+-----+-----+
|  a   |  b   |  c   |  d   |  e   |  f   |  g   |  h   | lon | lat |
+------+------+------+------+------+------+------+------+-----+-----+
| 22   | 33   | NULL | NULL | NULL | NULL | NULL | NULL |  11 |  22 |
| NULL | NULL | 1    | 2    | NULL | NULL | NULL | NULL |  44 |  45 |
| NULL | NULL | NULL | NULL | NULL | NULL | NULL | NULL | 100 | 101 |
| NULL | NULL | NULL | NULL | NULL | NULL | NULL | NULL | 200 | 201 |
+------+------+------+------+------+------+------+------+-----+-----+
</code>```

DEMO

 Problem: What if I have not just the columns a until h, but a until z, i.e many many columns in table1, table2, table3, and table4 -> It would be very time-consuming and the structure wouldn't be clear if I had to write everywhere NULL as [letter] in my sql statement

 @zarruq was a huge help and he suggested that In that case I can just use `UNION ALL` and then `PIVOT` to convert columns to rows

 However, I am not sure how to do that. And, I do not know 100% what he means by that.

 EDIT: SQLite does not support pivot: Any other suggestions?

答:
I don't believe there's a particularly neat way of doing this when you have 30+ columns. The following is the best I could do, using nested CTEs to implement full outer joins, then using coalesce to choose the first non-null lat/lon.

It's still required to enumerate all 30+ fields in the top SELECT statement, but at least the massive lists of NULL AS ... aren't needed:

```<code>SELECT
  a, b, c, d, e, f, g, h,
  coalesce(lat1, lat2, lat3, lat4) AS lat,
  coalesce(lon1, lon2, lon3, lon4) AS lon
  FROM (
    WITH t1_x_t2 AS (
        SELECT t1.*, t2.*,
        t1.lat AS lat1, t2.lat AS lat2, t1.lon AS lon1, t2.lon AS lon2
        FROM table1 t1 LEFT OUTER JOIN table2 t2 ON 0
      UNION ALL
        SELECT t1.*, t2.*,
        t1.lat AS lat1, t2.lat AS lat2, t1.lon AS lon1, t2.lon AS lon2
        FROM table2 t2 LEFT OUTER JOIN table1 t1 ON 0
    ), t3_x_t4 AS (
        SELECT t3.*, t4.*,
        t3.lat AS lat3, t4.lat AS lat4, t3.lon AS lon3, t4.lon AS lon4
        FROM table3 t3 LEFT OUTER JOIN table4 t4 ON 0
      UNION ALL
        SELECT t3.*, t4.*,
        t3.lat AS lat3, t4.lat AS lat4, t3.lon AS lon3, t4.lon AS lon4
        FROM table4 t4 LEFT OUTER JOIN table3 t3 ON 0
    )
    SELECT t1_x_t2.*, t3_x_t4.* FROM t1_x_t2 LEFT OUTER JOIN t3_x_t4 ON 0
    UNION ALL
    SELECT t1_x_t2.*, t3_x_t4.* FROM t3_x_t4 LEFT OUTER JOIN t1_x_t2 ON 0
)
</code>```

Body:
This question is an extension to this post

 I want to join four different tables with SQLite which have just two columns in common. However, assume that there are 30+ columns, i.e more than just columns a - h. Please take a look at following example

Table1:

a   b   lon lat
---------------
22  33  11  22

Table2:

c   d   lon lat
---------------
1   2   44  45

Table3

e       f       lon lat
-----------------------
NULL    NULL    100 101

Table4

g       h       lon lat
-----------------------
NULL    NULL    200 201

The current solution is the following

SELECT a,b,NULL AS c, NULL AS d,NULL AS e, NULL AS f, NULL AS g, NULL AS h,
lon,lat
FROM table1
UNION ALL
SELECT NULL, NULL,c,d,NULL AS e, NULL AS f, NULL AS g, NULL AS h, lon,lat
FROM table2
UNION ALL
SELECT NULL, NULL,NULL,NULL,e,f, NULL AS g, NULL AS h, lon,lat
FROM table3
UNION ALL
SELECT NULL, NULL,NULL,NULL,NULL,NULL,g,h, lon,lat
from table4

Result:

+------+------+------+------+------+------+------+------+-----+-----+
|  a   |  b   |  c   |  d   |  e   |  f   |  g   |  h   | lon | lat |
+------+------+------+------+------+------+------+------+-----+-----+
| 22   | 33   | NULL | NULL | NULL | NULL | NULL | NULL |  11 |  22 |
| NULL | NULL | 1    | 2    | NULL | NULL | NULL | NULL |  44 |  45 |
| NULL | NULL | NULL | NULL | NULL | NULL | NULL | NULL | 100 | 101 |
| NULL | NULL | NULL | NULL | NULL | NULL | NULL | NULL | 200 | 201 |
+------+------+------+------+------+------+------+------+-----+-----+

DEMO

 Problem: What if I have not just the columns a until h, but a until z, i.e many many columns in table1, table2, table3, and table4 -> It would be very time-consuming and the structure wouldn't be clear if I had to write everywhere NULL as [letter] in my sql statement

 @zarruq was a huge help and he suggested that In that case I can just use `UNION ALL` and then `PIVOT` to convert columns to rows

 However, I am not sure how to do that. And, I do not know 100% what he means by that.

 EDIT: SQLite does not support pivot: Any other suggestions?

Body:
I don't believe there's a particularly neat way of doing this when you have 30+ columns. The following is the best I could do, using nested CTEs to implement full outer joins, then using coalesce to choose the first non-null lat/lon.

It's still required to enumerate all 30+ fields in the top SELECT statement, but at least the massive lists of NULL AS ... aren't needed:

SELECT
  a, b, c, d, e, f, g, h,
  coalesce(lat1, lat2, lat3, lat4) AS lat,
  coalesce(lon1, lon2, lon3, lon4) AS lon
  FROM (
    WITH t1_x_t2 AS (
        SELECT t1.*, t2.*,
        t1.lat AS lat1, t2.lat AS lat2, t1.lon AS lon1, t2.lon AS lon2
        FROM table1 t1 LEFT OUTER JOIN table2 t2 ON 0
      UNION ALL
        SELECT t1.*, t2.*,
        t1.lat AS lat1, t2.lat AS lat2, t1.lon AS lon1, t2.lon AS lon2
        FROM table2 t2 LEFT OUTER JOIN table1 t1 ON 0
    ), t3_x_t4 AS (
        SELECT t3.*, t4.*,
        t3.lat AS lat3, t4.lat AS lat4, t3.lon AS lon3, t4.lon AS lon4
        FROM table3 t3 LEFT OUTER JOIN table4 t4 ON 0
      UNION ALL
        SELECT t3.*, t4.*,
        t3.lat AS lat3, t4.lat AS lat4, t3.lon AS lon3, t4.lon AS lon4
        FROM table4 t4 LEFT OUTER JOIN table3 t3 ON 0
    )
    SELECT t1_x_t2.*, t3_x_t4.* FROM t1_x_t2 LEFT OUTER JOIN t3_x_t4 ON 0
    UNION ALL
    SELECT t1_x_t2.*, t3_x_t4.* FROM t3_x_t4 LEFT OUTER JOIN t1_x_t2 ON 0
)


问:
Open Launch URL in an my app web view

Hello i set up onesignal Notification in my android app web view

but android when open notification will launch web browsers not in android app.

i want launch web url into  my app

please help me

答:
Put below code inside your FragmentWebInteractive class :

```<code>private class MyWebChromeClient extends WebChromeClient {
    Context context;

    public MyWebChromeClient(Context context) {
        super();
        this.context = context;
    }
}
</code>```

remove previous code for setting webViewClient and then set the web chrome client to webview as following :

```<code>   webView.setWebChromeClient(new MyWebChromeClient(this));
</code>```

Title: Open Launch URL in an my app web view

Body:
Put below code inside your FragmentWebInteractive class :

private class MyWebChromeClient extends WebChromeClient {
    Context context;

    public MyWebChromeClient(Context context) {
        super();
        this.context = context;
    }
}

remove previous code for setting webViewClient and then set the web chrome client to webview as following :

   webView.setWebChromeClient(new MyWebChromeClient(this));


问:
How to convert an object to a string for a list search?
I am trying to search a list that contains only objects for a string input entered by the user. If an object in the list has a name that corresponds to the string input, the code should print the relevant info of the object and return it.

However, output is "0" even if I enter an item I know is on the list. I need python to recognize the objects in the list as a string so that it knows when the input is equal to one of the objects.

This is my code:

```<code>flavor_input = str.upper(input('What is the flavor of the cake you are looking for? '))
for var in cakeList:
     if str(var) == flavor_input:
         print('The flavor has been found')
         print(var)
         return var
    if var not in cakeList:
         print('The cake is not on the list!')
         return 0
</code>```

答:
i cant write comments so, maybe trying this

```<code>if str.upper(var) in flavor_input:
</code>```

it may be that the var word is not uppercase. Also i think you can just compare them raw, without the loop

```<code>if flavor_input in cakeList
</code>```

hope that helped

Body:
I am trying to search a list that contains only objects for a string input entered by the user. If an object in the list has a name that corresponds to the string input, the code should print the relevant info of the object and return it.

However, output is "0" even if I enter an item I know is on the list. I need python to recognize the objects in the list as a string so that it knows when the input is equal to one of the objects.

This is my code:

flavor_input = str.upper(input('What is the flavor of the cake you are looking for? '))
for var in cakeList:
     if str(var) == flavor_input:
         print('The flavor has been found')
         print(var)
         return var
    if var not in cakeList:
         print('The cake is not on the list!')
         return 0

Body:
i cant write comments so, maybe trying this

if str.upper(var) in flavor_input:

it may be that the var word is not uppercase. Also i think you can just compare them raw, without the loop

if flavor_input in cakeList

hope that helped


问:
Json map to java object from inner - nested json property
Suppose I have JSON as follow.

```<code>{
    "took": 1,
    "timed_out": false,
    "_shards": {
        "total": 5,
        "successful": 5,
        "skipped": 0,
        "failed": 0
    },
    "hits": {
        "total": 1,
        "max_score": 1,
        "hits": [
            {
                "_index": "users",
                "_type": "students",
                "_id": "AWAEqh945A0BWjveqnd0",
                "_score": 1,
                "_source": {
                    "college": {
                        "sport": {
                            "name": "cricket",
                            "category": "batsman"
                        }
                    }
                }
            }
        ]
    }
}
</code>```

I want to map data to College object which start from _source field.

Is there way to say to Jackson or Gson to from where mapping should start ?
in this example from _source

The Response we get from ES server.
ES server hosted on AWS.
So we suppose to communicate through ES Java API RestClient.
Is it ok Query through ES Java API QueryBuilder.
What is Recommended. ?

答:
You can do the following using Gson:

```<code>    JSONObject object = new JSONObject(s); // s is you String Json
    JSONObject hits1 = object.getJSONObject("hits");
    JSONArray hits = hits1.getJSONArray("hits");
    for (Object jsonObj : hits) {
        JSONObject json = (JSONObject) jsonObj;
        JSONObject source = json.getJSONObject("_source");
        College college = new Gson().fromJson(source.getJSONObject("college").toString(), College.class);
    }
</code>```

You also need these two Pojos:

```<code>public class College {

    private Sport sport;

    public College() {
    }

    public Sport getSport() {
        return sport;
    }

    public void setSport(Sport sport) {
        this.sport = sport;
    }
}

public class Sport {

    private String name;
    private String category;

    public Sport() {
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getCategory() {
        return category;
    }

    public void setCategory(String category) {
        this.category = category;
    }
}
</code>```

Body:
Suppose I have JSON as follow.

{
    "took": 1,
    "timed_out": false,
    "_shards": {
        "total": 5,
        "successful": 5,
        "skipped": 0,
        "failed": 0
    },
    "hits": {
        "total": 1,
        "max_score": 1,
        "hits": [
            {
                "_index": "users",
                "_type": "students",
                "_id": "AWAEqh945A0BWjveqnd0",
                "_score": 1,
                "_source": {
                    "college": {
                        "sport": {
                            "name": "cricket",
                            "category": "batsman"
                        }
                    }
                }
            }
        ]
    }
}

I want to map data to College object which start from _source field.

Is there way to say to Jackson or Gson to from where mapping should start ?
in this example from _source

The Response we get from ES server.
ES server hosted on AWS.
So we suppose to communicate through ES Java API RestClient.
Is it ok Query through ES Java API QueryBuilder.
What is Recommended. ?

Body:
You can do the following using Gson:

    JSONObject object = new JSONObject(s); // s is you String Json
    JSONObject hits1 = object.getJSONObject("hits");
    JSONArray hits = hits1.getJSONArray("hits");
    for (Object jsonObj : hits) {
        JSONObject json = (JSONObject) jsonObj;
        JSONObject source = json.getJSONObject("_source");
        College college = new Gson().fromJson(source.getJSONObject("college").toString(), College.class);
    }

You also need these two Pojos:

public class College {

    private Sport sport;

    public College() {
    }

    public Sport getSport() {
        return sport;
    }

    public void setSport(Sport sport) {
        this.sport = sport;
    }
}

public class Sport {

    private String name;
    private String category;

    public Sport() {
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getCategory() {
        return category;
    }

    public void setCategory(String category) {
        this.category = category;
    }
}


问:
How call python to run script on $PATH
My $PATH environment variable has /a/path/with spaces/in/it, upon which sits a python script I want to run from a different location.

But when I try to run it with python3 I get a file not found error.

```<code>$ python3 prog.py

python3: can't open file 'prog.py': [Errno 2] No such file or directory
</code>```

The same happens when I attempt to apply the linux file command to it:

```<code>$ file prog.py

prog.py: cannot open `prog.py' (No such file or directory)
</code>```

Yet if I type the name of bash scripts on the same path, they run as expected.

Similarly, if I just type prog.py, my shell attempts to run it. So my system can see the file perfectly well.

What's more, If I cd to the actual location of prog.py, then tell python3 to run it, it executes as it ought.

Why does this happen, or fail to happen as they case may be?

And how can I execute the command as I wish?

答:
Answer was to attribute the python script properly as an executable.

(As described in the link provided in the comment above by Jean-François Fabre, and here).

That is, to have #! /usr/bin/python3 as the first line of the script, in addition to making it an executable, and then simply calling it to run it.

Title: How call python to run script on $PATH

Body:
My $PATH environment variable has /a/path/with spaces/in/it, upon which sits a python script I want to run from a different location.

But when I try to run it with python3 I get a file not found error.

$ python3 prog.py

python3: can't open file 'prog.py': [Errno 2] No such file or directory

The same happens when I attempt to apply the linux file command to it:

$ file prog.py

prog.py: cannot open `prog.py' (No such file or directory)

Yet if I type the name of bash scripts on the same path, they run as expected.

Similarly, if I just type prog.py, my shell attempts to run it. So my system can see the file perfectly well.

What's more, If I cd to the actual location of prog.py, then tell python3 to run it, it executes as it ought.

Why does this happen, or fail to happen as they case may be?

And how can I execute the command as I wish?


问:
how to exclude path information in gradle zip task
Apologies in advance for this simple question I am relatively new to Gradle.

I would like to run a Zip task during my Build process and create a .zip file in my "archive" directory but without the source file's directory structure. I managed to get the task working but its retaining the directory structure. I read that for linux Zip there is the option -j or -r which flattens the directory but I am not sure if this is available to me via the Gradle task.

```<code>My input file structures looks similar to the below,
    ./libs/
    ./libs/file1.jar
    ./scripts/script1.sh
    ./scripts/script2.sh
</code>```

but I would like to end up with a Zip file with directory structure as follows,

```<code>./
./file1.jar
./script1.sh
./script2.sh
</code>```

My current Zip task is as follows,

```<code>task makeZipForDeploy(type: Zip) {
            from 'build/'
            include 'libs/*' //to include all files in libs folder
            include 'scripts/*' //to include all files in the scripts folder
            archiveName("${archiveFileName}")
            destinationDir file("${archivePath}")
}
</code>```

答:
the solution was even more trivial than I thought. The below will flatten the structure

```<code>task makeZipForDeploy(type: Zip) {
    from 'build/libs' //to include all files in libs folder
    from 'build/scripts' //to include all files in the scripts folder
    archiveName("${archiveFileName}")
    destinationDir file("${archivePath}")
}
</code>```

Body:
Apologies in advance for this simple question I am relatively new to Gradle.

I would like to run a Zip task during my Build process and create a .zip file in my "archive" directory but without the source file's directory structure. I managed to get the task working but its retaining the directory structure. I read that for linux Zip there is the option -j or -r which flattens the directory but I am not sure if this is available to me via the Gradle task.

My input file structures looks similar to the below,
    ./libs/
    ./libs/file1.jar
    ./scripts/script1.sh
    ./scripts/script2.sh

but I would like to end up with a Zip file with directory structure as follows,

./
./file1.jar
./script1.sh
./script2.sh

My current Zip task is as follows,

task makeZipForDeploy(type: Zip) {
            from 'build/'
            include 'libs/*' //to include all files in libs folder
            include 'scripts/*' //to include all files in the scripts folder
            archiveName("${archiveFileName}")
            destinationDir file("${archivePath}")
}

Body:
the solution was even more trivial than I thought. The below will flatten the structure

task makeZipForDeploy(type: Zip) {
    from 'build/libs' //to include all files in libs folder
    from 'build/scripts' //to include all files in the scripts folder
    archiveName("${archiveFileName}")
    destinationDir file("${archivePath}")
}


问:
How to find the difference/mismatch between two JSON file?
I have two json files, one is expected json and the another one is the result of GET API call. I need to compare and find out the mismatch in the file.

Expected Json:

```<code>{
  "array": [
    1,
    2,
    3
  ],
  "boolean": true,
  "null": null,
  "number": 123,
  "object": {
    "a": "b",
    "c": "d",
    "e": "f"
  },
  "string": "Hello World"
}
</code>```

Actual Json response:

```<code>{
  "array": [
    1,
    2,
    3
  ],
  "boolean": true,
  "null": null,
  "number": 456,
  "object": {
    "a": "b",
    "c": "d",
    "e": "f"
  },
  "string": "India"
}
</code>```

Actually there are two mismatch: number received is 456 and string is India.

Is there a way to compare and get these two mismatch as results.

This need to be implemented in gatling/scala.

答:
You can use, for example, play-json library and recursively traverse both JSONs. For next input (a bit more sophisticated than yours input):

LEFT:

```<code>{
  "array" : [ 1, 2, 4 ],
  "boolean" : true,
  "null" : null,
  "number" : 123,
  "object" : {
    "a" : "b",
    "c" : "d",
    "e" : "f"
  },
  "string" : "Hello World",
  "absent-in-right" : true,
  "different-types" : 123
}
</code>```

RIGHT:

```<code>{
  "array" : [ 1, 2, 3 ],
  "boolean" : true,
  "null" : null,
  "number" : 456,
  "object" : {
    "a" : "b",
    "c" : "d",
    "e" : "ff"
  },
  "string" : "India",
  "absent-in-left" : true,
  "different-types" : "YES"
}
</code>```

It produces this output:

```<code>Next fields are absent in LEFT:
     *\absent-in-left
Next fields are absent in RIGHT:
     *\absent-in-right
'*\array\(2)' => 4 != 3
'*\number' => 123 != 456
'*\object\e' => f != ff
'*\string' => Hello World != India
Cannot compare JsNumber and JsString in '*\different-types'
</code>```

Code:

```<code>val left = Json.parse("""{"array":[1,2,4],"boolean":true,"null":null,"number":123,"object":{"a":"b","c":"d","e":"f"},"string":"Hello World","absent-in-right":true,"different-types":123}""").asInstanceOf[JsObject]
val right = Json.parse("""{"array":[1,2,3],"boolean":true,"null":null,"number":456,"object":{"a":"b","c":"d","e":"ff"},"string":"India","absent-in-left":true,"different-types":"YES"}""").asInstanceOf[JsObject]

// '*' - for the root node
showJsDiff(left, right, "*", Seq.empty[String])

def showJsDiff(left: JsValue, right: JsValue, parent: String, path: Seq[String]): Unit = {
  val newPath = path :+ parent
  if (left.getClass != right.getClass) {
    println(s"Cannot compare ${left.getClass.getSimpleName} and ${right.getClass.getSimpleName} " +
      s"in '${getPath(newPath)}'")
  }
  else {
    left match {
      // Primitive types are pretty easy to handle
      case JsNull => logIfNotEqual(JsNull, right.asInstanceOf[JsNull.type], newPath)
      case JsBoolean(value) => logIfNotEqual(value, right.asInstanceOf[JsBoolean].value, newPath)
      case JsNumber(value) => logIfNotEqual(value, right.asInstanceOf[JsNumber].value, newPath)
      case JsString(value) => logIfNotEqual(value, right.asInstanceOf[JsString].value, newPath)
      case JsArray(value) =>
        // For array we have to call showJsDiff on each element of array
        val arr1 = value
        val arr2 = right.asInstanceOf[JsArray].value
        if (arr1.length != arr2.length) {
          println(s"Arrays in '${getPath(newPath)}' have different length. ${arr1.length} != ${arr2.length}")
        }
        else {
          arr1.indices.foreach { idx =>
            showJsDiff(arr1(idx), arr2(idx), s"($idx)", newPath)
          }
        }
      case JsObject(value) =>
        val leftFields = value.keys.toSeq
        val rightJsObject = right.asInstanceOf[JsObject]
        val rightFields = rightJsObject.fields.map { case (name, value) => name }

        val absentInLeft = rightFields.diff(leftFields)
        if (absentInLeft.nonEmpty) {
          println("Next fields are absent in LEFT: ")
          absentInLeft.foreach { fieldName =>
            println(s"\t ${getPath(newPath :+ fieldName)}")
          }
        }
        val absentInRight = leftFields.diff(rightFields)
        if (absentInRight.nonEmpty) {
          println("Next fields are absent in RIGHT: ")
          absentInRight.foreach { fieldName =>
            println(s"\t ${getPath(newPath :+ fieldName)}")
          }
        }
        // For common fields we have to call showJsDiff on them
        val commonFields = leftFields.intersect(rightFields)
        commonFields.foreach { field =>
          showJsDiff(value(field), rightJsObject(field), field, newPath)
        }

    }
  }
}

def logIfNotEqual[T](left: T, right: T, path: Seq[String]): Unit = {
  if (left != right) {
    println(s"'${getPath(path)}' => $left != $right")
  }
}

def getPath(path: Seq[String]): String = path.mkString("\\")
</code>```

Body:
I have two json files, one is expected json and the another one is the result of GET API call. I need to compare and find out the mismatch in the file.

Expected Json:

{
  "array": [
    1,
    2,
    3
  ],
  "boolean": true,
  "null": null,
  "number": 123,
  "object": {
    "a": "b",
    "c": "d",
    "e": "f"
  },
  "string": "Hello World"
}

Actual Json response:

{
  "array": [
    1,
    2,
    3
  ],
  "boolean": true,
  "null": null,
  "number": 456,
  "object": {
    "a": "b",
    "c": "d",
    "e": "f"
  },
  "string": "India"
}

Actually there are two mismatch: number received is 456 and string is India.

Is there a way to compare and get these two mismatch as results.

This need to be implemented in gatling/scala.

Body:
You can use, for example, play-json library and recursively traverse both JSONs. For next input (a bit more sophisticated than yours input):

LEFT:

{
  "array" : [ 1, 2, 4 ],
  "boolean" : true,
  "null" : null,
  "number" : 123,
  "object" : {
    "a" : "b",
    "c" : "d",
    "e" : "f"
  },
  "string" : "Hello World",
  "absent-in-right" : true,
  "different-types" : 123
}

RIGHT:

{
  "array" : [ 1, 2, 3 ],
  "boolean" : true,
  "null" : null,
  "number" : 456,
  "object" : {
    "a" : "b",
    "c" : "d",
    "e" : "ff"
  },
  "string" : "India",
  "absent-in-left" : true,
  "different-types" : "YES"
}

It produces this output:

Next fields are absent in LEFT:
     *\absent-in-left
Next fields are absent in RIGHT:
     *\absent-in-right
'*\array\(2)' => 4 != 3
'*\number' => 123 != 456
'*\object\e' => f != ff
'*\string' => Hello World != India
Cannot compare JsNumber and JsString in '*\different-types'

Code:

val left = Json.parse("""{"array":[1,2,4],"boolean":true,"null":null,"number":123,"object":{"a":"b","c":"d","e":"f"},"string":"Hello World","absent-in-right":true,"different-types":123}""").asInstanceOf[JsObject]
val right = Json.parse("""{"array":[1,2,3],"boolean":true,"null":null,"number":456,"object":{"a":"b","c":"d","e":"ff"},"string":"India","absent-in-left":true,"different-types":"YES"}""").asInstanceOf[JsObject]

// '*' - for the root node
showJsDiff(left, right, "*", Seq.empty[String])

def showJsDiff(left: JsValue, right: JsValue, parent: String, path: Seq[String]): Unit = {
  val newPath = path :+ parent
  if (left.getClass != right.getClass) {
    println(s"Cannot compare ${left.getClass.getSimpleName} and ${right.getClass.getSimpleName} " +
      s"in '${getPath(newPath)}'")
  }
  else {
    left match {
      // Primitive types are pretty easy to handle
      case JsNull => logIfNotEqual(JsNull, right.asInstanceOf[JsNull.type], newPath)
      case JsBoolean(value) => logIfNotEqual(value, right.asInstanceOf[JsBoolean].value, newPath)
      case JsNumber(value) => logIfNotEqual(value, right.asInstanceOf[JsNumber].value, newPath)
      case JsString(value) => logIfNotEqual(value, right.asInstanceOf[JsString].value, newPath)
      case JsArray(value) =>
        // For array we have to call showJsDiff on each element of array
        val arr1 = value
        val arr2 = right.asInstanceOf[JsArray].value
        if (arr1.length != arr2.length) {
          println(s"Arrays in '${getPath(newPath)}' have different length. ${arr1.length} != ${arr2.length}")
        }
        else {
          arr1.indices.foreach { idx =>
            showJsDiff(arr1(idx), arr2(idx), s"($idx)", newPath)
          }
        }
      case JsObject(value) =>
        val leftFields = value.keys.toSeq
        val rightJsObject = right.asInstanceOf[JsObject]
        val rightFields = rightJsObject.fields.map { case (name, value) => name }

        val absentInLeft = rightFields.diff(leftFields)
        if (absentInLeft.nonEmpty) {
          println("Next fields are absent in LEFT: ")
          absentInLeft.foreach { fieldName =>
            println(s"\t ${getPath(newPath :+ fieldName)}")
          }
        }
        val absentInRight = leftFields.diff(rightFields)
        if (absentInRight.nonEmpty) {
          println("Next fields are absent in RIGHT: ")
          absentInRight.foreach { fieldName =>
            println(s"\t ${getPath(newPath :+ fieldName)}")
          }
        }
        // For common fields we have to call showJsDiff on them
        val commonFields = leftFields.intersect(rightFields)
        commonFields.foreach { field =>
          showJsDiff(value(field), rightJsObject(field), field, newPath)
        }

    }
  }
}

def logIfNotEqual[T](left: T, right: T, path: Seq[String]): Unit = {
  if (left != right) {
    println(s"'${getPath(path)}' => $left != $right")
  }
}

def getPath(path: Seq[String]): String = path.mkString("\\")


问:
HTML - Footer places itself above container
I am creating a small webpage to practice my HTML on and I can't seem to figure out why the Footer just places itself at underneath the Header instead of underneath the container I have created.

It is most likely something small that I have overlooked but I can't seem to figure out or a find a solution anywhere so advice here would be greatly appreciated.

header {
  height: 50px;
  width: 900px;
  color: white;
  margin: auto;
  padding: auto;
  background-color: black;
  display: block;
}

nav {
  float: right;
  background-color: black;
}

p,
h1,
h2,
li {
  font-family: sans-serif;
}

footer {
  height: 50px;
  width: 900px;
  color: white;
  margin: auto;
  background-color: black;
  text-align: center;
  padding: auto;
  display: block;
}

main {
  padding: auto;
  display: block;
}

#container {
  display: block;
  padding-bottom: 50px;
  margin: auto;
  width: 900px;
}

#left-column {
  display: inline-block;
  width: 450px;
  float: left;
}

#right-column {
  display: inline-block;
  float: right;
}

#button {
  border-radius: 5px;
  background-color: red;
  text-align: center;
  color: white;
  height: 50px;
  width: 80px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="container">
  <header>
    <p>Logo</p>
    <nav></nav>
  </header>
  <main>
    <div id="left-column">
      <h1>Website title</h1>
      <h2>Article title</h2>
      <p>Some text followed by a list:</p>
      <ul>
        <li>A list item</li>
        <li>A list item with a link (Click me)</li>
        <li>New deals daily</li>
      </ul>
      <p> Some more text</p>
    </div>
    <div id="right-column">
      <h2>Some content related to the article</h2>
      <div id="button">
        <p>A Button</p>
      </div>
    </div>
  </main>
  <footer>
    <p>©Website name 2017</p>
  </footer>
</div></code>```

答:
You need your footer to clear the floated elements that come before it by adding clear:both to your CSS:

header {
  height: 50px;
  width: 900px;
  color: white;
  margin: auto;
  padding: auto;
  background-color: black;
  display: block;
}

nav {
  float: right;
  background-color: black;
}

p,
h1,
h2,
li {
  font-family: sans-serif;
}

footer {
  height: 50px;
  width: 900px;
  color: white;
  margin: auto;
  background-color: black;
  text-align: center;
  padding: auto;
  display: block;
  clear:both;
}

main {
  padding: auto;
  display: block;
}

#container {
  display: block;
  padding-bottom: 50px;
  margin: auto;
  width: 900px;
}

#left-column {
  display: inline-block;
  width: 450px;
  float: left;
}

#right-column {
  display: inline-block;
  float: right;
}

#button {
  border-radius: 5px;
  background-color: red;
  text-align: center;
  color: white;
  height: 50px;
  width: 80px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="container">
  <header>
    <p>Logo</p>
    <nav></nav>
  </header>
  <main>
    <div id="left-column">
      <h1>Website title</h1>
      <h2>Article title</h2>
      <p>Some text followed by a list:</p>
      <ul>
        <li>A list item</li>
        <li>A list item with a link (Click me)</li>
        <li>New deals daily</li>
      </ul>
      <p> Some more text</p>
    </div>
    <div id="right-column">
      <h2>Some content related to the article</h2>
      <div id="button">
        <p>A Button</p>
      </div>
    </div>
  </main>
  <footer>
    <p>©Website name 2017</p>
  </footer>
</div></code>```

Body:
I am creating a small webpage to practice my HTML on and I can't seem to figure out why the Footer just places itself at underneath the Header instead of underneath the container I have created.

It is most likely something small that I have overlooked but I can't seem to figure out or a find a solution anywhere so advice here would be greatly appreciated.

header {
  height: 50px;
  width: 900px;
  color: white;
  margin: auto;
  padding: auto;
  background-color: black;
  display: block;
}

nav {
  float: right;
  background-color: black;
}

p,
h1,
h2,
li {
  font-family: sans-serif;
}

footer {
  height: 50px;
  width: 900px;
  color: white;
  margin: auto;
  background-color: black;
  text-align: center;
  padding: auto;
  display: block;
}

main {
  padding: auto;
  display: block;
}

#container {
  display: block;
  padding-bottom: 50px;
  margin: auto;
  width: 900px;
}

#left-column {
  display: inline-block;
  width: 450px;
  float: left;
}

#right-column {
  display: inline-block;
  float: right;
}

#button {
  border-radius: 5px;
  background-color: red;
  text-align: center;
  color: white;
  height: 50px;
  width: 80px;
}

Logo

Website title

Article title

Some text followed by a list:

A list item

A list item with a link (Click me)

New deals daily

 Some more text

Some content related to the article

A Button

©Website name 2017

Body:
You need your footer to clear the floated elements that come before it by adding clear:both to your CSS:

header {
  height: 50px;
  width: 900px;
  color: white;
  margin: auto;
  padding: auto;
  background-color: black;
  display: block;
}

nav {
  float: right;
  background-color: black;
}

p,
h1,
h2,
li {
  font-family: sans-serif;
}

footer {
  height: 50px;
  width: 900px;
  color: white;
  margin: auto;
  background-color: black;
  text-align: center;
  padding: auto;
  display: block;
  clear:both;
}

main {
  padding: auto;
  display: block;
}

#container {
  display: block;
  padding-bottom: 50px;
  margin: auto;
  width: 900px;
}

#left-column {
  display: inline-block;
  width: 450px;
  float: left;
}

#right-column {
  display: inline-block;
  float: right;
}

#button {
  border-radius: 5px;
  background-color: red;
  text-align: center;
  color: white;
  height: 50px;
  width: 80px;
}

<div id="container">
  <header>
    <p>Logo</p>
    <nav></nav>
  </header>
  <main>
    <div id="left-column">
      <h1>Website title</h1>
      <h2>Article title</h2>
      <p>Some text followed by a list:</p>
      <ul>
        <li>A list item</li>
        <li>A list item with a link (<a href="#">Click me</a>)</li>
        <li>New deals daily</li>
      </ul>
      <p> Some more text</p>
    </div>
    <div id="right-column">
      <h2>Some content related to the article</h2>
      <div id="button">
        <p>A Button</p>
      </div>
    </div>
  </main>
  <footer>
    <p>&copy;Website name 2017</p>
  </footer>
</div>


问:
How Can I Make WordPress's <?php the_title_attribute(); ?> Render %20 for Spaces?
I'm trying to render a WordPress theme that is 100% HTML5 compliant, and have managed my way through all but one snag.

At the end of certain posts I show a "Tweet" link, which uses the following source code in the Theme template:

```<code><a href="http://twitter.com/share?text=<?php the_title_attribute(); ?>&via=ianhines&url=<?php echo simple_url_shortener('','service=bit.ly+key&apikey=R_a6dc414291bb882024ddd99690f5eb61&login=ianhines&cache=no'); ?>" title="Share This Article on Twitter">Tweet</a>
</code>```

HTML5 forbids having spaces in URLs. They must be rendered as %20. However, <?php the_title_attribute; ?> renders an XHTML safe version of the Post Title with spaces maintained.

An example URL (rendered using the template source code above):

```<code>a href="http://twitter.com/share?text=Twitter, Reblog, and Email Comments&via=ianhines&url=http://ihin.es/eCoYN9" title="Share This Article on Twitter">Tweet</a>
</code>```

Is there any way I can force WordPress to render the spaces in this URL string as %20, and thereby make my site fully HTML5 compliant?

答:
```<code><?php
    $spaceurl=the_title_attribute('echo=0');
    $nonspaceurl=preg_replace('\s','%20',spaceurl);
?>

<a href="<?php echo $nonspaceurl; ?>">
    my link text
</a>
</code>```

EDIT

I added echo=0 to return the text instead of displaying it, see the_title_attribute.

Body:
I'm trying to render a WordPress theme that is 100% HTML5 compliant, and have managed my way through all but one snag.

At the end of certain posts I show a "Tweet" link, which uses the following source code in the Theme template:

<a href="http://twitter.com/share?text=<?php the_title_attribute(); ?>&via=ianhines&url=<?php echo simple_url_shortener('','service=bit.ly+key&apikey=R_a6dc414291bb882024ddd99690f5eb61&login=ianhines&cache=no'); ?>" title="Share This Article on Twitter">Tweet

HTML5 forbids having spaces in URLs. They must be rendered as %20. However, <?php the_title_attribute; ?> renders an XHTML safe version of the Post Title with spaces maintained.

An example URL (rendered using the template source code above):

a href="http://twitter.com/share?text=Twitter, Reblog, and Email Comments&via=ianhines&url=http://ihin.es/eCoYN9" title="Share This Article on Twitter">Tweet

Is there any way I can force WordPress to render the spaces in this URL string as %20, and thereby make my site fully HTML5 compliant?

Body:
<?php
    $spaceurl=the_title_attribute('echo=0');
    $nonspaceurl=preg_replace('\s','%20',spaceurl);
?>

<a href="<?php echo $nonspaceurl; ?>">
    my link text
</a>

EDIT

I added echo=0 to return the text instead of displaying it, see the_title_attribute.