问:
How to implement `protectedFields` in Parse-Server?
I believe this is a new feature in Parse-Server.

By default, the User class's email field is considered a protected field, meaning that email is set to read: false, write: false to the public by default. But, every other field in the User class is set to read: true, write: false

In Github, I saw this example:

```<code>export type ClassLevelPermissions = {
find?: { [string]: boolean },
count?: { [string]: boolean },
get?: { [string]: boolean },
create?: { [string]: boolean },
update?: { [string]: boolean },
delete?: { [string]: boolean },
addField?: { [string]: boolean },
readUserFields?: string[],
writeUserFields?: string[],

// new feature
protectedFields?: { [string]: boolean }
};
</code>```

For example, with the _User class, if the server was initialized with userSensitiveFields: ['email', 'sin', 'phone'], this would be the equivalent of:

```<code>{
// CLP for the class ... other
protectedFields: { "*": ["email", "sin"] }
};
</code>```

Now if you wanted an moderator role to be able to see the user's email but not the sin and an admin which can read it all

```<code>{
 protectedFields: {
   "*": ["email", "sin"],
   "role:moderator": ["sin"],
   "role:admin": []
 }
};
</code>```

After seeing this example, I was still confused where exactly to implement protectedFields. Do I implement it in my app's index.js, or main.js, etc?  Can somebody give me an example of how I can set a field: phoneNum to have a protectedField similiar to email's default?

答:
It is an option in parse server initialization. See the protectedField option here:
http://parseplatform.org/parse-server/api/master/ParseServerOptions.html

I don't know exactly where/how you are running your Parse server, but it should be something like this:

```<code>var express = require('express');
var ParseServer = require('parse-server').ParseServer;
var app = express();

var api = new ParseServer({
  databaseURI: 'mongodb://localhost:27017/dev',
  cloud: '/home/myApp/cloud/main.js',
  appId: 'myAppId',
  masterKey: 'myMasterKey',
  fileKey: 'optionalFileKey',
  serverURL: 'http://localhost:1337/parse'
  protectedFields: {
    _User: {
      "*": ["email", "sin"],
      "role:moderator": ["sin"],
      "role:admin": []
    }
  }
});

app.use('/parse', api);

app.listen(1337, function() {
  console.log('parse-server-example running on port 1337.');
});
</code>```

Body:
I believe this is a new feature in Parse-Server.

By default, the User class's email field is considered a protected field, meaning that email is set to read: false, write: false to the public by default. But, every other field in the User class is set to read: true, write: false

In Github, I saw this example:

export type ClassLevelPermissions = {
find?: { [string]: boolean },
count?: { [string]: boolean },
get?: { [string]: boolean },
create?: { [string]: boolean },
update?: { [string]: boolean },
delete?: { [string]: boolean },
addField?: { [string]: boolean },
readUserFields?: string[],
writeUserFields?: string[],

// new feature
protectedFields?: { [string]: boolean }
};

For example, with the _User class, if the server was initialized with userSensitiveFields: ['email', 'sin', 'phone'], this would be the equivalent of:

{
// CLP for the class ... other
protectedFields: { "*": ["email", "sin"] }
};

Now if you wanted an moderator role to be able to see the user's email but not the sin and an admin which can read it all

{
 protectedFields: {
   "*": ["email", "sin"],
   "role:moderator": ["sin"],
   "role:admin": []
 }
};

After seeing this example, I was still confused where exactly to implement protectedFields. Do I implement it in my app's index.js, or main.js, etc?  Can somebody give me an example of how I can set a field: phoneNum to have a protectedField similiar to email's default?

Body:
It is an option in parse server initialization. See the protectedField option here:
http://parseplatform.org/parse-server/api/master/ParseServerOptions.html

I don't know exactly where/how you are running your Parse server, but it should be something like this:

var express = require('express');
var ParseServer = require('parse-server').ParseServer;
var app = express();

var api = new ParseServer({
  databaseURI: 'mongodb://localhost:27017/dev',
  cloud: '/home/myApp/cloud/main.js',
  appId: 'myAppId',
  masterKey: 'myMasterKey',
  fileKey: 'optionalFileKey',
  serverURL: 'http://localhost:1337/parse'
  protectedFields: {
    _User: {
      "*": ["email", "sin"],
      "role:moderator": ["sin"],
      "role:admin": []
    }
  }
});

app.use('/parse', api);

app.listen(1337, function() {
  console.log('parse-server-example running on port 1337.');
});


来源: stackexchange

问:
Redux-Persist with React-Native-Background-Fetch
I am creating a React-Native app that fetches data from an API as a background service.

I have looked around the web if I can manually rehydrate the store with the data fetched during the background task, but I could not find anything.

Is it possible to rehydrate the redux-persist store manually while the app is killed, from a background 'service' task?

答:
For the people still wondering, if it is possible to use react-native-background-fetch for scheduling ANY task, it is completely fine as long as it does not touch the UI eg. (AsyncStorage, Redux-Persist, Realm, DB...) is not directly related to invoking change in the UI, so it is completely fine to use.

In my particular case, I am using the slowest option - AsyncStorage - to persist a props sort of object which I use on global App level and pass derived data onto my components:

```<code>// Example of HeadlessTask implementation

import BackgroundFetch from 'react-native-background-fetch'
import AsyncStorage from '@react-native-community/async-storage';

const HeadlessTask = async () => {

    // Prepare data - fetching from API, other transformations...
    let propsObject = {};

    AsyncStorage.setItem(ITEM_KEY, JSON.strigify(propsObject))
        .then(() => {
            console.log('[AsyncStorage] Object Saved!');
            // For iOS specifically we need to tell when the service job
            // is done.
            BackgroundFetch.finish();
        })
        .catch((e) => {
            console.log('[AsyncStorage] Error saving object: ', e);
            BackgroundFetch.finish();
        });
}
</code>```

P.S. See https://github.com/transistorsoft/react-native-background-fetch to see how to install and implement Background Fetch.

ContentLicense: CC BY-SA 4.0

Body:
For the people still wondering, if it is possible to use react-native-background-fetch for scheduling ANY task, it is completely fine as long as it does not touch the UI eg. (AsyncStorage, Redux-Persist, Realm, DB...) is not directly related to invoking change in the UI, so it is completely fine to use.

In my particular case, I am using the slowest option - AsyncStorage - to persist a props sort of object which I use on global App level and pass derived data onto my components:

// Example of HeadlessTask implementation

import BackgroundFetch from 'react-native-background-fetch'
import AsyncStorage from '@react-native-community/async-storage';

const HeadlessTask = async () => {

    // Prepare data - fetching from API, other transformations...
    let propsObject = {};

    AsyncStorage.setItem(ITEM_KEY, JSON.strigify(propsObject))
        .then(() => {
            console.log('[AsyncStorage] Object Saved!');
            // For iOS specifically we need to tell when the service job
            // is done.
            BackgroundFetch.finish();
        })
        .catch((e) => {
            console.log('[AsyncStorage] Error saving object: ', e);
            BackgroundFetch.finish();
        });
}

P.S. See https://github.com/transistorsoft/react-native-background-fetch to see how to install and implement Background Fetch.


问:
Update list of records and fields into django model with bulk_update
I want to update the list of records in the my model. I want to use bulk_update more preferably.
These are my data that I have taken from users and want to update them in my model:

```<code>{'2': ['present', 'study'], '3': ['study'], '4': ['present'], '6': ['no-present', 'no-study']}
</code>```

The numbers represent the user's ID, and the values of each key are also fields that need to be updated.
Also my model is:

```<code>#models.py
class Rollcall(models.Model):
        student = models.ForeignKey(User)
        curriculum_session = models.ForeignKey(CurriculumSession)
        is_present = models.BooleanField(default=False, )
        is_study = models.BooleanField(default=False,)
</code>```

This question in the persuit of this question In that question, I
  was able to store my record using create_bulk in the database and
  this question is about updating those data.

So, how can I do this? Also I see this link and saw that bulk_update have to argument: 'obj' and 'fields'. What are these arguments?

答:
bulk_update(objs, fields, batch_size=None)

objs is a list of the objects you want to update, and fields is a list of the fields that you want to update in those objects (meaning the ones you modified).

For example, if your clean_objects contains a bunch of Rollcall objects, and you want to upadate the is_present field from True to False, you would do

```<code>roll_call1 = RollCall(...) # assume is_present is True
roll_call2 = RollCall(...) # assume is_present is True

# Update the objects
roll_call1.is_present = False
roll_call2.is_present = False

# Create the list
clean_object = [rollcall_1, rollcall_2,]

# Update in db
Rollcall.objects.bulk_update(clean_objects, ["is_present"])
</code>```

Ok, updating with your example. If you have this data

```<code>data = {'2': ['present', 'study'], '3': ['study'], '4': ['present'], '6': ['no-present', 'no-study']}
</code>```

then you would first retrieve all the Rollcall objects referenced in this data (with one query ideally, in the spirit of being efficient and using bulk later). Then you'd update the relevant fields for each object based on the data above. Once all done, call the bulk update method.

```<code># Assuming the number in the `data` is the student id and not the rollcall id
rollcalls = Rollcall.objects.filter(student__id__in=data.keys())

for rollcall in rollcalls:
    # Parse the data
    values = data[str(rollcall.student.id)]
    if "present" in values:
        rollcall.is_present = True
    if "no-present" in values:
        rollcall.is_present = False
    if "study" in values:
        rollcall.is_study = True
    if "no-study" in values:
        rollcall.is_study = False

Rollcall.objects.bulk_update(rollcalls, ["is_present", "is_study"])
</code>```

Body:
I want to update the list of records in the my model. I want to use bulk_update more preferably.
These are my data that I have taken from users and want to update them in my model:

{'2': ['present', 'study'], '3': ['study'], '4': ['present'], '6': ['no-present', 'no-study']}

The numbers represent the user's ID, and the values of each key are also fields that need to be updated.
Also my model is:

#models.py
class Rollcall(models.Model):
        student = models.ForeignKey(User)
        curriculum_session = models.ForeignKey(CurriculumSession)
        is_present = models.BooleanField(default=False, )
        is_study = models.BooleanField(default=False,)

This question in the persuit of this question In that question, I
  was able to store my record using create_bulk in the database and
  this question is about updating those data.

So, how can I do this? Also I see this link and saw that bulk_update have to argument: 'obj' and 'fields'. What are these arguments?

Body:
bulk_update(objs, fields, batch_size=None)

objs is a list of the objects you want to update, and fields is a list of the fields that you want to update in those objects (meaning the ones you modified).

