问:
Display All Table Rows that are Checked
I have a multiple column table with one column being checkboxes. If you check a checkbox then press the "Checkout" button, it will take the specified rows and display them in the body of an email.

I originally bring in the top 100 rows to keep the info light for the user. I also have a search functionality where the user can search for specific rows. While you can maneuver throughout different searches and still keep all of the checkboxes checked with session storage, when you hit "Checkout" it only displays the table rows that are checked and currently visible on the page. So, if I searched for a table row and checked it, but then went back to the original top 100 rows by clicking home, then that row would not display on the email.

How can I fix this and show ALL rows that have been checked, whether they are visible on the page or not?

HTML:

```<code><section id="checkout-btn">
<button id="checkout" name="order" onclick="sendMail(); return false">Checkout</button>
</section>

<br>

<table id="merchTable" cellspacing="5" class="sortable">
    <thead>
        <tr class="ui-widget-header">
            <th class="sorttable_nosort"></th>
            <th class="sorttable_nosort">Loc</th>
            <th class="merchRow">Report Code</th>
            <th class="merchRow">SKU</th>
            <th class="merchRow">Special ID</th>
            <th class="merchRow">Description</th>
            <th class="merchRow">Quantity</th>
            <th class="sorttable_nosort">Unit</th>
            <th style="display: none;" class="num">Quantity #</th>
        </tr>
    </thead>
    <tbody>

        <?php foreach ($dbh->query($query) as $row) {?>

        <tr>
            <td class="ui-widget-content"><input type="checkbox" class="check" name="check" id="checkid-<?php echo intval ($row['ID'])?>"></td>
            <td class="loc ui-widget-content" data-loc="<?php echo $row['Loc'] ?>"><input type="hidden"><?php echo $row['Loc'];?></td>
            <td class="rp-code ui-widget-content" align="center" data-rp-code="<?php echo $row['Rp-Code'] ?>" id="rp-code-<?php echo intval ($row['Rp-Code'])?>"><?php echo $row['Rp-Code'];?></td>
            <td class="sku ui-widget-content" data-sku="<?php echo $row['SKU'] ?>" id="sku-<?php echo intval ($row['SKU'])?>"><?php echo $row['SKU'];?></td>
            <td class="special-id ui-widget-content" data-special-id="<?php echo $row['Special-ID'] ?>" align="center" id="special-id-<?php echo intval ($row['Special-ID'])?>"><?php echo $row['Special-ID'];?></td>
            <td class="description ui-widget-content" data-description="<?php echo htmlspecialchars($row['Description']) ?>" id="description-<?php echo intval ($row['Description'])?>"><?php echo $row['Description'];?></td>
            <td class="quantity ui-widget-content" data-quantity="<?php echo $row['Quantity'] ?>" align="center" id="quantity-<?php echo intval ($row['Quantity'])?>"><?php echo $row['Quantity'];?></td>
            <td class="unit ui-widget-content" data-unit="<?php echo $row['Unit'] ?>" id="unit-<?php echo intval ($row['Unit'])?>"><?php echo $row['Unit'];?></td>
            <td style="display: none;" class="quantity_num ui-widget-content"><input type="textbox" style="width: 100px;" class="spinner" id="spin-<?php echo intval ($row['ID'])?>"></td>
        </tr>

    <?php } ?>

    </tbody>
</table>
</code>```

JavaScript for keeping checked checkboxes, checked, throughout the session:

```<code>$(function(){
    $(':checkbox').each(function() {
        var $el = $(this);
        $el.prop('checked', sessionStorage[$el.prop('id')] === 'true');
    });

    $('input:checkbox').on('change', function() {
        var $el = $(this);
        sessionStorage[$el.prop('id')] = $el.is(':checked');
    });
});
</code>```

JavaScript that brings in data from table to email:

```<code>function sendMail() {
    var link = "mailto:me@example.com"
             + "?subject=" + encodeURIComponent("Order")
             + "&body=";

    var body = '';

  $('table tr input[name="check"]:checked').each(function(){
    var current_tr = $(this).parent().parent();

    var data = current_tr.find('.loc').data('loc');
    body +=  encodeURIComponent(data) + '\xa0\xa0';

    var data =current_tr.find('.rp-code').data('rp-code');
    body +=  encodeURIComponent(data) + '\xa0\xa0';

    var data =current_tr.find('.sku').data('sku');
    body +=  encodeURIComponent(data) + '\xa0\xa0';

    var data =current_tr.find('.special-id').data('special-id');
    body +=  encodeURIComponent(data) + '\xa0\xa0';

    var data =current_tr.find('.description').data('description');
    body +=  encodeURIComponent(data) + '\xa0\xa0';

    var data =current_tr.find('.quantity').data('quantity');
    body +=  encodeURIComponent(data) + '\xa0\xa0';

    var data =current_tr.find('.unit').data('unit');
    body +=  encodeURIComponent(data) + '\xa0\xa0';

    var data =current_tr.find('.spinner').data('spinner');
    body +=  encodeURIComponent(data) + '\xa0\xa0';

    body += '%0D%0A';

  });

  body += '';
  link += body;
  console.log(link);

  window.location.href = link;
}
</code>```

答:
Revised based your comments/new code:

Even with your new pasted code, the issue still remains that you can only output whats currently available on screen due looping over the table rows. Instead you need to take it a step further and build objects to house the information you need for building your email, then place those objects in storage for later retrieval.

Again looking at your code your checkboxes have a prefix of "check-id".

```<code>$('input:checkbox').on('change', function() {
    var $el = $(this);
    var key = $el.prop('id');
    var rowObject = {};

    //check if already in storage
    if(sessionStorage.getItem(key) !== null){
     rowObject = JSON.parse(sessionStorage.getItem(key));
     rowObject.checkedVal = $el.is(':checked'); //update it's check value
    }else{
     //build entire row object
     var current_tr = $(this).parent().parent();

     rowObject.loc = current_tr.find('.loc').data('loc');
     rowObject.rpCode = current_tr.find('.loc').data('rp-code');
     rowObject.sku = current_tr.find('.loc').data('sku');
     //etc. as many pieces as you need
    }

    //set to session
    sessionStorage.setItem(key, JSON.stringify(rowObject));

});

//then later for your send email method
function sendEmail(){
  var link = "mailto:me@example.com"
            + "?subject=" + encodeURIComponent("Order")
            + "&body=";

   var body = '';

  //loop over the row objects instead
  $.each(sessionStorage, function(key, value){
    //sort out the ones we want
    if(key.indexOf("checkid-") > -1){
      var rowObject = JSON.parse(sessionStorage.getItem(key));
      body +=  encodeURIComponent(rowObject.loc + '\xa0\xa0');
      body +=  encodeURIComponent(rowObject.rpCode + '\xa0\xa0');
      body +=  encodeURIComponent(rowObject.sku + '\xa0\xa0');
      //etc. as many pieces as you need

      body += '%0D%0A';
    }
  });

  //whatever other logic you have
}
</code>```

I haven't fully tested this code for your purposes but you get the idea, build your objects then use those during your iteration.

Title: Display All Table Rows that are Checked

Body:
I have a multiple column table with one column being checkboxes. If you check a checkbox then press the "Checkout" button, it will take the specified rows and display them in the body of an email.

I originally bring in the top 100 rows to keep the info light for the user. I also have a search functionality where the user can search for specific rows. While you can maneuver throughout different searches and still keep all of the checkboxes checked with session storage, when you hit "Checkout" it only displays the table rows that are checked and currently visible on the page. So, if I searched for a table row and checked it, but then went back to the original top 100 rows by clicking home, then that row would not display on the email.

How can I fix this and show ALL rows that have been checked, whether they are visible on the page or not?

HTML:

<button id="checkout" name="order" onclick="sendMail(); return false">Checkout</button>

            Loc
            Report Code
            SKU
            Special ID
            Description
            Quantity
            Unit
            Quantity #

        <?php foreach ($dbh->query($query) as $row) {?>

            <input type="checkbox" class="check" name="check" id="checkid-<?php echo intval ($row['ID'])?>">
            <td class="loc ui-widget-content" data-loc="<?php echo $row['Loc'] ?>"><input type="hidden"><?php echo $row['Loc'];?>
            <td class="rp-code ui-widget-content" align="center" data-rp-code="<?php echo $row['Rp-Code'] ?>" id="rp-code-<?php echo intval ($row['Rp-Code'])?>"><?php echo $row['Rp-Code'];?>
            <td class="sku ui-widget-content" data-sku="<?php echo $row['SKU'] ?>" id="sku-<?php echo intval ($row['SKU'])?>"><?php echo $row['SKU'];?>
            <td class="special-id ui-widget-content" data-special-id="<?php echo $row['Special-ID'] ?>" align="center" id="special-id-<?php echo intval ($row['Special-ID'])?>"><?php echo $row['Special-ID'];?>
            <td class="description ui-widget-content" data-description="<?php echo htmlspecialchars($row['Description']) ?>" id="description-<?php echo intval ($row['Description'])?>"><?php echo $row['Description'];?>
            <td class="quantity ui-widget-content" data-quantity="<?php echo $row['Quantity'] ?>" align="center" id="quantity-<?php echo intval ($row['Quantity'])?>"><?php echo $row['Quantity'];?>
            <td class="unit ui-widget-content" data-unit="<?php echo $row['Unit'] ?>" id="unit-<?php echo intval ($row['Unit'])?>"><?php echo $row['Unit'];?>
            <input type="textbox" style="width: 100px;" class="spinner" id="spin-<?php echo intval ($row['ID'])?>">

    <?php } ?>

JavaScript for keeping checked checkboxes, checked, throughout the session:

$(function(){
    $(':checkbox').each(function() {
        var $el = $(this);
        $el.prop('checked', sessionStorage[$el.prop('id')] === 'true');
    });

    $('input:checkbox').on('change', function() {
        var $el = $(this);
        sessionStorage[$el.prop('id')] = $el.is(':checked');
    });
});

JavaScript that brings in data from table to email:

function sendMail() {
    var link = "mailto:me@example.com"
             + "?subject=" + encodeURIComponent("Order")
             + "&body=";

    var body = '';

  $('table tr input[name="check"]:checked').each(function(){
    var current_tr = $(this).parent().parent();

    var data = current_tr.find('.loc').data('loc');
    body +=  encodeURIComponent(data) + '\xa0\xa0';

    var data =current_tr.find('.rp-code').data('rp-code');
    body +=  encodeURIComponent(data) + '\xa0\xa0';

    var data =current_tr.find('.sku').data('sku');
    body +=  encodeURIComponent(data) + '\xa0\xa0';

    var data =current_tr.find('.special-id').data('special-id');
    body +=  encodeURIComponent(data) + '\xa0\xa0';

    var data =current_tr.find('.description').data('description');
    body +=  encodeURIComponent(data) + '\xa0\xa0';

    var data =current_tr.find('.quantity').data('quantity');
    body +=  encodeURIComponent(data) + '\xa0\xa0';

    var data =current_tr.find('.unit').data('unit');
    body +=  encodeURIComponent(data) + '\xa0\xa0';

    var data =current_tr.find('.spinner').data('spinner');
    body +=  encodeURIComponent(data) + '\xa0\xa0';

    body += '%0D%0A';

  });

  body += '';
  link += body;
  console.log(link);

  window.location.href = link;
}

Body:
Revised based your comments/new code:

Even with your new pasted code, the issue still remains that you can only output whats currently available on screen due looping over the table rows. Instead you need to take it a step further and build objects to house the information you need for building your email, then place those objects in storage for later retrieval.

Again looking at your code your checkboxes have a prefix of "check-id".

