问:
Manifest merger failed when adding CameraX gradle dependency
I'm trying to use the CameraX library in a brand new Android Studio project based off the official CameraX demo app:

I've added the following dependencies to my (module) build.gradle:

```<code>    implementation "androidx.camera:camera-core:1.0.0-alpha01"
    implementation "androidx.camera:camera-camera2:1.0.0-alpha01"
</code>```

and my AndroidManifest.xml looks like:

```<code>    <?xml version="1.0" encoding="utf-8"?>
    <manifest xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    package="simplediary.raouf.camerapoc">

        <uses-permission android:name="android.permission.CAMERA" />
        <uses-feature android:name="android.hardware.camera" />

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

Trying to run the project I get the following error

```<code>Manifest merger failed : Attribute application@appComponentFactory value=(android.support.v4.app.CoreComponentFactory) from [com.android.support:support-compat:28.0.0] AndroidManifest.xml:22:18-91
is also present at [androidx.core:core:1.1.0-beta01] AndroidManifest.xml:22:18-86 value=(androidx.core.app.CoreComponentFactory).
Suggestion: add 'tools:replace="android:appComponentFactory"' to <application> element at AndroidManifest.xml:9:3-23:17 to override.
</code>```

Adding "tools:replace="android:appComponentFactory" to the application element in the manifest now results in this error:

```<code>Manifest merger failed with multiple errors, see logs
</code>```

So under 'Merged Manifest' in AndroidManifest.xml these are the errors I'm now seeing:

```<code>Error: tools:replace specified at line:9 for attribute android:appComponentFactory, but no new value specified app main manifest (this file), line 8 Error: Validation failed, exiting app main manifest (this file)
</code>```

How can I get around this issue? Full build.gradle:

```<code>apply plugin: 'com.android.application'

android {
    compileSdkVersion 28
    defaultConfig {
        applicationId "simplediary.raouf.camerapoc"
        minSdkVersion 21
        targetSdkVersion 28
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner
"android.support.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'),
'proguard-rules.pro'
        }
    }
}

dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    implementation 'com.android.support:appcompat-v7:28.0.0'
    implementation 'com.android.support.constraint:constraint-layout:1.1.3'
    implementation "androidx.camera:camera-core:1.0.0-alpha01"
    implementation "androidx.camera:camera-camera2:1.0.0-alpha01"
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'com.android.support.test:runner:1.0.2'
    androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2'
}
</code>```

Appreciate any help!

答:
You'll have to Migrate to AndroidX library:

here's the steps:

1/ go under "refactor"

2/in the drop down menu select "Migrate to AndroidX"

3/make sure to keep a Backup (by version control or check the keep backup checkbox)

4/follow the setup wizard

5/when finished clean project & rebuild

Body:
I'm trying to use the CameraX library in a brand new Android Studio project based off the official CameraX demo app:

I've added the following dependencies to my (module) build.gradle:

    implementation "androidx.camera:camera-core:1.0.0-alpha01"
    implementation "androidx.camera:camera-camera2:1.0.0-alpha01"

and my AndroidManifest.xml looks like:

    <?xml version="1.0" encoding="utf-8"?>
    <manifest xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    package="simplediary.raouf.camerapoc">

        <uses-permission android:name="android.permission.CAMERA" />
        <uses-feature android:name="android.hardware.camera" />

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

Trying to run the project I get the following error

Manifest merger failed : Attribute application@appComponentFactory value=(android.support.v4.app.CoreComponentFactory) from [com.android.support:support-compat:28.0.0] AndroidManifest.xml:22:18-91
is also present at [androidx.core:core:1.1.0-beta01] AndroidManifest.xml:22:18-86 value=(androidx.core.app.CoreComponentFactory).
Suggestion: add 'tools:replace="android:appComponentFactory"' to <application> element at AndroidManifest.xml:9:3-23:17 to override.

Adding "tools:replace="android:appComponentFactory" to the application element in the manifest now results in this error:

Manifest merger failed with multiple errors, see logs

So under 'Merged Manifest' in AndroidManifest.xml these are the errors I'm now seeing:

Error: tools:replace specified at line:9 for attribute android:appComponentFactory, but no new value specified app main manifest (this file), line 8 Error: Validation failed, exiting app main manifest (this file)

How can I get around this issue? Full build.gradle:

apply plugin: 'com.android.application'

android {
    compileSdkVersion 28
    defaultConfig {
        applicationId "simplediary.raouf.camerapoc"
        minSdkVersion 21
        targetSdkVersion 28
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner
"android.support.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'),
'proguard-rules.pro'
        }
    }
}

dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    implementation 'com.android.support:appcompat-v7:28.0.0'
    implementation 'com.android.support.constraint:constraint-layout:1.1.3'
    implementation "androidx.camera:camera-core:1.0.0-alpha01"
    implementation "androidx.camera:camera-camera2:1.0.0-alpha01"
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'com.android.support.test:runner:1.0.2'
    androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2'
}

Appreciate any help!


来源: stackexchange

问:
Not receiving Terminated after Exception in Akka.net
I have two actors (a parent and a child) and I use SupervisorStrategy.StoppingStrategy and Watch to handle errors. But the problem is that the parent is not receiving a Terminated-message when the child dies.

Below is a simple test to verify my problem.

```<code>    [Fact]
    public void ExceptionTest()
    {
        var child = Sys.ActorOf(Props.Create(() => new FooActor(), SupervisorStrategy.StoppingStrategy), "Name");
        Watch(child);
        child.Tell("Some message");
        ExpectMsg<Terminated>(); // This will not occur.
    }

    public class FooActor : ReceiveActor
    {
        public FooActor()
        {
            ReceiveAny((e) =>
            {
                // Crashes on every message.
                throw new Exception();
            });
        }
    }
</code>```

What I want is that the parent which is watching the child should get a Terminated whenever the child has an error which it doesn't handle. How can I accomplish it?

It works fine when I send a PoisonPill instead of throwing an Exception.

答:
Actors in tests seems to be created with restart supervising strategy and thus will not kill the actor when the exception happens. I can't find a way to change the supervisor strategy of tests. So I wrote this to create actors in tests with stopping supervisor strategy with out having to write a "real" wrapper actor.

```<code>    [Fact]
    public async Task ExceptionTest()
    {
        var actor = await CreateActorWithStoppingStrategy(Props.Create(() => new AsGoodAsDead()));

        Watch(actor);

        actor.Tell("Death");

        ExpectTerminated(actor);
    }

    private async Task<IActorRef> CreateActorWithStoppingStrategy(Props props)
    {
        IActorRef child = null;
        Action<IActorDsl> actor = d =>
        {
            d.Strategy   = SupervisorStrategy.StoppingStrategy;
            d.OnPreStart = context => child = context.ActorOf(props);
            d.ReceiveAny((o, context) => context.Sender.Tell("ready"));
        };
        var parent = Sys.ActorOf(Props.Create(() => new Act(actor)));
        await parent.Ask("ready?");
        return child;
    }

    public class AsGoodAsDead : UntypedActor
    {
        protected override void OnReceive(object message)
        {
            throw new Exception();
        }
    }
</code>```

The following line you wrote will give the child the stopping supervisor strategy, meaning the child's children will be stopped when something happens.

```<code>    var child = Sys.ActorOf(Props.Create(() => new FooActor(), SupervisorStrategy.StoppingStrategy), "Name");
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I have two actors (a parent and a child) and I use SupervisorStrategy.StoppingStrategy and Watch to handle errors. But the problem is that the parent is not receiving a Terminated-message when the child dies.

Below is a simple test to verify my problem.

    [Fact]
    public void ExceptionTest()
    {
        var child = Sys.ActorOf(Props.Create(() => new FooActor(), SupervisorStrategy.StoppingStrategy), "Name");
        Watch(child);
        child.Tell("Some message");
        ExpectMsg<Terminated>(); // This will not occur.
    }

    public class FooActor : ReceiveActor
    {
        public FooActor()
        {
            ReceiveAny((e) =>
            {
                // Crashes on every message.
                throw new Exception();
            });
        }
    }

What I want is that the parent which is watching the child should get a Terminated whenever the child has an error which it doesn't handle. How can I accomplish it?

It works fine when I send a PoisonPill instead of throwing an Exception.

Body:
Actors in tests seems to be created with restart supervising strategy and thus will not kill the actor when the exception happens. I can't find a way to change the supervisor strategy of tests. So I wrote this to create actors in tests with stopping supervisor strategy with out having to write a "real" wrapper actor.

    [Fact]
    public async Task ExceptionTest()
    {
        var actor = await CreateActorWithStoppingStrategy(Props.Create(() => new AsGoodAsDead()));

        Watch(actor);

        actor.Tell("Death");

        ExpectTerminated(actor);
    }

    private async Task<IActorRef> CreateActorWithStoppingStrategy(Props props)
    {
        IActorRef child = null;
        Action<IActorDsl> actor = d =>
        {
            d.Strategy   = SupervisorStrategy.StoppingStrategy;
            d.OnPreStart = context => child = context.ActorOf(props);
            d.ReceiveAny((o, context) => context.Sender.Tell("ready"));
        };
        var parent = Sys.ActorOf(Props.Create(() => new Act(actor)));
        await parent.Ask("ready?");
        return child;
    }

    public class AsGoodAsDead : UntypedActor
    {
        protected override void OnReceive(object message)
        {
            throw new Exception();
        }
    }

The following line you wrote will give the child the stopping supervisor strategy, meaning the child's children will be stopped when something happens.

    var child = Sys.ActorOf(Props.Create(() => new FooActor(), SupervisorStrategy.StoppingStrategy), "Name");


问:
Combing search results to use UNION or is there some other method
I have the following statement:

```<code>SELECT *
  FROM wp_bibliography x
  JOIN wp_term_relationships y
    ON y.object_id = x.post_id
WHERE y.term_taxonomy_id = 106
</code>```

I need to return results from wp_bibliography where term_taxonomy_id could be a single number as above or multiple, i.e return rows where term_taxonomy_id could be 106 and 108.

Should I be using a UNION for this? Obviously I need to remove any duplicates.

I have tried to use an IN('106','108') however this causes duplication.

I can't use an AND because then the join won't work. Any help would be much appreciated.

答:
At a guess, you're probably after something like this: </p>

```<code>SELECT c.olumns
     , y.ou
     , a.ctually
     , w.ant
  FROM wp_bibliography x
  JOIN wp_term_relationships y
    ON y.object_id = x.post_id
 WHERE y.term_taxonomy_id IN(106,108)
 GROUP
    BY s.omething
HAVING COUNT(*) = 2 -- WHERE '2 is the number of arguments in IN()
</code>```

Body:
I have the following statement:

SELECT *
  FROM wp_bibliography x
  JOIN wp_term_relationships y
    ON y.object_id = x.post_id
WHERE y.term_taxonomy_id = 106

I need to return results from wp_bibliography where term_taxonomy_id could be a single number as above or multiple, i.e return rows where term_taxonomy_id could be 106 and 108.

Should I be using a UNION for this? Obviously I need to remove any duplicates.

I have tried to use an IN('106','108') however this causes duplication.

I can't use an AND because then the join won't work. Any help would be much appreciated.

Body:
At a guess, you're probably after something like this:

SELECT c.olumns
     , y.ou
     , a.ctually
     , w.ant
  FROM wp_bibliography x
  JOIN wp_term_relationships y
    ON y.object_id = x.post_id
 WHERE y.term_taxonomy_id IN(106,108)
 GROUP
    BY s.omething
