问:
UIPageViewController subviewcontroller can't perform segue on viewDidAppear
I have a UIPageController which contains two subviewcontrollers. On start, I'm trying to perform a segue from SubViewControllerOne to LoginViewController when a user isn't authorized. I have a segue in viewDidAppear like so:

```<code>performSegue(withIdentifier: "authorizeSegue", sender: self);
</code>```

This produces an unsuccessful segue and a warning

```<code>Warning: Attempt to present <Volley.LoginViewController: 0x7f98bd801e00> on <Volley.SubViewControllerOne: 0x7f98bd608400> whose view is not in the window hierarchy!
</code>```

I've done this in the past with ViewControllers and TabBarViewControllers successfully.

When I wrap the segue in a timer, or trigger through an IBAction, the segue works perfectly fine. I believe it has something to do with the PageViewController.

```<code>class PageViewController: UIPageViewController, UIPageViewControllerDataSource, UIPageViewControllerDelegate, UIScrollViewDelegate {

    var subViewControllers = [UIViewController]()

    override func viewDidLoad() {
        super.viewDidLoad()
        self.delegate = self
        self.dataSource = self
        self.edgesForExtendedLayout = [];
        // Do any additional setup after loading the view.

        let subViewControllerOne = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "SubViewControllerOne") as! SubViewControllerOne
        let subViewControllerTwo = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "SubViewControllerTwo") as! SubViewControllerTwo
        subViewControllers = [yourPodcastViewController, appearancesViewController]
        setViewControllers([subViewControllers[0]], direction: .forward, animated: true, completion: nil)
    }

    required init?(coder: NSCoder) {
        super.init(transitionStyle: .scroll, navigationOrientation: .horizontal, options: nil)
    }
</code>```

The navigation controller and PageViewController

The segue from SubViewControllerOne to LoginViewController

答: I think because of view controller life cycle you should perform segue into viewWillApear

Body:
I have a UIPageController which contains two subviewcontrollers. On start, I'm trying to perform a segue from SubViewControllerOne to LoginViewController when a user isn't authorized. I have a segue in viewDidAppear like so:

performSegue(withIdentifier: "authorizeSegue", sender: self);

This produces an unsuccessful segue and a warning

Warning: Attempt to present <Volley.LoginViewController: 0x7f98bd801e00> on <Volley.SubViewControllerOne: 0x7f98bd608400> whose view is not in the window hierarchy!

I've done this in the past with ViewControllers and TabBarViewControllers successfully.

When I wrap the segue in a timer, or trigger through an IBAction, the segue works perfectly fine. I believe it has something to do with the PageViewController.

class PageViewController: UIPageViewController, UIPageViewControllerDataSource, UIPageViewControllerDelegate, UIScrollViewDelegate {

    var subViewControllers = [UIViewController]()

    override func viewDidLoad() {
        super.viewDidLoad()
        self.delegate = self
        self.dataSource = self
        self.edgesForExtendedLayout = [];
        // Do any additional setup after loading the view.

        let subViewControllerOne = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "SubViewControllerOne") as! SubViewControllerOne
        let subViewControllerTwo = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "SubViewControllerTwo") as! SubViewControllerTwo
        subViewControllers = [yourPodcastViewController, appearancesViewController]
        setViewControllers([subViewControllers[0]], direction: .forward, animated: true, completion: nil)
    }

    required init?(coder: NSCoder) {
        super.init(transitionStyle: .scroll, navigationOrientation: .horizontal, options: nil)
    }

The navigation controller and PageViewController

The segue from SubViewControllerOne to LoginViewController


来源: stackexchange

问:
How to use a PHP include to print HTML code based on URL filename
I'm trying to write a simple PHP script that uses PHP include to inject HTML based on the filename of the URL.

For example using a PHP include
- if the filename in the URL is dog.html print dog into the html document.
- if the filename in the URL is cat.html print cat into the html document.

This is to inject JSON-LD code for structured data.

I'm able to use PHP includes to print html code without issue, but its getting it to read the filename and print a specific portion of HTML that I can't seem to make work.

答:
You can use $_SERVER['REQUEST_URI'] to grab the Path, File, and Query of a url such as (   ..dog.php?dep=n/a&title=boss   )
 from a full url eg.  http://www.weeex.com/dog.php?dep=n/a&title=boss

To solve your case:

```<code> //Grab the filename from the uri using the basename function.

 $request_uri = $_SERVER['REQUEST_URI'] ;
//I am exploding at the  "?" delimiter so that I can get rid of the query I don't need

 $path=explode("?",$request_uri);
 $filename=basename($path[0]);

     //YOUR PHP INCLUDE CODE HERE
     include $filename ;
</code>```

this will work to grab the filename even with a complicated url like......"http://www.ex.com/dog.php?dep=n/a&title=boss"

I hope this will shed some light

ContentLicense: CC BY-SA 4.0

Body:
You can use $_SERVER['REQUEST_URI'] to grab the Path, File, and Query of a url such as (   ..dog.php?dep=n/a&title=boss   )
 from a full url eg.  http://www.weeex.com/dog.php?dep=n/a&title=boss

To solve your case:

 //Grab the filename from the uri using the basename function.

 $request_uri = $_SERVER['REQUEST_URI'] ;
//I am exploding at the  "?" delimiter so that I can get rid of the query I don't need

 $path=explode("?",$request_uri);
 $filename=basename($path[0]);

     //YOUR PHP INCLUDE CODE HERE
     include $filename ;

this will work to grab the filename even with a complicated url like......"http://www.ex.com/dog.php?dep=n/a&title=boss"

I hope this will shed some light


问:
Failed to resolve class via deferred binding
```<code>// ...some imports

public class Menu {
    final MenuMaker myClass = GWT.create(MenuMaker.class);  // ERROR
</code>```

My ...gwt.xml:

```<code>...
<generate-with class="com.gwt.rebind.MenuGenerator">
  <when-type-assignable class="com.gwt.client.MenuMaker" />
</generate-with>
...
</code>```

All work perfectly when I run compile in DevMode but when I "Build the project with the GWT compiler" I get this error:

```<code>      [ERROR] Line 15:  Failed to resolve 'com.gwt.client.MenuMaker' via deferred binding
   Scanning for additional dependencies: jar:file:/C:/eclipse/plugins/com.google.gwt.eclipse.sdkbundle_2.4.0.v201208080121-rel-r42/gwt-2.4.0/gwt-user.jar!/com/google/gwt/dom/client/DOMImpl.java
      [WARN] For the following type(s), generated source was never committed (did you forget to call commit()?)
         [WARN] com.gwt.client.MenuMakerGen
   [ERROR] Cannot proceed due to previous errors
</code>```

At the end of com.gwt.rebind.MenuGenerator:

```<code>sourceWriter.commit(logger);
</code>```

答:
Check your model/ Pojo Class should implements Serializable

interface and also
Class have default constructor(No argument constructor).

Body:
// ...some imports

public class Menu {
    final MenuMaker myClass = GWT.create(MenuMaker.class);  // ERROR

My ...gwt.xml:

...
<generate-with class="com.gwt.rebind.MenuGenerator">
  <when-type-assignable class="com.gwt.client.MenuMaker" />
</generate-with>
...

All work perfectly when I run compile in DevMode but when I "Build the project with the GWT compiler" I get this error:

      [ERROR] Line 15:  Failed to resolve 'com.gwt.client.MenuMaker' via deferred binding
   Scanning for additional dependencies: jar:file:/C:/eclipse/plugins/com.google.gwt.eclipse.sdkbundle_2.4.0.v201208080121-rel-r42/gwt-2.4.0/gwt-user.jar!/com/google/gwt/dom/client/DOMImpl.java
      [WARN] For the following type(s), generated source was never committed (did you forget to call commit()?)
         [WARN] com.gwt.client.MenuMakerGen
   [ERROR] Cannot proceed due to previous errors

At the end of com.gwt.rebind.MenuGenerator:

sourceWriter.commit(logger);


答:
If not very particular about ramda, you can do as below with one line using flatMap and map.

const l1 = [
  { a: 1, a1: 2 },
  { b: 3, b1: 4 },
  { c: 5, c1: 6 }
];
const l2 = [{ d: 2 }, { e: 2 }, { f: 2 }];

const merged = l2.flatMap(item2 => l1.map(item1 => ({ ...item1, ...item2 })));
console.log(JSON.stringify(merged));```

Title: How to combine two array using ramda library?

Body:
I have two array as below

const l1 = [ {"a": 1, "a1": 2}, {"b": 3, "b1": 4}, {"c": 5, "c1": 6} ];
const l2 = [ {"d": 2}, {"e": 2}, {"f": 2} ];

How can I use ramda library to combine these two and get result like

[ {"a": 1, "a1": 2, "d": 2}, {"a": 1, "a1": 2, "e": 2}, {"a": 1, "a1": 2, "f": 2},
{"b": 3, "b1": 4, "d": 2}, {"b": 3, "b1": 4, "e": 2}, {"b": 3, "b1": 4, "f": 2},
{"c": 5, "c1": 6, "d": 2}, {"c": 5, "c1": 6, "e": 2}, {"c": 5, "c1": 6, "f": 2} ]

I used

R.map(R.xprod(__, l2, l1)

But not working since i got object inside array.

Thanks in advance.


问:
Error inflating class after migration to androidx
I made a migration to Androidx but after the migration, I'm getting the following error:

```<code> Caused by: android.view.InflateException: Binary XML file line #12: Binary XML file line #2: Error inflating class android.support.design.widget.CoordinatorLayout
 Caused by: android.view.InflateException: Binary XML file line #2: Error inflating class android.support.design.widget.CoordinatorLayout
</code>```

I studied all the resources and migrated to Androidx, but I still have a lot of problems.
Can someone help me?
I will post the sections of the code below.

--------- beginning of crash ---------

```<code>2019-01-23 09:47:34.171 17578-17578/? E/AndroidRuntime: FATAL EXCEPTION: main
    Process: ir.bijac.com.bijac, PID: 17578
    java.lang.RuntimeException: Unable to start activity ComponentInfo{ir.bijac.com.bijac/ir.bijac.com.bijac.TestActivity}: android.view.InflateException: Binary XML file line #12: Binary XML file line #2: Error inflating class android.support.design.widget.CoordinatorLayout
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2665)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2726)
        at android.app.ActivityThread.-wrap12(ActivityThread.java)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1477)
        at android.os.Handler.dispatchMessage(Handler.java:102)
        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: android.view.InflateException: Binary XML file line #12: Binary XML file line #2: Error inflating class android.support.design.widget.CoordinatorLayout
     Caused by: android.view.InflateException: Binary XML file line #2: Error inflating class android.support.design.widget.CoordinatorLayout
     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.parseInclude(LayoutInflater.java:964)
        at android.view.LayoutInflater.rInflate(LayoutInflater.java:854)
        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 android.view.LayoutInflater.inflate(LayoutInflater.java:377)
        at androidx.appcompat.app.AppCompatDelegateImpl.setContentView(AppCompatDelegateImpl.java:469)
        at androidx.appcompat.app.AppCompatActivity.setContentView(AppCompatActivity.java:140)
        at ir.bijac.com.bijac.BaseActivity.onCreate(BaseActivity.java:43)
        at ir.bijac.com.bijac.TestActivity.onCreate(TestActivity.java:22)
        at android.app.Activity.performCreate(Activity.java:6679)
        at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1118)
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2618)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2726)
        at android.app.ActivityThread.-wrap12(ActivityThread.java)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1477)
        at android.os.Handler.dispatchMessage(Handler.java:102)
        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.NoClassDefFoundError: Failed resolution of: Landroid/support/coreui/R$attr;
        at android.support.design.widget.CoordinatorLayout.<init>(CoordinatorLayout.java:202)
        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.parseInclude(LayoutInflater.java:964)
        at android.view.LayoutInflater.rInflate(LayoutInflater.java:854)
        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 android.view.LayoutInflater.inflate(LayoutInflater.java:377)
        at androidx.appcompat.app.AppCompatDelegateImpl.setContentView(AppCompatDelegateImpl.java:469)
        at androidx.appcompat.app.AppCompatActivity.setContentView(AppCompatActivity.java:140)
        at ir.bijac.com.bijac.BaseActivity.onCreate(BaseActivity.java:43)
        at ir.bijac.com.bijac.TestActivity.onCreate(TestActivity.java:22)
        at android.app.Activity.performCreate(Activity.java:6679)
        at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1118)
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2618)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2726)
        at android.app.ActivityThread.-wrap12(ActivityThread.java)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1477)
        at android.os.Handler.dispatchMessage(Handler.java:102)
        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)
