答:
You can iterate over the first word letter by letter, if you find that the current letter is the one in your second string keep it and go on.</p>

```<code>def occurs_within(str1, str2):
    index = 0
    if len(str2) > len(str1):
        return False
    if str1 == str2:
        return True
    else:
        word = []
        index = 0
        for letter in str1:
            if index == len(str2):
                break
            if letter == str2[index]:
                index += 1
                word.append(letter)
        print(word)
        return ''.join(word) == str2
</code>```

Title: comparing two strings and their index seeing if all of string 2 is in string 1 with same order but different letter in between

Body:
You can iterate over the first word letter by letter, if you find that the current letter is the one in your second string keep it and go on.

def occurs_within(str1, str2):
    index = 0
    if len(str2) > len(str1):
        return False
    if str1 == str2:
        return True
    else:
        word = []
        index = 0
        for letter in str1:
            if index == len(str2):
                break
            if letter == str2[index]:
                index += 1
                word.append(letter)
        print(word)
        return ''.join(word) == str2


来源: stackexchange

问:
C - how to add a char to an array
I'm trying to figure out how to add a simple char to an array created with malloc.

```<code>#include <stdio.h>
#include <stdlib.h>

int main() {
    char *array = malloc(2);
    array[0] = "h";
    printf("%s", array);
    return 0;
}
</code>```

It gives the warning:

```<code> warning: assignment makes integer from pointer without a cast [-Wint-conversion]
array[0] = "h";
</code>```

and if I run the program anyway, it just prints out 3 random symbols.

答:
array[0] is a char&.

"h" is a const char[2].

You cannot assign an array of char to a char reference.

You probably wanted array[0] = 'h';, since 'h' is a const char.

ContentLicense: CC BY-SA 4.0

Title: C - how to add a char to an array

Body:
I'm trying to figure out how to add a simple char to an array created with malloc.

#include <stdio.h>
#include <stdlib.h>

int main() {
    char *array = malloc(2);
    array[0] = "h";
    printf("%s", array);
    return 0;
}

It gives the warning:

 warning: assignment makes integer from pointer without a cast [-Wint-conversion]
array[0] = "h";

and if I run the program anyway, it just prints out 3 random symbols.


问:
athena.getQueryExecution returns a status of RUNNING for 1 minute+, even though history says the job took 4 seconds
I'm writing a node app using typescript and the aws-sdk to call Athena.  Occasionally, the call to Athena will timeout after a minute of waiting for the Athena response.  The thing I don't understand is that if I go to the AWS console and look at the Athena History tab, it says my query took 4 seconds to succeed, yet in my code it runs for over a minute waiting for a response.  I'm hoping there's something I'm doing wrong in my code.

```<code>myFunct... {
    const athena = getAthena();

    const startQueryExecutionResponse: StartQueryExecutionOutput = await athena.startQueryExecution(params).promise();

    let status = "UNKNOWN";
    do {
        await sleep(1000);
        status = await getQueryStatus(athena, startQueryExecutionResponse);
    } while (status === "QUEUED" || status === "RUNNING");

    return await athena.getQueryResults(startQueryExecutionResponse as GetQueryResultsInput).promise();
};

const sleep = (ms: number) => {
    return new Promise(resolve => {
        setTimeout(resolve, ms)
    })
};

const getQueryStatus = async (athena: AWS.Athena, startQueryExecutionResponse: Athena.StartQueryExecutionOutput): Promise<QueryExecutionState> => {
    const result: GetQueryExecutionOutput = await athena.getQueryExecution(startQueryExecutionResponse as GetQueryResultsInput).promise();
    console.log(result);
    return result!.QueryExecution!.Status!.State || "Unknown"
};
</code>```

The code gets stuck in that while loop, and I can see from the console.log below, that the status is Status: { State: 'RUNNING', SubmissionDateTime: 2019-07-23T18:28:00.639Z }, over and over again.

If the AWS console says this query took 4 seconds to complete, why does the getQueryExecution response say it's still RUNNING for minutes?

答:
It is possible to get the QueryExecutionStatistics for your getQueryExecution function.

```<code>         "DataManifestLocation": "string",
         "DataScannedInBytes": number,
         "EngineExecutionTimeInMillis": number,
         "QueryPlanningTimeInMillis": number,
         "QueryQueueTimeInMillis": number,
         "ServiceProcessingTimeInMillis": number,
         "TotalExecutionTimeInMillis": number
</code>```

That might give you more insight, if you haven't already checked it. It could be the case that the 4 seconds is a subset of the total execution time. Perhaps your query is spending more time in planning as opposed to executing.

EngineExecutionTimeInMillis
  The number of milliseconds that the query took to execute.

Type: Long

Required: No

QueryPlanningTimeInMillis The number of milliseconds that Athena took
  to plan the query processing flow. This includes the time spent
  retrieving table partitions from the data source. Note that because
  the query engine performs the query planning, query planning time is a
  subset of engine processing time.

Type: Long

Required: No

source

Body:
I'm writing a node app using typescript and the aws-sdk to call Athena.  Occasionally, the call to Athena will timeout after a minute of waiting for the Athena response.  The thing I don't understand is that if I go to the AWS console and look at the Athena History tab, it says my query took 4 seconds to succeed, yet in my code it runs for over a minute waiting for a response.  I'm hoping there's something I'm doing wrong in my code.

myFunct... {
    const athena = getAthena();

    const startQueryExecutionResponse: StartQueryExecutionOutput = await athena.startQueryExecution(params).promise();

    let status = "UNKNOWN";
    do {
        await sleep(1000);
        status = await getQueryStatus(athena, startQueryExecutionResponse);
    } while (status === "QUEUED" || status === "RUNNING");

    return await athena.getQueryResults(startQueryExecutionResponse as GetQueryResultsInput).promise();
};

const sleep = (ms: number) => {
    return new Promise(resolve => {
        setTimeout(resolve, ms)
    })
};

const getQueryStatus = async (athena: AWS.Athena, startQueryExecutionResponse: Athena.StartQueryExecutionOutput): Promise<QueryExecutionState> => {
    const result: GetQueryExecutionOutput = await athena.getQueryExecution(startQueryExecutionResponse as GetQueryResultsInput).promise();
    console.log(result);
    return result!.QueryExecution!.Status!.State || "Unknown"
};

The code gets stuck in that while loop, and I can see from the console.log below, that the status is Status: { State: 'RUNNING', SubmissionDateTime: 2019-07-23T18:28:00.639Z }, over and over again.

If the AWS console says this query took 4 seconds to complete, why does the getQueryExecution response say it's still RUNNING for minutes?

Body:
It is possible to get the QueryExecutionStatistics for your getQueryExecution function.

         "DataManifestLocation": "string",
         "DataScannedInBytes": number,
         "EngineExecutionTimeInMillis": number,
         "QueryPlanningTimeInMillis": number,
         "QueryQueueTimeInMillis": number,
         "ServiceProcessingTimeInMillis": number,
         "TotalExecutionTimeInMillis": number

That might give you more insight, if you haven't already checked it. It could be the case that the 4 seconds is a subset of the total execution time. Perhaps your query is spending more time in planning as opposed to executing.

EngineExecutionTimeInMillis
  The number of milliseconds that the query took to execute.

Type: Long

Required: No

QueryPlanningTimeInMillis The number of milliseconds that Athena took
  to plan the query processing flow. This includes the time spent
  retrieving table partitions from the data source. Note that because
  the query engine performs the query planning, query planning time is a
  subset of engine processing time.

Type: Long

Required: No

source


问:
Laravel setup on HostGator shared plan
I'm trying to setup Laravel on a HostGator shared plan. I've followed these instructions:

http://laravel.io/forum/02-13-2014-how-to-install-laravel-on-a-hostgator-shared-server

I created and uploaded the .bashrc and .bash_profile files as instructed, then I run:

source ~/.bashrc

in the terminal, but then when I run php -v I get

No such file or directoryphp

I also tried uploading an htaccess file with AddHandler application/x-httpd-php55 .php to the root directory. When I run phpinfo() now, it shows php version 5.5.10, but php -v (before I run the source command) still shows version 5.2.17.

Any idea what I'm doing wrong?

答:
So there is one simple step that seems to get overlooked with most of the issues of setting up a subdomain to host a Laravel App using HostGator's Shared Hosting plan.

HostGator Shared Server Hosting Plan

Scenario:

Domain: https://yardpenalty.com is pointing to the home/username/public_html folder which has a WordPress installation.

Subdomain: https://games.yardpenalty.com is pointing to the home/username/games/public folder which has a Laravel App installation.

Problem:

We want the Laravel App to be accessed at the Subdomain's root level...

URI at https://games.yardpenalty.com

NOT at https://games.yardpenalty.com/public.

Solution:

Step 1:

Under our HostGator Shared Server Hosting Plan we can access the tools we need using cPanel.

Step 2:

In our cPanel we go-to Domains->Subdomains and we enter a name for our Subdomain (in this instance its called games).

Step 3:

Then we select a Domain from the dropdown list and in this scenario it is yardpenalty.com  which is pointing to my public_html folder.

Step 4:

Finally, under the Document Root / (a.k.a. home/user) we point it to the /games/public folder!

It should look something like the second listing from your cPanel:

ContentLicense: CC BY-SA 3.0

Title: Laravel setup on HostGator shared plan


问:
Rotating a 3d polygon into xy-plane while maintaining orientation
I have a polygon oriented any way and positioned anywhere in 3d space. I need to transform the polygon into the xy-plane so that I can perform various operations on it (in particular generating a grid of points across the bounding box of the polygon) in 2d rather than 3d, then transform it back.

The problem comes with the orientation of the transformed polygon. If I just wanted to rotate into the plane, I could take the angle between the polygon's normal and the xy-plane and rotate around an axis orthogonal to both (cross product). However, I require that the polygon's bounding box be oriented such that the bottom (lowest z-value) edge of the bounding box is coplanar with the xy-plane, both before and after transformation. In other words, the bounding box is resting flush on one side which is parallel to the ground. After transformation, this edge would be parallel to the x-axis. This is so that the grid of points I generate on the surface will always have rows running parallel to the ground, regardless of the polygon's orientation.

My approach is to perform two rotations; first rotate around the z-axis by the angle between the line formed by the intersection of the polygon's plane and the xy-plane, and the x-axis. This ensures that the bottom of the bounding box is not moving out of the xy-plane. Then, rotate again around the x-axis by the angle between the polygon's (new) normal and the xz-plane. Here are the steps:

Find the equation for the polygon's plane (from the normal).

Find the intersection of the polygon's plane and the xy-plane. This is a line in the xy-plane.

Find the angle between this line and the x-axis.

Rotate the polygon by this angle around the z-axis.

Determine new normal.

Find the angle between new normal and xy-plane's normal.

Rotate the polygon by this angle around the x-axis.

The polygon should now be in the xy-plane; generate bounding box using max/min x and y values, generate point grid, etc., then transform everything back to where it started.

I realize that two rotations should be combined to reduce the number of matrix multiplications, but this is the general algorithm.

I'm not a graphics expert; can anyone offer advice on this technique? Is there a better way? Does my approach sound correct? I am developing in Java and am looking at using the Transform3D class for the rotations.

答:
To handle 3D polygons it's common to simply ignore the Z coordinate (which effectively projects the plane directly into the XY plane) for your mappings, then just reinstate the Z coordinates later.

The only time this doesn't work is if the original polygon is perpendicular to the XY plane, since the resulting mapping degenerates to a line.