HAVING COUNT(*) = 2 -- WHERE '2 is the number of arguments in IN()


问:
Possibilities for sending push-notifications from a PHP webserver to an android smartwatch (without using Firebase/GCM etc.)
I am looking for Options to send push-notifications from laravel-php-web applications to an Android smartwatch. But I do not want to use any cloud service like Google Cloud Messaging or Google Firebase etc, because I don't want to share the sent sensible data with Google or another company.

Do you maybe have any suggestions about how to implement something like this?

答:
If you want to avoid using Google Firebase, you could make use of another service like Pusher or PubNub.
You could also make your own Pub/Sub server with Socket.io or the new Laravel-WebSockets library, a library that use the same API as Pusher (for easy integration). This last option is the one I'd recommend. You can check this channel for an in-deep tutorial.

In order to make Laravel-WebSockets to work with Android, just use the Pusher library for Android and set your host variables and keys in the config.


问:
Inserting multiple records in laravel
How do I multiple records in the bills_infos table?
It takes the data and stores in the array variable and even I can access it with the compact function. I have marked from where the problem starts.

public function store(Request $request){
    $request->validate([
            'from'=>'required',
            'to'=>'required',
            'textbox1'=>'required',
            'rate1'=>'required',
            'qty1'=>'required',
    ]);
    $store_bill=new Bills();
    $store_bill->from=request('from');
    $store_bill->name=request('to');
    $store_bill->discount=request('discount');
    if(is_null($store_bill->discount))
    {
        $store_bill->discount=0;
    }
    $store_bill->save();
    $invoice_no=Bills::orderBy('created_at','desc')->pluck('id')->first();
    for($i=1;$i<=10;$i++)
    {
        $item_name[$i]=request('textbox'.$i);
        $amount[$i]=request('rate'.$i);
        $quantity[$i]=request('qty'.$i);
    }
    //return compact('item_name','amount','quantity');
    //Works fine till here.
    /* Not Working From Here. */
    for($i=1;$i<=10;$i++)
    {
        if(!(is_null($item_name[$i]) || is_null($amount[$i]) || is_null($quantity[$i])))
        {
            $store_bills_info=new Bills_Infos();
            $store_bills_info->bills_id=$invoice_no;
            $store_bills_info->item_name=$item_name[$i];
            $store_bills_info->amount=$amount[$i];
            $store_bills_info->quantity=$quantity[$i];
            $store_bills_info->total=$amount[$i]*$quantity[$i];
            $store_bills_info->save();
            //return compact('store_bills_info');
            return view('print')->with('invoice_no',$invoice_no);
        }
    }
    return "Invoice can't be created due to some error";
}
```

答:
It not work because when your loop is in 0 iteration you used return !
And your loop dosnt go to the next iteration .

When you returning some thing in PHP functions codes after that will not be compiled .

So simply move your return after for .

Title: Inserting multiple records in laravel


问:
Table does not draw following rows
I tried to draw multiple tables with one stage, so far it worked with two tables in different rows, but when I try to add the 3rd or 4th it doesn't work. I tried to draw the tables alone and they work but not in combination which is funny, because they work for 2 Tables....

I tried drawing the tables single alone and they worked but not in combination.

```<code>public void setupScreen() {
    TextureAtlas menuUi = assetManager.get(Assetdescriptor.backGround);
    TextureRegion backGroundRegion = menuUi.findRegion(Regionnames.backGround);

    Skin menuSkin = assetManager.get(Assetdescriptor.skinUI);

    TextButton team1 = new TextButton("Team 1", menuSkin, "Team1");

    TextButton team2 = new TextButton("Team 2", menuSkin, "Team1");

    TextButton team3 = new TextButton("Team 3", menuSkin, "Team3");

    TextButton team4 = new TextButton("Team 4", menuSkin, "Team4");

    TextButton team5 = new TextButton("Team 5", menuSkin, "Team5");

    TextButton player1 = new TextButton("Spieler 1", menuSkin);
    player1.addListener(new ChangeListener() {
        @Override
        public void changed(ChangeEvent event, Actor actor) {
            System.out.println("Clicked");
        }
    });

    TextButton player2 = new TextButton("Spieler 2", menuSkin);

    TextButton kiPanzer1 = new TextButton("Ki Panzer 1", menuSkin);

    TextButton kiPanzer2 = new TextButton("Ki Panzer 2", menuSkin);

    TextButton kiPanzer3 = new TextButton("Ki Panzer 3", menuSkin);

    Table teamTable1 = new Table();
    Table teamTable2 = new Table();
    Table teamTable3 = new Table();
    Table teamTable4 = new Table();
    Table teamTable5 = new Table();

    Table TeamOverview = new Table();
    Table spieler1= new Table(); // Spieler 1
    Table spieler2= new Table(); // Spieler 2
    Table Ki3     = new Table(); // Ki Panzer
    Table Ki4     = new Table(); // Ki Panzer
    Table Ki5     = new Table(); // Ki panzer

    spieler1.add(player1);
    spieler2.add(player2);
    Ki3.add(kiPanzer1);
    Ki4.add(kiPanzer2);
    Ki5.add(kiPanzer3);

    TeamOverview.add(team1, team2, team3, team4, team5);

    teamTable1.center();
    teamTable1.add(spieler1,spieler2,Ki3,Ki4,Ki5);
    teamTable2.center();
    teamTable2.add(spieler1,spieler2,Ki3,Ki4,Ki5);
    teamTable3.center();
    teamTable3.add(spieler1,spieler2,Ki3,Ki4,Ki5);
    teamTable4.center();
    teamTable4.add(spieler1,spieler2,Ki3,Ki4,Ki5);

    Table table = new Table();
    table.add(TeamOverview);
    table.add(teamTable1).row();
   -- -These are the tables which dont work---
    table.add(teamTable2).row();
    table.add(teamTable3).row();
    table.add(teamTable4).row();
    -----------------------------------

    table.setFillParent(true);
    table.setBackground(new TextureRegionDrawable(backGroundRegion));
    table.pack();

    stage.addActor(table);

}
</code>```

There is no error message, but there is no change in drawing expected result is 6 rows but there is only 2.

答:
As far as I know you are not allowed to reuse the same object's (spieler1,spieler2,Ki3,Ki4,Ki5). Create unique instance for every time you add them to the different tables.

Check com.badlogic.gdx.scenes.scene2d.Group#addActor
(which Table extends from)

```<code>    public void addActor (Actor actor) {
        if (actor.parent != null) {
            if (actor.parent == this) return;
            actor.parent.removeActor(actor, false);
        }
        children.add(actor);
        actor.setParent(this);
        actor.setStage(getStage());
        childrenChanged();
    }
</code>```

A actor can only have one parent, the previous one is removed.
Your table might still have all the rows you want, they are just empty.
You can use setDebug(true) to see the drawing 'lines'.

Edit

This question seems to be a duplicate anyway.
Refer to
 How to draw several copies of the same actor on one stage at different positions?

Title: Table does not draw following rows

Body:
I tried to draw multiple tables with one stage, so far it worked with two tables in different rows, but when I try to add the 3rd or 4th it doesn't work. I tried to draw the tables alone and they work but not in combination which is funny, because they work for 2 Tables....

I tried drawing the tables single alone and they worked but not in combination.

public void setupScreen() {
    TextureAtlas menuUi = assetManager.get(Assetdescriptor.backGround);
    TextureRegion backGroundRegion = menuUi.findRegion(Regionnames.backGround);

    Skin menuSkin = assetManager.get(Assetdescriptor.skinUI);

    TextButton team1 = new TextButton("Team 1", menuSkin, "Team1");

    TextButton team2 = new TextButton("Team 2", menuSkin, "Team1");

    TextButton team3 = new TextButton("Team 3", menuSkin, "Team3");

    TextButton team4 = new TextButton("Team 4", menuSkin, "Team4");

    TextButton team5 = new TextButton("Team 5", menuSkin, "Team5");

    TextButton player1 = new TextButton("Spieler 1", menuSkin);
    player1.addListener(new ChangeListener() {
        @Override
        public void changed(ChangeEvent event, Actor actor) {
            System.out.println("Clicked");
        }
    });

    TextButton player2 = new TextButton("Spieler 2", menuSkin);

    TextButton kiPanzer1 = new TextButton("Ki Panzer 1", menuSkin);

    TextButton kiPanzer2 = new TextButton("Ki Panzer 2", menuSkin);

    TextButton kiPanzer3 = new TextButton("Ki Panzer 3", menuSkin);

    Table teamTable1 = new Table();
    Table teamTable2 = new Table();
    Table teamTable3 = new Table();
    Table teamTable4 = new Table();
    Table teamTable5 = new Table();

    Table TeamOverview = new Table();
    Table spieler1= new Table(); // Spieler 1
    Table spieler2= new Table(); // Spieler 2
    Table Ki3     = new Table(); // Ki Panzer
    Table Ki4     = new Table(); // Ki Panzer
    Table Ki5     = new Table(); // Ki panzer

    spieler1.add(player1);
    spieler2.add(player2);
    Ki3.add(kiPanzer1);
    Ki4.add(kiPanzer2);
    Ki5.add(kiPanzer3);

    TeamOverview.add(team1, team2, team3, team4, team5);

    teamTable1.center();
    teamTable1.add(spieler1,spieler2,Ki3,Ki4,Ki5);
    teamTable2.center();
    teamTable2.add(spieler1,spieler2,Ki3,Ki4,Ki5);
    teamTable3.center();
    teamTable3.add(spieler1,spieler2,Ki3,Ki4,Ki5);
    teamTable4.center();
    teamTable4.add(spieler1,spieler2,Ki3,Ki4,Ki5);

    Table table = new Table();
    table.add(TeamOverview);
    table.add(teamTable1).row();
   -- -These are the tables which dont work---
    table.add(teamTable2).row();
    table.add(teamTable3).row();
    table.add(teamTable4).row();
    -----------------------------------

    table.setFillParent(true);
    table.setBackground(new TextureRegionDrawable(backGroundRegion));
    table.pack();

    stage.addActor(table);

}

There is no error message, but there is no change in drawing expected result is 6 rows but there is only 2.

Body:
As far as I know you are not allowed to reuse the same object's (spieler1,spieler2,Ki3,Ki4,Ki5). Create unique instance for every time you add them to the different tables.

Check com.badlogic.gdx.scenes.scene2d.Group#addActor
(which Table extends from)

    public void addActor (Actor actor) {
        if (actor.parent != null) {
            if (actor.parent == this) return;
            actor.parent.removeActor(actor, false);
        }
        children.add(actor);
        actor.setParent(this);
        actor.setStage(getStage());
        childrenChanged();
    }

A actor can only have one parent, the previous one is removed.
Your table might still have all the rows you want, they are just empty.
You can use setDebug(true) to see the drawing 'lines'.

Edit

This question seems to be a duplicate anyway.
Refer to
 How to draw several copies of the same actor on one stage at different positions?


问:
Map a Mono field to a chain method
I'm relatively new to Spring WebFlux and Reactive programming in general, so please pardon my question is it doesn't make any sense.

I have a simple @PostMapping method that I'm trying to map a field in Mono to another chain method as such:

   @PostMapping
   public Mono<Delay> getPlanetNames(@RequestBody Mono<Delay> delayBody) {
      return delayBody
          .map(p -> new Delay(p.getDelayTime(), getRandomPlanetName()))
          .delayElement(Duration.ofMillis(50));
   }

    public String getRandomPlanetName() {
        Random rand = new Random();
        List<String> list = Stream.of(
                "Mercury",
                "Neptune")
                .collect(Collectors.toList());
        return list.get(rand.nextInt(list.size()));
    }
```