2019-01-23 09:47:34.171 17578-17578/? E/AndroidRuntime: Caused by: java.lang.ClassNotFoundException: Didn't find class "android.support.coreui.R$attr" on path: DexPathList[[zip file "/data/app/ir.bijac.com.bijac-2/base.apk", zip file "/data/app/ir.bijac.com.bijac-2/split_lib_dependencies_apk.apk", zip file "/data/app/ir.bijac.com.bijac-2/split_lib_slice_0_apk.apk", zip file "/data/app/ir.bijac.com.bijac-2/split_lib_slice_1_apk.apk", zip file "/data/app/ir.bijac.com.bijac-2/split_lib_slice_2_apk.apk", zip file "/data/app/ir.bijac.com.bijac-2/split_lib_slice_3_apk.apk", zip file "/data/app/ir.bijac.com.bijac-2/split_lib_slice_4_apk.apk", zip file "/data/app/ir.bijac.com.bijac-2/split_lib_slice_5_apk.apk", zip file "/data/app/ir.bijac.com.bijac-2/split_lib_slice_6_apk.apk", zip file "/data/app/ir.bijac.com.bijac-2/split_lib_slice_7_apk.apk", zip file "/data/app/ir.bijac.com.bijac-2/split_lib_slice_8_apk.apk", zip file "/data/app/ir.bijac.com.bijac-2/split_lib_slice_9_apk.apk"],nativeLibraryDirectories=[/data/app/ir.bijac.com.bijac-2/lib/x86, /system/lib, /vendor/lib]]
        at dalvik.system.BaseDexClassLoader.findClass(BaseDexClassLoader.java:56)
        at java.lang.ClassLoader.loadClass(ClassLoader.java:380)
        at java.lang.ClassLoader.loadClass(ClassLoader.java:312)
            ... 27 more
</code>```

build gradle:

```<code>apply plugin: 'com.android.application'
repositories {
    mavenCentral()
}

android {
    useLibrary 'org.apache.http.legacy'
    compileSdkVersion 28
    defaultConfig {
        applicationId "ir.bijac.com.bijac"
        minSdkVersion 18
        targetSdkVersion 28
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
    }

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

dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    implementation 'androidx.appcompat:appcompat:1.0.2'
    implementation 'com.google.android.material:material:1.1.0-alpha02'
    implementation 'androidx.legacy:legacy-support-core-utils:1.0.0'
    implementation 'androidx.cardview:cardview:1.0.0'
    implementation 'androidx.constraintlayout:constraintlayout:1.1.3'
    implementation 'androidx.recyclerview:recyclerview:1.0.0'
    implementation 'androidx.test.espresso:espresso-core:3.1.1'
    androidTestImplementation 'androidx.test:runner:1.1.1'
    androidTestUtil 'androidx.test:orchestrator:1.1.1'
    configurations.all { resolutionStrategy.force 'com.android.support:support-v4:28.0.0' }
    implementation 'com.theartofdev.edmodo:android-image-cropper:2.8.0'
    implementation 'com.squareup.picasso:picasso:2.5.2'
    implementation 'com.nineoldandroids:library:2.4.0'
    implementation 'com.daimajia.slider:library:1.1.5@aar'
    implementation "cz.msebera.android:httpclient:4.4.1.2"
    implementation 'org.apache.httpcomponents:httpcore:4.4.10'
    implementation 'com.androidadvance:topsnackbar:1.1.1'
    implementation 'co.ronash.android:pushe-base:1.4.1'
    implementation 'com.google.android.gms:play-services-gcm:16.0.0'
    implementation 'com.google.android.gms:play-services-location:16.0.0'
    implementation('com.crashlytics.sdk.android:crashlytics:2.9.4@aar') {
        transitive = true;
    }

}
</code>```

--------- activity_main.xml ---------

```<code>    <?xml version="1.0" encoding="utf-8"?>
    <androidx.coordinatorlayout.widget.CoordinatorLayout
    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"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:fitsSystemWindows="true"
    tools:openDrawer="start"
    >

    </androidx.coordinatorlayout.widget.CoordinatorLayout>
</code>```

答:
Simply Just go to XML file (in `res/layout) and replace </p>

```<code>androidx.appcompat.widget.RecyclerView
</code>```

<p>with: </p>

```<code>androidx.recyclerview.widget.RecyclerView
</code>```

Body:
I made a migration to Androidx but after the migration, I'm getting the following error:

 Caused by: android.view.InflateException: Binary XML file line #12: Binary XML file line #2: Error inflating class android.support.design.widget.CoordinatorLayout
 Caused by: android.view.InflateException: Binary XML file line #2: Error inflating class android.support.design.widget.CoordinatorLayout

I studied all the resources and migrated to Androidx, but I still have a lot of problems.
Can someone help me?
I will post the sections of the code below.

--------- beginning of crash ---------

2019-01-23 09:47:34.171 17578-17578/? E/AndroidRuntime: FATAL EXCEPTION: main
    Process: ir.bijac.com.bijac, PID: 17578
    java.lang.RuntimeException: Unable to start activity ComponentInfo{ir.bijac.com.bijac/ir.bijac.com.bijac.TestActivity}: android.view.InflateException: Binary XML file line #12: Binary XML file line #2: Error inflating class android.support.design.widget.CoordinatorLayout
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2665)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2726)
        at android.app.ActivityThread.-wrap12(ActivityThread.java)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1477)
        at android.os.Handler.dispatchMessage(Handler.java:102)
        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: android.view.InflateException: Binary XML file line #12: Binary XML file line #2: Error inflating class android.support.design.widget.CoordinatorLayout
     Caused by: android.view.InflateException: Binary XML file line #2: Error inflating class android.support.design.widget.CoordinatorLayout
     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.parseInclude(LayoutInflater.java:964)
        at android.view.LayoutInflater.rInflate(LayoutInflater.java:854)
        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 android.view.LayoutInflater.inflate(LayoutInflater.java:377)
        at androidx.appcompat.app.AppCompatDelegateImpl.setContentView(AppCompatDelegateImpl.java:469)
        at androidx.appcompat.app.AppCompatActivity.setContentView(AppCompatActivity.java:140)
        at ir.bijac.com.bijac.BaseActivity.onCreate(BaseActivity.java:43)
        at ir.bijac.com.bijac.TestActivity.onCreate(TestActivity.java:22)
        at android.app.Activity.performCreate(Activity.java:6679)
        at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1118)
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2618)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2726)
        at android.app.ActivityThread.-wrap12(ActivityThread.java)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1477)
        at android.os.Handler.dispatchMessage(Handler.java:102)
        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.NoClassDefFoundError: Failed resolution of: Landroid/support/coreui/R$attr;
        at android.support.design.widget.CoordinatorLayout.<init>(CoordinatorLayout.java:202)
        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.parseInclude(LayoutInflater.java:964)
        at android.view.LayoutInflater.rInflate(LayoutInflater.java:854)
        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 android.view.LayoutInflater.inflate(LayoutInflater.java:377)
        at androidx.appcompat.app.AppCompatDelegateImpl.setContentView(AppCompatDelegateImpl.java:469)
        at androidx.appcompat.app.AppCompatActivity.setContentView(AppCompatActivity.java:140)
        at ir.bijac.com.bijac.BaseActivity.onCreate(BaseActivity.java:43)
        at ir.bijac.com.bijac.TestActivity.onCreate(TestActivity.java:22)
        at android.app.Activity.performCreate(Activity.java:6679)
        at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1118)
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2618)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2726)
        at android.app.ActivityThread.-wrap12(ActivityThread.java)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1477)
        at android.os.Handler.dispatchMessage(Handler.java:102)
        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)
