问:
Ruby on Rails - Error making new app (rb:55:in 'require')
I've been following Mike Hartl's excellent Ruby on Rails Tutorial`.

I had to make some decisions earlier about versions for gem files and ruby. I decided (after some problems getting Heroku to work that I'd directly mimic the tutorial and versions of ruby described - leading me to go with rvm use 2.0.0 to set my version of ruby.

All was great on chapter one but now I'm getting an error message when i try to create a new rails project:

```<code>$ rails new demo_app
</code>```

/home/huw/.rvm/rubies/ruby-2.0.0-p481/lib/ruby/site_ruby/2.0.0/rubygems/core_ext/kernel_require.rb:55:in require': cannot load such file -- rails/cli (LoadError)
      from /home/huw/.rvm/rubies/ruby-2.0.0-p481/lib/ruby/site_ruby/2.0.0/rubygems/core_ext/kernel_require.rb:55:inrequire'
      from /usr/bin/rails:9:in `'

I have no idea what that means... but as its referencing my ruby version I'm guessing that my rails and ruby versions are out of sync...

Could someone advise on possible courses of action?

I imagine possible options would be:

Reset my ruby version to the latest (but I don't know what clashes
that would create with gems!)

Downgrade from rails 4.1 to rails 4 (I believe that's Mike Hardl's version)

Force things through somehow

I'm a complete rails Noob however, and have no idea where to begin on any of those options - or if that error code even backs up my assumptions!

答:
check for the rails is installed on your machine by the command bundle show rails.

If you get the version of rails and are still getting the above error, to resolve it you may have to use the command bundle exec before every rails command as in bundle exec rails s.

Body:
I've been following Mike Hartl's excellent Ruby on Rails Tutorial`.

I had to make some decisions earlier about versions for gem files and ruby. I decided (after some problems getting Heroku to work that I'd directly mimic the tutorial and versions of ruby described - leading me to go with rvm use 2.0.0 to set my version of ruby.

All was great on chapter one but now I'm getting an error message when i try to create a new rails project:

$ rails new demo_app

/home/huw/.rvm/rubies/ruby-2.0.0-p481/lib/ruby/site_ruby/2.0.0/rubygems/core_ext/kernel_require.rb:55:in require': cannot load such file -- rails/cli (LoadError)
      from /home/huw/.rvm/rubies/ruby-2.0.0-p481/lib/ruby/site_ruby/2.0.0/rubygems/core_ext/kernel_require.rb:55:inrequire'
      from /usr/bin/rails:9:in `'

I have no idea what that means... but as its referencing my ruby version I'm guessing that my rails and ruby versions are out of sync...

Could someone advise on possible courses of action?

I imagine possible options would be:

Reset my ruby version to the latest (but I don't know what clashes
that would create with gems!)

Downgrade from rails 4.1 to rails 4 (I believe that's Mike Hardl's version)

Force things through somehow

I'm a complete rails Noob however, and have no idea where to begin on any of those options - or if that error code even backs up my assumptions!


来源: stackexchange

问:
Trying to do a where filter in findOne and in Node api returns empty array when filtering by ids in loopback
Trying to do a where filter in findOne and in Node api returns empty array when filtering by ids in loopback

https://url/api/Model1/findOne?filter={"where":{"attrs":"id"}}
where id is exactly 24 digits long

答:
It is possible that you simple don't have an object with that ID in that particular collection in the database. In such a case you should get an empty array.

Or you may need to find by id and not by attr - it depends on how the relevant field in your database is named.

See the docs, there are good examples there: https://loopback.io/doc/en/lb2/Where-filter.html

E.g. this:

```<code>http://localhost:3000/api/Books?filter={"where":{"or":[{"id":1},{"id":2}]}}
</code>```

Note that the id is used and not attr. See what is your field in your case.

ContentLicense: CC BY-SA 4.0

Body:
It is possible that you simple don't have an object with that ID in that particular collection in the database. In such a case you should get an empty array.

Or you may need to find by id and not by attr - it depends on how the relevant field in your database is named.

See the docs, there are good examples there: https://loopback.io/doc/en/lb2/Where-filter.html

E.g. this:

http://localhost:3000/api/Books?filter={"where":{"or":[{"id":1},{"id":2}]}}

Note that the id is used and not attr. See what is your field in your case.

ContentLicense: CC BY-SA 3.0


问:
problem debugging a android application
i have some problem when i want to Debug my android code. When i go to Debug as/ it says (none applicable). I have set a breakpoint though there's no blue arrow on it. Anyone who knows why this is happening?

Thanks

答: You should setup your debug configuration. It should know what avd to use to launch your code on. If you're using eclipse this article should help.</p>

ContentLicense: CC BY-SA 2.5

Title: problem debugging a android application


问:
PHP Count lines and rows (length per line) of file
I have a php file like this.

```<code>Line   |   Length of Line
              1 2 3 4 5 6 7 8 9
1        |  < ? php
2        |
3        |                $g r a d e = 5;
4        |
5        |  ? >
</code>```

How to count Total lines and Length of each line from this file in php?

答:
This stack respond partially to your question: https://stackoverflow.com/a/13246630/6535806, just need in the while to get le length of the $line. So the code should look like:

```<code>$handle = fopen("filename.extention", "r");
// if the file exist
if ($handle) {
    // for each line
    while (($line = fgets($handle)) !== false) {
        // write the length of the line
        echo strlen($line).'<br />';
    }
    // then we close the file opened
    fclose($handle);
} else {
    // error opening the file.
}
</code>```

Body:
I have a php file like this.

Line   |   Length of Line
              1 2 3 4 5 6 7 8 9
1        |  < ? php
2        |
3        |                $g r a d e = 5;
4        |
5        |  ? >

How to count Total lines and Length of each line from this file in php?

Body:
This stack respond partially to your question: https://stackoverflow.com/a/13246630/6535806, just need in the while to get le length of the $line. So the code should look like:

$handle = fopen("filename.extention", "r");
// if the file exist
if ($handle) {
    // for each line
    while (($line = fgets($handle)) !== false) {
        // write the length of the line
        echo strlen($line).'<br />';
    }
    // then we close the file opened
    fclose($handle);
} else {
    // error opening the file.
}


问:
Make a Android application use FIPS 140-2 valiated cryptography
I have client who wants our application to use FIPS 140-2 validated cryptography. The app uses Okhttp and does some HTTPS requests. AFAIK Android uses OpenSSL C library and uses java wrapper javax/net/ssl.

Questions:

How to make android Application FIPS 140 -2 Complaint?

Is it not android at stack(OS) level should use FIPS Compliant OpenSSL, hence all app are default  FIPS 140 -2 Compliant?

Or our app should use FIPS 140-2 validated cryptography and make java javax/net/ssl to use it? Feasible?

Is there a  FIPS 140-2 JCE library which can be pluggable to OKhttp?

Thanks

答:
Modified OKHTTP and OKIO code to use the WolfSSL java wrappers and made it work.

Now any https requests made will go to WolfSSL layer instead of stock android BoringSSL/OpenSSL.


问:
Groovy global storing of closures from different scripts
Is it to possible to store closures from different groovy scripts?
Let's say I have some kind of class that should store the closures:

```<code>package com.test

class ClosureContainer {
    static closures = [:]

    static def AddClosure(String name, Closure cl) {
        println "Adding closure named ${name}"
        closures[name] = cl
    }
}
</code>```

And then I would like to have groovy scripts that would add closures to it:

```<code>import com.test.ClosureContainer as container

container.AddClosure("Interesting stuff", {
    println "I'm doing some interesting stuff"
})
</code>```

And later, I should be able to call it like:

```<code>def closureCode = ClosureContainer.closures["Interesting stuff"]
closureCode()
</code>```

What is the best approach to do it in Groovy? I'm not sure how to handle invoking of the scripts because classes are generated from these scripts.
I'm able to create instances of the scripts during runtime, but I'm not able to retrieve list of the classes/scripts without hardcoding it.

UPDATE:

Let's suppose I have testScript.groovy in package com.test.scripts that adds a few closures to the container. I tried to let the gradle generate classes from the scripts and create instance in the code like this:

```<code>def className = Class.forName("com.test.scripts.testScript")
def instance = className.newInstance()
instance.run()
</code>```

And I'm hardcoding the testScript name. But there will be a lot of scripts and I should be able to retrieve it dynamically.

答:
The recommended way to run groovy script is to use GroovyScriptEngine:

```<code>String[] path = new String[] { "." };
GroovyScriptEngine engine = new GroovyScriptEngine(path);
engine.run("yoursriptname.groovy", new Binding())
</code>```

NB: yoursriptname should be the path of your script relative to path.

If you want to pass bindings (arguments and then get the results) you have to use Binding.

Body:
Is it to possible to store closures from different groovy scripts?
Let's say I have some kind of class that should store the closures:

package com.test

class ClosureContainer {
    static closures = [:]

    static def AddClosure(String name, Closure cl) {
        println "Adding closure named ${name}"
        closures[name] = cl
    }
}

And then I would like to have groovy scripts that would add closures to it:

import com.test.ClosureContainer as container

container.AddClosure("Interesting stuff", {
    println "I'm doing some interesting stuff"
})

And later, I should be able to call it like:

def closureCode = ClosureContainer.closures["Interesting stuff"]
closureCode()

What is the best approach to do it in Groovy? I'm not sure how to handle invoking of the scripts because classes are generated from these scripts.
I'm able to create instances of the scripts during runtime, but I'm not able to retrieve list of the classes/scripts without hardcoding it.

UPDATE:

Let's suppose I have testScript.groovy in package com.test.scripts that adds a few closures to the container. I tried to let the gradle generate classes from the scripts and create instance in the code like this:

def className = Class.forName("com.test.scripts.testScript")
def instance = className.newInstance()
instance.run()

And I'm hardcoding the testScript name. But there will be a lot of scripts and I should be able to retrieve it dynamically.

Body:
The recommended way to run groovy script is to use GroovyScriptEngine:

String[] path = new String[] { "." };
GroovyScriptEngine engine = new GroovyScriptEngine(path);
engine.run("yoursriptname.groovy", new Binding())

NB: yoursriptname should be the path of your script relative to path.

If you want to pass bindings (arguments and then get the results) you have to use Binding.