<p>Basically what I want to achieve is to return a new Planet's name with "getRandomPlanetName()" and at the meantime setting a "delayElement" with a field in the Delay object. Something like this:</p>

<pre class="lang-java prettyprint-override"><code>   @PostMapping
   public Mono<Delay> getPlanetNames(@RequestBody Mono<Delay> delayBody) {
      return delayBody
          .map(p -> new Delay(p.getDelayTime(), getRandomPlanetName()))
          .delayElement(Duration.ofMillis(delayBody.getDelayTime));
   }

</code>```

Also, is it possible for me to return just a String, which is the result of getPlanetName() instead of a Mono of an object?

答:
Basically this looks into the Mono<Delay> for the delay time, and creates another Mono with this delayElement(delayTime).

```<code>@PostMapping
public Mono<String> getPlanetNames(@RequestBody Mono<Delay> delayBody) {
  return delayBody.flatMap(p -> {
    return Mono.just(getRandomPlanetName())
        .delayElement(Duration.ofMillis(p.getDelayTime()));
  });
}

private String getRandomPlanetName() {
  Random rand = new Random();
  List<String> list = Arrays.asList("Mercury", "Neptune");
  return list.get(rand.nextInt(list.size()));
}
</code>```

for better human readablity I put in the {}, you could also just write this:

```<code>@PostMapping
public Mono<String> getPlanetNames(@RequestBody Mono<Delay> delayBody) {
  return delayBody.flatMap(p -> Mono.just(getRandomPlanetName()).delayElement(Duration.ofMillis(p.getDelayTime())));
}
</code>```

Title: Map a Mono field to a chain method

Body:
I'm relatively new to Spring WebFlux and Reactive programming in general, so please pardon my question is it doesn't make any sense.

I have a simple @PostMapping method that I'm trying to map a field in Mono to another chain method as such:

   @PostMapping
   public Mono<Delay> getPlanetNames(@RequestBody Mono<Delay> delayBody) {
      return delayBody
          .map(p -> new Delay(p.getDelayTime(), getRandomPlanetName()))
          .delayElement(Duration.ofMillis(50));
   }

    public String getRandomPlanetName() {
        Random rand = new Random();
        List<String> list = Stream.of(
                "Mercury",
                "Neptune")
                .collect(Collectors.toList());
        return list.get(rand.nextInt(list.size()));
    }

Basically what I want to achieve is to return a new Planet's name with "getRandomPlanetName()" and at the meantime setting a "delayElement" with a field in the Delay object. Something like this:

   @PostMapping
   public Mono<Delay> getPlanetNames(@RequestBody Mono<Delay> delayBody) {
      return delayBody
          .map(p -> new Delay(p.getDelayTime(), getRandomPlanetName()))
          .delayElement(Duration.ofMillis(delayBody.getDelayTime));
   }

Also, is it possible for me to return just a String, which is the result of getPlanetName() instead of a Mono of an object?

Body:
Basically this looks into the Mono<Delay> for the delay time, and creates another Mono with this delayElement(delayTime).

@PostMapping
public Mono<String> getPlanetNames(@RequestBody Mono<Delay> delayBody) {
  return delayBody.flatMap(p -> {
    return Mono.just(getRandomPlanetName())
        .delayElement(Duration.ofMillis(p.getDelayTime()));
  });
}

private String getRandomPlanetName() {
  Random rand = new Random();
  List<String> list = Arrays.asList("Mercury", "Neptune");
  return list.get(rand.nextInt(list.size()));
}

for better human readablity I put in the {}, you could also just write this:

@PostMapping
public Mono<String> getPlanetNames(@RequestBody Mono<Delay> delayBody) {
  return delayBody.flatMap(p -> Mono.just(getRandomPlanetName()).delayElement(Duration.ofMillis(p.getDelayTime())));
}


问:
JavaScript documentation across standardized browsers for Events
I am attempting to learn JavaScript and find this task to be a bit difficult in some respects. Currently I am looking into event support across the major browsers. As far as events go, there seems to be two general flavors: (1) the Microsoft way, and (2) the standardized way.

I am aware that IE 8 does not support DOM Level 2 Events, but that IE 9 is expected to support DOM Level 3 Events. On the Microsoft side there exists a distinct list of DHTML Events. A description of the event object is also available.

In the standardized way I am clumping together DOM Level 0 support which has no official specification, and DOM Level 2 Events that where written by the W3C. This standardized way is generally followed by all of the major browsers except MSIE, namely: Firefox, Chrome, Safari, and Opera. Each of the standardized browsers have a varying level of documentation around their support of events as indicated by the following links.

DOM Level 0 Events

Gecko DOM Event Handlers

Safari HTML Reference: Supported Attributes

HTML, XHTML, and WML in Opera Presto 2.8

No information for Chrome.

DOM Level 2 Events

W3C DOM Level 2 Specification

Gecko DOM Events (appears to be incomplete)

Other Gecko DOM Events

Gecko DOM Event Object

WebKit Standards Support Targets (implicitly covering Chrome and Safari at a high level)

DOM 2 UI, Mouse & Mutation Events support in Opera Presto 2.8

Is it safe to say that the documentation across the standardized browsers is interoperable? I am aware of the Quirksmode Compatibility Tables in regards to this type of information. However, I hardly find that comforting when a problem is encountered and hope that there that are details I can count on instead. I'd also like to exclude libraries (such as Jquery and such) at this point.

答: No. There is much variation around key events within browsers, and the big libraries such as jQuery only normalize a bare minimum of it (correctly, in my view). The only way to deal with the inconsistencies is to learn from people who have learned the hard way. The best resource by miles that I've found is this page by Jan Wolter: http://unixpapa.com/js/key.html. Accurate and fairly comprehensive.</p>

ContentLicense: CC BY-SA 3.0


问:
Find an exact match from a patterns file for another file using awk (patterns contain regex symbols to be ignored)
I have a file which has the following patterns.

```<code>NO_MATCH
NO_MATCH||NO_MATCH
NO_MATCH||NO_MATCH||NO_MATCH
NO_MATCH||NO_MATCH||NO_MATCH||NO_MATCH
</code>```

These should be matched exactly with the 5th column of the target csv. I have tried:

```<code>awk 'NR==FNR{a[$0]=$0; next;} NR>FNR{if($5==a[$0])print $0}' pattern.csv input.csv > final_out.csv
</code>```

But the ||  in the patterns file result in bad matches. The 5th column in the target csv looks something like this:

```<code>"AAAA||AAAA"
"BBBB||BBBB"
"NO_MATCH"
"NO_MATCH||NO_MATCH||NO_MATCH"
"NO_MATCH||BBBB"
</code>```

I need to extract the 3rd and 4th lines.
Edit: I need exact match such as line 3 & 4. Hope this clears up the issue. The columns in the csv are double quoted as shown, and the quotes around fifth column should be removed.

答:
```<code>awk 'BEGIN{FS=OFS=","} NR==FNR{a["\""$0"\""];next} ($5 in a){gsub(/^"|"$/,"",$5);print}' pattern.csv input.csv > final_out.csv
</code>```

Keep pattern.csv's contents in an array with enclosing each line in quotes. For each line in input.csv, if fifth column exists in the array, remove quotes around it and print the line.

Body:
I have a file which has the following patterns.

NO_MATCH
NO_MATCH||NO_MATCH
NO_MATCH||NO_MATCH||NO_MATCH
NO_MATCH||NO_MATCH||NO_MATCH||NO_MATCH

These should be matched exactly with the 5th column of the target csv. I have tried:

awk 'NR==FNR{a[$0]=$0; next;} NR>FNR{if($5==a[$0])print $0}' pattern.csv input.csv > final_out.csv

But the ||  in the patterns file result in bad matches. The 5th column in the target csv looks something like this:

"AAAA||AAAA"
"BBBB||BBBB"
"NO_MATCH"
"NO_MATCH||NO_MATCH||NO_MATCH"
"NO_MATCH||BBBB"

I need to extract the 3rd and 4th lines.
Edit: I need exact match such as line 3 & 4. Hope this clears up the issue. The columns in the csv are double quoted as shown, and the quotes around fifth column should be removed.

Body:
awk 'BEGIN{FS=OFS=","} NR==FNR{a["\""$0"\""];next} ($5 in a){gsub(/^"|"$/,"",$5);print}' pattern.csv input.csv > final_out.csv

Keep pattern.csv's contents in an array with enclosing each line in quotes. For each line in input.csv, if fifth column exists in the array, remove quotes around it and print the line.


问:
In Fragment getActivity() sometimes return null
Android Studio 3.4

```<code>public class SubscribesFragment extends Fragment {

    @Override
    protected void initLogic() {
        IntentFilter intentFilterRefusePaperInvoice = new IntentFilter(ExistSubscribeWidget.ACTION_REFUSE_PAPER_INVOICE);
        LocalBroadcastManager.getInstance(getActivity()).registerReceiver(mMessageReceiver,
                intentFilterRefusePaperInvoice);

        super.initLogic();
    }

    private BroadcastReceiver mMessageReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, final Intent intent) {
            String action = intent.getAction();
            if (action.equals(ExistSubscribeWidget.ACTION_REFUSE_PAPER_INVOICE)) {
                String providerGUID = intent.getStringExtra(ProviderWidget.EXTRA_PROVIDER_TAG);
                String notificationSubscribeOwnerKey = intent.getStringExtra(ExistSubscribeWidget.NOTIFICATION_SUBSCRIBE_OWNERkEY);
                showConfirmDialogRefusePaperInvoice(providerGUID, notificationSubscribeOwnerKey);
            }
        }
    };

    private void showConfirmDialogRefusePaperInvoice(final String providerGUID, final String notificationSubscribeOwnerKey) {
        Activity actitivty = getActivity(); // NULL
        AlertDialog.Builder builder = new AlertDialog.Builder(actitivty); // NPE
        builder.setTitle(R.string.refuse_paper_dialog_title);
        View customView = AndroidUtil.getLinearLayout(actitivty, R.layout.refuse_paper_dialog);
builder.setView(customView);

}
</code>```

But sometimes (not every time) in method showConfirmDialogRefusePaperInvoice the app crash with NPE:

```<code> FATAL EXCEPTION: main
 Process: com.myproject.app, PID: 19430
 java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.res.Resources$Theme android.content.Context.getTheme()' on a null object reference
    at android.app.AlertDialog.resolveDialogTheme(AlertDialog.java:222)
    at android.app.AlertDialog$Builder.<init>(AlertDialog.java:452)
    at com.myproject.app.fragment.SubscribesFragment.showConfirmDialogRefusePaperInvoice(SubscribesFragment.java:67)
    at com.myproject.app.fragment.SubscribesFragment.access$000(SubscribesFragment.java:38)
    at com.myproject.app.fragment.SubscribesFragment$1.onReceive(SubscribesFragment.java:60)
    at android.support.v4.content.LocalBroadcastManager.executePendingBroadcasts(LocalBroadcastManager.java:313)
    at android.support.v4.content.LocalBroadcastManager$1.handleMessage(LocalBroadcastManager.java:121)
    at android.os.Handler.dispatchMessage(Handler.java:102)
    at android.os.Looper.loop(Looper.java:148)
    at android.app.ActivityThread.main(ActivityThread.java:5417)
    at java.lang.reflect.Method.invoke(Native Method)
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
</code>```

答: If you call showConfirmDialogRefusePaperInvoice before activity is created then yes your fragment will get null when calling getActivity(). You can make sure that activity is created in fragment by fragment callback onActivityCreated

Body:
Android Studio 3.4

public class SubscribesFragment extends Fragment {

    @Override
    protected void initLogic() {
        IntentFilter intentFilterRefusePaperInvoice = new IntentFilter(ExistSubscribeWidget.ACTION_REFUSE_PAPER_INVOICE);
        LocalBroadcastManager.getInstance(getActivity()).registerReceiver(mMessageReceiver,
                intentFilterRefusePaperInvoice);

        super.initLogic();
    }

    private BroadcastReceiver mMessageReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, final Intent intent) {
            String action = intent.getAction();
            if (action.equals(ExistSubscribeWidget.ACTION_REFUSE_PAPER_INVOICE)) {
                String providerGUID = intent.getStringExtra(ProviderWidget.EXTRA_PROVIDER_TAG);
                String notificationSubscribeOwnerKey = intent.getStringExtra(ExistSubscribeWidget.NOTIFICATION_SUBSCRIBE_OWNERkEY);
                showConfirmDialogRefusePaperInvoice(providerGUID, notificationSubscribeOwnerKey);
            }
        }
    };

    private void showConfirmDialogRefusePaperInvoice(final String providerGUID, final String notificationSubscribeOwnerKey) {
        Activity actitivty = getActivity(); // NULL
        AlertDialog.Builder builder = new AlertDialog.Builder(actitivty); // NPE
        builder.setTitle(R.string.refuse_paper_dialog_title);
        View customView = AndroidUtil.getLinearLayout(actitivty, R.layout.refuse_paper_dialog);
builder.setView(customView);

}

But sometimes (not every time) in method showConfirmDialogRefusePaperInvoice the app crash with NPE:

 FATAL EXCEPTION: main
 Process: com.myproject.app, PID: 19430
 java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.res.Resources$Theme android.content.Context.getTheme()' on a null object reference
    at android.app.AlertDialog.resolveDialogTheme(AlertDialog.java:222)
    at android.app.AlertDialog$Builder.<init>(AlertDialog.java:452)
    at com.myproject.app.fragment.SubscribesFragment.showConfirmDialogRefusePaperInvoice(SubscribesFragment.java:67)
    at com.myproject.app.fragment.SubscribesFragment.access$000(SubscribesFragment.java:38)
    at com.myproject.app.fragment.SubscribesFragment$1.onReceive(SubscribesFragment.java:60)
    at android.support.v4.content.LocalBroadcastManager.executePendingBroadcasts(LocalBroadcastManager.java:313)
    at android.support.v4.content.LocalBroadcastManager$1.handleMessage(LocalBroadcastManager.java:121)
    at android.os.Handler.dispatchMessage(Handler.java:102)
    at android.os.Looper.loop(Looper.java:148)
    at android.app.ActivityThread.main(ActivityThread.java:5417)
    at java.lang.reflect.Method.invoke(Native Method)
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)


问:
How to make a OkHttp call within a Android.WorkManager?
I have several OkHttp requests that I need to send and even if there is no internet for some time, in the end they have to be delivered. It seems that WorkManager is a good API that can handle this.
But how to integrate OkHttp requests and WorkManager?
And  (second) be able to get notifications?</p>

答:
I have recently used same as you want:

You can do that like:

```<code>@NonNull
@Override
public Result doWork() {

    // DO OKHTTP REQUEST HERE........

    return Result.success();
}
</code>```

Note : Do not use any UI thread here like progress bar.

Body:
I have recently used same as you want:

You can do that like:

@NonNull
@Override
public Result doWork() {

    // DO OKHTTP REQUEST HERE........

    return Result.success();
}

Note : Do not use any UI thread here like progress bar.


问:
How to use BackgroundWorker with main thread functions?
Ok, I was trying not to be too specific but, here it goes:

```<code>    public void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
    {

        DateTime startTeste = DateTime.Now;
        DateTime finishTeste = startTeste.AddSeconds(mTeste + sTeste);

        while(DateTime.Now <= finishTeste) //enquanto o teste nao terminar
        {
            if(backgroundWorker1.CancellationPending)
            {
                e.Cancel = true;
                break;
            }

            backgroundWorker1.ReportProgress((int)(DateTime.Now - startTeste).TotalSeconds + 30);

            //AtualizarVal();
            Teste();

            System.Threading.Thread.Sleep(30000);
        }
    }

 private void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e)
    {
        tProgress.Value = e.ProgressPercentage; //atualiza as barras de progresso
    }

    private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
    {
        if(e.Cancelled)     //Caso seja cancelado o BGW
        {
            MessageBox.Show("Thread got canceled");
        }

        if(nTeste == nTestes)
        {
            buttonSTART.Enabled = true;
            timer1.Stop();
            MessageBox.Show("Job done");
        }
    }
