问:
Firebase functions : Cannot set property config of #<Object> which has only a getter
Firebase functions was working fine
I updated to latest firebase-tools
Now running into this error issue when running firebase serve. </p>

```<code>[debug] [2020-05-28T20:37:11.387Z] [runtime-status] [93658] Error in handleMessage:  => TypeError: Cannot set property config of #<Object> which has only a getter: TypeError: Cannot set property config of #<Object> which has only a getter
    at {....}/node/v10.15.0/lib/node_modules/firebase-tools/lib/emulator/functionsEmulatorRuntime.js:455:19
    at Generator.next (<anonymous>)
    at fulfilled ({....}/node/v10.15.0/lib/node_modules/firebase-tools/lib/emulator/functionsEmulatorRuntime.js:5:58)
[warn] ⚠  functions: Cannot set property config of #<Object> which has only a getter {"metadata":{"emulator":{"name":"functions"},"message":"Cannot set property config of #<Object> which has only a getter"}}
[warn] ⚠  Your function was killed because it raised an unhandled error. {"metadata":{"emulator":{"name":"functions"},"message":"Your function was killed because it raised an unhandled error."}}
</code>```

答:
Turns out this was submitted and fixed about the same time that I posted it here: GitHub - firebase-tools - Cannot set property config of # which has only a getter #2301

Fix should be available in 8.4.1 soon.

Body:
Firebase functions was working fine
I updated to latest firebase-tools
Now running into this error issue when running firebase serve.

[debug] [2020-05-28T20:37:11.387Z] [runtime-status] [93658] Error in handleMessage:  => TypeError: Cannot set property config of #<Object> which has only a getter: TypeError: Cannot set property config of #<Object> which has only a getter
    at {....}/node/v10.15.0/lib/node_modules/firebase-tools/lib/emulator/functionsEmulatorRuntime.js:455:19
    at Generator.next (<anonymous>)
    at fulfilled ({....}/node/v10.15.0/lib/node_modules/firebase-tools/lib/emulator/functionsEmulatorRuntime.js:5:58)
[warn] ⚠  functions: Cannot set property config of #<Object> which has only a getter {"metadata":{"emulator":{"name":"functions"},"message":"Cannot set property config of #<Object> which has only a getter"}}
[warn] ⚠  Your function was killed because it raised an unhandled error. {"metadata":{"emulator":{"name":"functions"},"message":"Your function was killed because it raised an unhandled error."}}


来源: stackexchange

问:
how can I deploy legacy code ( build using .net framework 4.6) in iot edge device as module?
I have a code written in .net framework 4.6 which talks with a device (non iot, non IP) and reads data. I want this data to be sent to Azure IoT hub.
so instead of using Azure IoT Device SDK in it, and running it as a simulated device, I want to create IoT Edge module, so lifecycle management of this app will come handy.
But when I create new C# module in VS 2017, it forces me to use .net core 2.1. Is it possible to create Azure IoT Edge custom Module using .net Frameworks. and if yes, how ?? </p>