问:
Replacing values of a factor variable in a column of a data frame with an existing value of that column
This is my dataset:

```<code>codes<-c("a1", "b1", "c1", "a2", "b2", "c2", "a3", "b3", "c3")
dt= data.frame(codes)
</code>```

Now I want to replace “a1”,“a2” and “a3” with another existing value say “c3”.
As new to R, I know to replace a single value in a column, as in this case, my code would be:

```<code>dt$codes[dt$codes== “a1”] <- c3
</code>```

But since I need to replace more than one value here, I am thinking to solve it like this using the OR logic where codes = a1 or codes = a2 or codes = a3

```<code>dt$codes[dt$codes== “a1” || “a2” || “a3”] <- “c3”
</code>```

Obviously my codes throw some syntax error here. I am thinking that using OR approach might not be correct here.So are there any easy ways to replace the values of a column with an already existing value in that column? Thanks

答:
We can use %in%

```<code> dt$codes[dt$codes %in% c('a1', 'a2', 'a3')] <- 'c3'
</code>```

As it is factor class, more efficient approach would be to assign using levels

```<code>levels(dt$codes)[levels(dt$codes) %in% c('a1', 'a2', 'a3')] <- 'c3'
</code>```

Body:
This is my dataset:

codes<-c("a1", "b1", "c1", "a2", "b2", "c2", "a3", "b3", "c3")
dt= data.frame(codes)

Now I want to replace “a1”,“a2” and “a3” with another existing value say “c3”.
As new to R, I know to replace a single value in a column, as in this case, my code would be:

dt$codes[dt$codes== “a1”] <- c3

But since I need to replace more than one value here, I am thinking to solve it like this using the OR logic where codes = a1 or codes = a2 or codes = a3

dt$codes[dt$codes== “a1” || “a2” || “a3”] <- “c3”

Obviously my codes throw some syntax error here. I am thinking that using OR approach might not be correct here.So are there any easy ways to replace the values of a column with an already existing value in that column? Thanks

Body:
We can use %in%

 dt$codes[dt$codes %in% c('a1', 'a2', 'a3')] <- 'c3'

As it is factor class, more efficient approach would be to assign using levels

levels(dt$codes)[levels(dt$codes) %in% c('a1', 'a2', 'a3')] <- 'c3'


问:
Vis.js callback when the network finishes loading
I'm using a vis.js network that takes in some data and add's said data as nodes within the network.

The only issue is that after the network has been declared (using the nodes and edges specified, which may be a lot) it takes a while for the nodes in the network to render in.

Even when I declare the network like so:

```<code>var network = new vis.Network(container, data, options);
</code>```

And then follow it up with making the container visible:

```<code>$('#BreakdownBox').css('display','inline');
</code>```

It still becomes visible before the nodes have finished buffering, showing a blank canvas until they've rendered in.

My Question: How can I only make it visible once it's finished loading the nodes?
Is there a way to use the promises.js with this? Something like:

```<code>var network = new vis.Network(container, data, options).done(function{
    $('#BreakdownBox').css('display','inline');
});
</code>```

答:
In the end I used the native loading bar to vis.js, using their example code here

It's a little faulty but it's all I needed.

Body:
I'm using a vis.js network that takes in some data and add's said data as nodes within the network.

The only issue is that after the network has been declared (using the nodes and edges specified, which may be a lot) it takes a while for the nodes in the network to render in.

Even when I declare the network like so:

var network = new vis.Network(container, data, options);

And then follow it up with making the container visible:

$('#BreakdownBox').css('display','inline');

It still becomes visible before the nodes have finished buffering, showing a blank canvas until they've rendered in.

My Question: How can I only make it visible once it's finished loading the nodes?
Is there a way to use the promises.js with this? Something like:

var network = new vis.Network(container, data, options).done(function{
    $('#BreakdownBox').css('display','inline');
});


问:
What does it mean by object not reversible Django
I'm just trying to make a simple connection to another page using the url tag in Django. I'm getting a error of "'set' object is not reversible". After searching for a bit I've been unsuccessful in finding anything.

urls.py

```<code>from django.conf.urls import url
from . import views

APP_NAME = 'website'
urlpatterns = {
    url(r'^$', views.admin_view, name='adminview'),
    url(r'^eventview/$', views.event_view, name='eventview'),
}
</code>```

admin_view.html

```<code><!DOCTYPE html>
<html lang="en" >
<head>
{% load static %}
  {% block header%}
  {% include 'website/header.html' %}
  {% endblock %}

  <!-- Insert custom css here -->
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>

<!-- top navbar -->
  <nav class="navbar navbar-inverse navbar-fixed-top">
    <div class="container-fluid">

      <div class="navbar-header">
        <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar" aria-expanded="false" aria-controls="navbar">
          <span class="sr-only">Toggle navigation</span>
          <span class="icon-bar"></span>
          <span class="icon-bar"></span>
          <span class="icon-bar"></span>
        </button>
        <a class="navbar-brand" href="#">Vivid Fireworks</a>
      </div>

      <div id="navbar" class="navbar-collapse collapse">
        <ul class="nav navbar-nav navbar-right">
          <li><a href="{% url adminview %}">Dashboard</a></li>
          <li><a href="{% url eventview %}">Add Show</a></li>
          <li><a href="#">Settings</a></li>
          <li><a href="#">Profile</a></li>
          <li><a href="#">Help</a></li>
        </ul>
      </div>
    </div>
  </nav>
</code>```

I haven't ran into this problem before and it seems like it'll be a simple fix just something I'm over looking. Any help is appreciated.

答:
urlpatterns should be a list [...]. You currently have a set {...}. It should be:

```<code>urlpatterns = [
    url(r'^$', views.admin_view, name='adminview'),
    url(r'^eventview/$', views.event_view, name='eventview'),
]
</code>```

In the template, you should use quotes when the url pattern name is a string:

```<code>{% url 'adminview' %}
{% url 'eventview' %}
</code>```

If you want to use namespaces, then app_name should be lowercase.

```<code>app_name = 'website'
url_patterns = [
    ...
]
</code>```

You then need to include the namespace when you use the url tag

```<code>{% url 'website:adminview' %}
{% url 'website:eventview' %}
</code>```

Body:
I'm just trying to make a simple connection to another page using the url tag in Django. I'm getting a error of "'set' object is not reversible". After searching for a bit I've been unsuccessful in finding anything.

urls.py

from django.conf.urls import url
from . import views

APP_NAME = 'website'
urlpatterns = {
    url(r'^$', views.admin_view, name='adminview'),
    url(r'^eventview/$', views.event_view, name='eventview'),
}

admin_view.html

<!DOCTYPE html>

{% load static %}
  {% block header%}
  {% include 'website/header.html' %}
  {% endblock %}

  <meta name="viewport" content="width=device-width, initial-scale=1.0">

        <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar" aria-expanded="false" aria-controls="navbar">
          Toggle navigation

        </button>
        Vivid Fireworks

Dashboard

Add Show

Settings

Profile

Help

I haven't ran into this problem before and it seems like it'll be a simple fix just something I'm over looking. Any help is appreciated.

Body:
urlpatterns should be a list [...]. You currently have a set {...}. It should be:

urlpatterns = [
    url(r'^$', views.admin_view, name='adminview'),
    url(r'^eventview/$', views.event_view, name='eventview'),
]

In the template, you should use quotes when the url pattern name is a string:

{% url 'adminview' %}
{% url 'eventview' %}

If you want to use namespaces, then app_name should be lowercase.

app_name = 'website'
url_patterns = [
    ...
]

You then need to include the namespace when you use the url tag

{% url 'website:adminview' %}
{% url 'website:eventview' %}


问:
Slice columns in several parts Spark(1.5.2)-Scala
I have an RDD greater than 22 columns (therefore, I cannot transform it to a Dataframe in order to make the filtering) with 10 columns and I want to obtain a second dataframe with the columns 3 to 4 and the range of columns 7 to 10. In order to obtain the range from 7 to 10, I use the slice function the following way:

```<code>var aux = rdd.map(_.slice(7, 10))
</code>```

My problem comes when trying to join this interval with the interval from 3 to 4. I have seen that slice method only accepts one range. Is there any way to skip this limitation in order to obtain in a single variable both ranges?

答:
I don't know about performance, but you can do something like this:</p>

```<code>rdd.map(l => ((3 to 4) ++ (7 to 10)).map(l(_)))
</code>```

Body:
I have an RDD greater than 22 columns (therefore, I cannot transform it to a Dataframe in order to make the filtering) with 10 columns and I want to obtain a second dataframe with the columns 3 to 4 and the range of columns 7 to 10. In order to obtain the range from 7 to 10, I use the slice function the following way:

var aux = rdd.map(_.slice(7, 10))

My problem comes when trying to join this interval with the interval from 3 to 4. I have seen that slice method only accepts one range. Is there any way to skip this limitation in order to obtain in a single variable both ranges?

Body:
I don't know about performance, but you can do something like this:

rdd.map(l => ((3 to 4) ++ (7 to 10)).map(l(_)))


问:
How to prevent new tags being created within a Contenteditable element?
```<code><p contenteditable="true"></p>
<p contenteditable="true"></p>
<h1 contenteditable="true"></h1>
</code>```

The code above consists of individual contenteditable elements rather than having the parent be contenteditable.

The problem I have is that when the user hits the Enter button in either of the contenteditable elements, it creates a new tag within that tag itself.

Example

The output would be:

```<code><p contenteditable="true">
    <p>One</p>
    <p>Two</p>
</p>
</code>```

The desired output would be:

```<code><p contenteditable="true"></p>
<p contenteditable="true">One</p>
<p contenteditable="true">Two</p>
</code>```

I am also using jQuery to ensure that all the elements would end up as being contenteditable:

```<code>setInterval(function () {
    $('p').attr('contenteditable','true');
    $('h1').attr('contenteditable','true');
},100);
</code>```

I would appreciate any help, thanks!

答:
I have gotten this to work by checking if a contenteditable element contains a p tag after a certain interval.

If that happens to be the case, the child element will be moved in front of the parent.

```<code>setInterval(function () {
    $("[contenteditable='true']").each(function() {
        finder = $(this).find("p");
        $(finder).insertAfter($(this));
        $(finder).focus();
    });
},100);
</code>```

Body:
The code above consists of individual contenteditable elements rather than having the parent be contenteditable.