$('input:checkbox').on('change', function() {
    var $el = $(this);
    var key = $el.prop('id');
    var rowObject = {};

    //check if already in storage
    if(sessionStorage.getItem(key) !== null){
     rowObject = JSON.parse(sessionStorage.getItem(key));
     rowObject.checkedVal = $el.is(':checked'); //update it's check value
    }else{
     //build entire row object
     var current_tr = $(this).parent().parent();

     rowObject.loc = current_tr.find('.loc').data('loc');
     rowObject.rpCode = current_tr.find('.loc').data('rp-code');
     rowObject.sku = current_tr.find('.loc').data('sku');
     //etc. as many pieces as you need
    }

    //set to session
    sessionStorage.setItem(key, JSON.stringify(rowObject));

});

//then later for your send email method
function sendEmail(){
  var link = "mailto:me@example.com"
            + "?subject=" + encodeURIComponent("Order")
            + "&body=";

   var body = '';

  //loop over the row objects instead
  $.each(sessionStorage, function(key, value){
    //sort out the ones we want
    if(key.indexOf("checkid-") > -1){
      var rowObject = JSON.parse(sessionStorage.getItem(key));
      body +=  encodeURIComponent(rowObject.loc + '\xa0\xa0');
      body +=  encodeURIComponent(rowObject.rpCode + '\xa0\xa0');
      body +=  encodeURIComponent(rowObject.sku + '\xa0\xa0');
      //etc. as many pieces as you need

      body += '%0D%0A';
    }
  });

  //whatever other logic you have
}

I haven't fully tested this code for your purposes but you get the idea, build your objects then use those during your iteration.


来源: stackexchange

问:
How do I read CPU "stats" in Java from an Android phone?
I am trying to figure out the CPU usage by core, perhaps the temp if possible, and in general figure out what I can read from the CPU.

I have done some searching, and I have some code that returns the number of cores (see How can you detect a dual-core cpu on an Android device from code?).  Now I am trying to figure out how to use that to get the CPU usage by core from this link (Get Memory Usage in Android).

The only problem is I'm kinda new to Java/Android, so I'm having trouble understanding what the commenters are trying to say.  One comment says that you should change the delimiters on idle1 and cpu1...do I do the same for idle2 and cpu2?  Any help would be appreciated, so thank you in advance!

Ok so now I have a way better understanding of what I'm doing, but cores 2-4 on my 4 core test board are all reading 0.  On occasion, when I start the app, core 2 has a value > 0, but upon subsequent runs (the app updates values once per second) it returns to 0.  Here is the code I currently have, thank you so much!!!

```<code>    public double readUsage(int corenum) {
    int j=0;
    int coreVal = getNumCores();
    String[] toks;
    long idle1;
    long cpu1;
    long idle2;
    long cpu2;

    try {
            RandomAccessFile reader = new RandomAccessFile("/proc/stat", "r");
            String load = reader.readLine();
            reader.seek(0);
            while (j <= corenum){
                load = reader.readLine();
                j++;
            }
            j=0;
            toks = load.split(" ");

            if (corenum == 0) {
                idle1 = Long.parseLong(toks[5]);
                cpu1 = Long.parseLong(toks[2]) + Long.parseLong(toks[3]) + Long.parseLong(toks[4])
                      + Long.parseLong(toks[6]) + Long.parseLong(toks[7]) + Long.parseLong(toks[8]);
            }

            else {
                idle1 = Long.parseLong(toks[4]);
                cpu1 = Long.parseLong(toks[1]) + Long.parseLong(toks[2]) + Long.parseLong(toks[3])
                        + Long.parseLong(toks[5]) + Long.parseLong(toks[6]) + Long.parseLong(toks[7]);
            }

            try {
                 Thread.sleep(100);
            } catch (Exception e) {}

            reader.seek(0);
            while (j <= corenum){
                load = reader.readLine();
                j++;
            }
            j=0;
            reader.close();
            toks = load.split(" ");

            if (corenum == 0) {
                idle2 = Long.parseLong(toks[5]);
                cpu2 = Long.parseLong(toks[2]) + Long.parseLong(toks[3]) + Long.parseLong(toks[4])
                      + Long.parseLong(toks[6]) + Long.parseLong(toks[7]) + Long.parseLong(toks[8]);
            }

            else {
                idle2 = Long.parseLong(toks[4]);
                cpu2 = Long.parseLong(toks[1]) + Long.parseLong(toks[2]) + Long.parseLong(toks[3])
                        + Long.parseLong(toks[5]) + Long.parseLong(toks[6]) + Long.parseLong(toks[7]);
            }

           return (double)(cpu2 - cpu1) / ((cpu2 + idle2) - (cpu1 + idle1));

    } catch (IOException ex) {
        ex.printStackTrace();
    }

    return 9999999;
}
</code>```

答:
Despite that the answer seems to be valid, I have created a small parser to help the people to extract the information of "proc/stat". The documentation can be found here.

```<code>public class Cpu {
private String name = "";
private long cpu_user = 0;
private long cpu_niced = 0;
private long cpu_system = 0;
private long cpu_idle = 0;
private long cpu_iowait = 0;
private long cpu_irq = 0;
private long cpu_softirqs = 0;

public Cpu(String name, long cpu_user, long cpu_niced, long cpu_system, long cpu_idle, long cpu_iowait, long cpu_irq, long cpu_softirqs) {
    this.name = name;
    this.cpu_user = cpu_user;
    this.cpu_niced = cpu_niced;
    this.cpu_system = cpu_system;
    this.cpu_idle = cpu_idle;
    this.cpu_iowait = cpu_iowait;
    this.cpu_irq = cpu_irq;
    this.cpu_softirqs = cpu_softirqs;
}

public long getCpuUser() {
    return cpu_user;
}

public long getCpuNiced() {
    return cpu_niced;
}

public long getCpuSystem() {
    return cpu_system;
}

public long getCpuIdle() {
    return cpu_idle;
}

public long getCpuIowait() {
    return cpu_iowait;
}

public long getCpuIrq() {
    return cpu_irq;
}

public long getCpuSoftirqs() {
    return cpu_softirqs;
}

public double getAverageIdlePercentage(){
    return ( cpu_idle * 100 ) / ( cpu_user + cpu_niced + cpu_system + cpu_idle + cpu_iowait + cpu_irq + cpu_softirqs );
}

public String getName() {
    return name;
}

public String toString(){
    String temp ="";
    temp+= name+ " ";
    temp+= cpu_user+ " ";
    temp+= cpu_niced+ " ";
    temp+= cpu_system+ " ";
    temp+= cpu_idle+ " ";
    temp+= cpu_iowait+ " ";
    temp+= cpu_irq+ " ";
    temp+= cpu_softirqs+ " ";
    return temp;
}
}

public class StatFile {

/**
 * The very first line "cpu" aggregates the numbers in all of the other "cpuN" lines.
 * These numbers identify the amount of time the CPU has spent performing different kinds of work. Time units are in USER_HZ or Jiffies (typically hundredths of a second).
 */
private List<Cpu> cpus;
/**
 * Counts of interrupts serviced since boot time, for each of the possible system interrupts. The first column is the total of all interrupts serviced; each subsequent column is the total for that particular interrupt.
 */
private List<Long> interruptions;
/**
 * The total number of context switches across all CPUs.
 */
private long ctxt = 0;

/**
 * The time at which the system booted
 */
private Date btime;

/**
 * The number of processes and threads created, which includes (but is not limited to) those created by calls to the fork() and clone() system calls.
 */
private long processes = 0;

/**
 *  The number of processes currently running on CPUs
 */
private long procs_running = 0;

/**
 * The number of processes currently blocked, waiting for I/O to complete
 */
private long procs_blocked = 0;

private List<Long> softirq;

public StatFile(){
    cpus = new ArrayList<Cpu>();
    interruptions = new ArrayList<Long>();
    ctxt = 0;
    btime = new Date();
    processes = 0;
    procs_running = 0;
    procs_blocked = 0;
    softirq = new ArrayList<Long>();
}

public List<Cpu> getCpus() {
    return cpus;
}

public void setCpus(List<Cpu> cpus) {
    this.cpus = cpus;
}

public List<Long> getInterruptions() {
    return interruptions;
}

public void setInterruptions(List<Long> interruptions) {
    this.interruptions = interruptions;
}

public long getCtxt() {
    return ctxt;
}

public void setCtxt(long ctxt) {
    this.ctxt = ctxt;
}

public Date getBtime() {
    return btime;
}

public void setBtime(Date btime) {
    this.btime = btime;
}

public long getProcesses() {
    return processes;
}

public void setProcesses(long processes) {
    this.processes = processes;
}

public long getProcs_running() {
    return procs_running;
}

public void setProcs_running(long procs_running) {
    this.procs_running = procs_running;
}

public long getProcs_blocked() {
    return procs_blocked;
}

public void setProcs_blocked(long procs_blocked) {
    this.procs_blocked = procs_blocked;
}

public List<Long> getSoftirq() {
    return softirq;
}

public void setSoftirq(List<Long> softirq) {
    this.softirq = softirq;
}
}
</code>```

CpuUtils class:

```<code>public class CpuUtils {

 private static final String TAG = CpuUtils.class.getSimpleName();

 /**
 * Normal processes executing in user mode
 */
private static final int CPU_USER=1;
/**
 * Niced processes executing in user mode
 */
private static final int CPU_NICE=2;
/**
 * Processes executing in kernel mode
 */
private static final int CPU_SYSTEM=3;
/**
 * Twiddling thumbs
 */
private static final int CPU_IDLE=4;
/**
 * Waiting for I/O to complete
 */
private static final int CPU_IOWAIT=5;
/**
 * Servicing interrupts
 */
private static final int CPU_IRQ=6;
/**
 * Servicing softirqs
 */
private static final int CPU_SOFTIRQS=7;

public static StatFile parseStatsFile() {
    StatFile statFile = new StatFile();
    try {
        RandomAccessFile reader = new RandomAccessFile("/proc/stat", "r");
        try {
            while (true) {
                String load = reader.readLine();
                //Avoid problem parsing doble space
                if(load!=null) {
                    Log.d(TAG, "Stat: " + load);
                    load = load.replace("  ", " ");
                    String[] tokens = load.split(" ");
                    if (tokens[0].startsWith("cpu")) {
                        Cpu cpu = parseCpuTokens(tokens);
                        statFile.getCpus().add(cpu);
                    }
                    else if(tokens[0].startsWith("intr")){
                        for(int i=1; i<tokens.length; i++){
                            statFile.getInterruptions().add(Long.parseLong(tokens[i]));
                        }
                    }
                    else if(tokens[0].startsWith("ctxt")){
                        statFile.setCtxt(Long.parseLong(tokens[1]));
                    }
                    else if(tokens[0].startsWith("btime")){
                        //time is in seconds, therefore we need it in milliseconds
                        statFile.setBtime(new Date(Long.parseLong(tokens[1])*1000));
                    }
                    else if(tokens[0].startsWith("processes")){
                        statFile.setProcesses(Long.parseLong(tokens[1]));
                    }
                    else if(tokens[0].startsWith("procs_running")){
                        statFile.setProcs_running(Long.parseLong(tokens[1]));
                    }
                    else if(tokens[0].startsWith("procs_blocked")){
                        statFile.setProcs_blocked(Long.parseLong(tokens[1]));
                    }
                    else if(tokens[0].startsWith("softirq")){
                        for(int i=1; i<tokens.length; i++){
                            statFile.getSoftirq().add(Long.parseLong(tokens[i]));
                        }
                    }
                }
                else{
                    throw new EOFException("File end reached");
                }
            }
        } catch (EOFException ex) {

        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                reader.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }catch (FileNotFoundException e){
        e.printStackTrace();
        throw new IllegalStateException("Unable to access the stats");
    }

    return statFile;
}

private static Cpu parseCpuTokens(String[] tokens){
    Cpu cpu = new Cpu(tokens[0],
            Long.parseLong(tokens[CPU_USER]),
            Long.parseLong(tokens[CPU_NICE]),
            Long.parseLong(tokens[CPU_SYSTEM]),
            Long.parseLong(tokens[CPU_IDLE]),
            Long.parseLong(tokens[CPU_IOWAIT]),
            Long.parseLong(tokens[CPU_IRQ]),
            Long.parseLong(tokens[CPU_SOFTIRQS]));
    return cpu;
}
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I am trying to figure out the CPU usage by core, perhaps the temp if possible, and in general figure out what I can read from the CPU.

I have done some searching, and I have some code that returns the number of cores (see How can you detect a dual-core cpu on an Android device from code?).  Now I am trying to figure out how to use that to get the CPU usage by core from this link (Get Memory Usage in Android).

The only problem is I'm kinda new to Java/Android, so I'm having trouble understanding what the commenters are trying to say.  One comment says that you should change the delimiters on idle1 and cpu1...do I do the same for idle2 and cpu2?  Any help would be appreciated, so thank you in advance!

Ok so now I have a way better understanding of what I'm doing, but cores 2-4 on my 4 core test board are all reading 0.  On occasion, when I start the app, core 2 has a value > 0, but upon subsequent runs (the app updates values once per second) it returns to 0.  Here is the code I currently have, thank you so much!!!

    public double readUsage(int corenum) {
    int j=0;
    int coreVal = getNumCores();
    String[] toks;
    long idle1;
    long cpu1;
    long idle2;
    long cpu2;

    try {
            RandomAccessFile reader = new RandomAccessFile("/proc/stat", "r");
            String load = reader.readLine();
            reader.seek(0);
            while (j <= corenum){
                load = reader.readLine();
                j++;
            }
            j=0;
            toks = load.split(" ");

            if (corenum == 0) {
                idle1 = Long.parseLong(toks[5]);
                cpu1 = Long.parseLong(toks[2]) + Long.parseLong(toks[3]) + Long.parseLong(toks[4])
                      + Long.parseLong(toks[6]) + Long.parseLong(toks[7]) + Long.parseLong(toks[8]);
            }

            else {
                idle1 = Long.parseLong(toks[4]);
                cpu1 = Long.parseLong(toks[1]) + Long.parseLong(toks[2]) + Long.parseLong(toks[3])
                        + Long.parseLong(toks[5]) + Long.parseLong(toks[6]) + Long.parseLong(toks[7]);
            }

            try {
                 Thread.sleep(100);
            } catch (Exception e) {}

            reader.seek(0);
            while (j <= corenum){
                load = reader.readLine();
                j++;
            }
            j=0;
            reader.close();
            toks = load.split(" ");

            if (corenum == 0) {
                idle2 = Long.parseLong(toks[5]);
                cpu2 = Long.parseLong(toks[2]) + Long.parseLong(toks[3]) + Long.parseLong(toks[4])
                      + Long.parseLong(toks[6]) + Long.parseLong(toks[7]) + Long.parseLong(toks[8]);
            }

            else {
                idle2 = Long.parseLong(toks[4]);
                cpu2 = Long.parseLong(toks[1]) + Long.parseLong(toks[2]) + Long.parseLong(toks[3])
                        + Long.parseLong(toks[5]) + Long.parseLong(toks[6]) + Long.parseLong(toks[7]);
            }

           return (double)(cpu2 - cpu1) / ((cpu2 + idle2) - (cpu1 + idle1));

    } catch (IOException ex) {
        ex.printStackTrace();
    }

    return 9999999;
}

Body:
Despite that the answer seems to be valid, I have created a small parser to help the people to extract the information of "proc/stat". The documentation can be found here.

public class Cpu {
private String name = "";
private long cpu_user = 0;
private long cpu_niced = 0;
private long cpu_system = 0;
private long cpu_idle = 0;
private long cpu_iowait = 0;
private long cpu_irq = 0;
private long cpu_softirqs = 0;

public Cpu(String name, long cpu_user, long cpu_niced, long cpu_system, long cpu_idle, long cpu_iowait, long cpu_irq, long cpu_softirqs) {
    this.name = name;
    this.cpu_user = cpu_user;
    this.cpu_niced = cpu_niced;
    this.cpu_system = cpu_system;
    this.cpu_idle = cpu_idle;
    this.cpu_iowait = cpu_iowait;
    this.cpu_irq = cpu_irq;
    this.cpu_softirqs = cpu_softirqs;
}

public long getCpuUser() {
    return cpu_user;
}

public long getCpuNiced() {
    return cpu_niced;
}

public long getCpuSystem() {
    return cpu_system;
}

public long getCpuIdle() {
    return cpu_idle;
}

public long getCpuIowait() {
    return cpu_iowait;
}

public long getCpuIrq() {
    return cpu_irq;
}

public long getCpuSoftirqs() {
    return cpu_softirqs;
}

public double getAverageIdlePercentage(){
    return ( cpu_idle * 100 ) / ( cpu_user + cpu_niced + cpu_system + cpu_idle + cpu_iowait + cpu_irq + cpu_softirqs );
}

public String getName() {
    return name;
}

public String toString(){
    String temp ="";
    temp+= name+ " ";
    temp+= cpu_user+ " ";
    temp+= cpu_niced+ " ";
    temp+= cpu_system+ " ";
    temp+= cpu_idle+ " ";
    temp+= cpu_iowait+ " ";
    temp+= cpu_irq+ " ";
    temp+= cpu_softirqs+ " ";
    return temp;
}
}

public class StatFile {

/**
 * The very first line "cpu" aggregates the numbers in all of the other "cpuN" lines.
 * These numbers identify the amount of time the CPU has spent performing different kinds of work. Time units are in USER_HZ or Jiffies (typically hundredths of a second).
 */
private List<Cpu> cpus;
/**
 * Counts of interrupts serviced since boot time, for each of the possible system interrupts. The first column is the total of all interrupts serviced; each subsequent column is the total for that particular interrupt.
 */
private List<Long> interruptions;
/**
 * The total number of context switches across all CPUs.
 */
private long ctxt = 0;

/**
 * The time at which the system booted
 */
private Date btime;

/**
 * The number of processes and threads created, which includes (but is not limited to) those created by calls to the fork() and clone() system calls.
 */
private long processes = 0;

/**
 *  The number of processes currently running on CPUs
 */
private long procs_running = 0;

/**
 * The number of processes currently blocked, waiting for I/O to complete
 */
private long procs_blocked = 0;

private List<Long> softirq;

public StatFile(){
    cpus = new ArrayList<Cpu>();
    interruptions = new ArrayList<Long>();
    ctxt = 0;
    btime = new Date();
    processes = 0;
    procs_running = 0;
    procs_blocked = 0;
    softirq = new ArrayList<Long>();
}

public List<Cpu> getCpus() {
    return cpus;
}

public void setCpus(List<Cpu> cpus) {
    this.cpus = cpus;
}

public List<Long> getInterruptions() {
    return interruptions;
}

public void setInterruptions(List<Long> interruptions) {
    this.interruptions = interruptions;
}

public long getCtxt() {
    return ctxt;
}

public void setCtxt(long ctxt) {
    this.ctxt = ctxt;
}

public Date getBtime() {
    return btime;
}

public void setBtime(Date btime) {
    this.btime = btime;
}

public long getProcesses() {
    return processes;
}

public void setProcesses(long processes) {
    this.processes = processes;
}

public long getProcs_running() {
    return procs_running;
}

public void setProcs_running(long procs_running) {
    this.procs_running = procs_running;
}

public long getProcs_blocked() {
    return procs_blocked;
}

public void setProcs_blocked(long procs_blocked) {
    this.procs_blocked = procs_blocked;
}

public List<Long> getSoftirq() {
    return softirq;
}

public void setSoftirq(List<Long> softirq) {
    this.softirq = softirq;
}
}

CpuUtils class:

public class CpuUtils {

 private static final String TAG = CpuUtils.class.getSimpleName();

 /**
 * Normal processes executing in user mode
 */
private static final int CPU_USER=1;
/**
 * Niced processes executing in user mode
 */
private static final int CPU_NICE=2;
/**
 * Processes executing in kernel mode
 */
private static final int CPU_SYSTEM=3;
/**
 * Twiddling thumbs
 */
private static final int CPU_IDLE=4;
/**
 * Waiting for I/O to complete
 */
private static final int CPU_IOWAIT=5;
/**
 * Servicing interrupts
 */
private static final int CPU_IRQ=6;
/**
 * Servicing softirqs
 */
private static final int CPU_SOFTIRQS=7;

public static StatFile parseStatsFile() {
    StatFile statFile = new StatFile();
    try {
        RandomAccessFile reader = new RandomAccessFile("/proc/stat", "r");
        try {
            while (true) {
                String load = reader.readLine();
                //Avoid problem parsing doble space
                if(load!=null) {
                    Log.d(TAG, "Stat: " + load);
                    load = load.replace("  ", " ");
                    String[] tokens = load.split(" ");
                    if (tokens[0].startsWith("cpu")) {
                        Cpu cpu = parseCpuTokens(tokens);
                        statFile.getCpus().add(cpu);
                    }
                    else if(tokens[0].startsWith("intr")){
                        for(int i=1; i<tokens.length; i++){
                            statFile.getInterruptions().add(Long.parseLong(tokens[i]));
                        }
                    }
                    else if(tokens[0].startsWith("ctxt")){
                        statFile.setCtxt(Long.parseLong(tokens[1]));
                    }
                    else if(tokens[0].startsWith("btime")){
                        //time is in seconds, therefore we need it in milliseconds
                        statFile.setBtime(new Date(Long.parseLong(tokens[1])*1000));
                    }
                    else if(tokens[0].startsWith("processes")){
                        statFile.setProcesses(Long.parseLong(tokens[1]));
                    }
                    else if(tokens[0].startsWith("procs_running")){
                        statFile.setProcs_running(Long.parseLong(tokens[1]));
                    }
                    else if(tokens[0].startsWith("procs_blocked")){
                        statFile.setProcs_blocked(Long.parseLong(tokens[1]));
                    }
                    else if(tokens[0].startsWith("softirq")){
                        for(int i=1; i<tokens.length; i++){
                            statFile.getSoftirq().add(Long.parseLong(tokens[i]));
                        }
                    }
                }
                else{
                    throw new EOFException("File end reached");
                }
            }
        } catch (EOFException ex) {

        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                reader.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }catch (FileNotFoundException e){
        e.printStackTrace();
        throw new IllegalStateException("Unable to access the stats");
    }

    return statFile;
}

private static Cpu parseCpuTokens(String[] tokens){
    Cpu cpu = new Cpu(tokens[0],
            Long.parseLong(tokens[CPU_USER]),
            Long.parseLong(tokens[CPU_NICE]),
            Long.parseLong(tokens[CPU_SYSTEM]),
            Long.parseLong(tokens[CPU_IDLE]),
            Long.parseLong(tokens[CPU_IOWAIT]),
            Long.parseLong(tokens[CPU_IRQ]),
            Long.parseLong(tokens[CPU_SOFTIRQS]));
    return cpu;
}
}


问:
A web app with logins in a kiosk situation
We are looking at setting up an internal web application (ASP.NET MVC) as a kiosk for the employees that don't have a dedicated computer. We currently do not have this kiosk setup. Each employee will have their own login to look at some basic payroll information and request leaves of absence. This same web application will be used by the office workers with a dedicated PC at their desk.

I am going to go out on a limb and say that no matter how many times we tell the employees, the employees will not click log off when they walk away from the kiosk. What would you do to help prevent this from happening?

答:
The naive solution would be to enforce a timeout. If there's no activity from the user within a certain time limit (say, a minute or so), log them out. Of course, this won't prevent someone from walking up immediately after an employee is done and seeing how much money they make.

ATMs handle this, I think, by timing out after a minute or two, which isn't super-secure but at least offers some minimal security.

If the employees have any kind of RFID card or other security token, you could require them to put it in a reader slot, and log them out whenever the card disappears. Handling this within a web app, though, could get complicated.

ContentLicense: CC BY-SA 2.5


问:
How can I require a buyer's phone number with Paypal Express Checkout?
I'm working on Express Checkout integration, and have everything working without any technical problems. The only issue is that we need to have the buyer's phone number.

The GetExpressCheckoutDetails Documentation states that...

PayPal returns a contact phone number only if your Merchant Account
  Profile settings require that the buyer enter one.

A comment by PayPal_Robert on this question, made in late November of 2013 (So fairly recent) states...

You can require a phone number to be entered for guest checkout users.
  This is available via Profile > My selling tools > Payment receiving preferences > Contact > phone number > Require a phone number to be entered.

However, I don't see "Payment receiving preferences" available in my organization's Merchant Profile. (Screenshot)

Where is the option to require a buyer's contact phone number?

答: If anyone is still having trouble getting the phone number: even after I made the prefs change suggested above I couldn't see it in the payment response, but it IS available via a request to /v1/payments/payment/PAYMENT_ID via the REST API. Payer-PayerInfo->Phone.</p>


问:
Textview still visible even if listview gets an item
I have an imageview, 2 textviews that needs to appear when the listview is empty. I want the 2nd textview to be clickable
as well. Here is my code -

```<code><ImageView
        android:id="@android:id/empty"
        android:layout_width="120sp"
        android:layout_height="130sp"
        android:layout_gravity="center"
        android:gravity="center"
        android:src="@drawable/flower" />

    <TextView
        android:id="@android:id/empty"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:gravity="center"
        android:paddingTop="120sp"
        android:text="Warning" />

    <TextView
        android:id="@android:id/empty"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:gravity="center"
        android:paddingTop="200sp"
        android:text="Click Me" />
