问:
How to make a button Visible when RecyclerView has items in it?
i'm making a note taking app.
There's a button to clear all the items in RecyclerView and its Visibility is set to Gone. But I want it to be Visible only when there are Notes in the app.
 I don't know why using
 if (notesList.size()>0){
            removeAllButton.setVisibility(View.VISIBLE);
 doesn't work! How can i do this?

 Edit: Added the Adapter code.

Here's my Main Class:

```<code>public class MainActivity extends AppCompatActivity {
private List<Notes> notesList = new ArrayList<>();
private static final int REQUEST_CODE = 1001;
final NoteAdapter adapter = new NoteAdapter(this);

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    final RecyclerView recyclerView = findViewById(R.id.rv_recyclerView);
    LinearLayoutManager layoutManager = new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false);
    recyclerView.setLayoutManager(layoutManager);
    recyclerView.setAdapter(adapter);
    Button addNoteButton = findViewById(R.id.button_main_addNote);
    final Button removeAllButton = findViewById(R.id.button_main_deleteAll);
    addNoteButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent intent = new Intent(MainActivity.this, NoteEdit.class);
            startActivityForResult(intent, REQUEST_CODE);
        }
    });

    removeAllButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            adapter.removeAll();
            removeAllButton.setVisibility(View.GONE);
        }
    });
    if (adapter.getItemCount()>=1){
        removeAllButton.setVisibility(View.VISIBLE);
    }
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    if (requestCode == REQUEST_CODE &&
            resultCode == RESULT_OK &&
            data != null) {
        String noteTitle = data.getStringExtra(NoteEdit.Result_Key_Title);
        String noteDescription = data.getStringExtra(NoteEdit.Result_Key_Description);
        Notes notes = new Notes();
        notes.setNoteTitle(noteTitle);
        notes.setNoteDescription(noteDescription);
        adapter.addNote(notes);
        adapter.getItemCount();
    }
}}
</code>```

Adapter Class :

```<code>public class NoteAdapter extends RecyclerView.Adapter<NoteAdapter.SimpleItemViewHolder> {

private Context context;
private List<Notes> notes = new ArrayList<>();

public NoteAdapter(Context context) {

    this.context = context;
}

@Override
public SimpleItemViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
    LayoutInflater layoutInflater = LayoutInflater.from(context);
    View view = layoutInflater.inflate(R.layout.item_sample, parent, false);
    return new SimpleItemViewHolder(view);
}

@Override
public void onBindViewHolder(SimpleItemViewHolder holder, int position) {
    holder.bindNote(notes.get(position));

}

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

public void addNote(Notes note) {
    notes.add(note);
    notifyItemInserted(notes.size() - 1);
}

public void removeAll () {
    notes.clear();
    notifyDataSetChanged();
}

private TextView titleTextView;
private TextView descriptionTextView;

public class SimpleItemViewHolder extends RecyclerView.ViewHolder {

    public SimpleItemViewHolder(View itemView) {
        super(itemView);
        titleTextView = itemView.findViewById(R.id.tv_itemSample_title);
        descriptionTextView = itemView.findViewById(R.id.tv_itemSample_description);
    }

    public void bindNote(Notes note) {
        titleTextView.setText(note.getNoteTitle());
        descriptionTextView.setText(note.getNoteDescription());
    }

}}
</code>```

答:
I see that in onActivityResult you actually add the notes to the RecyclerView by using your adapter. After adding the note to the adapter you probably call notifydatasetchanged from the adapter.
After adding the note in the activity call getItemCount() on the adapter and only if it equal one make the button visible.
On the clicklistener of remove all button you should hide the button.

Also change notifyitemInserted after addnote to notifydatasetchanged

Gili

```<code>    package com.example.gilad.myapplication;

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.Button;

import java.util.ArrayList;

public class MainActivity extends AppCompatActivity {
    private List<Notes> notesList = new ArrayList<>();
    private static final int REQUEST_CODE = 1001;
    final NoteAdapter adapter = new NoteAdapter(this);
    private View mRemoveAllButton;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        final RecyclerView recyclerView = findViewById(R.id.rv_recyclerView);
        LinearLayoutManager layoutManager = new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false);
        recyclerView.setLayoutManager(layoutManager);
        recyclerView.setAdapter(adapter);
        Button addNoteButton = findViewById(R.id.button_main_addNote);
        mRemoveAllButton = findViewById(R.id.button_main_deleteAll);
        addNoteButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(MainActivity.this, NoteEdit.class);
                startActivityForResult(intent, REQUEST_CODE);
            }
        });

        mRemoveAllButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                adapter.removeAll();
                mRemoveAllButton.setVisibility(View.GONE);
            }
        });

    }
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUEST_CODE &&
                resultCode == RESULT_OK &&
                data != null) {
            String noteTitle = data.getStringExtra(NoteEdit.Result_Key_Title);
            String noteDescription = data.getStringExtra(NoteEdit.Result_Key_Description);
            Notes notes = new Notes();
            notes.setNoteTitle(noteTitle);
            notes.setNoteDescription(noteDescription);
            adapter.addNote(notes);
            final int adapterCount = adapter.getItemCount();
            if (adapterCount == 1){
                mRemoveAllButton.setVisibility(View.VISIBLE);
            }
        }
    }}
</code>```

Body:
i'm making a note taking app.
There's a button to clear all the items in RecyclerView and its Visibility is set to Gone. But I want it to be Visible only when there are Notes in the app.
 I don't know why using
 if (notesList.size()>0){
            removeAllButton.setVisibility(View.VISIBLE);
 doesn't work! How can i do this?

 Edit: Added the Adapter code.

Here's my Main Class:

public class MainActivity extends AppCompatActivity {
private List<Notes> notesList = new ArrayList<>();
private static final int REQUEST_CODE = 1001;
final NoteAdapter adapter = new NoteAdapter(this);

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    final RecyclerView recyclerView = findViewById(R.id.rv_recyclerView);
    LinearLayoutManager layoutManager = new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false);
    recyclerView.setLayoutManager(layoutManager);
    recyclerView.setAdapter(adapter);
    Button addNoteButton = findViewById(R.id.button_main_addNote);
    final Button removeAllButton = findViewById(R.id.button_main_deleteAll);
    addNoteButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent intent = new Intent(MainActivity.this, NoteEdit.class);
            startActivityForResult(intent, REQUEST_CODE);
        }
    });

    removeAllButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            adapter.removeAll();
            removeAllButton.setVisibility(View.GONE);
        }
    });
    if (adapter.getItemCount()>=1){
        removeAllButton.setVisibility(View.VISIBLE);
    }
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    if (requestCode == REQUEST_CODE &&
            resultCode == RESULT_OK &&
            data != null) {
        String noteTitle = data.getStringExtra(NoteEdit.Result_Key_Title);
        String noteDescription = data.getStringExtra(NoteEdit.Result_Key_Description);
        Notes notes = new Notes();
        notes.setNoteTitle(noteTitle);
        notes.setNoteDescription(noteDescription);
        adapter.addNote(notes);
        adapter.getItemCount();
    }
}}

Adapter Class :

public class NoteAdapter extends RecyclerView.Adapter<NoteAdapter.SimpleItemViewHolder> {

private Context context;
private List<Notes> notes = new ArrayList<>();

public NoteAdapter(Context context) {

    this.context = context;
}

@Override
public SimpleItemViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
    LayoutInflater layoutInflater = LayoutInflater.from(context);
    View view = layoutInflater.inflate(R.layout.item_sample, parent, false);
    return new SimpleItemViewHolder(view);
}

@Override
public void onBindViewHolder(SimpleItemViewHolder holder, int position) {
    holder.bindNote(notes.get(position));

}

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

public void addNote(Notes note) {
    notes.add(note);
    notifyItemInserted(notes.size() - 1);
}

public void removeAll () {
    notes.clear();
    notifyDataSetChanged();
}

private TextView titleTextView;
private TextView descriptionTextView;

public class SimpleItemViewHolder extends RecyclerView.ViewHolder {

    public SimpleItemViewHolder(View itemView) {
        super(itemView);
        titleTextView = itemView.findViewById(R.id.tv_itemSample_title);
        descriptionTextView = itemView.findViewById(R.id.tv_itemSample_description);
    }

    public void bindNote(Notes note) {
        titleTextView.setText(note.getNoteTitle());
        descriptionTextView.setText(note.getNoteDescription());
    }

}}

Body:
I see that in onActivityResult you actually add the notes to the RecyclerView by using your adapter. After adding the note to the adapter you probably call notifydatasetchanged from the adapter.
After adding the note in the activity call getItemCount() on the adapter and only if it equal one make the button visible.
On the clicklistener of remove all button you should hide the button.

Also change notifyitemInserted after addnote to notifydatasetchanged

Gili

    package com.example.gilad.myapplication;

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.Button;

import java.util.ArrayList;

public class MainActivity extends AppCompatActivity {
    private List<Notes> notesList = new ArrayList<>();
    private static final int REQUEST_CODE = 1001;
    final NoteAdapter adapter = new NoteAdapter(this);
    private View mRemoveAllButton;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        final RecyclerView recyclerView = findViewById(R.id.rv_recyclerView);
        LinearLayoutManager layoutManager = new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false);
        recyclerView.setLayoutManager(layoutManager);
        recyclerView.setAdapter(adapter);
        Button addNoteButton = findViewById(R.id.button_main_addNote);
        mRemoveAllButton = findViewById(R.id.button_main_deleteAll);
        addNoteButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(MainActivity.this, NoteEdit.class);
                startActivityForResult(intent, REQUEST_CODE);
            }
        });

        mRemoveAllButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                adapter.removeAll();
                mRemoveAllButton.setVisibility(View.GONE);
            }
        });

    }
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUEST_CODE &&
                resultCode == RESULT_OK &&
                data != null) {
            String noteTitle = data.getStringExtra(NoteEdit.Result_Key_Title);
            String noteDescription = data.getStringExtra(NoteEdit.Result_Key_Description);
            Notes notes = new Notes();
            notes.setNoteTitle(noteTitle);
            notes.setNoteDescription(noteDescription);
            adapter.addNote(notes);
            final int adapterCount = adapter.getItemCount();
            if (adapterCount == 1){
                mRemoveAllButton.setVisibility(View.VISIBLE);
            }
        }
    }}


来源: stackexchange

问:
Concurrently write multiple csv files from one, splitting on a partition column in Golang
My objective is to read one or multiple csv files that share a common format, and write to separate files based on a partition column in the csv data. Please allow that the last column is the partition, that data is un-sorted, and a given partition can be found in multiple files. Example of one file:

```<code>fsdio,abc,def,2017,11,06,01
1sdf9,abc,def,2017,11,06,04
22df9,abc,def,2017,11,06,03
1d243,abc,def,2017,11,06,02
</code>```

If this approach smells like the dreaded XY Problem, I'm happy to adjust.

What I've tried so far:

Read in the data set and iterate over each line

If the partition has
been seen, spin off a new worker routine (this will contain a file/csv
writer). Send the line into a chan []string.

As each worker is a file writer, it should only receive lines for exactly one partition over it's input channel.

This obviously doesn't work (yet),  as I'm not aware of how to send a line to the correct worker based on the partition value seen on a given line.

I've given each worker an id string for each partition value, but am not aware how to select that worker to send to, if I should be creating a separate chan []string for each worker and send to that channel with a select, or if perhaps a struct should hold each worker with some sort of pool and routing functionality.

TLDR; I'm lost as to how to conditionally send data to a given go routine or channel based on some categorical string value, where the number of unique's can be arbitrary, but likely does not exceed 24 unique partition values.

I will caveat by stating I've noticed questions like this do get down-voted, so if you feel this is counter-constructive or incomplete enough to down-vote, please comment with why so I can avoid repeating the offense.

Thanks for any help in advance!

Playground

Snippet:

```<code>  package main

    import (
        "encoding/csv"
        "fmt"
        "log"
        "strings"
        "time"
    )

    func main() {

        // CSV
        r := csv.NewReader(csvFile1)
        lines, err := r.ReadAll()
        if err != nil {
            log.Fatalf("error reading all lines: %v", err)
        }

        // CHANNELS
        lineChan := make(chan []string)

        // TRACKER
        var seenPartitions []string

        for _, line := range lines {

            hour := line[6]
            if !stringInSlice(hour, seenPartitions) {
                seenPartitions = append(seenPartitions, hour)
                go worker(hour, lineChan)
            }
            // How to send to the correct worker/channel?
            lineChan <- line

        }
        close(lineChan)
    }

    func worker(id string, lineChan <-chan []string) {
        for j := range lineChan {
            fmt.Println("worker", id, "started  job", j)
            // Write to a new file here and wait for input over the channel
            time.Sleep(time.Second)
            fmt.Println("worker", id, "finished job", j)
        }
    }

    func stringInSlice(str string, list []string) bool {
        for _, v := range list {
            if v == str {
                return true
            }
        }
        return false
    }

    // DUMMY
var csvFile1 = strings.NewReader(`
12fy3,abc,def,2017,11,06,04
fsdio,abc,def,2017,11,06,01
11213,abc,def,2017,11,06,02
1sdf9,abc,def,2017,11,06,01
2123r,abc,def,2017,11,06,03
1v2t3,abc,def,2017,11,06,01
1r2r3,abc,def,2017,11,06,02
g1253,abc,def,2017,11,06,02
d1e23,abc,def,2017,11,06,02
a1d23,abc,def,2017,11,06,02
12jj3,abc,def,2017,11,06,03
t1r23,abc,def,2017,11,06,03
22123,abc,def,2017,11,06,03
14d23,abc,def,2017,11,06,04
1d243,abc,def,2017,11,06,01
1da23,abc,def,2017,11,06,04
a1523,abc,def,2017,11,06,01
12453,abc,def,2017,11,06,04`)
</code>```

答:
Synchronous version no go concurrent magic first (see concurrent version below).

```<code>package main

import (
    "encoding/csv"
    "fmt"
    "io"
    "log"
    "strings"
)

func main() {

    // CSV
    r := csv.NewReader(csvFile1)
    partitions := make(map[string][][]string)

    for {
        rec, err := r.Read()
        if err != nil {
            if err == io.EOF {
                err = nil

                save_partitions(partitions)

                return
            }
            log.Fatal(err)
        }

        process(rec, partitions)
    }

}

// prints only
func save_partitions(partitions map[string][][]string) {
    for part, recs := range partitions {
        fmt.Println(part)
        for _, rec := range recs {
            fmt.Println(rec)
        }
    }
}

// this can also write/append directly to a file
func process(rec []string, partitions map[string][][]string) {
    l := len(rec)
    part := rec[l-1]
    if p, ok := partitions[part]; ok {
        partitions[part] = append(p, rec)
    } else {
        partitions[part] = [][]string{rec}
    }
}

// DUMMY
var csvFile1 = strings.NewReader(`
fsdio,abc,def,2017,11,06,01
1sdf9,abc,def,2017,11,06,01
1d243,abc,def,2017,11,06,01
1v2t3,abc,def,2017,11,06,01
a1523,abc,def,2017,11,06,01
1r2r3,abc,def,2017,11,06,02
11213,abc,def,2017,11,06,02
g1253,abc,def,2017,11,06,02
d1e23,abc,def,2017,11,06,02
a1d23,abc,def,2017,11,06,02
12jj3,abc,def,2017,11,06,03
t1r23,abc,def,2017,11,06,03
2123r,abc,def,2017,11,06,03
22123,abc,def,2017,11,06,03
14d23,abc,def,2017,11,06,04
1da23,abc,def,2017,11,06,04
12fy3,abc,def,2017,11,06,04
12453,abc,def,2017,11,06,04`)
</code>```

https://play.golang.org/p/--iqZGzxCF

And the concurrent version:

```<code>package main

import (
    "encoding/csv"
    "fmt"
    "io"
    "log"
    "strings"
    "sync"
)

var (
    // list of channels to communicate with workers
    // workers accessed synchronousely no mutex required
    workers = make(map[string]chan []string)

    // wg is to make sure all workers done before exiting main
    wg = sync.WaitGroup{}

    // mu used only for sequential printing, not relevant for program logic
    mu = sync.Mutex{}
)

func main() {

    // wait for all workers to finish up before exit
    defer wg.Wait()

    r := csv.NewReader(csvFile1)

    for {
        rec, err := r.Read()
        if err != nil {
            if err == io.EOF {
                savePartitions()
                return
            }
            log.Fatal(err) // sorry for the panic
        }
        process(rec)
    }

}

func process(rec []string) {
    l := len(rec)
    part := rec[l-1]

    if c, ok := workers[part]; ok {
        // send rec to worker
        c <- rec
    } else {
        // if no worker for the partition

        // make a chan
        nc := make(chan []string)
        workers[part] = nc

        // start worker with this chan
        go worker(nc)

        // send rec to worker via chan
        nc <- rec
    }
}

func worker(c chan []string) {

    // wg.Done signals to main worker completion
    wg.Add(1)
    defer wg.Done()

    part := [][]string{}
    for {
        // wait for a rec or close(chan)
        rec, ok := <-c
        if ok {
            // save the rec
            // instead of accumulation in memory
            // this can be saved to file directly
            part = append(part, rec)
        } else {
            // channel closed on EOF

            // dump partition
            // locks ensures sequential printing
            // not a required for independent files
            mu.Lock()
            for _, p := range part {
                fmt.Printf("%+v\n", p)
            }
            mu.Unlock()

            return
        }
    }
}

// simply signals to workers to stop
func savePartitions() {
    for _, c := range workers {
        // signal to all workers to exit
        close(c)
    }
}

// DUMMY
var csvFile1 = strings.NewReader(`
fsdio,abc,def,2017,11,06,01
1sdf9,abc,def,2017,11,06,01
1d243,abc,def,2017,11,06,01
1v2t3,abc,def,2017,11,06,01
a1523,abc,def,2017,11,06,01
1r2r3,abc,def,2017,11,06,02
11213,abc,def,2017,11,06,02
g1253,abc,def,2017,11,06,02
d1e23,abc,def,2017,11,06,02
a1d23,abc,def,2017,11,06,02
12jj3,abc,def,2017,11,06,03
t1r23,abc,def,2017,11,06,03
2123r,abc,def,2017,11,06,03
22123,abc,def,2017,11,06,03
14d23,abc,def,2017,11,06,04
1da23,abc,def,2017,11,06,04
12fy3,abc,def,2017,11,06,04
12453,abc,def,2017,11,06,04`)
</code>```

https://play.golang.org/p/oBTPosy0yT

Have fun!

ContentLicense: CC BY-SA 3.0

Body:
My objective is to read one or multiple csv files that share a common format, and write to separate files based on a partition column in the csv data. Please allow that the last column is the partition, that data is un-sorted, and a given partition can be found in multiple files. Example of one file:

fsdio,abc,def,2017,11,06,01
1sdf9,abc,def,2017,11,06,04
22df9,abc,def,2017,11,06,03
1d243,abc,def,2017,11,06,02

If this approach smells like the dreaded XY Problem, I'm happy to adjust.

What I've tried so far:

Read in the data set and iterate over each line

If the partition has
been seen, spin off a new worker routine (this will contain a file/csv
writer). Send the line into a chan []string.

As each worker is a file writer, it should only receive lines for exactly one partition over it's input channel.

This obviously doesn't work (yet),  as I'm not aware of how to send a line to the correct worker based on the partition value seen on a given line.

I've given each worker an id string for each partition value, but am not aware how to select that worker to send to, if I should be creating a separate chan []string for each worker and send to that channel with a select, or if perhaps a struct should hold each worker with some sort of pool and routing functionality.

TLDR; I'm lost as to how to conditionally send data to a given go routine or channel based on some categorical string value, where the number of unique's can be arbitrary, but likely does not exceed 24 unique partition values.

I will caveat by stating I've noticed questions like this do get down-voted, so if you feel this is counter-constructive or incomplete enough to down-vote, please comment with why so I can avoid repeating the offense.

Thanks for any help in advance!

Playground

Snippet:

  package main

    import (
        "encoding/csv"
        "fmt"
        "log"
        "strings"
        "time"
    )

    func main() {

        // CSV
        r := csv.NewReader(csvFile1)
        lines, err := r.ReadAll()
        if err != nil {
            log.Fatalf("error reading all lines: %v", err)
        }

        // CHANNELS
        lineChan := make(chan []string)

        // TRACKER
        var seenPartitions []string

        for _, line := range lines {

            hour := line[6]
            if !stringInSlice(hour, seenPartitions) {
                seenPartitions = append(seenPartitions, hour)
                go worker(hour, lineChan)
            }
            // How to send to the correct worker/channel?
            lineChan <- line

        }
        close(lineChan)
    }

    func worker(id string, lineChan <-chan []string) {
        for j := range lineChan {
            fmt.Println("worker", id, "started  job", j)
            // Write to a new file here and wait for input over the channel
            time.Sleep(time.Second)
            fmt.Println("worker", id, "finished job", j)
        }
    }

    func stringInSlice(str string, list []string) bool {
        for _, v := range list {
            if v == str {
                return true
            }
        }
        return false
    }

    // DUMMY
var csvFile1 = strings.NewReader(`
12fy3,abc,def,2017,11,06,04
fsdio,abc,def,2017,11,06,01
11213,abc,def,2017,11,06,02
1sdf9,abc,def,2017,11,06,01
2123r,abc,def,2017,11,06,03
1v2t3,abc,def,2017,11,06,01
1r2r3,abc,def,2017,11,06,02
g1253,abc,def,2017,11,06,02
d1e23,abc,def,2017,11,06,02
a1d23,abc,def,2017,11,06,02
12jj3,abc,def,2017,11,06,03
t1r23,abc,def,2017,11,06,03
22123,abc,def,2017,11,06,03
14d23,abc,def,2017,11,06,04
1d243,abc,def,2017,11,06,01
1da23,abc,def,2017,11,06,04
a1523,abc,def,2017,11,06,01
12453,abc,def,2017,11,06,04`)

Body:
Synchronous version no go concurrent magic first (see concurrent version below).

package main

import (
    "encoding/csv"
    "fmt"
    "io"
    "log"
    "strings"
)

func main() {

    // CSV
    r := csv.NewReader(csvFile1)
    partitions := make(map[string][][]string)

    for {
        rec, err := r.Read()
        if err != nil {
            if err == io.EOF {
                err = nil

                save_partitions(partitions)

                return
            }
            log.Fatal(err)
        }

        process(rec, partitions)
    }

}

// prints only
func save_partitions(partitions map[string][][]string) {
    for part, recs := range partitions {
        fmt.Println(part)
        for _, rec := range recs {
            fmt.Println(rec)
        }
    }
}

// this can also write/append directly to a file
func process(rec []string, partitions map[string][][]string) {
    l := len(rec)
    part := rec[l-1]
    if p, ok := partitions[part]; ok {
        partitions[part] = append(p, rec)
    } else {
        partitions[part] = [][]string{rec}
    }
}

// DUMMY
var csvFile1 = strings.NewReader(`
fsdio,abc,def,2017,11,06,01
1sdf9,abc,def,2017,11,06,01
1d243,abc,def,2017,11,06,01
1v2t3,abc,def,2017,11,06,01
a1523,abc,def,2017,11,06,01
1r2r3,abc,def,2017,11,06,02
11213,abc,def,2017,11,06,02
g1253,abc,def,2017,11,06,02
d1e23,abc,def,2017,11,06,02
a1d23,abc,def,2017,11,06,02
12jj3,abc,def,2017,11,06,03
t1r23,abc,def,2017,11,06,03
2123r,abc,def,2017,11,06,03
22123,abc,def,2017,11,06,03
14d23,abc,def,2017,11,06,04
1da23,abc,def,2017,11,06,04
12fy3,abc,def,2017,11,06,04
12453,abc,def,2017,11,06,04`)