</code>```

The function Teste() is:

```<code>    public void Teste()
    {
        tbtatual.Text = "12";
    }
</code>```

The only thing I want to do, is to write to a textbox, every 30seconds, and I have to it in a thread, because I'm going to write in more textboxes and I'm going to send controls via RS-232, because of those controls and of a Timer I need to use the thread, so that when my program sends and receives the data via RS-232 doesn't mess up with my timers.

Maybe this is too much code, but I think this way I'll make you understand what happens.

答:
You can't access UI components(Text boxes,MessegeBoxes etc) from other threads .These components controlled from UI Thread Example;</p>

```<code>public void BackgroundWorker1DoWork(object sender, DoWorkEventArgs e)
{
 //After some Work Done

     Application.Current.Dispatcher.Invoke(DispatcherPriority.Background, new
       ThreadStart(delegate
       {
             Teste();
       }));
}
</code>```

Body:
Ok, I was trying not to be too specific but, here it goes:

    public void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
    {

        DateTime startTeste = DateTime.Now;
        DateTime finishTeste = startTeste.AddSeconds(mTeste + sTeste);

        while(DateTime.Now <= finishTeste) //enquanto o teste nao terminar
        {
            if(backgroundWorker1.CancellationPending)
            {
                e.Cancel = true;
                break;
            }

            backgroundWorker1.ReportProgress((int)(DateTime.Now - startTeste).TotalSeconds + 30);

            //AtualizarVal();
            Teste();

            System.Threading.Thread.Sleep(30000);
        }
    }

 private void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e)
    {
        tProgress.Value = e.ProgressPercentage; //atualiza as barras de progresso
    }

    private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
    {
        if(e.Cancelled)     //Caso seja cancelado o BGW
        {
            MessageBox.Show("Thread got canceled");
        }

        if(nTeste == nTestes)
        {
            buttonSTART.Enabled = true;
            timer1.Stop();
            MessageBox.Show("Job done");
        }
    }

The function Teste() is:

    public void Teste()
    {
        tbtatual.Text = "12";
    }

The only thing I want to do, is to write to a textbox, every 30seconds, and I have to it in a thread, because I'm going to write in more textboxes and I'm going to send controls via RS-232, because of those controls and of a Timer I need to use the thread, so that when my program sends and receives the data via RS-232 doesn't mess up with my timers.

Maybe this is too much code, but I think this way I'll make you understand what happens.

Body:
You can't access UI components(Text boxes,MessegeBoxes etc) from other threads .These components controlled from UI Thread Example;

public void BackgroundWorker1DoWork(object sender, DoWorkEventArgs e)
{
 //After some Work Done

     Application.Current.Dispatcher.Invoke(DispatcherPriority.Background, new
       ThreadStart(delegate
       {
             Teste();
       }));
}


问:
Only apply cell calculation if cell next to it was edited
Instead of having a formula auto calculate through the whole column, I want the cell in a column only to apply the formula once the date was set in column A2. Its a count up feature. Right now the calculation takes the current time n C2 minus the time stamp in cell B2 that gives me a count up feature.

The formula that I am using "=C2-B2" which I want to apply to the whole column applies it automatically even tho there is no data in cell A2.

I want the count up only to start once they filled in the date in column A2 as this triggers my Script for time stamp. Right now its just got count ups on the whole column cells with the source cells arent even filled in .

答:
If I understand you correctly...

Add the following directly after e.source.getSheetByName('validated').getRange(row, 2).setValue(date); in your onedit.

```<code>var countdownrange = e.source.getSheetByName('validated').getRange(row, 4);
countdownrange.setFormulaR1C1("=R[0]C[-1]-R[0]C[-2]");
var nowrange = e.source.getSheetByName('validated').getRange(row, 3);
nowrange.setFormula("=NOW()");
</code>```

Body:
If I understand you correctly...

Add the following directly after e.source.getSheetByName('validated').getRange(row, 2).setValue(date); in your onedit.

var countdownrange = e.source.getSheetByName('validated').getRange(row, 4);
countdownrange.setFormulaR1C1("=R[0]C[-1]-R[0]C[-2]");
var nowrange = e.source.getSheetByName('validated').getRange(row, 3);
nowrange.setFormula("=NOW()");


问:
Singleton class in swift gives EXC_BAD_INSTRUCTION (code=EXC_I386_INVOP, subcode=0x0) error
I am writing a swift Network Manager library specifically to cater to my own API needs. This class is declared as final and there is a static let variable to define the singleton design pattern for this class. All the other functions in this class are class functions.

Unfortunately whenever this singleton class is called and the singleton design pattern method , i.e. static let sharedInstance : NetworkManager = NetworkManager.init() is called, it gives me

stop reason = EXC_BAD_INSTRUCTION (code=EXC_I386_INVOP, subcode=0x0)
  error.

I thought that there could be an issue with the threads, but no. I just invoked the NetworkManager.shared simply in a UIViewController's viewDidLoad and it gave me the same error.

I am providing the whole code for NetworkManager class herewith

```<code>final class NetworkManager {

    static let sharedInstance : NetworkManager = NetworkManager.init()

    private var urlConfig = URLSessionConfiguration.default
    private var urlSession = URLSession(configuration: sharedInstance.urlConfig)

    var basePath : String = "https://api.myjson.com/";

    private init() {

        print("This is getting called at all");
    }
    //MARK:- POST METHODS
    class func performPOST(urlString : String?, bodyParams : [String : AnyObject]? = nil, completionHandler : @escaping(Result<Data?,NetworkError>) -> Void){
        self.performJSON(urlString: urlString, bodyParams: bodyParams, method : .POST, completionHandler: completionHandler)
    }

    class func performPOST( url : URL?, bodyParams : [String : AnyObject]? = nil, headerParams : [String : Any]? = nil,completionHandler : @escaping(Result<Data?,NetworkError>) -> Void){
        self.performJSON(url: url, bodyParams: bodyParams, method : .POST, completionHandler: completionHandler)
    }

    class func performPOST( request : URLRequest?, completionHandler : @escaping(Result<Data?,NetworkError>) -> Void){
       self.performJSON(request: request, completionHandler: completionHandler)
    }

    //MARK:- JSON FUNCTIONS
    class func performJSON(urlString : String?, bodyParams : [String : AnyObject]? = nil, headerParams : [String : Any]? = nil,method : MethodType = .GET , completionHandler : @escaping(Result<Data?,NetworkError>) -> Void){

        guard let urlString = urlString, let compURL = URL.init(string: NetworkManager.sharedInstance.basePath + urlString) else {
            completionHandler(.failure(.badURL))
            return
        }

        var urlReq = URLRequest.init(url: compURL, cachePolicy: URLRequest.CachePolicy.reloadIgnoringCacheData, timeoutInterval: 30)

        do {
            try self.prepareTheURLRequest( request : &urlReq,
                                  bodyParams : bodyParams,
                                  headerParams : headerParams,
                                  method :method)
        }catch let error as NetworkError {
             completionHandler(.failure(error))
        }catch let error {
            completionHandler(.failure(NetworkError.unknownError(error)))
        }

        self.performJSON(request: urlReq, completionHandler: completionHandler)
    }

    class func performJSON( url : URL?, bodyParams : [String : AnyObject]? = nil, headerParams : [String : Any]? = nil,method : MethodType = .GET,  completionHandler : @escaping(Result<Data?,NetworkError>) -> Void){
    }

    //MARK:- FIRE_THE_REQUEST
    class func performJSON( request : URLRequest?, completionHandler : @escaping(Result<Data?,NetworkError>) -> Void){
        if let req = request {
            let _ = NetworkManager.sharedInstance.urlSession.dataTask(with: req) { (data, response, error) in
                if let er = error{
                    completionHandler(.failure(NetworkError.unknownError(er)))
                }else if let resp = response{
                    do {
                        try self.validateTheResponse(response: resp)
                        completionHandler(.success(data))
                    } catch let error {
                        completionHandler(.failure(NetworkError.unknownError(error)))
                    }
                }else{
                    completionHandler(.failure(NetworkError.noResponseReceived))
                }
            }
        }
    }

    //MARK:- VALIDATE_RESPONSE
    class func validateTheResponse(response : URLResponse) throws {

        if let httpResponse = response as? HTTPURLResponse {
            let statusCode = httpResponse.statusCode

            switch statusCode {

            case 200 ... 300 :
                break
            default:
                let newError = NSError(domain: "Improper Status Code Received", code: 42, userInfo: ["statusCode":statusCode] )
                throw newError
            }
        }
    }
}
</code>```

The error received is as follows

       (lldb) bt
  * thread #1, queue = 'com.apple.main-thread', stop reason = EXC_BAD_INSTRUCTION (code=EXC_I386_INVOP, subcode=0x0)
      frame #0: 0x000000010deab9d3 libdispatch.dylib_dispatch_once_wait + 101
      frame #1: 0x000000010bd00579 libswiftCore.dylibswift_once + 25   * frame #2: 0x000000010a7bfcd4 MVVMNetworkManager.sharedInstance.unsafeMutableAddressor at
  NetworkManager.swift:25:16
      frame #3: 0x000000010a7c010a MVVMNetworkManager.(self=0x0000600002756e20).init() at
  NetworkManager.swift:28:30
      frame #4: 0x000000010a7bfca0 MVVMNetworkManager.__allocating_init() at NetworkManager.swift:0
      frame #5: 0x000000010a7bfc4c MVVMglobalinit_33_100BB9A6FE18335AA78CDFBEA4A3C62B_func0 at
  NetworkManager.swift:25:65
      frame #6: 0x000000010deaadb5 libdispatch.dylib_dispatch_client_callout + 8
      frame #7: 0x000000010deac83d libdispatch.dylib_dispatch_once_callout + 66
      frame #8: 0x000000010bd00579 libswiftCore.dylibswift_once + 25
      frame #9: 0x000000010a7bfcd4 MVVMNetworkManager.sharedInstance.unsafeMutableAddressor at
  NetworkManager.swift:25:16
      frame #10: 0x000000010a7c06c3 MVVMstatic NetworkManager.performJSON(urlString="bins/9asku", bodyParams=nil,
  headerParams=nil, method=POST, completionHandler=0x000000010a7cc650
  MVVMpartial apply forwarder for closure #1
  (Swift.Result, MVVM.NetworkError>) ->
  () in MVVM.ListRequest.fetchAllLists(completionHandler:
  (Swift.Result>,
  MVVM.NetworkError>) -> ()) -> () at ,
  self=0x000000010a7d89e8) at NetworkManager.swift:52:88
      frame #11: 0x000000010a7c03fa MVVMstatic NetworkManager.performPOST(urlString="bins/9asku", bodyParams=nil,
  completionHandler=0x000000010a7cc650 MVVMpartial apply forwarder for
  closure #1 (Swift.Result,
  MVVM.NetworkError>) -> () in
  MVVM.ListRequest.fetchAllLists(completionHandler:
  (Swift.Result>,
  MVVM.NetworkError>) -> ()) -> () at ,
  self=0x000000010a7d89e8) at NetworkManager.swift:38:14
      frame #12: 0x000000010a7cc547 MVVMListRequest.fetchAllLists(completionHandler=0x000000010a7cf740
  MVVMclosure #1 (Swift.Result>,
  MVVM.NetworkError>) -> () in MVVM.ListPresenter.fetchAndShowList() ->
  () at ListPresenter.swift:29, self=0x0000600002b1c3a0) at
  ListRequest.swift:15:24
      frame #13: 0x000000010a7cf726 MVVMListPresenter.fetchAndShowList(self=0x0000600002779140) at
  ListPresenter.swift:29:17
      frame #14: 0x000000010a7c5551 MVVMListVC.viewDidAppear(animated=false, self=0x00007ff125e04540) at
  ListVC.swift:33:25
      frame #15: 0x000000010a7c55d3 MVVM@objc ListVC.viewDidAppear(_:) at <compiler-generated>:0
      frame #16: 0x000000010edb2536 UIKitCore-[UIViewController _setViewAppearState:isAnimating:] + 942
      frame #17: 0x000000010edb521c UIKitCore__64-[UIViewController viewDidMoveToWindow:shouldAppearOrDisappear:]_block_invoke + 42
      frame #18: 0x000000010edb35ab UIKitCore-[UIViewController _executeAfterAppearanceBlock] + 75
      frame #19: 0x000000010f3b9e05 UIKitCore_runAfterCACommitDeferredBlocks + 634
      frame #20: 0x000000010f3a9199 UIKitCore_cleanUpAfterCAFlushAndRunDeferredBlocks + 358
      frame #21: 0x000000010f3c7cd9 UIKitCore__34-[UIApplication _firstCommitBlock]_block_invoke_2 + 142
      frame #22: 0x000000010ca7eaec CoreFoundationCFRUNLOOP_IS_CALLING_OUT_TO_A_BLOCK + 12
      frame #23: 0x000000010ca7e2b0 CoreFoundation__CFRunLoopDoBlocks + 336
      frame #24: 0x000000010ca78b34 CoreFoundation__CFRunLoopRun + 1252
      frame #25: 0x000000010ca78302 CoreFoundationCFRunLoopRunSpecific + 626
      frame #26: 0x0000000114b302fe GraphicsServicesGSEventRunModal + 65
      frame #27: 0x000000010f3aeba2 UIKitCoreUIApplicationMain + 140
      frame #28: 0x000000010a7caceb MVVMmain at AppDelegate.swift:12:7
      frame #29: 0x000000010df1f541 libdyld.dylib`start + 1 (lldb)