For example, if your clean_objects contains a bunch of Rollcall objects, and you want to upadate the is_present field from True to False, you would do

roll_call1 = RollCall(...) # assume is_present is True
roll_call2 = RollCall(...) # assume is_present is True

# Update the objects
roll_call1.is_present = False
roll_call2.is_present = False

# Create the list
clean_object = [rollcall_1, rollcall_2,]

# Update in db
Rollcall.objects.bulk_update(clean_objects, ["is_present"])

Ok, updating with your example. If you have this data

data = {'2': ['present', 'study'], '3': ['study'], '4': ['present'], '6': ['no-present', 'no-study']}

then you would first retrieve all the Rollcall objects referenced in this data (with one query ideally, in the spirit of being efficient and using bulk later). Then you'd update the relevant fields for each object based on the data above. Once all done, call the bulk update method.

# Assuming the number in the `data` is the student id and not the rollcall id
rollcalls = Rollcall.objects.filter(student__id__in=data.keys())

for rollcall in rollcalls:
    # Parse the data
    values = data[str(rollcall.student.id)]
    if "present" in values:
        rollcall.is_present = True
    if "no-present" in values:
        rollcall.is_present = False
    if "study" in values:
        rollcall.is_study = True
    if "no-study" in values:
        rollcall.is_study = False

Rollcall.objects.bulk_update(rollcalls, ["is_present", "is_study"])


问:
Distributing an application server
I have an application server. At a high level, this application server has users and groups. Users are part of one or more groups, and the server keeps all users aware of the state of their groups and other users in their groups. There are three major functions:

Updating and broadcasting meta-data relating to users and their groups; for example, a user logs in and the server updates this user's status and broadcasts it to all online users in this user's groups.

Acting as a proxy between two or more users; the client takes advantage of peer-to-peer transfer, but in the case that two users are unable to directly connect to each other, the server will act as a proxy between them.

Storing data for offline users; if a client needs to send some data to a user who isn't online, the server will store that data for a period of time and then send it when the user next comes online.

I'm trying to modify this application to allow it to be distributed across multiple servers, not necessarily all on the same local network. However, I have a requirement that backwards compatibility with old clients cannot be broken; essentially, the distribution needs to be transparent to the client.

The biggest problem I'm having is handling the case of a user connected to Server A making an update that needs to be broadcast to a user on Server B.

By extension, an even bigger problem is when a user on Server A needs the server to act as a proxy between them and a user on Server B.

My initial idea was to try to assign each user a preferred server, using some algorithm that takes which users they need to communicate with into account. This could reduce the number of users who may need to communicate with users on other servers.

However, this only minimizes how often users on different servers will need to communicate. I still have the problem of achieving the communication between users on different servers.

The only solution I could come up with for this is having the servers connect to each other, when they need to deal with a user connected to a different server.

For example, if I'm connected to Server A and I need a proxy with another user connected to Server B, I would ask Server A for a proxy connection to this user. Server A would see that the other user is connected to Server B, so it would make a 'relay' connection to Server B. This connection would just forward my requests to Server B and the responses to me.

The problem with this is that it would increase bandwidth usage, which is already extremely high. Unfortunately, I don't see any other solution.

Are there any well known or better solutions to this problem? It doesn't seem like it's very common for a distributed system to have the requirement of communication between users on different servers.

答:
I don't know how much flexibility you have in modifying the existing server. The way I did this a long time ago was to have all the servers keep a TCP connection open to each other. I used a UDP broadcast which told the other servers about each other and allowed them to connect to new servers and remove servers that stopped sending the broadcast.

Then everytime a user connects to a server that server Unicasts a TCP message to all the servers it is connected to, and all the servers keeps a list of users and what server they are on.

Then as you suggest if you get a message from one user to another user on another server you have to relay that to the other server. The servers really need to be on the same LAN for this to work well.

You can run the server to server communications in a thread, and actually simulate the user being on the same server.

However maintaining the user lists and sending messages is prone to race conditions (like a user drops off while you are relaying the message from one server to another etc).

Maintaining the server code was a nightmare and this is really not the most efficient way to implement scalable servers. But if you have to use the legacy server code base then you really do not have too many options.

If you can look into using a language that supports remote processes and nodes like Erlang.

An alternative might be to use a message queue system like RabbitMQ or ActiveMQ, and have the servers talk to each other through that. Those system are designed to be scalable, and usually work off a Publish/Subscribe mechanism.

ContentLicense: CC BY-SA 3.0

Title: Distributing an application server


问:
How to create Service specific services in Angular
I have two services S1 and S2 in Angular

```<code>export class S1 {
    constructor(private s2: S2) {
    // ...
    }
}
</code>```

I want to create instance of S2 that is only scoped for S1 (the same as we do for Components)

Any suggestion on how to do that?

答:
I don't think this is possible because the decorator "@Injectable" only adds the providedIn metadata that defines which injectors will provide the injectable by associating it with an @NgModule. (see documentation)

Maybe if you share some concrete use-case we can see if there's any other workaround, but probably there's a shortage in your app structure design.

Body:
I have two services S1 and S2 in Angular

export class S1 {
    constructor(private s2: S2) {
    // ...
    }
}

I want to create instance of S2 that is only scoped for S1 (the same as we do for Components)

Any suggestion on how to do that?


问:
How to make work an Adapter to Listview inside a fragment
I'm using a fragment with a listview to show some elements from a firebase database. But it looks like the adapter doesn't work properly; i traced the code and everything looks working fine. Does anyone know where i have the error?

I tried getActivity().getBaseContext() and getContext() in the adapter context, but it also doesn't work

```<code>public class ListFragment extends Fragment implements View.OnClickListener{

    private RecyclerView rcv;
    private ListView lstvw;
    DatabaseReference ddbbr;

    public ListFragment() {
        // Required empty public constructor
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View v = inflater.inflate(R.layout.fragment_list, container, false);
        lstvw = v.findViewById(R.id.lstvwlistamini);
        ddbbr = FirebaseDatabase.getInstance().getReference("juegos");
        ddbbr.addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(@NonNull DataSnapshot dataSnapshot) {

                ArrayAdapter<String> adapter;
                ArrayList<String> list = new ArrayList<String>();

                for (DataSnapshot datasnapshot: dataSnapshot.getChildren()) {

                    Juego juego =  datasnapshot.getValue(Juego.class);

                    String titulo = juego.getTitulo();
                    list.add(titulo);
                    Toast toast = Toast.makeText(getContext(),list.get(0).toString(),Toast.LENGTH_LONG);
                    toast.show();

                }
                adapter = new ArrayAdapter<String>(getActivity(),android.R.layout.simple_list_item_1,list);
                lstvw.setAdapter(adapter);

            }

            @Override
            public void onCancelled(@NonNull DatabaseError databaseError) {

            }
        });

        // Inflate the layout for this fragment
        return inflater.inflate(R.layout.fragment_list, container, false);
    }
</code>```

As i said, the app doesn't crash and the interface works, but the listview is empty

答:
you are inflating a new view when you return the Fragment's view, at the last line of your onCreateView function return the view that inflated before , replace :

```<code>return inflater.inflate(R.layout.fragment_list, container, false);
</code>```

with :

```<code>return v;
</code>```

Body:
I'm using a fragment with a listview to show some elements from a firebase database. But it looks like the adapter doesn't work properly; i traced the code and everything looks working fine. Does anyone know where i have the error?

I tried getActivity().getBaseContext() and getContext() in the adapter context, but it also doesn't work

public class ListFragment extends Fragment implements View.OnClickListener{

    private RecyclerView rcv;
    private ListView lstvw;
    DatabaseReference ddbbr;

    public ListFragment() {
        // Required empty public constructor
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View v = inflater.inflate(R.layout.fragment_list, container, false);
        lstvw = v.findViewById(R.id.lstvwlistamini);
        ddbbr = FirebaseDatabase.getInstance().getReference("juegos");
        ddbbr.addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(@NonNull DataSnapshot dataSnapshot) {

                ArrayAdapter<String> adapter;
                ArrayList<String> list = new ArrayList<String>();

                for (DataSnapshot datasnapshot: dataSnapshot.getChildren()) {

                    Juego juego =  datasnapshot.getValue(Juego.class);

                    String titulo = juego.getTitulo();
                    list.add(titulo);
                    Toast toast = Toast.makeText(getContext(),list.get(0).toString(),Toast.LENGTH_LONG);
                    toast.show();

                }
                adapter = new ArrayAdapter<String>(getActivity(),android.R.layout.simple_list_item_1,list);
                lstvw.setAdapter(adapter);

            }

            @Override
            public void onCancelled(@NonNull DatabaseError databaseError) {

            }
        });

        // Inflate the layout for this fragment
        return inflater.inflate(R.layout.fragment_list, container, false);
    }

As i said, the app doesn't crash and the interface works, but the listview is empty

Body:
you are inflating a new view when you return the Fragment's view, at the last line of your onCreateView function return the view that inflated before , replace :

return inflater.inflate(R.layout.fragment_list, container, false);

with :

return v;


问:
What is the Best practice for try catch blocks to create clean code?

Possible Duplicate:

  Best practices for exception management in JAVA or C#

I've read a question earlier today on stackoverflow and it made me think about what is the best practice for handling exceptions.

So, my question is what is the best practice to handle exceptions to produce clean and high quality code.

Here is my code, I think it's quiet straight forward but please let me know if I'm wrong or not clear!
I've tried to keep in mind testability and same abstraction level in methods.

Every constructive comment is welcomed. :)

