问:
Error inflating class com.google.android.material.floatingactionbutton.FloatingActionButton Instrumentation Test
The app works fine if I normally run the app but when I try to test it shows error here is the full log of the error.

java.lang.RuntimeException: android.view.InflateException: Binary XML file line #14: Binary XML file line #14: Error inflating class com.google.android.material.floatingactionbutton.FloatingActionButton
  at androidx.test.runner.MonitoringInstrumentation.runOnMainSync(MonitoringInstrumentation.java:441)
  at androidx.test.core.app.ActivityScenario.onActivity(ActivityScenario.java:564)
  at androidx.fragment.app.testing.FragmentScenario.internalLaunch(FragmentScenario.java:300)
  at androidx.fragment.app.testing.FragmentScenario.launchInContainer(FragmentScenario.java:282)
  at androidx.fragment.app.testing.FragmentScenario.launchInContainer(FragmentScenario.java:262)
  at androidx.fragment.app.testing.FragmentScenario.launchInContainer(FragmentScenario.java:244)
  at androidx.fragment.app.testing.FragmentScenario.launchInContainer(FragmentScenario.java:228)
  at com.medium.todoapp.HomeFragmentInstrumentedTest.testRecyclerView(HomeFragmentInstrumentedTest.kt:14)
  at java.lang.reflect.Method.invoke(Native Method)
  at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
  at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
  at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
  at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
  at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
  at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:78)
  at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:57)
  at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
  at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
  at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
  at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
  at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
  at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
  at androidx.test.ext.junit.runners.AndroidJUnit4.run(AndroidJUnit4.java:104)
  at org.junit.runners.Suite.runChild(Suite.java:128)
  at org.junit.runners.Suite.runChild(Suite.java:27)
  at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
  at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
  at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
  at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
  at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
  at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
  at org.junit.runner.JUnitCore.run(JUnitCore.java:137)
  at org.junit.runner.JUnitCore.run(JUnitCore.java:115)
  at androidx.test.internal.runner.TestExecutor.execute(TestExecutor.java:56)
  at androidx.test.runner.AndroidJUnitRunner.onStart(AndroidJUnitRunner.java:392)
  at android.app.Instrumentation$InstrumentationThread.run(Instrumentation.java:1932)
  Caused by: android.view.InflateException: Binary XML file line #14: Binary XML file line #14: Error inflating class com.google.android.material.floatingactionbutton.FloatingActionButton
  Caused by: android.view.InflateException: Binary XML file line #14: Error inflating class com.google.android.material.floatingactionbutton.FloatingActionButton
  Caused by: java.lang.reflect.InvocationTargetException
  at java.lang.reflect.Constructor.newInstance0(Native Method)
  at java.lang.reflect.Constructor.newInstance(Constructor.java:430)
  at android.view.LayoutInflater.createView(LayoutInflater.java:645)
  at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:787)
  at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:727)
  at android.view.LayoutInflater.rInflate(LayoutInflater.java:858)
  at android.view.LayoutInflater.rInflateChildren(LayoutInflater.java:821)
  at android.view.LayoutInflater.inflate(LayoutInflater.java:518)
  at android.view.LayoutInflater.inflate(LayoutInflater.java:426)
  at com.medium.todoapp.HomeFragment.onCreateView(HomeFragment.kt:16)
  at androidx.fragment.app.Fragment.performCreateView(Fragment.java:2698)
  at androidx.fragment.app.FragmentStateManager.createView(FragmentStateManager.java:320)
  at androidx.fragment.app.FragmentManager.moveToState(FragmentManager.java:1187)
  at androidx.fragment.app.FragmentManager.moveToState(FragmentManager.java:1356)
  at androidx.fragment.app.FragmentManager.moveFragmentToExpectedState(FragmentManager.java:1434)
  at androidx.fragment.app.FragmentManager.moveToState(FragmentManager.java:1497)
  at androidx.fragment.app.BackStackRecord.executeOps(BackStackRecord.java:447)
  at androidx.fragment.app.FragmentManager.executeOps(FragmentManager.java:2169)
  at androidx.fragment.app.FragmentManager.executeOpsTogether(FragmentManager.java:1992)
  at androidx.fragment.app.FragmentManager.removeRedundantOperationsAndExecute(FragmentManager.java:1947)
  at androidx.fragment.app.FragmentManager.execSingleAction(FragmentManager.java:1818)
  at androidx.fragment.app.BackStackRecord.commitNow(BackStackRecord.java:297)
  at androidx.fragment.app.testing.FragmentScenario$1.perform(FragmentScenario.java:317)
  at androidx.fragment.app.testing.FragmentScenario$1.perform(FragmentScenario.java:301)
  at androidx.test.core.app.ActivityScenario.lambda$onActivity$2$ActivityScenario(ActivityScenario.java:551)
  at androidx.test.core.app.ActivityScenario$$Lambda$4.run(Unknown Source)
  at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:428)
  at java.util.concurrent.FutureTask.run(FutureTask.java:237)
  at android.app.Instrumentation$SyncRunnable.run(Instrumentation.java:1950)
  at android.os.Handler.handleCallback(Handler.java:751)
  at android.os.Handler.dispatchMessage(Handler.java:95)
  at android.os.Looper.loop(Looper.java:154)
  at android.app.ActivityThread.main(ActivityThread.java:6119)
  at java.lang.reflect.Method.invoke(Native Method)
  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886)
  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776)
  Caused by: java.lang.IllegalArgumentException: The style on this component requires your app theme to be Theme.AppCompat (or a descendant).
  at com.google.android.material.internal.ThemeEnforcement.checkTheme(ThemeEnforcement.java:243)
  at com.google.android.material.internal.ThemeEnforcement.checkAppCompatTheme(ThemeEnforcement.java:213)
  at com.google.android.material.internal.ThemeEnforcement.checkCompatibleTheme(ThemeEnforcement.java:148)
  at com.google.android.material.internal.ThemeEnforcement.obtainStyledAttributes(ThemeEnforcement.java:76)
  at com.google.android.material.floatingactionbutton.FloatingActionButton.(FloatingActionButton.java:211)
  at com.google.android.material.floatingactionbutton.FloatingActionButton.(FloatingActionButton.java:200)
  ... 36 more
  Test running failed: Instrumentation run failed due to 'Process crashed.'

Here is my XML file

```<code><?xml version="1.0" encoding="utf-8"?>
<layout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools">

    <data>

        <variable
            name="adapter"
            type="com.medium.todoapp.adapters.ToDoListAdapter" />
    </data>

    <androidx.constraintlayout.widget.ConstraintLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        tools:context=".HomeFragment">

        <androidx.recyclerview.widget.RecyclerView
            android:id="@+id/recyclerView"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            app:adapter="@{adapter}"
            app:layoutManager="androidx.recyclerview.widget.LinearLayoutManager"
            tools:listitem="@layout/item_todo" />

        <com.google.android.material.floatingactionbutton.FloatingActionButton
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_margin="20dp"
            app:layout_constraintBottom_toBottomOf="parent"
            app:layout_constraintEnd_toEndOf="parent" />

    </androidx.constraintlayout.widget.ConstraintLayout>
</layout>
</code>```

Here is my TestFile

```<code>@RunWith(AndroidJUnit4::class)
class HomeFragmentInstrumentedTest {

    @Test
    fun testRecyclerView() {
        val homeScenario = launchInContainer(HomeFragment::class.java)
        homeScenario.onFragment {
            Assert.assertNotEquals(it.view?.findViewById(R.id.recyclerView), null)
        }
    }

    @Test
    fun testAddTodoButton() {
        val homeScenario = launchInContainer(HomeFragment::class.java)
        homeScenario.onFragment {
            Assert.assertNotEquals(it.view?.findViewById(R.id.addToDo), null)
        }
    }
}
</code>```

```<code>override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
        bindings = DataBindingUtil.inflate(inflater, R.layout.fragment_home, container, false)
        bindings?.apply {
            this.adapter = ToDoListAdapter()
        }
        return bindings?.root
    }
</code>```

Build.gradle

```<code>apply plugin: 'com.android.application'
apply plugin: 'kotlin-android'
apply plugin: 'kotlin-android-extensions'
apply plugin: 'kotlin-kapt'

android {
    compileSdkVersion 29
    buildToolsVersion "29.0.2"

    defaultConfig {
        applicationId "com.medium.todoapp"
        minSdkVersion 21
        targetSdkVersion 29
        versionCode 1
        versionName "1.0"

        testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
    }

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

    dataBinding {
        enabled = true
    }

    kapt {
        generateStubs = true
    }

}

dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version"

    // AndroidX
    implementation 'androidx.appcompat:appcompat:1.1.0'
    implementation 'androidx.core:core-ktx:1.2.0'
    implementation 'androidx.constraintlayout:constraintlayout:1.1.3'
    implementation 'androidx.legacy:legacy-support-v4:1.0.0'

    // Test
    testImplementation 'junit:junit:4.13'
    androidTestImplementation 'androidx.test.ext:junit:1.1.1'
    androidTestImplementation 'androidx.test.espresso:espresso-core:3.2.0'

    // Tests
    testImplementation 'junit:junit:4.13'
    androidTestImplementation 'androidx.test.ext:junit:1.1.1'
    androidTestImplementation 'androidx.test.espresso:espresso-core:3.2.0'
    androidTestImplementation 'androidx.test:rules:1.2.0'

    // Mockito
    androidTestImplementation "org.mockito:mockito-core:2.24.5"
    androidTestImplementation "org.mockito:mockito-android:2.24.5"

    // FragmentScenario
    debugImplementation "org.jetbrains.kotlin:kotlin-stdlib:1.3.72"
    debugImplementation ("androidx.fragment:fragment-testing:1.2.4") {
        // required, while there is no version 1.2.0 yet.
        exclude group: "androidx.test", module: "core"
    }

    // Navigation Architecture Component
    implementation 'androidx.navigation:navigation-fragment-ktx:2.2.2'
    implementation 'androidx.navigation:navigation-ui-ktx:2.2.2'
}

</code>```

答:
Open the build.gradle file for your application.

Make sure that the repositories section includes Google's Maven Repository google(). For example:

```<code>  repositories {
    google()
    jcenter()
  }
</code>```

3.Add the library to the dependencies section:

```<code>    dependencies {
    // ...
    implementation 'com.google.android.material:material:<version>'
    // ...
  }
</code>```

more info link

Body:
The app works fine if I normally run the app but when I try to test it shows error here is the full log of the error.

