问:
php auto update script files
How can I create script version update function like in datalife engine cms ? For example customer has version 1.0 and I have created version 1.5. And I want the user to be able to update the script version directly from admin panel. How can I do it ?</p>

答:
Notice:  This is my own solution.

@Guilherme Soster has provided the basics on how to do it.  However if you do not want to do it yourself you can check my php-updater solution.  You can define what you want to add (overwrite or add) and delete as well as scripts you want to run in a YAML file.

Title: php auto update script files


来源: stackexchange

问:
Summing two 2-D lists
so this has kind of stumped me. I feel like it should be an easy problem though.
Lets say I have these two lists

```<code>a = [[3, 4], [4, 5]]
b = [[1, 2], [4, 6]]
</code>```

I am trying so it would return the sum of the two 2-D lists of each corresponding element like so

```<code>c = [[4, 6], [8, 11]]
</code>```

I am pretty sure I am getting lost in loops. I am only trying to use nested loops to produce an answer, any suggestions? I'm trying several different things so my code is not exactly complete or set in stone and will probably change by the time someone reponds so I won't leave a code here. I am trying though!

答:
I know it is an old question, but following nested loops code works exactly as desired by OP:

```<code>sumlist = []
for i, aa in enumerate(a):
    for j, bb in enumerate(b):
        if i == j:
            templist = []
            for k in range(2):
                templist.append(aa[k]+bb[k])
            sumlist.append(templist)
            templist = []
print(sumlist)
</code>```

Output:

```<code>[[4, 6], [8, 11]]
</code>```

ContentLicense: CC BY-SA 3.0

Title: Summing two 2-D lists

Body:
so this has kind of stumped me. I feel like it should be an easy problem though.
Lets say I have these two lists

a = [[3, 4], [4, 5]]
b = [[1, 2], [4, 6]]

I am trying so it would return the sum of the two 2-D lists of each corresponding element like so

c = [[4, 6], [8, 11]]

I am pretty sure I am getting lost in loops. I am only trying to use nested loops to produce an answer, any suggestions? I'm trying several different things so my code is not exactly complete or set in stone and will probably change by the time someone reponds so I won't leave a code here. I am trying though!

Body:
I know it is an old question, but following nested loops code works exactly as desired by OP:

sumlist = []
for i, aa in enumerate(a):
    for j, bb in enumerate(b):
        if i == j:
            templist = []
            for k in range(2):
                templist.append(aa[k]+bb[k])
            sumlist.append(templist)
            templist = []
print(sumlist)

Output:

[[4, 6], [8, 11]]

ContentLicense: CC BY-SA 4.0


问:
How do I do something LIKE in mysql in javascript?
I wanted to check the user's expertise and display their network graph. The reason I wanted to use LIKE is because in mysql database the expertise attribute is included also with their workplace. For example: Data Analyst at Petronas. So I wanted to check if their expertise is data analyst and display their network graph.

This is the code that I've tried:

```<code><?php
if (isset($_GET['id'])) {

    $id = $_GET['id'];
    $sql = "SELECT * FROM professional, job, location WHERE PROFESSIONAL_ID LIKE '%$id%' AND PROFESSIONAL_ID=JOB_ID AND JOB_ID = LOCATION_ID " ;
    $result = mysqli_query($conn, $sql);

    $row = mysqli_fetch_assoc($result);

    echo "
                <div class='card'>
                <img src='../images/img.png' style='width:100%'>
                <h2>".$row['PROFESSIONAL_NAME']."</h2>
                <p class='title'><i class='fa fa-briefcase' aria-hidden='true'></i> ".$row['JOB_NAME']."</p>
                <p class='marker'><i class='fa fa-map-marker' aria-hidden='true'></i> ".$row['LOCATION_NAME']."</p>
                <a href=".$row['PROFESSIONAL_URL']."><p><button>Contact</button></p></a>
              </div>

              <div class='network'>
              <h2> Filter Network</h2>
              </div>

              <div class='filter'>
        <input type='radio' value='Expertise' unchecked name='radioBtn' onclick='checkexpertise(".$row['JOB_NAME'].")'> <label> Expertise</label><br>
        <input type='radio' value='Location' unchecked name='radioBtn' onclick='checklocation(".$row['LOCATION_NAME'].")'> <label> Location</label><br>
        <input type='radio' value='Workplace' unchecked name='radioBtn' onclick='checkworkplace()'> <label> Workplace </label><br>
        <input type='radio' value='Past Workplace' unchecked name='radioBtn' onclick='checkpast()'> <label>Past Workplace</label><br>

      </div>";

}

?>
<script>
      function CheckExpertise (Expertise) {
        if Expertise LIKE %Data Analyst% OR %data analyst%
        {
          window.location.replace("expertise.html");
          }
      }
      </script>
</code>```

答:
You can use a regular expression for this:

```<code>if (/.*data analyst.*/i.test(Expertise)) {
  window.location.replace("expertise.html");
}
</code>```

But please take a look at mysqli prepared statements and output sanitization (e.g. using htmlentities). Users can send anything as "id" including crafted SQL queries which you probably don't want to execute ;)

```<code>$id = $_GET['id'];
$query = mysqli_prepare($conn, "SELECT * FROM professional, job, location WHERE PROFESSIONAL_ID LIKE ? AND PROFESSIONAL_ID=JOB_ID AND JOB_ID = LOCATION_ID " ;
mysqli_bind_param($query, "s", "%{$id}%");
mysqli_stmt_execute($query);
$result = mysqli_stmt_get_result($query);
</code>```

Body:
I wanted to check the user's expertise and display their network graph. The reason I wanted to use LIKE is because in mysql database the expertise attribute is included also with their workplace. For example: Data Analyst at Petronas. So I wanted to check if their expertise is data analyst and display their network graph.

This is the code that I've tried:

<?php
if (isset($_GET['id'])) {

    $id = $_GET['id'];
    $sql = "SELECT * FROM professional, job, location WHERE PROFESSIONAL_ID LIKE '%$id%' AND PROFESSIONAL_ID=JOB_ID AND JOB_ID = LOCATION_ID " ;
    $result = mysqli_query($conn, $sql);

    $row = mysqli_fetch_assoc($result);

    echo "

".$row['PROFESSIONAL_NAME']."

 ".$row['JOB_NAME']."

 ".$row['LOCATION_NAME']."

<button>Contact</button>

 Filter Network

        <input type='radio' value='Expertise' unchecked name='radioBtn' onclick='checkexpertise(".$row['JOB_NAME'].")'>  Expertise

        <input type='radio' value='Location' unchecked name='radioBtn' onclick='checklocation(".$row['LOCATION_NAME'].")'>  Location

        <input type='radio' value='Workplace' unchecked name='radioBtn' onclick='checkworkplace()'>  Workplace

        <input type='radio' value='Past Workplace' unchecked name='radioBtn' onclick='checkpast()'> Past Workplace

";

}

?>

Body:
You can use a regular expression for this:

if (/.*data analyst.*/i.test(Expertise)) {
  window.location.replace("expertise.html");
}

But please take a look at mysqli prepared statements and output sanitization (e.g. using htmlentities). Users can send anything as "id" including crafted SQL queries which you probably don't want to execute ;)