```<code>import java.awt.Point;
import java.io.Closeable;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.google.common.base.Preconditions;

/**
 * <p>This is a dummy code.</p>
 * The aim is present the best practice on exception separation and handling.
 */
public class ExceptionHandlingDemo {
    // System.out is not a good practice. Using logger is good for testing too (can be checked if the expected error messages are produced).
    private Logger logger = LoggerFactory.getLogger(ExceptionHandlingDemo.class);

    // instance of cannot work with List<Point>
    private interface PointList extends List<Point> {}

    /**
     * The method that loads a list of points from a file.
     * @param path - The path and the name of the file to be loaded.
     * Precondition: path cannot be {@code null}. In such case {@link NullPointerException} will be thrown.
     * Postcondition: if the file don't exist, some IOException occurs or the file doesn't contain the list the returned object is {@code null}.
     * */
    /* (Google throws NullpointerExceptio) since it is not forbidden for the developers to throw it. I know this is arguable but this is out of topic for now. */
    public List<Point> loadPointList(final String path) {
        Preconditions.checkNotNull(path, "The path of the file cannot be null");

        List<Point> pointListToReturn = null;
        ObjectInputStream in = null;

        try {
            in = openObjectInputStream(path);
            pointListToReturn = readPointList(in);
        } catch (final Throwable throwable) {
            handleException(throwable);
        } finally {
            close(in);
        }

        return pointListToReturn;
    }

    /*======== Private helper methods by now ========*/

    private ObjectInputStream openObjectInputStream(final String filename) throws FileNotFoundException, IOException {
        return new ObjectInputStream(new FileInputStream(filename));
    }

    private List<Point> readPointList(final ObjectInputStream objectInputStream) throws IOException, ClassNotFoundException {
        final Object object = objectInputStream.readObject();

        List<Point> ret = null;

        if (object instanceof PointList) {
            ret = (PointList) object;
        }
        return ret;
    }

    private void handleException(final Throwable throwable) {
        // I don't know the best practice here ...
        logger.error(throwable.toString());
    }

    private void close(final Closeable closeable) {
        if (closeable != null) {
            try {
                closeable.close();
            } catch (IOException e) {
                logger.error("Failed closing: %s", closeable);
            }
        }
    }

    /*======== Getters and setters by now. ========*/

    // ...

    /**
     * @param args
     */
    public static void main(String[] args) {
        ExceptionHandlingDemo test = new ExceptionHandlingDemo();
        test.loadPointList("test-filename.ext");
    }
}
</code>```

EDITED:

What I want to avoid is writing lot of catch cases after each other...

答:
For checked exceptions that I'm not going to bother, I always use org.apache.commons.lang.UnhandledException.

For example

```<code>/**
 * Calls Thread.sleep(millis)
 */
public static void threadSleep(final long millis) {
    try {
        Thread.sleep(millis);
    } catch (final InterruptedException e) {
        throw new UnhandledException(e);
    }
}
</code>```

Body:
Possible Duplicate:

  Best practices for exception management in JAVA or C#

I've read a question earlier today on stackoverflow and it made me think about what is the best practice for handling exceptions.

So, my question is what is the best practice to handle exceptions to produce clean and high quality code.

Here is my code, I think it's quiet straight forward but please let me know if I'm wrong or not clear!
I've tried to keep in mind testability and same abstraction level in methods.

Every constructive comment is welcomed. :)

import java.awt.Point;
import java.io.Closeable;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.google.common.base.Preconditions;

/**
 *
This is a dummy code.

 * The aim is present the best practice on exception separation and handling.
 */
public class ExceptionHandlingDemo {
    // System.out is not a good practice. Using logger is good for testing too (can be checked if the expected error messages are produced).
    private Logger logger = LoggerFactory.getLogger(ExceptionHandlingDemo.class);

    // instance of cannot work with List<Point>
    private interface PointList extends List<Point> {}

    /**
     * The method that loads a list of points from a file.
     * @param path - The path and the name of the file to be loaded.
     * Precondition: path cannot be {@code null}. In such case {@link NullPointerException} will be thrown.
     * Postcondition: if the file don't exist, some IOException occurs or the file doesn't contain the list the returned object is {@code null}.
     * */
    /* (Google throws NullpointerExceptio) since it is not forbidden for the developers to throw it. I know this is arguable but this is out of topic for now. */
    public List<Point> loadPointList(final String path) {
        Preconditions.checkNotNull(path, "The path of the file cannot be null");

        List<Point> pointListToReturn = null;
        ObjectInputStream in = null;

        try {
            in = openObjectInputStream(path);
            pointListToReturn = readPointList(in);
        } catch (final Throwable throwable) {
            handleException(throwable);
        } finally {
            close(in);
        }

        return pointListToReturn;
    }

    /*======== Private helper methods by now ========*/

    private ObjectInputStream openObjectInputStream(final String filename) throws FileNotFoundException, IOException {
        return new ObjectInputStream(new FileInputStream(filename));
    }

    private List<Point> readPointList(final ObjectInputStream objectInputStream) throws IOException, ClassNotFoundException {
        final Object object = objectInputStream.readObject();

        List<Point> ret = null;

        if (object instanceof PointList) {
            ret = (PointList) object;
        }
        return ret;
    }

    private void handleException(final Throwable throwable) {
        // I don't know the best practice here ...
        logger.error(throwable.toString());
    }

    private void close(final Closeable closeable) {
        if (closeable != null) {
            try {
                closeable.close();
            } catch (IOException e) {
                logger.error("Failed closing: %s", closeable);
            }
        }
    }

    /*======== Getters and setters by now. ========*/

    // ...

    /**
     * @param args
     */
    public static void main(String[] args) {
        ExceptionHandlingDemo test = new ExceptionHandlingDemo();
        test.loadPointList("test-filename.ext");
    }
}

EDITED:

What I want to avoid is writing lot of catch cases after each other...

Body:
For checked exceptions that I'm not going to bother, I always use org.apache.commons.lang.UnhandledException.

For example

/**
 * Calls Thread.sleep(millis)
 */
public static void threadSleep(final long millis) {
    try {
        Thread.sleep(millis);
    } catch (final InterruptedException e) {
        throw new UnhandledException(e);
    }
}


问:
c# linq if item is in list and get matching items from list
If my list contains: english cat, french cat, japanese dog, spanish dog

and I have an item: dog

Not only do I want to see if the list contains my item, but return the items that match, so I would expect: japanese dog, spanish dog

I have got as far as seeing if the item is in the list using the following code:

```<code>if (myList.Any(myItem.ToLower().Contains)) { }
</code>```

答:
I like to use regex and to do that such as for dogs:

```<code>var animals = new List<string>()
               { "japanese dog", "spanish dog", "english cat", "french cat" };

var dogs = animals.Where(type => Regex.IsMatch(type, "dog", RegexOptions.IgnoreCase))
                  .ToList();

// Returns {"japanese dog",  "spanish dog" }
</code>```

Why Regex you may ask, because its flexible and powerful...let me show:

Let us do some more advance linq work by having them sorted using the ToLookup extension and regex such as

```<code>var sortedbyDogs
            = animals.ToLookup(type => Regex.IsMatch(type, "dog", RegexOptions.IgnoreCase));
</code>```

which is grouped in memory like this:

Then just extract cats such as

```<code>var cats = sortedbyDogs[false].ToList()
</code>```

then pass in true for dogs.

But why split it by a boolean, what if there are more animals? Lets add a lemur to the list such as … "french cat", "Columbian Lemur" }; we do this:

```<code>var sorted = animals.ToLookup(type => Regex.Match(type,
                                                  "(dog|cat|lemur)",
                                                  RegexOptions.IgnoreCase).Value);
</code>```

Then to get our cats, here is the code:

sorted["cat"].ToList()

Body:
If my list contains: english cat, french cat, japanese dog, spanish dog

and I have an item: dog

Not only do I want to see if the list contains my item, but return the items that match, so I would expect: japanese dog, spanish dog

I have got as far as seeing if the item is in the list using the following code:

if (myList.Any(myItem.ToLower().Contains)) { }

Body:
I like to use regex and to do that such as for dogs:

var animals = new List<string>()
               { "japanese dog", "spanish dog", "english cat", "french cat" };

var dogs = animals.Where(type => Regex.IsMatch(type, "dog", RegexOptions.IgnoreCase))
                  .ToList();

// Returns {"japanese dog",  "spanish dog" }

Why Regex you may ask, because its flexible and powerful...let me show:

Let us do some more advance linq work by having them sorted using the ToLookup extension and regex such as

var sortedbyDogs
            = animals.ToLookup(type => Regex.IsMatch(type, "dog", RegexOptions.IgnoreCase));

which is grouped in memory like this:

Then just extract cats such as

var cats = sortedbyDogs[false].ToList()

then pass in true for dogs.

But why split it by a boolean, what if there are more animals? Lets add a lemur to the list such as … "french cat", "Columbian Lemur" }; we do this:

var sorted = animals.ToLookup(type => Regex.Match(type,
                                                  "(dog|cat|lemur)",
                                                  RegexOptions.IgnoreCase).Value);

Then to get our cats, here is the code:

sorted["cat"].ToList()


问:
How to write reusable javascript function with cypress commands
I am new to cypress and testing. I need to get the visible text from an element in cypress also store it inside a variable. with selenium we can easily get element value using getText() method. But in cypress we need to use a code like below.

HTML element:

```<code><div class='myClass'>this is text</div>
</code>```

javascript reusable function

```<code>function getText(byclassName)
    {
     let campaign;
        cy.get(byclassName)
        .invoke('text').then((text) => {
          campaign = text
          cy.log('campaign',  text)
          return text
        })
    }
</code>```

then my cypress test goes like this

```<code> it('finds the role', () => {
   const elementText= getText('.myClass')//fails
    cy.log('campaign',  getText('.myClass'))
 }) // it fails
</code>```

Please tell me what am I missing here? I want to write a generic function which returns me the visible text from div element and also store it or log it in console.

答:
You are returning the value inside your Promise function. Promises however can't return values, they can only resolve with a value. This means you'll have to use Promises throughout your code like this:</p>

```<code>function getText(byclassName) {
    return new Promise((resolve, reject) => {
        cy.get(byclassName).invoke('text')
            .then(campaign => {
                cy.log('campaign', campaign);
                resolve(campaign);
            });
    });
}

it('finds the role', function () {
    cy.visit(...);

    return getText('.myClass').then(elementText => {
        cy.log('campaign', elementText);

        expect(elementText).to.equal(...);
    });
})
</code>```

Body:
I am new to cypress and testing. I need to get the visible text from an element in cypress also store it inside a variable. with selenium we can easily get element value using getText() method. But in cypress we need to use a code like below.

HTML element:

this is text

javascript reusable function

function getText(byclassName)
    {
     let campaign;
        cy.get(byclassName)
        .invoke('text').then((text) => {
          campaign = text
          cy.log('campaign',  text)
          return text
        })
    }

then my cypress test goes like this

 it('finds the role', () => {
   const elementText= getText('.myClass')//fails
    cy.log('campaign',  getText('.myClass'))
 }) // it fails

Please tell me what am I missing here? I want to write a generic function which returns me the visible text from div element and also store it or log it in console.

Body:
You are returning the value inside your Promise function. Promises however can't return values, they can only resolve with a value. This means you'll have to use Promises throughout your code like this:

function getText(byclassName) {
    return new Promise((resolve, reject) => {
        cy.get(byclassName).invoke('text')
            .then(campaign => {
                cy.log('campaign', campaign);
                resolve(campaign);
            });
    });
}

it('finds the role', function () {
    cy.visit(...);

    return getText('.myClass').then(elementText => {
        cy.log('campaign', elementText);

        expect(elementText).to.equal(...);
    });
})


