问:
Build an executable using a pattern in Makefile
Here is a simple Makefile content:

```<code>CXXCOMP=g++
CXXFLAGS=-std=c++11 -g

%.o: %.cpp
    $(CXXCOMP) $(CXXFLAGS) -c $<

main: %.o
    $(CXXCOMP) $(CXXFLAGS) -o $@ $^
</code>```

I expect that the first rule will generate a .o file for each .cpp one, while the second rule will generate a main file from all the .o ones.

Actually, the following statement is printed to terminal when I try to make main:

```<code>target `main' doesn't match the target pattern
</code>```

Can you please explain a bit more in depth what's going on and how to solve this little issue?

答:
As John Bollinger pointed out in the comments, you should probably name either the sources or the object files explicitly. Not doing so is less safe, less predictable, and the price you pay in makefile complexity isn't even worth it.

To circumvent the complexity, you would have to have all of your header files, source files, object files, and output files in the same folder, which isn't great. This would, however, allow you to simply use the $(wildcard *.cpp) function. Otherwise you would have to chain a series of calls to first get all of the source files in the src directory, use the notdir function to strip the directory part of the name, and then use the patsubst function to do a switcheroo on the filename extension. That would look something like this:

```<code>OBJS = $(patsubst %.cpp, %.o, $(notdir $(wildcard src/*.cpp)))
</code>```

I personally prefer listing all the object files explicitly, but this will do what you want.

As an aside, the reason you need the wildcard function specifically is because while wildcards will generally work as expected in rules and targets, you're using it in a variable assignment, where it is being taken literally. If you set OBJS to *.o and echo the variable, you get this:

```<code>OBJS = *.o

echo_objs:
    @echo $(OBS)
</code>```

Output:

```<code>echo *.o
</code>```

Running the whole makefile gives the following error:

```<code>make: *** No rule to make target '*.o', needed by 'project'.  Stop.
</code>```

There are no object files in the directory currently, so using the wildcard function in the assignment results in echoing out nothing, which is the usual behavior. I echoed the names of all the object files in the directory: none.

What I like to do is list the object files like this:

```<code>OBJS = main.o file.o string.o # or whatever
</code>```

Then, having previously set the vpath variable like this:

```<code>vpath %.cpp src
vpath %.hpp include
</code>```

I can simply write:

```<code>OBJS = main.o
ASMS = $(patsubst %.o, %.asm, $(OBJS))

TARGET = project_name

all: assembler_output $(TARGET) # etc

$(TARGET): $(OBJS)
    $(CXX) $(CXXFLAGS) $(CPPFLAGS) -I include    -o $@ $^ $(LDFLAGS)

%.o: %.cpp
    $(CXX) $(CXXFLAGS) $(CPPFLAGS) -I include -c -o $@ $^

assembler_output: $(ASMS)

%.asm: %.cpp
    $(CXX) $(CXXFLAGS) $(CPPFLAGS) -I include -masm=intel -S -o $@ $^

.PHONY: clean
clean:
    $(RM) $(OBJS) $(TARGET)
</code>```

I included the additional target, because a) I like seeing what the compiler (and occasionally the preprocessor) are doing before the linker is invoked, and b) hopefully it helps modularize your goals somewhat.

Having hopefully answered the main question, I do have some suggestions on your makefile. You should really stick to the convention of naming the C compiler variable CC and the C++ compiler CXX, especially if you want to publish your code for others to use. Your users will expect to be able to configure the compilation settings for the project when they build it (maybe they don't have or use g++), and they'll be in for a surprise when they keep changing the CXX variable to no avail.

While a makefile for a toy project is short, they can get pretty unwieldy pretty fast, especially with test code, installation directives, etc., so making your users have to cat -n ./makefile | grep -E 'CXX' for all possible compilation directives to hunt down the actual variable will be pretty annoying. Not to mention you're declaring the variable in the makefile, so they can't override the settings. You might want to use ?= for those variables, that way they're only defined if no settings have been set through the console.

In fact, if you run make --print-data-base in the project directory and grep -E 'COMPILE', you can see the exact commands make has built-in to compile C, C++, assembler, fortran, etc. For C++ the command is:

```<code>COMPILE.cc = $(CXX) $(CXXFLAGS) $(CPPFLAGS) $(TARGET_ARCH) -c
</code>```

Since your users can configure those flags though, make sure your mandatory include directories aren't in CPPFLAGS. That variable is for optional libraries' include directories, in case your application allows users to compile with additional functionality if they have a specific library installed.

The linker command is LINK.cc = $(CXX) $(CXXFLAGS) $(CPPFLAGS) $(LDFLAGS) $(TARGET_ARCH), where LDFLAGS is the linker variable your users will also expect to be able to configure.

All of this really starts to matter once your projects start gaining size and complexity. Large projects will usually have nested subfolders and a top-level makefile will call each nested makefile recursively, and this is when sticking to a clear, well-defined convention starts to really matter.

Writing good makefiles takes practice, but it can be super rewarding. I've seen some truly masterful ones, none of them written by me, unfortunately. Hopefully this helps somewhat, though; for me it always helps to know why things are done they way they are, from a technical standpoint, before I really understand and embrace accepted practices.

Body:
Here is a simple Makefile content:

CXXCOMP=g++
CXXFLAGS=-std=c++11 -g

%.o: %.cpp
    $(CXXCOMP) $(CXXFLAGS) -c $<

main: %.o
    $(CXXCOMP) $(CXXFLAGS) -o $@ $^

I expect that the first rule will generate a .o file for each .cpp one, while the second rule will generate a main file from all the .o ones.

Actually, the following statement is printed to terminal when I try to make main:

target `main' doesn't match the target pattern

Can you please explain a bit more in depth what's going on and how to solve this little issue?

Body:
As John Bollinger pointed out in the comments, you should probably name either the sources or the object files explicitly. Not doing so is less safe, less predictable, and the price you pay in makefile complexity isn't even worth it.

To circumvent the complexity, you would have to have all of your header files, source files, object files, and output files in the same folder, which isn't great. This would, however, allow you to simply use the $(wildcard *.cpp) function. Otherwise you would have to chain a series of calls to first get all of the source files in the src directory, use the notdir function to strip the directory part of the name, and then use the patsubst function to do a switcheroo on the filename extension. That would look something like this:

OBJS = $(patsubst %.cpp, %.o, $(notdir $(wildcard src/*.cpp)))

I personally prefer listing all the object files explicitly, but this will do what you want.

As an aside, the reason you need the wildcard function specifically is because while wildcards will generally work as expected in rules and targets, you're using it in a variable assignment, where it is being taken literally. If you set OBJS to *.o and echo the variable, you get this:

OBJS = *.o

echo_objs:
    @echo $(OBS)

Output:

echo *.o

Running the whole makefile gives the following error:

make: *** No rule to make target '*.o', needed by 'project'.  Stop.

There are no object files in the directory currently, so using the wildcard function in the assignment results in echoing out nothing, which is the usual behavior. I echoed the names of all the object files in the directory: none.

What I like to do is list the object files like this:

OBJS = main.o file.o string.o # or whatever

Then, having previously set the vpath variable like this:

vpath %.cpp src
vpath %.hpp include

I can simply write:

OBJS = main.o
ASMS = $(patsubst %.o, %.asm, $(OBJS))

TARGET = project_name

all: assembler_output $(TARGET) # etc

$(TARGET): $(OBJS)
    $(CXX) $(CXXFLAGS) $(CPPFLAGS) -I include    -o $@ $^ $(LDFLAGS)

%.o: %.cpp
    $(CXX) $(CXXFLAGS) $(CPPFLAGS) -I include -c -o $@ $^

assembler_output: $(ASMS)

%.asm: %.cpp
    $(CXX) $(CXXFLAGS) $(CPPFLAGS) -I include -masm=intel -S -o $@ $^

.PHONY: clean
clean:
    $(RM) $(OBJS) $(TARGET)

I included the additional target, because a) I like seeing what the compiler (and occasionally the preprocessor) are doing before the linker is invoked, and b) hopefully it helps modularize your goals somewhat.

Having hopefully answered the main question, I do have some suggestions on your makefile. You should really stick to the convention of naming the C compiler variable CC and the C++ compiler CXX, especially if you want to publish your code for others to use. Your users will expect to be able to configure the compilation settings for the project when they build it (maybe they don't have or use g++), and they'll be in for a surprise when they keep changing the CXX variable to no avail.

While a makefile for a toy project is short, they can get pretty unwieldy pretty fast, especially with test code, installation directives, etc., so making your users have to cat -n ./makefile | grep -E 'CXX' for all possible compilation directives to hunt down the actual variable will be pretty annoying. Not to mention you're declaring the variable in the makefile, so they can't override the settings. You might want to use ?= for those variables, that way they're only defined if no settings have been set through the console.

In fact, if you run make --print-data-base in the project directory and grep -E 'COMPILE', you can see the exact commands make has built-in to compile C, C++, assembler, fortran, etc. For C++ the command is:

COMPILE.cc = $(CXX) $(CXXFLAGS) $(CPPFLAGS) $(TARGET_ARCH) -c

Since your users can configure those flags though, make sure your mandatory include directories aren't in CPPFLAGS. That variable is for optional libraries' include directories, in case your application allows users to compile with additional functionality if they have a specific library installed.

The linker command is LINK.cc = $(CXX) $(CXXFLAGS) $(CPPFLAGS) $(LDFLAGS) $(TARGET_ARCH), where LDFLAGS is the linker variable your users will also expect to be able to configure.

All of this really starts to matter once your projects start gaining size and complexity. Large projects will usually have nested subfolders and a top-level makefile will call each nested makefile recursively, and this is when sticking to a clear, well-defined convention starts to really matter.

Writing good makefiles takes practice, but it can be super rewarding. I've seen some truly masterful ones, none of them written by me, unfortunately. Hopefully this helps somewhat, though; for me it always helps to know why things are done they way they are, from a technical standpoint, before I really understand and embrace accepted practices.


来源: stackexchange

问:
How to show all objects and their comments in PostgreSQL?
I have been tasked as an ongoing project to comment everything in the postgres database thereby documenting all of the object and what they do. Is there a SELECT script out there that would show all the tables, views, columns, and functions, etc and their comments including the ones with null comments. Below is an example of what I am after:

```<code>SELECT object_type,object_schema,object_name,comment
FROM information_schema.some_table_out_there;

|object_type|object_schema|object_name|comment|
|table      | my_schema   |table1     |my first table
|table      | my_schema   |table2     |NULL
|view       | public      |employees  |NULL
|function   | public      |emps_insert|inserts employees
</code>```

I'd like to used this script to create a report where you drill to a form and comment on the database object your desired comment.

答:
information_schema is defined by an ANSI standard, so it only covers objects described by the SQL spec. Indexes aren't included, nor is anything Postgres-specific (event triggers, row security policies, etc.). If you want an exhaustive list, you'll need to go to the system catalogs.

There is no central list of objects; each object type lives in its own table, so you need to query each of them separately. However, there are some handy object information functions which will accept any object type, so we can glue these queries together fairly easily with some dynamic SQL:

```<code>create function describe_all_objects()
  returns table(
    type text,
    schema text,
    name text,
    identity text,
    comment text
  )
as $$
declare
  /* Cutoff for system object OIDs; see comments in src/include/access/transam.h */
  MIN_USER_OID constant oid = 16384;
  catalog_class regclass;
begin
  for catalog_class in
    /* Get a list of all catalog tables with an OID */
    select oid::regclass
    from pg_class
    where
      relhasoids and
      pg_class.oid < MIN_USER_OID and
      /* Enum members have no obj_description(); the enum itself is picked up in pg_type */
      pg_class.oid <> 'pg_enum'::regclass
  loop
    return query execute format(
      $SQL$
        /* Get descriptions for all user-created catalog entries */
        select
          info.type,
          info.schema,
          info.name,
          info.identity,
          coalesce(
            obj_description(catalog_table.oid, catalog_table.tableoid::regclass::text),
            shobj_description(catalog_table.oid, catalog_table.tableoid::regclass::text)
          ) as comment
        from
          %s as catalog_table,
          lateral pg_identify_object(catalog_table.tableoid, catalog_table.oid, 0) as info
        where
          catalog_table.oid >= %s
      $SQL$,
      catalog_class,
      MIN_USER_OID
    );
  end loop;

  /* Handle "sub-objects" (i.e. pg_attribute) separately */
  return query
    select
      info.type,
      info.schema,
      info.name,
      info.identity,
      col_description(attrelid, attnum) as comment
    from
      pg_attribute,
      lateral pg_identify_object('pg_class'::regclass, attrelid, attnum) as info
    where
      attrelid >= MIN_USER_OID and
      attnum >= 0 and
      not attisdropped;
end
$$
language plpgsql stable;

select * from describe_all_objects();
</code>```

This should cover every object in the database, right down to the implicit table array types and the columns on the TOAST table indexes, as well as server-wide objects like databases and users, so you'll likely want to filter this down quite a bit.

A handful of catalog tables need superuser permission to access directly, but if this is an issue, you should be able to modify the queries to pull the information from some public source (e.g. pg_authid is superuser-only because it contains password information, but you can look at pg_roles instead).

Let me know if you notice any omissions (and please test this more thoroughly than I did before using it for anything important :) ).

ContentLicense: CC BY-SA 4.0

Body:
I have been tasked as an ongoing project to comment everything in the postgres database thereby documenting all of the object and what they do. Is there a SELECT script out there that would show all the tables, views, columns, and functions, etc and their comments including the ones with null comments. Below is an example of what I am after:

SELECT object_type,object_schema,object_name,comment
FROM information_schema.some_table_out_there;

|object_type|object_schema|object_name|comment|
|table      | my_schema   |table1     |my first table
|table      | my_schema   |table2     |NULL
|view       | public      |employees  |NULL
|function   | public      |emps_insert|inserts employees

I'd like to used this script to create a report where you drill to a form and comment on the database object your desired comment.

Body:
information_schema is defined by an ANSI standard, so it only covers objects described by the SQL spec. Indexes aren't included, nor is anything Postgres-specific (event triggers, row security policies, etc.). If you want an exhaustive list, you'll need to go to the system catalogs.

There is no central list of objects; each object type lives in its own table, so you need to query each of them separately. However, there are some handy object information functions which will accept any object type, so we can glue these queries together fairly easily with some dynamic SQL:

create function describe_all_objects()
  returns table(
    type text,
    schema text,
    name text,
    identity text,
    comment text
  )
as $$
declare
  /* Cutoff for system object OIDs; see comments in src/include/access/transam.h */
  MIN_USER_OID constant oid = 16384;
  catalog_class regclass;
begin
  for catalog_class in
    /* Get a list of all catalog tables with an OID */
    select oid::regclass
    from pg_class
    where
      relhasoids and
      pg_class.oid < MIN_USER_OID and
      /* Enum members have no obj_description(); the enum itself is picked up in pg_type */
      pg_class.oid <> 'pg_enum'::regclass
  loop
    return query execute format(
      $SQL$
        /* Get descriptions for all user-created catalog entries */
        select
          info.type,
          info.schema,
          info.name,
          info.identity,
          coalesce(
            obj_description(catalog_table.oid, catalog_table.tableoid::regclass::text),
            shobj_description(catalog_table.oid, catalog_table.tableoid::regclass::text)
          ) as comment
        from
          %s as catalog_table,
          lateral pg_identify_object(catalog_table.tableoid, catalog_table.oid, 0) as info
        where
          catalog_table.oid >= %s
      $SQL$,
      catalog_class,
      MIN_USER_OID
    );
  end loop;

  /* Handle "sub-objects" (i.e. pg_attribute) separately */
  return query
    select
      info.type,
      info.schema,
      info.name,
      info.identity,
      col_description(attrelid, attnum) as comment
    from
      pg_attribute,
      lateral pg_identify_object('pg_class'::regclass, attrelid, attnum) as info
    where
      attrelid >= MIN_USER_OID and
      attnum >= 0 and
      not attisdropped;
end
$$
language plpgsql stable;

select * from describe_all_objects();

This should cover every object in the database, right down to the implicit table array types and the columns on the TOAST table indexes, as well as server-wide objects like databases and users, so you'll likely want to filter this down quite a bit.

A handful of catalog tables need superuser permission to access directly, but if this is an issue, you should be able to modify the queries to pull the information from some public source (e.g. pg_authid is superuser-only because it contains password information, but you can look at pg_roles instead).

Let me know if you notice any omissions (and please test this more thoroughly than I did before using it for anything important :) ).


问:
Error while using image-watermark in node.js
I am using image-watermark for adding watermark to a file on server side node.js and it is producing an error.

I tried installing modules image-watermark, imagemagick, and other dependencies. At first, I faced a problem similar to this. But, this problem was resolved by installing ImageMagick into my system and now that is resolved from this answer.

Now, I am getting an error in the following code:

```<code>const watermark = require('image-watermark');
const imagePath = path.resolve(__dirname,'./relative/path/to/image');
watermark.embedWatermarkWithCb(imagePath, { 'text': 'sample watermark' },
function (err) {
    if (!err)
      console.log('Succefully embeded watermark');
    else {
      //I am getting error here.
      console.log(err);
    }
});
</code>```

The image file should be exported with a watermark. But, instead I am getting this error:

```<code>{ Error: Command failed:
    at ChildProcess.<anonymous>(...\node_modules\imagemagick\imagemagick.js:88:15)
    at emitTwo (events.js:131:20)
    at ChildProcess.emit (events.js:214:7)
    at maybeClose (internal/child_process.js:925:16)
    at Process.ChildProcess._handle.onexit
(internal/child_process.js:209:5) timedOut: false, killed: false, code: 1,
signal: null }
</code>```

I used this answer to get to the root cause of the error. Without that I got Error: spawn ENOENT error only.

答:
I prepare a basic example for you:

download the code here

Pre-requisite:

```<code>install imagemagick in SO
install ghostscript in SO (for pdf files)
</code>```

Ex. for mac:

```<code>brew install imagemagick
brew install ghostscript (for pdf files)
</code>```

The steps are the following:

```<code>- You must enter the folder ./stackoverflow/56353310/

- npm install

- node index.js
</code>```

The output must be something like that:

any question please let me know.

Body:
I am using image-watermark for adding watermark to a file on server side node.js and it is producing an error.

I tried installing modules image-watermark, imagemagick, and other dependencies. At first, I faced a problem similar to this. But, this problem was resolved by installing ImageMagick into my system and now that is resolved from this answer.

Now, I am getting an error in the following code:

const watermark = require('image-watermark');
const imagePath = path.resolve(__dirname,'./relative/path/to/image');
watermark.embedWatermarkWithCb(imagePath, { 'text': 'sample watermark' },
function (err) {
    if (!err)
      console.log('Succefully embeded watermark');
    else {
      //I am getting error here.
      console.log(err);
    }
});

The image file should be exported with a watermark. But, instead I am getting this error:

{ Error: Command failed:
    at ChildProcess.<anonymous>(...\node_modules\imagemagick\imagemagick.js:88:15)
    at emitTwo (events.js:131:20)
    at ChildProcess.emit (events.js:214:7)
    at maybeClose (internal/child_process.js:925:16)
    at Process.ChildProcess._handle.onexit
(internal/child_process.js:209:5) timedOut: false, killed: false, code: 1,
signal: null }

I used this answer to get to the root cause of the error. Without that I got Error: spawn ENOENT error only.

Body:
I prepare a basic example for you:

download the code here

Pre-requisite:

install imagemagick in SO
install ghostscript in SO (for pdf files)

Ex. for mac:

brew install imagemagick
brew install ghostscript (for pdf files)

The steps are the following:

- You must enter the folder ./stackoverflow/56353310/

- npm install

- node index.js

The output must be something like that:

any question please let me know.


问:
Display a Modal on button click using Jquery
I want to display my Modal on button click. Below is my code.

```<code><input type="button" id="button1" value="Button" onclick="myFunction()"/>
<div id="openModal" class="modalDialog">
    <div>
        <a href="#close" title="Close" class="close">X</a>
        <h2>
            Modal Box</h2>
        <p>
            Hello world</p>
    </div>
</div>
</code>```

This is my unfinished script.

```<code><script type="text/javascript">
    $(document).ready(function () {

    });
</script>
</code>```

答: You probably have to set visibility:hidden; to the div, and set it to visible onclick</p>

ContentLicense: CC BY-SA 3.0

Body:
I want to display my Modal on button click. Below is my code.

<input type="button" id="button1" value="Button" onclick="myFunction()"/>

        X

            Modal Box

            Hello world

This is my unfinished script.


问:
Java and Hibernate - How to make OneToOne relation with SuperMappedClass and not an Entity
I have tree Entities: Client, ClientConfigurationA and ClientConfigurationB.

I try to make something like:

```<code>@Entity
@Table(name = "CLIENT")
public class Client {

    @Id
    private int id;

    @OneToOne(mappedBy = "client")
    private ClientConfiguration configuration

    // some getter and setter
}

@MappedSuperClass
public class ClientConfiguration {

    @Id
    private int id;

    @OneToOne
    @MapsId
    protected Client client;

    // getters and setters
}

@Entity(name = "CLIENT_CONF_A")
public class ClientConfigurationA extends ClientConfiguration { ... }

@Entity(name = "CLIENT_CONF_B")
public class ClientConfigurationB extends ClientConfiguration { ... }
</code>```

But actually I can't define a OneToOne related to MappedSuperClass and not an Entity.

So what's the best way to implement this case ?

I already tried this solution without succes.

Thanks for reading.

答:
It's impossible and here's why:

When hibernate processes entities it needs to know what table to join with when resolving one to one relations.

The problem arise with @MappedSuperClass is that it doesn't define table, so multiple entities could be inherited from this class, each one having different table. Hibernate just couldn't know what table to join then.

If you want to have common super class, I suggest using an abstract @Entity class.

Body:
I have tree Entities: Client, ClientConfigurationA and ClientConfigurationB.

I try to make something like:

@Entity
@Table(name = "CLIENT")
public class Client {

    @Id
    private int id;

    @OneToOne(mappedBy = "client")
    private ClientConfiguration configuration

    // some getter and setter
}

@MappedSuperClass
public class ClientConfiguration {

    @Id
    private int id;

    @OneToOne
    @MapsId
    protected Client client;

    // getters and setters
}

@Entity(name = "CLIENT_CONF_A")
public class ClientConfigurationA extends ClientConfiguration { ... }

@Entity(name = "CLIENT_CONF_B")
public class ClientConfigurationB extends ClientConfiguration { ... }

But actually I can't define a OneToOne related to MappedSuperClass and not an Entity.

So what's the best way to implement this case ?

I already tried this solution without succes.

Thanks for reading.


问:
Repeated Items in RecyclerView
I am having problems with repeated items in RecyclerView. Whenever I upload to my firebase and open the main activity again there are repeated itmes in the recyclerView from the previous load. How do I remove repeated items from my recyclerView.

Code for my Main Activity is

```<code>private RecyclerView mRecyclerView;
private RecyclerViewAdapter mAdapter;

private DatabaseReference mDatabaseReference;
private List<Upload> mUploads;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_posts);
    setupBottomNavigation();

    mRecyclerView = findViewById(R.id.recycler_view);
    mRecyclerView.setHasFixedSize(true);
    mRecyclerView.setLayoutManager(new LinearLayoutManager(this));

    mUploads = new ArrayList<>();

    mDatabaseReference = FirebaseDatabase.getInstance().getReference("uploads");

    mDatabaseReference.addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
            for(DataSnapshot postSnapshot : dataSnapshot.getChildren())
            {
                Upload upload = postSnapshot.getValue(Upload.class);
                mUploads.add(upload);
            }
            mAdapter = new RecyclerViewAdapter(MainActivity.this, mUploads);
            mRecyclerView.setAdapter(mAdapter);
        }

        @Override
        public void onCancelled(@NonNull DatabaseError databaseError) {
            Toast.makeText(MainActivity.this, databaseError.getMessage(), Toast.LENGTH_SHORT).show();
        }
    });

    Button btn_post = (Button) findViewById(R.id.post_Main);
    btn_post.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent intent_posts = new Intent(MainActivity.this, Posts.class);
            startActivity(intent_posts);

        }
    });

}
</code>```

Code from my Adapter class is

```<code>public class RecyclerViewAdapter extends RecyclerView.Adapter<RecyclerViewAdapter.rViewHolder> {

private Context mContext;
private List<Upload> mUploads;

public RecyclerViewAdapter(Context context, List<Upload> uploads){
    mContext = context;
    mUploads = uploads;
}

@Override
public rViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
    View view = LayoutInflater.from(mContext).inflate(R.layout.card_view_recycler_view, parent, false);
    return new rViewHolder(view);
}