答:
The problem in your code is in this line

```<code>private var urlSession = URLSession(configuration: sharedInstance.urlConfig)
</code>```

As when you create an instance of class then it's variables also get allocated in memory. But here you are trying to access a variable before it's initialisation complete.

To fix crash you can change your variable urlSession to something like this:

```<code>private var urlSession = URLSession(configuration: URLSessionConfiguration.default)
</code>```

Body:
I am writing a swift Network Manager library specifically to cater to my own API needs. This class is declared as final and there is a static let variable to define the singleton design pattern for this class. All the other functions in this class are class functions.

Unfortunately whenever this singleton class is called and the singleton design pattern method , i.e. static let sharedInstance : NetworkManager = NetworkManager.init() is called, it gives me

stop reason = EXC_BAD_INSTRUCTION (code=EXC_I386_INVOP, subcode=0x0)
  error.

I thought that there could be an issue with the threads, but no. I just invoked the NetworkManager.shared simply in a UIViewController's viewDidLoad and it gave me the same error.

I am providing the whole code for NetworkManager class herewith

final class NetworkManager {

    static let sharedInstance : NetworkManager = NetworkManager.init()

    private var urlConfig = URLSessionConfiguration.default
    private var urlSession = URLSession(configuration: sharedInstance.urlConfig)

    var basePath : String = "https://api.myjson.com/";

    private init() {

        print("This is getting called at all");
    }
    //MARK:- POST METHODS
    class func performPOST(urlString : String?, bodyParams : [String : AnyObject]? = nil, completionHandler : @escaping(Result<Data?,NetworkError>) -> Void){
        self.performJSON(urlString: urlString, bodyParams: bodyParams, method : .POST, completionHandler: completionHandler)
    }

    class func performPOST( url : URL?, bodyParams : [String : AnyObject]? = nil, headerParams : [String : Any]? = nil,completionHandler : @escaping(Result<Data?,NetworkError>) -> Void){
        self.performJSON(url: url, bodyParams: bodyParams, method : .POST, completionHandler: completionHandler)
    }

    class func performPOST( request : URLRequest?, completionHandler : @escaping(Result<Data?,NetworkError>) -> Void){
       self.performJSON(request: request, completionHandler: completionHandler)
    }

    //MARK:- JSON FUNCTIONS
    class func performJSON(urlString : String?, bodyParams : [String : AnyObject]? = nil, headerParams : [String : Any]? = nil,method : MethodType = .GET , completionHandler : @escaping(Result<Data?,NetworkError>) -> Void){

        guard let urlString = urlString, let compURL = URL.init(string: NetworkManager.sharedInstance.basePath + urlString) else {
            completionHandler(.failure(.badURL))
            return
        }

        var urlReq = URLRequest.init(url: compURL, cachePolicy: URLRequest.CachePolicy.reloadIgnoringCacheData, timeoutInterval: 30)

        do {
            try self.prepareTheURLRequest( request : &urlReq,
                                  bodyParams : bodyParams,
                                  headerParams : headerParams,
                                  method :method)
        }catch let error as NetworkError {
             completionHandler(.failure(error))
        }catch let error {
            completionHandler(.failure(NetworkError.unknownError(error)))
        }

        self.performJSON(request: urlReq, completionHandler: completionHandler)
    }

    class func performJSON( url : URL?, bodyParams : [String : AnyObject]? = nil, headerParams : [String : Any]? = nil,method : MethodType = .GET,  completionHandler : @escaping(Result<Data?,NetworkError>) -> Void){
    }

    //MARK:- FIRE_THE_REQUEST
    class func performJSON( request : URLRequest?, completionHandler : @escaping(Result<Data?,NetworkError>) -> Void){
        if let req = request {
            let _ = NetworkManager.sharedInstance.urlSession.dataTask(with: req) { (data, response, error) in
                if let er = error{
                    completionHandler(.failure(NetworkError.unknownError(er)))
                }else if let resp = response{
                    do {
                        try self.validateTheResponse(response: resp)
                        completionHandler(.success(data))
                    } catch let error {
                        completionHandler(.failure(NetworkError.unknownError(error)))
                    }
                }else{
                    completionHandler(.failure(NetworkError.noResponseReceived))
                }
            }
        }
    }