问:
Purpose of Unions in C and C++
I have used unions earlier comfortably; today I was alarmed when I read this post and came to know that this code

```<code>union ARGB
{
    uint32_t colour;

    struct componentsTag
    {
        uint8_t b;
        uint8_t g;
        uint8_t r;
        uint8_t a;
    } components;

} pixel;

pixel.colour = 0xff040201;  // ARGB::colour is the active member from now on

// somewhere down the line, without any edit to pixel

if(pixel.components.a)      // accessing the non-active member ARGB::components
</code>```

is actually undefined behaviour I.e. reading from a member of the union other than the one recently written to leads to undefined behaviour. If this isn't the intended usage of unions, what is? Can some one please explain it elaborately?

Update:

I wanted to clarify a few things in hindsight.

The answer to the question isn't the same for C and C++; my ignorant younger self tagged it as both C and C++.

After scouring through C++11's standard I couldn't conclusively say that it calls out accessing/inspecting a non-active union member is undefined/unspecified/implementation-defined. All I could find was §9.5/1:

If a standard-layout union contains several standard-layout structs that share a common initial sequence, and if an object of this standard-layout union type contains one of the standard-layout structs, it is permitted to inspect the common initial sequence of any of standard-layout struct members. §9.2/19: Two standard-layout structs share a common initial sequence if corresponding members have layout-compatible types and either neither member is a bit-field or both are bit-fields with the same width for a sequence of one or more initial members.

While in C, (C99 TC3 - DR 283 onwards) it's legal to do so (thanks to Pascal Cuoq for bringing this up). However, attempting to do it can still lead to undefined behavior, if the value read happens to be invalid (so called "trap representation") for the type it is read through. Otherwise, the value read is implementation defined.

C89/90 called this out under unspecified behavior (Annex J) and K&R's book says it's implementation defined. Quote from K&R:

This is the purpose of a union - a single variable that can legitimately hold any of one of several types. [...] so long as the usage is consistent: the type retrieved must be the type most recently stored. It is the programmer's responsibility to keep track of which type is currently stored in a union; the results are implementation-dependent if something is stored as one type and extracted as another.

Extract from Stroustrup's TC++PL (emphasis mine)

Use of unions can be essential for compatness of data [...] sometimes misused for "type conversion".

Above all, this question (whose title remains unchanged since my ask) was posed with an intention of understanding the purpose of unions AND not on what the standard allows E.g. Using inheritance for code reuse is, of course, allowed by the C++ standard, but it wasn't the purpose or the original intention of introducing inheritance as a C++ language feature. This is the reason Andrey's answer continues to remain as the accepted one.

答:
As others mentioned, unions combined with enumerations and wrapped into structs can be used to implement tagged unions. One practical use is to implement Rust's Result<T, E>, which is originally implemented using a pure enum (Rust can hold additional data in enumeration variants). Here is a C++ example:

```<code>template <typename T, typename E> struct Result {
    public:
    enum class Success : uint8_t { Ok, Err };
    Result(T val) {
        m_success = Success::Ok;
        m_value.ok = val;
    }
    Result(E val) {
        m_success = Success::Err;
        m_value.err = val;
    }
    inline bool operator==(const Result& other) {
        return other.m_success == this->m_success;
    }
    inline bool operator!=(const Result& other) {
        return other.m_success != this->m_success;
    }
    inline T expect(const char* errorMsg) {
        if (m_success == Success::Err) throw errorMsg;
        else return m_value.ok;
    }
    inline bool is_ok() {
        return m_success == Success::Ok;
    }
    inline bool is_err() {
        return m_success == Success::Err;
    }
    inline const T* ok() {
        if (is_ok()) return m_value.ok;
        else return nullptr;
    }
    inline const T* err() {
        if (is_err()) return m_value.err;
        else return nullptr;
    }

    // Other methods from https://doc.rust-lang.org/std/result/enum.Result.html

    private:
    Success m_success;
    union _val_t { T ok; E err; } m_value;
}
</code>```

Title: Purpose of Unions in C and C++

Body:
I have used unions earlier comfortably; today I was alarmed when I read this post and came to know that this code

union ARGB
{
    uint32_t colour;

    struct componentsTag
    {
        uint8_t b;
        uint8_t g;
        uint8_t r;
        uint8_t a;
    } components;

} pixel;

pixel.colour = 0xff040201;  // ARGB::colour is the active member from now on

// somewhere down the line, without any edit to pixel

if(pixel.components.a)      // accessing the non-active member ARGB::components

is actually undefined behaviour I.e. reading from a member of the union other than the one recently written to leads to undefined behaviour. If this isn't the intended usage of unions, what is? Can some one please explain it elaborately?

Update:

I wanted to clarify a few things in hindsight.

The answer to the question isn't the same for C and C++; my ignorant younger self tagged it as both C and C++.

After scouring through C++11's standard I couldn't conclusively say that it calls out accessing/inspecting a non-active union member is undefined/unspecified/implementation-defined. All I could find was §9.5/1:

If a standard-layout union contains several standard-layout structs that share a common initial sequence, and if an object of this standard-layout union type contains one of the standard-layout structs, it is permitted to inspect the common initial sequence of any of standard-layout struct members. §9.2/19: Two standard-layout structs share a common initial sequence if corresponding members have layout-compatible types and either neither member is a bit-field or both are bit-fields with the same width for a sequence of one or more initial members.

While in C, (C99 TC3 - DR 283 onwards) it's legal to do so (thanks to Pascal Cuoq for bringing this up). However, attempting to do it can still lead to undefined behavior, if the value read happens to be invalid (so called "trap representation") for the type it is read through. Otherwise, the value read is implementation defined.

C89/90 called this out under unspecified behavior (Annex J) and K&R's book says it's implementation defined. Quote from K&R:

This is the purpose of a union - a single variable that can legitimately hold any of one of several types. [...] so long as the usage is consistent: the type retrieved must be the type most recently stored. It is the programmer's responsibility to keep track of which type is currently stored in a union; the results are implementation-dependent if something is stored as one type and extracted as another.

Extract from Stroustrup's TC++PL (emphasis mine)

Use of unions can be essential for compatness of data [...] sometimes misused for "type conversion".

Above all, this question (whose title remains unchanged since my ask) was posed with an intention of understanding the purpose of unions AND not on what the standard allows E.g. Using inheritance for code reuse is, of course, allowed by the C++ standard, but it wasn't the purpose or the original intention of introducing inheritance as a C++ language feature. This is the reason Andrey's answer continues to remain as the accepted one.

Body:
As others mentioned, unions combined with enumerations and wrapped into structs can be used to implement tagged unions. One practical use is to implement Rust's Result<T, E>, which is originally implemented using a pure enum (Rust can hold additional data in enumeration variants). Here is a C++ example:

template <typename T, typename E> struct Result {
    public:
    enum class Success : uint8_t { Ok, Err };
    Result(T val) {
        m_success = Success::Ok;
        m_value.ok = val;
    }
    Result(E val) {
        m_success = Success::Err;
        m_value.err = val;
    }
    inline bool operator==(const Result& other) {
        return other.m_success == this->m_success;
    }
    inline bool operator!=(const Result& other) {
        return other.m_success != this->m_success;
    }
    inline T expect(const char* errorMsg) {
        if (m_success == Success::Err) throw errorMsg;
        else return m_value.ok;
    }
    inline bool is_ok() {
        return m_success == Success::Ok;
    }
    inline bool is_err() {
        return m_success == Success::Err;
    }
    inline const T* ok() {
        if (is_ok()) return m_value.ok;
        else return nullptr;
    }
    inline const T* err() {
        if (is_err()) return m_value.err;
        else return nullptr;
    }

    // Other methods from https://doc.rust-lang.org/std/result/enum.Result.html

    private:
    Success m_success;
    union _val_t { T ok; E err; } m_value;
}


问:
self.navigationController is nil during state restoration
After implementing state restoration in my app I am having difficulty with my view controllers.

My issue is that in viewDidLoad of the view controller I am attempting to restore the self.naigationController property, which is nil.

I have set breakpoints in the viewDidLoad method of each view controller that comes before the one I am trying to restore. In the first view controller, the navigation controller is found. In every one after that, including the one I am trying to restore, the navigation controller is nil.

This is causing bugs where I cannot set the navigation bar visibility, views are misplaced, etc.

Does anyone have an idea why this might be?

答: The navigationController property searches up the parentViewControllers to find one of class UINavigationController. Only view controllers loaded from the storyboard can find their navigation controller at the viewDidLoad time (and in awakeFromNib). It is likely you are instantiating a new instance of the view controller during the restore process rather than using the one that was created by the storyboard. The solution is either to help the restore process find the existing view controller if it has changed paths e.g. because of split controller orientation change (via viewControllerForRestorationPathComponents in your app delegate) although that comes with its own set of issues, or make your view controller work by not requiring the nav controller in the viewDidLoad, e.g. put it in the viewWillAppear as others have suggested.


问:
How to use Malloc Debug for checking native memory leaks?
I am exploring several options to figure out the best tool/way to find out memory leaks in native code in android app. As part of this exercise, I came across the option present in following url.

https://android.googlesource.com/platform/bionic/+/master/libc/malloc_debug/README_marshmallow_and_earlier.md

I wrote a sample app which calls a native function written in shared library. I put memory leak intentionally in this native function. Before running the app, I did

adb shell setprop libc.debug.malloc.program

adb shell setprop libc.debug.malloc 10

Then I started the app. But I could not see any prints in the logcat indicating memory leak.

If anybody has ever used this approach to find out the native memory leaks, could you please tell me if I am missing some thing. Is the logcat logs correct place to look for the leak messages? If not, how should I find the leak information?

答:
You are supposed to set backtrace based on the version your application has.

Try this command:

```<code>adb shell setprop libc.debug.malloc.options backtrace
</code>```

Then take dumpheap.

Body:
You are supposed to set backtrace based on the version your application has.

Try this command:

adb shell setprop libc.debug.malloc.options backtrace

Then take dumpheap.


问:
How can I remove the first and last Node from doubly linked list?
I have a homework to write a method that will remove the FIRST Node and return its value in a doubly linked list in O(1), and one more method to remove the LAST Node in doubly linked list and return its value in O(1). This is what I did so far.</p>