@Override
public void onBindViewHolder(@NonNull rViewHolder viewHolder, int position) {
    Upload uploadCurrent = mUploads.get(position);
    viewHolder.textViewDescription.setText(uploadCurrent.getDescription());
    Picasso.get().load(uploadCurrent.getImageUrl()).into(viewHolder.imageView);

}

@Override
public int getItemCount() {
    return mUploads.size();
}

public class rViewHolder extends RecyclerView.ViewHolder{
    public TextView textViewDescription;
    public ImageView imageView;

    public  rViewHolder(View itemView){
        super(itemView);
        textViewDescription = itemView.findViewById(R.id.r_description);
        imageView = itemView.findViewById(R.id.r_image_view);
    }
}
</code>```

答:
If you uninstall the app and install it again and there are duplicate items in the list the first time you run the app after installing, then there are duplicate items in the backend Firebase. If there are duplicate items only the second time you run the app then your code is responsible.

The code you have showed looks good to me. There have to be something else your not showing like by mistake you have duplicate addValueEventListener or you are feeding the Adapter a second time with the List<Upload> mUploads

As many suggest here that you do the mUploads.clear(); is not necessary since you populating the array from the onCreate(), witch only run once during Activity lifecykle

I would move the private List<Upload> mUploads; inside the onCreate() as a local variable if your not using it elsewhere

Title: Repeated Items in RecyclerView

Body:
I am having problems with repeated items in RecyclerView. Whenever I upload to my firebase and open the main activity again there are repeated itmes in the recyclerView from the previous load. How do I remove repeated items from my recyclerView.

Code for my Main Activity is

private RecyclerView mRecyclerView;
private RecyclerViewAdapter mAdapter;

private DatabaseReference mDatabaseReference;
private List<Upload> mUploads;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_posts);
    setupBottomNavigation();

    mRecyclerView = findViewById(R.id.recycler_view);
    mRecyclerView.setHasFixedSize(true);
    mRecyclerView.setLayoutManager(new LinearLayoutManager(this));

    mUploads = new ArrayList<>();

    mDatabaseReference = FirebaseDatabase.getInstance().getReference("uploads");

    mDatabaseReference.addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
            for(DataSnapshot postSnapshot : dataSnapshot.getChildren())
            {
                Upload upload = postSnapshot.getValue(Upload.class);
                mUploads.add(upload);
            }
            mAdapter = new RecyclerViewAdapter(MainActivity.this, mUploads);
            mRecyclerView.setAdapter(mAdapter);
        }

        @Override
        public void onCancelled(@NonNull DatabaseError databaseError) {
            Toast.makeText(MainActivity.this, databaseError.getMessage(), Toast.LENGTH_SHORT).show();
        }
    });

    Button btn_post = (Button) findViewById(R.id.post_Main);
    btn_post.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent intent_posts = new Intent(MainActivity.this, Posts.class);
            startActivity(intent_posts);

        }
    });

}

Code from my Adapter class is

public class RecyclerViewAdapter extends RecyclerView.Adapter<RecyclerViewAdapter.rViewHolder> {

private Context mContext;
private List<Upload> mUploads;

public RecyclerViewAdapter(Context context, List<Upload> uploads){
    mContext = context;
    mUploads = uploads;
}

@Override
public rViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
    View view = LayoutInflater.from(mContext).inflate(R.layout.card_view_recycler_view, parent, false);
    return new rViewHolder(view);
}

@Override
public void onBindViewHolder(@NonNull rViewHolder viewHolder, int position) {
    Upload uploadCurrent = mUploads.get(position);
    viewHolder.textViewDescription.setText(uploadCurrent.getDescription());
    Picasso.get().load(uploadCurrent.getImageUrl()).into(viewHolder.imageView);

}

@Override
public int getItemCount() {
    return mUploads.size();
}

public class rViewHolder extends RecyclerView.ViewHolder{
    public TextView textViewDescription;
    public ImageView imageView;

    public  rViewHolder(View itemView){
        super(itemView);
        textViewDescription = itemView.findViewById(R.id.r_description);
        imageView = itemView.findViewById(R.id.r_image_view);
    }
}


问:
java.lang.NoClassDefFoundError: org/apache/avro/LogicalType while reading Parquet
I'm trying to read a parquet file, with this simple code:

  ParquetReader<GenericRecord> reader = AvroParquetReader.<GenericRecord>builder(path).build());
  GenericRecord record = reader.read();
```