2019-01-23 09:47:34.171 17578-17578/? E/AndroidRuntime: Caused by: java.lang.ClassNotFoundException: Didn't find class "android.support.coreui.R$attr" on path: DexPathList[[zip file "/data/app/ir.bijac.com.bijac-2/base.apk", zip file "/data/app/ir.bijac.com.bijac-2/split_lib_dependencies_apk.apk", zip file "/data/app/ir.bijac.com.bijac-2/split_lib_slice_0_apk.apk", zip file "/data/app/ir.bijac.com.bijac-2/split_lib_slice_1_apk.apk", zip file "/data/app/ir.bijac.com.bijac-2/split_lib_slice_2_apk.apk", zip file "/data/app/ir.bijac.com.bijac-2/split_lib_slice_3_apk.apk", zip file "/data/app/ir.bijac.com.bijac-2/split_lib_slice_4_apk.apk", zip file "/data/app/ir.bijac.com.bijac-2/split_lib_slice_5_apk.apk", zip file "/data/app/ir.bijac.com.bijac-2/split_lib_slice_6_apk.apk", zip file "/data/app/ir.bijac.com.bijac-2/split_lib_slice_7_apk.apk", zip file "/data/app/ir.bijac.com.bijac-2/split_lib_slice_8_apk.apk", zip file "/data/app/ir.bijac.com.bijac-2/split_lib_slice_9_apk.apk"],nativeLibraryDirectories=[/data/app/ir.bijac.com.bijac-2/lib/x86, /system/lib, /vendor/lib]]
        at dalvik.system.BaseDexClassLoader.findClass(BaseDexClassLoader.java:56)
        at java.lang.ClassLoader.loadClass(ClassLoader.java:380)
        at java.lang.ClassLoader.loadClass(ClassLoader.java:312)
            ... 27 more

build gradle:

apply plugin: 'com.android.application'
repositories {
    mavenCentral()
}

android {
    useLibrary 'org.apache.http.legacy'
    compileSdkVersion 28
    defaultConfig {
        applicationId "ir.bijac.com.bijac"
        minSdkVersion 18
        targetSdkVersion 28
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
    }

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

dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    implementation 'androidx.appcompat:appcompat:1.0.2'
    implementation 'com.google.android.material:material:1.1.0-alpha02'
    implementation 'androidx.legacy:legacy-support-core-utils:1.0.0'
    implementation 'androidx.cardview:cardview:1.0.0'
    implementation 'androidx.constraintlayout:constraintlayout:1.1.3'
    implementation 'androidx.recyclerview:recyclerview:1.0.0'
    implementation 'androidx.test.espresso:espresso-core:3.1.1'
    androidTestImplementation 'androidx.test:runner:1.1.1'
    androidTestUtil 'androidx.test:orchestrator:1.1.1'
    configurations.all { resolutionStrategy.force 'com.android.support:support-v4:28.0.0' }
    implementation 'com.theartofdev.edmodo:android-image-cropper:2.8.0'
    implementation 'com.squareup.picasso:picasso:2.5.2'
    implementation 'com.nineoldandroids:library:2.4.0'
    implementation 'com.daimajia.slider:library:1.1.5@aar'
    implementation "cz.msebera.android:httpclient:4.4.1.2"
    implementation 'org.apache.httpcomponents:httpcore:4.4.10'
    implementation 'com.androidadvance:topsnackbar:1.1.1'
    implementation 'co.ronash.android:pushe-base:1.4.1'
    implementation 'com.google.android.gms:play-services-gcm:16.0.0'
    implementation 'com.google.android.gms:play-services-location:16.0.0'
    implementation('com.crashlytics.sdk.android:crashlytics:2.9.4@aar') {
        transitive = true;
    }

}

--------- activity_main.xml ---------

    <?xml version="1.0" encoding="utf-8"?>
    <androidx.coordinatorlayout.widget.CoordinatorLayout
    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"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:fitsSystemWindows="true"
    tools:openDrawer="start"
    >

    </androidx.coordinatorlayout.widget.CoordinatorLayout>