答:
When you create a module in VS or VS Code, they assume you want a 'traditional' (and cross platform) module.  So .NET Core is the only choice (for the cross platform part).  However, if you only want to use IoT Edge as a deployment/lifecycle mgmt vehicle, than you can build your own docker image independent of IoT Edge, yet deploy it through the IoT edge manifest.  This link talks about containerizing a traditional .NET app, which you should then be able to deploy with IoT Edge (it just won't 'talk' to ioT Edge).  We've done similar (non-iot-edge module) kind of things with stuff like influxdb, grafana, redis cache, etc.  We deploy and manage their lifecycle with IoT Edge, but they don't really talk to/through IoT Edge.

Note that if you create a container as mentioned in the article, you will be limited to running IoT Edge on Windows with Windows containers.

ContentLicense: CC BY-SA 4.0


问:
react native scrollview not smooth when app opend from background
i created simple app in react native ,everything works fine
but when the app go to background then active again
Scrollview not working smoothly
can some one have solution?</p>

答: Probably not the direct solution, but did you consider using <FlatList> instead of <ScrollView> given the former is more performant when it comes to rendering long lists.


问:
Rails 3 serialized form attribute
I have the following model:

```<code>class Deck < ActiveRecord::Base
  has_many :cards
  serialize :stats
  attr_accessible :name, :description, :stats
end
</code>```

In this, stats should be an array of strings.  I want to be able to add an arbitrary number of stats to the row (using javascript to add additional "stat" input boxes, but that is outside the scope if the question.)

My question is how do I reflect this structure in the view?  If I was building the form manually then it would look like:

```<code><input type="text" name="deck[stats][]">
</code>```

My view currently looks like:

```<code><%= f.fields_for :stats, @deck.stats do |p| %>
  <%= p.label :p, "Stats: " %>
  <%= p.text_field :p %>
<% end %>
</code>```

But this outputs:

```<code><input type="text" name="deck[stats][p]">
</code>```

I also want a counter so I can display the label as "Stat 1:", "Stat 2:", etc.

Any help is appreciated.

答:
By defining :p you are making it think you are looking for a method on stats called p, ie stats.p

```<code><%= f.fields_for :stats, @deck.stats do |p| %>
  <%= p.label :p, "Stats: " %>
  <%= p.text_field :p %>
<% end %>
</code>```

Rather just try  <%= p.text_field %> drop the :p

ContentLicense: CC BY-SA 3.0

Title: Rails 3 serialized form attribute

Body:
I have the following model:

class Deck < ActiveRecord::Base
  has_many :cards
  serialize :stats
  attr_accessible :name, :description, :stats
end

In this, stats should be an array of strings.  I want to be able to add an arbitrary number of stats to the row (using javascript to add additional "stat" input boxes, but that is outside the scope if the question.)

My question is how do I reflect this structure in the view?  If I was building the form manually then it would look like:

<input type="text" name="deck[stats][]">

My view currently looks like:

<%= f.fields_for :stats, @deck.stats do |p| %>
  <%= p.label :p, "Stats: " %>
  <%= p.text_field :p %>
<% end %>

But this outputs:

<input type="text" name="deck[stats][p]">

I also want a counter so I can display the label as "Stat 1:", "Stat 2:", etc.

Any help is appreciated.

Body:
By defining :p you are making it think you are looking for a method on stats called p, ie stats.p

<%= f.fields_for :stats, @deck.stats do |p| %>
  <%= p.label :p, "Stats: " %>
  <%= p.text_field :p %>
<% end %>

Rather just try  <%= p.text_field %> drop the :p


问:
pt-achive of percona is taking up too much CPU and database connections
I am archiving my RDS MySQL database to a secondary database using pt-archival from percona but during the archival activity the CPU and DB connections of the database increases. The archival activity consists of deleting data from the main database and copying it to the secondary database. Is there some way this can be reduced since this is a production database.

The pt-archive command is -

```<code>pt-archiver --source h=source-database.com,u=username,p=password,D=dbName,t=tableName --where "creation_time< current_date - interval 30 day" --dest h=dest-database.com,u=username,p=password  --limit 1000 --txn-size 1000 --progress 1000 --optimize=s
</code>```

答:
I can't solve your current problem.  You should consider a schema change that will prevent this problem recurring.

The gist is to PARTITION BY RANGE(...) the main table, then use DROP PARTITION (virtually instant) and REORGANIZE PARTITION (also fast).

Discussion on time-series partitioning:  http://mysql.rjweb.org/doc.php/partitionmaint

(Caveat:  You will need some downtime and/or pt-online-schema-change to partition your table, plus code and INDEX changes.)

More on taming big deletes:  http://mysql.rjweb.org/doc.php/deletebig

Body:
I am archiving my RDS MySQL database to a secondary database using pt-archival from percona but during the archival activity the CPU and DB connections of the database increases. The archival activity consists of deleting data from the main database and copying it to the secondary database. Is there some way this can be reduced since this is a production database.

The pt-archive command is -

pt-archiver --source h=source-database.com,u=username,p=password,D=dbName,t=tableName --where "creation_time< current_date - interval 30 day" --dest h=dest-database.com,u=username,p=password  --limit 1000 --txn-size 1000 --progress 1000 --optimize=s


问:
Crashlytics symbols upload fails with "GC overhead limit exceeded"
I've been desperately trying to upload my game symbols to crashlytics (gradlew uploadCrashlyticsSymbolFileRelease) and consistently failing with:

```<code>GC overhead limit exceeded
</code>```

What have I tried already... I'm making sure my deamon has lots of memory to play with:

```<code>-XX:MaxHeapSize=32g,-XX:MaxPermSize=4096m,-XX:+HeapDumpOnOutOfMemoryError,-Xmx4g
</code>```

also on build.gradle:

```<code>dexOptions {
        maxProcessCount 2
        javaMaxHeapSize "16g"
    }
</code>```

running the uploadCrashlyticsSymbolFileRelease with debug and callstack, shows:

```<code>[org.gradle.cache.internal.DefaultFileLockManager] Waiting to acquire shared lock on daemon addresses registry.
[org.gradle.process.internal.health.memory.MemoryManager] Emitting OS memory status event {Total: 17101328384, Free: 1893560320}
[org.gradle.internal.buildevents.BuildExceptionReporter] Caused by: java.lang.OutOfMemoryError: GC overhead limit exceeded
</code>```

I've also deleted the gradle registry folders, but nothing worked so far.
Contacted Firebase support on monday, but also got no reply.

I'm using the following versions:

```<code>implementation 'com.google.firebase:firebase-analytics:17.4.1'
implementation 'com.google.firebase:firebase-crashlytics-ndk:17.0.0'
</code>```

And this is working perfectly on another game I have.

答:
I've been trying to downgrade but there is no documentation anymore on how to properly setup 1.27 version. And the new version of my game using 1.27 is not sending any crash information to the console.

This is what I did. On root build.grande included

```<code>classpath 'io.fabric.tools:gradle:1.27.0'
</code>```

then on the app build.gradle...

on the top:

```<code>io.fabric.tools:gradle:1.27.0
</code>```

inside the android tag:

```<code>crashlytics {
    enableNdk true
    androidNdkOut ...    androidNdkLibsOut .....
}
</code>```

on the dependencies:

```<code>implementation 'com.crashlytics.sdk.android:crashlytics:2.10.1'
implementation 'com.crashlytics.sdk.android:crashlytics-ndk:2.1.1'
</code>```

And on the Java, included this on the onCreate event:

```<code>Fabric.with(this, new Crashlytics(), new CrashlyticsNdk());
</code>```

with the imports:

```<code>import io.fabric.sdk.android.Fabric;
import com.crashlytics.android.Crashlytics;
import com.crashlytics.android.ndk.CrashlyticsNdk;
</code>```

What am I missing?

Body:
I've been desperately trying to upload my game symbols to crashlytics (gradlew uploadCrashlyticsSymbolFileRelease) and consistently failing with:

GC overhead limit exceeded

What have I tried already... I'm making sure my deamon has lots of memory to play with:

-XX:MaxHeapSize=32g,-XX:MaxPermSize=4096m,-XX:+HeapDumpOnOutOfMemoryError,-Xmx4g

also on build.gradle:

dexOptions {
        maxProcessCount 2
        javaMaxHeapSize "16g"
    }

running the uploadCrashlyticsSymbolFileRelease with debug and callstack, shows:

[org.gradle.cache.internal.DefaultFileLockManager] Waiting to acquire shared lock on daemon addresses registry.
[org.gradle.process.internal.health.memory.MemoryManager] Emitting OS memory status event {Total: 17101328384, Free: 1893560320}
[org.gradle.internal.buildevents.BuildExceptionReporter] Caused by: java.lang.OutOfMemoryError: GC overhead limit exceeded

I've also deleted the gradle registry folders, but nothing worked so far.
Contacted Firebase support on monday, but also got no reply.

I'm using the following versions:

implementation 'com.google.firebase:firebase-analytics:17.4.1'
implementation 'com.google.firebase:firebase-crashlytics-ndk:17.0.0'

And this is working perfectly on another game I have.

Body:
I've been trying to downgrade but there is no documentation anymore on how to properly setup 1.27 version. And the new version of my game using 1.27 is not sending any crash information to the console.

This is what I did. On root build.grande included

classpath 'io.fabric.tools:gradle:1.27.0'

then on the app build.gradle...

on the top:

io.fabric.tools:gradle:1.27.0

inside the android tag:

crashlytics {
    enableNdk true
    androidNdkOut ...    androidNdkLibsOut .....
}

on the dependencies:

implementation 'com.crashlytics.sdk.android:crashlytics:2.10.1'
implementation 'com.crashlytics.sdk.android:crashlytics-ndk:2.1.1'

And on the Java, included this on the onCreate event:

Fabric.with(this, new Crashlytics(), new CrashlyticsNdk());

with the imports:

import io.fabric.sdk.android.Fabric;
import com.crashlytics.android.Crashlytics;
import com.crashlytics.android.ndk.CrashlyticsNdk;

What am I missing?


问:
How to use JavaScript to get an HTML template file out of S3 buffer data?
I have an HTML file loaded into an S3 bucket.  This file is intended to be used as a template for the body of an email.

I used one of the answers from this question (Read file from aws s3 bucket using node fs) to help me get the file out of the bucket.  Now it appears I have buffer data that I need to convert back into HTML, or a string version of it would also be fine.  Things I've tried so far haven't worked...

Here's what my code getting the template looks like:

```<code>async getEmailTemplate() {
    const s3 = new AWS.S3({ apiVersion: '2006-03-01' });
    const params = {
      Bucket: 'myBucket',
      Key: 'templates/email.html',
    };
    const template = await s3.getObject(params).promise();
    return template;
}
</code>```

When I log the data that "template" returns, it appears like this...  I need something like template.body.toString('latin1')...

```<code>console.log src/services/tests/unit/Controller.test.js:266
    {
      AcceptRanges: 'bytes',
      LastModified: 2020-05-28T19:36:23.000Z,
      ContentLength: 22745,
      ETag: '"1bcc123ba55b5b878109436c1274b94b"',
      ContentType: 'text/html',
      Metadata: {},
      Body: <Buffer 3c 21 44 4f 43 54 59 50 45 20 68 74 6d 6c 3e 0a 3c 68 74 6d 6c 20 78 6d 6c 6e 73 3a 76 3d 22 75 72 6e 3a 73 63 68 65 6d 61 73 2d 6d 69 63 72 6f 73 6f ... 22695 more bytes>
    }
</code>```

In case it makes a difference, the template contains js template literals that look like ${data.firstName}.  Currently the email is correctly getting populated and sent when the template is hardcoded in the javascript file with `` surrounding it.  But I'm trying to update the code to pull the template from an external source instead.

Thank you for taking the time to read my question...  Does anyone have suggestions for me? :)

答:
If you change "body" to "Body" it should work, here's some old code thats almost the same as yours and is working fine:</p>

```<code> let { Body } = await s3.getObject(params).promise();
 return Body.toString(encoding)
</code>```

Body:
I have an HTML file loaded into an S3 bucket.  This file is intended to be used as a template for the body of an email.

I used one of the answers from this question (Read file from aws s3 bucket using node fs) to help me get the file out of the bucket.  Now it appears I have buffer data that I need to convert back into HTML, or a string version of it would also be fine.  Things I've tried so far haven't worked...

Here's what my code getting the template looks like:

async getEmailTemplate() {
    const s3 = new AWS.S3({ apiVersion: '2006-03-01' });
    const params = {
      Bucket: 'myBucket',
      Key: 'templates/email.html',
    };
    const template = await s3.getObject(params).promise();
    return template;
}