$id = $_GET['id'];
$query = mysqli_prepare($conn, "SELECT * FROM professional, job, location WHERE PROFESSIONAL_ID LIKE ? AND PROFESSIONAL_ID=JOB_ID AND JOB_ID = LOCATION_ID " ;
mysqli_bind_param($query, "s", "%{$id}%");
mysqli_stmt_execute($query);
$result = mysqli_stmt_get_result($query);


问:
Is there a way to Debug why my executable JAR of a JavaFX-Project runs on my Computer but not on others ? (Using jdk 1.8._051)
I exportet a Jar of a JavaFX2 Project. It works fine, but when I run it on another machine there will be a
classDefNotFoundExeption: javafx.application.Application

Any hints how to tackle this Problem ?

This is my Manifest:

```<code>Class-Path: .
Main-Class: proj.view.Launcher

</code>```

I also programmed Launcher that starts a Swing GUI in case JavaFX is not found.

Here is my Launcher Class

public class Launcher {

    public static void main(String[] args) {

        try {

            Class c = javafx.application.Application.class;
            proj.main.App.main(args);

        }catch (NoClassDefFoundError e) {
            String[] t = {"Swing Backup","Application start Error"};
            MainFrame.remote(t);

        }

    }

}

```

答:
To me it looks like runnable jar issue if then same code is working through IDE's on those machines. You can try maven assembly plugin to pack your jar.

The Apache Maven Assembly Plugin allows users to aggregate the project output along with its dependencies, modules, site documentation, and other files into a single, runnable package.

```<code><plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-assembly-plugin</artifactId>
    <executions>
        <execution>
            <phase>package</phase>
            <goals>
                <goal>single</goal>
            </goals>
            <configuration>
                <archive>
                <manifest>
                    <mainClass>
                        package.your_main_class
                    </mainClass>
                </manifest>
                </archive>
                <descriptorRefs>
                    <descriptorRef>jar-with-dependencies</descriptorRef>
                </descriptorRefs>
            </configuration>
        </execution>
    </executions>
</plugin>
</code>```

Body:
I exportet a Jar of a JavaFX2 Project. It works fine, but when I run it on another machine there will be a
classDefNotFoundExeption: javafx.application.Application

Any hints how to tackle this Problem ?

This is my Manifest:

Class-Path: .
Main-Class: proj.view.Launcher

I also programmed Launcher that starts a Swing GUI in case JavaFX is not found.

Here is my Launcher Class

public class Launcher {

    public static void main(String[] args) {

        try {

            Class c = javafx.application.Application.class;
            proj.main.App.main(args);

        }catch (NoClassDefFoundError e) {
            String[] t = {"Swing Backup","Application start Error"};
            MainFrame.remote(t);

        }

    }

}

Body:
To me it looks like runnable jar issue if then same code is working through IDE's on those machines. You can try maven assembly plugin to pack your jar.

The Apache Maven Assembly Plugin allows users to aggregate the project output along with its dependencies, modules, site documentation, and other files into a single, runnable package.

<plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-assembly-plugin</artifactId>
    <executions>
        <execution>
            <phase>package</phase>
            <goals>
                <goal>single</goal>
            </goals>
            <configuration>
                <archive>
                <manifest>
                    <mainClass>
                        package.your_main_class
                    </mainClass>
                </manifest>
                </archive>
                <descriptorRefs>
                    <descriptorRef>jar-with-dependencies</descriptorRef>
                </descriptorRefs>
            </configuration>
        </execution>
    </executions>
</plugin>


问:
sql query for getting the newest call
Can someone point me to the right direction what i need to read? ...

I have two tables. 1st with customer id and customer name. 2nd with customer id and date of call to customer. I used LEFT JOIN to get a list for each customern with all calls to him. Like this:

```<code>1, Max Mustermann, 2019-05-22
1, Max Mustermann, 2019-05-20 (<- I don't want this row to appear.)
2, Ilse Meier,
</code>```

I used LEFT JOIN to get customers without calls too.

Now I want this result with only the latest call.

For one call (to get the latest) I could do:

SELECT * FROM calls ORDER BY call_date DESC LIMIT 1;

I'm stuck. What do I need to read about?

答:
You can use group by and max() to get a customer with the newest call. When a customer has never called there will be NULL in Maxdateofcall.

```<code>select
     t1.customerid
    ,t1.customername
    ,max(t2.dateofcall) as Maxdateofcall
from table1 t1 left join table1 t2 on t1.customerid = t2.customerid
group by t1.customerid ,t1.customername

1, Max Mustermann, 2019-05-22
2, Ilse Meier, null
</code>```

Title: sql query for getting the newest call

Body:
Can someone point me to the right direction what i need to read? ...

I have two tables. 1st with customer id and customer name. 2nd with customer id and date of call to customer. I used LEFT JOIN to get a list for each customern with all calls to him. Like this:

1, Max Mustermann, 2019-05-22
1, Max Mustermann, 2019-05-20 (<- I don't want this row to appear.)
2, Ilse Meier,

I used LEFT JOIN to get customers without calls too.

Now I want this result with only the latest call.

For one call (to get the latest) I could do:

SELECT * FROM calls ORDER BY call_date DESC LIMIT 1;

I'm stuck. What do I need to read about?

Body:
You can use group by and max() to get a customer with the newest call. When a customer has never called there will be NULL in Maxdateofcall.

select
     t1.customerid
    ,t1.customername
    ,max(t2.dateofcall) as Maxdateofcall
from table1 t1 left join table1 t2 on t1.customerid = t2.customerid
group by t1.customerid ,t1.customername

1, Max Mustermann, 2019-05-22
2, Ilse Meier, null


问:
SharePoint 2007: How can I perform a series of operations within a transaction?
I would love to know how to perform a series of operations in a SharePoint context within a transaction.  For example, I would like to be able to do something like the following:

```<code>context.BeginTransaction();
listItemA.Update();
listItemB.Update();
context.CommitTransaction();
</code>```

I know this isn't possible with the OOTB APIs, but someone has got to have figured out how to accomplish this.  Is it possible to get a reference to the database connection in order to handle the transaction?  Or any other ideas?

答:
Although SharePoint technically uses SQL as a storage backing, we're not supposed to treat it like a database-based application. SP creates a faux-filesystem of sorts, which is what we interact with via the API. So from the developer perspective, Sharepoint is pretty much transaction-less.

Unfortunately that's pretty much all there is to it :) Even thinking about trying to get involved with the database directly will result in Old Testament pain. Rending of garments, wailing and gnashing of teeth ;)

OwnerDisplayName: Trent

ContentLicense: CC BY-SA 2.5

Body:
I would love to know how to perform a series of operations in a SharePoint context within a transaction.  For example, I would like to be able to do something like the following:

context.BeginTransaction();
listItemA.Update();
listItemB.Update();
context.CommitTransaction();

I know this isn't possible with the OOTB APIs, but someone has got to have figured out how to accomplish this.  Is it possible to get a reference to the database connection in order to handle the transaction?  Or any other ideas?

LastEditorDisplayName: Trent

OwnerDisplayName: Rex M

LastEditorDisplayName: Rex M


问:
Lotus notes html email problem
I've made an html email but unfortunately, my client uses a lotus 6.5 which renders css and other stuffs poorly. Now I've fixed most of it, except for one problem, it generated a huge spacing in the bottom part. It almost like a
 when you look at it in Lotus notes but when i put in a border=1 inside the table, it produced a somewhat hollow spacing. Anyone one encountered this?

Heres a screenshot:
http://i.stack.imgur.com/Nlss8.png

For reference, here is what it should look like:
http://www.interfaceflor.asia/oi_buzz/apr/english.html

Any help would be appreciated. Its making me nuts for days now. Thanks. :)

Regards,
Mark

答:
Well, the problem is likely Lotus Notes here and not your code. Notes is very buggy and non-standard when it comes to rendering HTML emails.

My advice is to stay away from using CSS if you want to have it render correctly.  Use tables and perhaps image sizes to control spacing.

Or just explain to the client they need to accept these inconsistencies as long as they are using an email client from 2005.

If you can share some code too we might be able to be more specific.

Title: Lotus notes html email problem


问:
Change the background of a label when acting as checkbox
I have labels with images nested inside that is acting as a checkbox. What I can't figure out is how to change the background behind the image when that specific checkbox is selected (label clicked).

It appears as if one of the checkboxes is getting the background to show, but not both and the height element is not working.

Does anyone see what I am doing wrong?

.notificationImgs {
 width: 70px;
 height: auto;
 margin: 0 20px;
 cursor: pointer;
}
.notifCheck {
 display: none;
}
.notifCheck:checked + label {
 background: #CCC;
}
.notifCheck:checked .notificationImgs {
 background-color: #CCC;
 width: 100%;
 height: 70px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><label for="checkText">
   <img src="https://images.pexels.com/photos/67636/rose-blue-flower-rose-blooms-67636.jpeg?auto=compress&cs=tinysrgb&dpr=1&w=500" alt="Text Notifications" class="notificationImgs">
  </label>
  <input type="checkbox" name="checkText" class="notifCheck" id="checkText" value="text">
  <label for="checkEmail">
   <img src="https://images.pexels.com/photos/67636/rose-blue-flower-rose-blooms-67636.jpeg?auto=compress&cs=tinysrgb&dpr=1&w=500" alt="Email Notifications" class="notificationImgs">
  </label></code>```

答:
Its not adding background on correct label because of the ordering of input and label. Put related input (which is hidden checkbox) before the related label. So .notifCheck:checked + label can find the correct label. Also you can add display:inline-block to all label style. So it will resolve the height issue.

See the Snippet below:

.notificationImgs {
 width: 70px;
 height: auto;
 margin: 0 20px;
 cursor: pointer;
}
.notifCheck {
 display: none;
}
label{
  display:inline-block;
  padding:10px;
}
.notifCheck:checked + label {
 background: #CCC;
}
.notifCheck:checked .notificationImgs {
 background-color: #CCC;
 width: 100%;
 height: 70px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><input type="checkbox" name="checkText" class="notifCheck" id="checkText" value="text">
<label for="checkText">
  <img src="https://images.pexels.com/photos/67636/rose-blue-flower-rose-blooms-67636.jpeg?auto=compress&cs=tinysrgb&dpr=1&w=500" alt="Text Notifications" class="notificationImgs">
</label>
<input type="checkbox" name="checkEmail" class="notifCheck" id="checkEmail" value="text">
<label for="checkEmail">
  <img src="https://images.pexels.com/photos/67636/rose-blue-flower-rose-blooms-67636.jpeg?auto=compress&cs=tinysrgb&dpr=1&w=500" alt="Email Notifications" class="notificationImgs">
</label></code>```

Body:
I have labels with images nested inside that is acting as a checkbox. What I can't figure out is how to change the background behind the image when that specific checkbox is selected (label clicked).

It appears as if one of the checkboxes is getting the background to show, but not both and the height element is not working.

Does anyone see what I am doing wrong?

.notificationImgs {
 width: 70px;
 height: auto;
 margin: 0 20px;
 cursor: pointer;
}
.notifCheck {
 display: none;
}
.notifCheck:checked + label {
 background: #CCC;
}
.notifCheck:checked .notificationImgs {
 background-color: #CCC;
 width: 100%;
 height: 70px;
}

  <input type="checkbox" name="checkText" class="notifCheck" id="checkText" value="text">

Body:
Its not adding background on correct label because of the ordering of input and label. Put related input (which is hidden checkbox) before the related label. So .notifCheck:checked + label can find the correct label. Also you can add display:inline-block to all label style. So it will resolve the height issue.

See the Snippet below:

.notificationImgs {
 width: 70px;
 height: auto;
 margin: 0 20px;
 cursor: pointer;
}
.notifCheck {
 display: none;
}
label{
  display:inline-block;
  padding:10px;
}
.notifCheck:checked + label {
 background: #CCC;
}
.notifCheck:checked .notificationImgs {
 background-color: #CCC;
 width: 100%;
 height: 70px;
}

<input type="checkbox" name="checkText" class="notifCheck" id="checkText" value="text">
<label for="checkText">
  <img src="https://images.pexels.com/photos/67636/rose-blue-flower-rose-blooms-67636.jpeg?auto=compress&cs=tinysrgb&dpr=1&w=500" alt="Text Notifications" class="notificationImgs">
</label>
<input type="checkbox" name="checkEmail" class="notifCheck" id="checkEmail" value="text">
<label for="checkEmail">
  <img src="https://images.pexels.com/photos/67636/rose-blue-flower-rose-blooms-67636.jpeg?auto=compress&cs=tinysrgb&dpr=1&w=500" alt="Email Notifications" class="notificationImgs">
</label>


问:
Rails 3 Autocomplete Across Multiple Models
So I found some great info on Autocomplete for Rails 3, it looks really easy to use.  But I have a use case that doesnt fit and I need some advice.

I want to give the user the ability to add Products and Services to an Invoice through a simple form.  I'd like them to be able to type into the Item field and have it autocomplete from both Product.name and Service.name as a single set.

I'm thinking of trying to write a parent model that overlays all three, but I still don't think that solves my problem since I can't use a function in the autocomplete definition from what I understand.

Any advice on how I might try to accomplish this?  Even with the simple search examples that are out there they seem to be restricted to a single model.

答:
If client-side autocomplete is an option (e.g. you have few products and services), you could go with JQuery autocomplete:

controller:

```<code>@keys = @categories.map { |x| x.name } + @entries.map { |x| x.description }
@autocomplete_categories = @keys.to_json.html_safe
</code>```

view:

```<code><script type="text/javascript">
$(document).ready(function() {
    var data = <%= @autocomplete_categories %>;
    $("#auto").autocomplete( { source: data } );
});
</script>

<input type="text" name="auto" id="auto" />
</code>```

Body:
If client-side autocomplete is an option (e.g. you have few products and services), you could go with JQuery autocomplete:

controller:

@keys = @categories.map { |x| x.name } + @entries.map { |x| x.description }
@autocomplete_categories = @keys.to_json.html_safe

view:

<script type="text/javascript">
$(document).ready(function() {
    var data = <%= @autocomplete_categories %>;
    $("#auto").autocomplete( { source: data } );
});
</script>

<input type="text" name="auto" id="auto" />


问:
Extracting only modified codes by using git diff
I want the diffrence between two separate branches B1 and B2 to extract the modified codes in B2.
Here, the B1 is more like a parent/Developer branch under which other feature branches(e.g B2,B3,B4,B5) are created, modifications are done and then merged into B1.
The issue i am facing is, whenever i do a git diff --name-status between the B1 and B2, or between commit id's of the same, i get more than what is modified in B2.

The reason is, before B2, other branches(B3,B4) may have been merged into B1 which results in B2 getting behind B1 due to the changes made by the other branches merged into it.

Now, if i do a diff, it not only gives me code names changed in B2, but also B3 and B4.

Is there any way to implement this. I have tried all possible ways that i am aware of.

答:
Try with

```<code>git diff --name-status B1...B2 # triple dot
git diff B1...B2
</code>```

That should work

Body:
Try with

git diff --name-status B1...B2 # triple dot
git diff B1...B2

That should work


问:
NaN when adding two numbers
Why explosion.pdi can be (and is) NaN after adding a number (explosion.ppsd) to it ?

Console logs : (you can see the two are Number and not NaN before the addition, and explosion.pdi is NaN after)

```<code>console.log('before: pdi = ' + explosion.pdi + ' | ppsd = ' + explosion.ppsd);
console.log('typeof pdi = ' + typeof(explosion.pdi) + ' | typeof ppsd = ' + typeof(explosion.ppsd));

explosion.pdi += explosion.ppsp; // Here :

console.log('after: pdi = ' + explosion.pdi + ' | ppsd = ' + explosion.ppsd);
console.log('typeof pdi = ' + typeof(explosion.pdi) + ' | typeof ppsd = ' + typeof(explosion.ppsd));
</code>```

Edit: Sorry, typo problem (ppsp => ppsd)

答: There is a typo in "explosion.pdi += explosion.ppsp;" it needs to be explosion.pdi += explosion.ppsd</p>

Title: NaN when adding two numbers

Body:
Why explosion.pdi can be (and is) NaN after adding a number (explosion.ppsd) to it ?

Console logs : (you can see the two are Number and not NaN before the addition, and explosion.pdi is NaN after)

console.log('before: pdi = ' + explosion.pdi + ' | ppsd = ' + explosion.ppsd);
console.log('typeof pdi = ' + typeof(explosion.pdi) + ' | typeof ppsd = ' + typeof(explosion.ppsd));

explosion.pdi += explosion.ppsp; // Here :

console.log('after: pdi = ' + explosion.pdi + ' | ppsd = ' + explosion.ppsd);
console.log('typeof pdi = ' + typeof(explosion.pdi) + ' | typeof ppsd = ' + typeof(explosion.ppsd));

Edit: Sorry, typo problem (ppsp => ppsd)


问:
Undefined Instruction exception in ARM code
I'm doing bare-metal programming (I'm developing a kernel) on an ARM-Cortex A53, SoC BCM2837 (Raspberry PI 3 in other words). I'm actually writing the piece of software responsable to handle the mini UART (a sort of hello world, as reported on OsDev wiki https://wiki.osdev.org/ARM_RaspberryPi_Tutorial_C). So I've written a set of functions to handle the mini UART, let's consider the following, since the problem persists for any of the other functions:

```<code>void miniUartSendByte(unsigned char byte){
  // FIFO can accept at least one byte
  while(*AUX_MU_LSR_REG & 0b100000);

  // write byte to buffer
  *AUX_MU_IO_REG = byte;
  return;
}
</code>```

where AUX_MU_* is of type volatile unsigned int*. this the disassemble of the code above:

```<code>  1000ac:       d10043ff        sub     sp, sp, #0x10
  1000b0:       39003fe0        strb    w0, [sp, #15]
  1000b4:       d503201f        nop
  1000b8:       d28a0a80        mov     x0, #0x5054                     // #20564
  1000bc:       f2afc420        movk    x0, #0x7e21, lsl #16
  1000c0:       b9400000        ldr     w0, [x0]
  1000c4:       121b0000        and     w0, w0, #0x20
  1000c8:       7100001f        cmp     w0, #0x0
  1000cc:       54ffff61        b.ne    1000b8 <miniUartSendByte+0xc>   // b.any
  1000d0:       d28a0800        mov     x0, #0x5040                     // #20544
  1000d4:       f2afc420        movk    x0, #0x7e21, lsl #16
  1000d8:       39403fe1        ldrb    w1, [sp, #15]
  1000dc:       b9000001        str     w1, [x0]
  1000e0:       d503201f        nop
  1000e4:       910043ff        add     sp, sp, #0x10
  1000e8:       d65f03c0        ret

</code>```

and this the execution as reported by QEMU:

```<code>----------------
IN: kernel_main
0x00100050:  a9bf7bfd  stp      x29, x30, [sp, #-0x10]!
0x00100054:  910003fd  mov      x29, sp
0x00100058:  52800c60  movz     w0, #0x63
0x0010005c:  94000012  bl       #0x1000a4 // jump to miniUartSendByte

----------------
IN: miniUartSendByte
0x001000a4:  d10043ff  sub      sp, sp, #0x10
0x001000a8:  39003fe0  strb     w0, [sp, #0xf]
0x001000ac:  d503201f  nop
0x001000b0:  d28a0a80  movz     x0, #0x5054
0x001000b4:  f2afc420  movk     x0, #0x7e21, lsl #16
0x001000b8:  b9400000  ldr      w0, [x0]
0x001000bc:  121b0000  and      w0, w0, #0x20
0x001000c0:  7100001f  cmp      w0, #0
0x001000c4:  54ffff61  b.ne     #0x1000b0

----------------
IN:
0x00000200:  00000000  .byte    0x00, 0x00, 0x00, 0x00 // ??
</code>```

As you can see, when the machine executes the jump, it receives an exception and jumps to the address 0x200, where the interrupt handler is placed (note, no interrupt handler has been configured, I've not implemented it yet) and gets stucked at address 0x200 executing an infinite loop (default behaviour when no interrupt handler is present). Now, from QEMU I was able to capture the type of exception:

```<code>Taking exception 1 [Undefined Instruction]
...from EL3 to EL3
...with ESR 0x0/0x2000000
...with ELR 0x200
...to EL3 PC 0x200 PSTATE 0x3cd

</code>```

I'm compiling with the following command:

```<code>aarch64-elf-gcc -Wall -O0 -ffreestanding -nostdinc -nostdlib -nostartfiles -mcpu=cortex-a53 -g -c ... -o ...
</code>```

I've also tried to see if this was a "compiler" problem, trying to execute the following totally useless code:

```<code>void a(){
  for(int j=0; j<10; j++);
  return;
}

void b(char* string){
  for(int i = 0; i<10; i++){
    a();
  }
  return;
}

void kernel_main(){

  a();
  b("test");

  while(1);

  return;
}

</code>```

but the execution goes without any problem...
now I can't figure out what's going wrong. I mean, there is nothing bad in the C code producing that assembler, and addresses in the assembly code seems ok... any idea where the problem arises?? Why that Undefined Instruction exception?? If more information are needed I can provide more details

答:
The problem was in the wrong base address set for accessing the peripherals' registers. Once set it to 0x3F000000, no exception is raised anymore.

I had setted as base address 0x7E000000, misleading what reported in the BCM datasheet:

Physical addresses range from 0x3F000000 to 0x3FFFFFFF for peripherals. The
  bus addresses for peripherals are set up to map onto the peripheral bus address range
  starting at 0x7E000000. Thus a peripheral advertised here at bus address 0x7Ennnnnn is
  available at physical address 0x3Fnnnnnn.

But later is reported:

The peripheral addresses specified in this document are bus addresses. Software directly
  accessing peripherals must translate these addresses into physical or virtual addresses

Body:
I'm doing bare-metal programming (I'm developing a kernel) on an ARM-Cortex A53, SoC BCM2837 (Raspberry PI 3 in other words). I'm actually writing the piece of software responsable to handle the mini UART (a sort of hello world, as reported on OsDev wiki https://wiki.osdev.org/ARM_RaspberryPi_Tutorial_C). So I've written a set of functions to handle the mini UART, let's consider the following, since the problem persists for any of the other functions:

void miniUartSendByte(unsigned char byte){
  // FIFO can accept at least one byte
  while(*AUX_MU_LSR_REG & 0b100000);

  // write byte to buffer
  *AUX_MU_IO_REG = byte;
  return;
}

where AUX_MU_* is of type volatile unsigned int*. this the disassemble of the code above:

  1000ac:       d10043ff        sub     sp, sp, #0x10
  1000b0:       39003fe0        strb    w0, [sp, #15]
  1000b4:       d503201f        nop
  1000b8:       d28a0a80        mov     x0, #0x5054                     // #20564
  1000bc:       f2afc420        movk    x0, #0x7e21, lsl #16
  1000c0:       b9400000        ldr     w0, [x0]
  1000c4:       121b0000        and     w0, w0, #0x20
  1000c8:       7100001f        cmp     w0, #0x0
  1000cc:       54ffff61        b.ne    1000b8 <miniUartSendByte+0xc>   // b.any
  1000d0:       d28a0800        mov     x0, #0x5040                     // #20544
  1000d4:       f2afc420        movk    x0, #0x7e21, lsl #16
  1000d8:       39403fe1        ldrb    w1, [sp, #15]
  1000dc:       b9000001        str     w1, [x0]
  1000e0:       d503201f        nop
  1000e4:       910043ff        add     sp, sp, #0x10
  1000e8:       d65f03c0        ret

and this the execution as reported by QEMU:

----------------
IN: kernel_main
0x00100050:  a9bf7bfd  stp      x29, x30, [sp, #-0x10]!
0x00100054:  910003fd  mov      x29, sp
0x00100058:  52800c60  movz     w0, #0x63
0x0010005c:  94000012  bl       #0x1000a4 // jump to miniUartSendByte

----------------
IN: miniUartSendByte
0x001000a4:  d10043ff  sub      sp, sp, #0x10
0x001000a8:  39003fe0  strb     w0, [sp, #0xf]
0x001000ac:  d503201f  nop
0x001000b0:  d28a0a80  movz     x0, #0x5054
0x001000b4:  f2afc420  movk     x0, #0x7e21, lsl #16
0x001000b8:  b9400000  ldr      w0, [x0]
0x001000bc:  121b0000  and      w0, w0, #0x20
0x001000c0:  7100001f  cmp      w0, #0
0x001000c4:  54ffff61  b.ne     #0x1000b0

----------------
IN:
0x00000200:  00000000  .byte    0x00, 0x00, 0x00, 0x00 // ??

As you can see, when the machine executes the jump, it receives an exception and jumps to the address 0x200, where the interrupt handler is placed (note, no interrupt handler has been configured, I've not implemented it yet) and gets stucked at address 0x200 executing an infinite loop (default behaviour when no interrupt handler is present). Now, from QEMU I was able to capture the type of exception:

Taking exception 1 [Undefined Instruction]
...from EL3 to EL3
...with ESR 0x0/0x2000000
...with ELR 0x200
...to EL3 PC 0x200 PSTATE 0x3cd

I'm compiling with the following command:

aarch64-elf-gcc -Wall -O0 -ffreestanding -nostdinc -nostdlib -nostartfiles -mcpu=cortex-a53 -g -c ... -o ...

I've also tried to see if this was a "compiler" problem, trying to execute the following totally useless code:

void a(){
  for(int j=0; j<10; j++);
  return;
}

void b(char* string){
  for(int i = 0; i<10; i++){
    a();
  }
  return;
}

void kernel_main(){

  a();
  b("test");

  while(1);

  return;
}

but the execution goes without any problem...
now I can't figure out what's going wrong. I mean, there is nothing bad in the C code producing that assembler, and addresses in the assembly code seems ok... any idea where the problem arises?? Why that Undefined Instruction exception?? If more information are needed I can provide more details


问:
No results in record set
I have a temporary table being created from a query. From that table I am selecting the items and placing them in a specific order to display in a listbox. Everything works great until I try to add a where clause to my select statement.

What I'd like to do is, when I run the query that isn't working below, just have the variables return as "0".

I have tried to do an if statement that just makes my variable "0", but I still get the same "No Current Record" error.

The below query it works fine;

  strQuery = "SELECT * FROM " & currentTime & " Order By CVT, CVY, CVW,
  AdjusterName"
```

<p>But when I add in a where clause of <=1 then I get a "No Current Record" error. The second query is;</p>

<pre class="lang-vb prettyprint-override"><code>  strQuery = "SELECT * FROM " & currentTime & " WHERE CVT <=1 Order By
  CVT, CVY, CVW, AdjusterName"
</code>```

When I run this second query I get a "No Current Record" error. This is where I'd like it to just display a zero instead.

Just in case it's needed, here is the entire function;

    If ClaimTypeCB = "MO" Then
        strQuery = "SELECT * FROM " & currentTime & " WHERE CVT <=1 Order
        By CVT, CVY, CVW, AdjusterName"
    Else
        strQuery = "SELECT * FROM " & currentTime & " Order By CVT, CVY,
        CVW, AdjusterName"
    End If
        Set daoQueryResult = db.OpenRecordset(strQuery)

        daoQueryResult.MoveLast
        intRecordCount = daoQueryResult.RecordCount
        daoQueryResult.MoveFirst

    If intRecordCount = 0 Then
        intCVT = 0
    End If
```

<p>(The above If Statement is where I tried to insert an If statement, but it didn't work, and I still get a "No Current Record" error.)</p>

<pre class="lang-vb prettyprint-override"><code>    If intRecordCount <> 0 Then
        With daoQueryResult
            Do While Not .EOF

                If IsNull(!CVT) Then
                    intCVT = 0
                Else
                    intCVT = !CVT
                End If

                If IsNull(!CVY) Then
                    intCVY = 0
                Else
                    intCVY = !CVY
                End If

                If IsNull(!CVW) Then
                    intCVW = 0
                Else
                    intCVW = (!CVW)
                End If

                AvailAdjList.AddItem !AdjusterName & "," & intCVT & "," & intCVY & "," & intCVW
                .MoveNext
            Loop
        End With
    End If
</code>```

I really just want CVT to return as zero if it is 0 or 1.

答:
Try this query:

```<code>strQuery = "SELECT CVT, CVY, CVW, AdjusterName FROM " & currentTime & " WHERE CVT <= 1 Order By CVT, CVY, CVW, AdjusterName" _
         & " UNION ALL " _
         & "SELECT DISTINCT 0, NULL, NULL, NULL FROM " & currentTime & " WHERE NOT EXISTS " _
         & "(SELECT 1 FROM " & currentTime & " WHERE CVT <= 1)"
</code>```

It uses UNION ALL so that if the 1st query does not return any rows, the 2nd query will return a row with values: 0, NULL, NULL, NULL

I hope I have no typos.

Title: No results in record set

Body:
I have a temporary table being created from a query. From that table I am selecting the items and placing them in a specific order to display in a listbox. Everything works great until I try to add a where clause to my select statement.

What I'd like to do is, when I run the query that isn't working below, just have the variables return as "0".

I have tried to do an if statement that just makes my variable "0", but I still get the same "No Current Record" error.

The below query it works fine;

  strQuery = "SELECT * FROM " & currentTime & " Order By CVT, CVY, CVW,
  AdjusterName"

But when I add in a where clause of <=1 then I get a "No Current Record" error. The second query is;

  strQuery = "SELECT * FROM " & currentTime & " WHERE CVT <=1 Order By
  CVT, CVY, CVW, AdjusterName"

When I run this second query I get a "No Current Record" error. This is where I'd like it to just display a zero instead.

Just in case it's needed, here is the entire function;

    If ClaimTypeCB = "MO" Then
        strQuery = "SELECT * FROM " & currentTime & " WHERE CVT <=1 Order
        By CVT, CVY, CVW, AdjusterName"
    Else
        strQuery = "SELECT * FROM " & currentTime & " Order By CVT, CVY,
        CVW, AdjusterName"
    End If
        Set daoQueryResult = db.OpenRecordset(strQuery)

        daoQueryResult.MoveLast
        intRecordCount = daoQueryResult.RecordCount
        daoQueryResult.MoveFirst

    If intRecordCount = 0 Then
        intCVT = 0
    End If

(The above If Statement is where I tried to insert an If statement, but it didn't work, and I still get a "No Current Record" error.)

    If intRecordCount <> 0 Then
        With daoQueryResult
            Do While Not .EOF

                If IsNull(!CVT) Then
                    intCVT = 0
                Else
                    intCVT = !CVT
                End If

                If IsNull(!CVY) Then
                    intCVY = 0
                Else
                    intCVY = !CVY
                End If

                If IsNull(!CVW) Then
                    intCVW = 0
                Else
                    intCVW = (!CVW)
                End If

                AvailAdjList.AddItem !AdjusterName & "," & intCVT & "," & intCVY & "," & intCVW
                .MoveNext
            Loop
        End With
    End If

I really just want CVT to return as zero if it is 0 or 1.

Body:
Try this query:

strQuery = "SELECT CVT, CVY, CVW, AdjusterName FROM " & currentTime & " WHERE CVT <= 1 Order By CVT, CVY, CVW, AdjusterName" _
         & " UNION ALL " _
         & "SELECT DISTINCT 0, NULL, NULL, NULL FROM " & currentTime & " WHERE NOT EXISTS " _
         & "(SELECT 1 FROM " & currentTime & " WHERE CVT <= 1)"

It uses UNION ALL so that if the 1st query does not return any rows, the 2nd query will return a row with values: 0, NULL, NULL, NULL

I hope I have no typos.


问:
VBA: Protecting Shape Objects only
I read quite a few posts but didn't find anything similar to what I'm trying to achieve. I basically have a few Shape objects in my worksheet which have macros assigned to them. I would like to protect these objects using VBA so users can interact with them but not edit them in any way. I however, would like the users(and my VBA) to be able to freely manipulate the rest of the workbook as they like.

I tried ActiveSheet.Protect DrawingObjects:=True but the problem is that the usability of the rest of the application is quite limited as well. For example I have a checkbox that hides/unhides a range of cells but when the sheet is protected, I cannot execute the macro and I get an exception. Is there a way to protect the Shape objects only and basically leave the rest of the workbook unrestricted as if the sheet was unprotected?

Thanks,
Dimitar

答:
If you omit the other parameters, you will get their default values. Do something like this instead:</p>

```<code>ActiveSheet.Protect DrawingObjects:=True, _
                    Contents:=False, _
                    Scenarios:=False, _
                    UserInterfaceOnly:=False, _
                    AllowFormattingCells:=True, _
                    AllowFormattingColumns:=True, _
                    AllowFormattingRows:=True, _
                    AllowInsertingColumns:=True, _
                    AllowInsertingRows:=True, _
                    AllowInsertingHyperlinks:=True, _
                    AllowDeletingColumns:=True, _
                    AllowDeletingRows:=True, _
                    AllowSorting:=True, _
                    AllowFiltering:=True, _
                    AllowUsingPivotTables:=True
</code>```

Title: VBA: Protecting Shape Objects only

Body:
If you omit the other parameters, you will get their default values. Do something like this instead:

ActiveSheet.Protect DrawingObjects:=True, _
                    Contents:=False, _
                    Scenarios:=False, _
                    UserInterfaceOnly:=False, _
                    AllowFormattingCells:=True, _
                    AllowFormattingColumns:=True, _
                    AllowFormattingRows:=True, _
                    AllowInsertingColumns:=True, _
                    AllowInsertingRows:=True, _
                    AllowInsertingHyperlinks:=True, _
                    AllowDeletingColumns:=True, _
                    AllowDeletingRows:=True, _
                    AllowSorting:=True, _
                    AllowFiltering:=True, _
                    AllowUsingPivotTables:=True


问:
Tombstone scanning in system.log
I have a cassandra cluster with less delete use case. I found in my system.log "Read 10 live and 5645464 tombstones cells in keyspace.table" What does it mean? please help to understand.

Thanks.

答:
For Cassandra, all the information recorded is immutable. This means that when you have a delete operation (explicit with a delete statement or with a Time To Live [TTL] clause), the database will add another record with a special flag named tombstone. All these records will stay on the database until the gc_grace_seconds periods have passed; the default is 10 days.

In your case, the engine found out that most of the records retrieved were deleted, but they are still waiting for the gc_grace_seconds to pass, to let compaction reclaim the space. One possible option to fix the issue is to decrease gc_grace_seconds for that table.

For more information, please refer to this article from the Last Pickle.

Title: Tombstone scanning in system.log


问:
Java Timer & KeyEvents problem
I have been making Tetris game and it's almost complete. I have a problem with KeyEvents and a Timer.

My Timer calls actionPerformed every 400ms which drops down tetris block. Problem is that if I press something from the keyboard (down, left, right etc), those commands are noted also every 400 milliseconds. How can I make the timer call actionPerformed every 400ms but so that I can press whenever and how many times I want something from the keyboard and it's instantly recognized/responded to?

EDIT: Here's some of code like people asked

```<code>public class Game extends JPanel implements ActionListener {

public static final HashMap<Character, Color> colors = new HashMap<Character,Color>();
Timer timer;
Block kpl;
Grid gameBoard;
char[][] grid;
boolean paused = false;

public Game() {

    colors.put('P', Color.blue); colors.put('S', Color.green);
    colors.put('D', Color.pink); colors.put('L', Color.red);
    colors.put('Z', Color.orange); colors.put('A', Color.cyan);
    colors.put('T', Color.magenta);
    kpl = new Block();
    gameBoard = new Grid(21,10); // 21x10 sized gameboard
    grid = gameBoard.getGrid();
    addKeyListener(new KeyListening());
    setDoubleBuffered(true);
    setFocusable(true);
    timer = new Timer(100, this);
    timer.start();

}

@Override
public void paint(Graphics g) { // draws the current game situation
    super.paint(g);

        int height = getHeight()/grid.length;
        int width = getWidth()/grid[0].length/2;

        for (int row = 0; row < grid.length; ++row) {
            for (int column = 0; column < grid[row].length; ++column) {

                if (grid[row][column] == '.') { // if empty, paint white
                    g.setColor(Color.white);
                    g.fillRect(column*width, row*height , width, height);
                    g.setColor(Color.LIGHT_GRAY);
                    g.drawRect(column*width, row*height , width, height);
                }
                else if (grid[row][column] != '.') { // if not empty, paint with the color of the block
                    g.setColor(colors.get(grid[row][column]));
                    g.fillRect(column*width, row*height , width, height);
                    g.setColor(Color.BLACK);
                    g.drawRect(column*width, row*height , width, height);
                }
            }
        }

    Toolkit.getDefaultToolkit().sync();
    g.dispose();
}

public void actionPerformed(ActionEvent e) {
    if (!gameBoard.isFallingBlock())
        gameBoard.drop(kpl); // if not any falling blocks, drops a new block

    gameBoard.updateView(); // moves the block down
    repaint();
}

    private class KeyListening extends KeyAdapter {

    @Override
    public void keyPressed(KeyEvent e) {

        int key = e.getKeyCode();

        switch (key) {
            case KeyEvent.VK_LEFT:
                gameBoard.move("v"); // moves block left
                break;
            case KeyEvent.VK_RIGHT:
                gameBoard.move("o"); // moves block right
                break;
            case KeyEvent.VK_DOWN:
                gameBoard.updateView(); // moves block down
                break;
            case KeyEvent.VK_SPACE:
                gameBoard.move("p"); // drops the block to the bottom
                break;
            case KeyEvent.VK_UP: // rotates block
                gameBoard.move("k");
                break;
            case KeyEvent.VK_P: // makes the game pause
                if (paused) {
                    timer.start();
                    paused = false;
                    return;
                }

                timer.stop();
                paused = true;
                break;

        }

    }

}
</code>```

}

Had to translate the variables a little since I have been naming them with my own language. GUI is also pretty simple since I made first a text version of my Tetris so it basically runs the text version of it in the background and just paints the situation of the game.

Text version itself is char typed matrix where I move the blocks, for example:

```<code>..P..
..ppp
.....
.....
</code>```

SOLVED:

Problem solved! In public void keyPressed() after every command coming from keyboard I just called repaint()-method again like

```<code>        public void keyPressed(KeyEvent e) {

        int key = e.getKeyCode();
        switch (key) {
            case KeyEvent.VK_LEFT:
                gameBoard.move("v");
                repaint();
                break;
</code>```

Originally my game responded to my keyboard commands instantly but drew the current state of game every 400ms in actionPerformed() where the repaint() was called. Now my blocks can be moved whenever I want without any "delay" and they're still dropping steady every 400ms :)

答: You need to make sure you are using a Swing Timer and are not blocking the Event Dispatching Thread. More than likely you need a separate actionPerformed method to handle the key events than the block drops.

Title: Java Timer & KeyEvents problem

Body:
I have been making Tetris game and it's almost complete. I have a problem with KeyEvents and a Timer.

My Timer calls actionPerformed every 400ms which drops down tetris block. Problem is that if I press something from the keyboard (down, left, right etc), those commands are noted also every 400 milliseconds. How can I make the timer call actionPerformed every 400ms but so that I can press whenever and how many times I want something from the keyboard and it's instantly recognized/responded to?

EDIT: Here's some of code like people asked

public class Game extends JPanel implements ActionListener {

public static final HashMap<Character, Color> colors = new HashMap<Character,Color>();
Timer timer;
Block kpl;
Grid gameBoard;
char[][] grid;
boolean paused = false;

public Game() {

    colors.put('P', Color.blue); colors.put('S', Color.green);
    colors.put('D', Color.pink); colors.put('L', Color.red);
    colors.put('Z', Color.orange); colors.put('A', Color.cyan);
    colors.put('T', Color.magenta);
    kpl = new Block();
    gameBoard = new Grid(21,10); // 21x10 sized gameboard
    grid = gameBoard.getGrid();
    addKeyListener(new KeyListening());
    setDoubleBuffered(true);
    setFocusable(true);
    timer = new Timer(100, this);
    timer.start();

}

@Override
public void paint(Graphics g) { // draws the current game situation
    super.paint(g);

        int height = getHeight()/grid.length;
        int width = getWidth()/grid[0].length/2;

        for (int row = 0; row < grid.length; ++row) {
            for (int column = 0; column < grid[row].length; ++column) {

                if (grid[row][column] == '.') { // if empty, paint white
                    g.setColor(Color.white);
                    g.fillRect(column*width, row*height , width, height);
                    g.setColor(Color.LIGHT_GRAY);
                    g.drawRect(column*width, row*height , width, height);
                }
                else if (grid[row][column] != '.') { // if not empty, paint with the color of the block
                    g.setColor(colors.get(grid[row][column]));
                    g.fillRect(column*width, row*height , width, height);
                    g.setColor(Color.BLACK);
                    g.drawRect(column*width, row*height , width, height);
                }
            }
        }

    Toolkit.getDefaultToolkit().sync();
    g.dispose();
}

public void actionPerformed(ActionEvent e) {
    if (!gameBoard.isFallingBlock())
        gameBoard.drop(kpl); // if not any falling blocks, drops a new block

    gameBoard.updateView(); // moves the block down
    repaint();
}

    private class KeyListening extends KeyAdapter {

    @Override
    public void keyPressed(KeyEvent e) {

        int key = e.getKeyCode();

        switch (key) {
            case KeyEvent.VK_LEFT:
                gameBoard.move("v"); // moves block left
                break;
            case KeyEvent.VK_RIGHT:
                gameBoard.move("o"); // moves block right
                break;
            case KeyEvent.VK_DOWN:
                gameBoard.updateView(); // moves block down
                break;
            case KeyEvent.VK_SPACE:
                gameBoard.move("p"); // drops the block to the bottom
                break;
            case KeyEvent.VK_UP: // rotates block
                gameBoard.move("k");
                break;
            case KeyEvent.VK_P: // makes the game pause
                if (paused) {
                    timer.start();
                    paused = false;
                    return;
                }

                timer.stop();
                paused = true;
                break;

        }

    }

}

}

Had to translate the variables a little since I have been naming them with my own language. GUI is also pretty simple since I made first a text version of my Tetris so it basically runs the text version of it in the background and just paints the situation of the game.

Text version itself is char typed matrix where I move the blocks, for example:

..P..
..ppp
.....
.....

SOLVED:

Problem solved! In public void keyPressed() after every command coming from keyboard I just called repaint()-method again like

        public void keyPressed(KeyEvent e) {

        int key = e.getKeyCode();
        switch (key) {
            case KeyEvent.VK_LEFT:
                gameBoard.move("v");
                repaint();
                break;

Originally my game responded to my keyboard commands instantly but drew the current state of game every 400ms in actionPerformed() where the repaint() was called. Now my blocks can be moved whenever I want without any "delay" and they're still dropping steady every 400ms :)


问:
How to display different data on one php page without using the GET method
I am developing a simple profile website that allows different users to create a profile and share their profile link so that other can view their profile. I need to use one page to output the profile data instead of creating several pages for each user.

I am using Xampp version 7.3.5-0 runing Apache Server and PHP7.
My current profile link is pro/profile/?user=mike, where pro/ is the site URL, profile is a folder containing index.php file to display the user profile and ?user=mike is the query string. Mike in this query string is the username of the current profile to view, if you want to view the profile for another user, say John, you just replace 'mike' with 'john'.
Below is a sample query code and error code in index.php file available in the /profile folder:

```<code> <?php
  require('db_connect.php');
  $username=($_GET['user']);
  $result=mysqli_query($db_connect,"SELECT * FROM  users WHERE
  username='$username' LIMIT 1");
  $count=mysqli_num_rows($result);
  while($row=mysqli_fetch_array($result)){
?>

<?php
  if ($count==0) {
    echo "Oops! No information was found for $username";
   }else{
   echo "";
}
?>
</code>```

Currently if I want to view profiles for three people, say mike, john and hilda, I will use:
1. pro/profile/?user=mike
2. pro/profile/?user=john
3. pro/profile/?user=hilda
If I input a user that does not exist, it will display the error message above.

Now I would like to use a different code that will output the user profile without using the GET method, but still using one index.php file instead of creating a folder and a page for each user because there are hundreds of users. The links would change to these:
1. pro/profile/mike
2. pro/profile/john
3. pro/profile/hilda

I don't know if it is possible, please help.

答:
You can easily get the username from the url path like this:

$path = parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH);
$parts = explode('/', $path);
$username = end($parts);
```

<p>or you can use: </p>

```$username = basename(parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH));
```

Body:
I am developing a simple profile website that allows different users to create a profile and share their profile link so that other can view their profile. I need to use one page to output the profile data instead of creating several pages for each user.

I am using Xampp version 7.3.5-0 runing Apache Server and PHP7.
My current profile link is pro/profile/?user=mike, where pro/ is the site URL, profile is a folder containing index.php file to display the user profile and ?user=mike is the query string. Mike in this query string is the username of the current profile to view, if you want to view the profile for another user, say John, you just replace 'mike' with 'john'.
Below is a sample query code and error code in index.php file available in the /profile folder:

 <?php
  require('db_connect.php');
  $username=($_GET['user']);
  $result=mysqli_query($db_connect,"SELECT * FROM  users WHERE
  username='$username' LIMIT 1");
  $count=mysqli_num_rows($result);
  while($row=mysqli_fetch_array($result)){
?>

<?php
  if ($count==0) {
    echo "Oops! No information was found for $username";
   }else{
   echo "";
}
?>

Currently if I want to view profiles for three people, say mike, john and hilda, I will use:
1. pro/profile/?user=mike
2. pro/profile/?user=john
3. pro/profile/?user=hilda
If I input a user that does not exist, it will display the error message above.

Now I would like to use a different code that will output the user profile without using the GET method, but still using one index.php file instead of creating a folder and a page for each user because there are hundreds of users. The links would change to these:
1. pro/profile/mike
2. pro/profile/john
3. pro/profile/hilda

I don't know if it is possible, please help.

Body:
You can easily get the username from the url path like this:

$path = parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH);
$parts = explode('/', $path);
$username = end($parts);

or you can use:

$username = basename(parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH));


问:
gcloud Firebase Android Test: Unable to access the test environment catalog: ResponseError 403: Not authorized for project
What I did:

I set up gcloud on a jenkins docker container with this guide:
https://firebase.google.com/docs/test-lab/continuous

What I want to execute:

```<code>gcloud firebase test android run --app ./app/build/outputs/apk/app-debug.apk
</code>```

The error I get:

```<code>ERROR: (gcloud.firebase.test.android.run) Unable to access the test environment catalog: ResponseError 403: Not authorized for project <project-id>
</code>```

Question

What am I doing wrong? I tried to add the service account under IAM with all Service-Account rules, but this didn't help.

Is it possible to enable these APIs specially for the service-account? I did so only for the complete project and gmail account: Enable required APIs. After logging in using the service account: "In the Google Developers Console API Library page, enable the Google Cloud Testing API and Cloud Tool Results API. To enable these APIs, type these API names into the search box at the top of the console, and then click Enable API on the overview page for that API. "

My steps so far in detail:

```<code>docker exec -it container bash

export CLOUD_SDK_REPO="cloud-sdk-$(lsb_release -c -s)"
echo "deb http://packages.cloud.google.com/apt $CLOUD_SDK_REPO main" | sudo tee -a /etc/apt/sources.list.d/google-cloud-sdk.list
curl https://packages.cloud.google.com/apt/doc/apt-key.gpg | sudo apt-key add -
sudo apt-get update && sudo apt-get install google-cloud-sdk
gcloud init

# only if this service account does not already exist:
# gcloud iam service-accounts create continuous-integration

gcloud iam service-accounts keys create $JENKINS_HOME/gce-continuous-integration-key.json --iam-account=continuous-integration@<project-id>.iam.gserviceaccount.com

gcloud auth activate-service-account continuous-integration@<project-id>.iam.gserviceaccount.com --key-file=$JENKINS_HOME/gce-continuous-integration-key.json

gcloud auth login continuous-integration@<project-id>.iam.gserviceaccount.com

jenkins@VM:/$ gcloud config list
# returns:
[compute]
region = europe-west3
zone = europe-west3-c
[core]
account = continuous-integration@<project-id>.iam.gserviceaccount.com
disable_usage_reporting = True
project = <project-id>
Your active configuration is: [default]
</code>```

答:
Editor role does not worked for me, In my case, I was creating the service account from the IAM page, but it turns out that some things are missing from there, so what you need to do is "generate a private key" in https://console.firebase.google.com/u/0/project/my-project/settings/serviceaccounts/adminsdk

I mean: Settings/Service accounts/Firebase Admin SDK -> Generate Private Key.

Body:
What I did:

I set up gcloud on a jenkins docker container with this guide:
https://firebase.google.com/docs/test-lab/continuous

What I want to execute:

gcloud firebase test android run --app ./app/build/outputs/apk/app-debug.apk

The error I get:

ERROR: (gcloud.firebase.test.android.run) Unable to access the test environment catalog: ResponseError 403: Not authorized for project <project-id>

Question

What am I doing wrong? I tried to add the service account under IAM with all Service-Account rules, but this didn't help.

Is it possible to enable these APIs specially for the service-account? I did so only for the complete project and gmail account: Enable required APIs. After logging in using the service account: "In the Google Developers Console API Library page, enable the Google Cloud Testing API and Cloud Tool Results API. To enable these APIs, type these API names into the search box at the top of the console, and then click Enable API on the overview page for that API. "

My steps so far in detail:

docker exec -it container bash

export CLOUD_SDK_REPO="cloud-sdk-$(lsb_release -c -s)"
echo "deb http://packages.cloud.google.com/apt $CLOUD_SDK_REPO main" | sudo tee -a /etc/apt/sources.list.d/google-cloud-sdk.list
curl https://packages.cloud.google.com/apt/doc/apt-key.gpg | sudo apt-key add -
sudo apt-get update && sudo apt-get install google-cloud-sdk
gcloud init

# only if this service account does not already exist:
# gcloud iam service-accounts create continuous-integration

gcloud iam service-accounts keys create $JENKINS_HOME/gce-continuous-integration-key.json --iam-account=continuous-integration@<project-id>.iam.gserviceaccount.com

gcloud auth activate-service-account continuous-integration@<project-id>.iam.gserviceaccount.com --key-file=$JENKINS_HOME/gce-continuous-integration-key.json

gcloud auth login continuous-integration@<project-id>.iam.gserviceaccount.com

jenkins@VM:/$ gcloud config list
# returns:
[compute]
region = europe-west3
zone = europe-west3-c
[core]
account = continuous-integration@<project-id>.iam.gserviceaccount.com
disable_usage_reporting = True
project = <project-id>
Your active configuration is: [default]


问:
laravel prevent go back after order placed in ecommerce
How to prevent Laravel page from going back after order placed to not make a double payment. I've got many related answers but none of them work with me.

I've tried makeing a middleware class and call header code

and called it from route file

return $response->header('Cache-Control','no-store, nocache, no-store, max-age=0, must-revalidate')
->header('Pragma','no-cache')
->header('Expires','Sun, 02 Jan 1990 00:00:00 GMT')
->header('Cache-Control',' post-check=0, pre-check=0, false');
```

<p>and then I've called the class in route like this:</p>

<pre class="lang-php prettyprint-override"><code>Route::group(['middleware' => 'prevent-order-back'],function(){
        Auth::routes();
        //Route::get('/home', 'HomeController@index');
        Route::post('/place_order', 'OrdersController@place_order');
    });
</code>```

I'm using Laravel 5.5

答:
Adding the following after the the code in the place_order function in the OrdersController might solve your problem:
return redirect(view('<path to order placed page or index>')).
using a redirect from the controller prevents the browser from sending the data again.
more info about how to implement the redirects is available in the Laravel documentation

Body:
How to prevent Laravel page from going back after order placed to not make a double payment. I've got many related answers but none of them work with me.

I've tried makeing a middleware class and call header code

and called it from route file

return $response->header('Cache-Control','no-store, nocache, no-store, max-age=0, must-revalidate')
->header('Pragma','no-cache')
->header('Expires','Sun, 02 Jan 1990 00:00:00 GMT')
->header('Cache-Control',' post-check=0, pre-check=0, false');

and then I've called the class in route like this:

Route::group(['middleware' => 'prevent-order-back'],function(){
        Auth::routes();
        //Route::get('/home', 'HomeController@index');
        Route::post('/place_order', 'OrdersController@place_order');
    });

I'm using Laravel 5.5


问:
Printing Float Value to STDOUT in assembly linux
I'm trying to print float values to console but it gives unexpected results too large number having different sign.

Program

```<code>.data
    float_: .asciz "%f\n"
    n1: .float 10.4
        n2: .float 10.3
.text

.globl main

main:
    sub $1, %esp
    finit
    flds n1
    fsubs n2
    fsts 1(%esp)

    movl 1(%esp), %eax
    call pfl
    addl $1, %esp

.exit:
    movl $1, %eax
    movl $0, %ebx
    int $0x80

pfl:
    pushal
    push %eax
    push $float_
    call printf
    add $8, %esp
    popal
    ret
</code>```

Output

Different every time but between -400...0.0... to -500000..0.0...

答:
Various problems with your code. Most importantly, %f expects a double but you pass a float. See man 3 printf or a C book. Furthermore a float is 4 bytes so you'd be well advised to allocate 4 bytes not 1. To make matters worse, you are not even using the 1 byte allocated since that is at (%esp) but you used 1(%esp). For a double you will need 8 bytes. Next, you forgot to pop the value from the FPU. Also, current calling conventions require 16 byte aligned stack, even in 32 bit mode.

Finally, it's not recommended to use the exit system call directly in main or other code that uses libc function.  Instead, just ret or call exit if you really insist to make sure libc cleanup (like flushing stdio buffers) happens.  Otherwise you'll get no output if you redirect stdout to a file so it's full-buffered.

Here is a possible version fixing all of the above:

```<code>.data
    float_: .asciz "%f\n"
    n1: .float 10.4
    n2: .float 10.3
.text

.globl main

main:
    sub $12, %esp      # 8 bytes for double, + 4 bytes for alignment
    flds n1
    fsubs n2
    fstpl (%esp)       # pop double from fpu

    movl (%esp), %eax  # low 4 bytes
    movl 4(%esp), %edx # high 4 bytes
    call pfl
    addl $12, %esp

    ret

## input: EDX:EAX = the bit-pattern for a double
pfl:
    push %edx
    push %eax
    push $float_      # 3x push realigns the stack by 16 again
    call printf
    add $12, %esp
    ret
</code>```

Bouncing your double through integer registers is unnecessary; if you inlined call printf into your main function you could have just used fstpl to put the double on the stack right above a pointer to the format string.

Or made your pfl function takes its input in %st(0) instead of integer registers, since you're making up a custom calling convention anyway.

(I assume your next question is going to be why it prints 0.099999 instead of 0.1 :))

Body:
I'm trying to print float values to console but it gives unexpected results too large number having different sign.

Program

.data
    float_: .asciz "%f\n"
    n1: .float 10.4
        n2: .float 10.3
.text

.globl main

main:
    sub $1, %esp
    finit
    flds n1
    fsubs n2
    fsts 1(%esp)

    movl 1(%esp), %eax
    call pfl
    addl $1, %esp

.exit:
    movl $1, %eax
    movl $0, %ebx
    int $0x80

pfl:
    pushal
    push %eax
    push $float_
    call printf
    add $8, %esp
    popal
    ret

Output

Different every time but between -400...0.0... to -500000..0.0...

Body:
Various problems with your code. Most importantly, %f expects a double but you pass a float. See man 3 printf or a C book. Furthermore a float is 4 bytes so you'd be well advised to allocate 4 bytes not 1. To make matters worse, you are not even using the 1 byte allocated since that is at (%esp) but you used 1(%esp). For a double you will need 8 bytes. Next, you forgot to pop the value from the FPU. Also, current calling conventions require 16 byte aligned stack, even in 32 bit mode.

Finally, it's not recommended to use the exit system call directly in main or other code that uses libc function.  Instead, just ret or call exit if you really insist to make sure libc cleanup (like flushing stdio buffers) happens.  Otherwise you'll get no output if you redirect stdout to a file so it's full-buffered.

Here is a possible version fixing all of the above:

.data
    float_: .asciz "%f\n"
    n1: .float 10.4
    n2: .float 10.3
.text

.globl main

main:
    sub $12, %esp      # 8 bytes for double, + 4 bytes for alignment
    flds n1
    fsubs n2
    fstpl (%esp)       # pop double from fpu

    movl (%esp), %eax  # low 4 bytes
    movl 4(%esp), %edx # high 4 bytes
    call pfl
    addl $12, %esp

    ret

## input: EDX:EAX = the bit-pattern for a double
pfl:
    push %edx
    push %eax
    push $float_      # 3x push realigns the stack by 16 again
    call printf
    add $12, %esp
    ret

Bouncing your double through integer registers is unnecessary; if you inlined call printf into your main function you could have just used fstpl to put the double on the stack right above a pointer to the format string.

Or made your pfl function takes its input in %st(0) instead of integer registers, since you're making up a custom calling convention anyway.

(I assume your next question is going to be why it prints 0.099999 instead of 0.1 :))


答:
Label should come after checkbox in your case.

label{
 display:inline-block;
    padding:10px;
    background: #eee;
}
.notificationImgs {
 width: 70px;
 height: auto;
 margin: 0 20px;
 cursor: pointer;
}
.notifCheck {
 display: none;
}
.notifCheck:checked + label {
 background: #aaa;
}
.notifCheck:checked .notificationImgs {
 background-color: #aaa;
 width: 100%;
 height: 70px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><input type="checkbox" name="checkText" class="notifCheck" id="checkText" value="text">
<label for="checkText">
  <img src="https://images.pexels.com/photos/67636/rose-blue-flower-rose-blooms-67636.jpeg?auto=compress&cs=tinysrgb&dpr=1&w=500" alt="Text Notifications" class="notificationImgs">
</label>

<input type="checkbox" name="checkEmail" class="notifCheck" id="checkEmail" value="text">
<label for="checkEmail">
  <img src="https://images.pexels.com/photos/67636/rose-blue-flower-rose-blooms-67636.jpeg?auto=compress&cs=tinysrgb&dpr=1&w=500" alt="Email Notifications" class="notificationImgs">
</label></code>```

Title: Change the background of a label when acting as checkbox

Body:
Label should come after checkbox in your case.

label{
 display:inline-block;
    padding:10px;
    background: #eee;
}
.notificationImgs {
 width: 70px;
 height: auto;
 margin: 0 20px;
 cursor: pointer;
}
.notifCheck {
 display: none;
}
.notifCheck:checked + label {
 background: #aaa;
}
.notifCheck:checked .notificationImgs {
 background-color: #aaa;
 width: 100%;
 height: 70px;
}

<input type="checkbox" name="checkText" class="notifCheck" id="checkText" value="text">
<label for="checkText">
  <img src="https://images.pexels.com/photos/67636/rose-blue-flower-rose-blooms-67636.jpeg?auto=compress&cs=tinysrgb&dpr=1&w=500" alt="Text Notifications" class="notificationImgs">
</label>

<input type="checkbox" name="checkEmail" class="notifCheck" id="checkEmail" value="text">
<label for="checkEmail">
  <img src="https://images.pexels.com/photos/67636/rose-blue-flower-rose-blooms-67636.jpeg?auto=compress&cs=tinysrgb&dpr=1&w=500" alt="Email Notifications" class="notificationImgs">
</label>


问:
Vue js form submission method
I'm relatively new to Vuejs & am trying to get this form working but it keeps showing me these errors when i submit. Can anyone guide me on this?

```<code><template>
  <form @submit.prevent="handleSubmit">
    <input class="input" type="text" v-model="user.name">
    <input class="input" type="text" v-model="user.email">
    <input class="input" type="text" v-model="user.phone">
    <button class="button is-primary" type="submit">Submit</button>
  </form>
</template>

<script>
export default {
  data() {
    return {
      user: {
        name: '',
        email: '',
        phone: ''
      },
      test: "BEFORE SUBMIT"
    };
  },
  method: {
    handleSubmit() {
      let user = new user({
        name: this.user.name,
        email: this.user.email,
        phone: this.user.phone,
      });

      this.test = "AFTER SUBMIT";
    }
  }
};
</script>
</code>```

答:
You're calling handleSubmit method but you haven't defined it on the Vue instance.

That's because you should call the Vue instance property methods, not method, even when you have only 1 method.

Title: Vue js form submission method

Body:
I'm relatively new to Vuejs & am trying to get this form working but it keeps showing me these errors when i submit. Can anyone guide me on this?

<template>
  <form @submit.prevent="handleSubmit">
    <input class="input" type="text" v-model="user.name">
    <input class="input" type="text" v-model="user.email">
    <input class="input" type="text" v-model="user.phone">
    <button class="button is-primary" type="submit">Submit</button>
  </form>
</template>


问:
plot_summs() change size of plotted regression coefficients
I'm using plot_summs() from the jtools package to plot regression coefficients. I'm trying to make the plot big enough to see for a presentation and I figured out how to change the size of everything except the actual plotted coefficients (see the example plot below).

Anyone have any ideas how to make the plotted coefficients bigger?

```<code>#example data and models
states <- as.data.frame(state.x77)
fit1 <- lm(Income ~ Frost + Illiteracy + Murder +
         Population + Area + `Life Exp` + `HS Grad`,
       data = states, weights = runif(50, 0.1, 3))
fit2 <- lm(Income ~ Frost + Illiteracy + Murder +
         Population + Area + `Life Exp` + `HS Grad`,
       data = states, weights = runif(50, 0.1, 3))
fit3 <- lm(Income ~ Frost + Illiteracy + Murder +
         Population + Area + `Life Exp` + `HS Grad`,
       data = states, weights = runif(50, 0.1, 3))

# Plot all 3 regressions with custom predictor labels,
# standardized coefficients, and robust standard errors
testplot <- plot_summs(fit1, fit2, fit3, coefs = c("Frost Days" =
     "Frost", "% Illiterate" = "Illiteracy","Murder Rate" = "Murder"),
                   scale = TRUE, robust = TRUE)

#custom theme to format
apatheme=theme_bw()+
theme(panel.grid.major=element_blank(),
    panel.grid.minor=element_blank(),
    panel.border=element_blank(),
    axis.line=element_line(),
    text=element_text(family='Helvetica'),
    legend.title=element_blank(),
    axis.text=element_text(size=25),
    axis.title=element_text(size=15),
    legend.text = element_text(size = 20))

testplot  + apatheme + labs(x = "\n Beta Estimate \n ", y = NULL)
</code>```

答:
You have to set the height and width that you want. At the top of your code type this:

```<code>plot.new()
dev.new(width=5, height=4)
</code>```

Adjust the width and height as needed.

Body:
I'm using plot_summs() from the jtools package to plot regression coefficients. I'm trying to make the plot big enough to see for a presentation and I figured out how to change the size of everything except the actual plotted coefficients (see the example plot below).

Anyone have any ideas how to make the plotted coefficients bigger?

#example data and models
states <- as.data.frame(state.x77)
fit1 <- lm(Income ~ Frost + Illiteracy + Murder +
         Population + Area + `Life Exp` + `HS Grad`,
       data = states, weights = runif(50, 0.1, 3))
fit2 <- lm(Income ~ Frost + Illiteracy + Murder +
         Population + Area + `Life Exp` + `HS Grad`,
       data = states, weights = runif(50, 0.1, 3))
fit3 <- lm(Income ~ Frost + Illiteracy + Murder +
         Population + Area + `Life Exp` + `HS Grad`,
       data = states, weights = runif(50, 0.1, 3))

# Plot all 3 regressions with custom predictor labels,
# standardized coefficients, and robust standard errors
testplot <- plot_summs(fit1, fit2, fit3, coefs = c("Frost Days" =
     "Frost", "% Illiterate" = "Illiteracy","Murder Rate" = "Murder"),
                   scale = TRUE, robust = TRUE)

#custom theme to format
apatheme=theme_bw()+
theme(panel.grid.major=element_blank(),
    panel.grid.minor=element_blank(),
    panel.border=element_blank(),
    axis.line=element_line(),
    text=element_text(family='Helvetica'),
    legend.title=element_blank(),
    axis.text=element_text(size=25),
    axis.title=element_text(size=15),
    legend.text = element_text(size = 20))

testplot  + apatheme + labs(x = "\n Beta Estimate \n ", y = NULL)

Body:
You have to set the height and width that you want. At the top of your code type this:

plot.new()
dev.new(width=5, height=4)

Adjust the width and height as needed.


问:
Speed up reading/hashing millions of files/images
I have directories containing 100K - 1 million images. I'm going to create a hash for each image so that I can, in the future, find an exact match based on these hashes. My current approach is:

def hash_test(images):      # images is a list of image paths
    hashes = []
    for image in images:
        with open(folder + image, 'rb', buffering=0) as f:
           hashes.append(hashlib.sha256(f.read()).hexdigest())
           # hashes.append(CityHash128(f.read()))
    return hashes
```

```31%|███       | 102193/334887 [00:04<42:15, 112.02it/s]
```

Of what I can tell from my experiments, the file.read() operation is my bottleneck, which means that I am I/O bound. This is also confirmed by checking iotop . I am reading from a HDD. I have read about memory-mapped reading, but couldn't get my head around whether it was applicable in this situation or not.

My question is: is there a way to optimize this reading operation?

答:
It's also possible that the problem has to do with the number of files in a directory. Some file systems experience severely degraded performance when you get many thousands of files in a single directory. If you have 100K or more files in a single directory, it takes significant time for the file system just to find the file before opening and reading it.

That said, let's think about this a bit. If I'm reading your output correctly, your program completed approximately 102K out of 335K files in four hours and 42 minutes. In round numbers, that's about 6 files per second. So it'll take about 15.5 hours to do all 335K files.

If this is a one-time task, then just set it up to run overnight, and it'll be done when you get back to work in the morning. If you have to index a million files, start the process on Friday night and it'll be done when you get into the office on Monday.

If it's not a one-time task, then you have other problems . . .

Body:
I have directories containing 100K - 1 million images. I'm going to create a hash for each image so that I can, in the future, find an exact match based on these hashes. My current approach is:

def hash_test(images):      # images is a list of image paths
    hashes = []
    for image in images:
        with open(folder + image, 'rb', buffering=0) as f:
           hashes.append(hashlib.sha256(f.read()).hexdigest())
           # hashes.append(CityHash128(f.read()))
    return hashes

31%|███       | 102193/334887 [00:04<42:15, 112.02it/s]

Of what I can tell from my experiments, the file.read() operation is my bottleneck, which means that I am I/O bound. This is also confirmed by checking iotop . I am reading from a HDD. I have read about memory-mapped reading, but couldn't get my head around whether it was applicable in this situation or not.

My question is: is there a way to optimize this reading operation?


问:
How to compare two @ character in clojure
Please, how can I write this in clojure? I have an @ character and I want to compare it to "@".

eg (= @ "@")

gives error (ClassCastException java.lang.String cannot be cast to java.util.concurrent.Future  clojure.core/deref-future (core.clj:2206))

答:
Yoy can quote your @ using \@ for Clojure to interpret it as a character literal. By default @ is a reader macro for a deref form to make many other things in clojure less verbose. Anyway:

```<code>(= \@ \@)

true
</code>```

If you want to check that the first character of a string is a @ then:

```<code>(= \@ (first "@"))

true
</code>```

The following only works in Clojurescript as it doesn't have a character type and just uses strings of length one.

```<code>(= \@ "@")

true ;; in cljs only
</code>```

Body:
Yoy can quote your @ using \@ for Clojure to interpret it as a character literal. By default @ is a reader macro for a deref form to make many other things in clojure less verbose. Anyway:

(= \@ \@)

true

If you want to check that the first character of a string is a @ then:

(= \@ (first "@"))

true

The following only works in Clojurescript as it doesn't have a character type and just uses strings of length one.

(= \@ "@")

true ;; in cljs only


问:
Retrieve values from related table foreign key using Eloquent
Sorry if the question isn't clear.. I'm not super fluent in databases.

I have three tables:

```<code> companies       equipment          parts
-----------     -----------      -----------
id               id               id
name             company_id       equipment_id

</code>```

Using Eloquent, how do I get a Collection of all the parts that belong to the company with id=1

I know you setup relationships in the model. So now I can get all a company's equipment ($myCompany->equipment), and all equipment's parts ($myEquipment->parts), but I'm not sure how to easily get values in the reverse direction two tables away.

Thanks!

答:
Laravel has such a beautiful documentation and API for this very thing. Take a look at the hasManyThrough relationship.

So in your Company model add this:

```<code>/**
 * Get all of the parts for the company.
 */
public function parts()
{
    return $this->hasManyThrough('App\Part', 'App\Equipment');
}
</code>```

Body:
Sorry if the question isn't clear.. I'm not super fluent in databases.

I have three tables:

 companies       equipment          parts
-----------     -----------      -----------
id               id               id
name             company_id       equipment_id

Using Eloquent, how do I get a Collection of all the parts that belong to the company with id=1

I know you setup relationships in the model. So now I can get all a company's equipment ($myCompany->equipment), and all equipment's parts ($myEquipment->parts), but I'm not sure how to easily get values in the reverse direction two tables away.

Thanks!

Body:
Laravel has such a beautiful documentation and API for this very thing. Take a look at the hasManyThrough relationship.

So in your Company model add this:

/**
 * Get all of the parts for the company.
 */
public function parts()
{
    return $this->hasManyThrough('App\Part', 'App\Equipment');
}


问:
authorize.net mac API
I have built a kiosk environment in MAC OSX 10.6.6 and i wanto charge a PC user before he starts using the system. i have the application made. I wanto use authorize.net for authenticating. With what i have searched, CIM SOAP is the method i should use.

My question is is there any webservice available on authorize.net where i can send a xml file and expect a response .? If not, what other options do i have??

thanks in advance. If any sample code or reference is there, let me know( FOR MAC)

答:
Authorize.Net's API is platform agnostic so it doesn't matter what environment you use it in. It can be a Mac, PC, POS system, or website, etc.

Their AIM API has an XML interface for processing transactions. You can get a developer's account to test your integration with. They also offer sample code to get you started.

Title: authorize.net mac API


问:
Found reliance on default encoding: new java.io.FileWriter(File, boolean)
I'm using FileWrite class to write into a file.and its working fine. But FindBugs is pointing me a Minor issue in my code snippet.

code snippet:

```<code>  SimpleDateFormat formatter = new SimpleDateFormat("yyyy_MM_dd");
        Date now = new Date();
        String fileName = formatter.format(now) + ".txt";
        FileWriter writer = null;
        try {
            File root = new File(Environment.getExternalStorageDirectory(), "Test");
            if (!root.exists()) {
                root.mkdirs();
            }
            File gpxfile = new File(root, fileName);

            writer = new FileWriter(gpxfile, true);
            writer.append(text + "\n\n");

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

        } finally {
            if (writer != null) {
                try {
                    writer.flush();
                    writer.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
</code>```

Findbug Report:

Reliance on default encoding
Found reliance on default encoding: new java.io.FileWriter(File, boolean)

In which line i'm getting this Error?

```<code>  writer = new FileWriter(gpxfile, true);
</code>```

Could some one please brief me what is this exactly?
And how can we solve this?

答:
```<code>File file = new File(someFilePath);
Writer w = new OutputStreamWriter(new FileOutputStream(file), "UTF-8");
PrintWriter pw = new PrintWriter(w);
pw.println(someContent);
pw.close();
</code>```

Body:
I'm using FileWrite class to write into a file.and its working fine. But FindBugs is pointing me a Minor issue in my code snippet.

code snippet:

  SimpleDateFormat formatter = new SimpleDateFormat("yyyy_MM_dd");
        Date now = new Date();
        String fileName = formatter.format(now) + ".txt";
        FileWriter writer = null;
        try {
            File root = new File(Environment.getExternalStorageDirectory(), "Test");
            if (!root.exists()) {
                root.mkdirs();
            }
            File gpxfile = new File(root, fileName);

            writer = new FileWriter(gpxfile, true);
            writer.append(text + "\n\n");

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

        } finally {
            if (writer != null) {
                try {
                    writer.flush();
                    writer.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

Findbug Report:

Reliance on default encoding
Found reliance on default encoding: new java.io.FileWriter(File, boolean)

In which line i'm getting this Error?

  writer = new FileWriter(gpxfile, true);

Could some one please brief me what is this exactly?
And how can we solve this?


问:
How to centre play button using Material UI and Flexbox
I am looking for some advice regarding this layout. I am struggling to get the play button in the middle with the borders. I have the following code so far, I am just struggling with getting flexbox to position the play button.

```<code>    function Tasks(props) {
  const { classes } = props;
  return (
    <div className={classes.root}>
      <Paper className={classes.paper}>
        <Grid container spacing={2}>
          <Grid item xs={12} sm container>
            <Grid item xs container direction="column" spacing={2}>
              <Grid item xs>
              <div className="name-label">
              Name
              </div>
              <Typography variant="h6" gutterBottom>
              Order cofee beans
              </Typography>
              <div className="form-divider"></div>
                <Typography variant="body2" color="textSecondary">
                  Process of Description
                </Typography>
              </Grid>
            </Grid>
            <Grid item>
              <Typography variant="subtitle">Workers Assigned</Typography>
              <Grid item xs={3}>
        <i class="far fa-play-circle"></i>
      </Grid>
              <Typography variant="h6" gutterBottom>
              0/25</Typography>
            </Grid>
          </Grid>
        </Grid>
      </Paper>
    </div>
  );
}
</code>```

Currently, I am unsure if the Grid is the issue or if I need to better structure what I have, any feedback would be much appreciated. I have an image of what it should look like:

Image

答:
I wouldn't use flex to position the button like that. It looks like you'd want something like:

const styles = theme => ({
  box1: {
    display: "flex",
    position: "relative",
    "& .playButton": {
      position: "absolute",
      top: "50%",
      transform: "translateY(-50%)"
    }
  }
});

const YourComponent = props => (

    {...}
    <Grid item classes={{ root: props.classes.box1}}>
      <Typography variant="subtitle">Workers Assigned</Typography>
      <Grid item xs={3} className="playButton">

      </Grid>
      <Typography variant="h6" gutterBottom>0/25</Typography>
    </Grid>
    {...}

);

YourComponent = withStyles(styles)(YourComponent);```

Body:
I am looking for some advice regarding this layout. I am struggling to get the play button in the middle with the borders. I have the following code so far, I am just struggling with getting flexbox to position the play button.

    function Tasks(props) {
  const { classes } = props;
  return (

      <Paper className={classes.paper}>
        <Grid container spacing={2}>
          <Grid item xs={12} sm container>
            <Grid item xs container direction="column" spacing={2}>
              <Grid item xs>

              Name

              <Typography variant="h6" gutterBottom>
              Order cofee beans
              </Typography>

                <Typography variant="body2" color="textSecondary">
                  Process of Description
                </Typography>
              </Grid>
            </Grid>
            <Grid item>
              <Typography variant="subtitle">Workers Assigned</Typography>
              <Grid item xs={3}>

      </Grid>
              <Typography variant="h6" gutterBottom>
              0/25</Typography>
            </Grid>
          </Grid>
        </Grid>
      </Paper>

  );
}

Currently, I am unsure if the Grid is the issue or if I need to better structure what I have, any feedback would be much appreciated. I have an image of what it should look like:

Image

Body:
I wouldn't use flex to position the button like that. It looks like you'd want something like:

const styles = theme => ({
  box1: {
    display: "flex",
    position: "relative",
    "& .playButton": {
      position: "absolute",
      top: "50%",
      transform: "translateY(-50%)"
    }
  }
});

const YourComponent = props => (
  <div>
    {...}
    <Grid item classes={{ root: props.classes.box1}}>
      <Typography variant="subtitle">Workers Assigned</Typography>
      <Grid item xs={3} className="playButton">
        <i class="far fa-play-circle"></i>
      </Grid>
      <Typography variant="h6" gutterBottom>0/25</Typography>
    </Grid>
    {...}
  </div>
);

YourComponent = withStyles(styles)(YourComponent);


问:
Apply log2 transformation only to numeric columns of a data.frame
I am trying to run a log2 transformation on my data set but I keep getting an error that says "non-numeric variable(s) in data frame". My data has row.names = 1 and header = TRUE and is of class data.frame()

I tried adding lappy(na.strings) but this does not fix the problem

```<code>Shared_DEGs <- cbind(UT.Degs_heatmap[2:11], MT.Degs_heatmap[2:11], HT.Degs_heatmap[2:11])
Shared_DEGs1 <- `row.names<-`(Shared_DEGs, (UT.Degs_heatmap[,1]))
MyData.INF.log2 <- log2(Shared_DEGs1)
</code>```

The data should be log2 transformed as an output

答:
I always recommend using 'tidyverse' to process data frame. Install it with install.packages('tidyverse')

```<code>library(tidyverse)
log2_transformed <- mutate_if(your_data, is.numeric, log2)
</code>```

Body:
I am trying to run a log2 transformation on my data set but I keep getting an error that says "non-numeric variable(s) in data frame". My data has row.names = 1 and header = TRUE and is of class data.frame()

I tried adding lappy(na.strings) but this does not fix the problem

Shared_DEGs <- cbind(UT.Degs_heatmap[2:11], MT.Degs_heatmap[2:11], HT.Degs_heatmap[2:11])
Shared_DEGs1 <- `row.names<-`(Shared_DEGs, (UT.Degs_heatmap[,1]))
MyData.INF.log2 <- log2(Shared_DEGs1)

The data should be log2 transformed as an output

Body:
I always recommend using 'tidyverse' to process data frame. Install it with install.packages('tidyverse')

library(tidyverse)
log2_transformed <- mutate_if(your_data, is.numeric, log2)


问:
I want to add frequency on base of position of ranking which their execution partially run not accurate - PHP
I have conditional function which their execution not running as per business meet which to be require transformation as with desired result. This function contain ranking and frequency which are part of multidimensional array and their execution of sum on based of some calculation

I want to add frequency on base of position of ranking which their execution partially run not accurate. could you please help me out.

```<code><?php
$arr = array (
    'AMXB 5321'  => array(
        array("course_title_code" => "AMB 5321",
              "content" => "Course",
              "total" => "303",
              "count" => "85",
              "ranking" => array(array(5),array(2,4,5)),
              "frequency" => array(array(5),array(1,2,11))),
        array("course_title_code" => "AMB 5321",
              "content" => "Succeed in the course",
              "total" => "300",
              "count" => "85",
              "ranking" => array(array(3,5),array(3,4,5)),
              "frequency" => array(array(1,4),array(1,2,11))
             )
    ));

array_walk($arr, function(&$v,$k){
    foreach($v as $key => &$s){
        $s['ranking'] = implode(',',range(1,5));
        foreach($s['frequency'] as $key => &$value){
            $temp   = $value;
            $value = (count($value) == 5) ? $value : array_merge(array_fill(0, 5 - count($value), 0), $temp);
            if($key == 1){
                for($i=0;$i<count($value);$i++){
                    $value[$i] += $s['frequency'][$key-1][$i];
                }
                $temFormat = implode(',',$s['frequency'][1]);
            }
        }
        unset($s['frequency']);
        $s['frequency'] = $temFormat;
    }
});

echo "```";
print_r($arr);

?>
```

<p>Desired Result</p>

```Array
(
    [AMXB 5321] => Array
        (
            [0] => Array
                (
                    [course_title_code] => AMB 5321
                    [content] => Course
                    [total] => 303
                    [count] => 85
                    [ranking] => 1,2,3,4,5
                    [frequency] => 0,1,0,2,16
                )

            [1] => Array
                (
                    [course_title_code] => AMB 5321
                    [content] => Succeed in the course
                    [total] => 300
                    [count] => 85
                    [ranking] => 1,2,3,4,5
                    [frequency] => 0,0,2,2,15
                )

        )

)
```

答:
You can do that like this:

```<code>function calRanking($ranks, $freqs) {
    $res = array_fill(0, 5, 0); // create array of 0
    foreach($ranks as $k => $v) {
        foreach(array_map(null, $v,  $freqs[$k]) as $e) {
            $res[$e[0]-1]+= $e[1]; //add the frequency according to rank key
        }
    }
    return $res;
}

foreach($a as &$v) { // for each calculate and implode
    $v["frequency"] = implode(',', calRanking($v["ranking"], $v["frequency"]));
    $v["ranking"] = implode(',',range(1,5));
}
</code>```

I assumed user with a lot of answer and reputation may build the question in more suite-able way for future learning...

Live example: 3v4l

Reference: array-fill, array-map

Body:
I have conditional function which their execution not running as per business meet which to be require transformation as with desired result. This function contain ranking and frequency which are part of multidimensional array and their execution of sum on based of some calculation

I want to add frequency on base of position of ranking which their execution partially run not accurate. could you please help me out.

<?php
$arr = array (
    'AMXB 5321'  => array(
        array("course_title_code" => "AMB 5321",
              "content" => "Course",
              "total" => "303",
              "count" => "85",
              "ranking" => array(array(5),array(2,4,5)),
              "frequency" => array(array(5),array(1,2,11))),
        array("course_title_code" => "AMB 5321",
              "content" => "Succeed in the course",
              "total" => "300",
              "count" => "85",
              "ranking" => array(array(3,5),array(3,4,5)),
              "frequency" => array(array(1,4),array(1,2,11))
             )
    ));

array_walk($arr, function(&$v,$k){
    foreach($v as $key => &$s){
        $s['ranking'] = implode(',',range(1,5));
        foreach($s['frequency'] as $key => &$value){
            $temp   = $value;
            $value = (count($value) == 5) ? $value : array_merge(array_fill(0, 5 - count($value), 0), $temp);
            if($key == 1){
                for($i=0;$i<count($value);$i++){
                    $value[$i] += $s['frequency'][$key-1][$i];
                }
                $temFormat = implode(',',$s['frequency'][1]);
            }
        }
        unset($s['frequency']);
        $s['frequency'] = $temFormat;
    }
});

echo "
";
print_r($arr);

?>

Desired Result

Array
(
    [AMXB 5321] => Array
        (
            [0] => Array
                (
                    [course_title_code] => AMB 5321
                    [content] => Course
                    [total] => 303
                    [count] => 85
                    [ranking] => 1,2,3,4,5
                    [frequency] => 0,1,0,2,16
                )

            [1] => Array
                (
                    [course_title_code] => AMB 5321
                    [content] => Succeed in the course
                    [total] => 300
                    [count] => 85
                    [ranking] => 1,2,3,4,5
                    [frequency] => 0,0,2,2,15
                )

        )

)

Body:
You can do that like this:

function calRanking($ranks, $freqs) {
    $res = array_fill(0, 5, 0); // create array of 0
    foreach($ranks as $k => $v) {
        foreach(array_map(null, $v,  $freqs[$k]) as $e) {
            $res[$e[0]-1]+= $e[1]; //add the frequency according to rank key
        }
    }
    return $res;
}

foreach($a as &$v) { // for each calculate and implode
    $v["frequency"] = implode(',', calRanking($v["ranking"], $v["frequency"]));
    $v["ranking"] = implode(',',range(1,5));
}

I assumed user with a lot of answer and reputation may build the question in more suite-able way for future learning...

Live example: 3v4l

Reference: array-fill, array-map