问:
How to make an element in a page the same visual width as another element exactly?
I'm trying to make it so that element A's width is equal to B's width so that they both visually appear to be the same.

I tried to do:

$('#A').css('max-width', $('#B').css('width'));
```

But this doesn't work the way I want it to, because B's width is 83%, so A's max width becomes 83%.

This doesn't make A visually the same as it just becomes 83% of its parent element, which makes it appear bigger on the page.

Is there a way to calculate the visual width of B so I can use that as A's max-width, using jQuery?

EDIT: I can't edit the document structure.

答:
via javascript only, offsetWidth should do :

The HTMLElement.offsetWidth read-only property returns the layout width of an element as an integer.

var myW = document.querySelector("#a").offsetWidth;
document.querySelector("#b").style.width=myW+"px";```
<pre class="snippet-code-css lang-css prettyprint-override"><code>p {float:left;clear:left;border:solid;margin:1px 1em;box-sizing:border-box;}</code>```

some content to give a width

:
```

Body:
I'm trying to make it so that element A's width is equal to B's width so that they both visually appear to be the same.

I tried to do:

$('#A').css('max-width', $('#B').css('width'));

But this doesn't work the way I want it to, because B's width is 83%, so A's max width becomes 83%.

This doesn't make A visually the same as it just becomes 83% of its parent element, which makes it appear bigger on the page.

Is there a way to calculate the visual width of B so I can use that as A's max-width, using jQuery?

EDIT: I can't edit the document structure.

Body:
via javascript only, offsetWidth should do :

The HTMLElement.offsetWidth read-only property returns the layout width of an element as an integer.

var myW = document.querySelector("#a").offsetWidth;
document.querySelector("#b").style.width=myW+"px";

p {float:left;clear:left;border:solid;margin:1px 1em;box-sizing:border-box;}

<p id="a">some content to give a width</p>
<p id="b">:</p>


问:
Why Does This Typescript Output "[Class] is not a constructor."?
I'm working in typescript 1.5 in visual studio. I have a main class called app.ts, and another called FizzBuzzManager.ts. I can't figure out what is wrong with this code, but it outputs the error, "TypeError: jim.FizzBuzzManager is not a constructor".

app.ts

```<code> namespace jim {
    class Greeter {
        element: HTMLElement;
        span: HTMLElement;
        timerToken: number;

        constructor() {
            window.console.log("constructing Greeter.");
            this.init();
        }

        private init() {
            window.console.log("Calling init.");
            var _fizzBuzzManager: any = new jim.FizzBuzzManager();
    }

}

    window.onload = () => {
        window.console.log("Hello")
        var greeter = new Greeter();

};
</code>```

FizzBuzzManager.ts

```<code>namespace jim {

export class FizzBuzzManager {

    constructor() {
        window.console.log("Making a FizzBuzzManager.");
    }

    public myThing: String = "Hi";

    public fizzBuzz2() {
        window.console.log("fizzbuzzing2 " + this.myThing);
    }

}

export function fizzBuzz() {
    window.console.log("export function fizzbuzz");
}

}
</code>```

The output when looking at the compiled output in a browser is this:

```<code>Hello                                                  app.js:15:9
constructing Greeter.                                  app.js:5:13
Calling init.                                          app.js:9:13
TypeError: jim.FizzBuzzManager is not a constructor    app.js:10:36
</code>```

答:
I had this error my_imported_module_1.MyModule is not a constructor.

I was using the approach when I got this error:
import { MyModule } from 'my-module-sdk';

but I got it to work when I changed it to this approach:
const MyModule = require('my-module-sdk');

In my tsconfig.json, I have "target" set to "es5", and tried changing it "es6" and that still didn't help.

Here are some of my other tsconfig options:

```<code>"target": "es5",
"module": "esnext",
"declaration": true,
"rootDir": "./src",
"moduleResolution": "node",
"lib": ["es6", "dom", "es2016", "es2017", "es2018", "es2019",
"es2020"],
"esModuleInterop": true,
"allowSyntheticDefaultImports": true,
"allowJs": false
</code>```

Body:
I'm working in typescript 1.5 in visual studio. I have a main class called app.ts, and another called FizzBuzzManager.ts. I can't figure out what is wrong with this code, but it outputs the error, "TypeError: jim.FizzBuzzManager is not a constructor".