<p>But getting NoClassDefFoundError for org.apache.avro.LogicalType. Any ideas what I am doing wrong?</p>

<p>my version in pom.xml:</p>

<pre class="lang-xml prettyprint-override"><code>    <dependency>
      <groupId>org.apache.parquet</groupId>
      <artifactId>parquet-avro</artifactId>
      <version>1.10.1</version>
    </dependency>
</code>```

full stack trace

```<code>java.lang.NoClassDefFoundError: org/apache/avro/LogicalType
    at org.apache.parquet.avro.AvroRecordConverter.<clinit>(AvroRecordConverter.java:840)
    at org.apache.parquet.avro.AvroRecordMaterializer.<init>(AvroRecordMaterializer.java:33)
    at org.apache.parquet.avro.AvroReadSupport.prepareForRead(AvroReadSupport.java:138)
    at org.apache.parquet.hadoop.InternalParquetRecordReader.initialize(InternalParquetRecordReader.java:183)
    at org.apache.parquet.hadoop.ParquetReader.initReader(ParquetReader.java:156)
    at org.apache.parquet.hadoop.ParquetReader.read(ParquetReader.java:135)
    at cz.seznam.robot.calc.scrank.fulltext.io.ParquetFulltextConverterTest.test(ParquetFulltextConverterTest.java:47)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
    at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
    at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
    at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
    at org.junit.rules.ExternalResource$1.evaluate(ExternalResource.java:48)
    at org.junit.rules.RunRules.evaluate(RunRules.java:20)
    at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
    at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:78)
    at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:57)
    at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
    at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
    at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
    at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
    at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
    at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
    at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:86)
    at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:538)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:760)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:460)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:206)
Caused by: java.lang.ClassNotFoundException: org.apache.avro.LogicalType
    at java.net.URLClassLoader.findClass(URLClassLoader.java:381)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
    at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:338)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
    ... 32 more

</code>```

答:
Ohghg...I had wrong versions of avro, working is this combination</p>

```<code><dependency>
   <groupId>org.apache.parquet</groupId>
   <artifactId>parquet-avro</artifactId>
   <version>1.10.1</version>
</dependency>
<dependency>
    <groupId>org.apache.avro</groupId>
    <artifactId>avro</artifactId>
    <version>1.9.0</version>