Body:
Simply Just go to XML file (in `res/layout) and replace

androidx.appcompat.widget.RecyclerView

with:

androidx.recyclerview.widget.RecyclerView


问:
Exit YouTube fullscreen back button Cordova closes the app
I play a YouTube video in fullscreen mode, and when I press the back button, it closes the app instead of exiting the the full-screen mode. I'm using JavaScript with Cordova 6.3.1 for Android. Here is my code:

```<code>document.addEventListener("deviceready", onDeviceReady, false);

function onDeviceReady() {
   document.addEventListener("backbutton", function (e) {
     e.preventDefault();
       screen.orientation.lock('portrait');
     }, false);
}
</code>```

The previous code does not work as expected.

Thanks in advance.

答:
I haven't found the answer yet, but I'm posting my findings so far in hopes it helps someone.

Version : cordova-android 8.1.0

What I found

The problem comes from the fact that to display the Youtube video fullscreen, the SystemWebChromeClient calls the CordovaWebViewImpl.showCustomView() method. By doing so, the new view seems to catch the Back button event before Cordova is able to onDispatchKeyEvent() and send the backbutton event to the JavaScript side.

Here is some log taken, with comments added for clarity

```<code>// Video is fullscreen, and then dismissed with the onscreen minimize button
D/CordovaWebViewImpl: showCustomView : showing Custom View + view = android.widget.FrameLayout{a7cc344 V.E...... ......I. 0,0-0,0}
D/CordovaWebViewImpl: hideCustomView : Hiding Custom View : mCustomView = android.widget.FrameLayout{a7cc344 V.E...... .......D 0,0-1080,1704}

// While the video is not displayed fullscreen, the back button event is correctly caught and sent to the JS side
D/CordovaWebViewImpl: onDispatchKeyEvent : isBackButton = true mCustomView = null

// Once again in fullscreen, then click on the back button
D/CordovaWebViewImpl: showCustomView : showing Custom View + view = android.widget.FrameLayout{fa6d336 V.E...... ......I. 0,0-0,0}
// No back button event caught
// A destroy lifecycle event is sent (from the video FrameLayout handling?) and handleDestroy() is called
D/CordovaWebViewImpl: handleDestroy : load about:blank
D/CordovaWebViewImpl: >>> loadUrl(about:blank)
W/cr_AwContents: WebView.destroy() called while WebView is still attached to window.
D/CordovaWebViewImpl: hideCustomView : Hiding Custom View : mCustomView = android.widget.FrameLayout{a7cc344 V.E...... .......D 0,0-1080,1704}
</code>```

What I tried

Create a subclass of FrameLayout, with overrides for onKeyDown() and onKeyUp(), use it in showCustomerView()

The video then wasn't displayed anymore.

Docs

https://developer.android.com/reference/android/widget/FrameLayout

Body:
I play a YouTube video in fullscreen mode, and when I press the back button, it closes the app instead of exiting the the full-screen mode. I'm using JavaScript with Cordova 6.3.1 for Android. Here is my code:

document.addEventListener("deviceready", onDeviceReady, false);

function onDeviceReady() {
   document.addEventListener("backbutton", function (e) {
     e.preventDefault();
       screen.orientation.lock('portrait');
     }, false);
}

The previous code does not work as expected.

Thanks in advance.

Body:
I haven't found the answer yet, but I'm posting my findings so far in hopes it helps someone.

Version : cordova-android 8.1.0

What I found

The problem comes from the fact that to display the Youtube video fullscreen, the SystemWebChromeClient calls the CordovaWebViewImpl.showCustomView() method. By doing so, the new view seems to catch the Back button event before Cordova is able to onDispatchKeyEvent() and send the backbutton event to the JavaScript side.

Here is some log taken, with comments added for clarity

// Video is fullscreen, and then dismissed with the onscreen minimize button
D/CordovaWebViewImpl: showCustomView : showing Custom View + view = android.widget.FrameLayout{a7cc344 V.E...... ......I. 0,0-0,0}
D/CordovaWebViewImpl: hideCustomView : Hiding Custom View : mCustomView = android.widget.FrameLayout{a7cc344 V.E...... .......D 0,0-1080,1704}

// While the video is not displayed fullscreen, the back button event is correctly caught and sent to the JS side
D/CordovaWebViewImpl: onDispatchKeyEvent : isBackButton = true mCustomView = null

// Once again in fullscreen, then click on the back button
D/CordovaWebViewImpl: showCustomView : showing Custom View + view = android.widget.FrameLayout{fa6d336 V.E...... ......I. 0,0-0,0}
// No back button event caught
// A destroy lifecycle event is sent (from the video FrameLayout handling?) and handleDestroy() is called
D/CordovaWebViewImpl: handleDestroy : load about:blank
D/CordovaWebViewImpl: >>> loadUrl(about:blank)
W/cr_AwContents: WebView.destroy() called while WebView is still attached to window.
D/CordovaWebViewImpl: hideCustomView : Hiding Custom View : mCustomView = android.widget.FrameLayout{a7cc344 V.E...... .......D 0,0-1080,1704}

What I tried

Create a subclass of FrameLayout, with overrides for onKeyDown() and onKeyUp(), use it in showCustomerView()

The video then wasn't displayed anymore.

Docs

https://developer.android.com/reference/android/widget/FrameLayout


问:
log4php can't create file in a linux environment
I've create a small php application with log4php on my work desktop machine running windows 7 and net.
it works fine, daily file it's been created and log are in.

NOw i'm on my laptop running ubuntu 11,04. i originally gave persmission 755  to the folder Integrator (name of the app) and subfolder under /var/www/Ingrator.after realizing this

Mon May 16 18:03:44 2011] [error] [client 127.0.0.1] PHP Warning:  fopen(./logs/daily_20110516.log): failed to open stream: Permission denied in /var/www/Integrator/lib/log4php/appenders/LoggerAppenderFile.php on line 77

permission issue in the apache log, i've changed the owner to be the current owner, but this. it gives the same error.now it's even with the permission 777. it's still persistent.
So i'm a little surprise.how can i fix that? thanks for reading this.

答:
The error says it's trying to open the file, which means that the Apache user doesn't have permission to the file. Basically, it can open the folder and see that the file is there, but can't do anything with it, because permissions for folders are separate from permissions for files.

Make sure the file is owned by www-data, in the www-data group, or has read/write permissions that www-data can use (assuming you left the Apache user as www-data, if not, use the Apache user you've set).

ContentLicense: CC BY-SA 3.0


问:
Add-Text Comments only in APEX Page
On a Oracle Apex Detail Page, I have a readonly Text
field which displays the Field Comments, which is read only.

I hava another Field "New Comment" , which is not bound to a Database Field.

If the Form has been saved successfully, i want that Contents
of the non-bound Field is appednded to the readonly Field, with a timestamp in the header.

So I want to know whats the best approach to do this?

答:
Create your own process which will update the comment column, e.g.

```<code>update your_table t set
  t.comment = to_char(sysdate, 'dd.mm.yyyy hh24:mi') ||   --> timestamp
              chr(10)        ||                           --> new line
             :P1_NEW_COMMENT ||                           --> new comment first
              chr(10)        ||
              t.comment;                                  --> old comment
</code>```

Title: Add-Text Comments only in APEX Page

Body:
Create your own process which will update the comment column, e.g.

update your_table t set
  t.comment = to_char(sysdate, 'dd.mm.yyyy hh24:mi') ||   --> timestamp
              chr(10)        ||                           --> new line
             :P1_NEW_COMMENT ||                           --> new comment first
              chr(10)        ||
              t.comment;                                  --> old comment


问:
Vue data passed from parent to child not accessing
I have an app.vue file in which i have the parent codes.

```<code><template>
  <div id="app" class="small-container">
    <h1>Employees</h1>
    <employee-form @add:employee="addNewEmployee" />
    <employee-table :employees="employees" />
  </div>
</template>

<script>
import EmployeeTable from '@/components/EmployeeTable.vue'
import EmployeeForm from '@/components/EmployeeForm.vue'

export default {
  name: 'app',
  components: {
    EmployeeTable,
    EmployeeForm,
  },
  data() {
    return {
      employees: [
        {
          id: 1,
          name: 'Richard Hendricks',
          email: 'richard@piedpiper.com',
        },
        {
          id: 2,
          name: 'Bertram Gilfoyle',
          email: 'gilfoyle@piedpiper.com',
        },
        {
          id: 3,
          name: 'Dinesh Chugtai',
          email: 'dinesh@piedpiper.com',
        },
      ],
      misc:'testbro',
    }
  },
  methods:{
    addNewEmployee: function( new_employee){
        var length = Object.keys(this.employees).length;
        length = length+1;
        this.employees.push({id:length,name:new_employee.name,email:new_employee.email});
    }
  }
}
</script>
</code>```

I am passing two parameters in data() method to child EmployeeTable.

```<code><template>
  <div id="employee-table">
    <table>
      <thead>
        <tr>
          <th>Employee name</th>
          <th>Employee email</th>
        </tr>
      </thead>
      <tbody>
        <tr v-for="employee in employees" :key="employee.id">
          <td>{{ employee.name }}</td>
          <td>{{ employee.email }}</td>
        </tr>
      </tbody>
      <tfoot>
          <tr>
              <td>Misc Label</td>
              <td>{{misc}}</td>
          </tr>
      </tfoot>
    </table>
  </div>
</template>

<script>
    export default {
    name: 'employee-table',
    inheritAttrs: false,
        props: {
            employees: Array,
            misc: String,
        },
    }
</script>
</code>```

The Employee name and email is displayed, but the misc {{misc}} is not displayed. Am i accessing the prop incorrectly ?

答:
It is not that you are accessing the prop incorrectly, you are actually not passing the misc to the child component at all. You are only passing employees as a prop if you read carefully:

```<code><employee-table :employees="employees" />
</code>```

Correct code would look like this (in parent):

```<code><employee-table :employees="employees" :misc="misc" />
</code>```

Body:
I have an app.vue file in which i have the parent codes.

<template>

Employees

    <employee-form @add:employee="addNewEmployee" />
    <employee-table :employees="employees" />

</template>

I am passing two parameters in data() method to child EmployeeTable.

<template>

          Employee name
          Employee email

          {{ employee.name }}
          {{ employee.email }}

              Misc Label
              {{misc}}

</template>

The Employee name and email is displayed, but the misc {{misc}} is not displayed. Am i accessing the prop incorrectly ?

Body:
It is not that you are accessing the prop incorrectly, you are actually not passing the misc to the child component at all. You are only passing employees as a prop if you read carefully:

<employee-table :employees="employees" />

Correct code would look like this (in parent):

<employee-table :employees="employees" :misc="misc" />


答:
You're not passing misc to the child component, you have:

```<code><employee-table :employees="employees" />
</code>```

But you need:

```<code><employee-table :employees="employees" :misc="misc" />
</code>```

Title: Vue data passed from parent to child not accessing

Body:
You're not passing misc to the child component, you have:

<employee-table :employees="employees" />

But you need:

<employee-table :employees="employees" :misc="misc" />


问:
Round Down Decimal Places Javascript
I need a rounding down many many decimal places down, basically roundTo but supposedly rounding down at the spot. Example,

```<code>take the number, 1.087179939485353505
but to the fifth place, with roundTo of 6
roundTo(1.087179939485353505, 6) is 1.08718
</code>```

I need 1.08717 not 1.08718 in javascript.

```<code>var Variable = roundTo(Variable / 1000000000000000000, 6);
</code>```

Resolved
There seems to be no native javascript decimal rounding function that rounds down. One of two options are available.

Convert to string and manipulate the data that way (makes the most sense).

Utilize a number and multiply, floor then re-divide again for your number

答:
```<code>var Variable = Variable / 1000000000000000000;
Variable *= 1000000;
Variable = Math.floor(Variable);
Variable /= 1000000;
var Variable = roundTo(Variable, 6);
</code>```

I took my decimal, multiplied it by how many places I wanted to roundTo, math floor for absolute low rounding and divided it once again before lastly using roundTo for the precise decimal place. Seems the only way.

Title: Round Down Decimal Places Javascript

Body:
I need a rounding down many many decimal places down, basically roundTo but supposedly rounding down at the spot. Example,

take the number, 1.087179939485353505
but to the fifth place, with roundTo of 6
roundTo(1.087179939485353505, 6) is 1.08718

I need 1.08717 not 1.08718 in javascript.

var Variable = roundTo(Variable / 1000000000000000000, 6);

Resolved
There seems to be no native javascript decimal rounding function that rounds down. One of two options are available.

Convert to string and manipulate the data that way (makes the most sense).

Utilize a number and multiply, floor then re-divide again for your number

Body:
var Variable = Variable / 1000000000000000000;
Variable *= 1000000;
Variable = Math.floor(Variable);
Variable /= 1000000;
var Variable = roundTo(Variable, 6);

I took my decimal, multiplied it by how many places I wanted to roundTo, math floor for absolute low rounding and divided it once again before lastly using roundTo for the precise decimal place. Seems the only way.


问:
Release iOS apps without needing the UDID
We are currently developing an iOS app, we want it to be installed on any device for testing, can we do so without needing the UDID for specific devices?</p>

答:
Basically, you have three options:

Option one: Local installation. Physically connect the iOS device to your development mac and run it on that device in XCode. This will save it as an app on that device so you can test further even when it's disconnected. Main upside: simplicity. Main downside: the physical proximity required.

Option two: Testflight. This allows users to opt-in to a beta program where you can send out new builds to their devices. Main upside: allows a curated list of remote beta testers. Main downside: Builds are invalidated every 90 days.

Option three: Enterprise distribution. This allows you to package the app as a .ipa file and host it on a web server, where anyone with the link can download your app. Main upside: Widest possible reach and easiest download process for testers. Main downside: Costs $299 per year, you must be a corporation.

All three options have you dealing with Apple's often-confusing code-sign process. The first one can be done with automatic certificate management, but the other two will have to be manually configured.

Relevant setup tutorials:

Testflight

Enterprise Distribution


答:
NOTE: This solution relies on defaultdict being ordered, which is something that was introduced on Python 3.6

Somewhat naive approach:

from collections import defaultdict

# Create a dictionary of people
people = defaultdict(list)

# Open up your file in read-only mode
with open('your_file.txt', 'r') as f:
    # Iterate over all lines, stripping them and splitting them into words
    for line in filter(bool, map(str.split, map(str.strip, f))):
        # Retrieve the name of the person
        # either from the current line or use the name of the last person processed
        name, words = list(people)[-1] if line[0] == '*' else line[0], line[1:]
        # Add all remaining words to that person's record
        people[name].extend(words)

print(people['anna'])
# ['C500', 'C521', 'C523', 'C547', 'C555', 'C556', 'C557', 'C559', 'C562', 'C563', 'C566', 'C567', 'C568', 'C569', 'C571', 'C572', 'C573', 'C574', 'C575', 'C576', 'C578']
```

<p>It also has the additional benefit of returning an empty <code>list</code> for unknown names:</p>

<pre class="lang-py prettyprint-override"><code>print(people['matt'])
# []
</code>```

Title: Adding words between lines to an array

Body:
This is the content of my file:

david    C001 C002 C004 C005 C006 C007

*    C008 C009 C010 C011 C016 C017 C018

*    C019 C020 C021 C022 C023 C024 C025

anna C500 C521 C523 C547 C555 C556

*    C557 C559 C562 C563 C566 C567 C568

*    C569 C571 C572 C573 C574 C575 C576

*    C578

charlie    C701 C702 C704 C706 C707 C708

*    C709 C712 C715 C716 C717 C718

I want my output to be:

david=[C001,C002,C004,C005,C006,C007,C008,C009,C010,C011,C016,C017,C018,C019,C020,C021,C022,C023,C024,C025]

anna=[C500,C521,C523,C547,C555,C556,C557,C559,C562,C563,C566,C567,C568,C569,C571,C572,C573,C574,C575,C576,C578]

charlie=[C701,C702,C704,C706,C707,C708,C709,C712,C715,C716,C717,C718]

I am able to create:

david=[C001,C002,C004,C005,C006,C007]
anna=[C500,C521,C523,C547,C555,C556]
charlie=[C701,C702,C704,C706,C707,C708]

counting the number of words in a line and using line[0] as the array name and adding the remaining words to the array.
However, I don't know how to take the continuation of words in the next lines starting with "*" to the array.

Can anyone help?

Body:
NOTE: This solution relies on defaultdict being ordered, which is something that was introduced on Python 3.6

Somewhat naive approach:

from collections import defaultdict

# Create a dictionary of people
people = defaultdict(list)

# Open up your file in read-only mode
with open('your_file.txt', 'r') as f:
    # Iterate over all lines, stripping them and splitting them into words
    for line in filter(bool, map(str.split, map(str.strip, f))):
        # Retrieve the name of the person
        # either from the current line or use the name of the last person processed
        name, words = list(people)[-1] if line[0] == '*' else line[0], line[1:]
        # Add all remaining words to that person's record
        people[name].extend(words)

print(people['anna'])
# ['C500', 'C521', 'C523', 'C547', 'C555', 'C556', 'C557', 'C559', 'C562', 'C563', 'C566', 'C567', 'C568', 'C569', 'C571', 'C572', 'C573', 'C574', 'C575', 'C576', 'C578']

It also has the additional benefit of returning an empty list for unknown names:

print(people['matt'])
# []


问:
Access on-prem resources via Azure
I'm trying to access on-prem resources (file share on a file server) via Azure, but I'm stuck and don't know how to continue.

On Prem: 1 Domain Controller and 1 File Server (Server 2019 Std). Both are joined to a local domain. The DC runs Azure AD Connect for sync.
Client: Laptop running Windows 10, joined to the Azure AD. Is in a different network.

Goal: Laptop should access the file share.
For sure I just could use a VPN or smth, but I'm trying to learn a bit Azure.
I'm referring to the following Microsoft Website: https://learn.microsoft.com/en-us/microsoft-365/business/access-resources
"You can also allow access to on-premises resources like line of business (LOB) apps, file shares, and printers. To allow access, use Azure AD Connect to synchronize your on-premises Active Directory with Azure Active Directory."

答: I dont think those are related at all. Network path must exist between your laptop and the file share. And the Azure AD Connect can help you with authentication\authorization, not with establishing the network connection. You should use VPN to establish network connectivity and you can use Azure AD Connect to sync identities to be able to use the same identity to access resources in the cloud\on-premises</p>

Title: Access on-prem resources via Azure


问:
getExtras causing app to crash
I am working on an Android App that lets me create an Event in CreateActivity, and than passes the data from CreateActivity to the MainActivity through Bundle and putExtras().

It appears as if I am using .getExtras() or getString() wrong. The app crashes once the b.getString("TITLE") function is implemented.

```<code>public class MainActivity extends FragmentActivity implements OnClickListener {

    ListView listView;
    int lastIndex = -1;
    ArrayList<Event> lstEvents;

    // detail view
    TextView tvTitle, tvTime, tvDate;
    ImageView img;
    View vw_master;

    boolean _isBack = true;

    ImageButton add;

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

        // get list view
        listView = (ListView) findViewById(R.id.listViewFragment);
        lstEvents = new ArrayList<Event>();

        // // get detail controls
        tvTitle = (TextView) findViewById(R.id.textViewTitle);
        tvDate = (TextView) findViewById(R.id.textViewDate);
        tvTime = (TextView) findViewById(R.id.textViewTime);

        Bundle b = this.getIntent().getExtras();
        b.getString("TITLE");

            add = (ImageButton) findViewById(R.id.add);
        add.setOnClickListener(this);

    }

    @Override
    public void onClick(View v) {
        // TODO Auto-generated method stub
        switch (v.getId()) {
        case R.id.add:
            Intent intent = new Intent(this, CreateActivity.class);
            startActivity(intent);
            break;
        }
    }

}
</code>```

CREATEACTIVITY

```<code> public class CreateActivity extends Activity implements OnClickListener {

    EditText etTitle;
    Button btDate;
    Button btTime;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_create);
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);

        // /onclicklistener
        findViewById(R.id.btn_confirm).setOnClickListener(this);

        // edittexts and buttons
        btDate = (Button) findViewById(R.id.btn_date);
        etTitle = (EditText) findViewById(R.id.editTextTitle);
        btTime = (Button) findViewById(R.id.btn_time);
    }

    // Will be called via the onClick attribute
    // of the buttons in main.xml
    public void onClick(View view) {
        switch (view.getId()) {
        case R.id.btn_confirm:
             String title = etTitle.getText().toString();
             String time = btTime.getText().toString();
             String date = btDate.getText().toString();

            Log.e("LOG", title);
            Log.e("LOG", time);
            Log.e("LOG", date);

            Bundle newBundle = new Bundle();
            newBundle.putString("TITLE", title);
            newBundle.putString("TIME", time);
            newBundle.putString("DATE", date);

            Intent intent = new Intent(this, MainActivity.class);
            intent.putExtras(newBundle);
            startActivity(intent);
            break;
        }

    }

    public void showTimePickerDialog(View v) {
        DialogFragment newFragment = new TimePickerFragment();
        newFragment.show(getFragmentManager(), "timePicker");
    }

    public void showDatePickerDialog(View v) {
        DialogFragment newFragment = new DatePickerFragment();
        newFragment.show(getFragmentManager(), "datePicker");
    }

}
</code>```

Error Log :

```<code>03-03 15:44:07.117: E/AndroidRuntime(15202): FATAL EXCEPTION: main
03-03 15:44:07.117: E/AndroidRuntime(15202): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.datetracker/com.example.datetracker.MainActivity}: java.lang.NullPointerException
03-03 15:44:07.117: E/AndroidRuntime(15202):    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2202)
03-03 15:44:07.117: E/AndroidRuntime(15202):    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2252)
03-03 15:44:07.117: E/AndroidRuntime(15202):    at android.app.ActivityThread.access$600(ActivityThread.java:146)
03-03 15:44:07.117: E/AndroidRuntime(15202):    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1240)
03-03 15:44:07.117: E/AndroidRuntime(15202):    at android.os.Handler.dispatchMessage(Handler.java:99)
03-03 15:44:07.117: E/AndroidRuntime(15202):    at android.os.Looper.loop(Looper.java:137)
03-03 15:44:07.117: E/AndroidRuntime(15202):    at android.app.ActivityThread.main(ActivityThread.java:5168)
03-03 15:44:07.117: E/AndroidRuntime(15202):    at java.lang.reflect.Method.invokeNative(Native Method)
03-03 15:44:07.117: E/AndroidRuntime(15202):    at java.lang.reflect.Method.invoke(Method.java:511)
03-03 15:44:07.117: E/AndroidRuntime(15202):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:797)
03-03 15:44:07.117: E/AndroidRuntime(15202):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:564)
03-03 15:44:07.117: E/AndroidRuntime(15202):    at dalvik.system.NativeStart.main(Native Method)
03-03 15:44:07.117: E/AndroidRuntime(15202): Caused by: java.lang.NullPointerException
03-03 15:44:07.117: E/AndroidRuntime(15202):    at com.example.datetracker.MainActivity.onCreate(MainActivity.java:47)
03-03 15:44:07.117: E/AndroidRuntime(15202):    at android.app.Activity.performCreate(Activity.java:5200)
03-03 15:44:07.117: E/AndroidRuntime(15202):    at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1080)
03-03 15:44:07.117: E/AndroidRuntime(15202):    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2166)
</code>```

答:
You should declare all your variables inside onCreate() method!!!</p>

```<code>public class WebsiteActivity extends AppCompatActivity {

    @SuppressLint("SetJavaScriptEnabled")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_website);

        WebView webView;
        Intent intent = getIntent();
        String website = intent.getStringExtra("key");

        //Open website
        webView = findViewById(R.id.webViewId);
        webView.getSettings().setJavaScriptEnabled(true);
        webView.setWebViewClient(new WebViewClient());
        webView.loadUrl(website);

    }
}
</code>```

Title: getExtras causing app to crash

Body:
I am working on an Android App that lets me create an Event in CreateActivity, and than passes the data from CreateActivity to the MainActivity through Bundle and putExtras().

It appears as if I am using .getExtras() or getString() wrong. The app crashes once the b.getString("TITLE") function is implemented.

public class MainActivity extends FragmentActivity implements OnClickListener {

    ListView listView;
    int lastIndex = -1;
    ArrayList<Event> lstEvents;

    // detail view
    TextView tvTitle, tvTime, tvDate;
    ImageView img;
    View vw_master;

    boolean _isBack = true;

    ImageButton add;

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

        // get list view
        listView = (ListView) findViewById(R.id.listViewFragment);
        lstEvents = new ArrayList<Event>();

        // // get detail controls
        tvTitle = (TextView) findViewById(R.id.textViewTitle);
        tvDate = (TextView) findViewById(R.id.textViewDate);
        tvTime = (TextView) findViewById(R.id.textViewTime);

        Bundle b = this.getIntent().getExtras();
        b.getString("TITLE");

            add = (ImageButton) findViewById(R.id.add);
        add.setOnClickListener(this);

    }

    @Override
    public void onClick(View v) {
        // TODO Auto-generated method stub
        switch (v.getId()) {
        case R.id.add:
            Intent intent = new Intent(this, CreateActivity.class);
            startActivity(intent);
            break;
        }
    }

}

CREATEACTIVITY

 public class CreateActivity extends Activity implements OnClickListener {

    EditText etTitle;
    Button btDate;
    Button btTime;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_create);
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);

        // /onclicklistener
        findViewById(R.id.btn_confirm).setOnClickListener(this);

        // edittexts and buttons
        btDate = (Button) findViewById(R.id.btn_date);
        etTitle = (EditText) findViewById(R.id.editTextTitle);
        btTime = (Button) findViewById(R.id.btn_time);
    }

    // Will be called via the onClick attribute
    // of the buttons in main.xml
    public void onClick(View view) {
        switch (view.getId()) {
        case R.id.btn_confirm:
             String title = etTitle.getText().toString();
             String time = btTime.getText().toString();
             String date = btDate.getText().toString();

            Log.e("LOG", title);
            Log.e("LOG", time);
            Log.e("LOG", date);

            Bundle newBundle = new Bundle();
            newBundle.putString("TITLE", title);
            newBundle.putString("TIME", time);
            newBundle.putString("DATE", date);

            Intent intent = new Intent(this, MainActivity.class);
            intent.putExtras(newBundle);
            startActivity(intent);
            break;
        }

    }

    public void showTimePickerDialog(View v) {
        DialogFragment newFragment = new TimePickerFragment();
        newFragment.show(getFragmentManager(), "timePicker");
    }

    public void showDatePickerDialog(View v) {
        DialogFragment newFragment = new DatePickerFragment();
        newFragment.show(getFragmentManager(), "datePicker");
    }

}

Error Log :

03-03 15:44:07.117: E/AndroidRuntime(15202): FATAL EXCEPTION: main
03-03 15:44:07.117: E/AndroidRuntime(15202): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.datetracker/com.example.datetracker.MainActivity}: java.lang.NullPointerException
03-03 15:44:07.117: E/AndroidRuntime(15202):    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2202)
03-03 15:44:07.117: E/AndroidRuntime(15202):    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2252)
03-03 15:44:07.117: E/AndroidRuntime(15202):    at android.app.ActivityThread.access$600(ActivityThread.java:146)
03-03 15:44:07.117: E/AndroidRuntime(15202):    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1240)
03-03 15:44:07.117: E/AndroidRuntime(15202):    at android.os.Handler.dispatchMessage(Handler.java:99)
03-03 15:44:07.117: E/AndroidRuntime(15202):    at android.os.Looper.loop(Looper.java:137)
03-03 15:44:07.117: E/AndroidRuntime(15202):    at android.app.ActivityThread.main(ActivityThread.java:5168)
03-03 15:44:07.117: E/AndroidRuntime(15202):    at java.lang.reflect.Method.invokeNative(Native Method)
03-03 15:44:07.117: E/AndroidRuntime(15202):    at java.lang.reflect.Method.invoke(Method.java:511)
03-03 15:44:07.117: E/AndroidRuntime(15202):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:797)
03-03 15:44:07.117: E/AndroidRuntime(15202):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:564)
03-03 15:44:07.117: E/AndroidRuntime(15202):    at dalvik.system.NativeStart.main(Native Method)
03-03 15:44:07.117: E/AndroidRuntime(15202): Caused by: java.lang.NullPointerException
03-03 15:44:07.117: E/AndroidRuntime(15202):    at com.example.datetracker.MainActivity.onCreate(MainActivity.java:47)
03-03 15:44:07.117: E/AndroidRuntime(15202):    at android.app.Activity.performCreate(Activity.java:5200)
03-03 15:44:07.117: E/AndroidRuntime(15202):    at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1080)
03-03 15:44:07.117: E/AndroidRuntime(15202):    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2166)

Body:
You should declare all your variables inside onCreate() method!!!

public class WebsiteActivity extends AppCompatActivity {

    @SuppressLint("SetJavaScriptEnabled")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_website);

        WebView webView;
        Intent intent = getIntent();
        String website = intent.getStringExtra("key");

        //Open website
        webView = findViewById(R.id.webViewId);
        webView.getSettings().setJavaScriptEnabled(true);
        webView.setWebViewClient(new WebViewClient());
        webView.loadUrl(website);

    }
}


问:
How to set modal dialog title dynamically in oracle apex 18
I want to set modal dialog title dynamically based on an interactive element.

ex) In page 50, I've made an Interactive Grid and set the link on "Title" column, when user click on title column, a modal dialog appears.
I want to set the title of that modal dialog to title column's content.

But modal dialog's title doesn't change dynamically.
In this case, how can I apply the titles dynamically?

I've seen many solution related to this question, but I can't solve my problem.

答:
I made such dialogcreate js function.

It moves popup page Title to modal dialog title.

So, dynamic calculated title &P51_TITLE. would be applied automatically.

```<code>$(document).on("dialogcreate", ".ui-dialog--apex", function(e) {
  var lDialog = $(this);
  lDialog.find('iframe').on('load',function () {
      lDialog.children(".ui-dialog-content")
      .dialog("option", "title", $(this.contentDocument).find('title').html());
  });
});
</code>```

I am very disappointed that something like this (or any other solution) do not work in apex modal pages by default!

Body:
I made such dialogcreate js function.

It moves popup page Title to modal dialog title.

So, dynamic calculated title &P51_TITLE. would be applied automatically.

$(document).on("dialogcreate", ".ui-dialog--apex", function(e) {
  var lDialog = $(this);
  lDialog.find('iframe').on('load',function () {
      lDialog.children(".ui-dialog-content")
      .dialog("option", "title", $(this.contentDocument).find('title').html());
  });
});

I am very disappointed that something like this (or any other solution) do not work in apex modal pages by default!


问:
F# - Extract option from Expr
Is there a way to extract a parameter from an Expr?

An example:

```<code>let hasStringOption (e:Expr<string option>) =
    let myOption : string option = ..some code to get the string option from e