app.ts

 namespace jim {
    class Greeter {
        element: HTMLElement;
        span: HTMLElement;
        timerToken: number;

        constructor() {
            window.console.log("constructing Greeter.");
            this.init();
        }

        private init() {
            window.console.log("Calling init.");
            var _fizzBuzzManager: any = new jim.FizzBuzzManager();
    }

}

    window.onload = () => {
        window.console.log("Hello")
        var greeter = new Greeter();

};

FizzBuzzManager.ts

namespace jim {

export class FizzBuzzManager {

    constructor() {
        window.console.log("Making a FizzBuzzManager.");
    }

    public myThing: String = "Hi";

    public fizzBuzz2() {
        window.console.log("fizzbuzzing2 " + this.myThing);
    }

}

export function fizzBuzz() {
    window.console.log("export function fizzbuzz");
}

}

The output when looking at the compiled output in a browser is this:

Hello                                                  app.js:15:9
constructing Greeter.                                  app.js:5:13
Calling init.                                          app.js:9:13
TypeError: jim.FizzBuzzManager is not a constructor    app.js:10:36

Body:
I had this error my_imported_module_1.MyModule is not a constructor.

I was using the approach when I got this error:
import { MyModule } from 'my-module-sdk';

but I got it to work when I changed it to this approach:
const MyModule = require('my-module-sdk');

In my tsconfig.json, I have "target" set to "es5", and tried changing it "es6" and that still didn't help.

Here are some of my other tsconfig options:

"target": "es5",
"module": "esnext",
"declaration": true,
"rootDir": "./src",
"moduleResolution": "node",
"lib": ["es6", "dom", "es2016", "es2017", "es2018", "es2019",
"es2020"],
"esModuleInterop": true,
"allowSyntheticDefaultImports": true,
"allowJs": false


问:
How to pass a session to 'Model.create()' in Mongoose.?
How can I pass a session variable to Model.Create() in mongoose.

I have tried some code but it gives me the following error:  "to pass a session to Model.create() in Mongoose, you must pass an array".

```<code>    const mongoose = require("mongoose");
    const Company = require("../models/company");
    const Address = require("../models/userAddress");

    exports.add_company = async (req ,res,next)=>{

    const  session = await mongoose.startSession();
    await session.startTransaction();
    const createdDocs = [];

    try{
    const address = new Address({
    _id: new mongoose.Types.ObjectId(),
    addressName: req.body.addressName,
    address1: req.body.address1,
    address2: req.body.address2,
    city: req.body.city,

    pincode: req.body.pincode

    });

    await Address.create(session,address);

    createdDocs.push(address);

    const company = new Company({
             _id: new mongoose.Types.ObjectId(),
             companyName: req.body.companyname,
             companyType: req.body.companytype,
             companyDesc: req.body.companydesc,
             companyWebsite: req.body.companywebsite,
             companyLogo: req.file ? req.file.path : null,
             addressId:createdDocs[0].addressId

         });
     await  Company.create(session,company);

         createdDocs.push(company);

         await session.commitTransaction();
         console.log(createdDocs);

         res.status(200).json({
          message:"company registered registerd",
          companyName:createdDocs[1].companyName,
          address:createdDocs[0].addressName,

        });

     }
     catch(err){

     await session.abortTransaction();
     res.json({ status:false, message:err.message});

     }
     finally {
     session.endSession();
     }

     };
</code>```

答:
https://mongoosejs.com/docs/transactions.html

Keep the object in Array, and session as second argument.
refer the link here, this might help.

Body:
How can I pass a session variable to Model.Create() in mongoose.

I have tried some code but it gives me the following error:  "to pass a session to Model.create() in Mongoose, you must pass an array".

    const mongoose = require("mongoose");
    const Company = require("../models/company");
    const Address = require("../models/userAddress");

    exports.add_company = async (req ,res,next)=>{

    const  session = await mongoose.startSession();
    await session.startTransaction();
    const createdDocs = [];

    try{
    const address = new Address({
    _id: new mongoose.Types.ObjectId(),
    addressName: req.body.addressName,
    address1: req.body.address1,
    address2: req.body.address2,
    city: req.body.city,

    pincode: req.body.pincode

    });

    await Address.create(session,address);

    createdDocs.push(address);

    const company = new Company({
             _id: new mongoose.Types.ObjectId(),
             companyName: req.body.companyname,
             companyType: req.body.companytype,
             companyDesc: req.body.companydesc,
             companyWebsite: req.body.companywebsite,
             companyLogo: req.file ? req.file.path : null,
             addressId:createdDocs[0].addressId

         });
     await  Company.create(session,company);

         createdDocs.push(company);

         await session.commitTransaction();
         console.log(createdDocs);

         res.status(200).json({
          message:"company registered registerd",
          companyName:createdDocs[1].companyName,
          address:createdDocs[0].addressName,

        });

     }
     catch(err){

     await session.abortTransaction();
     res.json({ status:false, message:err.message});

     }
     finally {
     session.endSession();
     }

     };


问:
How to disable HTTP requests on Heroku and/or auto-redirect to HTTPS?
I'm currently deploying a Scala Play 2.7.x application to Heroku intending only HTTPS access but the HTTP access is still available and then in this case, the authentication doesn't work.

How can I disable HTTP completely for a Scala Play application deployed in Heroku?

答:
Heroku doesn't handle redirection for you:

Redirects need to be performed at the application level as the Heroku router does not provide this functionality. You should code the redirect logic into your application.

It looks like this is relatively straightforward with Play Framework version 2.6 or later:

```<code>play.filters.enabled += play.filters.https.RedirectHttpsFilter
</code>```

If necessary, you can override this setting in your development environment by passing -Dplay.filters.enabled=<whatever> locally, or provide an alternate configuration file with -Dconfig.file.

Body:
Heroku doesn't handle redirection for you:

Redirects need to be performed at the application level as the Heroku router does not provide this functionality. You should code the redirect logic into your application.

It looks like this is relatively straightforward with Play Framework version 2.6 or later:

play.filters.enabled += play.filters.https.RedirectHttpsFilter

If necessary, you can override this setting in your development environment by passing -Dplay.filters.enabled=<whatever> locally, or provide an alternate configuration file with -Dconfig.file.


问:
Configure JMS with ActiveMQ in Thorntail
I have a little issue about configuring JMS on Thorntail. In my project for development purpose I'm using Wildfly, but for remote server, we are using (my team) IBM Portal. I upgraded the local server from Wildfly to Thorntail and after I want to launch my app locally (using maven), it crashed. I looked into logs and I found that it gives my:

```<code>2019-12-04 10:49:50,957 ERROR [org.jboss.as.controller.management-operation] (main) WFLYCTL0013: Operation ("add") failed - address: (("deployment" => "myproject.war")) - failure description: {
    "WFLYCTL0412: Required services that are not installed:" => ["jboss.naming.context.java.module.myproject.env.jms.notification"],
    "WFLYCTL0180: Services with missing/unavailable dependencies" => [
        "jboss.naming.context.java.module.myproject.env.\"myproject.notifications.service.impl.JmsNotificationServiceImpl\".connectionFactory is missing [jboss.naming.context.java.module.myproject.env.jms.notification]",
        "jboss.naming.context.java.module.myproject.env.\"myproject.notifications.service.impl.JmsNotificationServiceImpl\".topic is missing [jboss.naming.context.java.module.myproject.env.jms.notification]"
    ]
}
2019-12-04 10:49:50,994 ERROR [org.jboss.as.server] (main) WFLYSRV0021: Deploy of deployment "myproject.war" was rolled back with the following failure message:
{
    "WFLYCTL0412: Required services that are not installed:" => ["jboss.naming.context.java.module.myproject.env.jms.notification"],
    "WFLYCTL0180: Services with missing/unavailable dependencies" => [
        "jboss.naming.context.java.module.myproject.env.\"myproject.notifications.service.impl.JmsNotificationServiceImpl\".connectionFactory is missing [jboss.naming.context.java.module.myproject.env.jms.notification]",
        "jboss.naming.context.java.module.myproject.env.\"myproject.notifications.service.impl.JmsNotificationServiceImpl\".topic is missing [jboss.naming.context.java.module.myproject.env.jms.notification]"
    ]
}
</code>```

In our local environment we didn't configured any queue for JMS purposes, becouse our main queue mechanism was on remote server (IBM Portal).
There is some code we are using:

```<code>public class JmsNotificationServiceImpl implements JmsNotificationService {

    @Resource(lookup = "jms/notificationCF")
    private ConnectionFactory connectionFactory;

    @Resource(lookup = "jms/topic/notification")
    private Topic topic;

    @Override
    public void send(String string) throws Exception {
        Connection connection = null;
        try {
            connection = connectionFactory.createConnection();
            Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
            MessageProducer producer = session.createProducer(topic);

            log.info("Sending JMS message to topic...");
            producer.send(session.createObjectMessage(string));
            log.info("Message sent succesfull.");
        } catch (JMSException e) {
            throw new Exception("Error while creation or sending jms message", e);
        }
    }

}
</code>```

I found that there is a build in ActiveMQ in Thorntail, but I don't really know how to configure ConnectionFactory and Topic in ActiveMQ. Could anyone help me to understand where put some configuration and how to configure it?

答:
Minimalistic project-defaults.yml That allows your thorntail instance to connect to an remote Message Broker

```<code>swarm:
  network:
    socket-binding-groups:
      standard-sockets:
        outbound-socket-bindings:
          remote-activemq-socket-binding:
            remote-host: 127.0.0.1
            remote-port: 61616
  messaging-activemq:
    servers:
      default:
        remote-connectors:
          remote-activemq-connector:
            socket-binding: remote-activemq-socket-binding
        pooled-connection-factories:
          remote-connection-factory:
            user: myuser
            password: otherpassword
            connectors:
              - remote-activemq-connector
            entries:
              - 'java:/jms/remote-mq'
              - 'java:/DefaultJMSConnectionFactory'
        jms-queues:
          session-tracking-queue:
            entries:
              entry: 'java:/jms/queue/testQueue'
</code>```

Requires the following dependency to be included:

```<code><dependency>
    <groupId>io.thorntail</groupId>
    <artifactId>messaging</artifactId>
</dependency>
</code>```

Body:
I have a little issue about configuring JMS on Thorntail. In my project for development purpose I'm using Wildfly, but for remote server, we are using (my team) IBM Portal. I upgraded the local server from Wildfly to Thorntail and after I want to launch my app locally (using maven), it crashed. I looked into logs and I found that it gives my:

2019-12-04 10:49:50,957 ERROR [org.jboss.as.controller.management-operation] (main) WFLYCTL0013: Operation ("add") failed - address: (("deployment" => "myproject.war")) - failure description: {
    "WFLYCTL0412: Required services that are not installed:" => ["jboss.naming.context.java.module.myproject.env.jms.notification"],
    "WFLYCTL0180: Services with missing/unavailable dependencies" => [
        "jboss.naming.context.java.module.myproject.env.\"myproject.notifications.service.impl.JmsNotificationServiceImpl\".connectionFactory is missing [jboss.naming.context.java.module.myproject.env.jms.notification]",
        "jboss.naming.context.java.module.myproject.env.\"myproject.notifications.service.impl.JmsNotificationServiceImpl\".topic is missing [jboss.naming.context.java.module.myproject.env.jms.notification]"
    ]
}
2019-12-04 10:49:50,994 ERROR [org.jboss.as.server] (main) WFLYSRV0021: Deploy of deployment "myproject.war" was rolled back with the following failure message:
{
    "WFLYCTL0412: Required services that are not installed:" => ["jboss.naming.context.java.module.myproject.env.jms.notification"],
    "WFLYCTL0180: Services with missing/unavailable dependencies" => [
        "jboss.naming.context.java.module.myproject.env.\"myproject.notifications.service.impl.JmsNotificationServiceImpl\".connectionFactory is missing [jboss.naming.context.java.module.myproject.env.jms.notification]",
        "jboss.naming.context.java.module.myproject.env.\"myproject.notifications.service.impl.JmsNotificationServiceImpl\".topic is missing [jboss.naming.context.java.module.myproject.env.jms.notification]"
    ]
}

In our local environment we didn't configured any queue for JMS purposes, becouse our main queue mechanism was on remote server (IBM Portal).
There is some code we are using:

public class JmsNotificationServiceImpl implements JmsNotificationService {

    @Resource(lookup = "jms/notificationCF")
    private ConnectionFactory connectionFactory;

    @Resource(lookup = "jms/topic/notification")
    private Topic topic;

    @Override
    public void send(String string) throws Exception {
        Connection connection = null;
        try {
            connection = connectionFactory.createConnection();
            Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
            MessageProducer producer = session.createProducer(topic);

            log.info("Sending JMS message to topic...");
            producer.send(session.createObjectMessage(string));
            log.info("Message sent succesfull.");
        } catch (JMSException e) {
            throw new Exception("Error while creation or sending jms message", e);
        }
    }

}

I found that there is a build in ActiveMQ in Thorntail, but I don't really know how to configure ConnectionFactory and Topic in ActiveMQ. Could anyone help me to understand where put some configuration and how to configure it?

Body:
Minimalistic project-defaults.yml That allows your thorntail instance to connect to an remote Message Broker

swarm:
  network:
    socket-binding-groups:
      standard-sockets:
        outbound-socket-bindings:
          remote-activemq-socket-binding:
            remote-host: 127.0.0.1
            remote-port: 61616
  messaging-activemq:
    servers:
      default:
        remote-connectors:
          remote-activemq-connector:
            socket-binding: remote-activemq-socket-binding
        pooled-connection-factories:
          remote-connection-factory:
            user: myuser
            password: otherpassword
            connectors:
              - remote-activemq-connector
            entries:
              - 'java:/jms/remote-mq'
              - 'java:/DefaultJMSConnectionFactory'
        jms-queues:
          session-tracking-queue:
            entries:
              entry: 'java:/jms/queue/testQueue'

Requires the following dependency to be included:

<dependency>
    <groupId>io.thorntail</groupId>
    <artifactId>messaging</artifactId>
</dependency>


问:
Test a Nested Class Method in Rspec
Is there a way to test for the existence of a class method being called from another class method?

```<code>class AnimalRecord < ApplicationRecord
  COLLAR_ID = AnimalCollar::ID
  belongs_to :animal
  serialize :json, JSON
  scope :collar_id, -> { for_collar(COLLAR_ID) }

  def self.current_record(animal)
    animal_info = AnimalRecord.collar_id.first
    calculate_nutrients(animal_info)
  end

  def self.calculate_nutrients(animal)
    code result
  end
end
</code>```

I can test the current_record method from current_record. But what is the proper way to test the calculate_nutrients method?

I had this:

```<code>context "test record" do
  before do
    @animal = create(:animal... )
    @animal_record = create(:animal_record...)
  end

  it "calls #calculate_nutrients" do
    expected_response = responseHere
    expect(AnimalRecord).to receive(:calculate_nutrients).and_return(expected_response)

    AnimalRecord.current_record(@animal)
  end
</code>```

But I get an error that says this:

```<code>    expected: 1 time with any arguments
       received: 0 times with any arguments
</code>```

答: I think you have do remove the line expect(AnimalRecord).to receive(:event) from the test example. Seems there is no such method defined on AnimalRecord, but you are trying to "expect" it.

Title: Test a Nested Class Method in Rspec

Body:
Is there a way to test for the existence of a class method being called from another class method?

class AnimalRecord < ApplicationRecord
  COLLAR_ID = AnimalCollar::ID
  belongs_to :animal
  serialize :json, JSON
  scope :collar_id, -> { for_collar(COLLAR_ID) }

  def self.current_record(animal)
    animal_info = AnimalRecord.collar_id.first
    calculate_nutrients(animal_info)
  end

  def self.calculate_nutrients(animal)
    code result
  end
end

I can test the current_record method from current_record. But what is the proper way to test the calculate_nutrients method?

I had this:

context "test record" do
  before do
    @animal = create(:animal... )
    @animal_record = create(:animal_record...)
  end

  it "calls #calculate_nutrients" do
    expected_response = responseHere
    expect(AnimalRecord).to receive(:calculate_nutrients).and_return(expected_response)

    AnimalRecord.current_record(@animal)
  end

But I get an error that says this:

    expected: 1 time with any arguments
       received: 0 times with any arguments


问:
How can I check which file is a function in?
I'm working with PHP and sometimes, I want to find where the function being used is located. How can I do this easily without tracing through everything?</p>

答: Add a logging class: Example here: http://llihp.blogspot.com/2011/05/php-logger-class.html</p>


问:
using pandas isin with groupby
I have a dataframe the looks like the following below. I want to be able to find out the  total number of "missing" that is occurring in the dataframe but to also group the data by columns A,B and C.

```<code>               A   B           C        D        E        F  total_missing
0     Miami Heat  FL  Basketball       21  MISSING  MISSING             11
1     Miami Heat  FL  Basketball       17  MISSING  MISSING             11
2     Miami Heat  FL  Basketball  MISSING       12       23             11
3  Orlando Magic  FL  Basketball  MISSING        5  MISSING             11
4  Orlando Magic  FL  Basketball       10  MISSING  MISSING             11
5  Orlando Magic  FL  Basketball        5  MISSING  MISSING             11
</code>```

This code below only gives back the total number of the words missing which is 11 and it appears in all the rows. I just want the total 11 to appear in one cell and to be able to group it by columns a,b and c which I am not sure how to do with the isin function. Any help would be appreciated.

```<code>import pandas as pd
df = pd.read_excel(r'C:\ds_test\basketball.xlsx')
df['total_missing'] = df.isin(["MISSING"]).sum().sum()
print(df['total_missing'])

</code>```

答:
If I understand you correctly, you want:</p>

```<code>dfn = (
    df.assign(Total_missing=df.eq('MISSING').sum(axis=1))
      .groupby(['A', 'B', 'C'])['Total_missing'].sum()
      .reset_index()
)

               A   B           C  Total_missing
0     Miami Heat  FL  Basketball              5
1  Orlando Magic  FL  Basketball              6
</code>```

Title: using pandas isin with groupby

Body:
I have a dataframe the looks like the following below. I want to be able to find out the  total number of "missing" that is occurring in the dataframe but to also group the data by columns A,B and C.

               A   B           C        D        E        F  total_missing
0     Miami Heat  FL  Basketball       21  MISSING  MISSING             11
1     Miami Heat  FL  Basketball       17  MISSING  MISSING             11
2     Miami Heat  FL  Basketball  MISSING       12       23             11
3  Orlando Magic  FL  Basketball  MISSING        5  MISSING             11
4  Orlando Magic  FL  Basketball       10  MISSING  MISSING             11
5  Orlando Magic  FL  Basketball        5  MISSING  MISSING             11

This code below only gives back the total number of the words missing which is 11 and it appears in all the rows. I just want the total 11 to appear in one cell and to be able to group it by columns a,b and c which I am not sure how to do with the isin function. Any help would be appreciated.

import pandas as pd
df = pd.read_excel(r'C:\ds_test\basketball.xlsx')
df['total_missing'] = df.isin(["MISSING"]).sum().sum()
print(df['total_missing'])

Body:
If I understand you correctly, you want:

dfn = (
    df.assign(Total_missing=df.eq('MISSING').sum(axis=1))
      .groupby(['A', 'B', 'C'])['Total_missing'].sum()
      .reset_index()
)

               A   B           C  Total_missing
0     Miami Heat  FL  Basketball              5
1  Orlando Magic  FL  Basketball              6


问:
Best way to split data of varying length into columns
I have some data that includes 4 columns. First column is a place and last three columns are numbers or ranges of numbers.

What is the best way to split this data into four columns?

```<code>Red Coast Van 240-250 240-250 285-365
Beanbelt 310-400 310-400 450-540
North Star 310-400 310-400 450-540
Hamilton Fines, TA 380-390 380-390 505-530
Western Beanbelt 310-400 310-400 450-525
Main, PA 370-380 370-380 505-525
Dust Dodge, NY 380-390 380-390 520-525
Midwest Bean Belt (Des) m 400-475 400-475 572-615
</code>```

Desired Output

```<code>Red Coast Van; 240-250; 240-250; 285-365
Beanbelt; 310-400; 310-400; 450-540
North Star; 310-400; 310-400; 450-540
Hamilton Fines, TA; 380-390; 380-390; 505-530
Western Beanbelt; 310-400; 310-400; 450-525
Main, PA; 370-380; 370-380; 505-525
Dust Dodge, NY; 380-390; 380-390; 520-525
Midwest Bean Belt (Des) m; 400-475; 400-475; 572-615
</code>```

答:
Based on your example and description, it looks like columns 2nd, 3rd, and 4th are space-separated. Therefore you can do this using awk the following way:

set the input field separator FS to space and the output field separator OFS to ; (you can do this una tantum in the BEGIN procedure);

join all the fields from $1 to $(NF - 3) (i.e. the columns from the 1st to the 4th to last one) in a single field, $1;

shift the remaining fields $(NF - 2)-$NF to $2-$4 and adjust NF to 4;

print the modified record.

From words to code:

```<code>awk '
BEGIN { FS = " "; OFS = "; " }
{
  for (i = 2; i <= NF - 3; ++i)
    $1 = $1" "$i
}
{
  $2 = $(NF - 2)
  $3 = $(NF - 1)
  $4 = $NF
  NF = 4
}
{ print $0 }' youfile
</code>```

Body:
I have some data that includes 4 columns. First column is a place and last three columns are numbers or ranges of numbers.

What is the best way to split this data into four columns?

Red Coast Van 240-250 240-250 285-365
Beanbelt 310-400 310-400 450-540
North Star 310-400 310-400 450-540
Hamilton Fines, TA 380-390 380-390 505-530
Western Beanbelt 310-400 310-400 450-525
Main, PA 370-380 370-380 505-525
Dust Dodge, NY 380-390 380-390 520-525
Midwest Bean Belt (Des) m 400-475 400-475 572-615

Desired Output

Red Coast Van; 240-250; 240-250; 285-365
Beanbelt; 310-400; 310-400; 450-540
North Star; 310-400; 310-400; 450-540
Hamilton Fines, TA; 380-390; 380-390; 505-530
Western Beanbelt; 310-400; 310-400; 450-525
Main, PA; 370-380; 370-380; 505-525
Dust Dodge, NY; 380-390; 380-390; 520-525
Midwest Bean Belt (Des) m; 400-475; 400-475; 572-615

Body:
Based on your example and description, it looks like columns 2nd, 3rd, and 4th are space-separated. Therefore you can do this using awk the following way:

set the input field separator FS to space and the output field separator OFS to ; (you can do this una tantum in the BEGIN procedure);

join all the fields from $1 to $(NF - 3) (i.e. the columns from the 1st to the 4th to last one) in a single field, $1;

shift the remaining fields $(NF - 2)-$NF to $2-$4 and adjust NF to 4;

print the modified record.

From words to code:

awk '
BEGIN { FS = " "; OFS = "; " }
{
  for (i = 2; i <= NF - 3; ++i)
    $1 = $1" "$i
}
{
  $2 = $(NF - 2)
  $3 = $(NF - 1)
  $4 = $NF
  NF = 4
}
{ print $0 }' youfile


问:
How to properly add elements to an array in Python
I have two arrays as the code shows below (A and B). I would like to take as output C = [[1, 2, 3, 11], [4, 5, 6, 12], [7, 8, 9, 13]]

I'm trying to, but the only thing I could reach was this:

```<code>A = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
B = [11, 12, 13]
C = [[x, y] for x, y in zip(A, B)]

print(C)
# Output: [[[1, 2, 3], 11], [[4, 5, 6], 12], [[7, 8, 9], 13]]
</code>```

答:
You didn't have the same level of nesting in both A and B, which is why you got a weird answer. A is a list of lists, while B is just a list.

Solutions

If you want to add inplace:

```<code>A.append(B)
# Output: A = [[1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 11, 12]]
</code>```

Otherwise:

```<code>C = A + [B]
</code>```

which leaves A and B untouched and creates a new joined list.

Timings

Conclusion: for this problem it really doesn't matter which way you do it, as the timings are about the same for each case. Some ways are more readable though.

Code for timing:

```<code>import timeit

A = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
B = [10, 11, 12]

def append_arrs(arrs=(A, B)):
    a, b = arrs
    a.append(b)
    return a

def plus_arrs(arrs=(A, B)):
    return arrs[0] + [arrs[1]]

def loopadd_arrs(arrs=(A, B)):
    return [x + [y] for x, y in zip(*arrs)]

def listadd_arrs(arrs=(A, B)):
    a, b = arrs
    return list((*a, b))

func_list = ["append_arrs", "plus_arrs", "loopadd_arrs", "listadd_arrs"]

for func in func_list:
    t = timeit.timeit(stmt=f'{func}', setup=f'from __main__ import {func}')
    print(f"Time for {func}: {t}")
</code>```

Body:
I have two arrays as the code shows below (A and B). I would like to take as output C = [[1, 2, 3, 11], [4, 5, 6, 12], [7, 8, 9, 13]]

I'm trying to, but the only thing I could reach was this:

A = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
B = [11, 12, 13]
C = [[x, y] for x, y in zip(A, B)]

print(C)
# Output: [[[1, 2, 3], 11], [[4, 5, 6], 12], [[7, 8, 9], 13]]

Body:
You didn't have the same level of nesting in both A and B, which is why you got a weird answer. A is a list of lists, while B is just a list.

Solutions

If you want to add inplace:

A.append(B)
# Output: A = [[1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 11, 12]]

Otherwise:

C = A + [B]

which leaves A and B untouched and creates a new joined list.

Timings

Conclusion: for this problem it really doesn't matter which way you do it, as the timings are about the same for each case. Some ways are more readable though.

Code for timing:

import timeit

A = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
B = [10, 11, 12]

def append_arrs(arrs=(A, B)):
    a, b = arrs
    a.append(b)
    return a

def plus_arrs(arrs=(A, B)):
    return arrs[0] + [arrs[1]]

def loopadd_arrs(arrs=(A, B)):
    return [x + [y] for x, y in zip(*arrs)]

def listadd_arrs(arrs=(A, B)):
    a, b = arrs
    return list((*a, b))

func_list = ["append_arrs", "plus_arrs", "loopadd_arrs", "listadd_arrs"]

for func in func_list:
    t = timeit.timeit(stmt=f'{func}', setup=f'from __main__ import {func}')
    print(f"Time for {func}: {t}")


问:
How to remove Set-Cookie header from response in rails 3?
I have some actions that respond with static content. I also need them cached on client.

Similar question was asked in the past for rails 2

Is it possible to omit set-cookie header from the response in Rails 2.3?

答:
Try this: Remove charset from Rails content type or http://guides.rubyonrails.org/action_controller_overview.html#setting-custom-headers

Hope this would help.


Title: Python regex ignore empty lines

Body:
I have data with the following structure:

[TimingPoints]
21082,410.958904109589,4,3,1,60,1,0
21082,-250,4,3,1,100,0,0
22725,-142.857142857143,4,3,1,100,0,0
23547,-166.666666666667,4,3,1,100,0,0

24369,-333.333333333335,4,3,1,100,0,0
27657,-200.000000000001,4,3,1,100,0,0
29301,-142.857142857143,4,3,1,100,0,0
30123,-166.666666666667,4,3,1,100,0,0
30945,-250,4,3,1,100,0,0

32588,-166.666666666667,4,3,1,100,0,0
34232,-250,4,3,1,100,0,0
35876,-142.857142857143,4,3,1,100,0,0
36698,-166.666666666667,4,3,1,100,0,0
37520,-250,4,3,1,100,0,0
42451,-142.857142857143,4,3,1,100,0,0

[HitObjects]
256,192,17794,12,0,20876,0:0:0:0:
159,96,21082,6,0,B|204:120|204:120|254:103|254:103|305:130|355:102,1,210
409,27,22725,2,0,P|446:96|405:179,1,171.499994766236
269,284,23547,2,0,B|317:250|324:193|324:193|328:220|350:236,1,146.999995513916

I'd like to read all lines under [TimingPoints] before [HitObjects] in a list.
Empty lines should be ignored.
So the final list should contain:

21082,410.958904109589,4,3,1,60,1,0
21082,-250,4,3,1,100,0,0
22725,-142.857142857143,4,3,1,100,0,0
23547,-166.666666666667,4,3,1,100,0,0
24369,-333.333333333335,4,3,1,100,0,0
27657,-200.000000000001,4,3,1,100,0,0
29301,-142.857142857143,4,3,1,100,0,0
30123,-166.666666666667,4,3,1,100,0,0
30945,-250,4,3,1,100,0,0
32588,-166.666666666667,4,3,1,100,0,0
34232,-250,4,3,1,100,0,0
35876,-142.857142857143,4,3,1,100,0,0
36698,-166.666666666667,4,3,1,100,0,0
37520,-250,4,3,1,100,0,0
42451,-142.857142857143,4,3,1,100,0,0

I tried it with the following regex pattern:
\[TimingPoints\]((.|\n)*)\[HitObjects] but it does not ignore the empty lines.
How can I match the lines to get what is described above?
Also how can I load all the matched lines in a list with python?

Body:
Don't get me wrong, I'm a huge fan of regex and use it daily.  But it's a bit heavy for this task.

1) Read the file into a list and strip any whitespace (including new line characters), and drop the line if it's empty