    //MARK:- VALIDATE_RESPONSE
    class func validateTheResponse(response : URLResponse) throws {

        if let httpResponse = response as? HTTPURLResponse {
            let statusCode = httpResponse.statusCode

            switch statusCode {

            case 200 ... 300 :
                break
            default:
                let newError = NSError(domain: "Improper Status Code Received", code: 42, userInfo: ["statusCode":statusCode] )
                throw newError
            }
        }
    }
}

The error received is as follows

       (lldb) bt
  * thread #1, queue = 'com.apple.main-thread', stop reason = EXC_BAD_INSTRUCTION (code=EXC_I386_INVOP, subcode=0x0)
      frame #0: 0x000000010deab9d3 libdispatch.dylib_dispatch_once_wait + 101
      frame #1: 0x000000010bd00579 libswiftCore.dylibswift_once + 25   * frame #2: 0x000000010a7bfcd4 MVVMNetworkManager.sharedInstance.unsafeMutableAddressor at
  NetworkManager.swift:25:16
      frame #3: 0x000000010a7c010a MVVMNetworkManager.(self=0x0000600002756e20).init() at
  NetworkManager.swift:28:30
      frame #4: 0x000000010a7bfca0 MVVMNetworkManager.__allocating_init() at NetworkManager.swift:0
      frame #5: 0x000000010a7bfc4c MVVMglobalinit_33_100BB9A6FE18335AA78CDFBEA4A3C62B_func0 at
  NetworkManager.swift:25:65
      frame #6: 0x000000010deaadb5 libdispatch.dylib_dispatch_client_callout + 8
      frame #7: 0x000000010deac83d libdispatch.dylib_dispatch_once_callout + 66
      frame #8: 0x000000010bd00579 libswiftCore.dylibswift_once + 25
      frame #9: 0x000000010a7bfcd4 MVVMNetworkManager.sharedInstance.unsafeMutableAddressor at
  NetworkManager.swift:25:16
      frame #10: 0x000000010a7c06c3 MVVMstatic NetworkManager.performJSON(urlString="bins/9asku", bodyParams=nil,
  headerParams=nil, method=POST, completionHandler=0x000000010a7cc650
  MVVMpartial apply forwarder for closure #1
  (Swift.Result, MVVM.NetworkError>) ->
  () in MVVM.ListRequest.fetchAllLists(completionHandler:
  (Swift.Result>,
  MVVM.NetworkError>) -> ()) -> () at ,
  self=0x000000010a7d89e8) at NetworkManager.swift:52:88
      frame #11: 0x000000010a7c03fa MVVMstatic NetworkManager.performPOST(urlString="bins/9asku", bodyParams=nil,
  completionHandler=0x000000010a7cc650 MVVMpartial apply forwarder for
  closure #1 (Swift.Result,
  MVVM.NetworkError>) -> () in
  MVVM.ListRequest.fetchAllLists(completionHandler:
  (Swift.Result>,
  MVVM.NetworkError>) -> ()) -> () at ,
  self=0x000000010a7d89e8) at NetworkManager.swift:38:14
      frame #12: 0x000000010a7cc547 MVVMListRequest.fetchAllLists(completionHandler=0x000000010a7cf740
  MVVMclosure #1 (Swift.Result>,
  MVVM.NetworkError>) -> () in MVVM.ListPresenter.fetchAndShowList() ->
  () at ListPresenter.swift:29, self=0x0000600002b1c3a0) at
  ListRequest.swift:15:24
      frame #13: 0x000000010a7cf726 MVVMListPresenter.fetchAndShowList(self=0x0000600002779140) at
  ListPresenter.swift:29:17
      frame #14: 0x000000010a7c5551 MVVMListVC.viewDidAppear(animated=false, self=0x00007ff125e04540) at
  ListVC.swift:33:25
      frame #15: 0x000000010a7c55d3 MVVM@objc ListVC.viewDidAppear(_:) at <compiler-generated>:0
      frame #16: 0x000000010edb2536 UIKitCore-[UIViewController _setViewAppearState:isAnimating:] + 942
      frame #17: 0x000000010edb521c UIKitCore__64-[UIViewController viewDidMoveToWindow:shouldAppearOrDisappear:]_block_invoke + 42
      frame #18: 0x000000010edb35ab UIKitCore-[UIViewController _executeAfterAppearanceBlock] + 75
      frame #19: 0x000000010f3b9e05 UIKitCore_runAfterCACommitDeferredBlocks + 634
      frame #20: 0x000000010f3a9199 UIKitCore_cleanUpAfterCAFlushAndRunDeferredBlocks + 358
      frame #21: 0x000000010f3c7cd9 UIKitCore__34-[UIApplication _firstCommitBlock]_block_invoke_2 + 142
      frame #22: 0x000000010ca7eaec CoreFoundationCFRUNLOOP_IS_CALLING_OUT_TO_A_BLOCK + 12
      frame #23: 0x000000010ca7e2b0 CoreFoundation__CFRunLoopDoBlocks + 336
      frame #24: 0x000000010ca78b34 CoreFoundation__CFRunLoopRun + 1252
      frame #25: 0x000000010ca78302 CoreFoundationCFRunLoopRunSpecific + 626
      frame #26: 0x0000000114b302fe GraphicsServicesGSEventRunModal + 65
      frame #27: 0x000000010f3aeba2 UIKitCoreUIApplicationMain + 140
      frame #28: 0x000000010a7caceb MVVMmain at AppDelegate.swift:12:7
      frame #29: 0x000000010df1f541 libdyld.dylib`start + 1 (lldb)

Body:
The problem in your code is in this line

private var urlSession = URLSession(configuration: sharedInstance.urlConfig)

As when you create an instance of class then it's variables also get allocated in memory. But here you are trying to access a variable before it's initialisation complete.

To fix crash you can change your variable urlSession to something like this:

private var urlSession = URLSession(configuration: URLSessionConfiguration.default)