</dependency>
</code>```

Body:
I'm trying to read a parquet file, with this simple code:

  ParquetReader<GenericRecord> reader = AvroParquetReader.<GenericRecord>builder(path).build());
  GenericRecord record = reader.read();

But getting NoClassDefFoundError for org.apache.avro.LogicalType. Any ideas what I am doing wrong?

my version in pom.xml:

    <dependency>
      <groupId>org.apache.parquet</groupId>
      <artifactId>parquet-avro</artifactId>
      <version>1.10.1</version>
    </dependency>

full stack trace

java.lang.NoClassDefFoundError: org/apache/avro/LogicalType
    at org.apache.parquet.avro.AvroRecordConverter.<clinit>(AvroRecordConverter.java:840)
    at org.apache.parquet.avro.AvroRecordMaterializer.<init>(AvroRecordMaterializer.java:33)
    at org.apache.parquet.avro.AvroReadSupport.prepareForRead(AvroReadSupport.java:138)
    at org.apache.parquet.hadoop.InternalParquetRecordReader.initialize(InternalParquetRecordReader.java:183)
    at org.apache.parquet.hadoop.ParquetReader.initReader(ParquetReader.java:156)
    at org.apache.parquet.hadoop.ParquetReader.read(ParquetReader.java:135)
    at cz.seznam.robot.calc.scrank.fulltext.io.ParquetFulltextConverterTest.test(ParquetFulltextConverterTest.java:47)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
    at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
    at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
    at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
    at org.junit.rules.ExternalResource$1.evaluate(ExternalResource.java:48)
    at org.junit.rules.RunRules.evaluate(RunRules.java:20)
    at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
    at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:78)
    at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:57)
    at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
    at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
    at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
    at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
    at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
    at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
    at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:86)
    at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:538)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:760)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:460)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:206)
Caused by: java.lang.ClassNotFoundException: org.apache.avro.LogicalType
    at java.net.URLClassLoader.findClass(URLClassLoader.java:381)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
    at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:338)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
    ... 32 more

Body:
Ohghg...I had wrong versions of avro, working is this combination

<dependency>
   <groupId>org.apache.parquet</groupId>
   <artifactId>parquet-avro</artifactId>
   <version>1.10.1</version>
</dependency>
<dependency>
    <groupId>org.apache.avro</groupId>
    <artifactId>avro</artifactId>
    <version>1.9.0</version>
</dependency>


问:
How to mount local directory to concourse pipeline job?
I am trying to connect local git repository to concourse so that i can perform automated testing on my local environment even before committing the code to GitRepo. In other terms i want to perform some tasks before git commit using concourse pipeline for which i want to mount my local working directory to concourse pipeline jobs.</p>

答:
You can't run a pipeline or a complete job with a local repository, only a task. But that's OK, as a job main goal is to setup inputs and outputs for a task, and you will be providing them locally

The command is fly execute, and the complete doc is here : https://concourse-ci.org/tasks.html#running-tasks

To run a tasks locally you will have to have the task in a separate yaml file, not inline in your pipeline.

The basic command where you run the task run-tests.yml with the input repository set to the current directory:

```<code>fly -t my_target execute --config run-tests.yml --input repository=.
</code>```

Body:
You can't run a pipeline or a complete job with a local repository, only a task. But that's OK, as a job main goal is to setup inputs and outputs for a task, and you will be providing them locally

The command is fly execute, and the complete doc is here : https://concourse-ci.org/tasks.html#running-tasks

To run a tasks locally you will have to have the task in a separate yaml file, not inline in your pipeline.

The basic command where you run the task run-tests.yml with the input repository set to the current directory:

fly -t my_target execute --config run-tests.yml --input repository=.


问:
Call Method that inside Another Component - React Js
i need to know how to fetch state of component from other component by calling the seconed component method inside of first component ?
like :

class General extends Component {

  state = {
    input:"
   }

   fetchState() {
    return this.state;
   }

  handleChange () {
    this.setState({[e.target.name]: e.traget.value});
  }

  render() {
    return <input type="text" name="input" onChange={this.handleChange.bind(this}>
  }

}

class Car extends Component {

  render() {
    console.log( General.fetchState() );
    return null;
  }

}```

i know i can use static method but i don't have access to this keyword.

答:
The recommended way of doing that kind of things is by composing components and passing the parent's states as props

```<code>class General extends Component {
  state = { ... }

  render () {
    return (
      <Car {...this.state} />
    )
  }
}

class Car extends Component {
  render () {
    console.log(this.props)
    return (...)
  }
}
</code>```

Now if you want to share a global state between components could be a good idea to use context api with hooks.

```<code>import React, { createContext, useContext } from "react";
import ReactDom from "react-dom";

const initialState = { sharedValue: "Simple is better" };
const StateContext = createContext({});

const General = () => {
  const globalState = useContext(StateContext);
  return <h1>General: {globalState.sharedValue}</h1>;
};

const Car = () => {
  const globalState = useContext(StateContext);
  return <h1>Car: {globalState.sharedValue}</h1>;
};

const App = () => {
  return (
    <StateContext.Provider value={initialState}>
      <General />
      <Car />
    </StateContext.Provider>
  );
};

ReactDom.render(
  <App />,
  document.getElementById("root")
);
</code>```

Here is the example link.

And here I have a repo with a more elaborated example managing global state with just hooks.

Body:
i need to know how to fetch state of component from other component by calling the seconed component method inside of first component ?
like :

class General extends Component {

  state = {
    input:"
   }

   fetchState() {
    return this.state;
   }

  handleChange () {
    this.setState({[e.target.name]: e.traget.value});
  }

  render() {
    return <input type="text" name="input" onChange={this.handleChange.bind(this}>
  }

}

class Car extends Component {

  render() {
    console.log( General.fetchState() );
    return null;
  }

}

i know i can use static method but i don't have access to this keyword.

Body:
The recommended way of doing that kind of things is by composing components and passing the parent's states as props

class General extends Component {
  state = { ... }

  render () {
    return (
      <Car {...this.state} />
    )
  }
}

class Car extends Component {
  render () {
    console.log(this.props)
    return (...)
  }
}

Now if you want to share a global state between components could be a good idea to use context api with hooks.

import React, { createContext, useContext } from "react";
import ReactDom from "react-dom";

const initialState = { sharedValue: "Simple is better" };
const StateContext = createContext({});

const General = () => {
  const globalState = useContext(StateContext);
  return <h1>General: {globalState.sharedValue}</h1>;
};

const Car = () => {
  const globalState = useContext(StateContext);
  return <h1>Car: {globalState.sharedValue}</h1>;
};

const App = () => {
  return (
    <StateContext.Provider value={initialState}>
      <General />
      <Car />
    </StateContext.Provider>
  );
};

ReactDom.render(
  <App />,
  document.getElementById("root")
);

Here is the example link.

And here I have a repo with a more elaborated example managing global state with just hooks.


问:
Not able to get the response from asp.net core controller end point in reactjs response
I am new to ASP.NET Core and React js.
I am not able to get the response in React from the ASP.NET controller endpoint. All code at the backend is executing from start to return response line and getting data at the return line but in the response of react js, I am not able to see the data.

I tried :

```<code>  public void ConfigureServices(IServiceCollection services)
        {

            services.AddMvc(options =>
            {
                options.InputFormatters.Add(new BypassFormDataInputFormatter());
                options.RespectBrowserAcceptHeader = true;
                options.InputFormatters.Add(new BypassFormDataInputFormatter());
                options.OutputFormatters.Add(new XmlSerializerOutputFormatter());
      }).AddXmlSerializerFormatters().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
}
</code>```

this is my front end :

```<code>getRecordsByPaging = (pagingData) => {
    debugger
    var jsonData = JSON.stringify(pagingData);
    return fetch('/get-products', {
        method: 'POST',
        body: jsonData,
        headers: {
            'Content-Type': 'application/json',
            'Accept': 'application/json'
        }
    }).then(res => {
        return res;
    }).catch(err => err);
}
</code>```

this is my backend:

```<code>    [HttpPost]
    [Route("get-products")]
    public async Task<IActionResult> GetCustomers([FromBody] req)
    {
        try
        {
            if (!ModelState.IsValid)
            {
                return null;
            }
            var response = await _productSvc.GetProducts(req);
            if (response == null)
            {
                return null;
            }

            return Ok(response);

        }
        catch (Exception e)
        {
            return null;
        }

    }
</code>```

I do not know what am doing wrong .

I am getting at react js side :

```<code>body: (...)
bodyUsed: false
headers: Headers {}
ok: true
redirected: false
status: 200
statusText: ""
type: "basic"
url: "https://localhost:44384/get-products"
__proto__: Response
</code>```

答:
You need to read the actual response of your ajax request:

```<code>getRecordsByPaging = (pagingData) => {
    var jsonData = JSON.stringify(pagingData);
    return fetch('/get-products', {
        method: 'POST',
        body: jsonData,
        headers: {
            'Content-Type': 'application/json',
            'Accept': 'application/json'
        }
    })
    .then(r => r.json())
    .then(res => {
        return res;
    }).catch(err => err);
}
</code>```

As you can see, the added line is .then(r => r.json()) which will actually get the JSON response from your request.

You can read more about the fetch api at https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch

Basic fetch:

A basic fetch request is really simple to set up. Have a look at the
  following code:

```<code>fetch('http://example.com/movies.json')
  .then(function(response) {
    return response.json();
  })
  .then(function(myJson) {
    console.log(JSON.stringify(myJson));
  });
</code>```

Here we are fetching a JSON file across the network and print it to
  the console. The simplest use of fetch() takes one argument — the path
  to the resource you want to fetch — and returns a promise containing
  the response (a Response object).

This is just an HTTP response of course, not the actual JSON. To
  extract the JSON body content from the response, we use the json()
  method (defined on the Body mixin, which is implemented by both the
  Request and Response objects.)

Body:
I am new to ASP.NET Core and React js.
I am not able to get the response in React from the ASP.NET controller endpoint. All code at the backend is executing from start to return response line and getting data at the return line but in the response of react js, I am not able to see the data.

I tried :

  public void ConfigureServices(IServiceCollection services)
        {

            services.AddMvc(options =>
            {
                options.InputFormatters.Add(new BypassFormDataInputFormatter());
                options.RespectBrowserAcceptHeader = true;
                options.InputFormatters.Add(new BypassFormDataInputFormatter());
                options.OutputFormatters.Add(new XmlSerializerOutputFormatter());
      }).AddXmlSerializerFormatters().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
}

this is my front end :

getRecordsByPaging = (pagingData) => {
    debugger
    var jsonData = JSON.stringify(pagingData);
    return fetch('/get-products', {
        method: 'POST',
        body: jsonData,
        headers: {
            'Content-Type': 'application/json',
            'Accept': 'application/json'
        }
    }).then(res => {
        return res;
    }).catch(err => err);
}

this is my backend:

    [HttpPost]
    [Route("get-products")]
    public async Task<IActionResult> GetCustomers([FromBody] req)
    {
        try
        {
            if (!ModelState.IsValid)
            {
                return null;
            }
            var response = await _productSvc.GetProducts(req);
            if (response == null)
            {
                return null;
            }

            return Ok(response);

        }
        catch (Exception e)
        {
            return null;
        }

    }

I do not know what am doing wrong .

I am getting at react js side :

body: (...)
bodyUsed: false
headers: Headers {}
ok: true
redirected: false
status: 200
statusText: ""
type: "basic"
url: "https://localhost:44384/get-products"
__proto__: Response

Body:
You need to read the actual response of your ajax request:

getRecordsByPaging = (pagingData) => {
    var jsonData = JSON.stringify(pagingData);
    return fetch('/get-products', {
        method: 'POST',
        body: jsonData,
        headers: {
            'Content-Type': 'application/json',
            'Accept': 'application/json'
        }
    })
    .then(r => r.json())
    .then(res => {
        return res;
    }).catch(err => err);
}

As you can see, the added line is .then(r => r.json()) which will actually get the JSON response from your request.

You can read more about the fetch api at https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch

Basic fetch:

A basic fetch request is really simple to set up. Have a look at the
  following code:

fetch('http://example.com/movies.json')
  .then(function(response) {
    return response.json();
  })
  .then(function(myJson) {
    console.log(JSON.stringify(myJson));
  });

Here we are fetching a JSON file across the network and print it to
  the console. The simplest use of fetch() takes one argument — the path
  to the resource you want to fetch — and returns a promise containing
  the response (a Response object).

This is just an HTTP response of course, not the actual JSON. To
  extract the JSON body content from the response, we use the json()
  method (defined on the Body mixin, which is implemented by both the
  Request and Response objects.)


问:
How to extract number suffix from a filename
In Java I have a filename example ABC.12.txt.gz, I want to extract number 12 from the filename. Currently I am using last index method and extracting substring multiple times.</p>

答:
We can use something like this to extract the number from a string</p>

```<code> String fileName="ABC.12.txt.gz";
 String numberOnly= fileName.replaceAll("[^0-9]", "");
</code>```

Body:
We can use something like this to extract the number from a string