```<code>class DoubleList<T>
{
    DNode _start;
    DNode _end;

    public void AddFirst(T value)
    {
        DNode tmp = new DNode(value);
        tmp._next = _start;
        tmp._prev = null;
        if (_start != null)
        {
            _start._prev = tmp;
        }
        _start = tmp;
        if (_start._next == null)
            _end = tmp;
    }

    public void AddLast(DoubleList<T> doubleyList, T value)
    {
        DNode tmp = new DNode(value);
        if (_start == null)
        {
            AddFirst(value);
            return;
        }
        DNode lastNode = GetLastNode(doubleyList);
        lastNode._next = tmp;
        tmp._prev = lastNode;
        _end._next = tmp;
        _end = tmp;
    }
}
</code>```

答:
Here's a quick solution I came out with, trying to use your syntax:</p>

```<code>public DNode RemoveHead()
{
    // "Save" the current head to return it at the end
    DNode head = _start;

    if (_start != null)
    {
        // The start becomes the element next to the current one
        _start = _start._next;

        // The first node has to have no "previous" one
        if (_start != null) _start._prev = null;
    }

    return head;
}

public DNode RemoveTail()
{
    // "Save" the current tail to return it at the end
    DNode tail = _end;

    if (_end != null)
    {
        // The end becomes the element previous to the current one
        _end = _end._prev;

        // The last node has to have no "next" one
        if (_end != null) _end._next = null;
    }

    return tail;
}
</code>```

Body:
I have a homework to write a method that will remove the FIRST Node and return its value in a doubly linked list in O(1), and one more method to remove the LAST Node in doubly linked list and return its value in O(1). This is what I did so far.

class DoubleList<T>
{
    DNode _start;
    DNode _end;

    public void AddFirst(T value)
    {
        DNode tmp = new DNode(value);
        tmp._next = _start;
        tmp._prev = null;
        if (_start != null)
        {
            _start._prev = tmp;
        }
        _start = tmp;
        if (_start._next == null)
            _end = tmp;
    }

    public void AddLast(DoubleList<T> doubleyList, T value)
    {
        DNode tmp = new DNode(value);
        if (_start == null)
        {
            AddFirst(value);
            return;
        }
        DNode lastNode = GetLastNode(doubleyList);
        lastNode._next = tmp;
        tmp._prev = lastNode;
        _end._next = tmp;
        _end = tmp;
    }
}

Body:
Here's a quick solution I came out with, trying to use your syntax:

public DNode RemoveHead()
{
    // "Save" the current head to return it at the end
    DNode head = _start;

    if (_start != null)
    {
        // The start becomes the element next to the current one
        _start = _start._next;

        // The first node has to have no "previous" one
        if (_start != null) _start._prev = null;
    }

    return head;
}

public DNode RemoveTail()
{
    // "Save" the current tail to return it at the end
    DNode tail = _end;

    if (_end != null)
    {
        // The end becomes the element previous to the current one
        _end = _end._prev;

        // The last node has to have no "next" one
        if (_end != null) _end._next = null;
    }

    return tail;
}


问:
keep screen and data state with Angular 7
I need to know a way to keep the current state of my component in Angular when I leave the screen and navigate to another screen.

In my component I have a counter that displays the duration of a service that the user is currently performing, I also have a form with several information about the service that is being performed.

When I exit the screen display and navigate to another screen, the counter can not reset, and the entire screen display should be the same as it was before I left and navigated to another route.

I would also like the state to be maintained when I close the tab and open again and the duration time continues even though I am not having the application open.

The duration should only stop when I click on finalize, I can close the application and open again, the state of the screen with the information will always be maintained and the duration never stops until I end the attendance.

Example.:

Duration before closing application. 00:10:00

10 minutes after closing application and opening again. 00:20:00

How can I do this? Since the life cycle of the components in Angular?

答:
you need to implement your custom RouteReuseStrategy

app-routing-cache.ts

```<code>import {
    RouteReuseStrategy,
    DefaultUrlSerializer,
    ActivatedRouteSnapshot,
    DetachedRouteHandle
} from '@angular/router';

export class AppRoutingCache implements RouteReuseStrategy {
    routesToCache: string[] = ['my-route1']; // add your routes to cache here
    storedRouteHandles = new Map<string, DetachedRouteHandle>();

    shouldDetach(route: ActivatedRouteSnapshot): boolean {
        return this.routesToCache.indexOf(route.routeConfig.path) > -1;
    }

    store(route: ActivatedRouteSnapshot, handle: DetachedRouteHandle): void {
        this.storedRouteHandles.set(route.routeConfig.path, handle);
    }

    shouldAttach(route: ActivatedRouteSnapshot): boolean {
        return this.storedRouteHandles.has(route.routeConfig.path);
    }

    retrieve(route: ActivatedRouteSnapshot): DetachedRouteHandle {
        return this.storedRouteHandles.get(route.routeConfig.path);
    }

    shouldReuseRoute(future: ActivatedRouteSnapshot, curr: ActivatedRouteSnapshot): boolean {
        return future.routeConfig === curr.routeConfig;
    }
}
</code>```

in app.moudle

```<code>providers: [
  ...
  { provide: RouteReuseStrategy, useClass: AppRoutingCache }

]
</code>```

Body:
you need to implement your custom RouteReuseStrategy

app-routing-cache.ts

import {
    RouteReuseStrategy,
    DefaultUrlSerializer,
    ActivatedRouteSnapshot,
    DetachedRouteHandle
} from '@angular/router';

export class AppRoutingCache implements RouteReuseStrategy {
    routesToCache: string[] = ['my-route1']; // add your routes to cache here
    storedRouteHandles = new Map<string, DetachedRouteHandle>();

    shouldDetach(route: ActivatedRouteSnapshot): boolean {
        return this.routesToCache.indexOf(route.routeConfig.path) > -1;
    }

    store(route: ActivatedRouteSnapshot, handle: DetachedRouteHandle): void {
        this.storedRouteHandles.set(route.routeConfig.path, handle);
    }

    shouldAttach(route: ActivatedRouteSnapshot): boolean {
        return this.storedRouteHandles.has(route.routeConfig.path);
    }

    retrieve(route: ActivatedRouteSnapshot): DetachedRouteHandle {
        return this.storedRouteHandles.get(route.routeConfig.path);
    }

    shouldReuseRoute(future: ActivatedRouteSnapshot, curr: ActivatedRouteSnapshot): boolean {
        return future.routeConfig === curr.routeConfig;
    }
}

in app.moudle

providers: [
  ...
  { provide: RouteReuseStrategy, useClass: AppRoutingCache }

]


问:
Iphone dev : how can I get a result from google currency converter?
Sorry for my english ^^
I would know how I can have a result from the google converter tool for currency, available on http://www.google.com/finance/converter?a=1&from=USD&to=GBP for example.

I have already tried something like that :

```<code>    -(IBAction)getResponse:(id) sender{

     NSString *myURLString = @"http://www.google.com/finance/converter?a=1&from=USD&to=GBP";

     NSURL *myURL =  [NSURL URLWithString: myURLString];

     NSData *data = [NSData alloc];

     data=[NSData dataWithContentsOfURL:myURL];

     if(data!=nil && data != ""){

          NSString *response = [[[NSString alloc] initWithData:data]]

          [label setText: response];

     }

     else [label setText:@"not working"];
}
</code>```

But when I click on my button, the label does not have a text (it is like it is empty).
Am I doing something wrong ?
Is it possible what I want to do ?
Thank you very much for your futures answers !
Olivier.

答:
Yeah.. It is possible...
See the data that you are getting is an HTML file or can be treated as xml. Just parse that xml file and get the result. There ia lot of things in that file but you have to only extract

```<code><div id=currency_converter_result>1 USD = <span class=bld>0.6118 GBP</span>
</code>```

Hey try this URL
http://www.google.com/ig/calculator?hl=en&q=1USD=?INR

This URL will return the JSON

{lhs: "1 U.S. dollar",rhs: "44.5097254 Indian rupees",error: "",icc: true}

Just parse it. :)

Body:
Sorry for my english ^^
I would know how I can have a result from the google converter tool for currency, available on http://www.google.com/finance/converter?a=1&from=USD&to=GBP for example.

I have already tried something like that :

    -(IBAction)getResponse:(id) sender{

     NSString *myURLString = @"http://www.google.com/finance/converter?a=1&from=USD&to=GBP";

     NSURL *myURL =  [NSURL URLWithString: myURLString];

     NSData *data = [NSData alloc];

     data=[NSData dataWithContentsOfURL:myURL];

     if(data!=nil && data != ""){

          NSString *response = [[[NSString alloc] initWithData:data]]

          [label setText: response];

     }

     else [label setText:@"not working"];
}

But when I click on my button, the label does not have a text (it is like it is empty).
Am I doing something wrong ?
Is it possible what I want to do ?
Thank you very much for your futures answers !
Olivier.

Body:
Yeah.. It is possible...
See the data that you are getting is an HTML file or can be treated as xml. Just parse that xml file and get the result. There ia lot of things in that file but you have to only extract

<div id=currency_converter_result>1 USD = <span class=bld>0.6118 GBP</span>

Hey try this URL
http://www.google.com/ig/calculator?hl=en&q=1USD=?INR

This URL will return the JSON

{lhs: "1 U.S. dollar",rhs: "44.5097254 Indian rupees",error: "",icc: true}

Just parse it. :)


问:
Interpreting Results From Explain Analyze in Postgres
Recently did a query which took about 9 minutes to complete. Attempting to determine why, I used EXPLAIN ANALYZE to help solve the problem. From the output, it looks as though everything has the appropriate indexes, it's just taking an extremely long time.

I've put the query and the results below. Is it just taking this long due to the amount of data? Or is there something which I am doing wrong. Does my query need to fundamentally change, in order to improve the performance?

Additional Info: PostgreSQL 10.6. System in a Xeon @ 3.4Ghz, with SSD and 24GB of memory, so it's fairly good spec desktop.