</code>```

How would I get the string option inside the Expr and assign it to myOption?

答: Sadly (or not), you cannot evaluate F# quotations. The F# PowerPack has a limited ability to compile quotations to LINQ expressions (which can be evaluated).</p>

Title: F# - Extract option from Expr

Body:
Is there a way to extract a parameter from an Expr?

An example:

let hasStringOption (e:Expr<string option>) =
    let myOption : string option = ..some code to get the string option from e

How would I get the string option inside the Expr and assign it to myOption?


问:
How to fetch mutilple fields using distinct in MongoDb and NodeJS
I am trying to get multiple fields from MongoDb using NodeJS.I am using distinct function to get name and phone number from a documents where order status is pending.

Below is my code:

```<code>const coll = client.db("My_db").collection("Orders");
            coll.distinct("name","phone",{order_status:"pending"},(function(err,docs){

               let output = docs.map(r => ({'name':r,'phone':r}));
                  res.send(output);
            }));
</code>```

It is showing error:

```<code>TypeError: Cannot read property 'map' of undefined.
</code>```

Someone please let me know how can I get desired results.Any help would be appreciated.

THANKS

答:
You can use aggregate to get multiple distinct fields.

```<code>coll.aggregate([
{ "$match": {
     "order_status": "pending"
}},
{ "$group": { "_id": { name: "$name", phone: "$phone" } } }
]).exec().then(docs =>{
 console.log(docs);
 // all your other functionality and response
 }).catch(error=>{
 console.log(error) // catching errors if occurred
 })