java.lang.RuntimeException: android.view.InflateException: Binary XML file line #14: Binary XML file line #14: Error inflating class com.google.android.material.floatingactionbutton.FloatingActionButton
  at androidx.test.runner.MonitoringInstrumentation.runOnMainSync(MonitoringInstrumentation.java:441)
  at androidx.test.core.app.ActivityScenario.onActivity(ActivityScenario.java:564)
  at androidx.fragment.app.testing.FragmentScenario.internalLaunch(FragmentScenario.java:300)
  at androidx.fragment.app.testing.FragmentScenario.launchInContainer(FragmentScenario.java:282)
  at androidx.fragment.app.testing.FragmentScenario.launchInContainer(FragmentScenario.java:262)
  at androidx.fragment.app.testing.FragmentScenario.launchInContainer(FragmentScenario.java:244)
  at androidx.fragment.app.testing.FragmentScenario.launchInContainer(FragmentScenario.java:228)
  at com.medium.todoapp.HomeFragmentInstrumentedTest.testRecyclerView(HomeFragmentInstrumentedTest.kt:14)
  at java.lang.reflect.Method.invoke(Native Method)
  at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
  at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
  at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
  at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
  at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
  at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:78)
  at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:57)
  at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
  at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
  at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
  at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
  at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
  at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
  at androidx.test.ext.junit.runners.AndroidJUnit4.run(AndroidJUnit4.java:104)
  at org.junit.runners.Suite.runChild(Suite.java:128)
  at org.junit.runners.Suite.runChild(Suite.java:27)
  at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
  at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
  at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
  at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
  at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
  at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
  at org.junit.runner.JUnitCore.run(JUnitCore.java:137)
  at org.junit.runner.JUnitCore.run(JUnitCore.java:115)
  at androidx.test.internal.runner.TestExecutor.execute(TestExecutor.java:56)
  at androidx.test.runner.AndroidJUnitRunner.onStart(AndroidJUnitRunner.java:392)
  at android.app.Instrumentation$InstrumentationThread.run(Instrumentation.java:1932)
  Caused by: android.view.InflateException: Binary XML file line #14: Binary XML file line #14: Error inflating class com.google.android.material.floatingactionbutton.FloatingActionButton
  Caused by: android.view.InflateException: Binary XML file line #14: Error inflating class com.google.android.material.floatingactionbutton.FloatingActionButton
  Caused by: java.lang.reflect.InvocationTargetException
  at java.lang.reflect.Constructor.newInstance0(Native Method)
  at java.lang.reflect.Constructor.newInstance(Constructor.java:430)
  at android.view.LayoutInflater.createView(LayoutInflater.java:645)
  at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:787)
  at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:727)
  at android.view.LayoutInflater.rInflate(LayoutInflater.java:858)
  at android.view.LayoutInflater.rInflateChildren(LayoutInflater.java:821)
  at android.view.LayoutInflater.inflate(LayoutInflater.java:518)
  at android.view.LayoutInflater.inflate(LayoutInflater.java:426)
  at com.medium.todoapp.HomeFragment.onCreateView(HomeFragment.kt:16)
  at androidx.fragment.app.Fragment.performCreateView(Fragment.java:2698)
  at androidx.fragment.app.FragmentStateManager.createView(FragmentStateManager.java:320)
  at androidx.fragment.app.FragmentManager.moveToState(FragmentManager.java:1187)
  at androidx.fragment.app.FragmentManager.moveToState(FragmentManager.java:1356)
  at androidx.fragment.app.FragmentManager.moveFragmentToExpectedState(FragmentManager.java:1434)
  at androidx.fragment.app.FragmentManager.moveToState(FragmentManager.java:1497)
  at androidx.fragment.app.BackStackRecord.executeOps(BackStackRecord.java:447)
  at androidx.fragment.app.FragmentManager.executeOps(FragmentManager.java:2169)
  at androidx.fragment.app.FragmentManager.executeOpsTogether(FragmentManager.java:1992)
  at androidx.fragment.app.FragmentManager.removeRedundantOperationsAndExecute(FragmentManager.java:1947)
  at androidx.fragment.app.FragmentManager.execSingleAction(FragmentManager.java:1818)
  at androidx.fragment.app.BackStackRecord.commitNow(BackStackRecord.java:297)
  at androidx.fragment.app.testing.FragmentScenario$1.perform(FragmentScenario.java:317)
  at androidx.fragment.app.testing.FragmentScenario$1.perform(FragmentScenario.java:301)
  at androidx.test.core.app.ActivityScenario.lambda$onActivity$2$ActivityScenario(ActivityScenario.java:551)
  at androidx.test.core.app.ActivityScenario$$Lambda$4.run(Unknown Source)
  at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:428)
  at java.util.concurrent.FutureTask.run(FutureTask.java:237)
  at android.app.Instrumentation$SyncRunnable.run(Instrumentation.java:1950)
  at android.os.Handler.handleCallback(Handler.java:751)
  at android.os.Handler.dispatchMessage(Handler.java:95)
  at android.os.Looper.loop(Looper.java:154)
  at android.app.ActivityThread.main(ActivityThread.java:6119)
  at java.lang.reflect.Method.invoke(Native Method)
  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886)
  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776)
  Caused by: java.lang.IllegalArgumentException: The style on this component requires your app theme to be Theme.AppCompat (or a descendant).
  at com.google.android.material.internal.ThemeEnforcement.checkTheme(ThemeEnforcement.java:243)
  at com.google.android.material.internal.ThemeEnforcement.checkAppCompatTheme(ThemeEnforcement.java:213)
  at com.google.android.material.internal.ThemeEnforcement.checkCompatibleTheme(ThemeEnforcement.java:148)
  at com.google.android.material.internal.ThemeEnforcement.obtainStyledAttributes(ThemeEnforcement.java:76)
  at com.google.android.material.floatingactionbutton.FloatingActionButton.(FloatingActionButton.java:211)
  at com.google.android.material.floatingactionbutton.FloatingActionButton.(FloatingActionButton.java:200)
  ... 36 more
  Test running failed: Instrumentation run failed due to 'Process crashed.'

Here is my XML file

<?xml version="1.0" encoding="utf-8"?>
<layout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools">

    <data>

        <variable
            name="adapter"
            type="com.medium.todoapp.adapters.ToDoListAdapter" />
    </data>

    <androidx.constraintlayout.widget.ConstraintLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        tools:context=".HomeFragment">

        <androidx.recyclerview.widget.RecyclerView
            android:id="@+id/recyclerView"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            app:adapter="@{adapter}"
            app:layoutManager="androidx.recyclerview.widget.LinearLayoutManager"
            tools:listitem="@layout/item_todo" />

        <com.google.android.material.floatingactionbutton.FloatingActionButton
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_margin="20dp"
            app:layout_constraintBottom_toBottomOf="parent"
            app:layout_constraintEnd_toEndOf="parent" />

    </androidx.constraintlayout.widget.ConstraintLayout>
</layout>

Here is my TestFile

@RunWith(AndroidJUnit4::class)
class HomeFragmentInstrumentedTest {

    @Test
    fun testRecyclerView() {
        val homeScenario = launchInContainer(HomeFragment::class.java)
        homeScenario.onFragment {
            Assert.assertNotEquals(it.view?.findViewById(R.id.recyclerView), null)
        }
    }

    @Test
    fun testAddTodoButton() {
        val homeScenario = launchInContainer(HomeFragment::class.java)
        homeScenario.onFragment {
            Assert.assertNotEquals(it.view?.findViewById(R.id.addToDo), null)
        }
    }
}

override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
        bindings = DataBindingUtil.inflate(inflater, R.layout.fragment_home, container, false)
        bindings?.apply {
            this.adapter = ToDoListAdapter()
        }
        return bindings?.root
    }

Build.gradle

apply plugin: 'com.android.application'
apply plugin: 'kotlin-android'
apply plugin: 'kotlin-android-extensions'
apply plugin: 'kotlin-kapt'

android {
    compileSdkVersion 29
    buildToolsVersion "29.0.2"

    defaultConfig {
        applicationId "com.medium.todoapp"
        minSdkVersion 21
        targetSdkVersion 29
        versionCode 1
        versionName "1.0"

        testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
    }

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

    dataBinding {
        enabled = true
    }

    kapt {
        generateStubs = true
    }

}

dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version"

    // AndroidX
    implementation 'androidx.appcompat:appcompat:1.1.0'
    implementation 'androidx.core:core-ktx:1.2.0'
    implementation 'androidx.constraintlayout:constraintlayout:1.1.3'
    implementation 'androidx.legacy:legacy-support-v4:1.0.0'

    // Test
    testImplementation 'junit:junit:4.13'
    androidTestImplementation 'androidx.test.ext:junit:1.1.1'
    androidTestImplementation 'androidx.test.espresso:espresso-core:3.2.0'

    // Tests
    testImplementation 'junit:junit:4.13'
    androidTestImplementation 'androidx.test.ext:junit:1.1.1'
    androidTestImplementation 'androidx.test.espresso:espresso-core:3.2.0'
    androidTestImplementation 'androidx.test:rules:1.2.0'

    // Mockito
    androidTestImplementation "org.mockito:mockito-core:2.24.5"
    androidTestImplementation "org.mockito:mockito-android:2.24.5"

    // FragmentScenario
    debugImplementation "org.jetbrains.kotlin:kotlin-stdlib:1.3.72"
    debugImplementation ("androidx.fragment:fragment-testing:1.2.4") {
        // required, while there is no version 1.2.0 yet.
        exclude group: "androidx.test", module: "core"
    }

    // Navigation Architecture Component
    implementation 'androidx.navigation:navigation-fragment-ktx:2.2.2'
    implementation 'androidx.navigation:navigation-ui-ktx:2.2.2'
}

Body:
Open the build.gradle file for your application.

Make sure that the repositories section includes Google's Maven Repository google(). For example:

  repositories {
    google()
    jcenter()
  }

3.Add the library to the dependencies section:

    dependencies {
    // ...
    implementation 'com.google.android.material:material:<version>'
    // ...
  }

more info link


来源: stackexchange

问:
Django filter by two parameters
I want to filter by two parameters. I have this:

```<code>    def get_queryset(self):
        queryset = Product.objects.filter(
             Q(category__in=self.request.GET.getlist("category")) &
             Q(brand__in=self.request.GET.getlist("brand")))
        return queryset
</code>```

But this works only if two filters are chosen(otherwise it returns nothing). I want my program to filter by one filter if only one is chosen and filter by two parameters if two are chosen. How can I do that?

答:
You can do this.</p>

```<code>def get_queryset(self):
  kwargs = {}
  if self.request.GET.getlist("category"):
      kwargs["category__in"] = self.request.GET.getlist("category")

  if self.request.GET.getlist("brand"):
      kwargs["brand__in"] = self.request.GET.getlist("brand")

  return Product.objects.filter(**kwargs)
</code>```

ContentLicense: CC BY-SA 4.0

Title: Django filter by two parameters

Body:
I want to filter by two parameters. I have this:

    def get_queryset(self):
        queryset = Product.objects.filter(
             Q(category__in=self.request.GET.getlist("category")) &
             Q(brand__in=self.request.GET.getlist("brand")))
        return queryset

But this works only if two filters are chosen(otherwise it returns nothing). I want my program to filter by one filter if only one is chosen and filter by two parameters if two are chosen. How can I do that?

Body:
You can do this.

def get_queryset(self):
  kwargs = {}
  if self.request.GET.getlist("category"):
      kwargs["category__in"] = self.request.GET.getlist("category")

  if self.request.GET.getlist("brand"):
      kwargs["brand__in"] = self.request.GET.getlist("brand")

  return Product.objects.filter(**kwargs)