</code>```

The image view disappears when the list view gets an item but the text views are still visible.
How can I make these 2 textviews disappear when the list view gets an item? Also how can I make my second text view clickable?

答:
You can easily make them invisible. In your activity do this when you add an item to the list:

```<code>TextView tvXY = (TextView) findViewById(R.id.[TheIdHere]);
tvXY.setVisibility(View.GONE);
</code>```

In your xml file you will have to change the id of the textviews too. Choose different ids for both of them. You can change the id by editing this:

```<code>@android:id/empty
</code>```

To something like this.

```<code>@+id/[TheIdHere]
</code>```

Body:
I have an imageview, 2 textviews that needs to appear when the listview is empty. I want the 2nd textview to be clickable
as well. Here is my code -

<ImageView
        android:id="@android:id/empty"
        android:layout_width="120sp"
        android:layout_height="130sp"
        android:layout_gravity="center"
        android:gravity="center"
        android:src="@drawable/flower" />

    <TextView
        android:id="@android:id/empty"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:gravity="center"
        android:paddingTop="120sp"
        android:text="Warning" />

    <TextView
        android:id="@android:id/empty"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:gravity="center"
        android:paddingTop="200sp"
        android:text="Click Me" />

The image view disappears when the list view gets an item but the text views are still visible.
How can I make these 2 textviews disappear when the list view gets an item? Also how can I make my second text view clickable?

Body:
You can easily make them invisible. In your activity do this when you add an item to the list:

TextView tvXY = (TextView) findViewById(R.id.[TheIdHere]);
tvXY.setVisibility(View.GONE);

In your xml file you will have to change the id of the textviews too. Choose different ids for both of them. You can change the id by editing this:

@android:id/empty

To something like this.

@+id/[TheIdHere]


问:
"Cannot use table in schema '' for entity since it is being used for another entity" error
We are trying to map the ASPNetUsers table to our custom table users. Below are the classes and their relationship.

```<code>public partial class Users
{
    public int Id { get; set; }
    public string FirstName { get; set; }
    public string MiddleName { get; set; }
    public string LastName { get; set; }
    public string UserInfoId { get; set; }
    public virtual AspNetUsers UserInfo { get; set; }
}