</code>```

after this aggregation i don't think you will be needing an map function but you can console.log and check it. if needed the map function will be pretty much the same.

Hope this helps. GOOD LUCK :)

Body:
I am trying to get multiple fields from MongoDb using NodeJS.I am using distinct function to get name and phone number from a documents where order status is pending.

Below is my code:

const coll = client.db("My_db").collection("Orders");
            coll.distinct("name","phone",{order_status:"pending"},(function(err,docs){

               let output = docs.map(r => ({'name':r,'phone':r}));
                  res.send(output);
            }));

It is showing error:

TypeError: Cannot read property 'map' of undefined.

Someone please let me know how can I get desired results.Any help would be appreciated.

THANKS

Body:
You can use aggregate to get multiple distinct fields.

coll.aggregate([
{ "$match": {
     "order_status": "pending"
}},
{ "$group": { "_id": { name: "$name", phone: "$phone" } } }
]).exec().then(docs =>{
 console.log(docs);
 // all your other functionality and response
 }).catch(error=>{
 console.log(error) // catching errors if occurred
 })

after this aggregation i don't think you will be needing an map function but you can console.log and check it. if needed the map function will be pretty much the same.

Hope this helps. GOOD LUCK :)


问:
Parallel automation in Selenium
I am new to Selenium.

My doubt is,

After submitting credential form during automation (login), is it possible to create multiple driver instance, and have multiple browser windows and run events parallely in different threads, by injecting sessions/cookies to increase performance. I learned its not possible to work on different tabs parallely.
My main concern is regarding the time consumption. Would it cost have multiple driver instances?

Thanks in advance.
Happy coding :)

答:
Yes its possible.

Try to use selenium grid documentation can be found here in order to parallelization

It allows to run tests in parallel on multiple machines

I recommend to use it with docker if you are going to work on a local environment

You can found more info here Selenium docker github

Regarding your question, its better to work on different browser instances than trying to work on different tabs.

The only cost will be the infrastructure cost, you can use testing frameworks in python like pytest to parallelize your test execution against selenium grid

Title: Parallel automation in Selenium


答:
Well it depends how you are sending a html file to PHP script.?
If sent in $_GET, Than get file name simply replace .html using str_replace and print it..

Title: How to use a PHP include to print HTML code based on URL filename

Body:
I'm trying to write a simple PHP script that uses PHP include to inject HTML based on the filename of the URL.

For example using a PHP include
- if the filename in the URL is dog.html print dog into the html document.
- if the filename in the URL is cat.html print cat into the html document.

This is to inject JSON-LD code for structured data.

I'm able to use PHP includes to print html code without issue, but its getting it to read the filename and print a specific portion of HTML that I can't seem to make work.


问:
Use value from one cell to define "coordinates" of another cell
I want to use the value of one cell, e.g. 3 to specifiy the coordinates of another cell.

This is what I tried:

```<code>Wert = Range("E22").Value
Sheets("Tabelle2").Range("A1:BWert").Copy
</code>```

答:
I tried it in my actual code and it did copy it however it pasted it from A1 and A1 to like J 1 and J2. heres my entire code: It was supposed to copy the range A1:B10 from Table2 to A1:B10 in Table3.

How could this be done?

```<code>Option Explicit

Sub Kopieren()
Dim Wert As Integer

Wert = Range("E22").Value

Sheets("Tabelle2").Range("A1:B" & Wert).Copy
Sheets("Tabelle3").Range("A1:B" & Wert).PasteSpecial xlPasteValues, Transpose:=True

End Sub```
```

Body:
I want to use the value of one cell, e.g. 3 to specifiy the coordinates of another cell.

This is what I tried:

Wert = Range("E22").Value
Sheets("Tabelle2").Range("A1:BWert").Copy

Body:
I tried it in my actual code and it did copy it however it pasted it from A1 and A1 to like J 1 and J2. heres my entire code: It was supposed to copy the range A1:B10 from Table2 to A1:B10 in Table3.

How could this be done?

Option Explicit

Sub Kopieren()
Dim Wert As Integer

Wert = Range("E22").Value

Sheets("Tabelle2").Range("A1:B" & Wert).Copy
Sheets("Tabelle3").Range("A1:B" & Wert).PasteSpecial xlPasteValues, Transpose:=True