https://play.golang.org/p/--iqZGzxCF

And the concurrent version:

package main

import (
    "encoding/csv"
    "fmt"
    "io"
    "log"
    "strings"
    "sync"
)

var (
    // list of channels to communicate with workers
    // workers accessed synchronousely no mutex required
    workers = make(map[string]chan []string)

    // wg is to make sure all workers done before exiting main
    wg = sync.WaitGroup{}

    // mu used only for sequential printing, not relevant for program logic
    mu = sync.Mutex{}
)

func main() {

    // wait for all workers to finish up before exit
    defer wg.Wait()

    r := csv.NewReader(csvFile1)

    for {
        rec, err := r.Read()
        if err != nil {
            if err == io.EOF {
                savePartitions()
                return
            }
            log.Fatal(err) // sorry for the panic
        }
        process(rec)
    }

}

func process(rec []string) {
    l := len(rec)
    part := rec[l-1]

    if c, ok := workers[part]; ok {
        // send rec to worker
        c <- rec
    } else {
        // if no worker for the partition

        // make a chan
        nc := make(chan []string)
        workers[part] = nc

        // start worker with this chan
        go worker(nc)

        // send rec to worker via chan
        nc <- rec
    }
}

func worker(c chan []string) {

    // wg.Done signals to main worker completion
    wg.Add(1)
    defer wg.Done()

    part := [][]string{}
    for {
        // wait for a rec or close(chan)
        rec, ok := <-c
        if ok {
            // save the rec
            // instead of accumulation in memory
            // this can be saved to file directly
            part = append(part, rec)
        } else {
            // channel closed on EOF

            // dump partition
            // locks ensures sequential printing
            // not a required for independent files
            mu.Lock()
            for _, p := range part {
                fmt.Printf("%+v\n", p)
            }
            mu.Unlock()

            return
        }
    }
}

// simply signals to workers to stop
func savePartitions() {
    for _, c := range workers {
        // signal to all workers to exit
        close(c)
    }
}

// DUMMY
var csvFile1 = strings.NewReader(`
fsdio,abc,def,2017,11,06,01
1sdf9,abc,def,2017,11,06,01
1d243,abc,def,2017,11,06,01
1v2t3,abc,def,2017,11,06,01
a1523,abc,def,2017,11,06,01
1r2r3,abc,def,2017,11,06,02
11213,abc,def,2017,11,06,02
g1253,abc,def,2017,11,06,02
d1e23,abc,def,2017,11,06,02
a1d23,abc,def,2017,11,06,02
12jj3,abc,def,2017,11,06,03
t1r23,abc,def,2017,11,06,03
2123r,abc,def,2017,11,06,03
22123,abc,def,2017,11,06,03
14d23,abc,def,2017,11,06,04
1da23,abc,def,2017,11,06,04
12fy3,abc,def,2017,11,06,04
12453,abc,def,2017,11,06,04`)

https://play.golang.org/p/oBTPosy0yT

Have fun!


问:
bigcommerce requested resources increase limit 250
I was trying to increase my API resource request from 250 to all our listed product. I'm using a custom PHP application to achieve this.

I refer to this pulling 50 categories

This is what I did so far.

```<code>$url = 'https://example.com/api/v2/products.json?limit=250';
</code>```

Thanks for help

答:
There is no way to request more than 250 at a time--this is a firm limit built into the API. What you can do though is use pagination and loop through each page until you've pulled all of the records. To pull the first page of 250 records, you would request:

$url = 'https://example.com/api/v2/products.json?page=1&limit=250';

Body:
I was trying to increase my API resource request from 250 to all our listed product. I'm using a custom PHP application to achieve this.

I refer to this pulling 50 categories

This is what I did so far.

$url = 'https://example.com/api/v2/products.json?limit=250';

Thanks for help


问:
Update pandas dataframe based on matching columns of a second dataframe
I have two pandas dataframes (df_1, df_2) with the same columns, but in one dataframe (df_1) some values of one column are missing. So I want to fill in those missing values from df_2, but only when the the values of two columns match.

Here is a little example what my data looks like:

df_1:

df_2:

I tried to add the missing values with:

```<code>df_1.update(df_2, overwrite=False)
</code>```

But the problem is, that it will fill in the values, even when just one column matches. I want to fill in the value when the columns "housenumber" AND "street" matches.

答:
I think you need set_index for Multiindex in both DataFrames and then combine_first or fillna:

```<code>df1 = df_1.set_index(["housenumber", "street"])
df2 = df_2.set_index(["housenumber", "street"])

df = df1.combine_first(df2).reset_index()
</code>```

```<code>df = df1.fillna(df2).reset_index()
</code>```

Body:
I have two pandas dataframes (df_1, df_2) with the same columns, but in one dataframe (df_1) some values of one column are missing. So I want to fill in those missing values from df_2, but only when the the values of two columns match.

Here is a little example what my data looks like:

df_1:

df_2:

I tried to add the missing values with:

df_1.update(df_2, overwrite=False)

But the problem is, that it will fill in the values, even when just one column matches. I want to fill in the value when the columns "housenumber" AND "street" matches.

Body:
I think you need set_index for Multiindex in both DataFrames and then combine_first or fillna:

df1 = df_1.set_index(["housenumber", "street"])
df2 = df_2.set_index(["housenumber", "street"])

df = df1.combine_first(df2).reset_index()

df = df1.fillna(df2).reset_index()


问:
Mark fields as dirty in Linq To Sql
One of my entities in my LinqToSql model has a field of type XElement, mapped to an XML column in SQL Server.

When I do the following:

```<code>myEntity.MyXmlField.Add(new XAttribute("attribute", "value"));
...
DataContext.SubmitChanges();
</code>```

The field does not get updated in the database (but other fields do).
I take it that the DataContext cannot track changes made inside the XElement and thus this field is not marked as dirty and does not get updated.

Is this the correct assumption and how can I fix it?

EDIT

After reading the link that The Scrum Meister provided, it looks like

```<code>myEntity.MyXmlField = new XElement(myEntity.MyXmlField);
</code>```

will solve the issue.