When I log the data that "template" returns, it appears like this...  I need something like template.body.toString('latin1')...

console.log src/services/tests/unit/Controller.test.js:266
    {
      AcceptRanges: 'bytes',
      LastModified: 2020-05-28T19:36:23.000Z,
      ContentLength: 22745,
      ETag: '"1bcc123ba55b5b878109436c1274b94b"',
      ContentType: 'text/html',
      Metadata: {},
      Body: <Buffer 3c 21 44 4f 43 54 59 50 45 20 68 74 6d 6c 3e 0a 3c 68 74 6d 6c 20 78 6d 6c 6e 73 3a 76 3d 22 75 72 6e 3a 73 63 68 65 6d 61 73 2d 6d 69 63 72 6f 73 6f ... 22695 more bytes>
    }

In case it makes a difference, the template contains js template literals that look like ${data.firstName}.  Currently the email is correctly getting populated and sent when the template is hardcoded in the javascript file with `` surrounding it.  But I'm trying to update the code to pull the template from an external source instead.

Thank you for taking the time to read my question...  Does anyone have suggestions for me? :)

Body:
If you change "body" to "Body" it should work, here's some old code thats almost the same as yours and is working fine:

 let { Body } = await s3.getObject(params).promise();
 return Body.toString(encoding)


问:
Unnecessary border shown when clicked content area on understrap theme
I'm developing wordpress theme using Understrap, with using customstrap child theme of livecanvas. It uses Bootstrap 4.

I developed my theme, but there is unnecessary border when I clicked the content area on theme. I checked the code on browser using inspects but i could not find the code that caused this problem.

here is understrap repo: https://github.com/understrap/understrap

and my page.php

```<code><?php
/**
 * The template for displaying all pages
 *
 * This is the template that displays all pages by default.
 * Please note that this is the WordPress construct of pages
 * and that other 'pages' on your WordPress site will use a
 * different template.
 *
 * @package understrap
 */

// Exit if accessed directly.
defined( 'ABSPATH' ) || exit;

get_header();

$container = get_theme_mod( 'understrap_container_type' );

?>

<div class="wrapper" id="page-wrapper">

    <div class="<?php echo esc_attr( $container ); ?>" id="content" tabindex="-1">

        <div class="row">

            <!-- Do the left sidebar check -->
            <?php get_template_part( 'global-templates/left-sidebar-check' ); ?>

            <main class="site-main" id="main">

                <?php
                while ( have_posts() ) {
                    the_post();
                    get_template_part( 'loop-templates/content', 'page' );

                }
                ?>

            </main><!-- #main -->

            <!-- Do the right sidebar check -->
            <?php get_template_part( 'global-templates/right-sidebar-check' ); ?>

        </div><!-- .row -->

    </div><!-- #content -->

</div><!-- #page-wrapper -->

<?php
get_footer();
</code>```

Which selector that I need to use to prevent this problem?

Here is the image of this be like:

1- 1st image is Default

2- 2nd image When I clicked the content area

When I clicked the content area

答:
I'm pretty sure this is outline property in CSS.

As we cannot see your code right now, for debugging I would suggest to try pasting this in your styles to check if that helps:

* {
  border: none !important;
  box-shadow: none !important;
  outline: none !important;
}
```

Body:
I'm developing wordpress theme using Understrap, with using customstrap child theme of livecanvas. It uses Bootstrap 4.

I developed my theme, but there is unnecessary border when I clicked the content area on theme. I checked the code on browser using inspects but i could not find the code that caused this problem.

here is understrap repo: https://github.com/understrap/understrap

and my page.php

<?php
/**
 * The template for displaying all pages
 *
 * This is the template that displays all pages by default.
 * Please note that this is the WordPress construct of pages
 * and that other 'pages' on your WordPress site will use a
 * different template.
 *
 * @package understrap
 */

// Exit if accessed directly.
defined( 'ABSPATH' ) || exit;

get_header();

$container = get_theme_mod( 'understrap_container_type' );

?>

    <div class="<?php echo esc_attr( $container ); ?>" id="content" tabindex="-1">

            <?php get_template_part( 'global-templates/left-sidebar-check' ); ?>

                <?php
                while ( have_posts() ) {
                    the_post();
                    get_template_part( 'loop-templates/content', 'page' );

                }
                ?>

            <?php get_template_part( 'global-templates/right-sidebar-check' ); ?>

<?php
get_footer();

Which selector that I need to use to prevent this problem?

Here is the image of this be like:

1- 1st image is Default

2- 2nd image When I clicked the content area

When I clicked the content area


问:
In-place modification, insertion or removal in the same function for hash maps in Rust
Say I have a hash map m: HashMap<K, V>, a key k: K and a value v: V, and would like to do the following:

If m does not contain a value at index k, insert v at index k.

If m contains a value w at index k, apply a function fn combine(x: V, y: V) -> Option<V> to v and w, and:

If the result is None, remove the entry at index k from m.

If the result is Some(u), replace the value at index k by u.

Is there a way to do this "in-place", without calling functions that access, modify or remove the value at k multiple times?

I would also like to avoid copying data, so ideally one shouldn't need to clone v to feed the clones into insert and combine separately.

I could rewrite combine to use (mutable) references (or inline it), but the wish of not copying data still remains.

答:
I managed to do it in one access, one write and one key-deletion in total in the worst case. The last key-deletion should not be necessary, but I'm not certain it can be done. I gave it my best so far. I hope this helps!

Okay, so I think we want to use the Entry API.

The full method list for Entry is here.

I think we'd do it in the following order:

If m contains a value w at index k: (two more steps)

Or insert v at index k.

This can be done by using .and_modify and then .or_insert. Something like this:

let map = // ... Initialize the map

// Do stuff to it
// ...

// Our important bit:

let mut delete_entry = false;

map.entry(k)
   .and_modify(|w| { // If the entry exists, we modify it

     let u = combine(v, w);

     match u {

       Some(y) => *w = y;

       None => delete_entry = true;
       }
     }
   )
   .or_insert(v); // If it doesn't, we insert v

if delete_entry {
  map.remove(k);
}
```

I don't think there's a way to do all three things without that last map.remove access, so this is my best attempt for now.

Body:
I managed to do it in one access, one write and one key-deletion in total in the worst case. The last key-deletion should not be necessary, but I'm not certain it can be done. I gave it my best so far. I hope this helps!

Okay, so I think we want to use the Entry API.

The full method list for Entry is here.

I think we'd do it in the following order:

If m contains a value w at index k: (two more steps)

Or insert v at index k.

This can be done by using .and_modify and then .or_insert. Something like this:

let map = // ... Initialize the map

// Do stuff to it
// ...

// Our important bit:

let mut delete_entry = false;

map.entry(k)
   .and_modify(|w| { // If the entry exists, we modify it

     let u = combine(v, w);

     match u {

       Some(y) => *w = y;

       None => delete_entry = true;
       }
     }
   )
   .or_insert(v); // If it doesn't, we insert v

if delete_entry {
  map.remove(k);
}

I don't think there's a way to do all three things without that last map.remove access, so this is my best attempt for now.


问:
Css3 evaluatable expressions?
Are there any techniques that allow for expressions in css3 statements?

Frequently it is helpful to do such things as width: 35%+20px or similar. Right now the only solutions I have to these circumstances are to either redesign the page or to use javascript to dynamically set the css.

答: The CSS working draft on values and units specifies a calc function, though it is only supported in the latest versions of IE and Firefox.</p>

Title: Css3 evaluatable expressions?


问:
Error in R function readGPS: gpsbabel not found
I'm trying to download a gpx file from the YOURS routing API (http://wiki.openstreetmap.org/wiki/YOURS#Routing_API) and upload the file to R using the readGPS function contained in the maptools package.

Here is the code:

```<code>require(utils)
require(maptools)

URL <- 'http://www.yournavigation.org/api/1.0/saveas.php?type=gpx&data=5.62373%2053.01,5.62359%2053.01014,5.62336%2053.01024,5.62314%2053.010303'

download.file(URL, 'tmpTrip.gpx')
gpx.raw <- readGPS(i='gpx', f='tmpTrip.gpx', type='t')
</code>```

And the error I receive:

```<code>Error in readGPS(i = "gpx", f = "tmpTrip.gpx", type = "t") :
  gpsbabel not found
</code>```

I do have installed gpsbabel and I can see the gpx file correctly downloaded in my working directory.
My system and R version are:
Windows 7 Enterprise Service Pack 1, running on Intel Core i5-3320M CPU @ 2.60GHz, 4GB RAM, 32 bit OS.

```<code>R version 3.1.0 (2014-04-10) -- "Spring Dance"
Copyright (C) 2014 The R Foundation for Statistical Computing
Platform: i386-w64-mingw32/i386 (32-bit)
</code>```

Any help is much appreciated, thank you!!

答:
For Mac users:</p>

```<code>setwd("/Applications/GPSBabelFE.app")
</code>```

Body:
I'm trying to download a gpx file from the YOURS routing API (http://wiki.openstreetmap.org/wiki/YOURS#Routing_API) and upload the file to R using the readGPS function contained in the maptools package.

Here is the code:

require(utils)
require(maptools)

URL <- 'http://www.yournavigation.org/api/1.0/saveas.php?type=gpx&data=5.62373%2053.01,5.62359%2053.01014,5.62336%2053.01024,5.62314%2053.010303'

download.file(URL, 'tmpTrip.gpx')
gpx.raw <- readGPS(i='gpx', f='tmpTrip.gpx', type='t')

And the error I receive:

Error in readGPS(i = "gpx", f = "tmpTrip.gpx", type = "t") :
  gpsbabel not found

I do have installed gpsbabel and I can see the gpx file correctly downloaded in my working directory.
My system and R version are:
Windows 7 Enterprise Service Pack 1, running on Intel Core i5-3320M CPU @ 2.60GHz, 4GB RAM, 32 bit OS.

R version 3.1.0 (2014-04-10) -- "Spring Dance"
Copyright (C) 2014 The R Foundation for Statistical Computing
Platform: i386-w64-mingw32/i386 (32-bit)

Any help is much appreciated, thank you!!

Body:
For Mac users:

setwd("/Applications/GPSBabelFE.app")


问:
I'm trying to set an Interval inside a setInterval, but it is Accelerating

var i = 0
function fill(){
    setInterval(animation,30)  // the problem starts here.
    function animation(){
        if (i<100){
            i++
            load.style.width = i+'%'
        } else {
            i = 0
        }
    }
    clearInterval(animation,30) // this should stop the interval above, but it is accelerating. Anyone nows how to solve it?
}
fill()
setInterval(fill,3000)
```

答:
It's accelerating because you don't correctly stop the previous interval. So every time you call fill() it adds another interval function that's updating the progress bar.

You need to save the result of setInterval in a variable, and use that in the clearInterval call.

You should call clearInterval when you reach the 100% limit, not immediately after calling setInterval.

var i = 0

function fill() {
  var interval = setInterval(animation, 30) // the problem starts here.
  function animation() {
    if (i < 100) {
      i++
      load.style.width = i + '%'
    } else {
      i = 0
      clearInterval(interval)
    }
  }
}
fill()
setInterval(fill, 3000)```
<pre class="snippet-code-css lang-css prettyprint-override"><code>#load {
  background-color: blue;
  height: 30px;
}</code>```

```

Body:
It's accelerating because you don't correctly stop the previous interval. So every time you call fill() it adds another interval function that's updating the progress bar.

You need to save the result of setInterval in a variable, and use that in the clearInterval call.

You should call clearInterval when you reach the 100% limit, not immediately after calling setInterval.

var i = 0

function fill() {
  var interval = setInterval(animation, 30) // the problem starts here.
  function animation() {
    if (i < 100) {
      i++
      load.style.width = i + '%'
    } else {
      i = 0
      clearInterval(interval)
    }
  }
}
fill()
setInterval(fill, 3000)

#load {
  background-color: blue;
  height: 30px;
}

<div id="load"></div>


问:
How to make a stopwatch that takes a widget off the air?
I need to know how to make this stopwatch, which after 48 hours disables a widget, which in my case is a button. Can someone explain to me how to do it? What classes to use?

I tried to use this, but don't works:

```<code>var timer = Timer(Duration(seconds: 1), () => print('done'));
</code>```

答:
it seems to me that you want this button to be disabled after 2 days of the app that was installed, you need persist the date on the device so that after app-restarts the date will be itself, you need to use a package the persists the data on the device. i recommend shared_preference which is easy to use.

for your case, in the screen where you use the button you need to do this

import 'package:shared_preferences/shared_preferences.dart';

class MyFirstStatefullScreen extends StatefullWidget {
  MyFirstStatefullScreenState createState() => MyFirstStatefullScreenState();
}

class MyFirstStatefullScreenState extends State<MyFirstStatefullScreen>{
// some other code that u wrote
  bool shouldButtonBeActive = true;

 @override
 void initState() {
    Future.delayed(Duration(0))
          .then((_) {
         SharedPreferences sharedPrefs= await SharedPreferences.getInstance();

         final deadLine = sharedPrefs.getString('deadLine');

         if(deadLine == null) {
           // this is the first time the app has been installed on the device
           // so we need to set the deadLine to N number of days after the installation

           final deadLineDate = DateTime.now().add(Duration(days: 2)); // 2 days from the date that the app was installed;

           sharedPrefs.setString(deadLineDate.toIso8601String()); // set it so we can check on the successfull state

          return;

         }

         final deadLineDate = DateTime.parse(deadLine); // since we stored it as a string;
          /// the deadline is set and is not null

         if(DateTime.now().compareTo(deadLineDate) == 0) {
          we are successfull, N hours have passed since the intial instalation, now we can disable the button

             shouldButtonBeActive = false; // the button should be disabled
         }

       })

 }

  Widget build(context) {

      // in your UI where you use the button

       MaterialButton(
         child: Text("Button"),
         onPressed: shouldButtonBeActive ? func() : null
       )
   }
}