问:
flutter: top of image deleted in stack widget
I am trying to use stack in my widget tree:

```<code>  body: Center(
    child: SingleChildScrollView(
      child: Stack(
        overflow: Overflow.visible,
        children: <Widget>[
          Container(
            // card view
            alignment: Alignment.center,
            height: 200,
            margin: EdgeInsets.only(
                top: 20.0, bottom: 50.0, left: 50.0, right: 50.0),
            decoration: BoxDecoration(
              color: color_transparent_black,
              borderRadius: BorderRadius.circular(14.0),
            ),
          ),
          Positioned(
            top: -60,
            left: 0,
            right: 0,
            bottom: 0,
            child: Align(
              alignment: Alignment.topCenter,
              child: Container(
                width: width * 0.3,
                height: height * 0.2,
                child: CircleAvatar(
                  backgroundColor: Colors.transparent,
                  child: Image.asset("assets/images/ic_setting.png"),
                ),
              ),
            ),
          ),
        ],
      ),
    ),
  ),
);
</code>```

And this result is this:

Why top of setting icon has been deleted?

答:
Its most likely because you set the top: -60  for the Positioned widget.

Edit 1:

Stop clipping by removing SingleChildScrollView

And you can center all children of Stack using alignment: Alignment.topCenter property of Stack widget itself.

```<code> child: Center(
     child: Stack(
         overflow: Overflow.visible,
         alignment: Alignment.topCenter,
         children: <Widget>[
              Container(
                   height: 200,
                              ...
              ),
              Positioned(
                   top: -60,
                   ...
                   child: Container(
                               ...
                   ),
              ),
      ),
 ]),
</code>```

Body:
I am trying to use stack in my widget tree:

  body: Center(
    child: SingleChildScrollView(
      child: Stack(
        overflow: Overflow.visible,
        children: <Widget>[
          Container(
            // card view
            alignment: Alignment.center,
            height: 200,
            margin: EdgeInsets.only(
                top: 20.0, bottom: 50.0, left: 50.0, right: 50.0),
            decoration: BoxDecoration(
              color: color_transparent_black,
              borderRadius: BorderRadius.circular(14.0),
            ),
          ),
          Positioned(
            top: -60,
            left: 0,
            right: 0,
            bottom: 0,
            child: Align(
              alignment: Alignment.topCenter,
              child: Container(
                width: width * 0.3,
                height: height * 0.2,
                child: CircleAvatar(
                  backgroundColor: Colors.transparent,
                  child: Image.asset("assets/images/ic_setting.png"),
                ),
              ),
            ),
          ),
        ],
      ),
    ),
  ),
);

And this result is this:

Why top of setting icon has been deleted?

Body:
Its most likely because you set the top: -60  for the Positioned widget.

Edit 1:

Stop clipping by removing SingleChildScrollView

And you can center all children of Stack using alignment: Alignment.topCenter property of Stack widget itself.

 child: Center(
     child: Stack(
         overflow: Overflow.visible,
         alignment: Alignment.topCenter,
         children: <Widget>[
              Container(
                   height: 200,
                              ...
              ),
              Positioned(
                   top: -60,
                   ...
                   child: Container(
                               ...
                   ),
              ),
      ),
 ]),


问:
How to get permalinks on a non-Wordpress site
Hello guys I have some websites I'm currently building but I have a problem...I have pages such as blogPosts.php?postID=7

I would love something like blogPosts.com/post title

Meaning I dont want people to see the variables I'm passing..

Same applies to a couple of other pages. I was told that permalinks is the key but everywhere I check, all I see is Wordpress but I am designing my site from scratch.

I'm running XAMPP from my pc.

I would really appreciate any help..

Thanks a lot

答:
It sounds like you want to make "clean" URLs.

You can do it using Apache configuration files and PHP.

Here's an article which will tell you how.

ContentLicense: CC BY-SA 3.0


问:
Can I clean-up / delete local Composer directory?
I have about 800 json files with a total of 1 GB in composer\Local\repo\https---repo.packagist.org

What's the purpose of those files? What might happen if I just remove them?

composer\Local\files\ contains 80 MB only.

答: Simply clear the cache with composer clear-cache.


问:
Fail to create a custom domain name for websocket API gateway using AWS Cloudformation
I need to create a custom domain name for a websocket enabled API gateway and seems that CloudFormation for API gateway v2 (which is basically for websocket) doesn’t support it (at least the documentation  https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/cfn-reference-apigatewayv2.html  doesn’t mention this). I tried with AWS::ApiGateway::DomainName which I believe is for Rest API gateway but the stack fails with the error

This custom domain name cannot map to WEBSOCKET protocol Apis.