However this solution is quite specific to XElement (as it's easy to clone it), and involves a lot of processing if the XElement is large.

There's got to be a general way of letting the DataContext know that a field has changed.

答:
The problem here is that altering the value of the XML column doesn't mark it as 'changed' - the reference doesn't change, so the mapper doesn't know that it has changed.

The answer is surprisingly simple:

```<code>var field = new XElement(myEntity.MyXmlField);
field.Add(new XAttribute("attribute", "value"));
myEntity.MyXmlField = field;
</code>```

ContentLicense: CC BY-SA 2.5

Title: Mark fields as dirty in Linq To Sql

Body:
One of my entities in my LinqToSql model has a field of type XElement, mapped to an XML column in SQL Server.

When I do the following:

myEntity.MyXmlField.Add(new XAttribute("attribute", "value"));
...
DataContext.SubmitChanges();

The field does not get updated in the database (but other fields do).
I take it that the DataContext cannot track changes made inside the XElement and thus this field is not marked as dirty and does not get updated.

Is this the correct assumption and how can I fix it?

EDIT

After reading the link that The Scrum Meister provided, it looks like

myEntity.MyXmlField = new XElement(myEntity.MyXmlField);

will solve the issue.

However this solution is quite specific to XElement (as it's easy to clone it), and involves a lot of processing if the XElement is large.

There's got to be a general way of letting the DataContext know that a field has changed.

Body:
The problem here is that altering the value of the XML column doesn't mark it as 'changed' - the reference doesn't change, so the mapper doesn't know that it has changed.

The answer is surprisingly simple:

var field = new XElement(myEntity.MyXmlField);
field.Add(new XAttribute("attribute", "value"));
myEntity.MyXmlField = field;


问:
Creating dynamic elements with jQuery separately in different divs
I'm using jQuery in order to create dinamically input forms. I made an example of my code (this example doesn't creates input forms but it works exacly as my script, and it reproduce the same error) that you can play in order to understand better what I mean.

The problem is that if I press "Add" of the first div "event", my jQuery produces the skulls with numbers starting from 1.

After that I press "Add" of the second div "event", but the numbers starts not from 1, but from the last number of the first div "event".

Change the class "event" is not possible. In this example there are 2 div but they could be 3-4-5 or more, all with the class "event".

What can I do in order to start both the "event" from 1?

var i = 1;

$('.plus').click(function(e) {

  var $numberDiv = $('' + i + '').addClass('numberDiv');
  var $clear = $('
').addClass('clear');
  var $event = $(e.currentTarget).closest('.event');

  $event.find('.participantContainer').append($numberDiv);

  i++;
})

$('.minus').click(function(e) {
  var $numberDiv = $(''> + i + '').addClass('numberDiv');
  var $clear = $('
').addClass('clear');
  var $event = $(e.currentTarget).closest('.event');

  $event.find('.numberDiv:last').remove();

  i--;
})

$('.reset').click(function() {
 i = 1;
  $('.numberDiv').each(function() {
   $(this).remove();
  })
})```
<pre class="snippet-code-css lang-css prettyprint-override"><code>body {
    font-family: sans-serif;
}

button {
    background: none;
}

.clear {
  clear: both;
}

.plus,
.minus,
.reset {
  height: 33px;
    font-size: 20px;
    cursor: pointer;
    margin-right: 2px;
    float: left;
    margin-bottom: 10px;
    border-radius: 10px;
    padding: 0 0 0 0;
}

.plus {
  border: 2px solid green;
  width: 56px;
}

.plus:hover {
  background-color: green;
}

.minus:hover {
  background-color:red;
}

.minus {
  border: 2px solid red;
  width: 95px;
}

.reset {
  border: 2px solid blue;
  width: 95px;
}

.reset:hover {
  background-color: lightblue;
}

.numberDiv {
  font-size: 20px;
  position: relative;
  top: -5px;
  margin-right: 10px;
}

.numberDiv:before {
  content:'☠';
  font-size: 30px;
}

.participantContainer {
  float: left;
}</code>```

  <button class="plus">Add</button>
  <button class="minus">Remove</button>

  <button class="plus">Add</button>
  <button class="minus">Remove</button>

<button class="reset">Reset</button>```

The main reason is of course that I'm learning and I don't have a lot of experience with jQuery.

Thanks in Advance!

答:
You can just change your variable i to be an array and target that on the plus and minus like so</p>

```<code>var i = [];

$('.plus').click(function(e) {

  var index = $('.plus').index(this);
  i[index] = typeof i[index] === 'undefined' ? 1 : i[index] + 1;

  var $numberDiv = $('<span>' + i[index]  + '</span>').addClass('numberDiv');
  var $clear = $('<div />').addClass('clear');
  var $event = $(e.currentTarget).closest('.event');

  $event.find('.participantContainer').append($numberDiv);

})

$('.minus').click(function(e) {
  var index = $('.minus').index(this);
  i[index] = typeof i[index] === 'undefined' ? 1 : i[index] - 1;
  var $numberDiv = $('<span>'> + i[index]  + '</span>').addClass('numberDiv');
  var $clear = $('<div />').addClass('clear');
  var $event = $(e.currentTarget).closest('.event');

  $event.find('.numberDiv:last').remove();
})

$('.reset').click(function() {
    i = [];
  $('.numberDiv').each(function() {
    $(this).remove();
  })
})
</code>```

Body:
I'm using jQuery in order to create dinamically input forms. I made an example of my code (this example doesn't creates input forms but it works exacly as my script, and it reproduce the same error) that you can play in order to understand better what I mean.

The problem is that if I press "Add" of the first div "event", my jQuery produces the skulls with numbers starting from 1.

After that I press "Add" of the second div "event", but the numbers starts not from 1, but from the last number of the first div "event".

Change the class "event" is not possible. In this example there are 2 div but they could be 3-4-5 or more, all with the class "event".

What can I do in order to start both the "event" from 1?

var i = 1;

$('.plus').click(function(e) {

  var $numberDiv = $('' + i + '').addClass('numberDiv');
  var $clear = $('
').addClass('clear');
  var $event = $(e.currentTarget).closest('.event');

  $event.find('.participantContainer').append($numberDiv);

  i++;
})

$('.minus').click(function(e) {
  var $numberDiv = $(''> + i + '').addClass('numberDiv');
  var $clear = $('
').addClass('clear');
  var $event = $(e.currentTarget).closest('.event');

  $event.find('.numberDiv:last').remove();

  i--;
})

$('.reset').click(function() {
 i = 1;
  $('.numberDiv').each(function() {
   $(this).remove();
  })
})

body {
    font-family: sans-serif;
}

button {
    background: none;
}

.clear {
  clear: both;
}

.plus,
.minus,
.reset {
  height: 33px;
    font-size: 20px;
    cursor: pointer;
    margin-right: 2px;
    float: left;
    margin-bottom: 10px;
    border-radius: 10px;
    padding: 0 0 0 0;
}

.plus {
  border: 2px solid green;
  width: 56px;
}

.plus:hover {
  background-color: green;
}

.minus:hover {
  background-color:red;
}

.minus {
  border: 2px solid red;
  width: 95px;
}

.reset {
  border: 2px solid blue;
  width: 95px;
}

.reset:hover {
  background-color: lightblue;
}

.numberDiv {
  font-size: 20px;
  position: relative;
  top: -5px;
  margin-right: 10px;
}

.numberDiv:before {
  content:'☠';
  font-size: 30px;
}

.participantContainer {
  float: left;
}

  <button class="plus">Add</button>
  <button class="minus">Remove</button>

  <button class="plus">Add</button>
  <button class="minus">Remove</button>

<button class="reset">Reset</button>

The main reason is of course that I'm learning and I don't have a lot of experience with jQuery.

Thanks in Advance!

Body:
You can just change your variable i to be an array and target that on the plus and minus like so

var i = [];

$('.plus').click(function(e) {

  var index = $('.plus').index(this);
  i[index] = typeof i[index] === 'undefined' ? 1 : i[index] + 1;

  var $numberDiv = $('<span>' + i[index]  + '</span>').addClass('numberDiv');
  var $clear = $('<div />').addClass('clear');
  var $event = $(e.currentTarget).closest('.event');

  $event.find('.participantContainer').append($numberDiv);

})

$('.minus').click(function(e) {
  var index = $('.minus').index(this);
  i[index] = typeof i[index] === 'undefined' ? 1 : i[index] - 1;
  var $numberDiv = $('<span>'> + i[index]  + '</span>').addClass('numberDiv');
  var $clear = $('<div />').addClass('clear');
  var $event = $(e.currentTarget).closest('.event');

  $event.find('.numberDiv:last').remove();
})

$('.reset').click(function() {
    i = [];
  $('.numberDiv').each(function() {
    $(this).remove();
  })
})


问:
How to speed up importing dataframes into pandas
I understand that one of the reasons why pandas can be relatively slow importing csv files is that it needs to scan the entire content of a column before guessing the type (see the discussions around the mostly deprecated low_memory option for pandas.read_csv). Is my understanding correct?

If it is, what would be a good format in which to store a dataframe, and which explicitly specifies data types, so pandas doesn't have to guess (SQL is not an option for now)?

Any option in particular from those listed here?

My dataframes have floats, integers, dates, strings and Y/N, so formats supporting numeric values only won't do.

答:
You can improve the efficiency of importing from a CSV file by specifying column names and their datatypes to your call to pandas.read_csv. If you have existing column headers in the file, you probably don't have to specify the names and can just use those, but I like to skip the header and specify names for completeness:

```<code>import pandas as pd
import numpy as np
col_names = ['a', 'b', 'whatever', 'your', 'names', 'are']
col_types = {k: np.int32 for k in col_names}  # create the type dict
col_types['a'] = 'object'  # can change whichever ones you like
df = pd.read_csv(fname,
                 header = None,  # since we are specifying our own names
                 skiprows=[0],  # if you *do* have a header row, skip it
                 names=col_names,
                 dtype=col_types)
</code>```

On a large sample dataset comprising mostly integer columns, this was about 20% faster than specifying dtype='object' in the call to pd.read_csv for me.

ContentLicense: CC BY-SA 4.0

Body:
You can improve the efficiency of importing from a CSV file by specifying column names and their datatypes to your call to pandas.read_csv. If you have existing column headers in the file, you probably don't have to specify the names and can just use those, but I like to skip the header and specify names for completeness:

import pandas as pd
import numpy as np
col_names = ['a', 'b', 'whatever', 'your', 'names', 'are']
col_types = {k: np.int32 for k in col_names}  # create the type dict
col_types['a'] = 'object'  # can change whichever ones you like
df = pd.read_csv(fname,
                 header = None,  # since we are specifying our own names
                 skiprows=[0],  # if you *do* have a header row, skip it
                 names=col_names,
                 dtype=col_types)

On a large sample dataset comprising mostly integer columns, this was about 20% faster than specifying dtype='object' in the call to pd.read_csv for me.


问:
TensorFlow : Cant load trained model
I am trying to train, save and load a tensorflow model using tflearn

```<code>        # Building convolutional network

        network = input_data(shape=[None, imageSize, imageSize, 1], name='input')
        network = conv_2d(network, imageSize, self.windowSize, activation='relu', regularizer="L2")
        network = max_pool_2d(network, 2)
        network = local_response_normalization(network)
        network = conv_2d(network, imageSize * 2, self.windowSize, activation='relu', regularizer="L2")
        network = max_pool_2d(network, 2)
        network = local_response_normalization(network)
        network = fully_connected(network, (dim4 * dim4) * (imageSize * 2), activation='tanh')
        network = dropout(network, keep)
        network = fully_connected(network, (dim4 * dim4) * (imageSize * 2), activation='tanh')
        network = dropout(network, keep)
        network = fully_connected(network, n_classes, activation='softmax')
        network = regression(network, optimizer='adam', learning_rate=self.learningRate,
                                loss='categorical_crossentropy', name='target')

        model = tflearn.DNN(network, tensorboard_verbose=0, tensorboard_dir='some/dir')
        model.fit(

            {'input': np.array(myData.train_x).reshape(-1, self.imageSize, self.imageSize, 1)}, {'target': myData.train_y}, n_epoch=self.epochs,

            validation_set=(
                {'input': np.array(myData.test_x).reshape(-1, self.imageSize, self.imageSize, 1)},
            {'target': myData.test_y}),
        snapshot_step=100, show_metric=True, run_id='convnet')
        model.save("some/path/model")
</code>```

this part works. next, i do

```<code>        model_path = "some/path/model.meta"

        if os.path.exists(model_path):
            model.load(model_path)
        else :
            return "need to train the model"

        prediction = self.model.predict([<some_input>])
        print(str(prediction))
        return prediction
</code>```

this fails at model.load(model_path). I get the following error trace

```<code>DataLossError (see above for traceback): Unable to open table file some/path/model.meta: Data loss: not an sstable (bad magic number): perhaps your file is in a different file format and you need to use a different restore operator?
     [[Node: save_5/RestoreV2_4 = RestoreV2[dtypes=[DT_FLOAT], _device="/job:localhost/replica:0/task:0/device:CPU:0"](_arg_save_5/Const_0_0, save_5/RestoreV2_4/tensor_names, save_5/RestoreV2_4/shape_and_slices)]]
Caused by op 'save_5/RestoreV2_4', defined at:
</code>```

what is meant by

```<code>Data loss: not an sstable (bad magic number): perhaps your file is in a different file format and you need to use a different restore operator?
</code>```

I can see that the model is indeed saved properly and is not an empty file. Why cant i load it?

Version Information

```<code>tensorflow==1.4.0
tensorflow-tensorboard==0.4.0rc2
tflearn==0.3.2
Python 3.6.3 :: Anaconda, Inc.
</code>```

答:
ANSWER :

As discussed in the comments, The path you are saving the variables to must contain the ".ckpt" file name.

Similarly restoring should take place through the same ".ckpt" file

Title: TensorFlow : Cant load trained model

Body:
I am trying to train, save and load a tensorflow model using tflearn

        # Building convolutional network

        network = input_data(shape=[None, imageSize, imageSize, 1], name='input')
        network = conv_2d(network, imageSize, self.windowSize, activation='relu', regularizer="L2")
        network = max_pool_2d(network, 2)
        network = local_response_normalization(network)
        network = conv_2d(network, imageSize * 2, self.windowSize, activation='relu', regularizer="L2")
        network = max_pool_2d(network, 2)
        network = local_response_normalization(network)
        network = fully_connected(network, (dim4 * dim4) * (imageSize * 2), activation='tanh')
        network = dropout(network, keep)
        network = fully_connected(network, (dim4 * dim4) * (imageSize * 2), activation='tanh')
        network = dropout(network, keep)
        network = fully_connected(network, n_classes, activation='softmax')
        network = regression(network, optimizer='adam', learning_rate=self.learningRate,
                                loss='categorical_crossentropy', name='target')

        model = tflearn.DNN(network, tensorboard_verbose=0, tensorboard_dir='some/dir')
        model.fit(

            {'input': np.array(myData.train_x).reshape(-1, self.imageSize, self.imageSize, 1)}, {'target': myData.train_y}, n_epoch=self.epochs,

            validation_set=(
                {'input': np.array(myData.test_x).reshape(-1, self.imageSize, self.imageSize, 1)},
            {'target': myData.test_y}),
        snapshot_step=100, show_metric=True, run_id='convnet')
        model.save("some/path/model")

this part works. next, i do

        model_path = "some/path/model.meta"

        if os.path.exists(model_path):
            model.load(model_path)
        else :
            return "need to train the model"

        prediction = self.model.predict([<some_input>])
        print(str(prediction))
        return prediction

this fails at model.load(model_path). I get the following error trace

DataLossError (see above for traceback): Unable to open table file some/path/model.meta: Data loss: not an sstable (bad magic number): perhaps your file is in a different file format and you need to use a different restore operator?
     [[Node: save_5/RestoreV2_4 = RestoreV2[dtypes=[DT_FLOAT], _device="/job:localhost/replica:0/task:0/device:CPU:0"](_arg_save_5/Const_0_0, save_5/RestoreV2_4/tensor_names, save_5/RestoreV2_4/shape_and_slices)]]
Caused by op 'save_5/RestoreV2_4', defined at:

what is meant by

Data loss: not an sstable (bad magic number): perhaps your file is in a different file format and you need to use a different restore operator?

I can see that the model is indeed saved properly and is not an empty file. Why cant i load it?

Version Information

tensorflow==1.4.0
tensorflow-tensorboard==0.4.0rc2
tflearn==0.3.2
Python 3.6.3 :: Anaconda, Inc.


问:
Save input into a char array C++
How can I save input into a char array C++?

The problem I have is that I do not know beforehand how much input will the user provide.

I would like to use only arrays and chars.

答:
You can use std:string.

```<code>#include <iostream>
#include <string>

int main()
{
    std::string s;
    std::cin >> s;

    const char *cstr = s.c_str();

    std::cout << cstr;
}
</code>```

Title: Save input into a char array C++

Body:
You can use std:string.

#include <iostream>
#include <string>

int main()
{
    std::string s;
    std::cin >> s;

    const char *cstr = s.c_str();

    std::cout << cstr;
}


问:
rapidminer and sentiment analysis
Is anyone out there used Rapidminer for sentiment analysis... Is this a right combination???

If not how do I get started with a simple sentiment analysis application??

答:
This series of videos should help:

http://vancouverdata.blogspot.com/2010/11/text-analytics-with-rapidminer-loading.html

Title: rapidminer and sentiment analysis


问:
AWS Federated Login: (AccessDenied) when calling the AssumeRoleWithSAML operation
When I try to login using federated login for AWS CLI, I get this error:

```<code>botocore.exceptions.ClientError: An error occurred (AccessDenied) when calling the AssumeRoleWithSAML operation: Not authorized to perform sts:AssumeRoleWithSAML
</code>```

This prevents me from logging into AWS CLI, and I need that so I can access our CodeCommit repo.

How should I fix this error, do I need to specify the role explicitly?

答:
It turned out I did need to specify the role explicitly, by its ARN.

```<code>aws_cli_login --role arn:aws:iam::28475767868:role/my-role
</code>```

It worked after that. Probably when I didn't specify a role it tried some default role for which I didn't have access.

Body:
When I try to login using federated login for AWS CLI, I get this error:

botocore.exceptions.ClientError: An error occurred (AccessDenied) when calling the AssumeRoleWithSAML operation: Not authorized to perform sts:AssumeRoleWithSAML

This prevents me from logging into AWS CLI, and I need that so I can access our CodeCommit repo.

How should I fix this error, do I need to specify the role explicitly?

Body:
It turned out I did need to specify the role explicitly, by its ARN.

aws_cli_login --role arn:aws:iam::28475767868:role/my-role

It worked after that. Probably when I didn't specify a role it tried some default role for which I didn't have access.


答:
You could split by new line and then split with the preserving quote regex from this answer.

Later map items in an array. Voila!

var string = '$A$1,$B$1,$C$1,$D$1,$E$1,$F$1,$G$1\n$A$2,"$B,$2",$C$2,$D$2,$E$2,$F$2,$G$2\n$A$3,$B$3,,,,,\n$A$4,$B$4,$C$4,$D$4,$E$4,$F$4,$G$4',
    result = string.split('\n').map(s => s.split(/,(?=(?:(?:[^"]*"){2})*[^"]*$)/).map(s => [s]));

console.log(result);```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.as-console-wrapper { max-height: 100% !important; top: 0; }</code>```

Title: How do I parse a comma seperated string into a 2d-array

Body:
I'd like to parse a comma seperated string into an 2d-array.
The values are seperated with a comma and each new line with a new line character.

$A$1,$B$1,$C$1,$D$1,$E$1,$F$1,$G$1 $A$2,"$B,$2",$C$2,$D$2,$E$2,$F$2,$G$2 $A$3,$B$3,,,,, $A$4,$B$hg4,$C$4,$D$4,$E$4,$F$4,$G$4 $A$5,$B$5,$C$5,$D$5,$E$5,$F$5,$G$5 $A$6,$B$6,$C$6,$D$6,$E$6,$F$6,$G$6 $A$7,$B$7,$C$7,,$E$7,$F$7,$G$7 $A$8,$B$8,$C$8,,$E$8,$F$8,$G$8 $A$9,$B$9,$C$9,,$E$9,$F$9,$G$9 $A$10,$B$10,$C$10,,$E$10,$F$10,$G$10 $A$11,$B$11,$C$11,,$E$11,$F$11,$G$11 $A$12,$B$12,$C$12,$D$12,$E$12,$F$12,$G$12 $A$13,,$C$13,$D$13,$E$13,$F$13,$G$13 ,,$C$14,$D$14,$E$14,$F$14,$G$14 ,,$C$15,$D$15,$E$15,$F$15,$G$15 $A$16,$B$16,$C$16,$D$16,$E$16,$F$16,$G$16

The desired outcome should be like this:

arr = [[$A$1],[$B$1],[$C$1],[$D$1],[$E$1],[$F$1],[$G$1]],[[$A$2],["$B,$2"],[$C$2],[$D$2],[$E$2],[$F$2],[$G$2]],[[$A$3],[$B$3],[],[],[],[],[]],[[$A$4],[$B$4],[$C$4],[$D$4],[$E$4],[$F$4],[$G$4]],...

Body:
You could split by new line and then split with the preserving quote regex from this answer.

Later map items in an array. Voila!

var string = '$A$1,$B$1,$C$1,$D$1,$E$1,$F$1,$G$1\n$A$2,"$B,$2",$C$2,$D$2,$E$2,$F$2,$G$2\n$A$3,$B$3,,,,,\n$A$4,$B$4,$C$4,$D$4,$E$4,$F$4,$G$4',
    result = string.split('\n').map(s => s.split(/,(?=(?:(?:[^"]*"){2})*[^"]*$)/).map(s => [s]));

console.log(result);

.as-console-wrapper { max-height: 100% !important; top: 0; }


问:
Angular $http.get() - how to catch "access control" errors
I'm using $http.get() to commit an API request which works just fine as long as I enable CORS in my browser while testing.  Of course, that's just a bandaid.

I found this article:
Angular $http.get: How to catch all the errors?

And have my code set up with a then().catch() and while the catch code is executed as expected, the error is still thrown:

XMLHttpRequest cannot load 'url here' due to access control checks.

Even when I manually disable CORS for development's sake, I still get 401 errors, despite my catch().

The goal is prevent the old "red text" errors in the console and just handle them with an alert to the user.

答:
When you send an http request in a browser, it first sends OPTIONS request which is called preflight. The browser blocks the request if the response for the preflight request doesn't contain Access-Control-Allow-Origin headers.

This preflight request is transparent to Javascript. So, for every ajax call, the browser sends two requests if the destination is cross-domain.

Even though you catch the error, browser is going to report the network error in the console if the preflight request fails.


问:
Need help understanding a specific alloc/release idiom in iOS/Objective-C programming
I'm an experienced C/C++ programmer starting to learn Objective-C development. I'm currently looking through the UICatalog sample and came across another instance of an idiom I've seen several places and never understood.

Code:

```<code>ButtonsViewController *buttonsViewController = [[ButtonsViewController alloc] initWithNibName:@"ButtonsViewController" bundle:nil];
[self.menuList addObject:[NSDictionary dictionaryWithObjectsAndKeys:
                                       NSLocalizedString(@"ButtonsTitle", @""), kTitleKey,
                                       NSLocalizedString(@"ButtonsExplain", @""), kExplainKey,
                                       buttonsViewController, kViewControllerKey, nil]];
[buttonsViewController release];
</code>```

AFAIK, this allocates and initializes a ButtonsViewController, creates an NSDictionary for the ButtonsViewController and adds the dictionary to an NSMutableArray called menuList (which is a member variable of the MainViewController where the above code lives) and then releases the buttonsViewController that it just created. Later, the MainViewController uses the dictionary entry to switch views to the buttonsViewController when necessary.

My question is: why is the buttonsViewController still valid after this code? It was allocated and released with no 'retains' between. Does adding something to an NSDictionary or NSMutableArray have an implicit 'retain'? If so, was I supposed to be able to figure that out somehow, or is it just one of those things you have to read and remember?

答:
Yes, containers like NSDictionary and NSMutableArray retain (or copy, in the case of dictionary keys) the objects you put into them.

See the Collections Programming Topics guide from Apple.

Body:
I'm an experienced C/C++ programmer starting to learn Objective-C development. I'm currently looking through the UICatalog sample and came across another instance of an idiom I've seen several places and never understood.

Code:

ButtonsViewController *buttonsViewController = [[ButtonsViewController alloc] initWithNibName:@"ButtonsViewController" bundle:nil];
[self.menuList addObject:[NSDictionary dictionaryWithObjectsAndKeys:
                                       NSLocalizedString(@"ButtonsTitle", @""), kTitleKey,
                                       NSLocalizedString(@"ButtonsExplain", @""), kExplainKey,
                                       buttonsViewController, kViewControllerKey, nil]];
[buttonsViewController release];

AFAIK, this allocates and initializes a ButtonsViewController, creates an NSDictionary for the ButtonsViewController and adds the dictionary to an NSMutableArray called menuList (which is a member variable of the MainViewController where the above code lives) and then releases the buttonsViewController that it just created. Later, the MainViewController uses the dictionary entry to switch views to the buttonsViewController when necessary.

My question is: why is the buttonsViewController still valid after this code? It was allocated and released with no 'retains' between. Does adding something to an NSDictionary or NSMutableArray have an implicit 'retain'? If so, was I supposed to be able to figure that out somehow, or is it just one of those things you have to read and remember?


问:
Change position p:dialog when I resize the page
i'm a problem with a p:dialog.

Here the code:

```<code>        <p:dialog id="loginDialog" header="Login" width="400" widgetVar="dlg" visible="true"
            rendered="#{loginBean.f_loginRendered}" closable="false" showEffect="clip" draggable="false" resizable="false"
            style="box-shadow: 7px 10px 5px #303030; position:absolute;">
            <h:panelGrid id="panelGrid" columns="2" cellpadding="5" style="margin: 0 auto;">
                <h:outputLabel for="username" value="Username: *" />
                <p:inputText id="username" value="#{loginBean.f_username}" required="true" label="Username"/>
                <h:outputLabel for="password" value="Password: *" />
                <p:password id="password" value="#{loginBean.f_password}" required="true" label="Password"/>

<center>            <p:commandButton id="loginButton" value="Login" update="globalGrowl" actionListener="#{loginBean.checkDown}" /> </center>
        </h:panelGrid >

        </p:dialog>
</code>```

It's a simple login form. The problem is that when I resize the webpage, the dialog is fixed and it does not move by following the page, unlike the pictures.

How I can do it?

答:
In case your web page is resizing only horizontally, you can do it using JavaScript by adding this code in h:body element of your page

```<code><script type="text/javascript">
            window.onresize = function(event) {
                console.log("Screen is resized");
                var dialog = document.getElementById("loginDialog");
                var windowHeight=window.innerHeight;
                var windowWidth=window.innerWidth;
                console.log("Window W/H=" + windowWidth + "/" + windowHeight);
                //width of your dialog set in p:dialog
                var dialogWidth=400;
                //position your dialog x px left from browser window left border
                dialog.style.left=((windowWidth-dialogWidth)/2)+"px"
            }
</script>
</code>```

Beware that

if your p:dialog is wrapped up by h:form element with id defined, you will need to change one line of script above like this

```<code>var dialog = document.getElementById("yourFormId:loginDialog");
</code>```

if your web page is resizing vertically too, you will need to set/calculate p:dialog height and to apply additional line inside JavaScript function

```<code>dialog.style.top = ((windowHeight-dialogHeight)/2)+"px"
</code>```

Body:
i'm a problem with a p:dialog.

Here the code:

            <h:panelGrid id="panelGrid" columns="2" cellpadding="5" style="margin: 0 auto;">
                <h:outputLabel for="username" value="Username: *" />

                <h:outputLabel for="password" value="Password: *" />

        </h:panelGrid >

It's a simple login form. The problem is that when I resize the webpage, the dialog is fixed and it does not move by following the page, unlike the pictures.

How I can do it?

Body:
In case your web page is resizing only horizontally, you can do it using JavaScript by adding this code in h:body element of your page

<script type="text/javascript">
            window.onresize = function(event) {
                console.log("Screen is resized");
                var dialog = document.getElementById("loginDialog");
                var windowHeight=window.innerHeight;
                var windowWidth=window.innerWidth;
                console.log("Window W/H=" + windowWidth + "/" + windowHeight);
                //width of your dialog set in p:dialog
                var dialogWidth=400;
                //position your dialog x px left from browser window left border
                dialog.style.left=((windowWidth-dialogWidth)/2)+"px"
            }
</script>

Beware that

if your p:dialog is wrapped up by h:form element with id defined, you will need to change one line of script above like this

var dialog = document.getElementById("yourFormId:loginDialog");

if your web page is resizing vertically too, you will need to set/calculate p:dialog height and to apply additional line inside JavaScript function

dialog.style.top = ((windowHeight-dialogHeight)/2)+"px"


问:
Error - Configuration With name 'default' not found- React Native android importing projects for Android
I have two react native projects Project A on which I am working on. I had previously created another project for setting the orientation (also react native having java code to expose the orientation methods to javascript). I included the orientation project using npm install  into Project A node modules. As per the documentation available added the following entries in settings.gradle of Proj A --
include ':orientation',':app'
project(':orientation').projectDir = new File(settingsDir, '../node_modules/react-native-my-orientation/android/')

And then added compile project(':orientation') in build.gradle available within the app folder. When the compiles i keep getting the error Configuration With name 'default' not found.
Has anyone faced such a problem in including an external project to a react-native android project.

答: I just solved this issue. Sometimes when you install RN packages with npm, or more specifically uninstall them, code is leftover in the Android files. You can manually delete this packages in the app/build.gradle file also the settings.gradle file and that works for me.


问:
Delete entire row if cell (date) value is within the time range
I need help on my coding. So basically the codes below will get the data from another sheet and close it automatically. What I wanted to output is just the rows that will fall between 14:00 and 22:00 of the day. So if the SLA target date would be beyond that range, I'l like to delete that row and shift up so that the output will have no spaces in between. I'm not sure how to do it.

below is my code:

```<code>Option Explicit

Private Sub Workbook_Open()
    Call ClearData
    Call ReadDataFromCloseFile
End Sub

Sub ReadDataFromCloseFile()
    On Error GoTo ErrHandler
    Application.ScreenUpdating = False

    Dim src_im As Workbook
    Dim src_fr As Workbook
    Dim src_chm As Workbook
    ' OPEN THE SOURCE EXCEL WORKBOOK IN "READ ONLY MODE".
    Set src_im = Workbooks.Open(ThisWorkbook.Path & "\incident_sla.csv", True, True)
    ' GET THE TOTAL ROWS FROM THE SOURCE WORKBOOK.
    Dim iTotalRows_im As Integer
    iTotalRows_im = src_im.Worksheets("incident_sla").UsedRange.Rows.Count
    Set src_fr = Workbooks.Open(ThisWorkbook.Path & "\sc_req_item_sla.csv", True, True)
    Dim iTotalRows_fr As Integer
    iTotalRows_fr = src_fr.Worksheets("sc_req_item_sla").UsedRange.Rows.Count
    Set src_chm = Workbooks.Open(ThisWorkbook.Path & "\change_task.csv", True, True)
    Dim iTotalRows_chm As Integer
    iTotalRows_chm = src_chm.Worksheets("change_task").UsedRange.Rows.Count

    ' COPY DATA FROM SOURCE (CLOSE WORKGROUP) TO THE DESTINATION WORKBOOK.
    Dim iCnt_im As Integer         ' COUNTER.
    For iCnt_im = 2 To iTotalRows_im
    If Format(src_im.Worksheets("incident_sla").Range("G" & iCnt_im).Value, "mm/dd/yyyy hh:mm") < Format(Date + TimeValue("22:00:00"), "mm/dd/yyyy hh:mm") Then
        Worksheets("Pre-shift").Range("A" & iCnt_im + 2).Formula = src_im.Worksheets("incident_sla").Range("A" & iCnt_im).Formula
        Worksheets("Pre-shift").Range("B" & iCnt_im + 2).Formula = src_im.Worksheets("incident_sla").Range("B" & iCnt_im).Formula
        Worksheets("Pre-shift").Range("B" & iCnt_im + 2).WrapText = False
        Worksheets("Pre-shift").Range("C" & iCnt_im + 2).Formula = src_im.Worksheets("incident_sla").Range("C" & iCnt_im).Formula
        Worksheets("Pre-shift").Range("C" & iCnt_im + 2).Borders.LineStyle = xlContinuous
        Worksheets("Pre-shift").Range("C" & iCnt_im + 2).Borders.Color = RGB(0, 0, 0)
        Worksheets("Pre-shift").Range("D" & iCnt_im + 2).Formula = src_im.Worksheets("incident_sla").Range("D" & iCnt_im).Formula
        Worksheets("Pre-shift").Range("E" & iCnt_im + 2).Formula = src_im.Worksheets("incident_sla").Range("E" & iCnt_im).Formula
        Worksheets("Pre-shift").Range("F" & iCnt_im + 2).Formula = src_im.Worksheets("incident_sla").Range("F" & iCnt_im).Formula
        Worksheets("Pre-shift").Range("G" & iCnt_im + 2).Value = Format(src_im.Worksheets("incident_sla").Range("G" & iCnt_im).Value, "mm/dd/yyyy hh:mm")
        Worksheets("Pre-shift").Range("H" & iCnt_im + 2).Formula = src_im.Worksheets("incident_sla").Range("H" & iCnt_im).Formula
        Worksheets("Pre-shift").Range("H" & iCnt_im + 2).Borders.LineStyle = xlContinuous
        Worksheets("Pre-shift").Range("H" & iCnt_im + 2).Borders.Color = RGB(0, 0, 0)
        Worksheets("Pre-shift").Range("I" & iCnt_im + 2).Value = Format(Date + TimeValue("22:00:00"), "mm/dd/yyyy hh:mm")
        Worksheets("Pre-shift").Range("J" & iCnt_im + 2).Formula = Worksheets("Pre-shift").Range("I" & iCnt_im + 2).Value <= Worksheets("Pre-shift").Range("G" & iCnt_im + 2).Value
    Else
            Worksheets("Pre-shift").Rows(iCnt_im + 2).EntireRow.Delete shift:=xlUp
    End If
    Next iCnt_im

    Sheets("Pre-shift").Range("A3") = "Incident ID"
    Sheets("Pre-shift").Range("A3").Interior.Color = RGB(0, 0, 0)
    Sheets("Pre-shift").Range("A3").Font.Color = RGB(255, 255, 255)
    Sheets("Pre-shift").Range("B3") = "Title"
    Sheets("Pre-shift").Range("B3").Interior.Color = RGB(0, 0, 0)
    Sheets("Pre-shift").Range("B3").Font.Color = RGB(255, 255, 255)
    Sheets("Pre-shift").Range("C3") = "Assignee Name"
    Sheets("Pre-shift").Range("C3").Interior.Color = RGB(0, 0, 0)
    Sheets("Pre-shift").Range("C3").Font.Color = RGB(255, 255, 255)
    Sheets("Pre-shift").Range("D3") = "Status"
    Sheets("Pre-shift").Range("D3").Interior.Color = RGB(0, 0, 0)
    Sheets("Pre-shift").Range("D3").Font.Color = RGB(255, 255, 255)
    Sheets("Pre-shift").Range("E3") = "Service Type"
    Sheets("Pre-shift").Range("E3").Interior.Color = RGB(0, 0, 0)
    Sheets("Pre-shift").Range("E3").Font.Color = RGB(255, 255, 255)
    Sheets("Pre-shift").Range("F3") = "Priority"
    Sheets("Pre-shift").Range("F3").Interior.Color = RGB(0, 0, 0)
    Sheets("Pre-shift").Range("F3").Font.Color = RGB(255, 255, 255)
    Sheets("Pre-shift").Range("G3") = "SLA Target Date"
    Sheets("Pre-shift").Range("G3").Interior.Color = RGB(0, 0, 0)
    Sheets("Pre-shift").Range("G3").Font.Color = RGB(255, 255, 255)
    Sheets("Pre-shift").Range("H3") = iCnt_im
    Sheets("Pre-shift").Range("H3").Interior.Color = RGB(0, 0, 0)
    Sheets("Pre-shift").Range("H3").Font.Color = RGB(255, 255, 255)
'
'    Dim after As Integer
'
'    For after = 2 To iCnt_im
'    If Worksheets("Pre-shift").Range("J" & after + 2).Value = False Then
'    Else
'            Worksheets("Pre-shift").Rows(after + 2).EntireRow.Delete shift:=xlUp
'    End If
'    Next after

'    If iCnt_im = 2 Then
'    Sheets("Pre-shift").Range("A4").Interior.Color = RGB(191, 191, 191)
'    End If
    Dim iCnt_fr As Integer
    For iCnt_fr = 2 To iTotalRows_fr
'        If CDate(src_fr.Worksheets("sc_req_item_sla").Range("E" & iCnt_fr).Formula) > Now() Then
        Worksheets("Pre-shift").Range("A" & iCnt_fr + iCnt_im + 2).Formula = src_fr.Worksheets("sc_req_item_sla").Range("A" & iCnt_fr).Formula
        Worksheets("Pre-shift").Range("B" & iCnt_fr + iCnt_im + 2).Formula = src_fr.Worksheets("sc_req_item_sla").Range("B" & iCnt_fr).Formula
        Worksheets("Pre-shift").Range("B" & iCnt_fr + iCnt_im + 2).WrapText = False
        Worksheets("Pre-shift").Range("C" & iCnt_fr + iCnt_im + 2).Formula = src_fr.Worksheets("sc_req_item_sla").Range("C" & iCnt_fr).Formula
        Worksheets("Pre-shift").Range("C" & iCnt_fr + iCnt_im + 2).Borders.LineStyle = xlContinuous
        Worksheets("Pre-shift").Range("C" & iCnt_fr + iCnt_im + 2).Borders.Color = RGB(0, 0, 0)
        Worksheets("Pre-shift").Range("D" & iCnt_fr + iCnt_im + 2).Formula = src_fr.Worksheets("sc_req_item_sla").Range("D" & iCnt_fr).Formula
        Worksheets("Pre-shift").Range("E" & iCnt_fr + iCnt_im + 2).Formula = src_fr.Worksheets("sc_req_item_sla").Range("E" & iCnt_fr).Formula
        Worksheets("Pre-shift").Range("F" & iCnt_fr + iCnt_im + 2).Formula = src_fr.Worksheets("sc_req_item_sla").Range("F" & iCnt_fr).Formula
        Worksheets("Pre-shift").Range("G" & iCnt_fr + iCnt_im + 2).Formula = src_fr.Worksheets("sc_req_item_sla").Range("G" & iCnt_im).Formula
'        Else: .EntireRow.Delete
'        End If
    Next iCnt_fr
    Sheets("Pre-shift").Range("A" & iCnt_im + 3).Formula = "Fulfillment ID"
    Sheets("Pre-shift").Range("A" & iCnt_im + 3).Interior.Color = RGB(0, 0, 0)
    Sheets("Pre-shift").Range("A" & iCnt_im + 3).Font.Color = RGB(255, 255, 255)
    Sheets("Pre-shift").Range("B" & iCnt_im + 3).Formula = "Title"
    Sheets("Pre-shift").Range("C" & iCnt_im + 3).Formula = "Assignee Name"
    Sheets("Pre-shift").Range("D" & iCnt_im + 3).Formula = "Status"
    Sheets("Pre-shift").Range("E" & iCnt_im + 3).Formula = "SLA Target Date"
    Sheets("Pre-shift").Range("F" & iCnt_im + 3).Formula = "Assignment"
    Sheets("Pre-shift").Range("A" & iCnt_im + 3).Interior.Color = RGB(0, 0, 0)
    Sheets("Pre-shift").Range("A" & iCnt_im + 3).Font.Color = RGB(255, 255, 255)
    Sheets("Pre-shift").Range("A" & iCnt_im + 3).Interior.Color = RGB(0, 0, 0)
    Sheets("Pre-shift").Range("A" & iCnt_im + 3).Font.Color = RGB(255, 255, 255)
    Sheets("Pre-shift").Range("B" & iCnt_im + 3).Interior.Color = RGB(0, 0, 0)
    Sheets("Pre-shift").Range("B" & iCnt_im + 3).Font.Color = RGB(255, 255, 255)
    Sheets("Pre-shift").Range("C" & iCnt_im + 3).Interior.Color = RGB(0, 0, 0)
    Sheets("Pre-shift").Range("C" & iCnt_im + 3).Font.Color = RGB(255, 255, 255)
    Sheets("Pre-shift").Range("D" & iCnt_im + 3).Interior.Color = RGB(0, 0, 0)
    Sheets("Pre-shift").Range("D" & iCnt_im + 3).Font.Color = RGB(255, 255, 255)
    Sheets("Pre-shift").Range("E" & iCnt_im + 3).Interior.Color = RGB(0, 0, 0)
    Sheets("Pre-shift").Range("E" & iCnt_im + 3).Font.Color = RGB(255, 255, 255)
    Sheets("Pre-shift").Range("F" & iCnt_im + 3).Interior.Color = RGB(0, 0, 0)
    Sheets("Pre-shift").Range("F" & iCnt_im + 3).Font.Color = RGB(255, 255, 255)

    Dim iCnt_chm As Integer
    For iCnt_chm = 2 To iTotalRows_chm
    Worksheets("Pre-shift").Range("A" & iCnt_chm + iCnt_fr + iCnt_im + 2).Formula = src_chm.Worksheets("change_task").Range("A" & iCnt_chm).Formula
    Worksheets("Pre-shift").Range("B" & iCnt_chm + iCnt_fr + iCnt_im + 2).Formula = src_chm.Worksheets("change_task").Range("B" & iCnt_chm).Formula
    Worksheets("Pre-shift").Range("C" & iCnt_chm + iCnt_fr + iCnt_im + 2).Formula = src_chm.Worksheets("change_task").Range("C" & iCnt_chm).Formula
    Worksheets("Pre-shift").Range("C" & iCnt_chm + iCnt_fr + iCnt_im + 2).HorizontalAlignment = xlLeft
    'Worksheets("Pre-shift").Range("C" & iCnt_chm + iCnt_fr + iCnt_im + 2).WrapText = True
    Worksheets("Pre-shift").Range("D" & iCnt_chm + iCnt_fr + iCnt_im + 2).Formula = src_chm.Worksheets("change_task").Range("D" & iCnt_chm).Formula
    Worksheets("Pre-shift").Range("E" & iCnt_chm + iCnt_fr + iCnt_im + 2).Formula = src_chm.Worksheets("change_task").Range("E" & iCnt_chm).Formula
    Worksheets("Pre-shift").Range("F" & iCnt_chm + iCnt_fr + iCnt_im + 2).Formula = src_chm.Worksheets("change_task").Range("F" & iCnt_chm).Formula
    Worksheets("Pre-shift").Range("D" & iCnt_chm + iCnt_fr + iCnt_im + 2).Borders.LineStyle = xlContinuous
    Worksheets("Pre-shift").Range("D" & iCnt_chm + iCnt_fr + iCnt_im + 2).Borders.Color = RGB(0, 0, 0)
    Worksheets("Pre-shift").Range("G" & iCnt_chm + iCnt_fr + iCnt_im + 2).Formula = src_chm.Worksheets("change_task").Range("G" & iCnt_chm).Formula

    Next iCnt_chm
    Sheets("Pre-shift").Range("A" & iCnt_fr + iCnt_im + 3).Formula = "Parent Change"
    Sheets("Pre-shift").Range("B" & iCnt_fr + iCnt_im + 3).Formula = "Task ID"
    Sheets("Pre-shift").Range("C" & iCnt_fr + iCnt_im + 3).Formula = "Title"
    Sheets("Pre-shift").Range("D" & iCnt_fr + iCnt_im + 3).Formula = "Assignee"
    Sheets("Pre-shift").Range("E" & iCnt_fr + iCnt_im + 3).Formula = "Status"
    Sheets("Pre-shift").Range("F" & iCnt_fr + iCnt_im + 3).Formula = "Planned Start"
    Sheets("Pre-shift").Range("G" & iCnt_fr + iCnt_im + 3).Formula = "Planned End"

    Sheets("Pre-shift").Range("A" & iCnt_fr + iCnt_im + 3).Interior.Color = RGB(0, 0, 0)
    Sheets("Pre-shift").Range("A" & iCnt_fr + iCnt_im + 3).Font.Color = RGB(255, 255, 255)
    Sheets("Pre-shift").Range("B" & iCnt_fr + iCnt_im + 3).Interior.Color = RGB(0, 0, 0)
    Sheets("Pre-shift").Range("B" & iCnt_fr + iCnt_im + 3).Font.Color = RGB(255, 255, 255)
    Sheets("Pre-shift").Range("C" & iCnt_fr + iCnt_im + 3).Interior.Color = RGB(0, 0, 0)
    Sheets("Pre-shift").Range("C" & iCnt_fr + iCnt_im + 3).Font.Color = RGB(255, 255, 255)
    Sheets("Pre-shift").Range("D" & iCnt_fr + iCnt_im + 3).Interior.Color = RGB(0, 0, 0)
    Sheets("Pre-shift").Range("D" & iCnt_fr + iCnt_im + 3).Font.Color = RGB(255, 255, 255)
    Sheets("Pre-shift").Range("E" & iCnt_fr + iCnt_im + 3).Interior.Color = RGB(0, 0, 0)
    Sheets("Pre-shift").Range("E" & iCnt_fr + iCnt_im + 3).Font.Color = RGB(255, 255, 255)
    Sheets("Pre-shift").Range("F" & iCnt_fr + iCnt_im + 3).Interior.Color = RGB(0, 0, 0)
    Sheets("Pre-shift").Range("F" & iCnt_fr + iCnt_im + 3).Font.Color = RGB(255, 255, 255)
    Sheets("Pre-shift").Range("G" & iCnt_fr + iCnt_im + 3).Interior.Color = RGB(0, 0, 0)
    Sheets("Pre-shift").Range("G" & iCnt_fr + iCnt_im + 3).Font.Color = RGB(255, 255, 255)

    ' CLOSE THE SOURCE FILE.
    src_im.Close False             ' FALSE - DON'T SAVE THE SOURCE FILE.
    Set src_im = Nothing
    src_fr.Close False             ' FALSE - DON'T SAVE THE SOURCE FILE.
    Set src_fr = Nothing
    src_chm.Close False             ' FALSE - DON'T SAVE THE SOURCE FILE.
    Set src_chm = Nothing

ErrHandler:
    Application.EnableEvents = True
    Application.ScreenUpdating = True
End Sub
</code>```

答:
This will correctly evaluate your time values.  Can't you just not COPY DATA FROM SOURCE (CLOSE WORKGROUP) TO THE DESTINATION WORKBOOK?

For it to be today's date, just check that too

```<code>If TimeValue(src_im.Worksheets("incident_sla").Range("G" & iCnt_im).Value) > TimeValue("13:59:59") And TimeValue(src_im.Worksheets("incident_sla").Range("G" & iCnt_im).Value) < TimeValue("22:00:01")  and Int(src_im.Worksheets("incident_sla").Range("G" & iCnt_im).Value) = Date Then
</code>```

Body:
I need help on my coding. So basically the codes below will get the data from another sheet and close it automatically. What I wanted to output is just the rows that will fall between 14:00 and 22:00 of the day. So if the SLA target date would be beyond that range, I'l like to delete that row and shift up so that the output will have no spaces in between. I'm not sure how to do it.

below is my code:

Option Explicit

Private Sub Workbook_Open()
    Call ClearData
    Call ReadDataFromCloseFile
End Sub

Sub ReadDataFromCloseFile()
    On Error GoTo ErrHandler
    Application.ScreenUpdating = False

    Dim src_im As Workbook
    Dim src_fr As Workbook
    Dim src_chm As Workbook
    ' OPEN THE SOURCE EXCEL WORKBOOK IN "READ ONLY MODE".
    Set src_im = Workbooks.Open(ThisWorkbook.Path & "\incident_sla.csv", True, True)
    ' GET THE TOTAL ROWS FROM THE SOURCE WORKBOOK.
    Dim iTotalRows_im As Integer
    iTotalRows_im = src_im.Worksheets("incident_sla").UsedRange.Rows.Count
    Set src_fr = Workbooks.Open(ThisWorkbook.Path & "\sc_req_item_sla.csv", True, True)
    Dim iTotalRows_fr As Integer
    iTotalRows_fr = src_fr.Worksheets("sc_req_item_sla").UsedRange.Rows.Count
    Set src_chm = Workbooks.Open(ThisWorkbook.Path & "\change_task.csv", True, True)
    Dim iTotalRows_chm As Integer
    iTotalRows_chm = src_chm.Worksheets("change_task").UsedRange.Rows.Count

    ' COPY DATA FROM SOURCE (CLOSE WORKGROUP) TO THE DESTINATION WORKBOOK.
    Dim iCnt_im As Integer         ' COUNTER.
    For iCnt_im = 2 To iTotalRows_im
    If Format(src_im.Worksheets("incident_sla").Range("G" & iCnt_im).Value, "mm/dd/yyyy hh:mm") < Format(Date + TimeValue("22:00:00"), "mm/dd/yyyy hh:mm") Then
        Worksheets("Pre-shift").Range("A" & iCnt_im + 2).Formula = src_im.Worksheets("incident_sla").Range("A" & iCnt_im).Formula
        Worksheets("Pre-shift").Range("B" & iCnt_im + 2).Formula = src_im.Worksheets("incident_sla").Range("B" & iCnt_im).Formula
        Worksheets("Pre-shift").Range("B" & iCnt_im + 2).WrapText = False
        Worksheets("Pre-shift").Range("C" & iCnt_im + 2).Formula = src_im.Worksheets("incident_sla").Range("C" & iCnt_im).Formula
        Worksheets("Pre-shift").Range("C" & iCnt_im + 2).Borders.LineStyle = xlContinuous
        Worksheets("Pre-shift").Range("C" & iCnt_im + 2).Borders.Color = RGB(0, 0, 0)
        Worksheets("Pre-shift").Range("D" & iCnt_im + 2).Formula = src_im.Worksheets("incident_sla").Range("D" & iCnt_im).Formula
        Worksheets("Pre-shift").Range("E" & iCnt_im + 2).Formula = src_im.Worksheets("incident_sla").Range("E" & iCnt_im).Formula
        Worksheets("Pre-shift").Range("F" & iCnt_im + 2).Formula = src_im.Worksheets("incident_sla").Range("F" & iCnt_im).Formula
        Worksheets("Pre-shift").Range("G" & iCnt_im + 2).Value = Format(src_im.Worksheets("incident_sla").Range("G" & iCnt_im).Value, "mm/dd/yyyy hh:mm")
        Worksheets("Pre-shift").Range("H" & iCnt_im + 2).Formula = src_im.Worksheets("incident_sla").Range("H" & iCnt_im).Formula
        Worksheets("Pre-shift").Range("H" & iCnt_im + 2).Borders.LineStyle = xlContinuous
        Worksheets("Pre-shift").Range("H" & iCnt_im + 2).Borders.Color = RGB(0, 0, 0)
        Worksheets("Pre-shift").Range("I" & iCnt_im + 2).Value = Format(Date + TimeValue("22:00:00"), "mm/dd/yyyy hh:mm")
        Worksheets("Pre-shift").Range("J" & iCnt_im + 2).Formula = Worksheets("Pre-shift").Range("I" & iCnt_im + 2).Value <= Worksheets("Pre-shift").Range("G" & iCnt_im + 2).Value
    Else
            Worksheets("Pre-shift").Rows(iCnt_im + 2).EntireRow.Delete shift:=xlUp
    End If
    Next iCnt_im

    Sheets("Pre-shift").Range("A3") = "Incident ID"
    Sheets("Pre-shift").Range("A3").Interior.Color = RGB(0, 0, 0)
    Sheets("Pre-shift").Range("A3").Font.Color = RGB(255, 255, 255)
    Sheets("Pre-shift").Range("B3") = "Title"
    Sheets("Pre-shift").Range("B3").Interior.Color = RGB(0, 0, 0)
    Sheets("Pre-shift").Range("B3").Font.Color = RGB(255, 255, 255)
    Sheets("Pre-shift").Range("C3") = "Assignee Name"
    Sheets("Pre-shift").Range("C3").Interior.Color = RGB(0, 0, 0)
    Sheets("Pre-shift").Range("C3").Font.Color = RGB(255, 255, 255)
    Sheets("Pre-shift").Range("D3") = "Status"
    Sheets("Pre-shift").Range("D3").Interior.Color = RGB(0, 0, 0)
    Sheets("Pre-shift").Range("D3").Font.Color = RGB(255, 255, 255)
    Sheets("Pre-shift").Range("E3") = "Service Type"
    Sheets("Pre-shift").Range("E3").Interior.Color = RGB(0, 0, 0)
    Sheets("Pre-shift").Range("E3").Font.Color = RGB(255, 255, 255)
    Sheets("Pre-shift").Range("F3") = "Priority"
    Sheets("Pre-shift").Range("F3").Interior.Color = RGB(0, 0, 0)
    Sheets("Pre-shift").Range("F3").Font.Color = RGB(255, 255, 255)
    Sheets("Pre-shift").Range("G3") = "SLA Target Date"
    Sheets("Pre-shift").Range("G3").Interior.Color = RGB(0, 0, 0)
    Sheets("Pre-shift").Range("G3").Font.Color = RGB(255, 255, 255)
    Sheets("Pre-shift").Range("H3") = iCnt_im
    Sheets("Pre-shift").Range("H3").Interior.Color = RGB(0, 0, 0)
    Sheets("Pre-shift").Range("H3").Font.Color = RGB(255, 255, 255)
'
'    Dim after As Integer
'
'    For after = 2 To iCnt_im
'    If Worksheets("Pre-shift").Range("J" & after + 2).Value = False Then
'    Else
'            Worksheets("Pre-shift").Rows(after + 2).EntireRow.Delete shift:=xlUp
'    End If
'    Next after

'    If iCnt_im = 2 Then
'    Sheets("Pre-shift").Range("A4").Interior.Color = RGB(191, 191, 191)
'    End If
    Dim iCnt_fr As Integer
    For iCnt_fr = 2 To iTotalRows_fr
'        If CDate(src_fr.Worksheets("sc_req_item_sla").Range("E" & iCnt_fr).Formula) > Now() Then
        Worksheets("Pre-shift").Range("A" & iCnt_fr + iCnt_im + 2).Formula = src_fr.Worksheets("sc_req_item_sla").Range("A" & iCnt_fr).Formula
        Worksheets("Pre-shift").Range("B" & iCnt_fr + iCnt_im + 2).Formula = src_fr.Worksheets("sc_req_item_sla").Range("B" & iCnt_fr).Formula
        Worksheets("Pre-shift").Range("B" & iCnt_fr + iCnt_im + 2).WrapText = False
        Worksheets("Pre-shift").Range("C" & iCnt_fr + iCnt_im + 2).Formula = src_fr.Worksheets("sc_req_item_sla").Range("C" & iCnt_fr).Formula
        Worksheets("Pre-shift").Range("C" & iCnt_fr + iCnt_im + 2).Borders.LineStyle = xlContinuous
        Worksheets("Pre-shift").Range("C" & iCnt_fr + iCnt_im + 2).Borders.Color = RGB(0, 0, 0)
        Worksheets("Pre-shift").Range("D" & iCnt_fr + iCnt_im + 2).Formula = src_fr.Worksheets("sc_req_item_sla").Range("D" & iCnt_fr).Formula
        Worksheets("Pre-shift").Range("E" & iCnt_fr + iCnt_im + 2).Formula = src_fr.Worksheets("sc_req_item_sla").Range("E" & iCnt_fr).Formula
        Worksheets("Pre-shift").Range("F" & iCnt_fr + iCnt_im + 2).Formula = src_fr.Worksheets("sc_req_item_sla").Range("F" & iCnt_fr).Formula
        Worksheets("Pre-shift").Range("G" & iCnt_fr + iCnt_im + 2).Formula = src_fr.Worksheets("sc_req_item_sla").Range("G" & iCnt_im).Formula
'        Else: .EntireRow.Delete
'        End If
    Next iCnt_fr
    Sheets("Pre-shift").Range("A" & iCnt_im + 3).Formula = "Fulfillment ID"
    Sheets("Pre-shift").Range("A" & iCnt_im + 3).Interior.Color = RGB(0, 0, 0)
    Sheets("Pre-shift").Range("A" & iCnt_im + 3).Font.Color = RGB(255, 255, 255)
    Sheets("Pre-shift").Range("B" & iCnt_im + 3).Formula = "Title"
    Sheets("Pre-shift").Range("C" & iCnt_im + 3).Formula = "Assignee Name"
    Sheets("Pre-shift").Range("D" & iCnt_im + 3).Formula = "Status"
    Sheets("Pre-shift").Range("E" & iCnt_im + 3).Formula = "SLA Target Date"
    Sheets("Pre-shift").Range("F" & iCnt_im + 3).Formula = "Assignment"
    Sheets("Pre-shift").Range("A" & iCnt_im + 3).Interior.Color = RGB(0, 0, 0)
    Sheets("Pre-shift").Range("A" & iCnt_im + 3).Font.Color = RGB(255, 255, 255)
    Sheets("Pre-shift").Range("A" & iCnt_im + 3).Interior.Color = RGB(0, 0, 0)
    Sheets("Pre-shift").Range("A" & iCnt_im + 3).Font.Color = RGB(255, 255, 255)
    Sheets("Pre-shift").Range("B" & iCnt_im + 3).Interior.Color = RGB(0, 0, 0)
    Sheets("Pre-shift").Range("B" & iCnt_im + 3).Font.Color = RGB(255, 255, 255)
    Sheets("Pre-shift").Range("C" & iCnt_im + 3).Interior.Color = RGB(0, 0, 0)
    Sheets("Pre-shift").Range("C" & iCnt_im + 3).Font.Color = RGB(255, 255, 255)
    Sheets("Pre-shift").Range("D" & iCnt_im + 3).Interior.Color = RGB(0, 0, 0)
    Sheets("Pre-shift").Range("D" & iCnt_im + 3).Font.Color = RGB(255, 255, 255)
    Sheets("Pre-shift").Range("E" & iCnt_im + 3).Interior.Color = RGB(0, 0, 0)
    Sheets("Pre-shift").Range("E" & iCnt_im + 3).Font.Color = RGB(255, 255, 255)
    Sheets("Pre-shift").Range("F" & iCnt_im + 3).Interior.Color = RGB(0, 0, 0)
    Sheets("Pre-shift").Range("F" & iCnt_im + 3).Font.Color = RGB(255, 255, 255)

    Dim iCnt_chm As Integer
    For iCnt_chm = 2 To iTotalRows_chm
    Worksheets("Pre-shift").Range("A" & iCnt_chm + iCnt_fr + iCnt_im + 2).Formula = src_chm.Worksheets("change_task").Range("A" & iCnt_chm).Formula
    Worksheets("Pre-shift").Range("B" & iCnt_chm + iCnt_fr + iCnt_im + 2).Formula = src_chm.Worksheets("change_task").Range("B" & iCnt_chm).Formula
    Worksheets("Pre-shift").Range("C" & iCnt_chm + iCnt_fr + iCnt_im + 2).Formula = src_chm.Worksheets("change_task").Range("C" & iCnt_chm).Formula
    Worksheets("Pre-shift").Range("C" & iCnt_chm + iCnt_fr + iCnt_im + 2).HorizontalAlignment = xlLeft
    'Worksheets("Pre-shift").Range("C" & iCnt_chm + iCnt_fr + iCnt_im + 2).WrapText = True
    Worksheets("Pre-shift").Range("D" & iCnt_chm + iCnt_fr + iCnt_im + 2).Formula = src_chm.Worksheets("change_task").Range("D" & iCnt_chm).Formula
    Worksheets("Pre-shift").Range("E" & iCnt_chm + iCnt_fr + iCnt_im + 2).Formula = src_chm.Worksheets("change_task").Range("E" & iCnt_chm).Formula
    Worksheets("Pre-shift").Range("F" & iCnt_chm + iCnt_fr + iCnt_im + 2).Formula = src_chm.Worksheets("change_task").Range("F" & iCnt_chm).Formula
    Worksheets("Pre-shift").Range("D" & iCnt_chm + iCnt_fr + iCnt_im + 2).Borders.LineStyle = xlContinuous
    Worksheets("Pre-shift").Range("D" & iCnt_chm + iCnt_fr + iCnt_im + 2).Borders.Color = RGB(0, 0, 0)
    Worksheets("Pre-shift").Range("G" & iCnt_chm + iCnt_fr + iCnt_im + 2).Formula = src_chm.Worksheets("change_task").Range("G" & iCnt_chm).Formula

    Next iCnt_chm
    Sheets("Pre-shift").Range("A" & iCnt_fr + iCnt_im + 3).Formula = "Parent Change"
    Sheets("Pre-shift").Range("B" & iCnt_fr + iCnt_im + 3).Formula = "Task ID"
    Sheets("Pre-shift").Range("C" & iCnt_fr + iCnt_im + 3).Formula = "Title"
    Sheets("Pre-shift").Range("D" & iCnt_fr + iCnt_im + 3).Formula = "Assignee"
    Sheets("Pre-shift").Range("E" & iCnt_fr + iCnt_im + 3).Formula = "Status"
    Sheets("Pre-shift").Range("F" & iCnt_fr + iCnt_im + 3).Formula = "Planned Start"
    Sheets("Pre-shift").Range("G" & iCnt_fr + iCnt_im + 3).Formula = "Planned End"

    Sheets("Pre-shift").Range("A" & iCnt_fr + iCnt_im + 3).Interior.Color = RGB(0, 0, 0)
    Sheets("Pre-shift").Range("A" & iCnt_fr + iCnt_im + 3).Font.Color = RGB(255, 255, 255)
    Sheets("Pre-shift").Range("B" & iCnt_fr + iCnt_im + 3).Interior.Color = RGB(0, 0, 0)
    Sheets("Pre-shift").Range("B" & iCnt_fr + iCnt_im + 3).Font.Color = RGB(255, 255, 255)
    Sheets("Pre-shift").Range("C" & iCnt_fr + iCnt_im + 3).Interior.Color = RGB(0, 0, 0)
    Sheets("Pre-shift").Range("C" & iCnt_fr + iCnt_im + 3).Font.Color = RGB(255, 255, 255)
    Sheets("Pre-shift").Range("D" & iCnt_fr + iCnt_im + 3).Interior.Color = RGB(0, 0, 0)
    Sheets("Pre-shift").Range("D" & iCnt_fr + iCnt_im + 3).Font.Color = RGB(255, 255, 255)
    Sheets("Pre-shift").Range("E" & iCnt_fr + iCnt_im + 3).Interior.Color = RGB(0, 0, 0)
    Sheets("Pre-shift").Range("E" & iCnt_fr + iCnt_im + 3).Font.Color = RGB(255, 255, 255)
    Sheets("Pre-shift").Range("F" & iCnt_fr + iCnt_im + 3).Interior.Color = RGB(0, 0, 0)
    Sheets("Pre-shift").Range("F" & iCnt_fr + iCnt_im + 3).Font.Color = RGB(255, 255, 255)
    Sheets("Pre-shift").Range("G" & iCnt_fr + iCnt_im + 3).Interior.Color = RGB(0, 0, 0)
    Sheets("Pre-shift").Range("G" & iCnt_fr + iCnt_im + 3).Font.Color = RGB(255, 255, 255)

    ' CLOSE THE SOURCE FILE.
    src_im.Close False             ' FALSE - DON'T SAVE THE SOURCE FILE.
    Set src_im = Nothing
    src_fr.Close False             ' FALSE - DON'T SAVE THE SOURCE FILE.
    Set src_fr = Nothing
    src_chm.Close False             ' FALSE - DON'T SAVE THE SOURCE FILE.
    Set src_chm = Nothing

ErrHandler:
    Application.EnableEvents = True
    Application.ScreenUpdating = True
End Sub

Body:
This will correctly evaluate your time values.  Can't you just not COPY DATA FROM SOURCE (CLOSE WORKGROUP) TO THE DESTINATION WORKBOOK?

For it to be today's date, just check that too

If TimeValue(src_im.Worksheets("incident_sla").Range("G" & iCnt_im).Value) > TimeValue("13:59:59") And TimeValue(src_im.Worksheets("incident_sla").Range("G" & iCnt_im).Value) < TimeValue("22:00:01")  and Int(src_im.Worksheets("incident_sla").Range("G" & iCnt_im).Value) = Date Then