public class ApplicationUser : IdentityUser
{
    public virtual Users Users { get; set; }
}
</code>```

When we are implementing the identity using these models, we get the         below error:

"Cannot use table 'AspNetUsers' in schema '' for entity 'AspNetUsers' since it is being used for another entity."

We have not done any changes in the ASPNetUsers tables; it is same as we got through the migration.

How can we fix this?

答:
In your ApplicationDbContext you have to customize the AspNetUsers table:

```<code>protected override void OnModelCreating(ModelBuilder builder)
{
    base.OnModelCreating(builder);
    new AspNetUsersConfiguration(builder.Entity<AspNetUsers>());
}
</code>```

And in your Configuration file:

```<code>public class AspNetUsersConfiguration
{
    public AspNetUsersConfiguration(EntityTypeBuilder<AspNetUsers> entity)
    {
     entity.ToTable("AspNetUsers", "dbo");
     entity.HasKey(e => e.Id);
    }
}
</code>```

The key answer is in define a schema dbo to table AspNetUsers.

Body:
We are trying to map the ASPNetUsers table to our custom table users. Below are the classes and their relationship.

public partial class Users
{
    public int Id { get; set; }
    public string FirstName { get; set; }
    public string MiddleName { get; set; }
    public string LastName { get; set; }
    public string UserInfoId { get; set; }
    public virtual AspNetUsers UserInfo { get; set; }
}

public class ApplicationUser : IdentityUser
{
    public virtual Users Users { get; set; }
}

When we are implementing the identity using these models, we get the         below error:

"Cannot use table 'AspNetUsers' in schema '' for entity 'AspNetUsers' since it is being used for another entity."

We have not done any changes in the ASPNetUsers tables; it is same as we got through the migration.

How can we fix this?

Body:
In your ApplicationDbContext you have to customize the AspNetUsers table:

protected override void OnModelCreating(ModelBuilder builder)
{
    base.OnModelCreating(builder);
    new AspNetUsersConfiguration(builder.Entity<AspNetUsers>());
}

And in your Configuration file:

public class AspNetUsersConfiguration
{
    public AspNetUsersConfiguration(EntityTypeBuilder<AspNetUsers> entity)
    {
     entity.ToTable("AspNetUsers", "dbo");
     entity.HasKey(e => e.Id);
    }
}

The key answer is in define a schema dbo to table AspNetUsers.

ContentLicense: CC BY-SA 4.0


问:
Left justification of nomenclature description in LaTeX
I'm using a LaTeX template (provided by ASME) to write a conference paper.
The asme2e.cls class defines a "nomenclature" environment as follows:

```<code>% Nomenclature environment
\newbox\tempbox
\newenvironment{nomenclature}{%
   \newcommand\entry[2]{%
       \setbox\tempbox\hbox{##1.\quad}
       \hangindent\wd\tempbox\noindent{##1}\quad\ignorespaces##2\par}
       \section*{NOMENCLATURE}}{\par\addvspace{12pt}}
</code>```

which is used, in the .tex source file, as follows:

```<code>\begin{nomenclature}
% [...]
    \entry{$C_{visc}$}{Viscous friction coefficient.}
    \entry{$M$}{Spool mass.}
% [...]
\end{nomenclature}
</code>```

resulting in the description texts not being left justified (since a fixed horizontal space is inserted between the symbol (e.g.: M) and the description (e.g.: Spool mass.), but the symbols have different lengths (e.g.: Cvisc is longer than M).

Is there a way to fix the class to have left-justified descriptions?
(I did a few experiments with \dimexpr and the calc package, but just got a bunch of errors).

(I also asked ASME if they could provide an updated template, but I'm still waiting for their feedback...)

答:
I couldn't solve the problem, but I found a "quick and dirty" workaround, using the Tabbing and setspace packages.
Here is the new .tex source:

```<code>%[...]

\usepackage{Tabbing}
\usepackage{setspace}

%[...]

\begin{nomenclature}
{\setstretch{1.1}
\begin{tabbing}
\noindent
% [...]
    \entry{$C_{visc}$}\quad\quad\={Viscous friction coefficient.}\\
    \entry{$M$}\>{Spool mass.}\\
    \entry{$v$}\>{Spool velocity.}\\
% [...]
\end{tabbing}
}    % end \setstretch
\end{nomenclature}

%[...]
</code>```

(Clearly, I'm completely bypassing the \entry command defined by the asme2e.cls class for the nomenclature environment).

Body:
I'm using a LaTeX template (provided by ASME) to write a conference paper.
The asme2e.cls class defines a "nomenclature" environment as follows:

% Nomenclature environment
\newbox\tempbox
\newenvironment{nomenclature}{%
   \newcommand\entry[2]{%
       \setbox\tempbox\hbox{##1.\quad}
       \hangindent\wd\tempbox\noindent{##1}\quad\ignorespaces##2\par}
       \section*{NOMENCLATURE}}{\par\addvspace{12pt}}

which is used, in the .tex source file, as follows:

\begin{nomenclature}
% [...]
    \entry{$C_{visc}$}{Viscous friction coefficient.}
    \entry{$M$}{Spool mass.}
% [...]
\end{nomenclature}

resulting in the description texts not being left justified (since a fixed horizontal space is inserted between the symbol (e.g.: M) and the description (e.g.: Spool mass.), but the symbols have different lengths (e.g.: Cvisc is longer than M).

Is there a way to fix the class to have left-justified descriptions?
(I did a few experiments with \dimexpr and the calc package, but just got a bunch of errors).

(I also asked ASME if they could provide an updated template, but I'm still waiting for their feedback...)

Body:
I couldn't solve the problem, but I found a "quick and dirty" workaround, using the Tabbing and setspace packages.
Here is the new .tex source:

%[...]

\usepackage{Tabbing}
\usepackage{setspace}

%[...]

\begin{nomenclature}
{\setstretch{1.1}
\begin{tabbing}
\noindent
% [...]
    \entry{$C_{visc}$}\quad\quad\={Viscous friction coefficient.}\\
    \entry{$M$}\>{Spool mass.}\\
    \entry{$v$}\>{Spool velocity.}\\
% [...]
\end{tabbing}
}    % end \setstretch
\end{nomenclature}

%[...]

(Clearly, I'm completely bypassing the \entry command defined by the asme2e.cls class for the nomenclature environment).


问:
Trying to implement something similar to jQuery
I'm trying to implement something similar to jQuery.

Basically, whenever I'd be doing something with DOM elements, I'd like to use a wrapper object's methods instead of manipulating the DOM directly.

This is what I have so far

HTML:

```<code><a href='#!'></a>
</code>```

JS:

```<code>var dd = function(selector)
{
    return new dd.prototype.constructor(selector);
}
dd.prototype =
{
    constructor: function(selector)
    {
        var nodes = document.querySelectorAll(selector);

        for(var i = 0; i < nodes.length; i++)
            this[i] = nodes[i];

        this.length = nodes.length;
        return Array.prototype.slice.call(this);
    },
    addClass: function(cl)
    {
        alert('a');
    }
};

var a = dd('[href="#!"]');
a.addClass('asd');
</code>```

The problems:

I get an error in the browser console saying that a.addClass is
not a function

dd('a') instanceof dd === false while $('a') instanceof $ === true, so I know that my logic is somehow wrong here.

Sadly, I don't quite get what I'm doing wrong.

答:
While reinventing the wheel isn't a good Idea,
what follows should help you.

Consider that jQuery supports custom builds,
so, first of all, have a look here https://github.com/jquery/jquery#how-to-build-your-own-jquery.

var dd = (function() {
  function dd(selector) {
    // class call check
    if(!(this instanceof dd)) {
      return new dd(selector);
    }

    Array
      .from(document.querySelectorAll(selector), (el, i) => {
        this[i] = el;
      })
    ;

    Object
      .defineProperty(this, 'length', {
        get: () => Object.keys(this).length
      })
    ;
  }

  dd.prototype.forEach = function(cb) {
    Object
      .keys(this)
      .forEach(i => {
        cb(this[i], i)
      })
    ;

    return this;
  }

  dd.prototype.addClass = function() {
    this.forEach(el => el.classList.add(...Array.from(arguments)));

    return this;
  }

  dd.prototype.removeClass = function() {
    this.forEach(el => el.classList.remove(...Array.from(arguments)));

    return this;
  }

  return dd;
})();

var odd = dd('strong');
var even = dd('span');

window.setTimeout(() => odd.addClass('foo'), 2000);
window.setTimeout(() => even.addClass('baz'), 3000);

console.log('odd', odd.length);
console.log('even', even.length);```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.cntr strong,
.cntr span {
  display: inline-flex;
  width: 20px;
  height: 20px;
  transition: 250ms all linear;
  margin: 2px;
  border: 1px solid cyan;
  background: lightseagreen;
}

.cntr .foo { background: yellow; }
.cntr .baz { background: orange; }</code>```

```

Body:
I'm trying to implement something similar to jQuery.

Basically, whenever I'd be doing something with DOM elements, I'd like to use a wrapper object's methods instead of manipulating the DOM directly.

This is what I have so far

HTML:

JS:

var dd = function(selector)
{
    return new dd.prototype.constructor(selector);
}
dd.prototype =
{
    constructor: function(selector)
    {
        var nodes = document.querySelectorAll(selector);

        for(var i = 0; i < nodes.length; i++)
            this[i] = nodes[i];

        this.length = nodes.length;
        return Array.prototype.slice.call(this);
    },
    addClass: function(cl)
    {
        alert('a');
    }
};

var a = dd('[href="#!"]');
a.addClass('asd');

The problems:

I get an error in the browser console saying that a.addClass is
not a function

dd('a') instanceof dd === false while $('a') instanceof $ === true, so I know that my logic is somehow wrong here.

Sadly, I don't quite get what I'm doing wrong.

Body:
While reinventing the wheel isn't a good Idea,
what follows should help you.

Consider that jQuery supports custom builds,
so, first of all, have a look here https://github.com/jquery/jquery#how-to-build-your-own-jquery.

var dd = (function() {
  function dd(selector) {
    // class call check
    if(!(this instanceof dd)) {
      return new dd(selector);
    }

    Array
      .from(document.querySelectorAll(selector), (el, i) => {
        this[i] = el;
      })
    ;

    Object
      .defineProperty(this, 'length', {
        get: () => Object.keys(this).length
      })
    ;
  }

  dd.prototype.forEach = function(cb) {
    Object
      .keys(this)
      .forEach(i => {
        cb(this[i], i)
      })
    ;

    return this;
  }

  dd.prototype.addClass = function() {
    this.forEach(el => el.classList.add(...Array.from(arguments)));

    return this;
  }

  dd.prototype.removeClass = function() {
    this.forEach(el => el.classList.remove(...Array.from(arguments)));

    return this;
  }

  return dd;
})();

var odd = dd('strong');
var even = dd('span');

window.setTimeout(() => odd.addClass('foo'), 2000);
window.setTimeout(() => even.addClass('baz'), 3000);

console.log('odd', odd.length);
console.log('even', even.length);

.cntr strong,
.cntr span {
  display: inline-flex;
  width: 20px;
  height: 20px;
  transition: 250ms all linear;
  margin: 2px;
  border: 1px solid cyan;
  background: lightseagreen;
}

.cntr .foo { background: yellow; }
.cntr .baz { background: orange; }

<section class="cntr">
 <strong></strong><span></span><strong></strong><span></span><strong></strong><span></span><strong></strong><span></span><strong></strong><span></span><strong></strong><span></span><strong></strong><span></span><strong></strong><span></span><strong></strong><span></span><strong></strong><span></span><strong></strong><span></span><strong></strong><span></span><strong></strong><span></span><strong></strong><span></span><strong></strong><span></span><strong></strong><span></span><strong></strong><span></span><strong></strong><span></span><strong></strong><span></span><strong></strong><span></span><strong></strong><span></span><strong></strong><span></span><strong></strong><span></span><strong></strong><span></span><strong></strong><span></span><strong></strong><span></span><strong></strong><span></span><strong></strong><span></span><strong></strong><span></span><strong></strong><span></span><strong></strong><span></span><strong></strong><span></span><strong></strong><span></span><strong></strong><span></span><strong></strong><span></span><strong></strong><span></span><strong></strong><span></span><strong></strong><span></span><strong></strong><span></span><strong></strong><span></span><strong></strong><span></span><strong></strong><span></span><strong></strong><span></span><strong></strong><span></span><strong></strong><span></span><strong></strong><span></span><strong></strong><span></span><strong></strong><span></span><strong></strong><span></span><strong></strong><span></span><strong></strong><span></span><strong></strong><span></span><strong></strong><span></span><strong></strong><span></span><strong></strong><span></span><strong></strong><span></span><strong></strong><span></span><strong></strong><span></span><strong></strong><span></span><strong></strong><span></span><strong></strong><span></span><strong></strong><span></span><strong></strong><span></span><strong></strong><span></span><strong></strong><span></span><strong></strong><span></span><strong></strong><span></span><strong></strong><span></span><strong></strong><span></span><strong></strong><span></span><strong></strong><span></span><strong></strong><span></span><strong></strong><span></span><strong></strong><span></span><strong></strong><span></span><strong></strong><span></span><strong></strong><span></span><strong></strong><span></span><strong></strong><span></span><strong></strong><span></span><strong></strong><span></span><strong></strong><span></span><strong></strong><span></span><strong></strong><span></span><strong></strong><span></span><strong></strong><span></span><strong></strong><span></span><strong></strong><span></span><strong></strong><span></span><strong></strong><span></span><strong></strong><span></span><strong></strong><span></span><strong></strong><span></span><strong></strong><span></span><strong></strong><span></span><strong></strong><span></span><strong></strong><span></span><strong></strong><span></span><strong></strong><span></span><strong></strong><span></span>
</section>


问:
Including third-party libraries in C applications
I'm a bit naive when it comes to application development in C. I've been writing a lot of code for a programming language I'm working on and I want to include stuff from ICU (for internationalization and unicode support).

The problem is, I'm just not sure if there are any conventions for including a third party library. for something like readline where lots of systems are probably going to have it installed already, it's safe to just link to it (I think). But what about if I wanted to include a version of the library in my own code? Is this common or am I thinking about this all wrong?

答:
It depends on the OS you're targeting.  For Linux and Unix system, you will typically see dynamic linking, so the application will use the library that is already installed on the system.  If you do this, that means it's up to the user to obtain the library if they don't already have it.  Package managers in Linux will do this for you if you package your application in the distro's package format.

On Windows you typically see static linking, which means the application bundles the library and it will use that specific version.  many different applications may use the same library but include their own version.  So you can have many copies of the library floating around on your system.


问:
How to use Life-ray 7 search engine API's with Elastic search?
We are developing a search engine application in Life Ray 7 and Elastic-Search(2.2). I’ve gone through the official documentation of Life-ray 7 API’ for elastic search but it only describes some classes we need to use and very confusing. We are not using elastic search native API and Transport client.

How to connect to EL from Life-ray? (We have gone through this official link  )

How to use life-ray 7 API for indexing and searching in Elastic search?( The official doc only mentions some classes for doing this. We can't find a doc to see how to use them, even Javadoc contains nothing)

I really appreciate if someone can provide us a link to a proper tutorial or an example of how to index a document (for ex: a profile object) in Elastic search on localhost.

We are completely new to the Liferay and elastic search, pardon me for any mistake. Also, we know how to develop the above logics using Native API of elastic search and Java Transport Client.

答:
```<code>How to connect to EL from Life-ray?
</code>```

This link describes the step-by-step process required to setup Liferay with Elastic search.

```<code>How to use life-ray 7 API for indexing and searching in Elastic search?
</code>```

The API's for search/indexing in Liferay 7.0 hasn't changed much. So, I would suggest referring to this link.

I personally haven't implemented Elastic Search in the past as I have used only GSA in my experience. However, I'm pretty sure this documentation is sufficient to get started.

Body:
How to connect to EL from Life-ray?

This link describes the step-by-step process required to setup Liferay with Elastic search.

How to use life-ray 7 API for indexing and searching in Elastic search?

The API's for search/indexing in Liferay 7.0 hasn't changed much. So, I would suggest referring to this link.

I personally haven't implemented Elastic Search in the past as I have used only GSA in my experience. However, I'm pretty sure this documentation is sufficient to get started.


问:
What LibGDX viewport can stretch to a given size?
I am trying to set up some smaller viewports for different stages inside my main viewport which is a StretchedViewport. So far, I have been doing it with ScalingViewports, with the scaling set to none, but today I tested it on a different device and I noticed the viewport's size did not stretch to the size relative to my main one's. To give you better image of how they are set up here is the code I am using.

```<code>viewport = new StretchViewport(720, 1280, cam);//the main viewport
viewport.apply();
cam.position.set(cam.viewportWidth / 2, cam.viewportHeight / 2,0);
secondaryViewport = new ScalingViewport(Scaling.none, 480, 675);//the smaller ones sized relative to the main one
coinInsertionViewport = new ScalingViewport(Scaling.none, 200, 69);
</code>```

What viewport can stretch to a given size relative to the StretchViewport's? StretchViewport stretches to whole screen, so it won't help me.

答:
If you want to restrict drawing area to a part of the screen the use setScreenBounds() method of the viewport.

This will only allow you to draw in the left half of the screen

```<code>viewport.setScreenBounds(0, 0, Gdx.graphics.getWidth() / 2, Gdx.graphics.getHeight());
</code>```

Body:
I am trying to set up some smaller viewports for different stages inside my main viewport which is a StretchedViewport. So far, I have been doing it with ScalingViewports, with the scaling set to none, but today I tested it on a different device and I noticed the viewport's size did not stretch to the size relative to my main one's. To give you better image of how they are set up here is the code I am using.

viewport = new StretchViewport(720, 1280, cam);//the main viewport
viewport.apply();
cam.position.set(cam.viewportWidth / 2, cam.viewportHeight / 2,0);
secondaryViewport = new ScalingViewport(Scaling.none, 480, 675);//the smaller ones sized relative to the main one
coinInsertionViewport = new ScalingViewport(Scaling.none, 200, 69);

What viewport can stretch to a given size relative to the StretchViewport's? StretchViewport stretches to whole screen, so it won't help me.

Body:
If you want to restrict drawing area to a part of the screen the use setScreenBounds() method of the viewport.

This will only allow you to draw in the left half of the screen

viewport.setScreenBounds(0, 0, Gdx.graphics.getWidth() / 2, Gdx.graphics.getHeight());


问:
Google Apps Script: How to remove empty Gmail labels?
With Google Apps Script, is it possible to remove empty (unused) Gmail labels?</p>

答:
Based on the answers above, here is a Google Apps Script to delete empty labels (with nested labels check). The Javascript is rough, but it works! The 'testing' variable determines if it just logs or actually deletes the labels.

You can debug, run Google Apps Scripts at https://script.google.com

```<code>//
// Set to 'false' if you want to actually delete labels
// otherwise it will log them but not delete them.
//
var testing = true;

//
// Deletes labels with no email threads
//
function deleteEmptyLabels() {

    Logger.log("Starting label cleanup");

    var allLabels = GmailApp.getUserLabels();

    var emptyLabels = allLabels.filter(function(label){ return isTreeEmpty(label, allLabels); } );

    for (var i = 0; i < emptyLabels.length; i++){

        Logger.log('Deleting empty label ' + emptyLabels[i].getName());

        if (!testing){
            emptyLabels[i].deleteLabel();
        }
    }

    Logger.log("Finished label cleanup");
}

//
// Finds labels below a parent
//
function getNestedLabels(parent, allLabels) {
    var name = parent.getName() + '/';
    return allLabels.filter(function(label) {
        return label.getName().slice(0, name.length) == name;
    });
}

//
// Tests a single label for 'emptiness'
//
function isLabelEmpty(label){
    return label.getThreads(0, 1) == 0;
}

//
// Tests a label, and nested labels for 'emptiness'
//
function isTreeEmpty(label, allLabels){

    if (!isLabelEmpty(label))
        return false;

    var nested = getNestedLabels(label, allLabels);

    for(var j = 0; j < nested.length; j++){
        if (!isTreeEmpty(nested[j], allLabels))
            return false;
        }

    return true;
}
</code>```

Body:
Based on the answers above, here is a Google Apps Script to delete empty labels (with nested labels check). The Javascript is rough, but it works! The 'testing' variable determines if it just logs or actually deletes the labels.

You can debug, run Google Apps Scripts at https://script.google.com

//
// Set to 'false' if you want to actually delete labels
// otherwise it will log them but not delete them.
//
var testing = true;

//
// Deletes labels with no email threads
//
function deleteEmptyLabels() {

    Logger.log("Starting label cleanup");

    var allLabels = GmailApp.getUserLabels();

    var emptyLabels = allLabels.filter(function(label){ return isTreeEmpty(label, allLabels); } );

    for (var i = 0; i < emptyLabels.length; i++){

        Logger.log('Deleting empty label ' + emptyLabels[i].getName());

        if (!testing){
            emptyLabels[i].deleteLabel();
        }
    }

    Logger.log("Finished label cleanup");
}

//
// Finds labels below a parent
//
function getNestedLabels(parent, allLabels) {
    var name = parent.getName() + '/';
    return allLabels.filter(function(label) {
        return label.getName().slice(0, name.length) == name;
    });
}

//
// Tests a single label for 'emptiness'
//
function isLabelEmpty(label){
    return label.getThreads(0, 1) == 0;
}

//
// Tests a label, and nested labels for 'emptiness'
//
function isTreeEmpty(label, allLabels){

    if (!isLabelEmpty(label))
        return false;

    var nested = getNestedLabels(label, allLabels);

    for(var j = 0; j < nested.length; j++){
        if (!isTreeEmpty(nested[j], allLabels))
            return false;
        }

    return true;
}


问:
Low-level caching with Django
Instead of caching the whole site, or whole views, I've decided to cache only a few heavy queries, using the low level caching API.

I'm doing something like this

```<code>key = ...
value = cache.get(key)
if value is None:
    value = ...
    cache.set(key, value, CACHE_TIMEOUT)
</code>```

It works almost as expected (question 01: is there a better way to do it?),

but if I set CACHE_TIMEOUT to a big value (86400: the db is updated once a day),
it looks that CACHE_TIMEOUT is being overrided by something else, and the value is cached just for a few minutes...

(question 02:) What am I doing wrong?

Is my timeout too long?
Or maybe I'm caching too much information? (value contains ~ 500-1000 objects, and it's evaluated in 50-60 different pages/keys)

答: Some cache servers (e.g. memcached) are lossy, and newer items will force older items out of the cache. Monitor your cache statistics and modify your configuration and/or behavior appropriately.</p>

Title: Low-level caching with Django

Body:
Instead of caching the whole site, or whole views, I've decided to cache only a few heavy queries, using the low level caching API.

I'm doing something like this

key = ...
value = cache.get(key)
if value is None:
    value = ...
    cache.set(key, value, CACHE_TIMEOUT)

It works almost as expected (question 01: is there a better way to do it?),

but if I set CACHE_TIMEOUT to a big value (86400: the db is updated once a day),
it looks that CACHE_TIMEOUT is being overrided by something else, and the value is cached just for a few minutes...

(question 02:) What am I doing wrong?

Is my timeout too long?
Or maybe I'm caching too much information? (value contains ~ 500-1000 objects, and it's evaluated in 50-60 different pages/keys)


问:
Why am I getting an error when I try to print the contents of a file I am searching for?
Can you help me with searching for and printing a file specified by text in textbox1? I have the following code but textbox1 shows me an error. I don't know if the code is correctly written and functioning right.

First class:

```<code>Public Class tisk
    'print
    Public Shared Function printers()
        Dim printThis
        Dim strDir As String
        Dim strFile As String
        Dim Textbox1 As String

        strDir = "C:\_Montix a.s. - cloud\iMontix\Testy"
        strFile = "C:\_Montix a.s. - cloud\iMontix\Testy\" & Textbox1.text & ".lbe"

        If Not fileexprint.FileExists Then
            MsgBox("Soubor neexistuje")
            printers = False
        Else

            fileprint.PrintThisfile()
            printers = True

        End If
    End Function

End Class
</code>```

Second class:

```<code>Public Class fileprint
    Public Shared Function PrintThisfile()
        Dim formname As Long
        Dim FileName As String

        On Error Resume Next
        Dim X As Long
        X = Shell(formname, "Print", FileName, 0&)
    End Function
End Class
</code>```

Third class:

```<code>Public Class fileexprint
    Public Shared Function FileExists()
        Dim fname As Boolean
        '   Returns TRUE if the file exists
        Dim X As String
        X = Dir(fname)
        If X <> "" Then FileExists = True _
        Else FileExists = False
    End Function
End Class
</code>```

When I fill a textbox with text, how can I search for a file in the computer using this text and print this file?

答: Your "Textbox1" is a variable and not actually getting the value from a textbox. If I'm not wrong, I believe you intend to get the value of a textbox and concatenate to form your directory url. You'll first need to add a text box to your windows/web form, give that textbox an id then call that id in your code behind. E.g. You add a text box with id "textbox001", in your code behind you'll do something like "textbox001.text". In your case it'll now be: strFile = "C:_Montix a.s. - cloud\iMontix\Testy\" & textbox001.text & ".lbe". Hope this helps.</p>

Body:
Can you help me with searching for and printing a file specified by text in textbox1? I have the following code but textbox1 shows me an error. I don't know if the code is correctly written and functioning right.

First class:

Public Class tisk
    'print
    Public Shared Function printers()
        Dim printThis
        Dim strDir As String
        Dim strFile As String
        Dim Textbox1 As String

        strDir = "C:\_Montix a.s. - cloud\iMontix\Testy"
        strFile = "C:\_Montix a.s. - cloud\iMontix\Testy\" & Textbox1.text & ".lbe"

        If Not fileexprint.FileExists Then
            MsgBox("Soubor neexistuje")
            printers = False
        Else

            fileprint.PrintThisfile()
            printers = True

        End If
    End Function

End Class

Second class:

Public Class fileprint
    Public Shared Function PrintThisfile()
        Dim formname As Long
        Dim FileName As String

        On Error Resume Next
        Dim X As Long
        X = Shell(formname, "Print", FileName, 0&)
    End Function
End Class

Third class:

Public Class fileexprint
    Public Shared Function FileExists()
        Dim fname As Boolean
        '   Returns TRUE if the file exists
        Dim X As String
        X = Dir(fname)
        If X <> "" Then FileExists = True _
        Else FileExists = False
    End Function
End Class

When I fill a textbox with text, how can I search for a file in the computer using this text and print this file?


问:
Python Pandas Columns variables
Now my code is reading csv files. I have to do the next steps: if CP3 and CP4 have values then it's false if don't it's true and finally i need to keep values but i want it to return in boolean, if it's filled or not.

```<code>df1 = pd.read_csv("JonnyTheBoy10.csv", usecols=['ART_TIPO', 'ART_DESIG', 'PORTA', 'CP4', 'CP3', 'LOCALIDADE'])

df1.isnull().any()

CP4 = df1["CP4"]  # boolean
CP3 = df1["CP3"]  # boolean

for line in df1.iterrows():
    for row in df2.iterrows():

        if CP4 and CP3 is False:
</code>```

Example:

```<code>CSV file = CP4, CP3
           3455, 543  CP4 and CP3 is False
           6473, null CP4 is False and CP3 is True
</code>```

答:
This gave you the result you want, you're free to store it wherever you find it appropriate:

```<code>res = ~(df1["CP4"] & df1["CP3"])
</code>```

The "~" operator inverse the "&" (and) operator.

Title: Python Pandas Columns variables

Body:
Now my code is reading csv files. I have to do the next steps: if CP3 and CP4 have values then it's false if don't it's true and finally i need to keep values but i want it to return in boolean, if it's filled or not.

df1 = pd.read_csv("JonnyTheBoy10.csv", usecols=['ART_TIPO', 'ART_DESIG', 'PORTA', 'CP4', 'CP3', 'LOCALIDADE'])

df1.isnull().any()

CP4 = df1["CP4"]  # boolean
CP3 = df1["CP3"]  # boolean

for line in df1.iterrows():
    for row in df2.iterrows():

        if CP4 and CP3 is False:

Example:

CSV file = CP4, CP3
           3455, 543  CP4 and CP3 is False
           6473, null CP4 is False and CP3 is True

Body:
This gave you the result you want, you're free to store it wherever you find it appropriate:

res = ~(df1["CP4"] & df1["CP3"])

The "~" operator inverse the "&" (and) operator.


问:
Find frequency of vector elements in a matrix
I have a matrix in R, here is a small example:

```<code>set.seed(1)
n.columns<-6
mat <- matrix(, nrow = 5, ncol = n.columns)
for(column in 1:n.columns){
  mat[, column] <- sample(1:10,5)
}
mat
</code>```

The matrix looks like this:

```<code>     [,1] [,2] [,3] [,4] [,5] [,6]
[1,]    3    9    3    5   10    4
[2,]    4   10    2    7    2    1
[3,]    5    6    6    8    6   10
[4,]    7    5   10    3    1    7
[5,]    2    1    5   10    9    3
</code>```

I also have a vector v of integers, v<-c(1,3,6), whose elements could theoretically appear in the matrix mat above.

What I am looking for is an overview of the number of times that each element in v appears in mat per column. For the current example this overview is

```<code>1: 0 1 0 0 1 1
3: 1 0 1 1 0 1
6: 0 1 1 0 1 0
</code>```

It is fairly straightforward to do this using for-loops and if-statements, but this solution is not very pretty.

Is there a professional way to do this?

答:
Using sapply on data.frame iterates over columns.

```<code>setNames(object = as.data.frame(sapply(v, function(a)
         sapply(as.data.frame(mat), function(b)
                             sum(a %in% b)))), nm = v)
#   1 3 6
#V1 0 1 0
#V2 1 0 1
#V3 0 1 1
#V4 0 1 0
#V5 1 0 1
#V6 1 1 0
</code>```

Body:
I have a matrix in R, here is a small example:

set.seed(1)
n.columns<-6
mat <- matrix(, nrow = 5, ncol = n.columns)
for(column in 1:n.columns){
  mat[, column] <- sample(1:10,5)
}
mat

The matrix looks like this:

     [,1] [,2] [,3] [,4] [,5] [,6]
[1,]    3    9    3    5   10    4
[2,]    4   10    2    7    2    1
[3,]    5    6    6    8    6   10
[4,]    7    5   10    3    1    7
[5,]    2    1    5   10    9    3

I also have a vector v of integers, v<-c(1,3,6), whose elements could theoretically appear in the matrix mat above.

What I am looking for is an overview of the number of times that each element in v appears in mat per column. For the current example this overview is

1: 0 1 0 0 1 1
3: 1 0 1 1 0 1
6: 0 1 1 0 1 0

It is fairly straightforward to do this using for-loops and if-statements, but this solution is not very pretty.

Is there a professional way to do this?

Body:
Using sapply on data.frame iterates over columns.

setNames(object = as.data.frame(sapply(v, function(a)
         sapply(as.data.frame(mat), function(b)
                             sum(a %in% b)))), nm = v)
#   1 3 6
#V1 0 1 0
#V2 1 0 1
#V3 0 1 1
#V4 0 1 0
#V5 1 0 1
#V6 1 1 0


问:
Swap two blocks of text programatically
I have an XML file made up of multiple blocks that are very similar. Here are two:

```<code>    <Grid Name="EMFieldMany" GridType="Uniform">
        <Topology TopologyType="3DRectMesh" Dimensions="40 40 40 "/>
        <Attribute AttributeType="Scalar" Name="Er" Center="Node">
            <DataItem Dimensions="40 40 40 " NumberType="Float" Precision="8" Format="HDF5" Endian="Big">
                Field_reflected_time_3D.hdf5:/field/Er-0
            </DataItem>
        </Attribute>
        <Geometry GeometryType="VXVYVZ">
            <DataItem Name="r" Dimensions="40" NumberType="Float" Precision="8" Format="HDF5" Endian="Big">
                Field_reflected_time_3D.hdf5:/coordinates/r
            </DataItem>
            <DataItem Name="theta" Dimensions="40" NumberType="Float" Precision="8" Format="HDF5" Endian="Big">
                Field_reflected_time_3D.hdf5:/coordinates/theta
            </DataItem>
            <DataItem Name="z" Dimensions="40" NumberType="Float" Precision="8" Format="HDF5" Endian="Big">
                Field_reflected_time_3D.hdf5:/coordinates/z
            </DataItem>
        </Geometry>
    </Grid>
    <Grid Name="EMFieldMany" GridType="Uniform">
        <Topology TopologyType="3DRectMesh" Dimensions="40 40 40 "/>
        <Attribute AttributeType="Scalar" Name="Er" Center="Node">
            <DataItem Dimensions="40 40 40 " NumberType="Float" Precision="8" Format="HDF5" Endian="Big">
                Field_reflected_time_3D.hdf5:/field/Er-1
            </DataItem>
        </Attribute>
        <Geometry GeometryType="VXVYVZ">
            <DataItem Name="r" Dimensions="40" NumberType="Float" Precision="8" Format="HDF5" Endian="Big">
                Field_reflected_time_3D.hdf5:/coordinates/r
            </DataItem>
            <DataItem Name="theta" Dimensions="40" NumberType="Float" Precision="8" Format="HDF5" Endian="Big">
                Field_reflected_time_3D.hdf5:/coordinates/theta
            </DataItem>
            <DataItem Name="z" Dimensions="40" NumberType="Float" Precision="8" Format="HDF5" Endian="Big">
                Field_reflected_time_3D.hdf5:/coordinates/z
            </DataItem>
        </Geometry>
    </Grid>
</code>```

Typically I have hundreds of similar <Grid> objects in a single file. Now, I want to programatically swap the positions of the <DataItem Name="r"> and <DataItem Name="z"> blocks in each <Grid> object such that the <DataItem>s are in the order z, theta, r. Also, for each Dimensions=" x y z " statement, each Dimensions attribute that contains three values, I want the attribute to be rewritten as Dimensions=" z y x ".

I don't really mind the programming language being used to do this. I'm on a Linux workstation with bash, python, perl... all the standard stuff.

EDIT: This answer uses sed to match blocks of text, but I'm not sure how to manipulate the selected block afterwards. This other answer swaps single lines up and down, but I'm not sure how to generalize to blocks of text, and to make it swap blocks.

答:
As you mention sed, I suggest this perl solution however it's better parsing xml with xml parser.

```<code>#!/usr/bin/perl

# changing input line separator
$/="</Grid>";

while ( $_=<> ) {
    s@(\s*<DataItem Name="r".*?</DataItem>)(\s*<DataItem Name="theta".*?</DataItem>)(\s*<DataItem Name="z".*?</DataItem>)@$3$2$1@s;
    s@<DataItem Dimensions="\K(\d+) (\d+) (\d+) @$3 $2 $1 @;
    print;
}
</code>```

Or the one-liner equivalent

```<code>perl -pe 'BEGIN{$/="</Grid>"}s@(\s*<DataItem Name="r".*?</DataItem>)(\s*<DataItem Name="theta".*?</DataItem>)(\s*<DataItem Name="z".*?</DataItem>)@$3$2$1@s;s@<DataItem Dimensions="\K(\d+) (\d+) (\d+) @$3 $2 $1 @;' <input.txt
</code>```

Title: Swap two blocks of text programatically

Body:
I have an XML file made up of multiple blocks that are very similar. Here are two:

    <Grid Name="EMFieldMany" GridType="Uniform">
        <Topology TopologyType="3DRectMesh" Dimensions="40 40 40 "/>
        <Attribute AttributeType="Scalar" Name="Er" Center="Node">
            <DataItem Dimensions="40 40 40 " NumberType="Float" Precision="8" Format="HDF5" Endian="Big">
                Field_reflected_time_3D.hdf5:/field/Er-0
            </DataItem>
        </Attribute>
        <Geometry GeometryType="VXVYVZ">
            <DataItem Name="r" Dimensions="40" NumberType="Float" Precision="8" Format="HDF5" Endian="Big">
                Field_reflected_time_3D.hdf5:/coordinates/r
            </DataItem>
            <DataItem Name="theta" Dimensions="40" NumberType="Float" Precision="8" Format="HDF5" Endian="Big">
                Field_reflected_time_3D.hdf5:/coordinates/theta
            </DataItem>
            <DataItem Name="z" Dimensions="40" NumberType="Float" Precision="8" Format="HDF5" Endian="Big">
                Field_reflected_time_3D.hdf5:/coordinates/z
            </DataItem>
        </Geometry>
    </Grid>
    <Grid Name="EMFieldMany" GridType="Uniform">
        <Topology TopologyType="3DRectMesh" Dimensions="40 40 40 "/>
        <Attribute AttributeType="Scalar" Name="Er" Center="Node">
            <DataItem Dimensions="40 40 40 " NumberType="Float" Precision="8" Format="HDF5" Endian="Big">
                Field_reflected_time_3D.hdf5:/field/Er-1
            </DataItem>
        </Attribute>
        <Geometry GeometryType="VXVYVZ">
            <DataItem Name="r" Dimensions="40" NumberType="Float" Precision="8" Format="HDF5" Endian="Big">
                Field_reflected_time_3D.hdf5:/coordinates/r
            </DataItem>
            <DataItem Name="theta" Dimensions="40" NumberType="Float" Precision="8" Format="HDF5" Endian="Big">
                Field_reflected_time_3D.hdf5:/coordinates/theta
            </DataItem>
            <DataItem Name="z" Dimensions="40" NumberType="Float" Precision="8" Format="HDF5" Endian="Big">
                Field_reflected_time_3D.hdf5:/coordinates/z
            </DataItem>
        </Geometry>
    </Grid>

Typically I have hundreds of similar <Grid> objects in a single file. Now, I want to programatically swap the positions of the <DataItem Name="r"> and <DataItem Name="z"> blocks in each <Grid> object such that the <DataItem>s are in the order z, theta, r. Also, for each Dimensions=" x y z " statement, each Dimensions attribute that contains three values, I want the attribute to be rewritten as Dimensions=" z y x ".

I don't really mind the programming language being used to do this. I'm on a Linux workstation with bash, python, perl... all the standard stuff.

EDIT: This answer uses sed to match blocks of text, but I'm not sure how to manipulate the selected block afterwards. This other answer swaps single lines up and down, but I'm not sure how to generalize to blocks of text, and to make it swap blocks.

Body:
As you mention sed, I suggest this perl solution however it's better parsing xml with xml parser.

#!/usr/bin/perl

# changing input line separator
$/="</Grid>";

while ( $_=<> ) {
    s@(\s*<DataItem Name="r".*?</DataItem>)(\s*<DataItem Name="theta".*?</DataItem>)(\s*<DataItem Name="z".*?</DataItem>)@$3$2$1@s;
    s@<DataItem Dimensions="\K(\d+) (\d+) (\d+) @$3 $2 $1 @;
    print;
}

Or the one-liner equivalent

perl -pe 'BEGIN{$/="</Grid>"}s@(\s*<DataItem Name="r".*?</DataItem>)(\s*<DataItem Name="theta".*?</DataItem>)(\s*<DataItem Name="z".*?</DataItem>)@$3$2$1@s;s@<DataItem Dimensions="\K(\d+) (\d+) (\d+) @$3 $2 $1 @;' <input.txt


问:
How do I open phone settings when a button is clicked?
I am trying to implement a feature in an App that shows an alert when the internet connection is not available.
The alert has two actions (OK and Settings), whenever a user clicks on settings, I want to take them to the phone settings programmatically.

I am using Swift and Xcode.

答:
Using @vivek's hint I develop an utils class based on Swift 3, hope you appreciate!

```<code>import Foundation
import UIKit

public enum PreferenceType: String {

    case about = "General&path=About"
    case accessibility = "General&path=ACCESSIBILITY"
    case airplaneMode = "AIRPLANE_MODE"
    case autolock = "General&path=AUTOLOCK"
    case cellularUsage = "General&path=USAGE/CELLULAR_USAGE"
    case brightness = "Brightness"
    case bluetooth = "Bluetooth"
    case dateAndTime = "General&path=DATE_AND_TIME"
    case facetime = "FACETIME"
    case general = "General"
    case keyboard = "General&path=Keyboard"
    case castle = "CASTLE"
    case storageAndBackup = "CASTLE&path=STORAGE_AND_BACKUP"
    case international = "General&path=INTERNATIONAL"
    case locationServices = "LOCATION_SERVICES"
    case accountSettings = "ACCOUNT_SETTINGS"
    case music = "MUSIC"
    case equalizer = "MUSIC&path=EQ"
    case volumeLimit = "MUSIC&path=VolumeLimit"
    case network = "General&path=Network"
    case nikePlusIPod = "NIKE_PLUS_IPOD"
    case notes = "NOTES"
    case notificationsId = "NOTIFICATIONS_ID"
    case phone = "Phone"
    case photos = "Photos"
    case managedConfigurationList = "General&path=ManagedConfigurationList"
    case reset = "General&path=Reset"
    case ringtone = "Sounds&path=Ringtone"
    case safari = "Safari"
    case assistant = "General&path=Assistant"
    case sounds = "Sounds"
    case softwareUpdateLink = "General&path=SOFTWARE_UPDATE_LINK"
    case store = "STORE"
    case twitter = "TWITTER"
    case facebook = "FACEBOOK"
    case usage = "General&path=USAGE"
    case video = "VIDEO"
    case vpn = "General&path=Network/VPN"
    case wallpaper = "Wallpaper"
    case wifi = "WIFI"
    case tethering = "INTERNET_TETHERING"
    case blocked = "Phone&path=Blocked"
    case doNotDisturb = "DO_NOT_DISTURB"

}
</code>```

```<code>enum PreferenceExplorerError: Error {
    case notFound(String)
}

open class PreferencesExplorer {

    // MARK: - Class properties -

    static private let preferencePath = "App-Prefs:root"

    // MARK: - Class methods -

    static func open(_ preferenceType: PreferenceType) throws {
        let appPath = "\(PreferencesExplorer.preferencePath)=\(preferenceType.rawValue)"
        if let url = URL(string: appPath) {
            if #available(iOS 10.0, *) {
                UIApplication.shared.open(url, options: [:], completionHandler: nil)
            } else {
               UIApplication.shared.openURL(url)
            }
        } else {
            throw PreferenceExplorerError.notFound(appPath)
        }
    }

}
</code>```

This is very helpful since that API's will change for sure and you can refactor once and very fast!

Body:
Using @vivek's hint I develop an utils class based on Swift 3, hope you appreciate!

import Foundation
import UIKit

public enum PreferenceType: String {

    case about = "General&path=About"
    case accessibility = "General&path=ACCESSIBILITY"
    case airplaneMode = "AIRPLANE_MODE"
    case autolock = "General&path=AUTOLOCK"
    case cellularUsage = "General&path=USAGE/CELLULAR_USAGE"
    case brightness = "Brightness"
    case bluetooth = "Bluetooth"
    case dateAndTime = "General&path=DATE_AND_TIME"
    case facetime = "FACETIME"
    case general = "General"
    case keyboard = "General&path=Keyboard"
    case castle = "CASTLE"
    case storageAndBackup = "CASTLE&path=STORAGE_AND_BACKUP"
    case international = "General&path=INTERNATIONAL"
    case locationServices = "LOCATION_SERVICES"
    case accountSettings = "ACCOUNT_SETTINGS"
    case music = "MUSIC"
    case equalizer = "MUSIC&path=EQ"
    case volumeLimit = "MUSIC&path=VolumeLimit"
    case network = "General&path=Network"
    case nikePlusIPod = "NIKE_PLUS_IPOD"
    case notes = "NOTES"
    case notificationsId = "NOTIFICATIONS_ID"
    case phone = "Phone"
    case photos = "Photos"
    case managedConfigurationList = "General&path=ManagedConfigurationList"
    case reset = "General&path=Reset"
    case ringtone = "Sounds&path=Ringtone"
    case safari = "Safari"
    case assistant = "General&path=Assistant"
    case sounds = "Sounds"
    case softwareUpdateLink = "General&path=SOFTWARE_UPDATE_LINK"
    case store = "STORE"
    case twitter = "TWITTER"
    case facebook = "FACEBOOK"
    case usage = "General&path=USAGE"
    case video = "VIDEO"
    case vpn = "General&path=Network/VPN"
    case wallpaper = "Wallpaper"
    case wifi = "WIFI"
    case tethering = "INTERNET_TETHERING"
    case blocked = "Phone&path=Blocked"
    case doNotDisturb = "DO_NOT_DISTURB"

}

enum PreferenceExplorerError: Error {
    case notFound(String)
}

open class PreferencesExplorer {

    // MARK: - Class properties -

    static private let preferencePath = "App-Prefs:root"

    // MARK: - Class methods -

    static func open(_ preferenceType: PreferenceType) throws {
        let appPath = "\(PreferencesExplorer.preferencePath)=\(preferenceType.rawValue)"
        if let url = URL(string: appPath) {
            if #available(iOS 10.0, *) {
                UIApplication.shared.open(url, options: [:], completionHandler: nil)
            } else {
               UIApplication.shared.openURL(url)
            }
        } else {
            throw PreferenceExplorerError.notFound(appPath)
        }
    }

}

This is very helpful since that API's will change for sure and you can refactor once and very fast!


问:
Does a foreign key reduce redundancy if all the columns are referenced?
I've read that one of the benefits of normalization is to reduce redundancy in the DB. But I'm wondering, if you end up referencing all the columns in the target table?

For example, if I have a Video table that references a Genre table, the Genre table might very likely have a single column with a dozen fairly static values like 'Horror' 'Sci-Fi' 'Romance' etc.

In a case like this, does it save any space to separate the two, or is the only benefit making it so you can update all referencing rows from one place?

答:
Right, space saving is ONE of the benefits, not the only one.

In the case you mentioned, no, you'll save no space if you use that one column as the PK which is fine.

You could abstract that table with a autonumber/sequence and use that as the PK, and make the current column the candidate key (so it stays unique).

But leaving your design exactly as you've outlined, the benefit is in consistency. You'll have only those 12 values... you'll not accidentally enter a value for "Horrer" or "PSY-Fi"


问:
FLAG_ACTIVITY_REORDER_TO_FRONT not working on some devices
So here is what I am trying to achieve here... We have two android APKs installed on the device... Each APK can force itself to be on the foreground (This is not an app the general public will use so it's okay...)

So we launch task a with activity a.

We then launch task b with activity b.

Then activity a & task a wants to go to foreground (This can happen at any time)

At some point later, activity a and task a wants to go to foreground

So we had this code working using the following code:

```<code>Intent i = new Intent(Variables.context, HomeActivity.class);
i.setFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
startActivity(i);
</code>```

Great!

However, on a phone running 4.2.2 (and maybe others too) we noticed that the behavior was not as expected. The following two things can happen.

Let's assume activity a & task a is in the foreground, but want to make activity b and task b come to the foreground it does not work.

However if no task was in the foreground and the home launcher is focused, then activity b and task b gets popped to the foreground as expected.

Here is an example of one of my manifest from one of the applications:

```<code> <activity
            android:name="some.app.id.goes.here"
            android:label="@string/app_name"
            android:screenOrientation="portrait"
            android:windowSoftInputMode="adjustPan">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
</code>```

I have tried adding this line of code:

```<code>android:launchMode="singleTop"
</code>```

and it still does not work.

Is there anything I am missing?

A few notes:

Activity A can be ANY application, not just our developed application which rules out activity A from stopping this from happening. We had the same results using Google chrome / Google maps / Google play store.

We do not override onNewIntent

答:
Well, what a pain this was...

Here is the workaround I had to make...

```<code>private void generateNotificationToPopActivityToTop(final int id, Context context, String message) {
        Intent notificationIntent = new Intent(context, HomeActivity.class);
        notificationIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
        PendingIntent intent = PendingIntent.getActivity(context, 0, notificationIntent, 0);

        NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(context)
                .setSmallIcon(R.drawable.ic_launcher)
                .setContentTitle(context.getString(R.string.app_name))
                .setFullScreenIntent(intent, true)
                .setPriority(NotificationCompat.PRIORITY_MAX)
                .setContentText(message)
                .setAutoCancel(true)
                .setDefaults(Notification.DEFAULT_SOUND | Notification.DEFAULT_VIBRATE | Notification.DEFAULT_LIGHTS);
        final NotificationManager mNotificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
        mNotificationManager.notify(id, mBuilder.build());

        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                mNotificationManager.cancel(id);
            }
        }, 1000);

    }
</code>```

Body:
So here is what I am trying to achieve here... We have two android APKs installed on the device... Each APK can force itself to be on the foreground (This is not an app the general public will use so it's okay...)

So we launch task a with activity a.

We then launch task b with activity b.

Then activity a & task a wants to go to foreground (This can happen at any time)

At some point later, activity a and task a wants to go to foreground

So we had this code working using the following code:

Intent i = new Intent(Variables.context, HomeActivity.class);
i.setFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
startActivity(i);

Great!

However, on a phone running 4.2.2 (and maybe others too) we noticed that the behavior was not as expected. The following two things can happen.

Let's assume activity a & task a is in the foreground, but want to make activity b and task b come to the foreground it does not work.

However if no task was in the foreground and the home launcher is focused, then activity b and task b gets popped to the foreground as expected.

Here is an example of one of my manifest from one of the applications:

 <activity
            android:name="some.app.id.goes.here"
            android:label="@string/app_name"
            android:screenOrientation="portrait"
            android:windowSoftInputMode="adjustPan">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

I have tried adding this line of code:

android:launchMode="singleTop"

and it still does not work.

Is there anything I am missing?

A few notes:

Activity A can be ANY application, not just our developed application which rules out activity A from stopping this from happening. We had the same results using Google chrome / Google maps / Google play store.

We do not override onNewIntent

Body:
Well, what a pain this was...

Here is the workaround I had to make...

private void generateNotificationToPopActivityToTop(final int id, Context context, String message) {
        Intent notificationIntent = new Intent(context, HomeActivity.class);
        notificationIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
        PendingIntent intent = PendingIntent.getActivity(context, 0, notificationIntent, 0);

        NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(context)
                .setSmallIcon(R.drawable.ic_launcher)
                .setContentTitle(context.getString(R.string.app_name))
                .setFullScreenIntent(intent, true)
                .setPriority(NotificationCompat.PRIORITY_MAX)
                .setContentText(message)
                .setAutoCancel(true)
                .setDefaults(Notification.DEFAULT_SOUND | Notification.DEFAULT_VIBRATE | Notification.DEFAULT_LIGHTS);
        final NotificationManager mNotificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
        mNotificationManager.notify(id, mBuilder.build());

        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                mNotificationManager.cancel(id);
            }
        }, 1000);

    }