I see that AWS CLI does support API gateway v2 create domain name command (https://docs.aws.amazon.com/cli/latest/reference/apigatewayv2/create-domain-name.html) but not sure the reason why the CloudFormation wouldn’t support this.

Any workaround or feedback would be greatly appreciated.

答:
No more need of lambda, https://stackoverflow.com/a/61834163/9799292

This Cloud Formation template is working just fine

```<code>Resources:
    WebSocketDomainName:
      Type: AWS::ApiGatewayV2::DomainName
      Properties:
        DomainName: <domain-name>
        DomainNameConfigurations:
          - EndpointType: 'REGIONAL'
            CertificateArn: <cert-arn>
    WebSocketMapping:
      Type: AWS::ApiGatewayV2::ApiMapping
      Properties:
        ApiId: <app-id>
        DomainName: !Ref WebSocketDomainName
        Stage: <stage-name>
</code>```

Body:
No more need of lambda, https://stackoverflow.com/a/61834163/9799292

This Cloud Formation template is working just fine

Resources:
    WebSocketDomainName:
      Type: AWS::ApiGatewayV2::DomainName
      Properties:
        DomainName: <domain-name>
        DomainNameConfigurations:
          - EndpointType: 'REGIONAL'
            CertificateArn: <cert-arn>
    WebSocketMapping:
      Type: AWS::ApiGatewayV2::ApiMapping
      Properties:
        ApiId: <app-id>
        DomainName: !Ref WebSocketDomainName
        Stage: <stage-name>


问:
Explicitly setting type on window for Intercom in Typescript throws error
As per the discussion here, I have had to extend the window object in order to strongly type Intercom's window functionality.

Originally the code used to look like this:

```<code>  setCurrentRoute() {
    if (
      this.currentRoute.getValue().indexOf('website') > -1 ||
      this.currentRoute.getValue().indexOf('builder') > -1
    ) {
      (window as any).Intercom('update', {
        hide_default_launcher: true,
      });
    } else {
      (window as any).Intercom('update', {
        hide_default_launcher: false,
      });
    }
    localStorage.setItem('currentRoute', this.currentRoute.getValue());
  }
</code>```

But as I am trying to leverage more of Typescript's type safety features, it now looks like this:

```<code>  declare global {
    interface Window {
      Intercom(update: string, params: { hide_default_launcher: boolean }): void;
    }
  }

  setCurrentRoute(): void {
    if (this.currentRoute.getValue().indexOf('website') > -1 || this.currentRoute.getValue().indexOf('builder') > -1) {
      this.window.Intercom('update', {
        'hide_default_launcher': true
      });
    } else {
      this.window.Intercom('update', {
        'hide_default_launcher': false
      });
    }
    localStorage.setItem('currentRoute', this.currentRoute.getValue());
  }
</code>```

However, I get the following error message:

```<code>ERROR TypeError: Cannot read property 'Intercom' of undefined
    at RouterService.push../src/app/shared/services/router.service.ts.RouterService.setCurrentRoute
</code>```

How do I fix it?

答:
I managed to fix it by doing the following:</p>

```<code>export interface RouterWindow extends Window {
  Intercom(update: string, params: { hide_default_launcher: boolean }): void;
}

  setCurrentRoute(): void {
    if (this.currentRoute.getValue().indexOf('website') > -1 || this.currentRoute.getValue().indexOf('builder') > -1) {
      (<RouterWindow>window).Intercom('update', {
        'hide_default_launcher': true
      });
    } else {
      (<RouterWindow>window).Intercom('update', {
        'hide_default_launcher': false
      });
    }
    localStorage.setItem('currentRoute', this.currentRoute.getValue());
  }
</code>```

Body:
As per the discussion here, I have had to extend the window object in order to strongly type Intercom's window functionality.

Originally the code used to look like this:

  setCurrentRoute() {
    if (
      this.currentRoute.getValue().indexOf('website') > -1 ||
      this.currentRoute.getValue().indexOf('builder') > -1
    ) {
      (window as any).Intercom('update', {
        hide_default_launcher: true,
      });
    } else {
      (window as any).Intercom('update', {
        hide_default_launcher: false,
      });
    }
    localStorage.setItem('currentRoute', this.currentRoute.getValue());
  }

But as I am trying to leverage more of Typescript's type safety features, it now looks like this:

  declare global {
    interface Window {
      Intercom(update: string, params: { hide_default_launcher: boolean }): void;
    }
  }

  setCurrentRoute(): void {
    if (this.currentRoute.getValue().indexOf('website') > -1 || this.currentRoute.getValue().indexOf('builder') > -1) {
      this.window.Intercom('update', {
        'hide_default_launcher': true
      });
    } else {
      this.window.Intercom('update', {
        'hide_default_launcher': false
      });
    }
    localStorage.setItem('currentRoute', this.currentRoute.getValue());
  }

However, I get the following error message:

ERROR TypeError: Cannot read property 'Intercom' of undefined
    at RouterService.push../src/app/shared/services/router.service.ts.RouterService.setCurrentRoute

How do I fix it?

Body:
I managed to fix it by doing the following:

export interface RouterWindow extends Window {
  Intercom(update: string, params: { hide_default_launcher: boolean }): void;
}

  setCurrentRoute(): void {
    if (this.currentRoute.getValue().indexOf('website') > -1 || this.currentRoute.getValue().indexOf('builder') > -1) {
      (<RouterWindow>window).Intercom('update', {
        'hide_default_launcher': true
      });
    } else {
      (<RouterWindow>window).Intercom('update', {
        'hide_default_launcher': false
      });
    }
    localStorage.setItem('currentRoute', this.currentRoute.getValue());
  }


问:
Value for argument "documentPath" is not a valid resource path. Path must be a non-empty string
I want to write a cloud function  that listens to whether a new document is created in the following subcollection of some document of users. However, the user document upon previous creation may not have a following subcollection.

In other words, I want a cloud that responds to db.collection(“users”).doc(“doc_id1”).collection(“following”).doc(“doc_id2”).set(new_document)
, and I have written the cloud function to be

```<code>exports.create_friend_request_onCreate = functions.firestore
  .document("users/{user_id}/{following}/{following_id}")
  .onCreate(f2);
</code>```

And implementation of  f2 is written in some other file

```<code>exports.f2 = async function(snapshot) {
 //some code
}
</code>```

However upon creation the document in the subcollection, I get the following error

Error: Value for argument "documentPath" is not a valid resource path. Path must be a non-empty string.

Can someone explain to me what is wrong here?

答:
Change this:

```<code>  .document("users/{user_id}/{following}/{following_id}")
</code>```

into this:

```<code>  .document("users/{user_id}/following/{following_id}")
</code>```

The collection shouldn't have a {wildcard}

Body:
I want to write a cloud function  that listens to whether a new document is created in the following subcollection of some document of users. However, the user document upon previous creation may not have a following subcollection.

In other words, I want a cloud that responds to db.collection(“users”).doc(“doc_id1”).collection(“following”).doc(“doc_id2”).set(new_document)
, and I have written the cloud function to be

exports.create_friend_request_onCreate = functions.firestore
  .document("users/{user_id}/{following}/{following_id}")
  .onCreate(f2);

And implementation of  f2 is written in some other file

exports.f2 = async function(snapshot) {
 //some code
}

However upon creation the document in the subcollection, I get the following error

Error: Value for argument "documentPath" is not a valid resource path. Path must be a non-empty string.

Can someone explain to me what is wrong here?

Body:
Change this:

  .document("users/{user_id}/{following}/{following_id}")

into this:

  .document("users/{user_id}/following/{following_id}")

The collection shouldn't have a {wildcard}


问:
How do I dynamically add multiple lines to a windows form tab?
I am trying to add a collection of lines to a tab dynamically, however after loading they do not continue to display correctly. Eventually I would like to have up to a few hundred.

Initially it will look like the first version but after scrolling the lines look like the second version.

In order to add these lines I have added a Paint event to the tab in the designer as:

this.TabTree.Paint += new System.Windows.Forms.PaintEventHandler(this.PaintLines);

And created a method

```<code>    private void PaintLines(object sender, PaintEventArgs e)
    {
        System.Drawing.Graphics g = e.Graphics;
        int linesLen = Lines.Count();
        for (int i = 0; i < linesLen; i++)
        {
            g.DrawLine(Pens.Red, Lines[i].X1, Lines[i].Y1, Lines[i].X2, Lines[i].Y2);
        }
    }
</code>```

This is based off the advise in here:

https://www.experts-exchange.com/questions/25024010/How-do-I-draw-a-line-on-the-page-of-a-tab-control.html

I think I am missing something about how Paint events work. I tried initially going through the main Paint event for the form but couldn't get the lines to show on the tab. I would also like to be able to delete and update the lines if possible.

If you can provide any information on how better to implement line drawing to a tab dynamically, or an alternative approach I would be very grateful. Maybe a way to clear the lines and redraw when a scroll event happens?

Thank you.

答:
I figured it out. I needed a refresh event to occur. That can happen from a button as in the link below or in my case at a scroll event. New code:

```<code>    private void TabTree_Scroll(object sender, ScrollEventArgs e)
    {
        TabTree.Refresh();
        scrollPos = e.NewValue;
    }

    private void PaintLines(object sender, PaintEventArgs e)
    {

        System.Drawing.Graphics g = e.Graphics;
        int linesLen = Lines.Count();
        for (int i = 0; i < linesLen; i++)
        {
            g.DrawLine(penObj, Lines[i].X1, Lines[i].Y1 - scrollPos, Lines[i].X2, Lines[i].Y2 - scrollPos);
        }
    }
</code>```

Helpful link:
https://www.youtube.com/watch?v=Jc5eXYwTROg

Body:
I am trying to add a collection of lines to a tab dynamically, however after loading they do not continue to display correctly. Eventually I would like to have up to a few hundred.

Initially it will look like the first version but after scrolling the lines look like the second version.

In order to add these lines I have added a Paint event to the tab in the designer as:

this.TabTree.Paint += new System.Windows.Forms.PaintEventHandler(this.PaintLines);

And created a method

    private void PaintLines(object sender, PaintEventArgs e)
    {
        System.Drawing.Graphics g = e.Graphics;
        int linesLen = Lines.Count();
        for (int i = 0; i < linesLen; i++)
        {
            g.DrawLine(Pens.Red, Lines[i].X1, Lines[i].Y1, Lines[i].X2, Lines[i].Y2);
        }
    }

This is based off the advise in here:

https://www.experts-exchange.com/questions/25024010/How-do-I-draw-a-line-on-the-page-of-a-tab-control.html

I think I am missing something about how Paint events work. I tried initially going through the main Paint event for the form but couldn't get the lines to show on the tab. I would also like to be able to delete and update the lines if possible.

If you can provide any information on how better to implement line drawing to a tab dynamically, or an alternative approach I would be very grateful. Maybe a way to clear the lines and redraw when a scroll event happens?

Thank you.

Body:
I figured it out. I needed a refresh event to occur. That can happen from a button as in the link below or in my case at a scroll event. New code:

    private void TabTree_Scroll(object sender, ScrollEventArgs e)
    {
        TabTree.Refresh();
        scrollPos = e.NewValue;
    }

    private void PaintLines(object sender, PaintEventArgs e)
    {

        System.Drawing.Graphics g = e.Graphics;
        int linesLen = Lines.Count();
        for (int i = 0; i < linesLen; i++)
        {
            g.DrawLine(penObj, Lines[i].X1, Lines[i].Y1 - scrollPos, Lines[i].X2, Lines[i].Y2 - scrollPos);
        }
    }

Helpful link:
https://www.youtube.com/watch?v=Jc5eXYwTROg


问:
MySQL not using PHP variables properly in Queries, replacing the variables with strings/integers works fine
MySQL is not using the variables as it should. it is not taking any value from them it is incrementing the auto-increment numbers in the MYSQL table, however the row is not saved. I am not given any errors.

I have tried like this:

```<code>$sql = "INSERT INTO `tbl_bike` (`userID`, `ManuPartNo`, `BikeManufacturer`, `BikeModel`, `BikeType`, `BikeWheel`, `BikeColour`, `BikeSpeed`, `BrakeType`, `FrameGender`, `AgeGroup`, `DistFeatures`)
VALUES (“.$userID.”, “.$PartNo.”, “.$BikeManufacturer.”, “.$BikeModel.”, “.$BikeType.”, “.$BikeWheel.”, “.$BikeColour.”, “.$BikeSpeed.”, “.$BrakeType.”, “.$FrameGender.”, “.$AgeGroup.”, “.$DistFeatures.”)";
</code>```

I have also tried replacing the " with ', Removing the . and even completely removing the ". Nothing has helped with this issue. When I use this query but remove the variables and instead put string, int etc in the correct places the query will function perfectly and put the results into the table. My variables are normally as follows:

```<code>$PartNo =  $_POST['ManuPartNo’];

$BikeManufacturer =  $_POST['BikeManufacturer’];

$BikeModel =  $_POST['BikeModel’];

$BikeType =  $_POST['BikeType’];

$BikeWheel =  $_POST['BikeWheel’];

$BikeColour =  $_POST['BikeColour’];

$BikeSpeed =  $_POST['BikeSpeed’];

$BrakeType =  $_POST['BrakeType’];

$FrameGender =  $_POST['FrameGender’];

$AgeGroup =  $_POST['AgeGroup’];

$DistFeatures =  $_POST['DistFeatures’];

</code>```

These variables normally take input from a separate PHP/HTML file with the '$_POST['DistFeatures’];'