```<code>SELECT      s.start_date, s.end_date, s.resources, s.activity_index, r.resource_id, sa.usedresourceset
FROM        rm_o_resource_usage_instance_splits_new s
INNER JOIN  rm_o_resource_usage r ON s.usage_id = r.id
INNER JOIN  scheduledactivities sa ON s.activity_index = sa.activity_index
    AND r.schedule_id = sa.solution_id
    and s.solution = sa.solution_id
WHERE       r.schedule_id = 14349
ORDER BY   r.resource_id, s.start_date
----------------------------------------------------------------
"Sort  (cost=18.01..18.01 rows=1 width=86) (actual time=541075.198..541099.504 rows=65354 loops=1)"
"  Sort Key: r.resource_id, s.start_date"
"  Sort Method: external merge  Disk: 8016kB"
"  ->  Nested Loop  (cost=0.85..18.00 rows=1 width=86) (actual time=6.946..540671.934 rows=65354 loops=1)"
"        Join Filter: (s.activity_index = sa.activity_index)"
"        Rows Removed by Join Filter: 3550029280"
"        ->  Nested Loop  (cost=0.42..12.93 rows=1 width=98) (actual time=0.074..1795.054 rows=65354 loops=1)"
"              Join Filter: (s.usage_id = r.id)"
"              Rows Removed by Join Filter: 248018"
"              ->  Index Scan using rm_o_resource_usage_instance_splits_new_solution_idx on rm_o_resource_usage_instance_splits_new s  (cost=0.42..4.76 rows=1 width=69) (actual time=0.032..36.395 rows=65354 loops=1)"
"                    Index Cond: (solution = 14349)"
"              ->  Seq Scan on rm_o_resource_usage r  (cost=0.00..8.15 rows=2 width=45) (actual time=0.018..0.019 rows=5 loops=65354)"
"                    Filter: (schedule_id = 14349)"
"                    Rows Removed by Filter: 332"
"        ->  Index Scan using scheduled_activities_idx on scheduledactivities sa  (cost=0.42..5.06 rows=1 width=16) (actual time=0.007..4.937 rows=54321 loops=65354)"
"              Index Cond: (solution_id = 14349)"
"Planning time: 1.547 ms"
"Execution time: 541104.491 ms"
</code>```

答:
Looking at your query exec plan a lot of time is spent on sorting

```<code>    "Sort  (cost=18.01..18.01 rows=1 width=86) (actual time=541075.198..541099.504 rows=65354 loops=1)"
"  Sort Key: r.resource_id, s.start_date"
"  Sort Method: external merge  Disk: 8016kB"
</code>```

I would recommend you  to increase work_mem param for PostgreSQL as described here

If you do a lot of complex sorts, and have a lot of memory, then increasing the work_mem parameter allows PostgreSQL to do larger
  in-memory sorts which, unsurprisingly, will be faster than disk-based
  equivalents.

This size is applied to each and every sort done by each user, and
  complex queries can use multiple working memory sort buffers. Set it
  to 50MB, and have 30 users submitting queries, and you are soon using
  1.5GB of real memory. Furthermore, if a query involves doing merge sorts of 8 tables, that requires 8 times work_mem. You need to
  consider what you set max_connections to in order to size this
  parameter correctly. This is a setting where data warehouse systems,
  where users are submitting very large queries, can readily make use of
  many gigabytes of memory.

log_temp_files can be used to log sorts, hashes, and temp files which
  can be useful in figuring out if sorts are spilling to disk instead of
  fitting in memory. You can see sorts spilling to disk using EXPLAIN
  ANALYZE plans as well. For example, if you see a line like Sort
  Method: external merge Disk: 7526kB in the output of EXPLAIN ANALYZE,
  a work_mem of at least 8MB would keep the intermediate data in memory
  and likely improve the query response time (although it may take
  substantially more than 8MB to do the sort entirely in memory, as data
  on disk is stored in a more compact format).

Body:
Recently did a query which took about 9 minutes to complete. Attempting to determine why, I used EXPLAIN ANALYZE to help solve the problem. From the output, it looks as though everything has the appropriate indexes, it's just taking an extremely long time.

I've put the query and the results below. Is it just taking this long due to the amount of data? Or is there something which I am doing wrong. Does my query need to fundamentally change, in order to improve the performance?

Additional Info: PostgreSQL 10.6. System in a Xeon @ 3.4Ghz, with SSD and 24GB of memory, so it's fairly good spec desktop.

SELECT      s.start_date, s.end_date, s.resources, s.activity_index, r.resource_id, sa.usedresourceset
FROM        rm_o_resource_usage_instance_splits_new s
INNER JOIN  rm_o_resource_usage r ON s.usage_id = r.id
INNER JOIN  scheduledactivities sa ON s.activity_index = sa.activity_index
    AND r.schedule_id = sa.solution_id
    and s.solution = sa.solution_id
WHERE       r.schedule_id = 14349
ORDER BY   r.resource_id, s.start_date
----------------------------------------------------------------
"Sort  (cost=18.01..18.01 rows=1 width=86) (actual time=541075.198..541099.504 rows=65354 loops=1)"
"  Sort Key: r.resource_id, s.start_date"
"  Sort Method: external merge  Disk: 8016kB"
"  ->  Nested Loop  (cost=0.85..18.00 rows=1 width=86) (actual time=6.946..540671.934 rows=65354 loops=1)"
"        Join Filter: (s.activity_index = sa.activity_index)"
"        Rows Removed by Join Filter: 3550029280"
"        ->  Nested Loop  (cost=0.42..12.93 rows=1 width=98) (actual time=0.074..1795.054 rows=65354 loops=1)"
"              Join Filter: (s.usage_id = r.id)"
"              Rows Removed by Join Filter: 248018"
"              ->  Index Scan using rm_o_resource_usage_instance_splits_new_solution_idx on rm_o_resource_usage_instance_splits_new s  (cost=0.42..4.76 rows=1 width=69) (actual time=0.032..36.395 rows=65354 loops=1)"
"                    Index Cond: (solution = 14349)"
"              ->  Seq Scan on rm_o_resource_usage r  (cost=0.00..8.15 rows=2 width=45) (actual time=0.018..0.019 rows=5 loops=65354)"
"                    Filter: (schedule_id = 14349)"
"                    Rows Removed by Filter: 332"
"        ->  Index Scan using scheduled_activities_idx on scheduledactivities sa  (cost=0.42..5.06 rows=1 width=16) (actual time=0.007..4.937 rows=54321 loops=65354)"
"              Index Cond: (solution_id = 14349)"
"Planning time: 1.547 ms"
"Execution time: 541104.491 ms"

Body:
Looking at your query exec plan a lot of time is spent on sorting

    "Sort  (cost=18.01..18.01 rows=1 width=86) (actual time=541075.198..541099.504 rows=65354 loops=1)"
"  Sort Key: r.resource_id, s.start_date"
"  Sort Method: external merge  Disk: 8016kB"

I would recommend you  to increase work_mem param for PostgreSQL as described here

If you do a lot of complex sorts, and have a lot of memory, then increasing the work_mem parameter allows PostgreSQL to do larger
  in-memory sorts which, unsurprisingly, will be faster than disk-based
  equivalents.

This size is applied to each and every sort done by each user, and
  complex queries can use multiple working memory sort buffers. Set it
  to 50MB, and have 30 users submitting queries, and you are soon using
  1.5GB of real memory. Furthermore, if a query involves doing merge sorts of 8 tables, that requires 8 times work_mem. You need to
  consider what you set max_connections to in order to size this
  parameter correctly. This is a setting where data warehouse systems,
  where users are submitting very large queries, can readily make use of
  many gigabytes of memory.

log_temp_files can be used to log sorts, hashes, and temp files which
  can be useful in figuring out if sorts are spilling to disk instead of
  fitting in memory. You can see sorts spilling to disk using EXPLAIN
  ANALYZE plans as well. For example, if you see a line like Sort
  Method: external merge Disk: 7526kB in the output of EXPLAIN ANALYZE,
  a work_mem of at least 8MB would keep the intermediate data in memory
  and likely improve the query response time (although it may take
  substantially more than 8MB to do the sort entirely in memory, as data
  on disk is stored in a more compact format).


问:
How should I construct an Oracle function, or other code, to measure time for business processes between two records
I need suggestions for designing tables and records in Oracle to handle business processes, status, and report times between statuses.

We have a transaction table that records an serial numbered record id, a document id, a date and time, and a status.  Statuses reflect where a document is in the approval process, reflecting a task that needs to be done on a document.  There are up to 40 statuses, showing both who needs to approve and what is the task being done.  So there is a document header or parent record, and multiple status records as child records.

The challenge is to analyzes where bottlenecks are, which tasks are taking the longest, etc.

From a business pov, a task receives a document, we have the date and time this happens.  We do not have a release or finish date and time for a current task.  All we have is the next task's start date and time.  Note that a document can only have one status at a time.

For reasons I won't go into, we cannot use ETL to create an end date and time for a status, although I think that is the solution.

Part of the challenge is that statuses are not entirely consecutive or have a fixed order.  Some statuses can start, stop, and later in the process start again.

What I would like to report is the time, on a weekly or monthly basis, that each status record takes, time date time end minus date time start.  Can anyone suggest a function or other way to accomplish this?

I don't need specific code.  I could use some example in pseudo code or just in outline form of how to solve this.  Then I could figure out the code.

答:
You can use a trigger after insert and after update on  transaction table to record on a LOG_TABLE every change: id transaction, last status, new status, who approve, change date-time (maybe using TiMESTAMP data type is fractional seconds care), terminal, session ID, username.

For insert: you need to define a type of "insert status", diferent for other 40 statuses. For example, is status are of numeric type, a "insert status" can be "-1" (minus one), so last status is "-1" and new status is status of the inserted record on transaction table.

With this LOG_TABLE you can develop a package with functions to calculate time between changed status, display all changes, dispplay last change, etc.


问:
Logic behind creating a basketball simulator with Python
I am learning Python 3.x together with Flask. I'm also a Basketball fan, so I thought I'd be a good idea to get in the water and try to do a game simulator, perhaps only between two teams to begin with - and learn more Python along the way.

My biggest question for start is what should the logic behind the simulator be? Let's say I want to sim two historic teams - Lakers00 vs Bulls 98. Stats of the players are available online.

I want it to be "realistic," so perhaps getting into percentages of each player? If Jordan shot let's say 50% for the season - should that be programmed into each 'player' and then tell what's the chance that the % is higher or lower than that in each simulation? Should I use .json to store the data?

Or is there a completely different approach I should take?

Once the code is in, I would ideally try to turn that into a website with Flask. What database would you recommend to use?

Thank you

答:
I don't know JSON, but I'd start with keeping it simple, if you're still working on this.

1: Players should have at least the following fields:
         Breakdown of possession usage (TO, 2 Pt shot, 3 pt shot)
         2 pt shooting percentage, 3 pt shooting percentage
2: I'd probably start by including something like usage percentage

The simplest way to do it would be have a player class with those attributes. If you took the advice of #2 you could use a function to pull out which player used the possession, and what they did with it (2 pt shot, 3 pt shot, turnover, and whether the shot was successful). Defense, rebounds, fouls might be more for later versions of the game, but if you start with that you'll at least have something that resembles basketball. I think NBA games are roughly 100 possessions.


问:
How to replace a parent batch file?
I've got an applicationStart.bat file that calls this update.bat, and I need the update.bat to replace the applicationStart.bat with a new one.

The code of the applicationStart.bat is something like:

```<code>@echo off

call update.bat

java -Xms128m -Xmx256m com.foo.bar
</code>```

And the code of the update.bat is like:

```<code>@echo off

..\JRE\bin\jar.exe -xvf .\updateFile.jar
</code>```

I've already tried putting the applicationStart.bat inside de updateFile.jar, and on some machines it replace without error, but on other machines it will generate an error and abort the extraction.

The applicationStart.bat just remains being used for the rest of the day, when the application is being used, and in some cases, the user can shutdown the machine from the application, making things harder because I can't create another process to wait for the application to end and replace the applicationStart.bat afterwards.

How can I get this applicationStart.bat to be replaced?

答:
Applicationstart.bat:

```<code>@echo off
if "%~1"=="::" goto mainline
update.bat

:mainline
java -Xms128m -Xmx256m com.foo.bar
</code>```

update.bat

```<code>@echo off
..\JRE\bin\jar.exe -xvf .\updateFile.jar
applicationstart.bat ::
</code>```

:: is a longtime-used parameter-value for varying the behaviour of a batch file.

Another approach to Applicationstart.bat:

```<code>@echo off
%1 update.bat

java -Xms128m -Xmx256m com.foo.bar
</code>```

In this version, applicationstart.bat will substitute nothing for %1 hence execute update but when replaced and re-invoked will have :: (or rem) substituted for %1 and hence no run update.bat

Title: How to replace a parent batch file?

Body:
I've got an applicationStart.bat file that calls this update.bat, and I need the update.bat to replace the applicationStart.bat with a new one.

The code of the applicationStart.bat is something like:

@echo off

call update.bat

java -Xms128m -Xmx256m com.foo.bar

And the code of the update.bat is like:

@echo off

..\JRE\bin\jar.exe -xvf .\updateFile.jar

I've already tried putting the applicationStart.bat inside de updateFile.jar, and on some machines it replace without error, but on other machines it will generate an error and abort the extraction.

The applicationStart.bat just remains being used for the rest of the day, when the application is being used, and in some cases, the user can shutdown the machine from the application, making things harder because I can't create another process to wait for the application to end and replace the applicationStart.bat afterwards.

How can I get this applicationStart.bat to be replaced?

Body:
Applicationstart.bat:

@echo off
if "%~1"=="::" goto mainline
update.bat

:mainline
java -Xms128m -Xmx256m com.foo.bar

update.bat

@echo off
..\JRE\bin\jar.exe -xvf .\updateFile.jar
applicationstart.bat ::

:: is a longtime-used parameter-value for varying the behaviour of a batch file.

Another approach to Applicationstart.bat:

@echo off
%1 update.bat

java -Xms128m -Xmx256m com.foo.bar

In this version, applicationstart.bat will substitute nothing for %1 hence execute update but when replaced and re-invoked will have :: (or rem) substituted for %1 and hence no run update.bat


问:
Firebase iOS stuck at 'Run your app to verify installation'
React Native Firebase installation for iOS gets held up at the "Run your app to verify installation" screen.

React Native Firebase has worked on Android for me before.

I followed these instructions.

https://rnfirebase.io/docs/v5.x.x/installation/ios
https://firebase.google.com/docs/ios/setup#add_the_sdk

Here are what I've done so far.

-Set up a project within Firebase.google.com page.

-Create an iOS app there.

-Install react-native-firebase via npm.

-Add GoogleService-Info.plist file to the project within XCode.

-Make changes to ios/[YOUR APP NAME]/AppDelegate.m file.

-Creat a new Podfile (Cocoa pod) and updated it by "pod update" command.

-Add and edited lines to the Podfile per the instruction.

-Run "pod install"

-Run "react-native link react-native-firebase" from the project root.

-Click "Next" button within Firebase console and move on to "Run your app to verify installation" section.

-Run the iOS app on simulator by running "react-native run-ios" command.

The app boots up and functions as normal in the simulator.

Nothing happens in the Firebase page.

This is the first couple of lines of my Podfile.

```<code># Uncomment the next line to define a global platform for your
project
platform :ios, '9.0'

# Required by RNFirebase
pod 'Firebase/Core', '~> 5.20.1'

target 'My_App_Name' do
</code>```

答:
https://dev-yakuza.github.io/en/react-native/react-native-firebase-admob/

Check this guy's blog. In his particular case, he is integrating Firebase and Admob, but the first part is really descriptive on how to install and set the RNFirebase package.

Body:
React Native Firebase installation for iOS gets held up at the "Run your app to verify installation" screen.

React Native Firebase has worked on Android for me before.

I followed these instructions.

https://rnfirebase.io/docs/v5.x.x/installation/ios
https://firebase.google.com/docs/ios/setup#add_the_sdk

Here are what I've done so far.

-Set up a project within Firebase.google.com page.

-Create an iOS app there.

-Install react-native-firebase via npm.

-Add GoogleService-Info.plist file to the project within XCode.

-Make changes to ios/[YOUR APP NAME]/AppDelegate.m file.

-Creat a new Podfile (Cocoa pod) and updated it by "pod update" command.

-Add and edited lines to the Podfile per the instruction.

-Run "pod install"

-Run "react-native link react-native-firebase" from the project root.

-Click "Next" button within Firebase console and move on to "Run your app to verify installation" section.

-Run the iOS app on simulator by running "react-native run-ios" command.

The app boots up and functions as normal in the simulator.

Nothing happens in the Firebase page.

This is the first couple of lines of my Podfile.

# Uncomment the next line to define a global platform for your
project
platform :ios, '9.0'

# Required by RNFirebase
pod 'Firebase/Core', '~> 5.20.1'

target 'My_App_Name' do


问:
Why do I get duplicate tuples in my query?
I am building a library database.