 String fileName="ABC.12.txt.gz";
 String numberOnly= fileName.replaceAll("[^0-9]", "");


问:
Nested Grid IN EXTJS
HI

How to design Nested grids in ExtJS
Please provide some samples(How to use RowExpander in ExtJS GridPanel)

答:
Try something like this:

```<code> //Create the Row Expander.
var expander = new Ext.ux.grid.RowExpander({
     tpl : new Ext.Template('<div id="myrow-{Id}" ></div>')
});

//Define the function to be called when the row is expanded.
function expandedRow(obj, record, body, rowIndex){
    //absId parameter for the http request to get the absence details.
    var absId = record.get('Id');

    var dynamicStore = //the new store for the nested grid.

    //Use Id to give each grid a unique identifier. The Id is used in the row expander tpl.
    //and in the grid.render("ID") method.
    var row = "myrow-" + record.get("Id");
    var id2 = "mygrid-" + record.get("Id");

   //Create the nested grid.
   var gridX = new Ext.grid.GridPanel({
        store: dynamicStore,
        stripeRows: true,
        columns: [
            //columns
        ],
        height: 120,
        id: id2
    });

    //Render the grid to the row expander template(tpl).
    gridX.render(row);
    gridX.getEl().swallowEvent([ 'mouseover', 'mousedown', 'click', 'dblclick' ]);
}

//Add an expand listener to the Row Expander.
expander.on('expand', expandedRow);
</code>```

You can find more information on this Here

Title: Nested Grid IN EXTJS

Body:
Try something like this:

 //Create the Row Expander.
var expander = new Ext.ux.grid.RowExpander({
     tpl : new Ext.Template('<div id="myrow-{Id}" ></div>')
});

//Define the function to be called when the row is expanded.
function expandedRow(obj, record, body, rowIndex){
    //absId parameter for the http request to get the absence details.
    var absId = record.get('Id');

    var dynamicStore = //the new store for the nested grid.

    //Use Id to give each grid a unique identifier. The Id is used in the row expander tpl.
    //and in the grid.render("ID") method.
    var row = "myrow-" + record.get("Id");
    var id2 = "mygrid-" + record.get("Id");

   //Create the nested grid.
   var gridX = new Ext.grid.GridPanel({
        store: dynamicStore,
        stripeRows: true,
        columns: [
            //columns
        ],
        height: 120,
        id: id2
    });

    //Render the grid to the row expander template(tpl).
    gridX.render(row);
    gridX.getEl().swallowEvent([ 'mouseover', 'mousedown', 'click', 'dblclick' ]);
}

//Add an expand listener to the Row Expander.
expander.on('expand', expandedRow);

You can find more information on this Here


问:
How to redirect from one page to another one with changing wp query and without reloading page?
The problem

There is a URL:
https://example.com/my-category/category

Need to create another one
https://example.com/shop

Behavior to achieve:

By visiting https://example.com/shop content and all query variables need to be identical like for https://example.com/my-category/category

https://example.com/my-category/category and https://example.com/shop - need to be the same.
Meta tags, title, and other content need to be identical.

Need to create an inner redirect

from https://example.com/shop

to https://example.com/my-category/category without reloading page.

This is the snippet what I've tried

flush_rewrite_rules();
add_rewrite_rule(
  '/shop?$',
  'index.php?product_cat=my-category',
  'top'
);

I expect to see the same page for these two URLs

https://example.com/my-category/category
and
https://example.com/shop

The second one needs to be redirected to the first one.

答:
I have found a solution via request filter

```<code>function example_rewrite_request($query){
    $request_uri = urldecode( $_SERVER['REQUEST_URI'] );

    $parsed_url = parse_url( $request_uri );

    if (  preg_match( '/^\/shop/', $parsed_url['path'] ) ) {
        $query['product_cat'] = 'my-category';
        unset( $query['post_type'] );

        return $query;
    }

    return $query;
}
</code>```

add_filter( 'request', 'example_rewrite_request', 9999, 1 );

Body:
I have found a solution via request filter

function example_rewrite_request($query){
    $request_uri = urldecode( $_SERVER['REQUEST_URI'] );

    $parsed_url = parse_url( $request_uri );

    if (  preg_match( '/^\/shop/', $parsed_url['path'] ) ) {
        $query['product_cat'] = 'my-category';
        unset( $query['post_type'] );

        return $query;
    }

    return $query;
}

add_filter( 'request', 'example_rewrite_request', 9999, 1 );


问:
Empty Data Error when checking if CSV is empty
I got a CSV file which sometimes it's empty and sometimes got content in it. I am trying to check if the CSV is empty or not, so I could know if to append to it or recreate it.

I have tried this:

```<code>check_df = pd.read_csv(r'my file')
if check_df.empty:
    csvfile = open(r'my file', 'w', newline='')
    obj = csv.writer(csvfile)
    obj.writerow(["date", "bmo amc", "stock symbol","company name"])
    print("csv empty")
else:
    csvfile = open(r'my file', 'a', newline='')
    obj = csv.writer(csvfile)
    print("appending csv")
</code>```

this code gives me the error:

```pandas.errors.EmptyDataError: No columns to parse from file```

pretty new to python if you can please be clear with the answers thanks.

答:
You should check to see if the file is empty using the python library instead of using pandas

in your case the file is 136bytes when empty so:

```<code>import os
if os.path.getsize('my file') < 137:
    csvfile = open(r'my file', 'a', newline='')
    obj = csv.writer(csvfile)
    print("appending csv")
else:
    csvfile = open(r'my file', 'w', newline='')
    obj = csv.writer(csvfile)
    obj.writerow(["date", "bmo amc", "stock symbol","company name"])
    print("csv empty")
</code>```

Body:
I got a CSV file which sometimes it's empty and sometimes got content in it. I am trying to check if the CSV is empty or not, so I could know if to append to it or recreate it.

I have tried this:

check_df = pd.read_csv(r'my file')
if check_df.empty:
    csvfile = open(r'my file', 'w', newline='')
    obj = csv.writer(csvfile)
    obj.writerow(["date", "bmo amc", "stock symbol","company name"])
    print("csv empty")
else:
    csvfile = open(r'my file', 'a', newline='')
    obj = csv.writer(csvfile)
    print("appending csv")

this code gives me the error:

pandas.errors.EmptyDataError: No columns to parse from file

pretty new to python if you can please be clear with the answers thanks.

Body:
You should check to see if the file is empty using the python library instead of using pandas

in your case the file is 136bytes when empty so:

import os
if os.path.getsize('my file') < 137:
    csvfile = open(r'my file', 'a', newline='')
    obj = csv.writer(csvfile)
    print("appending csv")
else:
    csvfile = open(r'my file', 'w', newline='')
    obj = csv.writer(csvfile)
    obj.writerow(["date", "bmo amc", "stock symbol","company name"])
    print("csv empty")


问:
How do I compile C++ to JavaScript in a browser?
I'm aware of Emscripten and LLVM, but neither are written in JavaScript intended for a browser.

As far as I can tell, the tools exist, but they haven't been put together, but I could very well be missing some key factor that makes it very difficult to compile C++ to JavaScript in a browser.

So I'll mention my naive implementation:

Compile Emscripten to C, then use Clang to compile it to LLVM, then use Emscripten to compile it to JavaScript.

Compile Clang to LLVM, then compile that to JavaScript through Emscripten.

Write some C++ and run it through JavaScript Clang, then run that LLVM through Emscripten to get JavaSscript

Run the resulting JavaScript!

I'm sure I'm missing something from my steps. Please let me know, and let me know if there are any efforts by the community to resolve those missing pieces.

EDIT: JSCPP is the closest I've found, but it lacks a lot of features and frankly the author took on an absurd undertaking, by trying to rewrite the parser etc. on his own, rather than using existing tools. Still, close and pretty neat.

答:
It is possible to compile C++ to JavaScript using a self-hosting version of Emscripten that runs in a browser, such as emception.

Alternatively, it is possible to run a C++ compiler (or even an entire operating system) using an x86 emulator in JavaScript.


问:
How to fetch a one table from HTML source file using lwp module?
I'm beginner. I want to know how to fetch one table form the source HTML file using LWP module? Is it possible to use Regex with LWP?</p>

答:
```<code>use Web::Query::LibXML 'wq';

wq('https://www.december.com/html/demo/table.html')
    ->find('table th')
    ->each(sub {
        my (undef, $e) = @_;
        print $e->text . "\n";
    });
__END__
Outer Table
Inner Table
CORNER
Head1
Head2
Head3
Head4
Head5
Head6
Little
</code>```


问:
Add cols in grid from variable with scss
Is it possible to make number of cols in grid-template-columns from a variable?

I have a variable $num-of-cols: 5; That I use to make classes whit scss and it works fine, but I also want to use the same variable to make cols for grid-template-columns.

Like: grid-template-columns: [col-1] $width-cols [col-2] $width-cols [col-3] $width-cols [col-4] $width-cols [col-5] $width-cols [col-6];

$width-cols should be calculatet 100%/$num-of-cols-$grid-gutter-width.
(The names is important and goes from 1 up till $num-of-cols).

```<code>$grid-gutter-width: 1rem;
$num-of-cols: 5;
$width-cols: calc(100%/#{$num-of-cols} - #{$grid-gutter-width});
.grid {
    display: grid;
    grid-gap: $grid-gutter-width;
    padding: $grid-gutter-width;
    padding-right: 0;
    grid-template-columns: [col-1] $width-cols [col-2] $width-cols [col-3] $width-cols [col-4] $width-cols [col-5] $width-cols [col-6];
    grid-template-rows: auto;
}
</code>```

答:
You can use a mixin (or a function) – like:

SCSS

```<code>$grid-gutter-width: 1rem;
$num-of-cols: 5;
$width-cols: calc(100%/#{$num-of-cols} - #{$grid-gutter-width});
@mixin grid-template-columns {
    $columns: [col-1],;  // note trailing comma indicates list
    @for $i from 2 through $num-of-cols + 1 {
        $columns: append($columns, $width-cols [col-#{$i}], space);
    }
    grid-template-columns: $columns;
}

.grid {
    display: grid;
    grid-gap: $grid-gutter-width;
    padding: $grid-gutter-width;
    padding-right: 0;
    @include grid-template-columns; // <= include
    grid-template-rows: auto;
}

</code>```

CSS

```<code>.grid {
  display: grid;
  grid-gap: 1rem;
  padding: 1rem;
  padding-right: 0;
  grid-template-columns: [col-1] calc(100%/5 - 1rem) [col-2] calc(100%/5 - 1rem) [col-3] calc(100%/5 - 1rem) [col-4] calc(100%/5 - 1rem) [col-5] calc(100%/5 - 1rem) [col-6];
  grid-template-rows: auto;
}
</code>```

Body:
Is it possible to make number of cols in grid-template-columns from a variable?

I have a variable $num-of-cols: 5; That I use to make classes whit scss and it works fine, but I also want to use the same variable to make cols for grid-template-columns.

Like: grid-template-columns: [col-1] $width-cols [col-2] $width-cols [col-3] $width-cols [col-4] $width-cols [col-5] $width-cols [col-6];

$width-cols should be calculatet 100%/$num-of-cols-$grid-gutter-width.
(The names is important and goes from 1 up till $num-of-cols).

$grid-gutter-width: 1rem;
$num-of-cols: 5;
$width-cols: calc(100%/#{$num-of-cols} - #{$grid-gutter-width});
.grid {
    display: grid;
    grid-gap: $grid-gutter-width;
    padding: $grid-gutter-width;
    padding-right: 0;
    grid-template-columns: [col-1] $width-cols [col-2] $width-cols [col-3] $width-cols [col-4] $width-cols [col-5] $width-cols [col-6];
    grid-template-rows: auto;
}

Body:
You can use a mixin (or a function) – like:

SCSS

$grid-gutter-width: 1rem;
$num-of-cols: 5;
$width-cols: calc(100%/#{$num-of-cols} - #{$grid-gutter-width});
@mixin grid-template-columns {
    $columns: [col-1],;  // note trailing comma indicates list
    @for $i from 2 through $num-of-cols + 1 {
        $columns: append($columns, $width-cols [col-#{$i}], space);
    }
    grid-template-columns: $columns;
}

.grid {
    display: grid;
    grid-gap: $grid-gutter-width;
    padding: $grid-gutter-width;
    padding-right: 0;
    @include grid-template-columns; // <= include
    grid-template-rows: auto;
}

CSS

.grid {
  display: grid;
  grid-gap: 1rem;
  padding: 1rem;
  padding-right: 0;
  grid-template-columns: [col-1] calc(100%/5 - 1rem) [col-2] calc(100%/5 - 1rem) [col-3] calc(100%/5 - 1rem) [col-4] calc(100%/5 - 1rem) [col-5] calc(100%/5 - 1rem) [col-6];
  grid-template-rows: auto;
}


问:
How does docker container access Internet
I have docker installed (Docker for Mac).
I start a new container with

```<code>docker run -it ubuntu
</code>```

I can see that my newly created container has internet access by simply invoking

```<code>ping google.com
</code>```

I see:

```<code>root@b06e1a46cc40:/# ping google.com
PING google.com (216.58.209.14) 56(84) bytes of data.
64 bytes from sof01s12-in-f14.1e100.net (216.58.209.14): icmp_seq=1 ttl=37 time=63.0 ms
64 bytes from sof01s12-in-f14.1e100.net (216.58.209.14): icmp_seq=2 ttl=37 time=63.7 ms
64 bytes from sof01s12-in-f14.1e100.net (216.58.209.14): icmp_seq=3 ttl=37 time=64.8 ms
</code>```

Next, I checked the networks that my container is connected to:

```<code>root@b06e1a46cc40:/# ip addr show
1: lo: <LOOPBACK,UP,LOWER_UP> mtu 65536 qdisc noqueue state UNKNOWN group default qlen 1
    link/loopback 00:00:00:00:00:00 brd 00:00:00:00:00:00
    inet 127.0.0.1/8 scope host lo
       valid_lft forever preferred_lft forever
2: tunl0@NONE: <NOARP> mtu 1480 qdisc noop state DOWN group default qlen 1
    link/ipip 0.0.0.0 brd 0.0.0.0
3: ip6tnl0@NONE: <NOARP> mtu 1452 qdisc noop state DOWN group default qlen 1
    link/tunnel6 :: brd ::
6: eth0@if7: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc noqueue state UP group default
    link/ether 02:42:ac:11:00:02 brd ff:ff:ff:ff:ff:ff link-netnsid 0
    inet 172.17.0.2/16 brd 172.17.255.255 scope global eth0
       valid_lft forever preferred_lft forever
root@b06e1a46cc40:/#
</code>```

As I understand, eth0 is used to access internet - it is a network 172.17.0.0/16.

When I look at network list of my host, I'm not connected to this network.

How does my container access internet then?

As I understand it, my container should access internet through my host, because, after all, my host is connected to internet, so this is the only way to access.

答:
From my understanding, Docker containers have an isolated network to which multiple containers can connect. Containers in the same network can immediately communicate with each other. This internal network can be made available to the internet.
See this documentation: https://docs.docker.com/v17.09/engine/userguide/networking/#bridge-networks </p>

Body:
I have docker installed (Docker for Mac).
I start a new container with

docker run -it ubuntu

I can see that my newly created container has internet access by simply invoking

ping google.com

I see:

root@b06e1a46cc40:/# ping google.com
PING google.com (216.58.209.14) 56(84) bytes of data.
64 bytes from sof01s12-in-f14.1e100.net (216.58.209.14): icmp_seq=1 ttl=37 time=63.0 ms
64 bytes from sof01s12-in-f14.1e100.net (216.58.209.14): icmp_seq=2 ttl=37 time=63.7 ms
64 bytes from sof01s12-in-f14.1e100.net (216.58.209.14): icmp_seq=3 ttl=37 time=64.8 ms

Next, I checked the networks that my container is connected to:

root@b06e1a46cc40:/# ip addr show
1: lo: <LOOPBACK,UP,LOWER_UP> mtu 65536 qdisc noqueue state UNKNOWN group default qlen 1
    link/loopback 00:00:00:00:00:00 brd 00:00:00:00:00:00
    inet 127.0.0.1/8 scope host lo
       valid_lft forever preferred_lft forever
2: tunl0@NONE: <NOARP> mtu 1480 qdisc noop state DOWN group default qlen 1
    link/ipip 0.0.0.0 brd 0.0.0.0
3: ip6tnl0@NONE: <NOARP> mtu 1452 qdisc noop state DOWN group default qlen 1
    link/tunnel6 :: brd ::
6: eth0@if7: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc noqueue state UP group default
    link/ether 02:42:ac:11:00:02 brd ff:ff:ff:ff:ff:ff link-netnsid 0
    inet 172.17.0.2/16 brd 172.17.255.255 scope global eth0
       valid_lft forever preferred_lft forever
root@b06e1a46cc40:/#

As I understand, eth0 is used to access internet - it is a network 172.17.0.0/16.

When I look at network list of my host, I'm not connected to this network.

How does my container access internet then?

As I understand it, my container should access internet through my host, because, after all, my host is connected to internet, so this is the only way to access.


问:
DataGrid column width doesn't auto-update
```<code><DataGridTextColumn Binding="{Binding Name}" Width="*"/>
<DataGridTextColumn Binding="{Binding Change}" Width="Auto"/>
</code>```

When the value of Change updates, its column doesn't update to fit the new value. So the column stays too small and the value is clipped.

Any ideas?

答:
i have had similar problem with my listview, the solution i found on how-to-autosize-and-right-align-gridviewcolumn-data-in-wpf here on stackoverflow.

In my case it was adding this piece of code into collectionchanged event handler of the observable collection the list view was bound to:

```<code>void listview_CollectionChanged(object sender, System.Collections.Specialized.NotifyCollectionChangedEventArgs e) {
        // this is a listview control
        GridView view = this.View as GridView;
        foreach(GridViewColumn c in view.Columns) {
            if(double.IsNaN(c.Width)) {
                c.Width = c.ActualWidth;
            }
            c.Width = double.NaN;
        }
    }
</code>```

It works for me, although sometimes the user can notice "blink" over the columns.

Body:
<DataGridTextColumn Binding="{Binding Name}" Width="*"/>
<DataGridTextColumn Binding="{Binding Change}" Width="Auto"/>

When the value of Change updates, its column doesn't update to fit the new value. So the column stays too small and the value is clipped.

Any ideas?

Body:
i have had similar problem with my listview, the solution i found on how-to-autosize-and-right-align-gridviewcolumn-data-in-wpf here on stackoverflow.

In my case it was adding this piece of code into collectionchanged event handler of the observable collection the list view was bound to:

void listview_CollectionChanged(object sender, System.Collections.Specialized.NotifyCollectionChangedEventArgs e) {
        // this is a listview control
        GridView view = this.View as GridView;
        foreach(GridViewColumn c in view.Columns) {
            if(double.IsNaN(c.Width)) {
                c.Width = c.ActualWidth;
            }
            c.Width = double.NaN;
        }
    }

It works for me, although sometimes the user can notice "blink" over the columns.


问:
Variables values in remotely executed complex bash commands
I want to run a complex list of commands on a remote host. I could solve easily by creating another script with such commands and then have my other script call it (with or without copying it to the remote host), but I do not want to. My issue is that I have some variables that are fixed for the whole script and then I have the for-loop variable. I can get one of the two to be properly evaluated on the remote host, but noth both. All I've found on similar issues is talks about using note quotes, " or ' around different elements. Nothing I've tried worked on both the fixed (to be expanded before ssh) and the loop variables (to be expanded remotely) at the same time (highlight for you, @Inian, since you can't fucking read the full question before marking it as duplicate of something it's not a duplicate of).

fixed_value="blue"

ssh remote_host << "EOF"
    value_list="VALUE1 VALUE2"
    for i in $value_list; do
        echo "executing $i"
        my_program -arg1 $i -arg2 "$fixed_value"
    done
EOF
```

<p>What I expect is to run my_program (which is a binary on the remote host) with two arguments, one is fixed and is actually passed as an input to the local script, the other is read from a list of fixed values, so that, in the example, I should end up executing on remote host the following:</p>

<pre class="lang-sh prettyprint-override"><code>my_program -arg1 VALUE1 -arg2 blue
my_program -arg1 VALUE2 -arg2 blue
</code>```

I probably need a way to 'pass values' to the script being executed in the remote host, or force evaluation of $fixed_value before the command is sent (which I tried to do by using quotes, but it didn't work), without preventing the evaluation of $i from being done on the remote host. Because all I get by switching around the quotes (or removing them, or changing them) is either:

my_program -arg1 -arg2 blue
my_program -arg1 -arg2 blue
```

<p>or</p>

<pre class="lang-sh prettyprint-override"><code>my_program -arg1 VALUE1 -arg2
my_program -arg1 VALUE2 -arg2
</code>```

答:
Restructured:

```<code>fixed_value="blue"
value_list=( VALUE1 VALUE2 )
for i in "${value_list[@]}"; do
    echo "executing $i"
    ssh remote_host "my_program -arg1 $i -arg2 $fixed_value"
done
</code>```

If you really want this to all be done in a single call, then write it as a script, scp it over, then ssh to call it on the target machine.

...or write it locally to a temp file :

```<code>$: cat a
echo '
fixed_value="blue"
value_list=( VALUE1 VALUE2 )
for i in "${value_list[@]}"; do
    echo "executing $i"
    echo "my_program -arg1 $i -arg2 $fixed_value"
done
'>/tmp/foo && . /tmp/foo && rm /tmp/foo
</code>```

and then run it as

```<code>ssh remote_host < a
</code>```

which produces:

```<code>Pseudo-terminal will not be allocated because stdin is not a terminal.
executing VALUE1
my_program -arg1 VALUE1 -arg2 blue
executing VALUE2
my_program -arg1 VALUE2 -arg2 blue
</code>```

Body:
I want to run a complex list of commands on a remote host. I could solve easily by creating another script with such commands and then have my other script call it (with or without copying it to the remote host), but I do not want to. My issue is that I have some variables that are fixed for the whole script and then I have the for-loop variable. I can get one of the two to be properly evaluated on the remote host, but noth both. All I've found on similar issues is talks about using note quotes, " or ' around different elements. Nothing I've tried worked on both the fixed (to be expanded before ssh) and the loop variables (to be expanded remotely) at the same time (highlight for you, @Inian, since you can't fucking read the full question before marking it as duplicate of something it's not a duplicate of).

fixed_value="blue"

ssh remote_host << "EOF"
    value_list="VALUE1 VALUE2"
    for i in $value_list; do
        echo "executing $i"
        my_program -arg1 $i -arg2 "$fixed_value"
    done
EOF

What I expect is to run my_program (which is a binary on the remote host) with two arguments, one is fixed and is actually passed as an input to the local script, the other is read from a list of fixed values, so that, in the example, I should end up executing on remote host the following:

my_program -arg1 VALUE1 -arg2 blue
my_program -arg1 VALUE2 -arg2 blue

I probably need a way to 'pass values' to the script being executed in the remote host, or force evaluation of $fixed_value before the command is sent (which I tried to do by using quotes, but it didn't work), without preventing the evaluation of $i from being done on the remote host. Because all I get by switching around the quotes (or removing them, or changing them) is either:

my_program -arg1 -arg2 blue
my_program -arg1 -arg2 blue

or

my_program -arg1 VALUE1 -arg2
my_program -arg1 VALUE2 -arg2

Body:
Restructured:

fixed_value="blue"
value_list=( VALUE1 VALUE2 )
for i in "${value_list[@]}"; do
    echo "executing $i"
    ssh remote_host "my_program -arg1 $i -arg2 $fixed_value"
done

If you really want this to all be done in a single call, then write it as a script, scp it over, then ssh to call it on the target machine.

...or write it locally to a temp file :

$: cat a
echo '
fixed_value="blue"
value_list=( VALUE1 VALUE2 )
for i in "${value_list[@]}"; do
    echo "executing $i"
    echo "my_program -arg1 $i -arg2 $fixed_value"
done
'>/tmp/foo && . /tmp/foo && rm /tmp/foo

and then run it as

ssh remote_host < a

which produces:

Pseudo-terminal will not be allocated because stdin is not a terminal.
executing VALUE1
my_program -arg1 VALUE1 -arg2 blue
executing VALUE2
my_program -arg1 VALUE2 -arg2 blue


问:
Efficiently add multiple lines to file by index
Given an input file data.dat like this one:

```<code># Some comment
# more comments
#
45.78
# aaa
0.056
0.67
# aaa
345.
0.78
99.
2.34
# aaa
65.7
0.9
</code>```

I need to add different comments above each line that starts with an "# aaa" so it looks like this:

```<code># Some comment
# more comments
#
45.78
# cmmt1
# aaa
0.056
0.67
# another cmmt
# aaa
345.
0.78
99.
2.34
# last one
# aaa
65.7
0.9
</code>```

I know a priori the number of "# aaa" comments present in the data.dat file,  but not their positions.

I have a way to do it (see code below) but it is quite complicated and not at all efficient. I need to apply this code to hundreds of large files, so I'm looking for an efficient way to do this.

```<code># Read file
with open("data.dat", mode="r") as f:
    data = f.readlines()

# Indexes of "# aaa" comments
idx = []
for i, line in enumerate(data):
    if line.startswith("# aaa"):
        idx.append(i)

# Insert new comments in their proper positions
add_data = ["# cmmt1\n", "# another cmmt\n", "# last one\n"]
for i, j in enumerate(idx):
    data.insert(j + i, add_data[i])

# Write final data to file
with open("data_final.dat", mode="w") as f:
    for item in data:
        f.write("{}".format(item))
</code>```

答:
I didn't do any benchmarks, but re.sub could be faster - just load the text file as whole, execute re.sub and write it out:

```<code>data = '''# Some comment
# more comments
#
45.78
# aaa
0.056
0.67
# aaa
345.
0.78
99.
2.34
# aaa
65.7
0.9'''

import re

def fn():
    add_data = ["# cmmt1\n", "# another cmmt\n", "# last one\n"]
    for d in add_data:
        yield d

out = re.sub(r'^# aaa', lambda r, f=fn(): next(f) + r.group(0), data, flags=re.MULTILINE)
print(out)
</code>```

Prints:

```<code># Some comment
# more comments
#
45.78
# cmmt1
# aaa
0.056
0.67
# another cmmt
# aaa
345.
0.78
99.
2.34
# last one
# aaa
65.7
0.9
</code>```

With files input/output:

```<code>import re

def fn():
    add_data = ["# cmmt1\n", "# another cmmt\n", "# last one\n"]
    for d in add_data:
        yield d

with open('data.dat', 'r') as f_in, \
    open('data.out', 'w') as f_out:
    f_out.write(re.sub(r'^# aaa', lambda r, f=fn(): next(f) + r.group(0), f_in.read(), flags=re.MULTILINE))
</code>```

Version 2:

```<code>import re

def fn():
    add_data = ["# cmmt1\n", "# another cmmt\n", "# last one\n"]
    add_data = [s + '#aaa' for s in add_data]
    for d in add_data:
        yield d

with open('data.dat', 'r') as f_in, \
    open('data.out', 'w') as f_out:
    f_out.write(re.sub(r'^# aaa', lambda r, f=fn(): next(f), f_in.read(), flags=re.MULTILINE))
</code>```

Body:
Given an input file data.dat like this one:

# Some comment
# more comments
#
45.78
# aaa
0.056
0.67
# aaa
345.
0.78
99.
2.34
# aaa
65.7
0.9

I need to add different comments above each line that starts with an "# aaa" so it looks like this:

# Some comment
# more comments
#
45.78
# cmmt1
# aaa
0.056
0.67
# another cmmt
# aaa
345.
0.78
99.
2.34
# last one
# aaa
65.7
0.9

I know a priori the number of "# aaa" comments present in the data.dat file,  but not their positions.

I have a way to do it (see code below) but it is quite complicated and not at all efficient. I need to apply this code to hundreds of large files, so I'm looking for an efficient way to do this.

# Read file
with open("data.dat", mode="r") as f:
    data = f.readlines()

# Indexes of "# aaa" comments
idx = []
for i, line in enumerate(data):
    if line.startswith("# aaa"):
        idx.append(i)

# Insert new comments in their proper positions
add_data = ["# cmmt1\n", "# another cmmt\n", "# last one\n"]
for i, j in enumerate(idx):
    data.insert(j + i, add_data[i])

# Write final data to file
with open("data_final.dat", mode="w") as f:
    for item in data:
        f.write("{}".format(item))

Body:
I didn't do any benchmarks, but re.sub could be faster - just load the text file as whole, execute re.sub and write it out:

data = '''# Some comment
# more comments
#
45.78
# aaa
0.056
0.67
# aaa
345.
0.78
99.
2.34
# aaa
65.7
0.9'''

import re

def fn():
    add_data = ["# cmmt1\n", "# another cmmt\n", "# last one\n"]
    for d in add_data:
        yield d

out = re.sub(r'^# aaa', lambda r, f=fn(): next(f) + r.group(0), data, flags=re.MULTILINE)
print(out)

Prints:

# Some comment
# more comments
#
45.78
# cmmt1
# aaa
0.056
0.67
# another cmmt
# aaa
345.
0.78
99.
2.34
# last one
# aaa
65.7
0.9

With files input/output:

import re

def fn():
    add_data = ["# cmmt1\n", "# another cmmt\n", "# last one\n"]
    for d in add_data:
        yield d

with open('data.dat', 'r') as f_in, \
    open('data.out', 'w') as f_out:
    f_out.write(re.sub(r'^# aaa', lambda r, f=fn(): next(f) + r.group(0), f_in.read(), flags=re.MULTILINE))

Version 2:

import re

def fn():
    add_data = ["# cmmt1\n", "# another cmmt\n", "# last one\n"]
    add_data = [s + '#aaa' for s in add_data]
    for d in add_data:
        yield d

with open('data.dat', 'r') as f_in, \
    open('data.out', 'w') as f_out:
    f_out.write(re.sub(r'^# aaa', lambda r, f=fn(): next(f), f_in.read(), flags=re.MULTILINE))


问:
How do I find the name of soccer players with same first name but different surnames?
I need to find the names of players from soccer team A that have the same first name but different surname as players from soccer team B. I need to produce the full names of all players from Team A, not just 'John'. I am able to use an additional column with Player IDs unique across all teams.

Basically table looks like this:

```<code>FirstName  LastName     Team
John       Snow         A
Batman     Dies         B
John       Dies         B
</code>```

I can produce a list of Team A names with the same first name as Team B players.

```<code>SELECT firstname, lastname FROM table
</code>```

Even though surname can't be used for one entry, it should be considered for other entries.

答:
You can use a common table expression and then do an inner join on the firstname. In the below example I've split the teams using the CTE and then joined back on ensuring the teams don't match, the last name doesn't match and the first name does match.

I've then used a union statement to show how the player in the other team can be shown as well.

```<code>declare @soccerteam table
(
    FirstName nvarchar(50),
    LastName nvarchar(50),
    Team nvarchar(3)
);

insert @soccerteam (FirstName, LastName, Team)
values
('John',       'Snow',         'A'),
('Batman',     'Dies',         'B'),
('John',       'Dies',         'B');

select * from @soccerteam;

with teamB as (select FirstName, LastName, Team from @soccerteam where Team='B')

select 'Players in Team A matching Team B', a.* from @soccerteam a inner join teamB b on a.FirstName=b.FirstName and a.LastName<>b.LastName and a.Team<>b.Team
union
select 'Players in Team B matching Team A', b.* from @soccerteam a inner join teamB b on a.FirstName=b.FirstName and a.LastName<>b.LastName and a.Team<>b.Team;
</code>```

Body:
I need to find the names of players from soccer team A that have the same first name but different surname as players from soccer team B. I need to produce the full names of all players from Team A, not just 'John'. I am able to use an additional column with Player IDs unique across all teams.

Basically table looks like this:

FirstName  LastName     Team
John       Snow         A
Batman     Dies         B
John       Dies         B

I can produce a list of Team A names with the same first name as Team B players.

SELECT firstname, lastname FROM table

Even though surname can't be used for one entry, it should be considered for other entries.

Body:
You can use a common table expression and then do an inner join on the firstname. In the below example I've split the teams using the CTE and then joined back on ensuring the teams don't match, the last name doesn't match and the first name does match.

I've then used a union statement to show how the player in the other team can be shown as well.

declare @soccerteam table
(
    FirstName nvarchar(50),
    LastName nvarchar(50),
    Team nvarchar(3)
);

insert @soccerteam (FirstName, LastName, Team)
values
('John',       'Snow',         'A'),
('Batman',     'Dies',         'B'),
('John',       'Dies',         'B');

select * from @soccerteam;

with teamB as (select FirstName, LastName, Team from @soccerteam where Team='B')

select 'Players in Team A matching Team B', a.* from @soccerteam a inner join teamB b on a.FirstName=b.FirstName and a.LastName<>b.LastName and a.Team<>b.Team
union
select 'Players in Team B matching Team A', b.* from @soccerteam a inner join teamB b on a.FirstName=b.FirstName and a.LastName<>b.LastName and a.Team<>b.Team;


问:
Parsing XML Using Python
i'm using Python 2.5 and WinXP.
i am parsing xml file as below:

```<code><Test>
<Default_Config>
  <LINK>{1: 1, 2: 2, 3: 3, 4: 4, 5: 5, 6: 6}</LINK>
  <Lanestat>{1: 2, 2: 4, 3: 6, 4: 8, 5: 10, 6: 12}</Lanestat>
  </Default_Config>
  </Test>
</code>```

however when i print out, the output is as below:

```<code>(None, '{1: 1, 2: 2, 3: 3, 4: 4, 5: 5, 6: 6}')
(None, '{1: 2, 2: 4, 3: 6, 4: 8, 5: 10, 6: 12}')
</code>```

Question: How to modify my code so that Link and Lanestat appears instead of None.
tq
Code:

```<code>import elementtree.ElementTree as ET

tree = ET.parse("dict1.xml")
doc = tree.getroot()

for elem in doc.findall('Default_Config/LINK'):
    #print elem.get('LINK'), elem.text
    a=elem.get('LINK'), elem.text
    print a

for elem in doc.findall('Default_Config/Lanestat'):

    #print elem.get('LINK'), elem.text
    a=elem.get('LINK'), elem.text
    print a
</code>```

答:
try using a=elem.tag instead of a=elem.get('LINK')</p>

```<code>import elementtree.ElementTree as ET

tree = ET.parse("dict1.xml")
doc = tree.getroot()

for elem in doc.findall('Default_Config/LINK'):
    a=elem.tag, elem.text
    print a

for elem in doc.findall('Default_Config/Lanestat'):
    a=elem.tag, elem.text
    print a
</code>```

Title: Parsing XML Using Python

Body:
i'm using Python 2.5 and WinXP.
i am parsing xml file as below:

<Test>
<Default_Config>
  <LINK>{1: 1, 2: 2, 3: 3, 4: 4, 5: 5, 6: 6}</LINK>
  <Lanestat>{1: 2, 2: 4, 3: 6, 4: 8, 5: 10, 6: 12}</Lanestat>
  </Default_Config>
  </Test>

however when i print out, the output is as below:

(None, '{1: 1, 2: 2, 3: 3, 4: 4, 5: 5, 6: 6}')
(None, '{1: 2, 2: 4, 3: 6, 4: 8, 5: 10, 6: 12}')

Question: How to modify my code so that Link and Lanestat appears instead of None.
tq
Code:

import elementtree.ElementTree as ET

tree = ET.parse("dict1.xml")
doc = tree.getroot()

for elem in doc.findall('Default_Config/LINK'):
    #print elem.get('LINK'), elem.text
    a=elem.get('LINK'), elem.text
    print a

for elem in doc.findall('Default_Config/Lanestat'):

    #print elem.get('LINK'), elem.text
    a=elem.get('LINK'), elem.text
    print a

Body:
try using a=elem.tag instead of a=elem.get('LINK')

import elementtree.ElementTree as ET

tree = ET.parse("dict1.xml")
doc = tree.getroot()

for elem in doc.findall('Default_Config/LINK'):
    a=elem.tag, elem.text
    print a

for elem in doc.findall('Default_Config/Lanestat'):
    a=elem.tag, elem.text
    print a


问:
How can i use Spark Context?
I assign the value as sc = pyspark.SparkContext(). It run and doesnt respond for so long on jupyter notebook as asteric sign appears and doesnt show any error or so.

I tried sc = SparkContext()

```<code>import pyspark
import os
from pyspark import SparkContext, SparkConf
sc = pyspark.SparkContext()  # At this part it don't respond
from pyspark.sql import SQLContext
sqlc = SQLContext(sc)
</code>```

It should go on.

答:
Try the following import: from pyspark import *
After that you can use it like so:

```<code>sc = SparkContext()
</code>```

Title: How can i use Spark Context?

Body:
I assign the value as sc = pyspark.SparkContext(). It run and doesnt respond for so long on jupyter notebook as asteric sign appears and doesnt show any error or so.

I tried sc = SparkContext()

import pyspark
import os
from pyspark import SparkContext, SparkConf
sc = pyspark.SparkContext()  # At this part it don't respond
from pyspark.sql import SQLContext
sqlc = SQLContext(sc)

It should go on.

Body:
Try the following import: from pyspark import *
After that you can use it like so:

sc = SparkContext()


问:
How to update table in MS Access 2007
I'm trying to update records in a table in MS Access 2007 from a temporary table. The temporary table gets new data from an external tool. The new data (2 columns) is supposed to go into the persistent table.

I tried the 2 following queries, but both show empty records when I look at the Datasheet view of the Query. (btw is there a better way to debug SQL in access?) The second Query also shows as many rows as there are in table1 instead of only the amount of rows edited by the external tool. (in both cases, the results are empty for every row)

the version that has at least the right amount of records:

```<code>UPDATE (table1 INNER JOIN table2 ON table1.key = table2.key)
SET table1.value1 = table2.value1, table1.datevalue = table2.datevalue
WHERE ((table1.value1) IS NULL);
</code>```

the version with as many records as result as there are records in table1:

```<code>UPDATE table1
SET table1.value1 = (SELECT value1
FROM table2
WHERE ((table1.value1 IS NULL)
AND (table1.key = table2.key))),
table1.datevalue = (SELECT datevalue
FROM table2
WHERE ((table1.key = table2.key)
AND (table1.value1 IS NULL)))
</code>```

In my test the tool manipulated 1 record so I expected to see one row as Output of the query with value1 and datevalue from table2, yet the output shows value1 and datevalue with empty entries (1 or (amount of records in table1)).

答:
```<code>show empty records when I look at the Datasheet view of the Query
</code>```

If you openn Update query in table mode, you will see only current values of the cells. You should run (execute) your query in order to get values updated. Update query cannot be checked for preview (as you want, as I understood).

Title: How to update table in MS Access 2007

Body:
I'm trying to update records in a table in MS Access 2007 from a temporary table. The temporary table gets new data from an external tool. The new data (2 columns) is supposed to go into the persistent table.

I tried the 2 following queries, but both show empty records when I look at the Datasheet view of the Query. (btw is there a better way to debug SQL in access?) The second Query also shows as many rows as there are in table1 instead of only the amount of rows edited by the external tool. (in both cases, the results are empty for every row)

the version that has at least the right amount of records:

UPDATE (table1 INNER JOIN table2 ON table1.key = table2.key)
SET table1.value1 = table2.value1, table1.datevalue = table2.datevalue
WHERE ((table1.value1) IS NULL);

the version with as many records as result as there are records in table1:

UPDATE table1
SET table1.value1 = (SELECT value1
FROM table2
WHERE ((table1.value1 IS NULL)
AND (table1.key = table2.key))),
table1.datevalue = (SELECT datevalue
FROM table2
WHERE ((table1.key = table2.key)
AND (table1.value1 IS NULL)))

In my test the tool manipulated 1 record so I expected to see one row as Output of the query with value1 and datevalue from table2, yet the output shows value1 and datevalue with empty entries (1 or (amount of records in table1)).

Body:
show empty records when I look at the Datasheet view of the Query

If you openn Update query in table mode, you will see only current values of the cells. You should run (execute) your query in order to get values updated. Update query cannot be checked for preview (as you want, as I understood).


问:
RxJs Observable Zip Array of Observables
There is an example of using zip to combine a fixed number of observables like the following:

```<code>var range = Rx.Observable.range(0, 5);
var source = Observable.zip(
      range,
      range.skip(1),
      range.skip(2),
      function (s1, s2, s3) {
            return s1 + ':' + s2 + ':' + s3;
      }
)
</code>```

My questions is what if I have an array of observables (length can be anything), how to accomplish the same like zip?

```<code>var arr = [observable1, observable2, ..]; //like 100 of them!
var source = Observable.zip(
      //how to put each observable here?
      function (__how to put argument here?_) {
            return /* loop through arguments*/;
      }
)
</code>```

答:
Since ES6 came out, you can simply pass an array as parameters for a function as so:

```<code>const arr = [ observable1, observable2, ...]
const source = Observable.zip(...arr)
</code>```

Worked for me :D

Body:
There is an example of using zip to combine a fixed number of observables like the following:

var range = Rx.Observable.range(0, 5);
var source = Observable.zip(
      range,
      range.skip(1),
      range.skip(2),
      function (s1, s2, s3) {
            return s1 + ':' + s2 + ':' + s3;
      }
)

My questions is what if I have an array of observables (length can be anything), how to accomplish the same like zip?

var arr = [observable1, observable2, ..]; //like 100 of them!
var source = Observable.zip(
      //how to put each observable here?
      function (__how to put argument here?_) {
            return /* loop through arguments*/;
      }
)

Body:
Since ES6 came out, you can simply pass an array as parameters for a function as so:

const arr = [ observable1, observable2, ...]
const source = Observable.zip(...arr)

Worked for me :D


问:
grails rollback db operation on some error

I have a service where to save a lot of data to db.
Using MYSQL
I have used like this

```<code>Domain1.withTransaction {text->
            def domain1=//Create my domain object to save
             if(!domain1.save()){
               domain1.errors.each {
                      println it
               }
               throw new RuntimeException('unable to save domain1')
        }
        Domain2.withTransaction {text->
            def domain2=//Create my domain object to save
             if(!domain2.save()){
               domain2.errors.each {
                      println it
               }
               throw new RuntimeException('unable to save domain2')
        }
</code>```

My problem if there occurred any problem in saving domain2 i need to roll back domain1 save also.

I need to remove domain1 from db.

答:
If you just want a single transaction which is rolled back when an unhandled unchecked exception is thrown, then don't start a nested transaction. The necessaary code changes are shown below:</p>

```<code>Domain1.withTransaction {text->
  def domain1=//Create my domain object to save
  if (!domain1.save()) {
    domain1.errors.each {
      println it
    }
    throw new RuntimeException('unable to save domain1')
  }

  def domain2=//Create my domain object to save
    if (!domain2.save()) {
      domain2.errors.each {
        println it
      }
    throw new RuntimeException('unable to save domain2')
  }
}
</code>```

Body:
I have a service where to save a lot of data to db.
Using MYSQL
I have used like this

Domain1.withTransaction {text->
            def domain1=//Create my domain object to save
             if(!domain1.save()){
               domain1.errors.each {
                      println it
               }
               throw new RuntimeException('unable to save domain1')
        }
        Domain2.withTransaction {text->
            def domain2=//Create my domain object to save
             if(!domain2.save()){
               domain2.errors.each {
                      println it
               }
               throw new RuntimeException('unable to save domain2')
        }

My problem if there occurred any problem in saving domain2 i need to roll back domain1 save also.

I need to remove domain1 from db.

Body:
If you just want a single transaction which is rolled back when an unhandled unchecked exception is thrown, then don't start a nested transaction. The necessaary code changes are shown below:

Domain1.withTransaction {text->
  def domain1=//Create my domain object to save
  if (!domain1.save()) {
    domain1.errors.each {
      println it
    }
    throw new RuntimeException('unable to save domain1')
  }

  def domain2=//Create my domain object to save
    if (!domain2.save()) {
      domain2.errors.each {
        println it
      }
    throw new RuntimeException('unable to save domain2')
  }
}