2) Index to find '[HitObjects]' and trim from the list, along with the header

3) Done

Sample Code:

path = './timing.txt'

with open(path, 'r') as f:
    text = [i.strip() for i in f if i.strip()]

# Keep only rows between the headers of interest.
result = text[text.index('[TimingPoints]')+1:text.index('[HitObjects]')]

Output:

['21082,410.958904109589,4,3,1,60,1,0',
 '21082,-250,4,3,1,100,0,0',
 '22725,-142.857142857143,4,3,1,100,0,0',
 '23547,-166.666666666667,4,3,1,100,0,0',
 '24369,-333.333333333335,4,3,1,100,0,0',
 '27657,-200.000000000001,4,3,1,100,0,0',
 '29301,-142.857142857143,4,3,1,100,0,0',
 '30123,-166.666666666667,4,3,1,100,0,0',
 '30945,-250,4,3,1,100,0,0',
 '32588,-166.666666666667,4,3,1,100,0,0',
 '34232,-250,4,3,1,100,0,0',
 '35876,-142.857142857143,4,3,1,100,0,0',
 '36698,-166.666666666667,4,3,1,100,0,0',
 '37520,-250,4,3,1,100,0,0',
 '42451,-142.857142857143,4,3,1,100,0,0']


问:
Swift: cannot convert value of type 'SomeType<T>' to expected argument type 'SomeType<_>'
I am using generics to build a paging library where I have code similar to this one (simplified):