I want to write a query that returns the available books on the library(their isbns,titles,author names,pubname,categoryName and the Number of copies available.

My query involves the following relations (with bold are the primary keys) :

Book  (ISBN, title,pubYear,numpages, pubName ) pubName FK to publisher

copies  (ISBN, copyNr, shelf ) ISBN FK to Book

borrows (memberID, ISBN, copyNr, date_of_borrowing, date_of_return ) memberID FK to member, ISBN FK to Books, (ISBN, copyNr) FK to copies

belongs_to  (ISBN, categoryName ) SBN FK to Book, categoryName FK to category

written_by  (ISBN, authID ) ISBN FK to Book, authID FK to author

author  (authID, AFirst, ALast, Abirthdate )

My approach is the following:

```<code>SELECT b.isbn, b.title,a.ALast, a.ALast, b.pubName, be.categoryName , COUNT(b.isbn) as Number_of_copies_available
FROM copies as c
INNER JOIN book as b ON c.isbn = b.isbn
INNER JOIN belong_to as be ON b.isbn = be.isbn
INNER JOIN written_by as w ON w.isbn=b.isbn
INNER JOIN author as a ON a.authID = w.authID
WHERE (c.isbn,c.copyNr) NOT IN (SELECT isbn, copyNr FROM borrows)
GROUP BY b.isbn
ORDER BY be.categoryName
</code>```

The problem is that I get duplicate tuples on the result before grouping which leads to more items per group.

For instance for some books I get the attribute value of Number_of_copies_available double than expected.

If I don't JOIN with the relations "written_by" and "author" then the result is correct. However, I also want to appear the author names in the result. What's my mistake? Thanks in advance!

答:
Still a bit confused..Could you explain me where the mistake exactly
  is and how could I fix this?

Not really meant as a answer, as this "comment" is way to large.

But a more SQL 92 valid rewrite would be more or less like below.

But as you didn't provide example data and expected results iám really guessing what you need

Query

```<code>SELECT
 book.isbn
 ...
FROM
 book
INNER JOIN (
  SELECT
    COUNT(book.isbn) AS Number_of_copies_available
  FROM
   book
  INNER JOIN
   copies
  ON
   book.isbn = copies.isbn

  ... # borrows table should also be needed here to be filterd?
) AS book_copies__count
ON
...
...
...
</code>```

Body:
I am building a library database.

I want to write a query that returns the available books on the library(their isbns,titles,author names,pubname,categoryName and the Number of copies available.

My query involves the following relations (with bold are the primary keys) :

Book  (ISBN, title,pubYear,numpages, pubName ) pubName FK to publisher

copies  (ISBN, copyNr, shelf ) ISBN FK to Book

borrows (memberID, ISBN, copyNr, date_of_borrowing, date_of_return ) memberID FK to member, ISBN FK to Books, (ISBN, copyNr) FK to copies

belongs_to  (ISBN, categoryName ) SBN FK to Book, categoryName FK to category

written_by  (ISBN, authID ) ISBN FK to Book, authID FK to author

author  (authID, AFirst, ALast, Abirthdate )

My approach is the following:

SELECT b.isbn, b.title,a.ALast, a.ALast, b.pubName, be.categoryName , COUNT(b.isbn) as Number_of_copies_available
FROM copies as c
INNER JOIN book as b ON c.isbn = b.isbn
INNER JOIN belong_to as be ON b.isbn = be.isbn
INNER JOIN written_by as w ON w.isbn=b.isbn
INNER JOIN author as a ON a.authID = w.authID
WHERE (c.isbn,c.copyNr) NOT IN (SELECT isbn, copyNr FROM borrows)
GROUP BY b.isbn
ORDER BY be.categoryName

The problem is that I get duplicate tuples on the result before grouping which leads to more items per group.

For instance for some books I get the attribute value of Number_of_copies_available double than expected.

If I don't JOIN with the relations "written_by" and "author" then the result is correct. However, I also want to appear the author names in the result. What's my mistake? Thanks in advance!

Body:
Still a bit confused..Could you explain me where the mistake exactly
  is and how could I fix this?

Not really meant as a answer, as this "comment" is way to large.

But a more SQL 92 valid rewrite would be more or less like below.

But as you didn't provide example data and expected results iám really guessing what you need

Query

SELECT
 book.isbn
 ...
FROM
 book
INNER JOIN (
  SELECT
    COUNT(book.isbn) AS Number_of_copies_available
  FROM
   book
  INNER JOIN
   copies
  ON
   book.isbn = copies.isbn

  ... # borrows table should also be needed here to be filterd?
) AS book_copies__count
ON
...
...
...


问:
Given a list of elements, replicate each element N times
I have to replicate each element n times like this:
?- replicate([a,b,c],2,X).  -> X = [a,a,b,b,c,c]
?- replicate([a,b,c],3,X).  -> X = [a,a,a,b,b,b,c,c,c]

I have tried everything with the information I have so far, the only thing I have been able to do is to determine which is the most repeating element like this:

```<code>%List of tuples, keeps track of the number of repetitions.
modify([],X,[(X,1)]).
modify([(X,Y)|Xs],X,[(X,K)|Xs]):- K is Y+1.
modify([(Z,Y)|Xs],X,[(Z,Y)|K]):- Z =\= X, modify(Xs,X,K).

highest((X1,Y1),(_,Y2),(X1,Y1)):- Y1 >= Y2.
highest((_,Y1),(X2,Y2),(X2,Y2)):- Y2 > Y1.

maxR([X],X).
maxR([X|Xs],K):- maxR(Xs,Z),highest(X,Z,K).

rep([],R,R).
rep([X|Xs],R,R1):-modify(R,X,R2),rep(Xs,R2,R1).

maxRepeated(X,R):- rep(X,[],K),maxR(K,R).

?- maxRepeated([1,3,3,4,3,2] ,X).
X = (3, 3) .

?- maxRepeated([1,2,3,4,5,6] ,X).
X = (1, 1) .
</code>```

答:
We can split the problem into two problems:

generate a list of N elements X with a predicate we implement replicate_item/3; and

do this for every element, and concatenate the result in a prdicate named replicate/3.

@joel76 already provided a nice implementation for replicate_item/3. I will only change the order of the parameters:

```<code>replicate_item(N, X, List) :-
    length(List, N),
    maplist(=(X), List).
</code>```

Now our replicate/3 prdicate can iterate over the list, and for each element use replicate_item/3 to generate a sublist. We can then use append/2 [swi-doc] for this:

```<code>replicate(LA, N, List) :-
    maplist(replicate_item(N), LA, LL),
    append(LL, List).
</code>```

Body:
I have to replicate each element n times like this:
?- replicate([a,b,c],2,X).  -> X = [a,a,b,b,c,c]
?- replicate([a,b,c],3,X).  -> X = [a,a,a,b,b,b,c,c,c]

I have tried everything with the information I have so far, the only thing I have been able to do is to determine which is the most repeating element like this:

%List of tuples, keeps track of the number of repetitions.
modify([],X,[(X,1)]).
modify([(X,Y)|Xs],X,[(X,K)|Xs]):- K is Y+1.
modify([(Z,Y)|Xs],X,[(Z,Y)|K]):- Z =\= X, modify(Xs,X,K).

highest((X1,Y1),(_,Y2),(X1,Y1)):- Y1 >= Y2.
highest((_,Y1),(X2,Y2),(X2,Y2)):- Y2 > Y1.

maxR([X],X).
maxR([X|Xs],K):- maxR(Xs,Z),highest(X,Z,K).

rep([],R,R).
rep([X|Xs],R,R1):-modify(R,X,R2),rep(Xs,R2,R1).

maxRepeated(X,R):- rep(X,[],K),maxR(K,R).

?- maxRepeated([1,3,3,4,3,2] ,X).
X = (3, 3) .

?- maxRepeated([1,2,3,4,5,6] ,X).
X = (1, 1) .

Body:
We can split the problem into two problems:

generate a list of N elements X with a predicate we implement replicate_item/3; and

do this for every element, and concatenate the result in a prdicate named replicate/3.

@joel76 already provided a nice implementation for replicate_item/3. I will only change the order of the parameters:

replicate_item(N, X, List) :-
    length(List, N),
    maplist(=(X), List).

Now our replicate/3 prdicate can iterate over the list, and for each element use replicate_item/3 to generate a sublist. We can then use append/2 [swi-doc] for this:

replicate(LA, N, List) :-
    maplist(replicate_item(N), LA, LL),
    append(LL, List).


问:
Extract authors meta data with XPath
I have a series of HTML-files where authors names are split into first and lastname, contained in meta tags.

My current HTML structure is as follows, I want to extract authors first and lastname in a correct way, so that I can use this data to index these HTML-files. The amount of authors may vary between HTML-documents.

```<code><!doctype html>
 <html lang="en">
 <head>
 <title>Title of document</title>
 <meta charset="utf-8" />
 <meta name="dcterms.title" content="The science papers title" />

<meta name="author" />
    <meta name="firstname" content="Eddard" />
    <meta name="lastname" content="Stark" />

<meta name="author" />
    <meta name="firstname" content="Tywin" />
    <meta name="lastname" content="Lannister" />

<meta name="author" />
    <meta name="firstname" content="Jon" />
    <meta name="lastname" content="Snow" />

 <meta name="dcterms.subject" content="The articles subject" />
 <meta name="description" content="The articles description, abstract or introduction" />
 <meta name="keywords" content="keyword1, keyword2, keyword3" />
</head>
</code>```

I have bee using C# and XPath to scrape this data, trying to figure out how to get data correct. My problem is that I can't seem to figure out how to extract the meta data and make look like this, so I can use each string variable in generating XML later.

```<code>var author_1: Eddard Stark
var author_2: Tywin Lannister
var author_3: Jon Snow
</code>```

My current C# test bed with XPaths.

```<code>            var url = "<URL TO DOCUMENT>";
            var web = new HtmlWeb();
            var doc = web.Load(url);
            var navigator = (HtmlAgilityPack.HtmlNodeNavigator)doc.CreateNavigator();

            // Xpaths
            var authors_list = doc.DocumentNode.SelectSingleNode("//meta[@name='author']");
            var authors_FirstName = "//meta[@name='author']/following::meta[1]/@content";
            var authors_LastName = "//meta[@name='lastname']/@content";

            // Laboratory
            var listOfAuthorsXpath = "//meta[@name='author']/following::meta[1]/@content";
            var nodes = doc.DocumentNode.SelectNodes(listOfAuthorsXpath);

            // SelectNodes
            var firstName = navigator.SelectSingleNode(authors_FirstName);
            var lastName = navigator.SelectSingleNode(authors_LastName);

            // Print to screen
            Console.WriteLine(firstName.Value + " " +lastName.Value);

            //Console.WriteLine(doc.DocumentNode.InnerHtml);
            Console.ReadKey();
</code>```

答:
[Updated Answer]

(Please notice that the XML that you share is not a valid XML, a  is missing)

With this snippet you can get the information that you need:

using System;
using System.Collections.Generic;
using System.Xml;

namespace XPath
{
    class MainClass
    {
        public static void Main()
        {
            XmlDocument doc = new XmlDocument();
            doc.Load(".... your file");

            // Xpaths
            XmlNode root = doc.DocumentElement;
            // Xpaths
            XmlNode root = doc.DocumentElement;
            XmlNodeList xmlFirstNameNodeList = root.SelectNodes("//html/head/meta[@name='firstname']");
            XmlNodeList xmlLastNameNodeList = root.SelectNodes("//html/head/meta[@name='lastname']");

            List<String> authors = new List<String>();

            for(int i=0; i<xmlFirstNameNodeList.Count; i++) {
                authors.Add(xmlFirstNameNodeList[i].Attributes["content"].Value + " " + xmlLastNameNodeList[i].Attributes["content"].Value);
            }

            Console.ReadKey();

        }
    }
}

```

<p>The content of List authors:</p>

<pre class="lang-cs prettyprint-override"><code>authors[0] = "Eddard Stark"
authors[1] = "Tywin Lannister"
authors[2] = "Jon Snow"
</code>```

Title: Extract authors meta data with XPath

Body:
I have a series of HTML-files where authors names are split into first and lastname, contained in meta tags.

My current HTML structure is as follows, I want to extract authors first and lastname in a correct way, so that I can use this data to index these HTML-files. The amount of authors may vary between HTML-documents.

<!doctype html>

 <title>Title of document</title>
 <meta charset="utf-8" />
 <meta name="dcterms.title" content="The science papers title" />

<meta name="author" />
    <meta name="firstname" content="Eddard" />
    <meta name="lastname" content="Stark" />

<meta name="author" />
    <meta name="firstname" content="Tywin" />
    <meta name="lastname" content="Lannister" />

<meta name="author" />
    <meta name="firstname" content="Jon" />
    <meta name="lastname" content="Snow" />

 <meta name="dcterms.subject" content="The articles subject" />
 <meta name="description" content="The articles description, abstract or introduction" />
 <meta name="keywords" content="keyword1, keyword2, keyword3" />

I have bee using C# and XPath to scrape this data, trying to figure out how to get data correct. My problem is that I can't seem to figure out how to extract the meta data and make look like this, so I can use each string variable in generating XML later.

var author_1: Eddard Stark
var author_2: Tywin Lannister
var author_3: Jon Snow

My current C# test bed with XPaths.

            var url = "<URL TO DOCUMENT>";
            var web = new HtmlWeb();
            var doc = web.Load(url);
            var navigator = (HtmlAgilityPack.HtmlNodeNavigator)doc.CreateNavigator();

            // Xpaths
            var authors_list = doc.DocumentNode.SelectSingleNode("//meta[@name='author']");
            var authors_FirstName = "//meta[@name='author']/following::meta[1]/@content";
            var authors_LastName = "//meta[@name='lastname']/@content";

            // Laboratory
            var listOfAuthorsXpath = "//meta[@name='author']/following::meta[1]/@content";
            var nodes = doc.DocumentNode.SelectNodes(listOfAuthorsXpath);

            // SelectNodes
            var firstName = navigator.SelectSingleNode(authors_FirstName);
            var lastName = navigator.SelectSingleNode(authors_LastName);

            // Print to screen
            Console.WriteLine(firstName.Value + " " +lastName.Value);

            //Console.WriteLine(doc.DocumentNode.InnerHtml);
            Console.ReadKey();

Body:
[Updated Answer]

(Please notice that the XML that you share is not a valid XML, a </html> is missing)

With this snippet you can get the information that you need:

using System;
using System.Collections.Generic;
using System.Xml;

namespace XPath
{
    class MainClass
    {
        public static void Main()
        {
            XmlDocument doc = new XmlDocument();
            doc.Load(".... your file");

            // Xpaths
            XmlNode root = doc.DocumentElement;
            // Xpaths
            XmlNode root = doc.DocumentElement;
            XmlNodeList xmlFirstNameNodeList = root.SelectNodes("//html/head/meta[@name='firstname']");
            XmlNodeList xmlLastNameNodeList = root.SelectNodes("//html/head/meta[@name='lastname']");

            List<String> authors = new List<String>();

            for(int i=0; i<xmlFirstNameNodeList.Count; i++) {
                authors.Add(xmlFirstNameNodeList[i].Attributes["content"].Value + " " + xmlLastNameNodeList[i].Attributes["content"].Value);
            }

            Console.ReadKey();

        }
    }
}

The content of List authors:

authors[0] = "Eddard Stark"
authors[1] = "Tywin Lannister"
authors[2] = "Jon Snow"