问:
C++ elegant way of passing (a subset of) options to a function
I have a function whose exact behaviour is controlled by a set of flags. Most of these are usually false. Having them all as parameters quickly becomes very messy.

I could create an enum for the flags:

```<code>enum ParseFlags { assignmentPossible = 1, commaDelimits = 2, isConst = 4 };
PExpression ParseExpr(unsigned int flags);
</code>```

A bit better: now, when calling the function, I only have to specify the values I want to set, instead of a long list of bools.

However, I would like to know if there is a more elegant or more general way of passing a subset of options to a function. What if I have non-boolean options?

I'm looking for a C++ (Boost is ok) way to call a function like:

```<code>ParseExpr({ isConst: true; maxDepth: 5 });
</code>```

where I can omit all values that I want to leave at their default.

What techniques and/or libraries exist for this?

答:
Ripping from this library's design, you could have a parameter class which curries its set methods.

```<code>class ParseFlags
{
public:
    ParseFlags& assignable(bool b) {assignable_ = b; return *this;}
    ParseFlags& delimiter(char c) {delimiter_ = c; return *this;}
    ParseFlags& constness(bool b) {constness_ = b; return *this;}
private:
    bool assignable_ = false;
    char delimiter_ = ',';
    bool constness_ = false;
};

PExpression ParseExpr(const ParseFlags& = ParseFlags{});
</code>```