struct PageData<T> {
    let item: T
    let pageNumber: Int
}

protocol PagedServiceProvider: class {
    func fetchPage<ItemType>(page: Int, completion: @escaping (PageData<ItemType>?) -> Void)
}

class TestPagedServiceProvider<ItemType>: PagedServiceProvider {
    var pageData: PageData<ItemType>?

    func fetchPage<ItemType>(page: Int, completion: @escaping (PageData<ItemType>?) -> Void) {
        completion(pageData) // COMPILATION ERROR HERE
    }
}
```

<p>the call to <code>completion(pageData)</code> produces the following error:</p>

<blockquote>
  <p>Cannot convert value of type <code>PageData<ItemType>?</code> to expected argument type <code>PageData<_>?</code></p>
</blockquote>

<p>This workaround casting with <code>as?</code> gets rid of the error:</p>

<pre class="lang-swift prettyprint-override"><code>class TestPagedServiceProvider<ItemType>: PagedServiceProvider {
    var pageData: PageData<ItemType>?

    func fetchPage<ItemType>(page: Int, completion: @escaping (PageData<ItemType>?) -> Void) {
        completion(pageData as? PageData<ItemType>)
    }
}
</code>```

Also if var pageData: PageData<ItemType>? is declared as a local variable inside the fetchPage<ItemType>... method, the error is gone as well.

NOTE: This gist provides additional context.

I am confused as to why the compiler requires an explicit cast (that looks redundant to me in this case).

Could it be a matter of placeholder types scope (the ItemType in the fetchPage<ItemType>... method is not the same as the ItemType for the TestPagedServiceProvider<ItemType> class)?

I tried giving them different names and using where clauses to no avail.

答:
Your type signature says that the caller can pass any type as ItemType, but then you require the closure to accept a PageData<String>?.