```

PS: we are using the Future inside the initState, because initState dose not allow async ( api calls, storage access) in it.

Body:
I need to know how to make this stopwatch, which after 48 hours disables a widget, which in my case is a button. Can someone explain to me how to do it? What classes to use?

I tried to use this, but don't works:

var timer = Timer(Duration(seconds: 1), () => print('done'));

Body:
it seems to me that you want this button to be disabled after 2 days of the app that was installed, you need persist the date on the device so that after app-restarts the date will be itself, you need to use a package the persists the data on the device. i recommend shared_preference which is easy to use.

for your case, in the screen where you use the button you need to do this

import 'package:shared_preferences/shared_preferences.dart';

class MyFirstStatefullScreen extends StatefullWidget {
  MyFirstStatefullScreenState createState() => MyFirstStatefullScreenState();
}

class MyFirstStatefullScreenState extends State<MyFirstStatefullScreen>{
// some other code that u wrote
  bool shouldButtonBeActive = true;

 @override
 void initState() {
    Future.delayed(Duration(0))
          .then((_) {
         SharedPreferences sharedPrefs= await SharedPreferences.getInstance();

         final deadLine = sharedPrefs.getString('deadLine');

         if(deadLine == null) {
           // this is the first time the app has been installed on the device
           // so we need to set the deadLine to N number of days after the installation

           final deadLineDate = DateTime.now().add(Duration(days: 2)); // 2 days from the date that the app was installed;

           sharedPrefs.setString(deadLineDate.toIso8601String()); // set it so we can check on the successfull state

          return;

         }

         final deadLineDate = DateTime.parse(deadLine); // since we stored it as a string;
          /// the deadline is set and is not null

         if(DateTime.now().compareTo(deadLineDate) == 0) {
          we are successfull, N hours have passed since the intial instalation, now we can disable the button

             shouldButtonBeActive = false; // the button should be disabled
         }

       })

 }

  Widget build(context) {

      // in your UI where you use the button

       MaterialButton(
         child: Text("Button"),
         onPressed: shouldButtonBeActive ? func() : null
       )
   }
}

PS: we are using the Future inside the initState, because initState dose not allow async ( api calls, storage access) in it.


问:
How can my class be provided some information about its environment?
Here's a code sample I wrote with encapsulation and composition in mind:

```<code>class Bullet {
 private:
  Vector2 position;
  Vector2 speed;

 public:
  void move(float time_delta) {
    position += speed * time_delta;
  }
};
</code>```

Basically, there's just a projectile moving in nowhere. However, a bullet can actually e. g. ricochet off a wall, having its speed changed significantly. Is there a good way of considering such interactions? I neither want my Bullet to know about "higher-rank" classes (which are supposed to use it themselves) nor write a single-use solution like this one:

```<code>template<typename F> void move(float time_delta, F collision_checker);
</code>```

UPDATE: worth reading if you want this question narrowed. Here's a simplified example of the wished logic for moving Bullets (I don't exactly mean the Bullet::move() member function!) and their interactions with other entities:

```<code>Vector2 destination = bullet.position + bullet.speed * time_delta;
if (std::optional<Creature> target = get_first_creature(bullet.position, destination)) {
  // decrease Bullet::speed depending on the target (and calculate the damage)
} else if (std::optional<Wall> obstacle = get_first_wall(bullet.position, destination)) {
  // calculate the ricochet changing Bullet::position and Bullet::speed
}
</code>```

All pieces of code represented by comments are supposed to use some properties of the Creature and Wall classes.

答:
From a design point of view, it is probably best if your bullet doesn't know how to detect when it's ... passing_through an obstacle (scnr). So it might be better to turn your Bullet class in to a struct, i.e. have it behave like a thing that is acted upon instead of a thing that acts.

You can still add your convenience function but have it be non-mutating:

```<code>struct Bullet {
  Vector2 position;
  Vector2 speed;
  Vector2 move(float time_delta) const {
    return position + speed * time_delta;
  }
};
</code>```

This way you can compute the collisions from the calling scope:

```<code>auto dest = bullet.move(dt);
while (std::optional<Collision> const col = detectCollision(bullet.position,dest)) {
  bullet.position = col->intersectPoint;
  bullet.speed = col->reflectedSpeed;
  dest = col->reflectDest;
}
bullet.position = dest;
</code>```

Here detectCollision checks whether the line from the bullet's current position to the new position dest intersects with any obstacle and computes the parameters of the reflection. Effectively you zig-zag your way to the destination that will result from all successive ping-pongs of the bullet with potential obstacles.

Body:
Here's a code sample I wrote with encapsulation and composition in mind:

class Bullet {
 private:
  Vector2 position;
  Vector2 speed;

 public:
  void move(float time_delta) {
    position += speed * time_delta;
  }
};

Basically, there's just a projectile moving in nowhere. However, a bullet can actually e. g. ricochet off a wall, having its speed changed significantly. Is there a good way of considering such interactions? I neither want my Bullet to know about "higher-rank" classes (which are supposed to use it themselves) nor write a single-use solution like this one:

template<typename F> void move(float time_delta, F collision_checker);

UPDATE: worth reading if you want this question narrowed. Here's a simplified example of the wished logic for moving Bullets (I don't exactly mean the Bullet::move() member function!) and their interactions with other entities:

Vector2 destination = bullet.position + bullet.speed * time_delta;
if (std::optional<Creature> target = get_first_creature(bullet.position, destination)) {
  // decrease Bullet::speed depending on the target (and calculate the damage)
} else if (std::optional<Wall> obstacle = get_first_wall(bullet.position, destination)) {
  // calculate the ricochet changing Bullet::position and Bullet::speed
}

All pieces of code represented by comments are supposed to use some properties of the Creature and Wall classes.

Body:
From a design point of view, it is probably best if your bullet doesn't know how to detect when it's ... passing_through an obstacle (scnr). So it might be better to turn your Bullet class in to a struct, i.e. have it behave like a thing that is acted upon instead of a thing that acts.

You can still add your convenience function but have it be non-mutating:

struct Bullet {
  Vector2 position;
  Vector2 speed;
  Vector2 move(float time_delta) const {
    return position + speed * time_delta;
  }
};

This way you can compute the collisions from the calling scope:

auto dest = bullet.move(dt);
while (std::optional<Collision> const col = detectCollision(bullet.position,dest)) {
  bullet.position = col->intersectPoint;
  bullet.speed = col->reflectedSpeed;
  dest = col->reflectDest;
}
bullet.position = dest;

Here detectCollision checks whether the line from the bullet's current position to the new position dest intersects with any obstacle and computes the parameters of the reflection. Effectively you zig-zag your way to the destination that will result from all successive ping-pongs of the bullet with potential obstacles.


问:
Vue Vuetify. v-model for v-checkbox not taking the correct value when inside a v-for loop
So I have this in my template:

```<code> <v-checkbox v-for="(option,index) in options" :key="option.id" :label="option.checked.toString()" :v-model="options[index].checked"></v-checkbox>
</code>```

And this in my data():

```<code>options: [
        {
          id: '1',
          name: 'Cotton',
          checked : true
        },
        {
          id: '2',
          name: 'Silk',
          checked : false
        }
 ]
</code>```

However, even when the value is true, the checkbox is not checked; why??

I have this in codepen:

https://codepen.io/averied/pen/JjYQLJQ?editable=true&editors=101%3Dhttps%3A%2F%2Fvuetifyjs.com%2Fen%2Fcomponents%2Fselection-controls%2F

答: You don't need : before v-model.

Body:
So I have this in my template:

 <v-checkbox v-for="(option,index) in options" :key="option.id" :label="option.checked.toString()" :v-model="options[index].checked"></v-checkbox>

And this in my data():

options: [
        {
          id: '1',
          name: 'Cotton',
          checked : true
        },
        {
          id: '2',
          name: 'Silk',
          checked : false
        }
 ]

However, even when the value is true, the checkbox is not checked; why??

I have this in codepen:

https://codepen.io/averied/pen/JjYQLJQ?editable=true&editors=101%3Dhttps%3A%2F%2Fvuetifyjs.com%2Fen%2Fcomponents%2Fselection-controls%2F

Body: You don't need : before v-model.


问:
laravel the requested url was not found on this server
I've an Ubuntu 14.04 kernel. I was installing my Laravel application in this server.
After installing, I tried to set the root directory to public.

```<code>sudo nano /etc/apache2/sites-available/000-default.conf
</code>```

I have only these options in the file

```<code><VirtualHost *:80>
        # The ServerName directive sets the request scheme, hostname and port t$
        # the server uses to identify itself. This is used when creating
        # redirection URLs. In the context of virtual hosts, the ServerName
        # specifies what hostname must appear in the request's Host: header to
        # match this virtual host. For the default virtual host (this file) this
        # value is not decisive as it is used as a last resort host regardless.
        # However, you must set it for any further virtual host explicitly.
        #ServerName www.example.com

        ServerAdmin webmaster@localhost
        DocumentRoot /var/www/html/public/

        # Available loglevels: trace8, ..., trace1, debug, info, notice, warn,
        # error, crit, alert, emerg.
        # It is also possible to configure the loglevel for particular
        # modules, e.g.
        #LogLevel info ssl:warn

        ErrorLog ${APACHE_LOG_DIR}/error.log
        CustomLog ${APACHE_LOG_DIR}/access.log combined

        # For most configuration files from conf-available/, which are
        # enabled or disabled at a global level, it is possible to
        # include a line for only one particular virtual host. For example the
        # following line enables the CGI configuration for this host only
        # after it has been globally disabled with "a2disconf".
        #Include conf-available/serve-cgi-bin.conf