I have tried removing the $_POST['DistFeatures’]; from the ends of each of them and just replacing the values with normal string or int values but still nothing helps. I am completely stuck and would appreciate any help with this.

This is all running on a plesk server.

答:
You should try this

```<code>$sql = "INSERT INTO tbl_bike (userID, ManuPartNo, BikeManufacturer, BikeModel, BikeType, BikeWheel, BikeColour, BikeSpeed, BrakeType, FrameGender, AgeGroup, DistFeatures) VALUES ('$userID', '$PartNo', '$BikeManufacturer', '$BikeModel', '$BikeType', '$BikeWheel', '$BikeColour', '$BikeSpeed', '$BrakeType', '$FrameGender', '$AgeGroup', '$DistFeatures')";
</code>```

If this doesn't work, enable the null property in sql values. So you can find out where the error originated.

Body:
MySQL is not using the variables as it should. it is not taking any value from them it is incrementing the auto-increment numbers in the MYSQL table, however the row is not saved. I am not given any errors.

I have tried like this:

$sql = "INSERT INTO `tbl_bike` (`userID`, `ManuPartNo`, `BikeManufacturer`, `BikeModel`, `BikeType`, `BikeWheel`, `BikeColour`, `BikeSpeed`, `BrakeType`, `FrameGender`, `AgeGroup`, `DistFeatures`)
VALUES (“.$userID.”, “.$PartNo.”, “.$BikeManufacturer.”, “.$BikeModel.”, “.$BikeType.”, “.$BikeWheel.”, “.$BikeColour.”, “.$BikeSpeed.”, “.$BrakeType.”, “.$FrameGender.”, “.$AgeGroup.”, “.$DistFeatures.”)";

I have also tried replacing the " with ', Removing the . and even completely removing the ". Nothing has helped with this issue. When I use this query but remove the variables and instead put string, int etc in the correct places the query will function perfectly and put the results into the table. My variables are normally as follows:

$PartNo =  $_POST['ManuPartNo’];

$BikeManufacturer =  $_POST['BikeManufacturer’];

$BikeModel =  $_POST['BikeModel’];

$BikeType =  $_POST['BikeType’];

$BikeWheel =  $_POST['BikeWheel’];

$BikeColour =  $_POST['BikeColour’];

$BikeSpeed =  $_POST['BikeSpeed’];

$BrakeType =  $_POST['BrakeType’];

$FrameGender =  $_POST['FrameGender’];

$AgeGroup =  $_POST['AgeGroup’];

$DistFeatures =  $_POST['DistFeatures’];

These variables normally take input from a separate PHP/HTML file with the '$_POST['DistFeatures’];'

I have tried removing the $_POST['DistFeatures’]; from the ends of each of them and just replacing the values with normal string or int values but still nothing helps. I am completely stuck and would appreciate any help with this.

This is all running on a plesk server.

Body:
You should try this

$sql = "INSERT INTO tbl_bike (userID, ManuPartNo, BikeManufacturer, BikeModel, BikeType, BikeWheel, BikeColour, BikeSpeed, BrakeType, FrameGender, AgeGroup, DistFeatures) VALUES ('$userID', '$PartNo', '$BikeManufacturer', '$BikeModel', '$BikeType', '$BikeWheel', '$BikeColour', '$BikeSpeed', '$BrakeType', '$FrameGender', '$AgeGroup', '$DistFeatures')";

If this doesn't work, enable the null property in sql values. So you can find out where the error originated.


问:
Upload a binary file using pure JavaScript
I'm working on a Chrome app that uses the HTML5 Filesystem API, and allows users to import and sync files.  One issue I'm having is that if the user tries to sync image files, the files get corrupted during the upload process to the server.  I'm assuming it's because they're binary.

For uploading, I opted just to make an Ajax POST request (using MooTools) and then put the file contents as the body of the request.  I told MooTools to turn off urlEncoding and set the charset to "x-user-defined" (not sure if that's necessary, I just saw it on some websites).

Given that Chrome doesn't have support for xhr.sendAsBinary, does anyone have any sample code that would allow me to send binary files via Ajax?

答:
FF's xhr.sendAsBinary() is not standard. XHR2 supports sending files (xhr.send(file)) and blobs (xhr.send(blob)):

```<code>function upload(blobOrFile) {
  var xhr = new XMLHttpRequest();
  xhr.open('POST', '/server', true);
  xhr.onload = function(e) { ... };

  // Listen to the upload progress.
  xhr.upload.onprogress = function(e) { ... };

  xhr.send(blobOrFile);
}
</code>```

You can also send an ArrayBuffer.

Body:
FF's xhr.sendAsBinary() is not standard. XHR2 supports sending files (xhr.send(file)) and blobs (xhr.send(blob)):

function upload(blobOrFile) {
  var xhr = new XMLHttpRequest();
  xhr.open('POST', '/server', true);
  xhr.onload = function(e) { ... };

  // Listen to the upload progress.
  xhr.upload.onprogress = function(e) { ... };

  xhr.send(blobOrFile);
}

You can also send an ArrayBuffer.


问:
I need to split this data into its own sets so that i may call on them when need
in java code
 The main this I have to do is read this file into an internal data structure

I just don't know how to split each room up and keep its data together while being able to call on either the id or description  etc. by its self when need but still keeping it as all in the room, so bedroom keeps all its information but when need I can call id or description separably

(this is my data they are rooms with a ID , name , summary about it and its exit ways)

```<code>Rooms:
ID=1, name = Bed Room
Description :
You are standing in the middle of a dark room. It's your room, but something feels off everything is gone just a plan dark room.
You see a red light sighing under the door it seems like a way to exit.
You can go North from here out the Door.
exits
North 2;
ID=2, name = Hallway
Description :
You enter the Hallway still noticing a red light, but it's still coming way down at the other end. You look around and notice patches of torn spots on the wall
full of black voids looking spots. Slowly sucking in more of the room. Everything else is black, and grey, just like your room was with more objects missing.
You know the red light is at the other end of the hallway with a entrance to the living room
exits
North 3, South 1;
ID=3, name = Living-room
Description :
You enter the living room its still has some color left, but you notice its slowly fading away on the table in the middle of the room surrounded by to gray couches.
you look over to your East and hear a Scream coming from the Dinning-room
but also notice Movement through the West Leading to the Basement
exits
East 4, West 5, South 2;
ID=4, name = Dinning-room
Description :
You have entered the Dinning-room and Notice shadows moving around the room you feel a cold and lifeless wind.
You are continuing to hear Screams but not from this room its coming from the East that leads to the Front-yard The screams get louder for ever step you get closer
exits
West 3, East 6;
ID=5, name = Basement
Description :
You have enter the Basement its empty and cold never felt temperatures this low. you notice smoke coming out of you mouth but also three different spots in
each corner of the basement also forming smoke just as you are.
There is not Exit other then East where you came from.
exits
East 3;
ID=6, name = Front-yard
Description :
You entered the Front-yard you notices Shadows moving along the lawn back in the fort but no ones there just you and you garden and your thoughts the driveway has no Cars
You notice you're all alone, but it can be possible you hear and see unexceptionable things. The house is floating in a endless void there is no where to go.
your only way is back into the house West
exits
West 4;
</code>```

答:
Looking at your data, in order to determine an appropriate implementation, I feel that the the exit directions should be an enum.

public enum Direction {
    EAST, NORTH, SOUTH, WEST;
}
```

<p>And an <em>exit</em> is a combination of a direction plus a number, i.e. how many room exits are there in the given direction. So I created a <code>RoomExit</code> class.</p>

<pre class="lang-java prettyprint-override"><code>public class RoomExit {
    private Direction  direction;
    private int  count;

    public RoomExit(Direction direction, int count) {
        if (count < 0) {
            throw new IllegalArgumentException("negative exits");
        }
        this.direction = direction;
        this.count = count;
    }

    public Direction getDirection() {
        return direction;
    }

    public int getCount() {
        return count;
    }
}
</code>```

Finally, your sample data describes a series of rooms where each room has an ID, a name, a description and a number of exits. So I created a RoomData class.

import java.util.ArrayList;
import java.util.List;

public class RoomData {
    private int  id;
    private String  name;
    private String  description;
    private List<RoomExit>  exits;

    public RoomData(int id, String name) {
        this.id = id;
        this.name = name;
        exits = new ArrayList<>();
    }

    public boolean addExit(RoomExit exit) {
        return exits.add(exit);
    }

    public String getDescription() {
        return description;
    }

    public void setDescription(String description) {
        this.description = description;
    }

    public int getId() {
        return id;
    }

    public String getName() {
        return name;
    }

    public List<RoomExit> getExits() {
        return exits;
    }

    public String toString() {
        return String.format("%d %s [%s] %d exits", id, name, description, exits.size());
    }
}
```

<p>Then I created a "driver" class that reads the text file containing the rooms data (I named this file <code>roomdata.txt</code>) and creates a list of rooms.</p>

<pre class="lang-java prettyprint-override"><code>import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

public class RoomTest {
    private static final String  COMMA = ",";
    private static final String  DESCRIPTION = "Description :";
    private static final String  EQUALS = "=";
    private static final String  EXITS = "exits";
    private static final String  ID = "ID";
    private static final String  SEMI_COLON = ";";

    private static int getRoomId(String line) {
        Objects.requireNonNull(line, "null line");
        String[] firstSplit = line.split(COMMA);
        if (firstSplit.length != 2) {
            throw new IllegalArgumentException("Unexpected line: " + line);
        }
        String[] secondSplit = firstSplit[0].split(EQUALS);
        if (secondSplit.length != 2) {
            throw new IllegalArgumentException("Unexpected line: " + line);
        }
        int roomId = Integer.parseInt(secondSplit[1].trim());
        return roomId;
    }

    private static String getRoomName(String line) {
        Objects.requireNonNull(line, "null line");
        String[] firstSplit = line.split(COMMA);
        if (firstSplit.length != 2) {
            throw new IllegalArgumentException("Unexpected line: " + line);
        }
        String[] secondSplit = firstSplit[1].split(EQUALS);
        if (secondSplit.length != 2) {
            throw new IllegalArgumentException("Unexpected line: " + line);
        }
        return secondSplit[1].trim();
    }

    private static void setRoomExits(RoomData room, String line) {
        Objects.requireNonNull(line, "null line");
        line = line.trim();
        if (line.endsWith(SEMI_COLON)) {
            line = line.substring(0, line.length() - 1);
        }
        String[] exits = line.split(COMMA);
        for (String exit : exits) {
            exit = exit.trim();
            String[] parts = exit.split(" ");
            if (parts.length != 2) {
                throw new IllegalArgumentException("Unexpected exit: " + exit);
            }
            RoomExit roomExit = new RoomExit(Direction.valueOf(parts[0].trim().toUpperCase()),
                                             Integer.parseInt(parts[1].trim()));
            room.addExit(roomExit);
        }
    }

    public static void main(String[] args) {
        try (FileReader fr = new FileReader("roomdata.txt");
             BufferedReader br = new BufferedReader(fr)) {
            boolean isExits = false;
            List<RoomData> rooms = new ArrayList<>();
            RoomData room = null;
            String line = br.readLine();
            StringBuilder description = null;
            while (line != null) {
                if (line.startsWith(ID)) {
                    if (room != null) {
                        isExits = false;
                        room.setDescription(description.toString());
                        rooms.add(room);
                        description = null;
                    }
                    room = new RoomData(getRoomId(line), getRoomName(line));
                }
                else if (DESCRIPTION.equals(line)) {
                    description = new StringBuilder();
                }
                else if (EXITS.equals(line)) {
                    isExits = true;
                }
                else {
                    if (isExits) {
                        setRoomExits(room, line);
                    }
                    else {
                        description.append(line);
                        description.append(System.lineSeparator());
                    }
                }
                line = br.readLine();
            }
            if (room != null) {
                room.setDescription(description.toString());
                rooms.add(room);
            }
            System.out.printf("There are %d rooms.%n", rooms.size());
            rooms.forEach(System.out::println);
        }
        catch (IOException xIo) {
            xIo.printStackTrace();
        }
    }
}
</code>```

Here is the output when running the above "driver" program.

```<code>There are 6 rooms.
1 Bed Room [You are standing in the middle of a dark room. It's your room, but something feels off everything is gone just a plan dark room.
You see a red light sighing under the door it seems like a way to exit.
You can go North from here out the Door.
] 1 exits
2 Hallway [You enter the Hallway still noticing a red light, but it's still coming way down at the other end. You look around and notice patches of torn spots on the wall
full of black voids looking spots. Slowly sucking in more of the room. Everything else is black, and grey, just like your room was with more objects missing.
You know the red light is at the other end of the hallway with a entrance to the living room
] 2 exits
3 Living-room [You enter the living room its still has some color left, but you notice its slowly fading away on the table in the middle of the room surrounded by to gray couches.
you look over to your East and hear a Scream coming from the Dinning-room
but also notice Movement through the West Leading to the Basement
] 3 exits
4 Dinning-room [You have entered the Dinning-room and Notice shadows moving around the room you feel a cold and lifeless wind.
You are continuing to hear Screams but not from this room its coming from the East that leads to the Front-yard The screams get louder for ever step you get closer
] 2 exits
5 Basement [You have enter the Basement its empty and cold never felt temperatures this low. you notice smoke coming out of you mouth but also three different spots in
each corner of the basement also forming smoke just as you are.
There is not Exit other then East where you came from.
] 1 exits
6 Front-yard [You entered the Front-yard you notices Shadows moving along the lawn back in the fort but no ones there just you and you garden and your thoughts the driveway has no Cars
You notice you're all alone, but it can be possible you hear and see unexceptionable things. The house is floating in a endless void there is no where to go.
your only way is back into the house West
] 1 exits
</code>```

Body:
in java code
 The main this I have to do is read this file into an internal data structure

I just don't know how to split each room up and keep its data together while being able to call on either the id or description  etc. by its self when need but still keeping it as all in the room, so bedroom keeps all its information but when need I can call id or description separably

(this is my data they are rooms with a ID , name , summary about it and its exit ways)

Rooms:
ID=1, name = Bed Room
Description :
You are standing in the middle of a dark room. It's your room, but something feels off everything is gone just a plan dark room.
You see a red light sighing under the door it seems like a way to exit.
You can go North from here out the Door.
exits
North 2;
ID=2, name = Hallway
Description :
You enter the Hallway still noticing a red light, but it's still coming way down at the other end. You look around and notice patches of torn spots on the wall
full of black voids looking spots. Slowly sucking in more of the room. Everything else is black, and grey, just like your room was with more objects missing.
You know the red light is at the other end of the hallway with a entrance to the living room
exits
North 3, South 1;
ID=3, name = Living-room
Description :
You enter the living room its still has some color left, but you notice its slowly fading away on the table in the middle of the room surrounded by to gray couches.
you look over to your East and hear a Scream coming from the Dinning-room
but also notice Movement through the West Leading to the Basement
exits
East 4, West 5, South 2;
ID=4, name = Dinning-room
Description :
You have entered the Dinning-room and Notice shadows moving around the room you feel a cold and lifeless wind.
You are continuing to hear Screams but not from this room its coming from the East that leads to the Front-yard The screams get louder for ever step you get closer
exits
West 3, East 6;
ID=5, name = Basement
Description :
You have enter the Basement its empty and cold never felt temperatures this low. you notice smoke coming out of you mouth but also three different spots in
each corner of the basement also forming smoke just as you are.
There is not Exit other then East where you came from.
exits
East 3;
ID=6, name = Front-yard
Description :
You entered the Front-yard you notices Shadows moving along the lawn back in the fort but no ones there just you and you garden and your thoughts the driveway has no Cars
You notice you're all alone, but it can be possible you hear and see unexceptionable things. The house is floating in a endless void there is no where to go.
your only way is back into the house West
exits
West 4;

Body:
Looking at your data, in order to determine an appropriate implementation, I feel that the the exit directions should be an enum.

public enum Direction {
    EAST, NORTH, SOUTH, WEST;
}

And an exit is a combination of a direction plus a number, i.e. how many room exits are there in the given direction. So I created a RoomExit class.

public class RoomExit {
    private Direction  direction;
    private int  count;

    public RoomExit(Direction direction, int count) {
        if (count < 0) {
            throw new IllegalArgumentException("negative exits");
        }
        this.direction = direction;
        this.count = count;
    }

    public Direction getDirection() {
        return direction;
    }

    public int getCount() {
        return count;
    }
}

Finally, your sample data describes a series of rooms where each room has an ID, a name, a description and a number of exits. So I created a RoomData class.

import java.util.ArrayList;
import java.util.List;

public class RoomData {
    private int  id;
    private String  name;
    private String  description;
    private List<RoomExit>  exits;

    public RoomData(int id, String name) {
        this.id = id;
        this.name = name;
        exits = new ArrayList<>();
    }

    public boolean addExit(RoomExit exit) {
        return exits.add(exit);
    }

    public String getDescription() {
        return description;
    }

    public void setDescription(String description) {
        this.description = description;
    }

    public int getId() {
        return id;
    }

    public String getName() {
        return name;
    }

    public List<RoomExit> getExits() {
        return exits;
    }

    public String toString() {
        return String.format("%d %s [%s] %d exits", id, name, description, exits.size());
    }
}

Then I created a "driver" class that reads the text file containing the rooms data (I named this file roomdata.txt) and creates a list of rooms.

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

public class RoomTest {
    private static final String  COMMA = ",";
    private static final String  DESCRIPTION = "Description :";
    private static final String  EQUALS = "=";
    private static final String  EXITS = "exits";
    private static final String  ID = "ID";
    private static final String  SEMI_COLON = ";";

    private static int getRoomId(String line) {
        Objects.requireNonNull(line, "null line");
        String[] firstSplit = line.split(COMMA);
        if (firstSplit.length != 2) {
            throw new IllegalArgumentException("Unexpected line: " + line);
        }
        String[] secondSplit = firstSplit[0].split(EQUALS);
        if (secondSplit.length != 2) {
            throw new IllegalArgumentException("Unexpected line: " + line);
        }
        int roomId = Integer.parseInt(secondSplit[1].trim());
        return roomId;
    }

    private static String getRoomName(String line) {
        Objects.requireNonNull(line, "null line");
        String[] firstSplit = line.split(COMMA);
        if (firstSplit.length != 2) {
            throw new IllegalArgumentException("Unexpected line: " + line);
        }
        String[] secondSplit = firstSplit[1].split(EQUALS);
        if (secondSplit.length != 2) {
            throw new IllegalArgumentException("Unexpected line: " + line);
        }
        return secondSplit[1].trim();
    }

    private static void setRoomExits(RoomData room, String line) {
        Objects.requireNonNull(line, "null line");
        line = line.trim();
        if (line.endsWith(SEMI_COLON)) {
            line = line.substring(0, line.length() - 1);
        }
        String[] exits = line.split(COMMA);
        for (String exit : exits) {
            exit = exit.trim();
            String[] parts = exit.split(" ");
            if (parts.length != 2) {
                throw new IllegalArgumentException("Unexpected exit: " + exit);
            }
            RoomExit roomExit = new RoomExit(Direction.valueOf(parts[0].trim().toUpperCase()),
                                             Integer.parseInt(parts[1].trim()));
            room.addExit(roomExit);
        }
    }

    public static void main(String[] args) {
        try (FileReader fr = new FileReader("roomdata.txt");
             BufferedReader br = new BufferedReader(fr)) {
            boolean isExits = false;
            List<RoomData> rooms = new ArrayList<>();
            RoomData room = null;
            String line = br.readLine();
            StringBuilder description = null;
            while (line != null) {
                if (line.startsWith(ID)) {
                    if (room != null) {
                        isExits = false;
                        room.setDescription(description.toString());
                        rooms.add(room);
                        description = null;
                    }
                    room = new RoomData(getRoomId(line), getRoomName(line));
                }
                else if (DESCRIPTION.equals(line)) {
                    description = new StringBuilder();
                }
                else if (EXITS.equals(line)) {
                    isExits = true;
                }
                else {
                    if (isExits) {
                        setRoomExits(room, line);
                    }
                    else {
                        description.append(line);
                        description.append(System.lineSeparator());
                    }
                }
                line = br.readLine();
            }
            if (room != null) {
                room.setDescription(description.toString());
                rooms.add(room);
            }
            System.out.printf("There are %d rooms.%n", rooms.size());
            rooms.forEach(System.out::println);
        }
        catch (IOException xIo) {
            xIo.printStackTrace();
        }
    }
}

Here is the output when running the above "driver" program.

There are 6 rooms.
1 Bed Room [You are standing in the middle of a dark room. It's your room, but something feels off everything is gone just a plan dark room.
You see a red light sighing under the door it seems like a way to exit.
You can go North from here out the Door.
] 1 exits
2 Hallway [You enter the Hallway still noticing a red light, but it's still coming way down at the other end. You look around and notice patches of torn spots on the wall
full of black voids looking spots. Slowly sucking in more of the room. Everything else is black, and grey, just like your room was with more objects missing.
You know the red light is at the other end of the hallway with a entrance to the living room
] 2 exits
3 Living-room [You enter the living room its still has some color left, but you notice its slowly fading away on the table in the middle of the room surrounded by to gray couches.
you look over to your East and hear a Scream coming from the Dinning-room
but also notice Movement through the West Leading to the Basement
] 3 exits
4 Dinning-room [You have entered the Dinning-room and Notice shadows moving around the room you feel a cold and lifeless wind.
You are continuing to hear Screams but not from this room its coming from the East that leads to the Front-yard The screams get louder for ever step you get closer
] 2 exits
5 Basement [You have enter the Basement its empty and cold never felt temperatures this low. you notice smoke coming out of you mouth but also three different spots in
each corner of the basement also forming smoke just as you are.
There is not Exit other then East where you came from.
] 1 exits
6 Front-yard [You entered the Front-yard you notices Shadows moving along the lawn back in the fort but no ones there just you and you garden and your thoughts the driveway has no Cars
You notice you're all alone, but it can be possible you hear and see unexceptionable things. The house is floating in a endless void there is no where to go.
your only way is back into the house West
] 1 exits


问:
Problem with requests.get() inside a loop. "No connection adapters found"
So I'm trying to scrape several pages using their JSON versions. When I run the code for a single URL (as in the first part of the code attached), I do get the desired output, however, when I try to do the same inside a for loop for several URLs, I get a "No connection adapters found" from requests, which doesn't make much sense because it is working for the same URL outside of the for loop.

```<code># Import package
import requests
from pandas import json_normalize
import pandas as pd

# Assign URL to variable: url
url = 'https://www.olx.com.gt/api/relevance/search?category=367&facet_limit=100&location=4168811&location_facet_limit=20&page=1&sorting=desc-creation&user=16c20011d0fx61aada41'

# Package the request, send the request and catch the response: r
r = requests.get(url)

# Decode the JSON data into a dictionary: json_data
json_data = r.json()

# Extract data from the Json file
json_data_2 = json_data['data']

#normalize json data into a dataframe
df = json_normalize(json_data_2)
df.head()
</code>```

Everything runs smoothly with this script. Here's where I get the error.

```<code>%%time

n_paginas = 0

all_urls = pd.DataFrame()

for paginas in range(0,20):
    n_paginas += 1
    olx_url = 'https://www.olx.com.gt/api/relevance/search?category=367&facet_limit=100&location=4168811&location_facet_limit=20&page=%s&sorting=desc-creation&user=16c20011d0fx61aada41'
    start_urls = [olx_url % n_paginas]
    r = requests.get(start_urls)
    #json_data = r.json()
    #json_data_2 = json_data['data']
    #df = json_normalize(json_data_2)
    #all_urls.apped(df)
</code>```

And this is the traceback:

```<code>---------------------------------------------------------------------------
InvalidSchema                             Traceback (most recent call last)
<timed exec> in <module>

~/anaconda3/lib/python3.7/site-packages/requests/api.py in get(url, params, **kwargs)
     74
     75     kwargs.setdefault('allow_redirects', True)
---> 76     return request('get', url, params=params, **kwargs)
     77
     78

~/anaconda3/lib/python3.7/site-packages/requests/api.py in request(method, url, **kwargs)
     59     # cases, and look like a memory leak in others.
     60     with sessions.Session() as session:
---> 61         return session.request(method=method, url=url, **kwargs)
     62
     63

~/anaconda3/lib/python3.7/site-packages/requests/sessions.py in request(self, method, url, params, data, headers, cookies, files, auth, timeout, allow_redirects, proxies, hooks, stream, verify, cert, json)
    528         }
    529         send_kwargs.update(settings)
--> 530         resp = self.send(prep, **send_kwargs)
    531
    532         return resp

~/anaconda3/lib/python3.7/site-packages/requests/sessions.py in send(self, request, **kwargs)
    635
    636         # Get the appropriate adapter to use
--> 637         adapter = self.get_adapter(url=request.url)
    638
    639         # Start time (approximately) of the request

~/anaconda3/lib/python3.7/site-packages/requests/sessions.py in get_adapter(self, url)
    726
    727         # Nothing matches :-/
--> 728         raise InvalidSchema("No connection adapters were found for {!r}".format(url))
    729
    730     def close(self):

InvalidSchema: No connection adapters were found for "['https://www.olx.com.gt/api/relevance/search?category=367&facet_limit=100&location=4168811&location_facet_limit=20&page=1&sorting=desc-creation&user=16c20011d0fx61aada41']"
</code>```

The new URLs based on the page number are being generated correctly, and if I input any of them on the script above it does work.

Any help will be highly appreciated.

Thank you in advance.

答:
You probably don't need the start_urls = [olx_url % n_paginas] part. Either way this slight modification to the for loop seemed to get the result.

```<code># Import package
import requests
from pandas import json_normalize
import pandas as pd

# Assign URL to variable: url
url = 'https://www.olx.com.gt/api/relevance/search?category=367&facet_limit=100&location=4168811&location_facet_limit=20&page=1&sorting=desc-creation&user=16c20011d0fx61aada41'

# Package the request, send the request and catch the response: r
r = requests.get(url)

# Decode the JSON data into a dictionary: json_data
json_data = r.json()

# Extract data from the Json file
json_data_2 = json_data['data']

#normalize json data into a dataframe
df = json_normalize(json_data_2)
df.head()

n_paginas = 0

all_urls = pd.DataFrame()

for paginas in range(0,20):
    n_paginas += 1
    olx_url = 'https://www.olx.com.gt/api/relevance/search?category=367&facet_limit=100&location=4168811&location_facet_limit=20&page={}&sorting=desc-creation&user=16c20011d0fx61aada41'.format(str(n_paginas))
    r = requests.get(olx_url)
    all_urls = all_urls.append(pd.DataFrame(json_normalize(r.json()['data'])))

all_urls.shape

(400, 60)
</code>```

Body:
So I'm trying to scrape several pages using their JSON versions. When I run the code for a single URL (as in the first part of the code attached), I do get the desired output, however, when I try to do the same inside a for loop for several URLs, I get a "No connection adapters found" from requests, which doesn't make much sense because it is working for the same URL outside of the for loop.

# Import package
import requests
from pandas import json_normalize
import pandas as pd

# Assign URL to variable: url
url = 'https://www.olx.com.gt/api/relevance/search?category=367&facet_limit=100&location=4168811&location_facet_limit=20&page=1&sorting=desc-creation&user=16c20011d0fx61aada41'

# Package the request, send the request and catch the response: r
r = requests.get(url)

# Decode the JSON data into a dictionary: json_data
json_data = r.json()

# Extract data from the Json file
json_data_2 = json_data['data']

#normalize json data into a dataframe
df = json_normalize(json_data_2)
df.head()

Everything runs smoothly with this script. Here's where I get the error.

%%time

n_paginas = 0

all_urls = pd.DataFrame()

for paginas in range(0,20):
    n_paginas += 1
    olx_url = 'https://www.olx.com.gt/api/relevance/search?category=367&facet_limit=100&location=4168811&location_facet_limit=20&page=%s&sorting=desc-creation&user=16c20011d0fx61aada41'
    start_urls = [olx_url % n_paginas]
    r = requests.get(start_urls)
    #json_data = r.json()
    #json_data_2 = json_data['data']
    #df = json_normalize(json_data_2)
    #all_urls.apped(df)

And this is the traceback:

---------------------------------------------------------------------------
InvalidSchema                             Traceback (most recent call last)
<timed exec> in <module>

~/anaconda3/lib/python3.7/site-packages/requests/api.py in get(url, params, **kwargs)
     74
     75     kwargs.setdefault('allow_redirects', True)
---> 76     return request('get', url, params=params, **kwargs)
     77
     78

~/anaconda3/lib/python3.7/site-packages/requests/api.py in request(method, url, **kwargs)
     59     # cases, and look like a memory leak in others.
     60     with sessions.Session() as session:
---> 61         return session.request(method=method, url=url, **kwargs)
     62
     63

~/anaconda3/lib/python3.7/site-packages/requests/sessions.py in request(self, method, url, params, data, headers, cookies, files, auth, timeout, allow_redirects, proxies, hooks, stream, verify, cert, json)
    528         }
    529         send_kwargs.update(settings)
--> 530         resp = self.send(prep, **send_kwargs)
    531
    532         return resp

~/anaconda3/lib/python3.7/site-packages/requests/sessions.py in send(self, request, **kwargs)
    635
    636         # Get the appropriate adapter to use
--> 637         adapter = self.get_adapter(url=request.url)
    638
    639         # Start time (approximately) of the request

~/anaconda3/lib/python3.7/site-packages/requests/sessions.py in get_adapter(self, url)
    726
    727         # Nothing matches :-/
--> 728         raise InvalidSchema("No connection adapters were found for {!r}".format(url))
    729
    730     def close(self):

InvalidSchema: No connection adapters were found for "['https://www.olx.com.gt/api/relevance/search?category=367&facet_limit=100&location=4168811&location_facet_limit=20&page=1&sorting=desc-creation&user=16c20011d0fx61aada41']"

The new URLs based on the page number are being generated correctly, and if I input any of them on the script above it does work.

Any help will be highly appreciated.

Thank you in advance.

Body:
You probably don't need the start_urls = [olx_url % n_paginas] part. Either way this slight modification to the for loop seemed to get the result.

# Import package
import requests
from pandas import json_normalize
import pandas as pd

# Assign URL to variable: url
url = 'https://www.olx.com.gt/api/relevance/search?category=367&facet_limit=100&location=4168811&location_facet_limit=20&page=1&sorting=desc-creation&user=16c20011d0fx61aada41'

# Package the request, send the request and catch the response: r
r = requests.get(url)

# Decode the JSON data into a dictionary: json_data
json_data = r.json()

# Extract data from the Json file
json_data_2 = json_data['data']

#normalize json data into a dataframe
df = json_normalize(json_data_2)
df.head()

n_paginas = 0

all_urls = pd.DataFrame()

for paginas in range(0,20):
    n_paginas += 1
    olx_url = 'https://www.olx.com.gt/api/relevance/search?category=367&facet_limit=100&location=4168811&location_facet_limit=20&page={}&sorting=desc-creation&user=16c20011d0fx61aada41'.format(str(n_paginas))
    r = requests.get(olx_url)
    all_urls = all_urls.append(pd.DataFrame(json_normalize(r.json()['data'])))

all_urls.shape

(400, 60)


问:
How to construct a STL file from blob return type
I have created a service to download STL file from a URL :-

service.ts:-

```<code>fetchData(filename:string) {

  let headers = new HttpHeaders();
  headers = headers.set('Accept', 'application/STL');
  return this.http.get(filename, { headers: headers, responseType: 'blob' });

}
</code>```

How can I construct the STL file now from this response?

答:
```<code>this.fetchData.subscribe((res) => {
   let url = window.URL.createObjectURL(res);
        let a = document.createElement('a');
        document.body.appendChild(a);
        a.setAttribute('style', 'display: none');
        a.href = url;
        a.download = res.filename;
        a.click();
        window.URL.revokeObjectURL(url);
        a.remove();
});
</code>```

Body:
I have created a service to download STL file from a URL :-

service.ts:-

fetchData(filename:string) {

  let headers = new HttpHeaders();
  headers = headers.set('Accept', 'application/STL');
  return this.http.get(filename, { headers: headers, responseType: 'blob' });

}

How can I construct the STL file now from this response?


问:
How to remove unused images from an Xcode project
I'm following this link to find the unused images from an xcode project but they are not working well for me. I tried Rob's answer and Roman's answer but they give me all the png images.
I tried to use the tool it also giving me all png images

EDIT

The way Im using script

1)i copy script and paste it in the terminal and press Enter.

2) save the script in txt file and in terminal i type sh myscript.txt

答:
I have created a python script to identify the unused images in a swift project: 'unused_assets.py' @ gist, which can be easily tweaked for an objective-c project as yours.

The script can be used like this:

```<code>python3 unused_assets.py '/Users/DevK/MyProject' '/Users/DevK/MyProject/MyProject/Assets/Assets.xcassets'
</code>```

Here are few rules to use the script:

It is important to pass project folder path as first argument, assets folder path as second argument

It is assumed that all the images are maintained within Assets.xcassets folder and are used either within swift/ objective-c files or within storyboards

Limitations in first version:

Doesn't work for objective c files, but can be tweaked to achieve expected behavior as specified in comment in below code

I will try to improve it over the time, based on feedback, however the first version should be good for most.

Here is the code. I tried to make the code self explanatory by adding appropriate comments to each important step, let me know if you still need more details.

```<code># Usage e.g.: python3 unused_assets.py '/Users/DevK/MyProject' '/Users/DevK/MyProject/MyProject/Assets/Assets.xcassets'
# It is important to pass project folder path as first argument, assets folder path as second argument
# It is assumed that all the images are maintained within Assets.xcassets folder and are used either within swift files or within storyboards

"""
@author = "Devarshi Kulshreshtha"
@copyright = "Copyright 2020, Devarshi Kulshreshtha"
@license = "GPL"
@version = "1.0.1"
@contact = "kulshreshtha.devarshi@gmail.com"
"""

import sys
import glob
from pathlib import Path
import mmap
import os
import time

# obtain start time
start = time.time()

arguments = sys.argv

# pass project folder path as argument 1
projectFolderPath = arguments[1].replace("\\", "") # replacing backslash with space
# pass assets folder path as argument 2
assetsPath = arguments[2].replace("\\", "") # replacing backslash with space

print(f"assetsPath: {assetsPath}")
print(f"projectFolderPath: {projectFolderPath}")

# obtain all assets / images
# obtain paths for all assets

assetsSearchablePath = assetsPath + '/**/*.imageset'  #alternate way to append: fr"{assetsPath}/**/*.imageset"
print(f"assetsSearchablePath: {assetsSearchablePath}")

imagesNameCountDict = {} # empty dict to store image name as key and occurrence count
for imagesetPath in glob.glob(assetsSearchablePath, recursive=True):
    # storing the image name as encoded so that we save some time later during string search in file
    encodedImageName = str.encode(Path(imagesetPath).stem)
    # initializing occurrence count as 0
    imagesNameCountDict[encodedImageName] = 0

print("Names of all assets obtained")

# search images in swift files
# obtain paths for all swift files

# For objective-c project, change '/**/*.swift' to '/**/*.m'
swiftFilesSearchablePath = projectFolderPath + '/**/*.swift' #alternate way to append: fr"{projectFolderPath}/**/*.swift"
print(f"swiftFilesSearchablePath: {swiftFilesSearchablePath}")

for swiftFilePath in glob.glob(swiftFilesSearchablePath, recursive=True):
    with open(swiftFilePath, 'rb', 0) as file, \
        mmap.mmap(file.fileno(), 0, access=mmap.ACCESS_READ) as s:
        # search all the assests within the swift file
        for encodedImageName in imagesNameCountDict:
            # file search
            if s.find(encodedImageName) != -1:
                # updating occurrence count, if found
                imagesNameCountDict[encodedImageName] += 1

print("Images searched in all swift files!")

# search images in storyboards
# obtain path for all storyboards

storyboardsSearchablePath = projectFolderPath + '/**/*.storyboard' #alternate way to append: fr"{projectFolderPath}/**/*.storyboard"
print(f"storyboardsSearchablePath: {storyboardsSearchablePath}")
for storyboardPath in glob.glob(storyboardsSearchablePath, recursive=True):
    with open(storyboardPath, 'rb', 0) as file, \
        mmap.mmap(file.fileno(), 0, access=mmap.ACCESS_READ) as s:
        # search all the assests within the storyboard file
        for encodedImageName in imagesNameCountDict:
            # file search
            if s.find(encodedImageName) != -1:
                # updating occurrence count, if found
                imagesNameCountDict[encodedImageName] += 1

print("Images searched in all storyboard files!")
print("Here is the list of unused assets:")

# printing all image names, for which occurrence count is 0
print('\n'.join({encodedImageName.decode("utf-8", "strict") for encodedImageName, occurrenceCount in imagesNameCountDict.items() if occurrenceCount == 0}))

print(f"Done in {time.time() - start} seconds!")
</code>```

Body:
I have created a python script to identify the unused images in a swift project: 'unused_assets.py' @ gist, which can be easily tweaked for an objective-c project as yours.

The script can be used like this:

python3 unused_assets.py '/Users/DevK/MyProject' '/Users/DevK/MyProject/MyProject/Assets/Assets.xcassets'

Here are few rules to use the script:

It is important to pass project folder path as first argument, assets folder path as second argument

It is assumed that all the images are maintained within Assets.xcassets folder and are used either within swift/ objective-c files or within storyboards

Limitations in first version:

Doesn't work for objective c files, but can be tweaked to achieve expected behavior as specified in comment in below code

I will try to improve it over the time, based on feedback, however the first version should be good for most.

Here is the code. I tried to make the code self explanatory by adding appropriate comments to each important step, let me know if you still need more details.

# Usage e.g.: python3 unused_assets.py '/Users/DevK/MyProject' '/Users/DevK/MyProject/MyProject/Assets/Assets.xcassets'
# It is important to pass project folder path as first argument, assets folder path as second argument
# It is assumed that all the images are maintained within Assets.xcassets folder and are used either within swift files or within storyboards

"""
@author = "Devarshi Kulshreshtha"
@copyright = "Copyright 2020, Devarshi Kulshreshtha"
@license = "GPL"
@version = "1.0.1"
@contact = "kulshreshtha.devarshi@gmail.com"
"""

import sys
import glob
from pathlib import Path
import mmap
import os
import time

# obtain start time
start = time.time()

arguments = sys.argv

# pass project folder path as argument 1
projectFolderPath = arguments[1].replace("\\", "") # replacing backslash with space
# pass assets folder path as argument 2
assetsPath = arguments[2].replace("\\", "") # replacing backslash with space

print(f"assetsPath: {assetsPath}")
print(f"projectFolderPath: {projectFolderPath}")

# obtain all assets / images
# obtain paths for all assets

assetsSearchablePath = assetsPath + '/**/*.imageset'  #alternate way to append: fr"{assetsPath}/**/*.imageset"
print(f"assetsSearchablePath: {assetsSearchablePath}")

imagesNameCountDict = {} # empty dict to store image name as key and occurrence count
for imagesetPath in glob.glob(assetsSearchablePath, recursive=True):
    # storing the image name as encoded so that we save some time later during string search in file
    encodedImageName = str.encode(Path(imagesetPath).stem)
    # initializing occurrence count as 0
    imagesNameCountDict[encodedImageName] = 0

print("Names of all assets obtained")

# search images in swift files
# obtain paths for all swift files

# For objective-c project, change '/**/*.swift' to '/**/*.m'
swiftFilesSearchablePath = projectFolderPath + '/**/*.swift' #alternate way to append: fr"{projectFolderPath}/**/*.swift"
print(f"swiftFilesSearchablePath: {swiftFilesSearchablePath}")

for swiftFilePath in glob.glob(swiftFilesSearchablePath, recursive=True):
    with open(swiftFilePath, 'rb', 0) as file, \
        mmap.mmap(file.fileno(), 0, access=mmap.ACCESS_READ) as s:
        # search all the assests within the swift file
        for encodedImageName in imagesNameCountDict:
            # file search
            if s.find(encodedImageName) != -1:
                # updating occurrence count, if found
                imagesNameCountDict[encodedImageName] += 1

print("Images searched in all swift files!")

# search images in storyboards
# obtain path for all storyboards

storyboardsSearchablePath = projectFolderPath + '/**/*.storyboard' #alternate way to append: fr"{projectFolderPath}/**/*.storyboard"
print(f"storyboardsSearchablePath: {storyboardsSearchablePath}")
for storyboardPath in glob.glob(storyboardsSearchablePath, recursive=True):
    with open(storyboardPath, 'rb', 0) as file, \
        mmap.mmap(file.fileno(), 0, access=mmap.ACCESS_READ) as s:
        # search all the assests within the storyboard file
        for encodedImageName in imagesNameCountDict:
            # file search
            if s.find(encodedImageName) != -1:
                # updating occurrence count, if found
                imagesNameCountDict[encodedImageName] += 1

print("Images searched in all storyboard files!")
print("Here is the list of unused assets:")

# printing all image names, for which occurrence count is 0
print('\n'.join({encodedImageName.decode("utf-8", "strict") for encodedImageName, occurrenceCount in imagesNameCountDict.items() if occurrenceCount == 0}))

print(f"Done in {time.time() - start} seconds!")


问:
ASP.NET Custom Control With A Property That Is An Interface
I want to have a property on my custom control that is an interface type. For example:

```<code>[
    ToolboxData("<{0}:MyTextBox runat=server></{0}:MyTextBox"),
    ParseChildren(true, "Validation")
]
class MyTextBox : WebControl
{
    [
        Category("Behavior"),
        Description("The validation to use"),
        DesignerSerializationVisibility(DesignerSerializationVisibility.Content),
        PersistenceMode(PersistenceMode.InnerDefaultProperty)
    ]
    public IValidation Validation { get; set; }
}
</code>```

Then when I go to use my control in a web form I would like to be able to do:

```<code>        <my:MyTextBox ID="txt" runat="server">
            <my:FancyValidator  />
        </my:MyTextBox>
</code>```

That way I will be able to define one class that could use any number of validators. When I try and do this now, I end up with an error saying:

Type 'IValidator' does not have a public property named 'FancyValidator'

What do I need to do to make this work?

Thanks!

答:
As a side note, I found that I can make this work if I make Validation of type List then the markup looks like this:

```<code><my:MyTextBox ID="txt" runat="server">
 <Validation>
   <my:FancyValidator />
 </Validation>
</my:MyTextBox>
</code>```

Not quite what I was after, but works.

ContentLicense: CC BY-SA 2.5

Body:
I want to have a property on my custom control that is an interface type. For example:

[
    ToolboxData("<{0}:MyTextBox runat=server></{0}:MyTextBox"),
    ParseChildren(true, "Validation")
]
class MyTextBox : WebControl
{
    [
        Category("Behavior"),
        Description("The validation to use"),
        DesignerSerializationVisibility(DesignerSerializationVisibility.Content),
        PersistenceMode(PersistenceMode.InnerDefaultProperty)
    ]
    public IValidation Validation { get; set; }
}

Then when I go to use my control in a web form I would like to be able to do:

        <my:MyTextBox ID="txt" runat="server">
            <my:FancyValidator  />
        </my:MyTextBox>

That way I will be able to define one class that could use any number of validators. When I try and do this now, I end up with an error saying:

Type 'IValidator' does not have a public property named 'FancyValidator'

What do I need to do to make this work?

Thanks!

Body:
As a side note, I found that I can make this work if I make Validation of type List then the markup looks like this:

<my:MyTextBox ID="txt" runat="server">
 <Validation>
   <my:FancyValidator />
 </Validation>
</my:MyTextBox>

Not quite what I was after, but works.


问:
How do you make every text display perfectly in the center of the image?
Look that every text is displayed below the picture. I would like every text to be displayed perfectly in the center of the picture.

Here is the code:
https://jsfiddle.net/Krzysiek_35/Ljybwz97/37/

body {
  left: 8%;
  top: 10%;
  position: absolute;
  background-color: #6699cc;
}

.box3 {
    background-color: #191919;
    position: absolute;
    padding: 15px 40px 15px;
    font-size: 12px;
    color: #DDDDDD;
    font-family: Verdana;
    font-size: 12px;
    width: 400px;
}

.box3 > li {
    display: block;
}

.box3 > li span {
    display: inline-block;
    vertical-align: middle;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><body>
  <div class="box3">
    <li>
      <img src="pictures/contact/skype.png" width="34px" height="34px" />
      <span>Skype name</span>
    </li>
    <li>
      <img src="pictures/contact/gadu-gadu.png" width="34px" height="34px" />
      <span>Gadu-Gadu number</span>
    </li>
    <li>
      <img src="pictures/contact/email.png" width="34px" height="34px" />
      <span>Email address</span>
    </li>
  </div>
</body></code>```

How do you make every text display perfectly in the center of the image?

I will be very grateful for effective help.

答:
Set vertical-align: middle to img:

body
{
 left: 8%;
  top: 10%;
  position: absolute;
  background-color: #6699cc;
}

.box3
{
 background-color: #191919;
 position: absolute;
 padding: 15px 40px 15px;
 font-size: 12px;
 color: #DDDDDD;
 font-family: Verdana;
 font-size: 12px;
 width: 400px;
}

.box3 > li
{
 display: block;
}

.box3 > li span
{
 display: inline-block;
 vertical-align: middle;
}

.box3 img{
    vertical-align: middle;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><body>

 <div class="box3">

  <li>
   <img src="pictures/contact/skype.png" width="34px" height="34px" />
   <span>Skype name</span>
  </li>

  <li>
   <img src="pictures/contact/gadu-gadu.png" width="34px" height="34px" />
   <span>Gadu-Gadu number</span>
  </li>

  <li>
   <img src="pictures/contact/email.png" width="34px" height="34px" />
   <span>Email address</span>
  </li>

 </div>

</body></code>```

Body:
Look that every text is displayed below the picture. I would like every text to be displayed perfectly in the center of the picture.

Here is the code:
https://jsfiddle.net/Krzysiek_35/Ljybwz97/37/

body {
  left: 8%;
  top: 10%;
  position: absolute;
  background-color: #6699cc;
}

.box3 {
    background-color: #191919;
    position: absolute;
    padding: 15px 40px 15px;
    font-size: 12px;
    color: #DDDDDD;
    font-family: Verdana;
    font-size: 12px;
    width: 400px;
}

.box3 > li {
    display: block;
}

.box3 > li span {
    display: inline-block;
    vertical-align: middle;
}

      Skype name

      Gadu-Gadu number

      Email address

How do you make every text display perfectly in the center of the image?

I will be very grateful for effective help.

Body:
Set vertical-align: middle to img:

body
{
 left: 8%;
  top: 10%;
  position: absolute;
  background-color: #6699cc;
}

.box3
{
 background-color: #191919;
 position: absolute;
 padding: 15px 40px 15px;
 font-size: 12px;
 color: #DDDDDD;
 font-family: Verdana;
 font-size: 12px;
 width: 400px;
}

.box3 > li
{
 display: block;
}

.box3 > li span
{
 display: inline-block;
 vertical-align: middle;
}

.box3 img{
    vertical-align: middle;
}

<body>

 <div class="box3">

  <li>
   <img src="pictures/contact/skype.png" width="34px" height="34px" />
   <span>Skype name</span>
  </li>

  <li>
   <img src="pictures/contact/gadu-gadu.png" width="34px" height="34px" />
   <span>Gadu-Gadu number</span>
  </li>

  <li>
   <img src="pictures/contact/email.png" width="34px" height="34px" />
   <span>Email address</span>
  </li>

 </div>

</body>