fetchPage is not actually generic (it can't accept types chosen by the caller), so you can't claim it is. What you mean is to remove the <ItemType> and say what you require:

```<code>func fetchPage(page: Int, completion: @escaping (PageData<String>?) -> Void) {
              ^^                                          ^^^^^^
</code>```

This, however, breaks your PagedServiceProvider protocol, because that protocol requires that TestPagedServiceProvider accept absolutely any ItemType, and it doesn't. You'll need to decide what you really mean. You might mean a protocol with an associated type here, which is a type that the implementation gets to pick rather than the caller.

```<code>protocol PagedServiceProvider: class {
    associatedtype ItemType
    func fetchPage(page: Int, completion: @escaping (PageData<ItemType>?) -> Void)
}
</code>```

This opens up some headaches, however, since now PagedServiceProvider cannot easily be put in an Array (it's no longer a concrete type). How you deal with this depends heavily on what problem you're actually solving. There is no general solution that is always appropriate.

Body:
I am using generics to build a paging library where I have code similar to this one (simplified):

struct PageData<T> {
    let item: T
    let pageNumber: Int
}

protocol PagedServiceProvider: class {
    func fetchPage<ItemType>(page: Int, completion: @escaping (PageData<ItemType>?) -> Void)
}

class TestPagedServiceProvider<ItemType>: PagedServiceProvider {
    var pageData: PageData<ItemType>?

    func fetchPage<ItemType>(page: Int, completion: @escaping (PageData<ItemType>?) -> Void) {
        completion(pageData) // COMPILATION ERROR HERE
    }
}

the call to completion(pageData) produces the following error:

Cannot convert value of type PageData<ItemType>? to expected argument type PageData<_>?

This workaround casting with as? gets rid of the error:

class TestPagedServiceProvider<ItemType>: PagedServiceProvider {
    var pageData: PageData<ItemType>?

    func fetchPage<ItemType>(page: Int, completion: @escaping (PageData<ItemType>?) -> Void) {
        completion(pageData as? PageData<ItemType>)
    }
}

Also if var pageData: PageData<ItemType>? is declared as a local variable inside the fetchPage<ItemType>... method, the error is gone as well.

NOTE: This gist provides additional context.

I am confused as to why the compiler requires an explicit cast (that looks redundant to me in this case).

Could it be a matter of placeholder types scope (the ItemType in the fetchPage<ItemType>... method is not the same as the ItemType for the TestPagedServiceProvider<ItemType> class)?

I tried giving them different names and using where clauses to no avail.

Body:
Your type signature says that the caller can pass any type as ItemType, but then you require the closure to accept a PageData<String>?.

fetchPage is not actually generic (it can't accept types chosen by the caller), so you can't claim it is. What you mean is to remove the <ItemType> and say what you require:

func fetchPage(page: Int, completion: @escaping (PageData<String>?) -> Void) {
              ^^                                          ^^^^^^

This, however, breaks your PagedServiceProvider protocol, because that protocol requires that TestPagedServiceProvider accept absolutely any ItemType, and it doesn't. You'll need to decide what you really mean. You might mean a protocol with an associated type here, which is a type that the implementation gets to pick rather than the caller.

protocol PagedServiceProvider: class {
    associatedtype ItemType
    func fetchPage(page: Int, completion: @escaping (PageData<ItemType>?) -> Void)
}

This opens up some headaches, however, since now PagedServiceProvider cannot easily be put in an Array (it's no longer a concrete type). How you deal with this depends heavily on what problem you're actually solving. There is no general solution that is always appropriate.


问:
Cleaning Data & Association Rules - R
I am trying to tidy the following dataset (in link) in R and then run an association rules below.

https://www.kaggle.com/fanatiks/shopping-cart

```<code>install.packages("dplyr")
library(dplyr)

df <- read.csv("Groceries (2).csv", header = F, stringsAsFactors = F, na.strings=c(""," ","NA"))
install.packages("stringr")
library(stringr)
temp1<- (str_extract(df$V1, "[a-z]+"))
temp2<- (str_extract(df$V1, "[^a-z]+"))
df<- cbind(temp1,df)
df[2] <- NULL
df[35] <- NULL
View(df)

summary(df)
str(df)

trans <- as(df,"transactions")
</code>```

I get the following error when I run the above trans <- as(df,"transactions") code:

Warning message:
Column(s) 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34 not logical or factor. Applying default discretization (see '? discretizeDF').

```<code>summary(trans)
</code>```

When I run the above code, I get the following:

```<code>transactions as itemMatrix in sparse format with
 1499 rows (elements/itemsets/transactions) and
 1268 columns (items) and a density of 0.01529042

most frequent items:
  V5= vegetables   V6= vegetables temp1=vegetables   V2= vegetables
             140              113              109              108
  V9= vegetables          (Other)
             103            28490
</code>```

The attached results is showing all the vegetable values as separate items instead of a combined vegetable score which is obviously increasing my number of columns. I am not sure why this is happening?

```<code>fit<-apriori(trans,parameter=list(support=0.006,confidence=0.25,minlen=2))
fit<-sort(fit,by="support")
inspect(head(fit))
</code>```

答:
For coercion to transaction class the dataframe needs to be made up of factor columns. You have a dataframe of characters - hence the error message. The data requires some further cleaning in order to get it to coerce properly.

I'm not very familiar with the arules package but I believe the read.transactions function may be more useful as it would automatically discard duplicates. I found it easiest to make a binary matrix and use a for loop, but I am sure there is a neater solution.

Continuing on directly from your code:

```<code>items <- as.character(unique(unlist(df))) # get all unique items
items <- items[which(str_detect(items, "[a-z]"))] # remove numbers

trans <- matrix(0, nrow = nrow(df), ncol = length(items))

for(i in 1:nrow(df)){
  trans[i,which(items %in% t(df[i,]))] <- 1
}

colnames(trans) <- items
rownames(trans) <- temp2

trans <- as(trans, "transactions")

summary(trans)
</code>```

Giving

```<code>transactions as itemMatrix in sparse format with
 1637 rows (elements/itemsets/transactions) and
 38 columns (items) and a density of 0.3359965

most frequent items:
 vegetables     poultry     waffles   ice cream  lunch meat     (Other)
       1058         582         562         556         555       17588

element (itemset/transaction) length distribution:
sizes
  0   1   3   4   5   6   7   8   9  10  11  12  13  14  15  16  17  18  19  20  21  22  23  24  25  26
102  36   8  57  51  51  71  69  63  80  79  58  84  91  72 105  97  87 114  91  82  46  30   7   4   2

   Min. 1st Qu.  Median    Mean 3rd Qu.    Max.
   0.00    8.00   14.00   12.77   18.00   26.00

includes extended item information - examples:
    labels
1     pork
2  shampoo
3    juice

includes extended transaction information - examples:
  transactionID
1      1/1/2000
2      1/1/2000
3      2/1/2000
</code>```

Title: Cleaning Data & Association Rules - R

Body:
I am trying to tidy the following dataset (in link) in R and then run an association rules below.

https://www.kaggle.com/fanatiks/shopping-cart

install.packages("dplyr")
library(dplyr)

df <- read.csv("Groceries (2).csv", header = F, stringsAsFactors = F, na.strings=c(""," ","NA"))
install.packages("stringr")
library(stringr)
temp1<- (str_extract(df$V1, "[a-z]+"))
temp2<- (str_extract(df$V1, "[^a-z]+"))
df<- cbind(temp1,df)
df[2] <- NULL
df[35] <- NULL
View(df)

summary(df)
str(df)

trans <- as(df,"transactions")

I get the following error when I run the above trans <- as(df,"transactions") code:

Warning message:
Column(s) 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34 not logical or factor. Applying default discretization (see '? discretizeDF').

summary(trans)

When I run the above code, I get the following:

transactions as itemMatrix in sparse format with
 1499 rows (elements/itemsets/transactions) and
 1268 columns (items) and a density of 0.01529042

most frequent items:
  V5= vegetables   V6= vegetables temp1=vegetables   V2= vegetables
             140              113              109              108
  V9= vegetables          (Other)
             103            28490

The attached results is showing all the vegetable values as separate items instead of a combined vegetable score which is obviously increasing my number of columns. I am not sure why this is happening?

fit<-apriori(trans,parameter=list(support=0.006,confidence=0.25,minlen=2))
fit<-sort(fit,by="support")
inspect(head(fit))

Body:
For coercion to transaction class the dataframe needs to be made up of factor columns. You have a dataframe of characters - hence the error message. The data requires some further cleaning in order to get it to coerce properly.

I'm not very familiar with the arules package but I believe the read.transactions function may be more useful as it would automatically discard duplicates. I found it easiest to make a binary matrix and use a for loop, but I am sure there is a neater solution.

Continuing on directly from your code:

items <- as.character(unique(unlist(df))) # get all unique items
items <- items[which(str_detect(items, "[a-z]"))] # remove numbers

trans <- matrix(0, nrow = nrow(df), ncol = length(items))

for(i in 1:nrow(df)){
  trans[i,which(items %in% t(df[i,]))] <- 1
}

colnames(trans) <- items
rownames(trans) <- temp2

trans <- as(trans, "transactions")

summary(trans)

Giving

transactions as itemMatrix in sparse format with
 1637 rows (elements/itemsets/transactions) and
 38 columns (items) and a density of 0.3359965

most frequent items:
 vegetables     poultry     waffles   ice cream  lunch meat     (Other)
       1058         582         562         556         555       17588

element (itemset/transaction) length distribution:
sizes
  0   1   3   4   5   6   7   8   9  10  11  12  13  14  15  16  17  18  19  20  21  22  23  24  25  26
102  36   8  57  51  51  71  69  63  80  79  58  84  91  72 105  97  87 114  91  82  46  30   7   4   2

   Min. 1st Qu.  Median    Mean 3rd Qu.    Max.
   0.00    8.00   14.00   12.77   18.00   26.00

includes extended item information - examples:
    labels
1     pork
2  shampoo
3    juice

includes extended transaction information - examples:
  transactionID
1      1/1/2000
2      1/1/2000
3      2/1/2000


问:
Use fiexed ratio axes with plotly.express facetrow / facetcol
is there a possibility to use fixed ratio axes in combination with subplots created by plotly.express by using facetrow / facetcol

This example works perfectly fine:

```<code>import plotly.express as px
df = px.data.iris()
fig = px.scatter(df, x="sepal_width", y="sepal_length", facet_col='species')

fig.update_layout(yaxis=dict(scaleanchor="x", scaleratio=1))
</code>```

As soon as I add the facetrow argument it does not adjust the axis.
Can I maybe set a default layout for the subplots using
layout = go.Layout(yaxis=dict(scaleanchor="x", scaleratio=1))

Thank you for your help,

Sören

答:
when creating facets plotly.express matches axes together so that you can synchronize the subplots when zooming, panning etc. This behaviour is not compatible with constraining axes aspect ratio. The code below where you disable axis matching gives the desired behaviour:

```<code>import plotly.express as px
df = px.data.iris()
fig = px.scatter(df, x="sepal_width", y="sepal_length", facet_col='species')

fig.update_yaxes(matches=None, showticklabels=True)
fig.update_xaxes(matches=None)
fig.update_layout(yaxis=dict(scaleanchor="x"))
fig.update_layout(yaxis2=dict(scaleanchor="x2"))
fig.update_layout(yaxis3=dict(scaleanchor="x2"))
fig.show()
</code>```

Body:
is there a possibility to use fixed ratio axes in combination with subplots created by plotly.express by using facetrow / facetcol

This example works perfectly fine:

import plotly.express as px
df = px.data.iris()
fig = px.scatter(df, x="sepal_width", y="sepal_length", facet_col='species')

fig.update_layout(yaxis=dict(scaleanchor="x", scaleratio=1))

As soon as I add the facetrow argument it does not adjust the axis.
Can I maybe set a default layout for the subplots using
layout = go.Layout(yaxis=dict(scaleanchor="x", scaleratio=1))

Thank you for your help,

Sören

Body:
when creating facets plotly.express matches axes together so that you can synchronize the subplots when zooming, panning etc. This behaviour is not compatible with constraining axes aspect ratio. The code below where you disable axis matching gives the desired behaviour:

import plotly.express as px
df = px.data.iris()
fig = px.scatter(df, x="sepal_width", y="sepal_length", facet_col='species')

fig.update_yaxes(matches=None, showticklabels=True)
fig.update_xaxes(matches=None)
fig.update_layout(yaxis=dict(scaleanchor="x"))
fig.update_layout(yaxis2=dict(scaleanchor="x2"))
fig.update_layout(yaxis3=dict(scaleanchor="x2"))
fig.show()


问:
React redux renders store state change, immediately then refresh app to initial
had struggle for a while with this one, I followed all the instructions and checked a lot of times, this is the code:

```<code>const CREATE_BOOK = 'CREATE_BOOK';
const REMOVE_BOOK = 'REMOVE_BOOK';

const mapStateToProps = state => ({
  books: state,
});

const createBookAction = book => ({
  type: CREATE_BOOK,
  book,
});

const BookReducer = (state = [], action) => {
  switch (action.type) {
    case CREATE_BOOK:
      return [...state, action.book];
    case REMOVE_BOOK: {
      const index = state.findIndex(action.book);
      return state.slice(0, index).concat(state.slice(index + 1, state.length));
    }
    default:
      return state;
  }
};

const rootReducer = combineReducers({
  books: BookReducer,
});

const store = createStore(rootReducer);

const initialState = {
  title: '',
  category: 'Action',
  id: () => (Math.random() * 100).toFixed(),
}

class BooksForm extends React.Component {
  constructor(props) {
    super(props);
    this.state = initialState;
    this.handleChange = this.handleChange.bind(this);
    this.handleSubmit = this.handleSubmit.bind(this);
  }

  handleChange(event) {
    const { target: { value }, target: { name } } = event;
    this.setState({
      [name]: value
    })
  }

  handleSubmit() {
    this.props.createBookAction(this.state);
    //this.setState(initialState);
  }

  render(){
    const categories = ['Action', 'Biography', 'History', 'Horror', 'Kids', 'Learning', 'Sci-Fi'];
    const categoriesBox = categories.map(cg => <option key={cg}>{cg}</option>);
    return (
      <form>
        <input name="title" onChange={this.handleChange} type="text" />
        <select name="category" onChange={this.handleChange}>{categoriesBox}</select>
        <button onClick={this.handleSubmit} type="submit">Submit</button>
      </form>
    );
  }
};

const App = props => {
  const { books: { books }, createBookAction } = props;
  return (
    <div>
      <BooksForm books={books} createBookAction={createBookAction} />
    </div>
  );
};

const Container = connect(mapStateToProps, { createBookAction })(App);

const AppWrapper = () => (
  <Provider store={store}>
    <Container />
  </Provider>
);
</code>```

The thing is, there is a render below all this and it's supposed to render a list ( which is also present but not included here ) with the new submitted book. It does for like a second and then it re-renders to it's initial state again ( no books ). I wonder if it's a state change but checked all the sources and still can't find what I'm missing. Also, the combined reducer is on purpose.

UPDATE
checked with redux-logger, and what it's doing is basically, when the button it's pressed, it updates the state but then it refreshes the page ( and re-start the app ) , showing it like in it's beginning state.

答: Ok, i solved it. The issue was that the submit button had a type="submit". Changed to type="button" and all worked.

Body:
had struggle for a while with this one, I followed all the instructions and checked a lot of times, this is the code:

const CREATE_BOOK = 'CREATE_BOOK';
const REMOVE_BOOK = 'REMOVE_BOOK';

const mapStateToProps = state => ({
  books: state,
});

const createBookAction = book => ({
  type: CREATE_BOOK,
  book,
});

const BookReducer = (state = [], action) => {
  switch (action.type) {
    case CREATE_BOOK:
      return [...state, action.book];
    case REMOVE_BOOK: {
      const index = state.findIndex(action.book);
      return state.slice(0, index).concat(state.slice(index + 1, state.length));
    }
    default:
      return state;
  }
};

const rootReducer = combineReducers({
  books: BookReducer,
});

const store = createStore(rootReducer);

const initialState = {
  title: '',
  category: 'Action',
  id: () => (Math.random() * 100).toFixed(),
}

class BooksForm extends React.Component {
  constructor(props) {
    super(props);
    this.state = initialState;
    this.handleChange = this.handleChange.bind(this);
    this.handleSubmit = this.handleSubmit.bind(this);
  }

  handleChange(event) {
    const { target: { value }, target: { name } } = event;
    this.setState({
      [name]: value
    })
  }

  handleSubmit() {
    this.props.createBookAction(this.state);
    //this.setState(initialState);
  }

  render(){
    const categories = ['Action', 'Biography', 'History', 'Horror', 'Kids', 'Learning', 'Sci-Fi'];
    const categoriesBox = categories.map(cg => <option key={cg}>{cg}</option>);
    return (
      <form>
        <input name="title" onChange={this.handleChange} type="text" />
        <select name="category" onChange={this.handleChange}>{categoriesBox}</select>
        <button onClick={this.handleSubmit} type="submit">Submit</button>
      </form>
    );
  }
};

const App = props => {
  const { books: { books }, createBookAction } = props;
  return (

      <BooksForm books={books} createBookAction={createBookAction} />

  );
};

const Container = connect(mapStateToProps, { createBookAction })(App);

const AppWrapper = () => (
  <Provider store={store}>
    <Container />
  </Provider>
);

The thing is, there is a render below all this and it's supposed to render a list ( which is also present but not included here ) with the new submitted book. It does for like a second and then it re-renders to it's initial state again ( no books ). I wonder if it's a state change but checked all the sources and still can't find what I'm missing. Also, the combined reducer is on purpose.

UPDATE
checked with redux-logger, and what it's doing is basically, when the button it's pressed, it updates the state but then it refreshes the page ( and re-start the app ) , showing it like in it's beginning state.


问:
about the failure of replication in tidygraph
I have a question.
I am using igraph and tidygraph.
In igraph, the information of node is like this,

```<code>1     A young
2     B young
3     C young
4     D adult
5     E adult
6     F   old
7     G   old
8     H   old
9     I   old
10    J   old
</code>```

However, when I used the same data for tidygraph, node C is labeled as adult, not young.......
What's wrong with my code??
How can I appropriately assign nodes$carac?

```<code>#https://www.r-graph-gallery.com/249-igraph-network-map-a-color.html

# library
library(igraph)
set.seed(1)
# create data:
links <- data.frame(
  source=c("A","A", "A", "A", "A","J", "B", "B", "C", "C", "D","I"),
  target=c("B","B", "C", "D", "J","A","E", "F", "G", "H", "I","I"),
  weight=(sample(1:4, 12, replace=T))

)
nodes <- data.frame(
  name=LETTERS[1:10],
  carac=c( rep("young",3),rep("adult",2), rep("old",5))
)

# Turn it into igraph object
network <- graph_from_data_frame(d=links, vertices=nodes, directed=F)

# Make a palette of 3 colors
library(RColorBrewer)
coul  <- brewer.pal(3, "Set1")

# Create a vector of color
my_color <- coul[as.numeric(as.factor(V(network)$carac))]

# Make the plot
plot(network, vertex.color=my_color)

library(ggraph)
library(tidygraph)
#
g<-as_tbl_graph(links, directed = FALSE)

g %>%
  mutate(degree = centrality_degree(),
         community = as.factor(V(network)$carac) )%>%
  ggraph(layout = "lgl") +
  geom_edge_link(aes(width = 1),
                 alpha = 0.8,
                 colour = "lightgray") +
  scale_edge_width(range = c(0.1, 1)) +geom_node_point(aes(colour = community, size = degree)) +
  geom_node_text(aes(label = name), repel = TRUE) +
  theme_graph()
</code>```

答:
The problem seems to be in this part

```<code>g <- as_tbl_graph(links, directed = FALSE)
g %>%
  mutate(degree = centrality_degree(),
         community = as.factor(V(network)$carac) )
</code>```

You seem to be assuming that the order of the nodes in the tbl_graph object are the same order as V(network) and that does not seem to be the case. It would be better to just create your own tbl_graph and specify both the nodes and edges at the same time. For example

```<code>g <- tbl_graph(nodes, links, directed=FALSE)
g %>%
   mutate(degree = centrality_degree(),
          community = carac)
</code>```

Then you don't have to worry about matching them back up later.

Body:
I have a question.
I am using igraph and tidygraph.
In igraph, the information of node is like this,

1     A young
2     B young
3     C young
4     D adult
5     E adult
6     F   old
7     G   old
8     H   old
9     I   old
10    J   old

However, when I used the same data for tidygraph, node C is labeled as adult, not young.......
What's wrong with my code??
How can I appropriately assign nodes$carac?

#https://www.r-graph-gallery.com/249-igraph-network-map-a-color.html

# library
library(igraph)
set.seed(1)
# create data:
links <- data.frame(
  source=c("A","A", "A", "A", "A","J", "B", "B", "C", "C", "D","I"),
  target=c("B","B", "C", "D", "J","A","E", "F", "G", "H", "I","I"),
  weight=(sample(1:4, 12, replace=T))

)
nodes <- data.frame(
  name=LETTERS[1:10],
  carac=c( rep("young",3),rep("adult",2), rep("old",5))
)

# Turn it into igraph object
network <- graph_from_data_frame(d=links, vertices=nodes, directed=F)

# Make a palette of 3 colors
library(RColorBrewer)
coul  <- brewer.pal(3, "Set1")

# Create a vector of color
my_color <- coul[as.numeric(as.factor(V(network)$carac))]

# Make the plot
plot(network, vertex.color=my_color)

library(ggraph)
library(tidygraph)
#
g<-as_tbl_graph(links, directed = FALSE)

g %>%
  mutate(degree = centrality_degree(),
         community = as.factor(V(network)$carac) )%>%
  ggraph(layout = "lgl") +
  geom_edge_link(aes(width = 1),
                 alpha = 0.8,
                 colour = "lightgray") +
  scale_edge_width(range = c(0.1, 1)) +geom_node_point(aes(colour = community, size = degree)) +
  geom_node_text(aes(label = name), repel = TRUE) +
  theme_graph()

Body:
The problem seems to be in this part

g <- as_tbl_graph(links, directed = FALSE)
g %>%
  mutate(degree = centrality_degree(),
         community = as.factor(V(network)$carac) )

You seem to be assuming that the order of the nodes in the tbl_graph object are the same order as V(network) and that does not seem to be the case. It would be better to just create your own tbl_graph and specify both the nodes and edges at the same time. For example

g <- tbl_graph(nodes, links, directed=FALSE)
g %>%
   mutate(degree = centrality_degree(),
          community = carac)

Then you don't have to worry about matching them back up later.


问:
SwiftUI: Parse JSON and create dynamic list
I would like to parse/decode a JSON string and then create a dynamic list.

Example JSON:
[{"course":"course1","teacher":"teacherName1"},{"course":"course1","teacher":"teacherName2"}]

My wish:

```<code>List {
  HStack {
    Text("course1")
    Spacer()
    Text("teacherName1")
  }
  HStack {
    Text("course2")
    Spacer()
    Text("teacherName2")
  }
}
</code>```

I've tried it with JSONDecoder() and arrays but Xcode marks my TabView over and over with this message: Cannot convert value of type 'Binding<Int>' to expected argument type 'Binding<_>?'

I'm new to swift, sorry ;)

答:
I made an example that you can follow:

import SwiftUI

let jsonString = """
[{"course":"course1","teacher":"teacherName1"},{"course":"course1","teacher":"teacherName2"}]
"""

let data = jsonString.data(using: .utf8) ?? Data()

struct Course: Codable, Identifiable {

    let id = UUID()
    let course: String
    let teacher: String
}

struct ContentView: View {

    let courses: [Course] = (try? JSONDecoder().decode([Course].self, from: data)) ?? []

    var body: some View {
        List(courses) { course in
            HStack {
                Text(course.course)
                Spacer()
                Text(course.teacher)
            }
        }
    }
}
```

I made the Course struct confirm to Identifiable as well as Codable so that the List can iterate over the array of courses. Also I defaulted to empty Data and empty courses array in case decoding fails. You could write better error handling here depending on your needs.

Body:
I would like to parse/decode a JSON string and then create a dynamic list.

Example JSON:
[{"course":"course1","teacher":"teacherName1"},{"course":"course1","teacher":"teacherName2"}]

My wish:

List {
  HStack {
    Text("course1")
    Spacer()
    Text("teacherName1")
  }
  HStack {
    Text("course2")
    Spacer()
    Text("teacherName2")
  }
}

I've tried it with JSONDecoder() and arrays but Xcode marks my TabView over and over with this message: Cannot convert value of type 'Binding<Int>' to expected argument type 'Binding<_>?'

I'm new to swift, sorry ;)

Body:
I made an example that you can follow:

import SwiftUI

let jsonString = """
[{"course":"course1","teacher":"teacherName1"},{"course":"course1","teacher":"teacherName2"}]
"""

let data = jsonString.data(using: .utf8) ?? Data()

struct Course: Codable, Identifiable {

    let id = UUID()
    let course: String
    let teacher: String
}

struct ContentView: View {

    let courses: [Course] = (try? JSONDecoder().decode([Course].self, from: data)) ?? []

    var body: some View {
        List(courses) { course in
            HStack {
                Text(course.course)
                Spacer()
                Text(course.teacher)
            }
        }
    }
}

I made the Course struct confirm to Identifiable as well as Codable so that the List can iterate over the array of courses. Also I defaulted to empty Data and empty courses array in case decoding fails. You could write better error handling here depending on your needs.


问:
iOS private/public data management and storage in Swift
Is it possible to display as one array objects retrieved from network and same model but retrieved from core data. Purpose is to have same data possible to be public (then retrieved from network) or private and then this data is stored locally in coredata model. Attributes/Properties will be the same for both.

I plan to display this as swiftUI view (if that matters)

After some search I came with idea to have one struct that based on its privacy property will be translated to core data class model or if public directly connected to networking layer?

for example (some pseudo swift ;) )

struct Note {
   let note: String
   let isPrivate: Bool

   func save(self) {
       if self.isPrivate { save to CoreData }
       else { send save request with use of networking }
   }
}

class coreDataModel: NSManagedObject {
   var note: String
   let isPrivate = true
}

struct networkingModel {
   var note: String
   let isPrivate = false
}

class modelManager {
   func joinData() {
       let joinedModel: Note = coreDataModel + networkingModel
    // and so on to display that model

   }
}
```

答:
I think you can try this, first load the ui with the existing local data. At the same time, make a call to your api on a background queue. Once the api results are available, filter for duplicates, then persist it locally. Then the last step is to notify the ui to reload.

This pseudo-code is a bit UIKit specific, however the same logic can be applied to when in SwiftUI. You won't need closure, you will compute directly to your publisher object, and ui will react based any new emits.

```<code>/// you can have one model for both api and core data
struct Note: Hashable { let uuid = UUID.init() }

class ModelManager {
    private var _items: Array<Note> = []

    var onChanged: ((Array<Note>) -> Void)? = nil
    // you might also have an init, where you can have a timer running
    func start() {
        loadFromCoreData { [weak self] (items) in
            guard let `self` = self else { return }
            self._items.append(contentsOf: items)
            self.onChanged?(self._items)
            self.loadFromApi()
        }
    }

    private func loadFromCoreData(completion: @escaping (Array<Note>) -> Void) {
        // background queue
        // logic to load from coredata.
        let coreDataResults: Array<Note> = []
        completion(coreDataResults)
    }

    private func loadFromApi() {
        // background queue
        let apiResults: Array<Note> = []
        compute(contents: apiResults)
    }

    private func compute(contents: Array<Note>) {
        let combined = zip(_items, contents).flatMap{[$0.0, $0.1] }
        let newItems = Array(Set(combined)) // set doesn't allow duplicates
        // save to db

        // insert to new to _items
        _items.append(contentsOf: newItems)
        // sort maybe to place new items on top
        self.onChanged?(self._items)

    }

}

// usage of this object
    let manager = ModelManager()
    manager.start()
    manager.onChanged = { items in
        // [weak self] remember of retain cycles
        // make sure you are on main queue when reloading

    }
</code>```

Body:
I think you can try this, first load the ui with the existing local data. At the same time, make a call to your api on a background queue. Once the api results are available, filter for duplicates, then persist it locally. Then the last step is to notify the ui to reload.

This pseudo-code is a bit UIKit specific, however the same logic can be applied to when in SwiftUI. You won't need closure, you will compute directly to your publisher object, and ui will react based any new emits.

/// you can have one model for both api and core data
struct Note: Hashable { let uuid = UUID.init() }

class ModelManager {
    private var _items: Array<Note> = []

    var onChanged: ((Array<Note>) -> Void)? = nil
    // you might also have an init, where you can have a timer running
    func start() {
        loadFromCoreData { [weak self] (items) in
            guard let `self` = self else { return }
            self._items.append(contentsOf: items)
            self.onChanged?(self._items)
            self.loadFromApi()
        }
    }

    private func loadFromCoreData(completion: @escaping (Array<Note>) -> Void) {
        // background queue
        // logic to load from coredata.
        let coreDataResults: Array<Note> = []
        completion(coreDataResults)
    }

    private func loadFromApi() {
        // background queue
        let apiResults: Array<Note> = []
        compute(contents: apiResults)
    }

    private func compute(contents: Array<Note>) {
        let combined = zip(_items, contents).flatMap{[$0.0, $0.1] }
        let newItems = Array(Set(combined)) // set doesn't allow duplicates
        // save to db

        // insert to new to _items
        _items.append(contentsOf: newItems)
        // sort maybe to place new items on top
        self.onChanged?(self._items)

    }

}

// usage of this object
    let manager = ModelManager()
    manager.start()
    manager.onChanged = { items in
        // [weak self] remember of retain cycles
        // make sure you are on main queue when reloading

    }


问:
Divide the data of array to two arrays
I’m getting a series of data from a json like it

```<code>   [
  {
   "name": "david",
    "gender": "Male"
  },
  {
    "name": "Sara",
    "gender": "Female"
  },
  {
    "name": "Philipp",
    "gender": "Male"
  },
  {
    "name": "Marry",
    "gender": "Female"
  }
]
</code>```

I get this data and store them into one array

Lets call it names

Now I want to create two other arrays

```<code>femaleNames

maleNames
</code>```

And I want to save all the female name in femaleNames and all the male names in maleNames based on the gender type of data.
I don’t that how I can implement this condition in swift 5. Could you please help me?
Thanks

答:
Assuming you have a model struct for your data along these lines:

```<code>enum Gender: Decodable, String {
    case female = "Female"
    case male = "Male"
}

struct NameEntry: Decodable {
    let name: String
    let gender: Gender
}
</code>```

and given a bunch of names in

```<code>var names: [NameEntry]
</code>```

your can filter easily using

```<code>let femaleNames = names.filter { $0.gender == .female }
let maleNames = names.filter { $0.gender == .male }
</code>```

Title: Divide the data of array to two arrays

Body:
I’m getting a series of data from a json like it

   [
  {
   "name": "david",
    "gender": "Male"
  },
  {
    "name": "Sara",
    "gender": "Female"
  },
  {
    "name": "Philipp",
    "gender": "Male"
  },
  {
    "name": "Marry",
    "gender": "Female"
  }
]

I get this data and store them into one array

Lets call it names

Now I want to create two other arrays

femaleNames

maleNames

And I want to save all the female name in femaleNames and all the male names in maleNames based on the gender type of data.
I don’t that how I can implement this condition in swift 5. Could you please help me?
Thanks

Body:
Assuming you have a model struct for your data along these lines:

enum Gender: Decodable, String {
    case female = "Female"
    case male = "Male"
}

struct NameEntry: Decodable {
    let name: String
    let gender: Gender
}

and given a bunch of names in

var names: [NameEntry]

your can filter easily using

let femaleNames = names.filter { $0.gender == .female }
let maleNames = names.filter { $0.gender == .male }


问:
Can't connect activities in activity diagram in EA
Hi I'm currently stuck with a problem with Activity diagram in EA. I'm trying to describe a code. When I add Start controll node and activity node I'm not able to connect them by control flow.

The same problem happens when I try to connect two activities together with control flow - I'm getting following error:

The requested connection is not UML compliant

Anybody can give some advice on this?

Thanks

答:
When I add Start controll node and activity node I'm not able to connect them by control flow.

The same problem happens when I try to connect two activities together with control flow

E.A. is right to refuse these flows, they have no sense

Rather than to add activities in your diagram use call behavior actions whose behavior is an activity, in that case a fork is drawn in the action to indicate that case. Example with BoUML :

The behavior of a call behavior action can also be a state machine.


问:
slideshow with jquery fancybox and iframe
I am trying to see if it is possible to create slideshow of html pages similar to flipboard.com
landing page.

I am able to load the html page using iframe in fancybox.

The page is at: http://yshara.com/test.html

My html/javascript looks like:

```<code><body onload="$('.extLink').trigger('click');">
  <div class="container">
    <div id="nextslide">
  <a class="extLink" href="http://google.com">Search the world with different sites.</a>
      <a class="extLink"  href="http://yahoo.com">Next</a>
      <a class="extLink" href="http://Bing.com">Next</a>
</div>
  </div>
</body>
</code>```

I was wondering if any of you javascript experts can help me with this one.

The first page is google.com, but it skips it to the next one, yahoo.com

How do I cycle back to the first page?

Thanks in advance for your help.

答: You shouldn't be triggering the .extLink class, as it's triggering 3 times. Try $('.extLink:eq(0)').click()

Body:
I am trying to see if it is possible to create slideshow of html pages similar to flipboard.com
landing page.

I am able to load the html page using iframe in fancybox.

The page is at: http://yshara.com/test.html

My html/javascript looks like:

  Search the world with different sites.
      Next
      Next

I was wondering if any of you javascript experts can help me with this one.

The first page is google.com, but it skips it to the next one, yahoo.com

How do I cycle back to the first page?

Thanks in advance for your help.


问:
Verify Order Of HTML Elements With Attribute Values Such as Class="Group0-Item1" Class="Group0-Item2" Class="Group1-Item1"
In my Selenium/C#/NUNIT project, I need to find a way to validate the order (top down hierarchy of a page's HTML) for a group of HTML elements (as well as the elements contained within those groups). These are my elements that show inside my page's HTML...

```<code><div class="gapBanner-banner-order1-group0"></div>
<div class="gapBanner-banner-order1-group1"></div>
<div class="gapBanner-banner-order1-group2"></div>
<div class="gapBanner-banner-order2-group2"></div>
</code>```

The validation I want to perform should be able to catch the following bugs:

Bug 1: The groups are not in order within the page's HTML. One of the elements that is in group1 appears first in the HTML before group0...

```<code><div class="gapBanner-banner-order1-group1"></div>
<div class="gapBanner-banner-order1-group0"></div>
<div class="gapBanner-banner-order1-group2"></div>
<div class="gapBanner-banner-order2-group2"></div>
</code>```

Bug #2: The elements WITHIN each group are not in order within the page's HTML. Group2-Order2 appears before Group2-Order1 within the HTML

```<code><div class="gapBanner-banner-order1-group0"></div>
<div class="gapBanner-banner-order1-group1"></div>
<div class="gapBanner-banner-order2-group2"></div>
<div class="gapBanner-banner-order1-group2"></div>
</code>```

The below is what I have coded so far, but it is definitely not going to do the job, not to mention, it is very messy. I cant figure out what kind of logic I need for this

```<code>            /// 5. Verify the correct order of elements in which they appear inside the HTML
            List<IWebElement> CustomPageHTMLComponents = Browser.
            FindElements(By.XPath("//div[contains(@class, 'group')")).ToList();
            List<IWebElement> uniqueGroups = new List<IWebElement>();
            // Get the unique groups
        for (int i = 0; i < CustomPageHTMLComponents.Count; i++)
        {
            IWebElement currentComponent = Browser.FindElements(By.XPath("//div[contains(@class, 'group')"))[i];
            string toBeSearched = "group";
            string currentComponenetClassAttributeValue = currentComponent.GetAttribute("class");
            int x = currentComponenetClassAttributeValue.IndexOf(toBeSearched);
            string groupNumber = currentComponenetClassAttributeValue.Substring(x + toBeSearched.Length);

            if (groupNumber == i.ToString())
            {
                uniqueGroups.Add(currentComponent);
            }
        }

             // Some kind of logic to verify everything???
        for (int i = 0; i < Page.CustomPageHTMLComponents.Count; i++)
        {
            IWebElement currentComponent = Browser.FindElements(By.XPath("//div[contains(@class, 'group')"))[i];

            string toBeSearched = "group";
            string currentComponenetClassAttributeValue = currentComponent.GetAttribute("class");
            int x = currentComponenetClassAttributeValue.IndexOf(toBeSearched);
            string groupNumber = currentComponenetClassAttributeValue.Substring(x + toBeSearched.Length);

            Assert.AreEqual(groupNumber, i.ToString());
        }
</code>```

答:
There are probably a number of ways to do this. This is the first way I came up with...

Grab all the class names from the desired elements and store them in string array #1

Make a copy of string array #1 and sort it

Compare the two arrays and if they are equal, then they were sorted to start with

I've checked the HTML you provided for the bugs you'd like to catch and it catches them all. The one issue I can think of is if you get more than 9 orders or groups the sorting will not be what you want because it's alpha order not numerical order, e.g. 1, 10, 2, ... instead of 1, 2, ... 10.

```<code>// capture the class names from the desired classes
string[] elements = _driver.FindElements(By.CssSelector("div[class^='gapBanner-banner-']")).Select(e => e.GetAttribute("class")).ToArray();
// make a copy of the array
string[] sortedElements = new string[elements.Length];
elements.CopyTo(sortedElements, 0);
// sort the copy
Array.Sort(sortedElements);
// compare the arrays for order using NUnit CollectionAssert
CollectionAssert.AreEqual(elements, sortedElements, "Verify ordering of elements");
</code>```

Body:
In my Selenium/C#/NUNIT project, I need to find a way to validate the order (top down hierarchy of a page's HTML) for a group of HTML elements (as well as the elements contained within those groups). These are my elements that show inside my page's HTML...

The validation I want to perform should be able to catch the following bugs:

Bug 1: The groups are not in order within the page's HTML. One of the elements that is in group1 appears first in the HTML before group0...

Bug #2: The elements WITHIN each group are not in order within the page's HTML. Group2-Order2 appears before Group2-Order1 within the HTML

The below is what I have coded so far, but it is definitely not going to do the job, not to mention, it is very messy. I cant figure out what kind of logic I need for this

            /// 5. Verify the correct order of elements in which they appear inside the HTML
            List<IWebElement> CustomPageHTMLComponents = Browser.
            FindElements(By.XPath("//div[contains(@class, 'group')")).ToList();
            List<IWebElement> uniqueGroups = new List<IWebElement>();
            // Get the unique groups
        for (int i = 0; i < CustomPageHTMLComponents.Count; i++)
        {
            IWebElement currentComponent = Browser.FindElements(By.XPath("//div[contains(@class, 'group')"))[i];
            string toBeSearched = "group";
            string currentComponenetClassAttributeValue = currentComponent.GetAttribute("class");
            int x = currentComponenetClassAttributeValue.IndexOf(toBeSearched);
            string groupNumber = currentComponenetClassAttributeValue.Substring(x + toBeSearched.Length);

            if (groupNumber == i.ToString())
            {
                uniqueGroups.Add(currentComponent);
            }
        }

             // Some kind of logic to verify everything???
        for (int i = 0; i < Page.CustomPageHTMLComponents.Count; i++)
        {
            IWebElement currentComponent = Browser.FindElements(By.XPath("//div[contains(@class, 'group')"))[i];

            string toBeSearched = "group";
            string currentComponenetClassAttributeValue = currentComponent.GetAttribute("class");
            int x = currentComponenetClassAttributeValue.IndexOf(toBeSearched);
            string groupNumber = currentComponenetClassAttributeValue.Substring(x + toBeSearched.Length);

            Assert.AreEqual(groupNumber, i.ToString());
        }

Body:
There are probably a number of ways to do this. This is the first way I came up with...

Grab all the class names from the desired elements and store them in string array #1

Make a copy of string array #1 and sort it

Compare the two arrays and if they are equal, then they were sorted to start with

I've checked the HTML you provided for the bugs you'd like to catch and it catches them all. The one issue I can think of is if you get more than 9 orders or groups the sorting will not be what you want because it's alpha order not numerical order, e.g. 1, 10, 2, ... instead of 1, 2, ... 10.

// capture the class names from the desired classes
string[] elements = _driver.FindElements(By.CssSelector("div[class^='gapBanner-banner-']")).Select(e => e.GetAttribute("class")).ToArray();
// make a copy of the array
string[] sortedElements = new string[elements.Length];
elements.CopyTo(sortedElements, 0);
// sort the copy
Array.Sort(sortedElements);
// compare the arrays for order using NUnit CollectionAssert
CollectionAssert.AreEqual(elements, sortedElements, "Verify ordering of elements");


问:
Referencing specific key value in JSON output
I have a JSON output that returns a lot of data, but I am only concerned with one piece of it. A part of my output is below:

```<code>data = {'vulnerabilities': {'critical': 3,
                            'exploits': 1,
                            'malwareKits': 0,
                            'moderate': 9,
                            'severe': 29,
                            'total': 41}}
</code>```

I would like to only reference 'critical' so that my output will have the number of criticals in there.

Code tried:

```<code>for element in data['vulnerabilities']:
    if element == ['critical']:
       print(element)
</code>```

答:
There seems to be a lot of issues with your code.

```<code>for element in data['vulnerabilities']:
</code>```

Here I see, you are accessing data['vulnerabilities'], which returns a dict itself. So when you are iterating over it, by default, python iterates over the keys.

Here

```<code>element == 'critical'
</code>```

is correct and not

```<code>if element == ['critical']:
</code>```

Here I assume you want to print the value of the key, as I mentioned above, the element is  one of the keys in dict so you should iterate over its items like below.

```<code>for key, value in data['vulnerabilities'].items():
    if key == 'critical':
       print(value)
</code>```

Body:
I have a JSON output that returns a lot of data, but I am only concerned with one piece of it. A part of my output is below:

data = {'vulnerabilities': {'critical': 3,
                            'exploits': 1,
                            'malwareKits': 0,
                            'moderate': 9,
                            'severe': 29,
                            'total': 41}}

I would like to only reference 'critical' so that my output will have the number of criticals in there.

Code tried:

for element in data['vulnerabilities']:
    if element == ['critical']:
       print(element)

Body:
There seems to be a lot of issues with your code.

for element in data['vulnerabilities']:

Here I see, you are accessing data['vulnerabilities'], which returns a dict itself. So when you are iterating over it, by default, python iterates over the keys.

Here

element == 'critical'

is correct and not

if element == ['critical']:

Here I assume you want to print the value of the key, as I mentioned above, the element is  one of the keys in dict so you should iterate over its items like below.

for key, value in data['vulnerabilities'].items():
    if key == 'critical':
       print(value)