The problem I have is that when the user hits the Enter button in either of the contenteditable elements, it creates a new tag within that tag itself.

Example

The output would be:

One

Two

The desired output would be:

One

Two

I am also using jQuery to ensure that all the elements would end up as being contenteditable:

setInterval(function () {
    $('p').attr('contenteditable','true');
    $('h1').attr('contenteditable','true');
},100);

I would appreciate any help, thanks!

Body:
I have gotten this to work by checking if a contenteditable element contains a p tag after a certain interval.

If that happens to be the case, the child element will be moved in front of the parent.

setInterval(function () {
    $("[contenteditable='true']").each(function() {
        finder = $(this).find("p");
        $(finder).insertAfter($(this));
        $(finder).focus();
    });
},100);


问:
How to solve Bootstrap navbar hidden
In the output below I can't see my navbar menu correctly. Where is the problem?

Please anyone help me.

I just changed my code bootstrap.css and make this line comment the line name: padding-bottom.

```<code><nav class="navbar navbar-inverse" style="height:120px;">
  <div class="container" style="padding-top:30px;">
    <div class="navbar-header">
      <button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#navbar">
        <span class="icon-bar"></span>
        <span class="icon-bar"></span>
        <span class="icon-bar"></span>
      </button>
        <a><img class="pull-left" src="images/mt-626_header_logo01.png"></a>
      <a class="navbar-brand" href="#"><strong style="color:white">SOFT</strong><strong style="color:#3EC7C2">APP</strong></a>
    </div>
    <div class="collapse navbar-collapse" id="navbar">
      <ul class="nav navbar-nav navbar-right">
        <li><a href="#">HOME</a></li>
        <li><a href="#">ABOUT</a></li>
        <li><a href="#">SERVICES</a></li>
        <li><a href="#">BLOG</a></li>
        <li><a href="#">CONTACTS</a></li>
      </ul>
    </div>
  </div>
</nav>

<!-- First Container -->
<div class="container-fluid fcontaner">
    <div class="row">
        <div class="col-md-12">
            <div class="col-md-6">
                <img src="images/mt-0626-img.png" style="height:100%;width:100%"/>
            </div>
            <div class="col-md-6">
                <h1 style="padding-top:150px"><strong style="color:white;">SOFT</strong><strong style="color:">APP</strong></h1>
                <h1>INNOVATIVE SOLUTIONS</h1>
                <h3 style="color:white;padding-bottom:50px;">Innovative solutions delivering a product, which <br>includes tomorrow’s technology – already today!</h3>
                <a href="#"><img src="images/mt-0626-img2.png"></a>
            </div>
        </div>
    </div>
</div>
</code>```

答: Remove the height and padding-top css.</p>

Title: How to solve Bootstrap navbar hidden

Body:
In the output below I can't see my navbar menu correctly. Where is the problem?

Please anyone help me.

I just changed my code bootstrap.css and make this line comment the line name: padding-bottom.

      <button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#navbar">

      </button>

      SOFTAPP

HOME

ABOUT

SERVICES

BLOG

CONTACTS

SOFTAPP

INNOVATIVE SOLUTIONS

Innovative solutions delivering a product, which
includes tomorrow’s technology – already today!

Body: Remove the height and padding-top css.


问:
If user Clears push notification How to handle?
I am developing android and IOS app, it requires push notification,I have integrated FCM with notification payload,(IOS only supports Notification payload).So as I know in notification payload FCM itself put Notification.Once user clicks then only I can get the data of notification It doent hit onMessage received when the app is killed.If user doesnt click.If he clears how to handle it.Please help me.

Thank you.

答:
Open your application while clearing the notification as Facebook and transfer payload to the application. Pending Intent should have your application's one of the activity components like.

```<code>Intent appIntent = new Intent(context, YourActivityName.class);
PendingIntent.getActivity(context, 0, appIntent, PendingIntent.FLAG_UPDATE_CURRENT));
</code>```

Also you can open Services and Broadcasts

Body:
Open your application while clearing the notification as Facebook and transfer payload to the application. Pending Intent should have your application's one of the activity components like.

Intent appIntent = new Intent(context, YourActivityName.class);
PendingIntent.getActivity(context, 0, appIntent, PendingIntent.FLAG_UPDATE_CURRENT));

Also you can open Services and Broadcasts


问:
Angular 2 easy pie chart not working
I am trying to convert my existing jquery easy-pie-chart to Angular 2. As I am finding it difficult to completely rewrite entire code, I am trying to modify in bits and pieces.

Now to convert existing code I have done this (earlier it was inner-html but event binding not working in Angular 2) .

```<code><div class="col-md-2" style="text-align:center;" *ngFor="let piedata of piemasterData">
    <label (click)="getData(piedata[1])" > {{piedata[1]}} </label>

    <div class="chart" data-percent= piedata[7] >
        <span class="percent">
            {{piedata[7]}}
        </span>
    </div>
    <br/>

</div>
</code>```

Then I am calling

```<code>$('.chart').easyPieChart({

})
</code>```

Now the problem is the easy-pie-chart is not taking the value set in data-percent. Hence its only showing a dot.

 .

For example here ABC should take 10.48 and gauge the same value. Further after inspect elementing I saw the data-percent="piedata[7]" . I tried many combinations {{piedata[7]}} but still the value is not reflecting. I am not sure how to fix this in Angular 2.

答: You can bind non-Angular attribute using this syntax : [attr.data-percent]="piedata[7]"

Title: Angular 2 easy pie chart not working

Body:
I am trying to convert my existing jquery easy-pie-chart to Angular 2. As I am finding it difficult to completely rewrite entire code, I am trying to modify in bits and pieces.

Now to convert existing code I have done this (earlier it was inner-html but event binding not working in Angular 2) .

     {{piedata[1]}}

            {{piedata[7]}}

Then I am calling

$('.chart').easyPieChart({

})

Now the problem is the easy-pie-chart is not taking the value set in data-percent. Hence its only showing a dot.

 .

For example here ABC should take 10.48 and gauge the same value. Further after inspect elementing I saw the data-percent="piedata[7]" . I tried many combinations {{piedata[7]}} but still the value is not reflecting. I am not sure how to fix this in Angular 2.


问:
Is "parsing" a subset of "compiling"?
When I think of "compiling" I think of turning C++ code into a binary. Or perhaps C# into CLR byte code. But "parsing" could be something like parsing Python, or a web template language, where it doesn't need to produce any binaries, but can either execute the code immediately, statement-by-statement, or output HTML directly.

Would you basically be doing the same task in either case? Ignoring the language syntax, would compiling C++ be equally as difficult as parsing a website template file (Django, Smarty, whatever), or Python?

What I'm trying to allude at, is if I study "compiling" or read a book on "compiling" will I necessarily pick up the skills to parse non-compiled languages?

答:
Compiling is actually more difficult than parsing since its just one of the preliminary steps in compiling.

After the parsing, a symbol table is generated from which the actual binary code is generated.

In interpreting languages such as Javascript, the statements can be executed as each statement is parsed.

http://en.wikipedia.org/wiki/Parsing

Title: Is "parsing" a subset of "compiling"?


问:
why am i getting different answers for the following
I am getting different outputs for the following code. please tell me the difference</p>
```<code>        var y = 1;
        var c = "anything";
        var d = 5;
        console.log(y == 1 && "anything"); // Output is anything
        console.log( "anything" && y == 1 ); // Output is true
</code>```

答:
&& and || are surprisingly powerful in JavaScript as compared to some other languages: They don't necessarily return a boolean.

&& evaluates its first operand and, if that's falsy*, uses that as its return value; if the first operand evalutes truthy*, && evaluates its second operand and uses that as its result value. In your y == 1 && "anything", since y == 1 is true (which is, of course, truthy), the result is the result of evaluating "anything" (which is "anything"). In your "anything" && y == 1, "anything" is truthy, and so the result is  the result of evaluating y == 1 (which is true).

|| works in a similar manner: It evaluates its first operand and, if that's truthy, uses that as its result value; otherwise, || evaluates its second operand uses uses that as its result value.

* falsy and truthy:

falsy - A value that coerces to false when used as a boolean. The falsy values are: "", 0, NaN, null, undefined, and of course, false. (On browsers, document.all is also falsy, for complicated reasons. If you're really curious, I cover it in Chapter 17 of my book JavaScript: The New Toys. Links in my profile if you're interested.)

truthy - A value that coerces to true when used as a boolean. Any non-falsy value is truthy, incl. "0" (zero in quotes), "false" (false in quotes), empty functions, empty arrays, and empty objects.

Body:
I am getting different outputs for the following code. please tell me the difference

        var y = 1;
        var c = "anything";
        var d = 5;
        console.log(y == 1 && "anything"); // Output is anything
        console.log( "anything" && y == 1 ); // Output is true


问:
Do we have to declare variable within try block or outside the try block?
What is the best practice/recommendation to declare and use the variable with try/catch/finally ?.

do we have to declare the variable out side of the try block and dispose on the finally ? or declare within try block and get dispose automatically ?

```<code>string Name = String.Empty;
try
{
    //do work
}
catch
{
   //safely access s
   Console.WriteLine(Name);
}

OR

string Name;
try
{
    //do work
}
catch
{
   if (!String.IsNullOrEmpty(Name))
   {
       //safely access s
       Console.WriteLine(Name);
   }
}
</code>```

答:
It depends on what type of variable is,

If it is any com component like connection, dataReader, filestream handle and you think the objects needs to be closed manually you should declare them outside of try and dispose them in finally.

If you have normal types of variables like you mentioned string it will be destroyed automatically no need to dispose them.

Better way to dispose COM components is to use using like this.

```<code>using(var test = new Object())
{//Do Coding here
}
</code>```

Body:
What is the best practice/recommendation to declare and use the variable with try/catch/finally ?.

do we have to declare the variable out side of the try block and dispose on the finally ? or declare within try block and get dispose automatically ?

string Name = String.Empty;
try
{
    //do work
}
catch
{
   //safely access s
   Console.WriteLine(Name);
}

OR

string Name;
try
{
    //do work
}
catch
{
   if (!String.IsNullOrEmpty(Name))
   {
       //safely access s
       Console.WriteLine(Name);
   }
}

Body:
It depends on what type of variable is,