End Sub```


问:
Is Ext-GWT still a nightmare?
Just got back reading a question from 2 years ago here.

From there and several other places on the internet i concluded that developing with Ext-GWT was sucky.

My question is, with the release of GXT 3, whether it is still the condition now?

答: A good performance comparision can be found here: http://gxtvsgwt.appspot.com/</p>

Title: Is Ext-GWT still a nightmare?


问:
How to restart python script inside bash script every x hours?

I have a quite simple question about starting and restarting python scripts inside an bash script. I hope it's not an duplicate but I didn't find a similiar question.
 I'm using a bash script which starts a couple of python scripts every time I create a docker container, but It should be probabaly the same on all linux based machines. It's simple as:

 python3 /mnt/device/script.py &

 Now the script will keep running and measure the brightness until the container is stopped. Now I figured out that there are some problems with the sensor library which are brightly discussed on github and still not solved which causes the script to stop every couple of hours. For me It would be enough to have just some command which restarts my script which is running in the background every x hours to avoid that error.
 So what I'm looking for ist some command which will be like the follwing:

 python3 for hour=1 /mnt/device/script.py restart &

Thanks in advance!

答:
You can use the Bash timeout command to send a signal to kill the Python script.

restart=""
while true; do
    timeout 3600 python3 /mnt/device/script.py $restart
    restart="restart"
done &
```

I'm guessing you don't really need this to run in the background (so maybe take out the &) and that you literally want restart to be passed as an argument after the first time.

Body:
You can use the Bash timeout command to send a signal to kill the Python script.

restart=""
while true; do
    timeout 3600 python3 /mnt/device/script.py $restart
    restart="restart"
done &

I'm guessing you don't really need this to run in the background (so maybe take out the &) and that you literally want restart to be passed as an argument after the first time.


问:
Best fitting rectangle with a variable number of small rectangles keeping aspect ratio
I need to find the optimal placement of a given N child rectangles keeping the aspect ratio of the father rectangle.
Use case is the following:
- the father rectangle is a big picture, let's say 4000x3000 pixels (this one can be rescaled).
- child rectangles are 296x128 pixels (e-ink displays of users)

The objective is to show the big picture across all the current number of displays (this number can change from 1 to 100)

This is an example:

Can happen that number of small rectangles will not fit the big rectangle aspect ratio, like if number of small rectangles is odd, in this case I can think to have like a small number (max 5) of spare rectangles to add in order to complete the big rectangle.

答:
this seems to be a valid approach (python + opencv)</p>

```<code>import cv2
import imutils

def split_image(image, boards_no=25, boards_shape=(128, 296), additional=5):

    # find image aspect ratio
    aspect_ratio = image.shape[1]/image.shape[0]
    print("\nIMAGE INFO:", image.shape, aspect_ratio)

    # find all valid combination of a,b that maximize your available badges
    valid_props = [(a, b) for a in range(boards_no+additional+1) for b in range(boards_no+additional+1) if a*b in [q for q in range(boards_no, boards_no+additional)]]
    print("\nVALID COMBINATIONS", valid_props)

    # find all aspect ratio from previous combination
    aspect_ratio_all = [
        {
            'board_x': a,
            'board_y': b,
            'aspect_ratio': (a*boards_shape[1])/(b*boards_shape[0]),
            'shape': (b*boards_shape[0], a*boards_shape[1]),
            'type': 'h'
        } for (a, b) in valid_props]
    aspect_ratio_all += [
        {
            'board_x': a,
            'board_y': b,
            'aspect_ratio': (a*boards_shape[0])/(b*boards_shape[1]),
            'shape': (b*boards_shape[1], a*boards_shape[0]),
            'type': 'v'
        } for (a, b) in valid_props]

    min_ratio_diff = min([abs(aspect_ratio-x['aspect_ratio']) for x in aspect_ratio_all])
    best_ratio = [x for x in aspect_ratio_all if abs(aspect_ratio-x['aspect_ratio']) == min_ratio_diff][0]
    print("\MOST SIMILAR ASPECT RATIO:", best_ratio)

    # resize image maximining height or width
    resized_img = imutils.resize(image, height=best_ratio['shape'][0])
    border_width = int((best_ratio['shape'][1] - resized_img.shape[1]) / 2)
    border_height = 0

    if resized_img.shape[1] > best_ratio['shape'][1]:
        resized_img = imutils.resize(image, width=best_ratio['shape'][1])
        border_height = int((best_ratio['shape'][0] - resized_img.shape[0]) / 2)
        border_width = 0
    print("RESIZED SHAPE:", resized_img.shape, "BORDERS (H, W):", (border_height, border_width))

    # fill the border with black
    resized_img = cv2.copyMakeBorder(
        resized_img,
        top=border_height,
        bottom=border_height,
        left=border_width,
        right=border_width,
        borderType=cv2.BORDER_CONSTANT,
        value=[0, 0, 0]
    )

    # split in tiles
    M = resized_img.shape[0] // best_ratio['board_y']
    N = resized_img.shape[1] // best_ratio['board_x']
    return [resized_img[x:x+M,y:y+N] for x in range(0,resized_img.shape[0],M) for y in range(0,resized_img.shape[1],N)]

image = cv2.imread('image.jpeg')
tiles = split_image(image)
</code>```

Body:
this seems to be a valid approach (python + opencv)

import cv2
import imutils

def split_image(image, boards_no=25, boards_shape=(128, 296), additional=5):

    # find image aspect ratio
    aspect_ratio = image.shape[1]/image.shape[0]
    print("\nIMAGE INFO:", image.shape, aspect_ratio)

    # find all valid combination of a,b that maximize your available badges
    valid_props = [(a, b) for a in range(boards_no+additional+1) for b in range(boards_no+additional+1) if a*b in [q for q in range(boards_no, boards_no+additional)]]
    print("\nVALID COMBINATIONS", valid_props)

    # find all aspect ratio from previous combination
    aspect_ratio_all = [
        {
            'board_x': a,
            'board_y': b,
            'aspect_ratio': (a*boards_shape[1])/(b*boards_shape[0]),
            'shape': (b*boards_shape[0], a*boards_shape[1]),
            'type': 'h'
        } for (a, b) in valid_props]
    aspect_ratio_all += [
        {
            'board_x': a,
            'board_y': b,
            'aspect_ratio': (a*boards_shape[0])/(b*boards_shape[1]),
            'shape': (b*boards_shape[1], a*boards_shape[0]),
            'type': 'v'
        } for (a, b) in valid_props]

    min_ratio_diff = min([abs(aspect_ratio-x['aspect_ratio']) for x in aspect_ratio_all])
    best_ratio = [x for x in aspect_ratio_all if abs(aspect_ratio-x['aspect_ratio']) == min_ratio_diff][0]
    print("\MOST SIMILAR ASPECT RATIO:", best_ratio)

    # resize image maximining height or width
    resized_img = imutils.resize(image, height=best_ratio['shape'][0])
    border_width = int((best_ratio['shape'][1] - resized_img.shape[1]) / 2)
    border_height = 0

    if resized_img.shape[1] > best_ratio['shape'][1]:
        resized_img = imutils.resize(image, width=best_ratio['shape'][1])
        border_height = int((best_ratio['shape'][0] - resized_img.shape[0]) / 2)
        border_width = 0
    print("RESIZED SHAPE:", resized_img.shape, "BORDERS (H, W):", (border_height, border_width))

    # fill the border with black
    resized_img = cv2.copyMakeBorder(
        resized_img,
        top=border_height,
        bottom=border_height,
        left=border_width,
        right=border_width,
        borderType=cv2.BORDER_CONSTANT,
        value=[0, 0, 0]
    )

    # split in tiles
    M = resized_img.shape[0] // best_ratio['board_y']
    N = resized_img.shape[1] // best_ratio['board_x']
    return [resized_img[x:x+M,y:y+N] for x in range(0,resized_img.shape[0],M) for y in range(0,resized_img.shape[1],N)]

image = cv2.imread('image.jpeg')
tiles = split_image(image)


问:
How to send multiple data streams from single client to a tcp server
Server Side code

var net = require('net');

var server = net.createServer((connection) => {
    console.log('server connected');

    connection.on('data', (data) => {
        console.log('data received');
        console.log('data is: \n' + data);
    });
});

var HOST = '127.0.0.1';
var PORT = '8000'

server.listen(PORT, HOST, function() {
    //listening
    console.log('server is listening to ' + PORT + '\n');

    server.on('connection', function(){
        console.log('connection made...\n')
    })
});
```

<p><strong>Client Side Code</strong></p>

<pre class="lang-js prettyprint-override"><code>var client = new net.Socket()

//connect to the server
client.connect(PORT,HOST,function() {
    'Client Connected to server'

    //send a file to the server
    var fileStream = fs.createReadStream(__dirname + '/readMe.txt');
    // console.log(__dirname + '/readMe.txt');
    fileStream.on('error', function(err){
        console.log(err);
    })

    fileStream.on('open',function() {
        fileStream.pipe(client);
    });

});

//handle closed
client.on('close', function() {
    console.log('server closed connection')
});

client.on('error', function(err) {
    console.log(err);
});
</code>```

I want to know how can we achieve creating a client and a TCP server and sending multiple data from only one client to server.

I know there can be multiple clients that can connect to server that request to server and get response back but I don't want that, I want to know is it possible that a single client can send multiple data streams to a server in node.js.

The thing is suppose there is a file in which 200 lines of chunk data is present so I know we can read that file using createReadStream but suppose there are multiple files which has 200 lines of data (example) so how to send these multiple files over TCP server

Any example would  be appreaciated.

Please give an explanation using a example as I am new to node.js

The example above is sending the data of one file to the server, My question what if the client want to send hundreds of files (or any data streams), So how can he send to through a single medium to TCP server ?

答:
This is possible using the net module, the fs module, and a basic forEach construct for looping over the files:

server.js

const net = require('net');
const host = "localhost";
const port = 3000;

const server = net.createServer((connection) => {
  console.log('server connected');

  connection.on('data', (data) => {
    console.log(`data received: ${data}`);
  });
});

server.listen(port, host, function () {
  console.log(`server is listening on ' + ${port}`);

  server.on('connection', function () {
    console.log('connection made...\n')
  })
});
```

<p><strong>client.js</strong></p>

<pre class="lang-js prettyprint-override"><code>const net = require("net");
const fs = require("fs");
const port = 3000;
const host = "localhost";

const files = [
  "file1.txt",
  "file1.txt",
  "file1.txt"
  // As many files as you want
]

const client = new net.Socket()

client.connect(port, host, function () {

  files.forEach(file => {

    const fileStream = fs.createReadStream(file);
    fileStream.on('error', function (err) {
      console.log(err);
    })

    fileStream.on('open', function () {
      fileStream.pipe(client);
    });

  });
});

client.on('close', function () {
  console.log('server closed connection')
});

client.on('error', function (err) {
  console.log(err);
});
</code>```