问:
Exploits in use of Externally-Controlled Format String
first, please look thought this website (https://cwe.mitre.org/data/definitions/134.html). They are some code is having vulnerability. I not really understand where is the vulnerability code, them talking about.

It has 3 code snippets with vulnerability such as PrintWrapper, Snprintf and %1$d, present on this website.

答:
@CassieJade you need to look at the documentation of these functions online.
printf, snpritf are pretty common functions. And by the way, this platform is not for school assignments. You are most welcome if you have tried something and want to follow from there.

http://www.cplusplus.com/reference/cstdio/printf/

http://www.cplusplus.com/reference/cstdio/snprintf/

The following explains beautifully about your concern of $.
(GCC) Dollar sign in printf format string

Notation %2$d means the same as %d (output signed integer), except it formats the parameter with given 1-based number (in your case it's a second parameter, b).

```<code>int a = 3, b = 2;

printf("%2$d %1$d", a, b);
</code>```

Here you would expect 3 2 to be printed, but it will print 2 3, because the parameter a becomes param#1, and b becomes param#2, and %2$d is printed first so 2 is printed first followed by %1$d which is 3

You may want to look at man page of printf, its a bit complex for newbies but its the final source of truth.

The following is your print wrapper.

```<code>char buf[5012];
memcpy(buf, argv[1], 5012);
printWrapper(argv[1]);
return (0);
</code>```

Your website says: When an attacker can modify an
  externally-controlled format string, this can lead to buffer
  overflows, denial of service, or data representation problems.

Now, if this argv1 can be provided by someone who is not trusted, he can provide any junk argument which will go to printf. The goal of your task is to not to feed on print() with any string that is externally controlled.
e.g. argv1 can be very huge string (max allowable).
Or for example I am the one invoking your program and I passed argv1 as "%d Hello World", your printWrapper will end up printing some junk like "-446798072 Hello World", because no integer is passed as argument in printf(argv1).

Also memcpy is reading fixed number of bytes from origin argv1 which can have shorter length string, in this case it will be an invalid read (read past bound).

snprintf(buf,128,argv[1]);

exploit here is very clear, the argv1 can be changed with containment of several specifiers like %n which can write n number of bytes to your buf rather than intended write. By using %X in argc1 hacker can gain address of a variable on stack which can be exploited further. All this is vulnerable because an external untrusted source is creating the format specifier string that is used by your printf or snprintf, sprintf functions.
For example suppose hacker gave "%200d" in the argv1. sprintf(buf, 128, argv[1]);
will land up printing 200 bytes and then a junk integer, which might not be intended at all, since its snprintf which is a bounded function it will allow only 128 bytes to be written which will be empty.

I hope it is clear now.

Body:
@CassieJade you need to look at the documentation of these functions online.
printf, snpritf are pretty common functions. And by the way, this platform is not for school assignments. You are most welcome if you have tried something and want to follow from there.

http://www.cplusplus.com/reference/cstdio/printf/

http://www.cplusplus.com/reference/cstdio/snprintf/

The following explains beautifully about your concern of $.
(GCC) Dollar sign in printf format string

Notation %2$d means the same as %d (output signed integer), except it formats the parameter with given 1-based number (in your case it's a second parameter, b).

int a = 3, b = 2;

printf("%2$d %1$d", a, b);

Here you would expect 3 2 to be printed, but it will print 2 3, because the parameter a becomes param#1, and b becomes param#2, and %2$d is printed first so 2 is printed first followed by %1$d which is 3

You may want to look at man page of printf, its a bit complex for newbies but its the final source of truth.

The following is your print wrapper.

char buf[5012];
memcpy(buf, argv[1], 5012);
printWrapper(argv[1]);
return (0);

Your website says: When an attacker can modify an
  externally-controlled format string, this can lead to buffer
  overflows, denial of service, or data representation problems.

Now, if this argv1 can be provided by someone who is not trusted, he can provide any junk argument which will go to printf. The goal of your task is to not to feed on print() with any string that is externally controlled.
e.g. argv1 can be very huge string (max allowable).
Or for example I am the one invoking your program and I passed argv1 as "%d Hello World", your printWrapper will end up printing some junk like "-446798072 Hello World", because no integer is passed as argument in printf(argv1).

Also memcpy is reading fixed number of bytes from origin argv1 which can have shorter length string, in this case it will be an invalid read (read past bound).

snprintf(buf,128,argv[1]);

exploit here is very clear, the argv1 can be changed with containment of several specifiers like %n which can write n number of bytes to your buf rather than intended write. By using %X in argc1 hacker can gain address of a variable on stack which can be exploited further. All this is vulnerable because an external untrusted source is creating the format specifier string that is used by your printf or snprintf, sprintf functions.
For example suppose hacker gave "%200d" in the argv1. sprintf(buf, 128, argv[1]);
will land up printing 200 bytes and then a junk integer, which might not be intended at all, since its snprintf which is a bounded function it will allow only 128 bytes to be written which will be empty.

I hope it is clear now.


问:
PassportJS deserializeUser never called
I've got Passport setup to authenticate users stored in mongodb. Seems to work fine: authentication succeeds/fails appropriately and session variables get set. However, getting Passport to check for a session is failing. Something seems to be quite wrong in that the console.log statements I've added to the deserializeUser callback never see the light of day. I assume my problem is related to deserializeUser never being called. Anyone able to diagnose my misstep?

```<code>// Passport configuration
passport.serializeUser(function(user, cb){ cb(null, user.id) });
passport.deserializeUser(function(uid, cb){
  console.log("Trying to deserialize user: "+uid);
  User.findById(uid, function(err, user){
    cb(err, user);
  });
});
// auth strategy function
passport.use(new LocalStrategy({usernameField: 'email'},
  function(email, pass, done){
    User.findOne({email: email}, function (err, user) {
      if (err)
        return done(err);
      if (!user)
        return done(null, false, {message: "Couldn't find user"});
      var crypted = bcrypt.hashSync(pass, user.salt);
      if(user.hashpass != crypted)
        return done(null, false, {message: "Bad password"});
      return done(null, user);
    });
  }
));

passport.CreateSession =  function (req, res, next) {
  passport.authenticate('local', function(err, user, info){
    if(err || !user)
      return res.json({status: "Failure: "+err});
    req.logIn(user, function (err){
      if(err)
        return res.json({status: "Failure: "+err});
      return res.json({status: "Authenticated"});
    });
  })(req, res, next);
};
</code>```

with the following in app.js:

```<code>app.post('/session', passport.CreateSession); // restify better
app.del('/session', passport.DestroySession);
app.get('/images', passport.CheckSession, routes.images);
</code>```

答:
In my case it was because I had this code:

```<code>app.get("/auth/google/callback",
    passport.authenticate("google", {
        failureRedirect: "/admin/login/?error",
    }),
    (req, res) => {
        return res.redirect("/admin/");
    },
);
</code>```

Apparently in this case req.login() will not be called (which calls deserialize). I changed it to this and it worked:

```<code>app.get("/auth/google/callback",
    passport.authenticate("google", {
        successRedirect: "/admin/",
        failureRedirect: "/admin/login/?error",
    })
);
</code>```

Title: PassportJS deserializeUser never called

Body:
I've got Passport setup to authenticate users stored in mongodb. Seems to work fine: authentication succeeds/fails appropriately and session variables get set. However, getting Passport to check for a session is failing. Something seems to be quite wrong in that the console.log statements I've added to the deserializeUser callback never see the light of day. I assume my problem is related to deserializeUser never being called. Anyone able to diagnose my misstep?

// Passport configuration
passport.serializeUser(function(user, cb){ cb(null, user.id) });
passport.deserializeUser(function(uid, cb){
  console.log("Trying to deserialize user: "+uid);
  User.findById(uid, function(err, user){
    cb(err, user);
  });
});
// auth strategy function
passport.use(new LocalStrategy({usernameField: 'email'},
  function(email, pass, done){
    User.findOne({email: email}, function (err, user) {
      if (err)
        return done(err);
      if (!user)
        return done(null, false, {message: "Couldn't find user"});
      var crypted = bcrypt.hashSync(pass, user.salt);
      if(user.hashpass != crypted)
        return done(null, false, {message: "Bad password"});
      return done(null, user);
    });
  }
));

passport.CreateSession =  function (req, res, next) {
  passport.authenticate('local', function(err, user, info){
    if(err || !user)
      return res.json({status: "Failure: "+err});
    req.logIn(user, function (err){
      if(err)
        return res.json({status: "Failure: "+err});
      return res.json({status: "Authenticated"});
    });
  })(req, res, next);
};

with the following in app.js:

app.post('/session', passport.CreateSession); // restify better
app.del('/session', passport.DestroySession);
app.get('/images', passport.CheckSession, routes.images);

Body:
In my case it was because I had this code:

app.get("/auth/google/callback",
    passport.authenticate("google", {
        failureRedirect: "/admin/login/?error",
    }),
    (req, res) => {
        return res.redirect("/admin/");
    },
);

Apparently in this case req.login() will not be called (which calls deserialize). I changed it to this and it worked:

app.get("/auth/google/callback",
    passport.authenticate("google", {
        successRedirect: "/admin/",
        failureRedirect: "/admin/login/?error",
    })
);


问:
How to go to next Activity in Android
I have three views main1.xml, main2.xml , main3.xml.  In main.xml I'm putting three buttons. When the user clicks on first button I want it to show main1.xml, if second button then main2.xml etc.. I am done with the main.xml files.

How to do I change the view?

答:
use Intent in startActivity
.</p>

```<code>startActivity(new Intent(FirstActivity.this, secondActivity.class);
</code>```

Title: How to go to next Activity in Android

Body:
use Intent in startActivity
.

startActivity(new Intent(FirstActivity.this, secondActivity.class);


问:
How do I fix a problem with a function that is supposed to only move 0's to the end of the list, but moves False values as well?
I'm writing a function to move 0's to the end of a list, but when a False value is in the list, it converts it to 0 and moves it to the end as well.

I've tried many variations of if statements including:

if i == 0

if type(i) != bool and i == 0

if str(i) == '0'

```<code>def move_zeros(array):
    for i in array:
        if str(i) == '0' and str(i) != 'False':
            array.remove(i)
            array.append(0)
    return array
</code>```

In case of [0,1,None,2,False,1,0], I expected the function to return [1,None,2,False,1,0,0], but it returned [1,None,2,1,0,0,0] instead.

答:
There are a couple of gotchas here. One that you already understood is that there is not trivial way to discriminate between 0 and False. However, there are two other points:

Modifying an iterable (list, dict, etc.) that you are iterating over is dangerous. You should avoid doing that (unless you cannot do otherwise, e.g. with very large amounts of data that you cannot afford to copy in memory).

array.remove() does not do what you think it does. It removes from array the first element that is == to its argument, which may or may not be in the same position as the element in the iteration loop. That is responsible for transforming your False into a 0.

With that in mind, here's a working version:

```<code>def is_integer_zero(x):
    # The cleanest way I found, but you could argue for other options
    return x == 0 and not isinstance(x, bool)

def move_zeros(array):
    left_part = []
    right_part = []

    for i in array:
        if is_integer_zero(i):
            right_part.append(i)
        else:
            left_part.append(i)

    return left_part + right_part

l = [0, 1, None, 2, False, 1, 0]

print(move_zeros(l))  # [1, None, 2, False, 1, 0, 0]
</code>```

right_part consists entirely of zeroes, so you could simplify the code / improve performance quite a bit, but that version has the advantage that you can use other conditions to choose what to right-shift.

Body:
I'm writing a function to move 0's to the end of a list, but when a False value is in the list, it converts it to 0 and moves it to the end as well.

I've tried many variations of if statements including:

if i == 0

if type(i) != bool and i == 0

if str(i) == '0'

def move_zeros(array):
    for i in array:
        if str(i) == '0' and str(i) != 'False':
            array.remove(i)
            array.append(0)
    return array

In case of [0,1,None,2,False,1,0], I expected the function to return [1,None,2,False,1,0,0], but it returned [1,None,2,1,0,0,0] instead.

Body:
There are a couple of gotchas here. One that you already understood is that there is not trivial way to discriminate between 0 and False. However, there are two other points:

Modifying an iterable (list, dict, etc.) that you are iterating over is dangerous. You should avoid doing that (unless you cannot do otherwise, e.g. with very large amounts of data that you cannot afford to copy in memory).

array.remove() does not do what you think it does. It removes from array the first element that is == to its argument, which may or may not be in the same position as the element in the iteration loop. That is responsible for transforming your False into a 0.

With that in mind, here's a working version:

def is_integer_zero(x):
    # The cleanest way I found, but you could argue for other options
    return x == 0 and not isinstance(x, bool)

def move_zeros(array):
    left_part = []
    right_part = []

    for i in array:
        if is_integer_zero(i):
            right_part.append(i)
        else:
            left_part.append(i)

    return left_part + right_part

l = [0, 1, None, 2, False, 1, 0]

print(move_zeros(l))  # [1, None, 2, False, 1, 0, 0]

right_part consists entirely of zeroes, so you could simplify the code / improve performance quite a bit, but that version has the advantage that you can use other conditions to choose what to right-shift.


问:
Parsing through output
I would like to create a list of Virtual IP values. There could one or more Virtual addresses associated with an interface. (192.168.1.1,192.168.2.1,192.168.3.1)

```<code>[Switch] disp vrrp verbose interface Vlan-interface 1 | begin Virtual_IP
     Virtual IP     : 192.168.1.1
                      192.168.2.1
     Master IP      : 0.0.0.0
     VRName         :
     Follow Name

[Switch] disp vrrp verbose interface Vlan-interface2 | begin Virtual_IP
     Virtual IP     : 192.168.3.1
     Master IP      : 0.0.0.0
     VRName         :
     Follow Name    :
</code>```

What I tried is to first, split the output using .split function and string "Master" as delimiter. Then I would use the first list item and spitted again using ":" as delimiter. The 2nd list item now contains:

192.168.1.1
192.168.2.1

When I split it again now using \n as delimeter I receive three items
192.168.1.1 192.168.2.1 and empty tab or white space

I could perhaps iterate through this last list and "remove" empty spaces, new lines and tabs.

Is this good approach is there a better way how to get same results?

答:
I have solved this by using different approach. First capturing the whole command output without piping it on the device itself.

```<code>output = connection.send_command('display vrrp verbose interface vlan-interface1')
</code>```

Then using splitlines() with range, I extracted the "interesting" lines.

```<code>lines = output.splitlines()[10:-3]
</code>```

Then it was a matter splitting each line into words and checking the contents of them, there are were two possibilities for match, either there was only one 1 word:

```<code>words = line.split()

    if len(words) == 1:
        #If only single word is returned then it is a VIP
        print('Words is equal to 1')
        vip = words[0]
        vips.append(vip)
</code>```

or there more with 2nd item containing the string 'IP'

```<code> elif words[1] == 'IP':
    #If multiple words are returned the 2nd will contain
    #IP vs MAC string
    print('Words Item 2 is qual to IP')
    vip = words[-1]
    vips.append(vip)
</code>```

As a result vips list will contain all VIPs, one or more.

Title: Parsing through output

Body:
I would like to create a list of Virtual IP values. There could one or more Virtual addresses associated with an interface. (192.168.1.1,192.168.2.1,192.168.3.1)

[Switch] disp vrrp verbose interface Vlan-interface 1 | begin Virtual_IP
     Virtual IP     : 192.168.1.1
                      192.168.2.1
     Master IP      : 0.0.0.0
     VRName         :
     Follow Name

[Switch] disp vrrp verbose interface Vlan-interface2 | begin Virtual_IP
     Virtual IP     : 192.168.3.1
     Master IP      : 0.0.0.0
     VRName         :
     Follow Name    :

What I tried is to first, split the output using .split function and string "Master" as delimiter. Then I would use the first list item and spitted again using ":" as delimiter. The 2nd list item now contains:

192.168.1.1
192.168.2.1

When I split it again now using \n as delimeter I receive three items
192.168.1.1 192.168.2.1 and empty tab or white space

I could perhaps iterate through this last list and "remove" empty spaces, new lines and tabs.

Is this good approach is there a better way how to get same results?

Body:
I have solved this by using different approach. First capturing the whole command output without piping it on the device itself.

output = connection.send_command('display vrrp verbose interface vlan-interface1')

Then using splitlines() with range, I extracted the "interesting" lines.

lines = output.splitlines()[10:-3]

Then it was a matter splitting each line into words and checking the contents of them, there are were two possibilities for match, either there was only one 1 word:

words = line.split()

    if len(words) == 1:
        #If only single word is returned then it is a VIP
        print('Words is equal to 1')
        vip = words[0]
        vips.append(vip)

or there more with 2nd item containing the string 'IP'

 elif words[1] == 'IP':
    #If multiple words are returned the 2nd will contain
    #IP vs MAC string
    print('Words Item 2 is qual to IP')
    vip = words[-1]
    vips.append(vip)

As a result vips list will contain all VIPs, one or more.


问:
Using cmd through C# to zip and unzip files problems
I've been using C# to execute cmd commands centred around zipping and unzipping files through the system.diagnostics.process class but have been encountering some difficulties:
while trying to zip or unzip some of the folders, the process does not complete the zip command and then stops to react to further commands. sometimes when that happens the zip files will appear after I have completely closed the program.

Please assit me thank you...

答: Detailed control over external processes can become very tricky. Is SharpZipLib not an option for you?</p>


问:
How to make a for _ in _ work for a function
I'm using code that compares a json list to a list in my python file, however the for loop im using comes back with TypeError: 'function' object is not iterable. I'm not sure how to fix this

I've tried changing "for k2 in occupants:" to "for k2 in occupants():" and "for k2 in occupants[:]:" but each of these had problems

```<code>url = 'http://api.open-notify.org/astros.json'
response = urllib.request.urlopen(url)
result = json.loads(response.read())
people = result["people"]
people_with_exist_state = []

occupants = [
{
    'name': "Oleg Kononenko",
    'bio': 'Oleg Dmitriyevich Kononenko is a Russian cosmonaut. He has flown to the International Space Station four times as a flight engineer and commander. Kononenko accumulated over 533 days in orbit during his first three long duration flights to ISS.',
    'img': 'https://upload.wikimedia.org/wikipedia/commons/thumb/a/a0/Kononenko.jpg/220px-Kononenko.jpg',
},
{

    'name': "David Saint-Jacques",
    'bio': "David Saint-Jacques (born January 6, 1970) is a Canadian astronaut with the Canadian Space Agency (CSA). He is also an astrophysicist, engineer, and a physician.",
    'img': 'https://upload.wikimedia.org/wikipedia/commons/thumb/f/f8/David_Saint-Jacques_official_portrait.jpg/440px-David_Saint-Jacques_official_portrait.jpg',
}, #countinues for all occupants of the ISS

@app.route("/occupants")
def occupants():
 for k in people:
  is_here = 0
  for k2 in occupants:
    if k['name'] == k2['name']:
      is_here = 1
  if is_here == 0:
     #name does not exist
     k['exist'] = 0
  else:
     # name exist
     k['exist'] = 1
  people_with_exist_state.append(k)
 return render_template('occupants.html', people=people_with_exist_state)
</code>```

答: Assuming people and occupants are global variables in your code you cant name the function def occupants(): like you named the variable occupants

Body:
I'm using code that compares a json list to a list in my python file, however the for loop im using comes back with TypeError: 'function' object is not iterable. I'm not sure how to fix this

I've tried changing "for k2 in occupants:" to "for k2 in occupants():" and "for k2 in occupants[:]:" but each of these had problems

url = 'http://api.open-notify.org/astros.json'
response = urllib.request.urlopen(url)
result = json.loads(response.read())
people = result["people"]
people_with_exist_state = []

occupants = [
{
    'name': "Oleg Kononenko",
    'bio': 'Oleg Dmitriyevich Kononenko is a Russian cosmonaut. He has flown to the International Space Station four times as a flight engineer and commander. Kononenko accumulated over 533 days in orbit during his first three long duration flights to ISS.',
    'img': 'https://upload.wikimedia.org/wikipedia/commons/thumb/a/a0/Kononenko.jpg/220px-Kononenko.jpg',
},
{

    'name': "David Saint-Jacques",
    'bio': "David Saint-Jacques (born January 6, 1970) is a Canadian astronaut with the Canadian Space Agency (CSA). He is also an astrophysicist, engineer, and a physician.",
    'img': 'https://upload.wikimedia.org/wikipedia/commons/thumb/f/f8/David_Saint-Jacques_official_portrait.jpg/440px-David_Saint-Jacques_official_portrait.jpg',
}, #countinues for all occupants of the ISS

@app.route("/occupants")
def occupants():
 for k in people:
  is_here = 0
  for k2 in occupants:
    if k['name'] == k2['name']:
      is_here = 1
  if is_here == 0:
     #name does not exist
     k['exist'] = 0
  else:
     # name exist
     k['exist'] = 1
  people_with_exist_state.append(k)
 return render_template('occupants.html', people=people_with_exist_state)


问:
Python : Joining separated numeric characters in text but leave alphabetic texts
I've some sample strings like :

```<code>sample_lt1 = 'CANCEL Bitcoin kev 1 96 35 2 0 5 7 5 6'
sample_lt2 = 'CANCEL Bitcoln key 1 6 3 5 20 5 7 56 Cash 2 9 00'
sample_lt3 = 'CANCEL Bitcein key 0 1 5 0 0 4 4 1 6 Cash '
</code>```

I'm trying to join the numbers separated by spaces in the string but leave the chunk of alphabetic characters. The desired output for those sample inputs would be :

```<code>sample_out1 = 'CANCEL Bitcoin kev 19635205756'
sample_out2 = 'CANCEL Bitcoln key 1635205756 Cash 2900'
sample_out3 = 'CANCEL Bitcein key 015004416 Cash ' # Removal of last space is ok.
</code>```

Till now, I have done this :

```<code>def ReForm(lt):
    lts = lt.split()
    c = 0
    new = []
    temp = []
    while c<len(lts):
        if lts[c].isnumeric():
            temp.append(lts[c])
        else:
            if temp:
                s = ''.join(temp)
                new.append(s)
            new.append(lts[c])
        c += 1
    ret = ' '.join(new)
    return ret
</code>```

The output given by my code is :

```<code>CANCEL Bitcoin kev
CANCEL Bitcoln key 1635205756 Cash
CANCEL Bitcein key 015004416 Cash
</code>```

It fails to join the space separated numbers in the first and second case. What am I doing wrong?

答:
Using Regex. --> re.sub with Lookbehind & Lookahead

Ex:

```<code>import re

sample_lt1 = 'CANCEL Bitcoin kev 1 96 35 2 0 5 7 5 6'
sample_lt2 = 'CANCEL Bitcoln key 1 6 3 5 20 5 7 56 Cash 2 9 00'
sample_lt3 = 'CANCEL Bitcein key 0 1 5 0 0 4 4 1 6 Cash '

data = [sample_lt1, sample_lt2, sample_lt3]

for i in data:
    print(re.sub(r"(?<=\d) (?=\d)", "", i))
</code>```

Output:

```<code>CANCEL Bitcoin kev 19635205756
CANCEL Bitcoln key 1635205756 Cash 2900
CANCEL Bitcein key 015004416 Cash
</code>```

Body:
I've some sample strings like :

sample_lt1 = 'CANCEL Bitcoin kev 1 96 35 2 0 5 7 5 6'
sample_lt2 = 'CANCEL Bitcoln key 1 6 3 5 20 5 7 56 Cash 2 9 00'
sample_lt3 = 'CANCEL Bitcein key 0 1 5 0 0 4 4 1 6 Cash '

I'm trying to join the numbers separated by spaces in the string but leave the chunk of alphabetic characters. The desired output for those sample inputs would be :

sample_out1 = 'CANCEL Bitcoin kev 19635205756'
sample_out2 = 'CANCEL Bitcoln key 1635205756 Cash 2900'
sample_out3 = 'CANCEL Bitcein key 015004416 Cash ' # Removal of last space is ok.

Till now, I have done this :

def ReForm(lt):
    lts = lt.split()
    c = 0
    new = []
    temp = []
    while c<len(lts):
        if lts[c].isnumeric():
            temp.append(lts[c])
        else:
            if temp:
                s = ''.join(temp)
                new.append(s)
            new.append(lts[c])
        c += 1
    ret = ' '.join(new)
    return ret

The output given by my code is :

CANCEL Bitcoin kev
CANCEL Bitcoln key 1635205756 Cash
CANCEL Bitcein key 015004416 Cash

It fails to join the space separated numbers in the first and second case. What am I doing wrong?

Body:
Using Regex. --> re.sub with Lookbehind & Lookahead

Ex:

import re

sample_lt1 = 'CANCEL Bitcoin kev 1 96 35 2 0 5 7 5 6'
sample_lt2 = 'CANCEL Bitcoln key 1 6 3 5 20 5 7 56 Cash 2 9 00'
sample_lt3 = 'CANCEL Bitcein key 0 1 5 0 0 4 4 1 6 Cash '

data = [sample_lt1, sample_lt2, sample_lt3]

for i in data:
    print(re.sub(r"(?<=\d) (?=\d)", "", i))

Output:

CANCEL Bitcoin kev 19635205756
CANCEL Bitcoln key 1635205756 Cash 2900
CANCEL Bitcein key 015004416 Cash


问:
How to define a "Stroke style" parameter on the .inx file of an Inkscape extension?
I'm trying to create a new Inkscape extension for a project, and I would be great to be able to control the Stroke style and the colour in the extension tab, like this:

I have tried looking it up in the documentation but there's no description of how to set the stroke style.

I have been able to create a colour selection parameter like this:
<param name="colour" type="color" gui-text="Colour: ">0</param>

Is there any way to define a style selection in the same way?

答:
You can use an extension to modify the SVG contents programmatically (i.e. add a stroke to an object by modifying its representation in the Object tree).

Edit: Sorry, I misunderstood previously.

You can only use the available input types, which are listed here:
http://wiki.inkscape.org/wiki/index.php/INX_Parameters

So, use number input fields or multiselection to get what you still need beyond color.


问:
Creating a new scheduled task with Powershell v2 from XML
I need to use Powershell v2 to create a new scheduled task. what I tried so far is the task scheduler com object as follows:

```<code>$task_path = "c:\Temp\tasks\*.xml"
$task_user = "Administrator"
$task_pass = "mypass"

$sch = New-Object -ComObject("Schedule.Service")
$sch.connect("localhost")
$folder = $sch.GetFolder("\")

Get-Item $task_path | %{
    $task_name = $_.Name.Replace('.xml', '')
    $task_xml = Get-Content $_.FullName

    $task = $sch.NewTask($null)

    $task.XmlText = $task_xml

    $folder.RegisterTaskDefinition($task_name, $task, 6, $task_user, $task_pass, 1, $null)
}
</code>```

Now the problem i'm facing with this is that i don't want to specify any additional info in the method RegisterTaskDefinition other than the task name and the task object, because everything is in the XML file, even the username and password.

How to do this?

答:
try this:

```<code>schtasks.exe /Create /XML C:\task.xml /tn taskname
</code>```

Hope it helps!

Body:
I need to use Powershell v2 to create a new scheduled task. what I tried so far is the task scheduler com object as follows:

$task_path = "c:\Temp\tasks\*.xml"
$task_user = "Administrator"
$task_pass = "mypass"

$sch = New-Object -ComObject("Schedule.Service")
$sch.connect("localhost")
$folder = $sch.GetFolder("\")

Get-Item $task_path | %{
    $task_name = $_.Name.Replace('.xml', '')
    $task_xml = Get-Content $_.FullName

    $task = $sch.NewTask($null)

    $task.XmlText = $task_xml

    $folder.RegisterTaskDefinition($task_name, $task, 6, $task_user, $task_pass, 1, $null)
}

Now the problem i'm facing with this is that i don't want to specify any additional info in the method RegisterTaskDefinition other than the task name and the task object, because everything is in the XML file, even the username and password.

How to do this?

Body:
try this:

schtasks.exe /Create /XML C:\task.xml /tn taskname

Hope it helps!