If it is any com component like connection, dataReader, filestream handle and you think the objects needs to be closed manually you should declare them outside of try and dispose them in finally.

If you have normal types of variables like you mentioned string it will be destroyed automatically no need to dispose them.

Better way to dispose COM components is to use using like this.

using(var test = new Object())
{//Do Coding here
}


问:
Insert element into numpy array
Lists have a very simple method to insert elements:

```<code>a = [1,2,3,4]
a.insert(2,66)
print a
[1, 2, 66, 3, 4]
</code>```

For a numpy array I could do:

```<code>a = np.asarray([1,2,3,4])
a_l = a.tolist()
a_l.insert(2,66)
a = np.asarray(a_l)
print a
[1 2 66 3 4]
</code>```

but this is very convoluted.

Is there an insert equivalent for numpy arrays?

答:
If you just want to insert items in consequent indices, as a more optimized way you can use np.concatenate() to concatenate slices of the array with your intended items:

For example in this case you can do:

```<code>In [21]: np.concatenate((a[:2], [66], a[2:]))
Out[21]: array([ 1,  2, 66,  3,  4])
</code>```

Benchmark (5 time faster than insert ):

```<code>In [19]: %timeit np.concatenate((a[:2], [66], a[2:]))
1000000 loops, best of 3: 1.43 us per loop

In [20]: %timeit np.insert(a, 2, 66)
100000 loops, best of 3: 6.86 us per loop
</code>```

And here is a benchmark with larger arrays (still 5 time faster):

```<code>In [22]: a = np.arange(1000)

In [23]: %timeit np.concatenate((a[:300], [66], a[300:]))
1000000 loops, best of 3: 1.73 us per loop

In [24]: %timeit np.insert(a, 300, 66)
100000 loops, best of 3: 7.72 us per loop
</code>```

Title: Insert element into numpy array

Body:
Lists have a very simple method to insert elements:

a = [1,2,3,4]
a.insert(2,66)
print a
[1, 2, 66, 3, 4]

For a numpy array I could do:

a = np.asarray([1,2,3,4])
a_l = a.tolist()
a_l.insert(2,66)
a = np.asarray(a_l)
print a
[1 2 66 3 4]

but this is very convoluted.

Is there an insert equivalent for numpy arrays?

Body:
If you just want to insert items in consequent indices, as a more optimized way you can use np.concatenate() to concatenate slices of the array with your intended items:

For example in this case you can do:

In [21]: np.concatenate((a[:2], [66], a[2:]))
Out[21]: array([ 1,  2, 66,  3,  4])

Benchmark (5 time faster than insert ):

In [19]: %timeit np.concatenate((a[:2], [66], a[2:]))
1000000 loops, best of 3: 1.43 us per loop

In [20]: %timeit np.insert(a, 2, 66)
100000 loops, best of 3: 6.86 us per loop

And here is a benchmark with larger arrays (still 5 time faster):

In [22]: a = np.arange(1000)

In [23]: %timeit np.concatenate((a[:300], [66], a[300:]))
1000000 loops, best of 3: 1.73 us per loop

In [24]: %timeit np.insert(a, 300, 66)
100000 loops, best of 3: 7.72 us per loop


问:
Is Data toggling in USB protocol specific to an Endpoint?
I am writing USB as a host, baremetal
I am facing some data toggling issues, my question is - is data toggling specific to an Endpoint

What I mean is consider BULK transfer, you got a BULK IN endpoint and a BULK OUT endpoint. Now if I am to read a block, I send the read(10) request to the BULK OUT and then accept the data read on BULK IN.

Now, if i send maybe a write(10) request to BULK OUT endpoint then what would the value for the data toggle be??
Would it be that obtained after the first request to BULK OUT(DATA0->DATA1) or would it be that after accepting the data read from first BULK IN(DATA0->DATA1->DATA0)

PS: I am implementing using the OpenHCI host controller protocol

答:
Yes, data toggling is specific to an endpoint.

Your BULK IN endpoint and your BULK OUT endpoint will not share data toggles. Instead, there are two separate data toggles, one for each endpoint.


问:
Integrating GSM/GPRS modem with Raspberry Pi 3 with Android things
I am trying to make a module with the help of Android Things. I need to send temperature and pressure readings to a server over the internet with the help of GSM/GPRS modem. I am using Raspberry Pi 3 with AndroidThings SDK. I am able to get temperature and pressure readings with the help of BMP 280 sensor but must use external GSM modem to send data to the server. Is it possible to integrate GSM modem with Android Things (Raspberry pi 3)? Where can I get resources to learn and do this, as I am new to Android Things and IoT? </p>

答:
Yes, You can integrating JYMG-100 GSM/GPRS modem with Raspberry Pi 3 with Android things. For this You need:

1) hardware UART<->RS232 converter (for example like that) because RP3 has 0..+5V UART input/outputs, but JYMG-100 GSM/GPRS modem - not UART, but RS232 interface with -12..+12V input/outputs, more details see here)