Body:
Server Side code

var net = require('net');

var server = net.createServer((connection) => {
    console.log('server connected');

    connection.on('data', (data) => {
        console.log('data received');
        console.log('data is: \n' + data);
    });
});

var HOST = '127.0.0.1';
var PORT = '8000'

server.listen(PORT, HOST, function() {
    //listening
    console.log('server is listening to ' + PORT + '\n');

    server.on('connection', function(){
        console.log('connection made...\n')
    })
});

Client Side Code

var client = new net.Socket()

//connect to the server
client.connect(PORT,HOST,function() {
    'Client Connected to server'

    //send a file to the server
    var fileStream = fs.createReadStream(__dirname + '/readMe.txt');
    // console.log(__dirname + '/readMe.txt');
    fileStream.on('error', function(err){
        console.log(err);
    })

    fileStream.on('open',function() {
        fileStream.pipe(client);
    });

});

//handle closed
client.on('close', function() {
    console.log('server closed connection')
});

client.on('error', function(err) {
    console.log(err);
});

I want to know how can we achieve creating a client and a TCP server and sending multiple data from only one client to server.

I know there can be multiple clients that can connect to server that request to server and get response back but I don't want that, I want to know is it possible that a single client can send multiple data streams to a server in node.js.

The thing is suppose there is a file in which 200 lines of chunk data is present so I know we can read that file using createReadStream but suppose there are multiple files which has 200 lines of data (example) so how to send these multiple files over TCP server

Any example would  be appreaciated.

Please give an explanation using a example as I am new to node.js

The example above is sending the data of one file to the server, My question what if the client want to send hundreds of files (or any data streams), So how can he send to through a single medium to TCP server ?

Body:
This is possible using the net module, the fs module, and a basic forEach construct for looping over the files:

server.js

const net = require('net');
const host = "localhost";
const port = 3000;

const server = net.createServer((connection) => {
  console.log('server connected');

  connection.on('data', (data) => {
    console.log(`data received: ${data}`);
  });
});

server.listen(port, host, function () {
  console.log(`server is listening on ' + ${port}`);

  server.on('connection', function () {
    console.log('connection made...\n')
  })
});

client.js

const net = require("net");
const fs = require("fs");
const port = 3000;
const host = "localhost";

const files = [
  "file1.txt",
  "file1.txt",
  "file1.txt"
  // As many files as you want
]

const client = new net.Socket()

client.connect(port, host, function () {

  files.forEach(file => {

    const fileStream = fs.createReadStream(file);
    fileStream.on('error', function (err) {
      console.log(err);
    })

    fileStream.on('open', function () {
      fileStream.pipe(client);
    });

  });
});

client.on('close', function () {
  console.log('server closed connection')
});

client.on('error', function (err) {
  console.log(err);
});


问:
How to replace NA with set of values
I have the following data frame:

```<code>library(dplyr)
library(tibble)

df <- tibble(
  source = c("a", "b", "c", "d", "e"),
  score = c(10, 5, NA, 3, NA ) )

df
</code>```

It looks like this:

```<code># A tibble: 5 x 2
  source score
  <chr>  <dbl>
1 a         10 . # current max value
2 b          5
3 c         NA
4 d          3
5 e         NA
</code>```

What I want to do is to replace NA in score column with values ranging for existing max  + n onwards. Where n range from 1 to total number of rows of the df

Resulting in this (hand-coded) :

```<code>  source score
  a         10
  b          5
  c         11 # obtained from 10 + 1
  d          3
  e         12 #  obtained from 10 + 2
</code>```

How can I achieve that?

答:
A base R solution

```<code>df$score[is.na(df$score)] <- seq(which(is.na(df$score))) + max(df$score,na.rm = TRUE)
</code>```

such that

```<code>> df
# A tibble: 5 x 2
  source score
  <chr>  <dbl>
1 a         10
2 b          5
3 c         11
4 d          3
5 e         12
</code>```

Title: How to replace NA with set of values

Body:
I have the following data frame:

library(dplyr)
library(tibble)

df <- tibble(
  source = c("a", "b", "c", "d", "e"),
  score = c(10, 5, NA, 3, NA ) )

df

It looks like this:

# A tibble: 5 x 2
  source score
  <chr>  <dbl>
1 a         10 . # current max value
2 b          5
3 c         NA
4 d          3
5 e         NA

What I want to do is to replace NA in score column with values ranging for existing max  + n onwards. Where n range from 1 to total number of rows of the df

Resulting in this (hand-coded) :

  source score
  a         10
  b          5
  c         11 # obtained from 10 + 1
  d          3
  e         12 #  obtained from 10 + 2

How can I achieve that?

Body:
A base R solution

df$score[is.na(df$score)] <- seq(which(is.na(df$score))) + max(df$score,na.rm = TRUE)

such that

> df
# A tibble: 5 x 2
  source score
  <chr>  <dbl>
1 a         10
2 b          5
3 c         11
4 d          3
5 e         12


问:
Is this kind of DB extension ok? / other faster(writing) NewRow() implementations
Do you agree this extension is ok, with normal code guidelines?

Or do you prefer another easy writing NewRow() solution?

```<code>        /// <summary>
        /// Adds a new row, with action. After the action, the row will be added to the tab
        /// </summary>
        public static void NewRow(this DataTable table, Action<DataRow> action)
        {
            var r = table.NewRow();
            action.Invoke(r);
            table.Rows.Add(r);
        }
....

            var tab = new DataTable();
            tab.Columns.Add("Foo", typeof(string));
            tab.Columns.Add("Bar", typeof(string));

            //add one row
            tab.NewRow((x) => x["FOO"] = "TEST");

            //add another row
            tab.NewRow((x) =>
            {
                x["FOO"] = "TEST2";
                x["BAR"] = "TEST2";
            });

</code>```

答:
Asking whether people agree with things is, almost by definition, entirely subjective. Will it work? Probably. To my mind, it seems entirely redundant compared with just returning the row and letting the caller work with it after adding, and note that anonymous methods (the lambdas) can have unexpected costs re captured variables etc. But; it'll work.

Personally, my main concern would be that you're using DataTable at all. There are scenarios where this is appropriate, but they are few and far between, and DataTable should not be your default data-handling choice (unless you're writing a tool that deals with ad-hoc queries on unknown databases). Contrast:

var list = new List<MyPurposeSpecificType>();
//...
list.Add(new MyPurposeSpecificType { Foo = "TEST", Bar = "TEST2" });
```

Body:
Do you agree this extension is ok, with normal code guidelines?

Or do you prefer another easy writing NewRow() solution?

        ///
        /// Adds a new row, with action. After the action, the row will be added to the tab
        ///
        public static void NewRow(this DataTable table, Action<DataRow> action)
        {
            var r = table.NewRow();
            action.Invoke(r);
            table.Rows.Add(r);
        }
....

            var tab = new DataTable();
            tab.Columns.Add("Foo", typeof(string));
            tab.Columns.Add("Bar", typeof(string));

            //add one row
            tab.NewRow((x) => x["FOO"] = "TEST");

            //add another row
            tab.NewRow((x) =>
            {
                x["FOO"] = "TEST2";
                x["BAR"] = "TEST2";
            });


答:
You could read the lists into a dictionary using regular expressions:</p>

```<code>import re
with open('file_name') as file:
    contents = file.read()
res_list = re.findall(r"[a-z]+\s+[^a-z]+",contents)
res_dict = {}
for p in res_list:
    elt = p.split()
    res_dict[elt[0]] = [e for e in elt[1:] if e != '*']

print(res_dict)
</code>```

Title: Adding words between lines to an array

Body:
This is the content of my file:

david    C001 C002 C004 C005 C006 C007

*    C008 C009 C010 C011 C016 C017 C018

*    C019 C020 C021 C022 C023 C024 C025

anna C500 C521 C523 C547 C555 C556

*    C557 C559 C562 C563 C566 C567 C568

*    C569 C571 C572 C573 C574 C575 C576

*    C578

charlie    C701 C702 C704 C706 C707 C708

*    C709 C712 C715 C716 C717 C718

I want my output to be:

david=[C001,C002,C004,C005,C006,C007,C008,C009,C010,C011,C016,C017,C018,C019,C020,C021,C022,C023,C024,C025]

anna=[C500,C521,C523,C547,C555,C556,C557,C559,C562,C563,C566,C567,C568,C569,C571,C572,C573,C574,C575,C576,C578]

charlie=[C701,C702,C704,C706,C707,C708,C709,C712,C715,C716,C717,C718]

I am able to create:

david=[C001,C002,C004,C005,C006,C007]
anna=[C500,C521,C523,C547,C555,C556]
charlie=[C701,C702,C704,C706,C707,C708]

counting the number of words in a line and using line[0] as the array name and adding the remaining words to the array.
However, I don't know how to take the continuation of words in the next lines starting with "*" to the array.

Can anyone help?

Body:
You could read the lists into a dictionary using regular expressions:

import re
with open('file_name') as file:
    contents = file.read()
res_list = re.findall(r"[a-z]+\s+[^a-z]+",contents)
res_dict = {}
for p in res_list:
    elt = p.split()
    res_dict[elt[0]] = [e for e in elt[1:] if e != '*']

print(res_dict)


问:
How to spread component props inside passed node element?
My question might be confusing but let me explain with an example here, let's say I have Button component and it has 5 different props like (type, href, appearance...) and if we want to do following:

```<code><Button type='button' href='<a { ...buttonProps }>Test Link</a>'/>
</code>```

Basically attach all Button props to a tag easily.

I found something similar over here but didn't get it. Any suggestions?

答:
You could do something like this if I understand the question properly:

Hooks area:

```<code>const clickHandler = () => {
    top.location.href = 'http://localhost';
}
</code>```

Then in the body

<Button onClick={()=>clickHandler(e)}>My Button</Button>
```

Body:
My question might be confusing but let me explain with an example here, let's say I have Button component and it has 5 different props like (type, href, appearance...) and if we want to do following:

<Button type='button' href='Test Link'/>

Basically attach all Button props to a tag easily.

I found something similar over here but didn't get it. Any suggestions?

Body:
You could do something like this if I understand the question properly:

Hooks area:

const clickHandler = () => {
    top.location.href = 'http://localhost';
}

Then in the body

<Button onClick={()=>clickHandler(e)}>My Button</Button>