Call it like

```<code>auto exp = ParseExpr(ParseFlags().constness(false).delimiter('.'));
auto exp2 = ParseExpr();
</code>```

Which is almost as good as having named parameters.

Body:
I have a function whose exact behaviour is controlled by a set of flags. Most of these are usually false. Having them all as parameters quickly becomes very messy.

I could create an enum for the flags:

enum ParseFlags { assignmentPossible = 1, commaDelimits = 2, isConst = 4 };
PExpression ParseExpr(unsigned int flags);

A bit better: now, when calling the function, I only have to specify the values I want to set, instead of a long list of bools.

However, I would like to know if there is a more elegant or more general way of passing a subset of options to a function. What if I have non-boolean options?

I'm looking for a C++ (Boost is ok) way to call a function like:

ParseExpr({ isConst: true; maxDepth: 5 });

where I can omit all values that I want to leave at their default.

What techniques and/or libraries exist for this?

Body:
Ripping from this library's design, you could have a parameter class which curries its set methods.

class ParseFlags
{
public:
    ParseFlags& assignable(bool b) {assignable_ = b; return *this;}
    ParseFlags& delimiter(char c) {delimiter_ = c; return *this;}
    ParseFlags& constness(bool b) {constness_ = b; return *this;}
private:
    bool assignable_ = false;
    char delimiter_ = ',';
    bool constness_ = false;
};

PExpression ParseExpr(const ParseFlags& = ParseFlags{});

Call it like

auto exp = ParseExpr(ParseFlags().constness(false).delimiter('.'));
auto exp2 = ParseExpr();

Which is almost as good as having named parameters.