</VirtualHost>

# vim: syntax=apache ts=4 sw=4 sts=4 sr noet
</code>```

I've changed the Document root to

```<code>DocumentRoot /var/www/html/public/
</code>```

Now when I tried to access my Laravel App, through 123.xxx.xxx.xxx/ it shows the home page and working well. It gets all the GET variable too. Eg: 123.xxx.xxx.xxx?type=wefwef

But when I go to other links such as 123.xxx.xxx.xxx/login it gives me an error

```<code>Not Found

The requested URL /login/ was not found on this server.

Apache/2.4.7 (Ubuntu) Server at 104.236.234.85 Port 80
</code>```

I have the routes.php working well on localhost. But not on this server. Please help me.

答:
For Ubunutu 18.04 inside a vagrant box ... This is what helped me

Ensure www-data has permissions to the .htaccess file

```
  <code>
    sudo chown www-data.www-data .htaccess
  </code>
```

edit the apache2 conf to allow for symlinks etc

```
  <code>
    sudo nano /etc/apache2/apache2.conf
  </code>
```

Add this to the file

<Directory /var/www/html/>
  Options Indexes FollowSymLinks
  AllowOverride all
  Require all granted
</Directory>```
</div>
</div>
</p>

<ol start="3">
<li><p>Restart your apache2 server</p>

```sudo service apache2 restart```

I hope this helps someone.

Body:
I've an Ubuntu 14.04 kernel. I was installing my Laravel application in this server.
After installing, I tried to set the root directory to public.

sudo nano /etc/apache2/sites-available/000-default.conf

I have only these options in the file

<VirtualHost *:80>
        # The ServerName directive sets the request scheme, hostname and port t$
        # the server uses to identify itself. This is used when creating
        # redirection URLs. In the context of virtual hosts, the ServerName
        # specifies what hostname must appear in the request's Host: header to
        # match this virtual host. For the default virtual host (this file) this
        # value is not decisive as it is used as a last resort host regardless.
        # However, you must set it for any further virtual host explicitly.
        #ServerName www.example.com

        ServerAdmin webmaster@localhost
        DocumentRoot /var/www/html/public/

        # Available loglevels: trace8, ..., trace1, debug, info, notice, warn,
        # error, crit, alert, emerg.
        # It is also possible to configure the loglevel for particular
        # modules, e.g.
        #LogLevel info ssl:warn

        ErrorLog ${APACHE_LOG_DIR}/error.log
        CustomLog ${APACHE_LOG_DIR}/access.log combined

        # For most configuration files from conf-available/, which are
        # enabled or disabled at a global level, it is possible to
        # include a line for only one particular virtual host. For example the
        # following line enables the CGI configuration for this host only
        # after it has been globally disabled with "a2disconf".
        #Include conf-available/serve-cgi-bin.conf
</VirtualHost>

# vim: syntax=apache ts=4 sw=4 sts=4 sr noet

I've changed the Document root to

DocumentRoot /var/www/html/public/

Now when I tried to access my Laravel App, through 123.xxx.xxx.xxx/ it shows the home page and working well. It gets all the GET variable too. Eg: 123.xxx.xxx.xxx?type=wefwef

But when I go to other links such as 123.xxx.xxx.xxx/login it gives me an error

Not Found

The requested URL /login/ was not found on this server.

Apache/2.4.7 (Ubuntu) Server at 104.236.234.85 Port 80

I have the routes.php working well on localhost. But not on this server. Please help me.

Body:
For Ubunutu 18.04 inside a vagrant box ... This is what helped me

Ensure www-data has permissions to the .htaccess file

    sudo chown www-data.www-data .htaccess

edit the apache2 conf to allow for symlinks etc

    sudo nano /etc/apache2/apache2.conf

Add this to the file

<Directory /var/www/html/>
  Options Indexes FollowSymLinks
  AllowOverride all
  Require all granted
</Directory>

Restart your apache2 server

sudo service apache2 restart

I hope this helps someone.


问:
what is the purpose of using this parameter, int (*cmp) (void*, void*)
in my homework ı couldn't understand this parameter ;

```<code>set_maker(LINKEDSTACK stack, int (*cmp) (void*, void*))
</code>```

can anybody explain this using?

thank you for helping.

答:
int (*cmp) (void*, void*)

It is the pointer to the function taking two parameters of type void * and returning int

It should be probably the function which compares two pointers or objects referenced by the pointers - who knows

Body:
in my homework ı couldn't understand this parameter ;

set_maker(LINKEDSTACK stack, int (*cmp) (void*, void*))

can anybody explain this using?

thank you for helping.


问:
Is there a callback for when a `RecylerView.ViewHolder` instance should be GC'd?

class MyRecyclerViewHolder : RecyclerView.ViewHolder {

  fun onBind(data: Data) {
    // launching an asynchronous action
  }
}
```

<p>I need to cancel the async action I'm launching when <code>onBind(..)</code> is called again on the same <code>MyRecyclerViewHolder</code> instance, or if <code>MyRecyclerViewHolder</code> is ready to be GC'd for whatever reason.</p>

<p>Obviously I can identify when <code>onBind(..)</code> is called again, but how can I register to be made aware of when the <code>MyRecyclerViewHolder(..)</code> instance is ready for GC so I can cancel the async action?</p>

<p>EDIT: Another way to think about this is that imagine that <code>ViewHolder</code> had the following API:</p>

<pre class="lang-kotlin prettyprint-override"><code>interface ViewHolder {

  // because you have constructor access, there's no need for `onCreate(..)`

  // may be called multiple times
  fun onBind(data: Data)

  fun onDestroy() // called once when it is no longer relevant
}
</code>```

How can I be notified that my ViewHolder should be "destroyed" - aka it is no longer relevant for the UI?

答:
You are maybe looking for something like this:

```<code>override fun onViewAttachedToWindow(holder: Type) {
}

override fun onViewDetachedFromWindow(holder: Type) {
}
</code>```

The onViewAttachedToWindow will be called everytime the viewholder gets in the screen. The onViewDetachedFromWindow will be called everytime the viewholder gets off the screen.

Body:
class MyRecyclerViewHolder : RecyclerView.ViewHolder {

  fun onBind(data: Data) {
    // launching an asynchronous action
  }
}

I need to cancel the async action I'm launching when onBind(..) is called again on the same MyRecyclerViewHolder instance, or if MyRecyclerViewHolder is ready to be GC'd for whatever reason.

Obviously I can identify when onBind(..) is called again, but how can I register to be made aware of when the MyRecyclerViewHolder(..) instance is ready for GC so I can cancel the async action?

EDIT: Another way to think about this is that imagine that ViewHolder had the following API:

interface ViewHolder {

  // because you have constructor access, there's no need for `onCreate(..)`

  // may be called multiple times
  fun onBind(data: Data)

  fun onDestroy() // called once when it is no longer relevant
}

How can I be notified that my ViewHolder should be "destroyed" - aka it is no longer relevant for the UI?

Body:
You are maybe looking for something like this:

override fun onViewAttachedToWindow(holder: Type) {
}

override fun onViewDetachedFromWindow(holder: Type) {
}

The onViewAttachedToWindow will be called everytime the viewholder gets in the screen. The onViewDetachedFromWindow will be called everytime the viewholder gets off the screen.


问:
Table Row onClick Overriding Checkbox
I'm having some issues with checkboxes in a table being "overridden" by the onClick attribute of the table row they are placed in.

I have a column with checkboxes as the leftmost column of a table, and I also have an onClick function defined for each table row. As a result, when I click any of the checkboxes, the onClick function of the table row triggers (though the checkbox is still clicked correctly).

Is there any way I can work around this? Having the table row's onClick only register for the other columns, for example? (I have no clue how the implementation of that would work, unfortunately, but that's the first solution I can think of.)

Thanks in advance!