2) implement AT-command control of JYMG-100 GSM/GPRS modem (yes, You need datasheet with JYMG-100 AT-command set, like this for SIM900 GSM/GPRS module, but for common tasks, like SMS processing You can use "standard" AT-commans like that. If You didn't find datasheet for JYMG-100 just open its body and look what GSM/GPRS it use) via RP3 UART like in this tutorial (also this question of proppy is very helpful). So, You just have to sent String with AT-command to JYMG-100 and get and analyze response String.


问:
Query for insert with values from a texbox
I tried searching for a simple answer but I get complex threads so..

I have a table named Issues with a field named IssueTimeStart. And the form name Issue_Log.

I just simply to put a button where the value, say StartTime.Text (this is a texbox) is inserted to IssueTimeStart field on the table.

I tried using "Insert Issues.IssueTimeStart VALUES Issue_Log.StartTime.text but nothing happens.

答:
That could be:

```<code>CurrentDb.Execute "Insert Into Issues (IssueTimeStart) Values (#" & Format(Me!StartTime.Value, "yyyy\/mm\/dd hh\:nn\:ss") & "#)"
</code>```

or to insert the current time for a blank textbox:

```<code>CurrentDb.Execute "Insert Into Issues (IssueTimeStart) Values (#" & Nz(Format(Me!StartTime.Value, Now), "yyyy\/mm\/dd hh\:nn\:ss") & "#)"
</code>```

or to debug:

```<code>Dim SQL As String
SQL = "Insert Into Issues (IssueTimeStart) Values (#" & Format(Me!StartTime.Value, "yyyy\/mm\/dd hh\:nn\:ss") & "#)"
Debug.Print SQL
CurrentDb.Execute SQL
</code>```

Now, study the output from Debug.Print

Body:
That could be:

CurrentDb.Execute "Insert Into Issues (IssueTimeStart) Values (#" & Format(Me!StartTime.Value, "yyyy\/mm\/dd hh\:nn\:ss") & "#)"

or to insert the current time for a blank textbox:

CurrentDb.Execute "Insert Into Issues (IssueTimeStart) Values (#" & Nz(Format(Me!StartTime.Value, Now), "yyyy\/mm\/dd hh\:nn\:ss") & "#)"

or to debug:

Dim SQL As String
SQL = "Insert Into Issues (IssueTimeStart) Values (#" & Format(Me!StartTime.Value, "yyyy\/mm\/dd hh\:nn\:ss") & "#)"
Debug.Print SQL
CurrentDb.Execute SQL

Now, study the output from Debug.Print


答:
It depends on the scope you need and what you want to do with the variable. If you declare it within the try block, you will not be able to use the variable outside the block, not even within the catch block. This has to do with the fact that catch has to handle an exceptional circumstance and finally should always be able to execute. When you declare your variable inside the try scope, you don't know if it has been initialized when the exception is thrown. And you never know if the variable is ever initialized after your try/catch block. Therefore, if you want to use a variable inside the catch/finally or later in the code, you can better be safe and declare it before (that way you are always sure you can handle the disposing in the finally block). But, always try to give your variable the smallest scope possible. So if you are sure you won't need it outside the try scope, declare it inside the try.

An example of what I meant:

```<code>try
{
    throw new SomeException("It goes wrong here");
    string iNeedThisVariable = "but i never get initialized";
}
catch (SomeException e)
{
    Console.Out.WriteLine(iNeedThisVariable); //This goes wrong, since you need to show the string, but it has never been initialized
}
finally
{
    Console.Out.WriteLine(iNeedThisVariable); //Also can't use it here!
}
</code>```

Title: Do we have to declare variable within try block or outside the try block?

Body:
It depends on the scope you need and what you want to do with the variable. If you declare it within the try block, you will not be able to use the variable outside the block, not even within the catch block. This has to do with the fact that catch has to handle an exceptional circumstance and finally should always be able to execute. When you declare your variable inside the try scope, you don't know if it has been initialized when the exception is thrown. And you never know if the variable is ever initialized after your try/catch block. Therefore, if you want to use a variable inside the catch/finally or later in the code, you can better be safe and declare it before (that way you are always sure you can handle the disposing in the finally block). But, always try to give your variable the smallest scope possible. So if you are sure you won't need it outside the try scope, declare it inside the try.

An example of what I meant:

try
{
    throw new SomeException("It goes wrong here");
    string iNeedThisVariable = "but i never get initialized";
}
catch (SomeException e)
{
    Console.Out.WriteLine(iNeedThisVariable); //This goes wrong, since you need to show the string, but it has never been initialized
}
finally
{
    Console.Out.WriteLine(iNeedThisVariable); //Also can't use it here!
}


问:
converting from php $_GET variables to code igniter
I am learning to use the CodeIgniter framework. I am coming form a world where get variables determined which body file to include in the index.php.

So with the MVC style coding I am unsure how to have a skeleton view which subsequent views are just the body of the page.

any Ideas?

答:
In CodeIgniter, GET variables(as in querystrings, eg. ?var1=alice&var2=bob) are not normally used for passing data, because they are disabled by default. Instead, URL segments (see http://codeigniter.com/user_guide/general/controllers.html#passinguri) or POST variables are used.

If it is necessary to use GET variables, thus enabling use of $_GET and/or $this->input->get(...), see this:

How can I use GET forms with CodeIgniter?

Edit: This may be useful in regards to loading a subv-iew within a main view:

http://codeigniter.com/wiki/Header_and_footer_and_menu_on_every_page/


问:
map-indexed alternative for reducers
Is there a map-indexed alternative for clojure.core.reducers? I would like something that would work lazily like r/map (without constructing new sequence).

答:
I suspect that what you really want to use is a transducer, since map-indexed has a 1-arity version (as does map, filter, and many other core functions) that returns a transducer.  Transducers are composable, and do not create an intermediate sequence.  Here is a short example:

```<code>(def xf (comp
          (map-indexed (fn [i value] [i value]))
          (filter (fn [[i value]] (odd? i)))
          (map second)))
</code>```

This says:  generate an indexed vector using map-indexed, filter out only the vectors whose index is odd, and get the second element.  It's a long-winded way of saying (filter odd? collection) but it's only for example purposes.

You can use this with into:

```<code>(into [] xf "ThisIsATest")
=> [\h \s \s \T \s]
</code>```

or you can use the transduce function and apply str to the result:

```<code>(transduce xf str "ThisIsATest")
=> "hssTs"
</code>```

Title: map-indexed alternative for reducers

Body:
I suspect that what you really want to use is a transducer, since map-indexed has a 1-arity version (as does map, filter, and many other core functions) that returns a transducer.  Transducers are composable, and do not create an intermediate sequence.  Here is a short example:

(def xf (comp
          (map-indexed (fn [i value] [i value]))
          (filter (fn [[i value]] (odd? i)))
          (map second)))

This says:  generate an indexed vector using map-indexed, filter out only the vectors whose index is odd, and get the second element.  It's a long-winded way of saying (filter odd? collection) but it's only for example purposes.

You can use this with into:

(into [] xf "ThisIsATest")
=> [\h \s \s \T \s]

or you can use the transduce function and apply str to the result:

(transduce xf str "ThisIsATest")
=> "hssTs"


问:
Why can't transplant the command from bash into awk?
```<code>x="qwerty"
x=$(echo $x | tr [a-z] [A-Z]);
echo $x
QWERTY
</code>```

I want to transplant it into awk.

1 to save as format.awk

```<code>#! /usr/bin/awk
{
x=$(echo -n $0 | tr [a-z] [A-Z])
print $x
}
</code>```

2  awk -f format.awk file

```<code>awk: format.awk: line 3: syntax error at or near tr
</code>```

Why and how to fix it?

It is easy to translate whole file with cat file |tr [a-z] [A-Z],there are many other works to do in awk,so it is necessary to translate lines one by one in awk,other task ommited.

答:
You cannot call tr like this:

You can do something like this:

```<code>awk '{print | "tr \"[a-z]\" \"[A-Z]\""}' file
</code>```

Or better do it entirely in awk as:

```<code>awk '{line = toupper($0); print line}' file
</code>```

Body:
x="qwerty"
x=$(echo $x | tr [a-z] [A-Z]);
echo $x
QWERTY

I want to transplant it into awk.

1 to save as format.awk

#! /usr/bin/awk
{
x=$(echo -n $0 | tr [a-z] [A-Z])
print $x
}

2  awk -f format.awk file

awk: format.awk: line 3: syntax error at or near tr

Why and how to fix it?

It is easy to translate whole file with cat file |tr [a-z] [A-Z],there are many other works to do in awk,so it is necessary to translate lines one by one in awk,other task ommited.

Body:
You cannot call tr like this:

You can do something like this:

awk '{print | "tr \"[a-z]\" \"[A-Z]\""}' file

Or better do it entirely in awk as:

awk '{line = toupper($0); print line}' file


问:
Failing installation of tensorpack
I'm trying to install tensorpack on Ubuntu 16.04 LTS.

```<code>$ sudo -H pip install --upgrade tensorpack
Collecting tensorpack
  Using cached tensorpack-0.1.7-py2.py3-none-any.whl
Collecting tabulate (from tensorpack)
  Using cached tabulate-0.7.7-py2.py3-none-any.whl
Collecting termcolor (from tensorpack)
  Downloading termcolor-1.1.0.tar.gz
Requirement already up-to-date: six in /usr/lib/python3/dist-packages (from tensorpack)
Requirement already up-to-date: numpy in /usr/local/lib/python3.5/dist-packages (from tensorpack)
Collecting subprocess32 (from tensorpack)
  Using cached subprocess32-3.2.7.tar.gz
    Complete output from command python setup.py egg_info:
    This backport is for Python 2.x only.

    ----------------------------------------
Command "python setup.py egg_info" failed with error code 1 in /tmp/pip-build-3vdwf8jw/subprocess32/
</code>```

Do you know what might be causing this error?

Edit: With pip3 it behaves the same.

```<code>$ sudo -H pip3 install --upgrade tensorpack
Collecting tensorpack
  Using cached tensorpack-0.1.7-py2.py3-none-any.whl
Collecting msgpack-numpy (from tensorpack)
  Using cached msgpack_numpy-0.3.9-py2.py3-none-any.whl
Collecting pyzmq (from tensorpack)
  Using cached pyzmq-16.0.2-cp35-cp35m-manylinux1_x86_64.whl
Collecting functools32 (from tensorpack)
  Using cached functools32-3.2.3-2.zip
    Complete output from command python setup.py egg_info:
    This backport is for Python 2.7 only.

    ----------------------------------------
Command "python setup.py egg_info" failed with error code 1 in /tmp/pip-build-ut16f9e3/functools32/
</code>```

答:
Tensorpack worked for me, but the per-requisite were

Using a Virtual Environment

virtualenv tensorpack

Secondly updating pip

pip install --upgrade pip

Lastly not using "sudo"

pip install tensorpack

Title: Failing installation of tensorpack

Body:
I'm trying to install tensorpack on Ubuntu 16.04 LTS.

$ sudo -H pip install --upgrade tensorpack
Collecting tensorpack
  Using cached tensorpack-0.1.7-py2.py3-none-any.whl
Collecting tabulate (from tensorpack)
  Using cached tabulate-0.7.7-py2.py3-none-any.whl
Collecting termcolor (from tensorpack)
  Downloading termcolor-1.1.0.tar.gz
Requirement already up-to-date: six in /usr/lib/python3/dist-packages (from tensorpack)
Requirement already up-to-date: numpy in /usr/local/lib/python3.5/dist-packages (from tensorpack)
Collecting subprocess32 (from tensorpack)
  Using cached subprocess32-3.2.7.tar.gz
    Complete output from command python setup.py egg_info:
    This backport is for Python 2.x only.

    ----------------------------------------
Command "python setup.py egg_info" failed with error code 1 in /tmp/pip-build-3vdwf8jw/subprocess32/

Do you know what might be causing this error?

Edit: With pip3 it behaves the same.

$ sudo -H pip3 install --upgrade tensorpack
Collecting tensorpack
  Using cached tensorpack-0.1.7-py2.py3-none-any.whl
Collecting msgpack-numpy (from tensorpack)
  Using cached msgpack_numpy-0.3.9-py2.py3-none-any.whl
Collecting pyzmq (from tensorpack)
  Using cached pyzmq-16.0.2-cp35-cp35m-manylinux1_x86_64.whl
Collecting functools32 (from tensorpack)
  Using cached functools32-3.2.3-2.zip
    Complete output from command python setup.py egg_info:
    This backport is for Python 2.7 only.

    ----------------------------------------
Command "python setup.py egg_info" failed with error code 1 in /tmp/pip-build-ut16f9e3/functools32/


问:
VM in virtualbox is already locked for a session (or being unlocked)
My VM in virtualbox can not start due to this error, I don't want to destroy it and reinstall it again, anyway to recover it ?

There was an error while executing VBoxManage, a CLI used by Vagrant
for controlling VirtualBox. The command and stderr is shown below.

```<code>Command: ["modifyvm", "319fcce3-e8ff-4b6f-a641-3aee1df6543f", "--natpf1", "delete", "ssh"]

Stderr: VBoxManage: error: The machine 'centos64_c6402_1454036461345_59755' is already locked for a session (or being unlocked)
VBoxManage: error: Details: code VBOX_E_INVALID_OBJECT_STATE (0x80bb0007), component MachineWrap, interface IMachine, callee nsISupports
VBoxManage: error: Context: "LockMachine(a->session, LockType_Write)" at line 493 of file VBoxManageModifyVM.cpp
</code>```

答: The only option that worked for me was to kill all the processes matching ps axl|grep -i vbox.</p>

Body:
My VM in virtualbox can not start due to this error, I don't want to destroy it and reinstall it again, anyway to recover it ?

There was an error while executing VBoxManage, a CLI used by Vagrant
for controlling VirtualBox. The command and stderr is shown below.

Command: ["modifyvm", "319fcce3-e8ff-4b6f-a641-3aee1df6543f", "--natpf1", "delete", "ssh"]

Stderr: VBoxManage: error: The machine 'centos64_c6402_1454036461345_59755' is already locked for a session (or being unlocked)
VBoxManage: error: Details: code VBOX_E_INVALID_OBJECT_STATE (0x80bb0007), component MachineWrap, interface IMachine, callee nsISupports
VBoxManage: error: Context: "LockMachine(a->session, LockType_Write)" at line 493 of file VBoxManageModifyVM.cpp


问:
How to set or get write permission on Google+ for post on google+ ?
We have tried to set/get write permission bellow:

```<code>https://www.googleapis.com/auth/plus.me
https://www.googleapis.com/auth/plus.stream.read
https://www.googleapis.com/auth/plus.stream.write
https://www.googleapis.com/auth/plus.circles.read
https://www.googleapis.com/auth/plus.circles.write
</code>```

for posting on google plus, but I am not able to post on google+ wall.

答:
We can able to post on Google+ Wall.

Once we will need top create Domain account for google so we will get write permission for posting.

I have already done it.

Body:
We have tried to set/get write permission bellow:

https://www.googleapis.com/auth/plus.me
https://www.googleapis.com/auth/plus.stream.read
https://www.googleapis.com/auth/plus.stream.write
https://www.googleapis.com/auth/plus.circles.read
https://www.googleapis.com/auth/plus.circles.write

for posting on google plus, but I am not able to post on google+ wall.


问:
C# Streamreader add new line
I have searched for this but every solution I've come across involves regex witch is not a solution for me.

My question is simple, I want the streamreader to add a new line everytime it reads the word "ice". Keep in mind that the streamreader is reading the input as 1 line.

My code is as follow:

```<code>using (StreamReader sr = new StreamReader(stream))
{
    VarrileKeeper.s = sr.ReadToEnd();
    //Console.WriteLine(VarrileKeeper.s);
    if (VarrileKeeper.s.ToString().Contains("ice"))
    {
        //insert newline in string
    }
    sr.Close();
}
</code>```

答:
Try the following:</p>

```<code> using (StreamReader sr = new StreamReader(stream))
 {
     {
         VarrileKeeper.s = sr.ReadToEnd();
         //Console.WriteLine(VarrileKeeper.s);
          if (VarrileKeeper.s.ToString().Contains("ice"))
          {
              VarrileKeeper.s = VarrileKeeper.s.Replace("ice", "ice" + System.Environment.NewLine);
          }

          sr.Close();
      }
}
</code>```

Title: C# Streamreader add new line

Body:
I have searched for this but every solution I've come across involves regex witch is not a solution for me.

My question is simple, I want the streamreader to add a new line everytime it reads the word "ice". Keep in mind that the streamreader is reading the input as 1 line.

My code is as follow:

using (StreamReader sr = new StreamReader(stream))
{
    VarrileKeeper.s = sr.ReadToEnd();
    //Console.WriteLine(VarrileKeeper.s);
    if (VarrileKeeper.s.ToString().Contains("ice"))
    {
        //insert newline in string
    }
    sr.Close();
}

Body:
Try the following:

 using (StreamReader sr = new StreamReader(stream))
 {
     {
         VarrileKeeper.s = sr.ReadToEnd();
         //Console.WriteLine(VarrileKeeper.s);
          if (VarrileKeeper.s.ToString().Contains("ice"))
          {
              VarrileKeeper.s = VarrileKeeper.s.Replace("ice", "ice" + System.Environment.NewLine);
          }

          sr.Close();
      }
}


问:
Custom post type archive root level theming
I'm stuck with a theming question. I have a Custom Post Type (Products) and a Custom Taxonomy (Product Types).

The CPT Archive checks if there are any direct Taxonomy children and if yes, displays them. If not, shows the products. So far, so good. Works fine. (Like a very basic shop system but without any plugin.)

But now I need to change layout of only the root level of the CPT Archive, where there are only child taxonomies visible. This must not affect any other level.

I have no real idea how to go for this.

Which are the filters I am searching for ("if this is the root level of the archive, show....")?

答:
Please create a file in your theme folder with the name archive-custom-post-type.php, like if chef is a custom post type archive-chef.php will be the archive page.

Hope it helps.


问:
How do I test custom Koa middleware for error handling?
As part of a migration of an older app from ExpressJs to Koa JS (v1). I've written a piece of middleware to handle any errors that occur. It looks something like this:

```<code>module.errors = function * (next) {
  try {
    yield next;
  } catch (err) {
    switch(err && err.message) {
      case: 'Bad Request':
        this.status = 400;
        this.body = {message: 'Bad Request'};
        brea;
      default:
        this.status = 500;
        this.body = {message: 'An error has occurred'};
    }

    this.app.emit('error', err, this);
  }
}
</code>```

It gets included in my application like this:

```<code>const app = require('koa')();
const router = require('koa-router');
const { errors } = require('./middleware/errors');

app.use(errors)
   .use(router.routes());

app.get('/some-request', function *(next){
  // request that could error
});

app.listen();
</code>```

This all works fine, but I'd like to test the middleware with my unit tests, and perhaps because I'm still fairly new to both Koa and Generator functions, I'm struggling to figure out how to do this.

I know that if I import the error handling middleware, I need to pass it a function that will throw an error, but how do I execute the function passed? Does it need to be closure of some description? How do I assert/expect on the values set for the status code and the like?

```<code>const { expect } = require('chai');
const { errors } = require('../middleware/errors');

describe('errors middleware', () => {

  it('returns a 500 on a generic error', () => {
      let thrower = function(){ throw new Error() }
      let errorHandler = errors(thrower());

      // mass of confusion

      expect(errorHandler.next()).to.throw(Error);
  });
});
</code>```

答:
you can use this library https://www.npmjs.com/package/co which used by koa.js 1.x to wrap your generator functions and mock the context object.</p>

```<code>const co = require('co');
const Emitter = require('events');
const { expect } = require('chai');
const { errors } = require('../middleware/errors');

const wrapped = co.wrap(errors);
const mockApp = new Emitter();

describe('errors middleware', () => {

  it('returns a 500 on a generic error', (done) => {
    const ERROR_MSG = 'middleware error';
    const ctx = {app: mockApp};
    const next = function* () {
      throw new Error(ERROR_MSG);
    }
    wrapped.call(ctx, next)
      .then(() => {
        try {
          expect(ctx.status).to.equal(500);
          expect(ctx.body.message).to.equal(ERROR_MSG);
          done();
        } catch (err) {
          done(err);
        }
      })
      .catch(err => done(err))

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

Body:
As part of a migration of an older app from ExpressJs to Koa JS (v1). I've written a piece of middleware to handle any errors that occur. It looks something like this:

module.errors = function * (next) {
  try {
    yield next;
  } catch (err) {
    switch(err && err.message) {
      case: 'Bad Request':
        this.status = 400;
        this.body = {message: 'Bad Request'};
        brea;
      default:
        this.status = 500;
        this.body = {message: 'An error has occurred'};
    }

    this.app.emit('error', err, this);
  }
}

It gets included in my application like this:

const app = require('koa')();
const router = require('koa-router');
const { errors } = require('./middleware/errors');

app.use(errors)
   .use(router.routes());

app.get('/some-request', function *(next){
  // request that could error
});

app.listen();

This all works fine, but I'd like to test the middleware with my unit tests, and perhaps because I'm still fairly new to both Koa and Generator functions, I'm struggling to figure out how to do this.

I know that if I import the error handling middleware, I need to pass it a function that will throw an error, but how do I execute the function passed? Does it need to be closure of some description? How do I assert/expect on the values set for the status code and the like?

const { expect } = require('chai');
const { errors } = require('../middleware/errors');

describe('errors middleware', () => {

  it('returns a 500 on a generic error', () => {
      let thrower = function(){ throw new Error() }
      let errorHandler = errors(thrower());

      // mass of confusion

      expect(errorHandler.next()).to.throw(Error);
  });
});

Body:
you can use this library https://www.npmjs.com/package/co which used by koa.js 1.x to wrap your generator functions and mock the context object.

const co = require('co');
const Emitter = require('events');
const { expect } = require('chai');
const { errors } = require('../middleware/errors');

const wrapped = co.wrap(errors);
const mockApp = new Emitter();

describe('errors middleware', () => {

  it('returns a 500 on a generic error', (done) => {
    const ERROR_MSG = 'middleware error';
    const ctx = {app: mockApp};
    const next = function* () {
      throw new Error(ERROR_MSG);
    }
    wrapped.call(ctx, next)
      .then(() => {
        try {
          expect(ctx.status).to.equal(500);
          expect(ctx.body.message).to.equal(ERROR_MSG);
          done();
        } catch (err) {
          done(err);
        }
      })
      .catch(err => done(err))

  });
});


问:
Get Domain LogonServer in C#
In a command prompt I am able to get the domain logon server by typing:

```<code>echo %logonserver%
</code>```

How can I get this same result in C#?

OwnerDisplayName: Ray Booysen

Title: Get Domain LogonServer in C#

Body:
In a command prompt I am able to get the domain logon server by typing:

echo %logonserver%

How can I get this same result in C#?

Body: System.Environment.GetEnvironmentVariable("logonserver")

OwnerDisplayName: Dave Markle


问:
Creating a generic function for a function of an animation that I have
I am learning Jquery, and I am making my new website. unluckily I am a more of a web designer (with experience more on Design that on Programming) and I am stuck in trying to create a generic function so I can use it for various div elements in the html.

This is the code

```<code>$(".myCircle").hover(
    // when the mouse enters the box do...
    function(){
        var $box = $(this),
        offset = $box.offset(),
        radius = $box.width() / 2,
        circle = new SimpleCircle(offset.left + radius, offset.top + radius, radius);

        $box.mousemove(function(e){
         if(myHover != "transition1" && circle.includesXY(e.pageX, e.pageY)){
             $(this).css({"cursor":"pointer"});
             myHover = "transition1";
                $("#black").stop().animate({"top":"-200px"}, speed/2, function(){
                    myHover = 1;
                });
            }

            else if(!circle.includesXY(e.pageX, e.pageY)){
             $(this).css({"cursor":"default"});
                if(myHover == 1 || myHover == "transition1"){
                    myHover = "transition0";
                    $("#black").stop().animate({"top":"0px"}, speed/2, function(){
                        myHover = 0;
                    });
                    $("body").unbind('mousemove');
                }
            }
       });

    },
    // when the mouse leaves the box do...
    function() {
        if(myHover == 1 || myHover == "transition1"){
            myHover = "transition0";
         $(this).css({"cursor":"default"});
            $("#black").stop().animate({"top":"0px"}, speed/2, function(){
                myHover = 0;
            })
        };
        $("body").unbind('mousemove');
    }
);
</code>```

The animation is a div with radius corner, that looks like a circle, and that with my on mouse hover I activate an animation behind the circle to come out.

What I would like to achive it is not to write all the time the same long function for when I want to use it for multiple div/circle. But re-use a generic function.

a function something like: function circleHover(myCircle, myTarget, eventIn(), eventOut())

where myTarget could be any other element, or even the same myCircle, and eventIn() and eventOut() are nothing else the animation (or anything else) on situations when the mouse enter, and when the mouse leaves.

I am having big trouble in creating in a generic way this

$("#black").stop().animate({"top":"-200px"}, speed/2, function(){
     myHover = 1;
});

I am sorry for my silly question, I really don't know where to look for the answer or where to learn more.

==============================

UPDATE- 1st DEC
at the end I end up with this code. I think that it is halfway of what I wanted.

```<code>function aniCircle(in_out, myThis, target, endPos, movePos, speed){
    if(typeof speed == "undefined"){speed = speed2};

    if(in_out == 1){
        var $box = myThis,
        offset = $box.offset(),
        radius = $box.width() / 2,
        circle = new SimpleCircle(offset.left + radius, offset.top + radius, radius);

        $box.mousemove(function(e){
            if(myHover != "transition1" && circle.includesXY(e.pageX, e.pageY)){
                $(this).css({"cursor":"pointer"});
                myHover = "transition1";

                $(target).stop().animate(movePos, speed, function(){
                    myHover = 1;
                });
            }else if(!circle.includesXY(e.pageX, e.pageY)){
                $(this).css({"cursor":"default"});
                if(myHover == 1 || myHover == "transition1"){
                    myHover = "transition0";
                    $(target).stop().animate(endPos, speed, function(){
                        myHover = 0;
                    });
                    $("body").unbind('mousemove');
                }
            }
        });
    }else if(in_out == 0){
        if(myHover == 1 || myHover == "transition1"){
            myHover = "transition0";
            myThis.css({"cursor":"default"});
            $(target).stop().animate(endPos, speed, function(){
                myHover = 0;
            })
        };
        $("body").unbind('mousemove');
    }
}
</code>```

and recalling the function like this

```<code>$("#logo").hover(
    // when the mouse enters the box do...
    function(){
        aniCircle(1, $(this), "#black", {"top":"0px"},{"top":"-200px"});
    },
    // when the mouse leaves the box do...
    function() {
        aniCircle(0, $(this), "#black", {"top":"0px"});
    }
);
</code>```

I am having difficulties to add various kind of behaviours, like make an animation of a target with a curve animation (Path plugin - arc, bezier and sin animated curves).

I don't expect to solve this problem, but I would like at least a review of the code on what I could optimise. I feel that the code it is a bit repetitive and ugly.

答:
I think you'd simply need to update your targeting within each function so that instead of looking for a node with an id, but rather a node with a class.  So, instead of using $('#black') as the selector, change the id="black" to a node with a class - like: class="black".  Then, inside each function, use jQuery's next method to target the next node classed as 'black':

```<code>$box.next('.black').stop()...
</code>```

You could also continue to develop this into a plugin, but you probably don't need to - it's completely up to you.  What you have (with the updated targeting approach) will work for all elements returned by the $('.myCircle') selector.

Body:
I am learning Jquery, and I am making my new website. unluckily I am a more of a web designer (with experience more on Design that on Programming) and I am stuck in trying to create a generic function so I can use it for various div elements in the html.

This is the code

$(".myCircle").hover(
    // when the mouse enters the box do...
    function(){
        var $box = $(this),
        offset = $box.offset(),
        radius = $box.width() / 2,
        circle = new SimpleCircle(offset.left + radius, offset.top + radius, radius);

        $box.mousemove(function(e){
         if(myHover != "transition1" && circle.includesXY(e.pageX, e.pageY)){
             $(this).css({"cursor":"pointer"});
             myHover = "transition1";
                $("#black").stop().animate({"top":"-200px"}, speed/2, function(){
                    myHover = 1;
                });
            }

            else if(!circle.includesXY(e.pageX, e.pageY)){
             $(this).css({"cursor":"default"});
                if(myHover == 1 || myHover == "transition1"){
                    myHover = "transition0";
                    $("#black").stop().animate({"top":"0px"}, speed/2, function(){
                        myHover = 0;
                    });
                    $("body").unbind('mousemove');
                }
            }
       });

    },
    // when the mouse leaves the box do...
    function() {
        if(myHover == 1 || myHover == "transition1"){
            myHover = "transition0";
         $(this).css({"cursor":"default"});
            $("#black").stop().animate({"top":"0px"}, speed/2, function(){
                myHover = 0;
            })
        };
        $("body").unbind('mousemove');
    }
);

The animation is a div with radius corner, that looks like a circle, and that with my on mouse hover I activate an animation behind the circle to come out.

What I would like to achive it is not to write all the time the same long function for when I want to use it for multiple div/circle. But re-use a generic function.

a function something like: function circleHover(myCircle, myTarget, eventIn(), eventOut())

where myTarget could be any other element, or even the same myCircle, and eventIn() and eventOut() are nothing else the animation (or anything else) on situations when the mouse enter, and when the mouse leaves.

I am having big trouble in creating in a generic way this

$("#black").stop().animate({"top":"-200px"}, speed/2, function(){
     myHover = 1;
});

I am sorry for my silly question, I really don't know where to look for the answer or where to learn more.

==============================

UPDATE- 1st DEC
at the end I end up with this code. I think that it is halfway of what I wanted.

function aniCircle(in_out, myThis, target, endPos, movePos, speed){
    if(typeof speed == "undefined"){speed = speed2};

    if(in_out == 1){
        var $box = myThis,
        offset = $box.offset(),
        radius = $box.width() / 2,
        circle = new SimpleCircle(offset.left + radius, offset.top + radius, radius);

        $box.mousemove(function(e){
            if(myHover != "transition1" && circle.includesXY(e.pageX, e.pageY)){
                $(this).css({"cursor":"pointer"});
                myHover = "transition1";

                $(target).stop().animate(movePos, speed, function(){
                    myHover = 1;
                });
            }else if(!circle.includesXY(e.pageX, e.pageY)){
                $(this).css({"cursor":"default"});
                if(myHover == 1 || myHover == "transition1"){
                    myHover = "transition0";
                    $(target).stop().animate(endPos, speed, function(){
                        myHover = 0;
                    });
                    $("body").unbind('mousemove');
                }
            }
        });
    }else if(in_out == 0){
        if(myHover == 1 || myHover == "transition1"){
            myHover = "transition0";
            myThis.css({"cursor":"default"});
            $(target).stop().animate(endPos, speed, function(){
                myHover = 0;
            })
        };
        $("body").unbind('mousemove');
    }
}

and recalling the function like this

$("#logo").hover(
    // when the mouse enters the box do...
    function(){
        aniCircle(1, $(this), "#black", {"top":"0px"},{"top":"-200px"});
    },
    // when the mouse leaves the box do...
    function() {
        aniCircle(0, $(this), "#black", {"top":"0px"});
    }
);

I am having difficulties to add various kind of behaviours, like make an animation of a target with a curve animation (Path plugin - arc, bezier and sin animated curves).

I don't expect to solve this problem, but I would like at least a review of the code on what I could optimise. I feel that the code it is a bit repetitive and ugly.

Body:
I think you'd simply need to update your targeting within each function so that instead of looking for a node with an id, but rather a node with a class.  So, instead of using $('#black') as the selector, change the id="black" to a node with a class - like: class="black".  Then, inside each function, use jQuery's next method to target the next node classed as 'black':

$box.next('.black').stop()...

You could also continue to develop this into a plugin, but you probably don't need to - it's completely up to you.  What you have (with the updated targeting approach) will work for all elements returned by the $('.myCircle') selector.


问:
Method 'WriteLine' of object 'ITextStream' failed
This may be a basic question, but was unable to figure out the issue as am quite new to VB 6.
This is what I came through on searching online for this error code

“Method'~' of object '~' failed" this usually happens when dll are not
  registered. Precisely, when the runtime  is not even able to tell what
  the object is, and the object is not able to propagate more infos
  back. It could be any component. It is a mismatched DLL file.”

Tried registering the scrrun.dll using regsvr32.exe too, yet no luck

Getting the error in the below code block, while trying to run the program

```<code>Sub PrintToConsole(ByVal LineToPrint As String)
    Dim fso As New FileSystemObject
    fso.GetStandardStream(StdOut).WriteLine (LineToPrint)
End Sub
</code>```

答:
Try this:</p>

```<code>Dim fso as Object
Set fso = CreateObject("Scripting.FileSystemObject")
fso.GetStandardStream(StdOut).WriteLine (LineToPrint)
</code>```

Body:
This may be a basic question, but was unable to figure out the issue as am quite new to VB 6.
This is what I came through on searching online for this error code

“Method'~' of object '~' failed" this usually happens when dll are not
  registered. Precisely, when the runtime  is not even able to tell what
  the object is, and the object is not able to propagate more infos
  back. It could be any component. It is a mismatched DLL file.”

Tried registering the scrrun.dll using regsvr32.exe too, yet no luck

Getting the error in the below code block, while trying to run the program

Sub PrintToConsole(ByVal LineToPrint As String)
    Dim fso As New FileSystemObject
    fso.GetStandardStream(StdOut).WriteLine (LineToPrint)
End Sub

Body:
Try this:

Dim fso as Object
Set fso = CreateObject("Scripting.FileSystemObject")
fso.GetStandardStream(StdOut).WriteLine (LineToPrint)


问:
Prolog: ignore unwanted variables in the output
Is there a way to force the prolog CLI to return query results with only the variables I'm interested in? A simple example would be:

```<code>?- mother(M, C1), father(F, C1).
</code>```

which returns bindings for all M, F and C1. But I'm interested only in M and F, while C1 is just clutter. In this simple example it's not bad but for longer queries with many helper variables it's much more vexing.

Is there a simple way to express that via the query; I mean without defining a separate rule?

Cheers,
  Jacek

答:
A very straight-forward way to do this is to use library(lambda) by Ulrich Neumerkel.

For example, in your case, given the sample facts:

```
mother_child(m, c).
father_child(f, c).
```

We get for your query:

```
?- mother_child(M, C),
   father_child(F, C).
M = m,
<b>C = c,</b>
F = f.
```

We would like to project away the variable C.

So we wrap the whole query inside a lambda expression such that only M and F have global scope and hence are reported by the toplevel:

```
?- <b>M^F</b>+\(mother_child(M, C),
         father_child(F, C)).
M = m,
F = f.
```

This obviously becomes all the more useful the more variables you want to project away. You only need to specify the variables you want the toplevel to report.

Body:
Is there a way to force the prolog CLI to return query results with only the variables I'm interested in? A simple example would be:

?- mother(M, C1), father(F, C1).

which returns bindings for all M, F and C1. But I'm interested only in M and F, while C1 is just clutter. In this simple example it's not bad but for longer queries with many helper variables it's much more vexing.

Is there a simple way to express that via the query; I mean without defining a separate rule?

Cheers,
  Jacek

Body:
A very straight-forward way to do this is to use library(lambda) by Ulrich Neumerkel.

For example, in your case, given the sample facts:

mother_child(m, c).
father_child(f, c).

We get for your query:

?- mother_child(M, C),
   father_child(F, C).
M = m,
C = c,
F = f.

We would like to project away the variable C.

So we wrap the whole query inside a lambda expression such that only M and F have global scope and hence are reported by the toplevel:

?- M^F+\(mother_child(M, C),
         father_child(F, C)).
M = m,
F = f.

This obviously becomes all the more useful the more variables you want to project away. You only need to specify the variables you want the toplevel to report.


问:
Kleisli exponentiation in Kotlin
I tried to write the Kleisli exponentiation in Kotlin:

```<code>fun <A,B> kleisli(n: Int, f: (A) -> B): (A) -> B = if (n == 1) f else { it -> f(kleisli(n-1, ::f)(it)) }
</code>```

that just composes f, n times (please do not put n = 0 in my code).

Kotlin (1.0.6) complains error: unsupported [References to variables aren't supported yet] pointing at the ::f.

Am I doing something wrong?

答:
Use just f instead of ::f, it is already a functional value (i.e. a parameter, a variable or a property of a functional type), so you don't need to make a callable reference of it.

```<code> ... else { it -> f(kleisli(n - 1, f)(it)) }
</code>```

Also, your example seems to have a type mismatch: kleisli(n - 1, f) returns a function of type (A) -> B, which is called on it of type A, returning a result of type B. Then the result is passed to f, but f can only receive A. To fix that, you can remove type parameter B and leave only A:

```<code>fun <A> kleisli(n: Int, f: (A) -> A) : (A) -> A =
    if (n == 1)
        f else
        { it -> f(kleisli(n - 1, f)(it)) }
</code>```

(runnable demo of this code)

Also, this code demonstrates the intention perfectly well in functional style, but it might result into redundant objects allocation and undesired call stack growth. It can, however, be rewritten into imperative style, which will work more efficiently:

```<code>fun <T> iterativeKleisli(n: Int, f: (T) -> T) : (T) -> T = { x ->
    var result = x
    for (i in 1..n)
        result = f(result)
    result
}
</code>```

Title: Kleisli exponentiation in Kotlin

Body:
I tried to write the Kleisli exponentiation in Kotlin:

fun  kleisli(n: Int, f: (A) -> B): (A) -> B = if (n == 1) f else { it -> f(kleisli(n-1, ::f)(it)) }

that just composes f, n times (please do not put n = 0 in my code).

Kotlin (1.0.6) complains error: unsupported [References to variables aren't supported yet] pointing at the ::f.

Am I doing something wrong?

Body:
Use just f instead of ::f, it is already a functional value (i.e. a parameter, a variable or a property of a functional type), so you don't need to make a callable reference of it.

 ... else { it -> f(kleisli(n - 1, f)(it)) }

Also, your example seems to have a type mismatch: kleisli(n - 1, f) returns a function of type (A) -> B, which is called on it of type A, returning a result of type B. Then the result is passed to f, but f can only receive A. To fix that, you can remove type parameter B and leave only A:

fun <A> kleisli(n: Int, f: (A) -> A) : (A) -> A =
    if (n == 1)
        f else
        { it -> f(kleisli(n - 1, f)(it)) }

(runnable demo of this code)

Also, this code demonstrates the intention perfectly well in functional style, but it might result into redundant objects allocation and undesired call stack growth. It can, however, be rewritten into imperative style, which will work more efficiently:

fun <T> iterativeKleisli(n: Int, f: (T) -> T) : (T) -> T = { x ->
    var result = x
    for (i in 1..n)
        result = f(result)
    result
}


问:
Is it possible to send date of transaction (not today) using Google Measurement Protocol?
I build application which pull sales data from Amazon and push it to Google Analytics.

I'm "hitting" transaction to Analytics and it's all works fine, the problem is that in Amazon the sales data updated after 48 hours (maximum) so I need to pull the report two days later.

Does anyone know if there's a way to send the date of the transaction? Can't find it in the Measurement Protocol API.

Thank you all, Peace and love :)

答:
Not really. You have the queue time parameter (offset between current time and time the data was tracked), but as it says in the documentation:

Values greater than four hours may lead to hits not being processed.

"May" indicates that this is not a completely fixed limit but I'm pretty sure that 48 hours are not covered (Philipp Walton, a Google engineer who frequents SO once mentioned that the queue time limit is somehow related to timezones and rollover between days, so I'd guess that two days are way to long).

Apart from that there is as of yet no way to set a date for a hit.


问:
Can I call the child's parent method from the base class?
How can i do this:

```<code>class BaseClass{
  void templateMethod(){
     methodImplementation();
     if(this.base.getType() != typeof(BaseClass)) this.base.methodImplementation();
  }
  void abstract methodImplementation();
}
class Derived1 : BaseClass{
  void override methodImplementation(){
     .. do things ..
  }
}
class Derived2 : Derived1{
  void override methodImplementation(){
     .. do more things ..
  }
}
</code>```

This would then result in both implementations (things AND more things) being executed.

```<code>Derived2 object = new Derived2();
object.templateMethod();
</code>```

Then all children and grand children and so on, would only need to implement their part of methodImplementation and it would get called throughout all levels when called in the final object.

But this.base is not a thing. What I need is to call the implementation of the parent of the instantiated object real class, but the code is in the baseClass so I can use it in a Template method pattern.

Thanks in advance, sorry if I'm not making myself clear. I just need to know if it can be done. This being good practice, optimal, recommended or useful is another thing that I'll consider.

EDIT:

The code above is not exactly right, it should be like this:

```<code>class BaseClass{
  void templateMethod(){
     methodImplementation();
     if(this.base.getType() != typeof(BaseClass)) this.base.templateMethod();
  }
  void abstract methodImplementation();
}
class Derived1 : BaseClass{
  void override methodImplementation(){
     .. do things ..
  }
}
class Derived2 : Derived1{
  void override methodImplementation(){
     .. do more things ..
  }
}
</code>```

the difference being that in BaseClass.templateMethod() what gets called in the second line is templateMethod(), not methodImplementation(), so it calls itself but from the "perspective" of the parent class. Now I'm thinking more and more this is just not possible and creates more confusion than anything.

答:
If I understand you correctly, you want to call all methodImplementation from top level derived class. You can do it like this:

```<code>class BaseClass{
  void templateMethod(){
     methodImplementation();
  }
  void abstract methodImplementation();
}
class Derived1 : BaseClass{
  // virtual as you want to derive it again
  virtual void override methodImplementation(){
     //.. do things ..
  }
}
class Derived2 : Derived1{
  void override methodImplementation(){
     //.. do more things ..
     base.methodImplementation();
  }
}
</code>```

Each derived class only has to implement his part of methodImplementation and at the end call their base class. Since methodImplementation is abstract dont call base on first level. Also mark all methodImplementation as virtual so you can override it again.

Body:
How can i do this:

class BaseClass{
  void templateMethod(){
     methodImplementation();
     if(this.base.getType() != typeof(BaseClass)) this.base.methodImplementation();
  }
  void abstract methodImplementation();
}
class Derived1 : BaseClass{
  void override methodImplementation(){
     .. do things ..
  }
}
class Derived2 : Derived1{
  void override methodImplementation(){
     .. do more things ..
  }
}

This would then result in both implementations (things AND more things) being executed.

Derived2 object = new Derived2();
object.templateMethod();

Then all children and grand children and so on, would only need to implement their part of methodImplementation and it would get called throughout all levels when called in the final object.

But this.base is not a thing. What I need is to call the implementation of the parent of the instantiated object real class, but the code is in the baseClass so I can use it in a Template method pattern.

Thanks in advance, sorry if I'm not making myself clear. I just need to know if it can be done. This being good practice, optimal, recommended or useful is another thing that I'll consider.

EDIT:

The code above is not exactly right, it should be like this:

class BaseClass{
  void templateMethod(){
     methodImplementation();
     if(this.base.getType() != typeof(BaseClass)) this.base.templateMethod();
  }
  void abstract methodImplementation();
}
class Derived1 : BaseClass{
  void override methodImplementation(){
     .. do things ..
  }
}
class Derived2 : Derived1{
  void override methodImplementation(){
     .. do more things ..
  }
}

the difference being that in BaseClass.templateMethod() what gets called in the second line is templateMethod(), not methodImplementation(), so it calls itself but from the "perspective" of the parent class. Now I'm thinking more and more this is just not possible and creates more confusion than anything.

Body:
If I understand you correctly, you want to call all methodImplementation from top level derived class. You can do it like this:

class BaseClass{
  void templateMethod(){
     methodImplementation();
  }
  void abstract methodImplementation();
}
class Derived1 : BaseClass{
  // virtual as you want to derive it again
  virtual void override methodImplementation(){
     //.. do things ..
  }
}
class Derived2 : Derived1{
  void override methodImplementation(){
     //.. do more things ..
     base.methodImplementation();
  }
}

Each derived class only has to implement his part of methodImplementation and at the end call their base class. Since methodImplementation is abstract dont call base on first level. Also mark all methodImplementation as virtual so you can override it again.


答:
You can call the base method in your derived classes. Here's an example. You can call the base method in each line of your derived class; depending on when you want to execute the logic.

```<code>public class Animal
{
    public void WhatAmI()
    {
        Console.WriteLine("Animal");
    }
}

public class Fish : Animal
{
    public new void WhatAmI()
    {
        base.WhatAmI();
        Console.WriteLine("Fish");
    }
}

public class HammerheadShark : Fish
{
    public new void WhatAmI()
    {
        base.WhatAmI();
        Console.WriteLine("HammerheadShark");
    }
}
</code>```

When you call the WhatAmI method:

```<code>var animal = new HammerheadShark();
animal.WhatAmI();
</code>```

You'll get this:

Animal

Fish

HammerheadShark

Title: Can I call the child's parent method from the base class?

Body:
You can call the base method in your derived classes. Here's an example. You can call the base method in each line of your derived class; depending on when you want to execute the logic.

public class Animal
{
    public void WhatAmI()
    {
        Console.WriteLine("Animal");
    }
}

public class Fish : Animal
{
    public new void WhatAmI()
    {
        base.WhatAmI();
        Console.WriteLine("Fish");
    }
}

public class HammerheadShark : Fish
{
    public new void WhatAmI()
    {
        base.WhatAmI();
        Console.WriteLine("HammerheadShark");
    }
}

When you call the WhatAmI method:

var animal = new HammerheadShark();
animal.WhatAmI();

You'll get this:

Animal

Fish

HammerheadShark