答:
```<code>$('.columnClass').click(function(e){
     if(this == e.target){
      //do things
 }
</code>```

})

This will only execute your click handler when it's actually the column that's being clicked, not the checkbox.

Title: Table Row onClick Overriding Checkbox

Body:
$('.columnClass').click(function(e){
     if(this == e.target){
      //do things
 }

})

This will only execute your click handler when it's actually the column that's being clicked, not the checkbox.


问:
How do I make a refresh button that refresh every user's input on form minutes
I have a code that read in a richtextbox the last row from a txt file.
What I want to introduce now is a refresh button with something like a text box.
I want to put it so user can put the number on the form that means minutes for the code and then user press the button refresh and the program will refresh every ... minutes. The program just call last file opened with open file dialog, refresh it on richtextbox every ... minutes.

Here is what I did to refresh just when you press the button refresh (maybe for implement it as I want I should put on the form another button and a text box?):

```<code>    private string thePath;
    public async void OpenFileBtn_ClickAsync(object sender, EventArgs e)
    {
         using(OpenFileDialog ofd = new OpenFileDialog() { Filter = "Text File|*.txt", Multiselect = false })
         {

             if (ofd.ShowDialog() == DialogResult.OK)
             {
                    thePath = ofd.FileName;
                    Refresh();
             }
         }
    }

    private void Refresh()
    {
        using (StreamReader rd = new StreamReader(thePath))
        {
            string[] lines = rd.ReadToEnd().Split(new string[] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries);
            ReaderRichTxtBox.Text = lines[lines.Length - 1];
        }
    }

    private void RefreshBtn_Click(object sender, EventArgs e)
    {
        Refresh();
    }
</code>```

How should the code be?
Thank you for help.

答:
```<code>public partial class TextReaderForm : Form
{

    public TextReaderForm()
    {
        InitializeComponent();
    }
    private System.Windows.Forms.Timer refreshtimer;
    private string thePath;
    public async void OpenFileBtn_ClickAsync(object sender, EventArgs e)
    {
         using(OpenFileDialog ofd = new OpenFileDialog() { Filter = "Text File|*.txt", Multiselect = false })
         {

             if (ofd.ShowDialog() == DialogResult.OK)
             {
                //using (StreamReader rd = new StreamReader(ofd.FileName))
                {
                    //ReaderRichTxtBox.Text = await rd.ReadToEndAsync();
                    //string[] lines = rd.ReadToEnd().Split(new string[] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries);
                    //ReaderRichTxtBox.Text = lines[lines.Length - 1];
                    thePath = ofd.FileName;
                    Refresh();
                }
             }
         }
    }

    private void Refresh()
    {
        using (StreamReader rd = new StreamReader(thePath))
        {
            string[] lines = rd.ReadToEnd().Split(new string[] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries);
            ReaderRichTxtBox.Text = lines[lines.Length - 1];
        }
    }

    private void RefreshBtn_Click(object sender, EventArgs e)
    {
        Refresh();
    }

    private void RefreshTimerBtn_Click(object sender, EventArgs e)
    {
        refreshtimer = new System.Windows.Forms.Timer();
        refreshtimer.Tick += new EventHandler(timer_Tick);
        refreshtimer.Interval = Convert.ToInt32(RefreshTimerTxtBox.Text) * 60000; //60000 is one minute
        timer1.Start();
    }
    void timer_Tick(object sender, EventArgs e)
    {
        Refresh();
    }
}
</code>```

Body:
I have a code that read in a richtextbox the last row from a txt file.
What I want to introduce now is a refresh button with something like a text box.
I want to put it so user can put the number on the form that means minutes for the code and then user press the button refresh and the program will refresh every ... minutes. The program just call last file opened with open file dialog, refresh it on richtextbox every ... minutes.

Here is what I did to refresh just when you press the button refresh (maybe for implement it as I want I should put on the form another button and a text box?):

    private string thePath;
    public async void OpenFileBtn_ClickAsync(object sender, EventArgs e)
    {
         using(OpenFileDialog ofd = new OpenFileDialog() { Filter = "Text File|*.txt", Multiselect = false })
         {

             if (ofd.ShowDialog() == DialogResult.OK)
             {
                    thePath = ofd.FileName;
                    Refresh();
             }
         }
    }

    private void Refresh()
    {
        using (StreamReader rd = new StreamReader(thePath))
        {
            string[] lines = rd.ReadToEnd().Split(new string[] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries);
            ReaderRichTxtBox.Text = lines[lines.Length - 1];
        }
    }

    private void RefreshBtn_Click(object sender, EventArgs e)
    {
        Refresh();
    }

How should the code be?
Thank you for help.


问:
Select a specific group of a grouped dataframe with pandas
I have the following dataframe:

```<code>df.index = df['Date']
df.groupby([df.index.month, df['Category'])['Amount'].sum()

Date   Category     Amount
1      A            -125.35
       B            -40.00
                    ...
12     A            505.15
       B            -209.00
</code>```

I would like to report the sum of the Amount for every Category B like:

```<code>Date   Category     Amount
1      B            -40.00
                    ...
12     B            -209.00
</code>```

I tried the df.get_group method but this method needs tuple that contains the Date and Category key. Is there a way to filter out only the Categories with B?

答:
You can use IndexSlice:

```<code># groupby here
df_group = df.groupby([df.index.month, df['Category'])['Amount'].sum()

# report only Category B
df_group.loc[pd.IndexSlice[:,'B'],:]
</code>```

Or query:

```<code># query works with index level name too
df_group.query('Category=="B"')
</code>```

Output:

```<code>               Amount
Date Category
1    B          -40.0
12   B         -209.0
</code>```

Body:
I have the following dataframe:

df.index = df['Date']
df.groupby([df.index.month, df['Category'])['Amount'].sum()

Date   Category     Amount
1      A            -125.35
       B            -40.00
                    ...
12     A            505.15
       B            -209.00

I would like to report the sum of the Amount for every Category B like:

Date   Category     Amount
1      B            -40.00
                    ...
12     B            -209.00

I tried the df.get_group method but this method needs tuple that contains the Date and Category key. Is there a way to filter out only the Categories with B?

Body:
You can use IndexSlice:

# groupby here
df_group = df.groupby([df.index.month, df['Category'])['Amount'].sum()

# report only Category B
df_group.loc[pd.IndexSlice[:,'B'],:]

Or query:

# query works with index level name too
df_group.query('Category=="B"')

Output:

               Amount
Date Category
1    B          -40.0
12   B         -209.0


问:
How to stop console from repeating loop over and over?
I'm trying to make the incorrect password start the loop over until the right password is inputted (which it does) but System.out.println statements repeat infinitely in the console. A break statement just terminates the code, but I want it to keep going except only printing the statements once. Any solutions?</p>

```<code>    public static void main(String[] args){

    System.out.println("What is the password?");

    Scanner passwordScan = new Scanner(System.in);
    String pass = passwordScan.nextLine();
    String password = "JohnnyRoberts123";

    while(password != pass) {
        System.out.println("Wrong password!");
        System.out.println("Try again, what is the password?");

        continue;
</code>```

答:
First, never hardcode the password. If just for testing , it's ok.

Second, you must update the password in the while loop, in order to check for validation as follows :

```<code>public static void main(String[] args){

    System.out.println("What is the password?");

    Scanner passwordScan = new Scanner(System.in);
    String password = "JohnnyRoberts123";
    String pass="";

    while(!password.equals(pass)) {
        System.out.println("Wrong password!");
        System.out.println("Try again, what is the password?");
        pass = passwordScan.nextLine();
        continue;
}
</code>```

Notice here, you can't compare strings as integers using == , Strings are treated as objects so you must compare them by using str1.equals(str2)

Body:
I'm trying to make the incorrect password start the loop over until the right password is inputted (which it does) but System.out.println statements repeat infinitely in the console. A break statement just terminates the code, but I want it to keep going except only printing the statements once. Any solutions?

    public static void main(String[] args){

    System.out.println("What is the password?");

    Scanner passwordScan = new Scanner(System.in);
    String pass = passwordScan.nextLine();
    String password = "JohnnyRoberts123";

    while(password != pass) {
        System.out.println("Wrong password!");
        System.out.println("Try again, what is the password?");

        continue;

Body:
First, never hardcode the password. If just for testing , it's ok.

Second, you must update the password in the while loop, in order to check for validation as follows :

public static void main(String[] args){

    System.out.println("What is the password?");

    Scanner passwordScan = new Scanner(System.in);
    String password = "JohnnyRoberts123";
    String pass="";

    while(!password.equals(pass)) {
        System.out.println("Wrong password!");
        System.out.println("Try again, what is the password?");
        pass = passwordScan.nextLine();
        continue;
}

Notice here, you can't compare strings as integers using == , Strings are treated as objects so you must compare them by using str1.equals(str2)


问:
how to structure a create-react-app project
I am using django on the backend and on the front end I am using react with create-react-app.

I have different apps on my web page that are somewhat independent from each other:

```<code>mydomainname/home
mydomainname/foo
mydomainname/bar
</code>```

They are all somewhat connected but logically completely different which is why I separated them.

Is this handled with only one create-react-app and one index.html file in the build folder? And something like the  browser router package for the different apps?

For example, if I look at the Facebook homepage (in case I want to build that with React) I understand that my news feed and my profile page and other people's pages are all connected and share similar components which is why it would make sense to have one index.html file.

But if I create a new public page (e.g. for a business figure), are all these components and functionalities handled in the same one index.html file? I could imagine that this will run into memory leaks and performance issues, or is this not the case? I can't seem to find anything about that neither in the create-react-app documentation nor through google.

答: React is not Html. In React you have only one page named index.html in folder public. The "pages" in react are named as 'Components', so you just create components and link them to each other. The first generated example component is App (App.js) component in src folder. All the transitions (transition from one component to second) will be done in index.html file.

Body:
I am using django on the backend and on the front end I am using react with create-react-app.

I have different apps on my web page that are somewhat independent from each other:

mydomainname/home
mydomainname/foo
mydomainname/bar

They are all somewhat connected but logically completely different which is why I separated them.

Is this handled with only one create-react-app and one index.html file in the build folder? And something like the  browser router package for the different apps?

For example, if I look at the Facebook homepage (in case I want to build that with React) I understand that my news feed and my profile page and other people's pages are all connected and share similar components which is why it would make sense to have one index.html file.

But if I create a new public page (e.g. for a business figure), are all these components and functionalities handled in the same one index.html file? I could imagine that this will run into memory leaks and performance issues, or is this not the case? I can't seem to find anything about that neither in the create-react-app documentation nor through google.


问:
Does const reference have external linkage in C++?
According to clause 3 of section 3.5 of C++ 1998 standard, a const reference has internal linkage.

A name having namespace scope (3.3.5) has internal linkage if it is the name of

an object, reference, function or function template that is explicitly declared static or,

an object or reference that is explicitly declared const and neither explicitly declared extern nor previously declared to have external linkage; or

a data member of an anonymous union.

But why multiple definition conflict is generated when compiling the following code?

```<code>// a.cpp
const int& a = 1;

int main()
{
    return 0;
}

// b.cpp
const int& a = 1;
</code>```

And then compile the code.

```<code>$ g++ a.cpp b.cpp
/tmp/ccb5Qi0M.o:(.bss+0x0): multiple definition of `a'
/tmp/ccD9vrzP.o:(.bss+0x0): first defined here
collect2: error: ld returned 1 exit status
</code>```

If the const reference is changed to const, as follows

```<code>// a.cpp
const int a = 1;

int main()
{
    return 0;
}

// b.cpp
const int a = 1;
</code>```

It is OK to compile.

答:
This is a program with the most const reference ever. It compiles, and links with C++17 (try it):

```<code>// a.cpp

extern const int& ir;

int main() { return ir; }
</code>```

```<code>// b.cpp

constexpr const int& ir = 42;
</code>```

As you can see, ir can be referenced from another translation unit, i.e. it has external linkage.

Conclusion: global reference variables have external linkage, unless declared as static or in anonymous namespace. Also the constexpr keyword on references does not make the reference a constant view to the referree (try it).

And constexpr references are not implicitly inline. This is redefinition of ir in C++17 (try it):

```<code>// a.cpp

constexpr const int& ir = 42;

int main() { return ir; }
</code>```

```<code>// b.cpp

constexpr const int& ir = 42;
</code>```

If you put inline before the declaration of ir in both files, it compiles and links (try it).

Body:
According to clause 3 of section 3.5 of C++ 1998 standard, a const reference has internal linkage.

A name having namespace scope (3.3.5) has internal linkage if it is the name of

an object, reference, function or function template that is explicitly declared static or,

an object or reference that is explicitly declared const and neither explicitly declared extern nor previously declared to have external linkage; or

a data member of an anonymous union.

But why multiple definition conflict is generated when compiling the following code?

// a.cpp
const int& a = 1;

int main()
{
    return 0;
}

// b.cpp
const int& a = 1;

And then compile the code.

$ g++ a.cpp b.cpp
/tmp/ccb5Qi0M.o:(.bss+0x0): multiple definition of `a'
/tmp/ccD9vrzP.o:(.bss+0x0): first defined here
collect2: error: ld returned 1 exit status

If the const reference is changed to const, as follows

// a.cpp
const int a = 1;

int main()
{
    return 0;
}

// b.cpp
const int a = 1;

It is OK to compile.

Body:
This is a program with the most const reference ever. It compiles, and links with C++17 (try it):

// a.cpp

extern const int& ir;

int main() { return ir; }

// b.cpp

constexpr const int& ir = 42;

As you can see, ir can be referenced from another translation unit, i.e. it has external linkage.

Conclusion: global reference variables have external linkage, unless declared as static or in anonymous namespace. Also the constexpr keyword on references does not make the reference a constant view to the referree (try it).

And constexpr references are not implicitly inline. This is redefinition of ir in C++17 (try it):

// a.cpp

constexpr const int& ir = 42;

int main() { return ir; }

// b.cpp

constexpr const int& ir = 42;

If you put inline before the declaration of ir in both files, it compiles and links (try it).


答:
Yes, and it's called Sass.

http://sass-lang.com/

Title: Css3 evaluatable expressions?

Body:
Are there any techniques that allow for expressions in css3 statements?

Frequently it is helpful to do such things as width: 35%+20px or similar. Right now the only solutions I have to these circumstances are to either redesign the page or to use javascript to dynamically set the css.


答:
You just need to move your code around a little so the line asking for input (passwordScan.nextLine()) is inside the while loop:

```<code>public static void main(String[] args) {
    Scanner passwordScan = new Scanner(System.in);
    String password = "JohnnyRoberts123";
    System.out.println("What is the password?");

    while (true) {
        String pass = passwordScan.nextLine();

        if (!password.equals(pass)) {
            System.out.println("Wrong password!");
            System.out.println("Try again, what is the password?");
        } else {
            break;
        }
    }
}
</code>```

Also note that you should never use != to compare strings, always use the equals method because it actually compares the string contents, not just the objects themselves.

Title: How to stop console from repeating loop over and over?

Body:
You just need to move your code around a little so the line asking for input (passwordScan.nextLine()) is inside the while loop:

public static void main(String[] args) {
    Scanner passwordScan = new Scanner(System.in);
    String password = "JohnnyRoberts123";
    System.out.println("What is the password?");

    while (true) {
        String pass = passwordScan.nextLine();

        if (!password.equals(pass)) {
            System.out.println("Wrong password!");
            System.out.println("Try again, what is the password?");
        } else {
            break;
        }
    }
}

Also note that you should never use != to compare strings, always use the equals method because it actually compares the string contents, not just the objects themselves.