问:
Bootstrap Popover Element Inside A-Link; Prevent A-Link Click From Firing
I have a Bootstrap Popover Image which should display a popup. This IMG is inside an A-link which has its own Click Handler.

My goal is to prevent the Parent A-Click from firing; when you click the image, the only thing you see is the popup, but not the real A-Click action (the alert box).

I know that this is done via e.stopPropagation() but the problem is, how do I get access to Bootstrap Popover's Click Handler? Where would I put e.stopPropagation?

$('[data-toggle="popover"]').popover();

$('#link').off('click.link').on('click.link', function() {
    alert('Clicked main link');
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7/js/bootstrap.min.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>

Main Link

<img src="abc.png" data-toggle="popover" data-placement="bottom" data-original-title="" data-content="PopOver Tooltip" aria-describedby="tooltip">
</code>```

Let me show why the IMG has to be inside the A. The A's are Accordion Menu Bars, and they all have a fixed width. You can go to a page by selecting a menu (you don't have to click right on the text). Some menu items also have an INFO I icon that displays a popup. The action of the I-Icon should be to display the popover. The action of the A-link itself should be to go the page as normal.

答:
Per our conversation in the comments I believe there are superior alternatives to relying on an anchor element to achieve this and would encourage you to explore alternatives like <button> since the purpose of this item seems to be better suited for that element.

That being said, to address the question at hand:

If you add a class to your anchor element so that you can target it via JavaScript your solution is quite simple:

```<code>$('a.poplink').click(function(e) {
  e.preventDefault();
});
</code>```

This will prevent any anchor element with the class of poplink from processing a click-through event, without prohibiting the Bootstrap Popover event tied to your .

$('[data-toggle="popover"]').popover();

$('a.poplink').click(function(e) {
  e.preventDefault();
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><link href="//maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet">
<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script type="text/javascript" src="//maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>

  Main Link
  <img src="abc.png" data-toggle="popover" data-placement="bottom" data-original-title="" data-content="PopOver Tooltip" aria-describedby="tooltip">
</code>```

Body:
I have a Bootstrap Popover Image which should display a popup. This IMG is inside an A-link which has its own Click Handler.

My goal is to prevent the Parent A-Click from firing; when you click the image, the only thing you see is the popup, but not the real A-Click action (the alert box).

I know that this is done via e.stopPropagation() but the problem is, how do I get access to Bootstrap Popover's Click Handler? Where would I put e.stopPropagation?

$('[data-toggle="popover"]').popover();

$('#link').off('click.link').on('click.link', function() {
    alert('Clicked main link');
});

<link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>

Main Link

Let me show why the IMG has to be inside the A. The A's are Accordion Menu Bars, and they all have a fixed width. You can go to a page by selecting a menu (you don't have to click right on the text). Some menu items also have an INFO I icon that displays a popup. The action of the I-Icon should be to display the popover. The action of the A-link itself should be to go the page as normal.

Body:
Per our conversation in the comments I believe there are superior alternatives to relying on an anchor element to achieve this and would encourage you to explore alternatives like <button> since the purpose of this item seems to be better suited for that element.

That being said, to address the question at hand:

If you add a class to your anchor element so that you can target it via JavaScript your solution is quite simple:

$('a.poplink').click(function(e) {
  e.preventDefault();
});

This will prevent any anchor element with the class of poplink from processing a click-through event, without prohibiting the Bootstrap Popover event tied to your <img>.

$('[data-toggle="popover"]').popover();

$('a.poplink').click(function(e) {
  e.preventDefault();
});

<link href="//maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet">
<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script type="text/javascript" src="//maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>

<a id="link" href="http://google.com" class="poplink" style="width:300px; height:100px; border:1px solid black;">
  Main Link
  <img src="abc.png" data-toggle="popover" data-placement="bottom" data-original-title="" data-content="PopOver Tooltip" aria-describedby="tooltip">
</a>


来源: stackexchange

问:
Accessing a folder from ClassLoader
I have a JAVA EE app. with this structure:

```<code>/iberiaApp
/iberiaApp/configFiles/hotel
/iberiaApp/config.jsp
/iberiaApp/WEB-INF/classes
</code>```

inside config.jsp I have this piece of code:

```<code> <%=FileReader.readFiles("configFiles/hotel")%>;
</code>```

and

```<code>public static List<String> readFiles (String folder) throws URISyntaxException {

    ClassLoader classLoader = FileReader.class.getClassLoader();

    URI uri = classLoader.getResource(folder).toURI();
</code>```

But I got a nullpointer getting the URI (classLoader.getResource(folder) is returning null)

答:
The web app root directory itself is not on the runtime classpath, so you can’t load a resource relative to the web app root via a class loader. Put the configuration files under src/main/resources, so at runtime they will be under WEB-INF/classes, and accessible via class loading.

Also you don’t want keep your config files under the web app root anyway, because then they are accessible to the web app users directly.

ContentLicense: CC BY-SA 3.0

Title: Accessing a folder from ClassLoader

Body:
I have a JAVA EE app. with this structure:

/iberiaApp
/iberiaApp/configFiles/hotel
/iberiaApp/config.jsp
/iberiaApp/WEB-INF/classes

inside config.jsp I have this piece of code:

 <%=FileReader.readFiles("configFiles/hotel")%>;

and

public static List<String> readFiles (String folder) throws URISyntaxException {

    ClassLoader classLoader = FileReader.class.getClassLoader();

    URI uri = classLoader.getResource(folder).toURI();

But I got a nullpointer getting the URI (classLoader.getResource(folder) is returning null)


问:
keyup event is not listened in form inside django template
I am using javascript and django for the first time. In my form, I need to show basic amount from the calculation of two field i.e quantity and rate. For that I did the following

```<code>{% block content %}
<div class="right_col" role="main">
    <h1 class="text-center"> Purchase Order</h1>
    <div class="space"></div>
    <!-- {%include 'includes/form.html'%} -->
    {%include 'dashboard/purchase_order/purchase_order_form.html'%}
</div>
{% endblock content %}

{% block javascripts %}
  {{ block.super }}
  <script>
    $(document).ready(function() {
      console.log('dom is ready');
      $('#form-change').keyup(function() {
        console.log('form')
        var quantity = document.getElementById('id_quantity').value;
        var rate = document.getElementById('id_rate').value;
        if (quantity && rate) {
          document.getElementById('id_basic_amount').value = parseInt(quantity) * parseInt(rate);
        }
      })
    })
  </script>
{% endblock javascripts %}

<form id="demo-form2 form-change" class="form-horizontal form-label-left" action="" method="post" enctype="multipart/form-data">
   {% csrf_token %}
   <div class="form-group">
      <div class="col-md-6 col-sm-6 col-xs-12">
         <input type="number" name="quantity" value="0" min="0" class="form-control col-md-7 col-xs-12" required="" id="id_quantity">
      </div>
   </div>
   <div class="form-group">
      <div class="col-md-6 col-sm-6 col-xs-12">
         <input type="number" name="rate" value="0.0" step="0.01" class="form-control col-md-7 col-xs-12" required="" id="id_rate">
      </div>
   </div>
   <div class="form-group">
      <div class="col-md-6 col-sm-6 col-xs-12">
         <input type="number" name="basic_amount" value="0.0" step="0.01" class="form-control col-md-7 col-xs-12" required="" id="id_basic_amount">
      </div>
   </div>
</form>
</code>```

but the keyup event is not listened. The line console.log('dom is ready') is shown in the console but the line console.log('form') is not consoled in the console. I tried separate javascript in jsbin and there it is working

http://jsbin.com/hadafezeqa/edit?html,console,output

why it is not working in django template only?

答:
Try binding the keyup event to one of the form elements, not the form itself.
Try changing the input of the form, like this:

```<code> <input type="number" name="quantity" value="0" min="0" class="form-control col-md-7 col-xs-12 form-change" required="" id="id_quantity">
</code>```

And:

```<code><input type="number" name="rate" value="0.0" step="0.01" class="form-control col-md-7 col-xs-12 form-change" required="" id="id_rate">
</code>```

And change $('#form-change').keyup() to $('.form-change').keyup()

Hopefully you could see the console.

OR

Change id of form.

```<code><form id="demo-form2 form-change">
</code>```

To:

```<code><form id="form-change">
</code>```

Body:
I am using javascript and django for the first time. In my form, I need to show basic amount from the calculation of two field i.e quantity and rate. For that I did the following

{% block content %}

 Purchase Order

    {%include 'dashboard/purchase_order/purchase_order_form.html'%}

{% endblock content %}

{% block javascripts %}
  {{ block.super }}

{% endblock javascripts %}

<form id="demo-form2 form-change" class="form-horizontal form-label-left" action="" method="post" enctype="multipart/form-data">
   {% csrf_token %}

         <input type="number" name="quantity" value="0" min="0" class="form-control col-md-7 col-xs-12" required="" id="id_quantity">

         <input type="number" name="rate" value="0.0" step="0.01" class="form-control col-md-7 col-xs-12" required="" id="id_rate">

         <input type="number" name="basic_amount" value="0.0" step="0.01" class="form-control col-md-7 col-xs-12" required="" id="id_basic_amount">

</form>

but the keyup event is not listened. The line console.log('dom is ready') is shown in the console but the line console.log('form') is not consoled in the console. I tried separate javascript in jsbin and there it is working

http://jsbin.com/hadafezeqa/edit?html,console,output

why it is not working in django template only?

Body:
Try binding the keyup event to one of the form elements, not the form itself.
Try changing the input of the form, like this:

 <input type="number" name="quantity" value="0" min="0" class="form-control col-md-7 col-xs-12 form-change" required="" id="id_quantity">

And:

<input type="number" name="rate" value="0.0" step="0.01" class="form-control col-md-7 col-xs-12 form-change" required="" id="id_rate">

And change $('#form-change').keyup() to $('.form-change').keyup()

Hopefully you could see the console.

OR

Change id of form.

<form id="demo-form2 form-change">

To:

<form id="form-change">


问:
Axios false 404 error
I'm having an issue where I think axios is querying the wrong URL just before query is sent.

```<code>getShows : function(){
  if( ! this.query ) return false;
  var getURL = this.makeUrlFromObject(this.query);
  console.log('getURL', getURL);
  var self = this;
  axios.get(getURL).then(function(response){
    console.log('response.data', response.data)
    self.shows = response.data;
  });
},
makeUrlFromObject : function(query){
  var queryArray = [];
  for (var prop in query) {
    if(!query.hasOwnProperty(prop)) continue;
    queryArray.push(prop + "=" + query[prop]);
  }
  var url = this.apiUrl + '?' + queryArray.join('&');
  return url;
},
...
</code>```

Running the getShows returns the following in the console:

```<code>1. getURL /api/all?date=20180131

2. GET http://website.dev/shows/false 404 (Not Found)                     false:1

3. response.data (3) [{…}, {…}, {…}]
</code>```

I can't seem to diagnose where this false:1 is coming from. The request and response are both working, just this extra request seems to crop up from nowhere.

答:
I'm an idiot. Following the ajax request, an image element is created on the page.

The response (not shown) happened to include an image file that was loaded into 2 of the 3 objects. The 3rd didn't have an image, so it came back as { image : false }.

When this was then used to create an image template, it was coming back as:

```<code><div style="background-image:url(false)">
</code>```

So the console came back with a get request for 'false', which 404d.

Title: Axios false 404 error

Body:
I'm having an issue where I think axios is querying the wrong URL just before query is sent.

getShows : function(){
  if( ! this.query ) return false;
  var getURL = this.makeUrlFromObject(this.query);
  console.log('getURL', getURL);
  var self = this;
  axios.get(getURL).then(function(response){
    console.log('response.data', response.data)
    self.shows = response.data;
  });
},
makeUrlFromObject : function(query){
  var queryArray = [];
  for (var prop in query) {
    if(!query.hasOwnProperty(prop)) continue;
    queryArray.push(prop + "=" + query[prop]);
  }
  var url = this.apiUrl + '?' + queryArray.join('&');
  return url;
},
...

Running the getShows returns the following in the console:

1. getURL /api/all?date=20180131

2. GET http://website.dev/shows/false 404 (Not Found)                     false:1

3. response.data (3) [{…}, {…}, {…}]

I can't seem to diagnose where this false:1 is coming from. The request and response are both working, just this extra request seems to crop up from nowhere.

Body:
I'm an idiot. Following the ajax request, an image element is created on the page.

The response (not shown) happened to include an image file that was loaded into 2 of the 3 objects. The 3rd didn't have an image, so it came back as { image : false }.

When this was then used to create an image template, it was coming back as:

<div style="background-image:url(false)">

So the console came back with a get request for 'false', which 404d.


问:
With 'kotlin-kapt' plugin, Android Studio doesnt provide specific errors about Dagger 2
I use Kotlin with Dagger 2. The problem is, when I make mistake while implementing Dagger (e.g., miss @Inject for class constractor), IDE doesnt show specifically where mistake is. Insead compiler error is always the same:

Execution failed for task ':app:kaptDebugKotlin'.
  Internal compiler error. See log for more details

Class with a deliberate mistake (commented @Inject):

```<code>class LoginPresenter //@Inject
constructor(private val request: LoginRequest)
</code>```

Project build.gradle file:

```<code>buildscript {
    ext.kotlin_version = '1.1.4-3'

    repositories {
        jcenter()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:2.3.3'
        classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
    }
}

allprojects {
    repositories {
        jcenter()
    }
}

task clean(type: Delete) {
    delete rootProject.buildDir
}
</code>```

Module build.gradle:

```<code>apply plugin: 'com.android.application'
apply plugin: 'kotlin-android'
apply plugin: 'kotlin-kapt'

android {
    compileSdkVersion 26
    buildToolsVersion "26.0.1"
    defaultConfig {
        applicationId "com.example.kravets_a.kotlinanddagger"
        minSdkVersion 16
        targetSdkVersion 26
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    ...

    compile 'com.google.dagger:dagger:2.10'
    annotationProcessor 'com.google.dagger:dagger-compiler:2.10'
    kapt "com.google.dagger:dagger-compiler:2.10"

    compile "org.jetbrains.kotlin:kotlin-stdlib-jre7:$kotlin_version"
}
repositories {
    mavenCentral()
}
</code>```

答:
The solution is to add this to your module's build.gradle:</p>

```<code>kapt {
    correctErrorTypes = true
}
</code>```

Body:
I use Kotlin with Dagger 2. The problem is, when I make mistake while implementing Dagger (e.g., miss @Inject for class constractor), IDE doesnt show specifically where mistake is. Insead compiler error is always the same:

Execution failed for task ':app:kaptDebugKotlin'.
  Internal compiler error. See log for more details

Class with a deliberate mistake (commented @Inject):

class LoginPresenter //@Inject
constructor(private val request: LoginRequest)

Project build.gradle file:

buildscript {
    ext.kotlin_version = '1.1.4-3'

    repositories {
        jcenter()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:2.3.3'
        classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
    }
}

allprojects {
    repositories {
        jcenter()
    }
}

task clean(type: Delete) {
    delete rootProject.buildDir
}

Module build.gradle:

apply plugin: 'com.android.application'
apply plugin: 'kotlin-android'
apply plugin: 'kotlin-kapt'

android {
    compileSdkVersion 26
    buildToolsVersion "26.0.1"
    defaultConfig {
        applicationId "com.example.kravets_a.kotlinanddagger"
        minSdkVersion 16
        targetSdkVersion 26
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    ...

    compile 'com.google.dagger:dagger:2.10'
    annotationProcessor 'com.google.dagger:dagger-compiler:2.10'
    kapt "com.google.dagger:dagger-compiler:2.10"

    compile "org.jetbrains.kotlin:kotlin-stdlib-jre7:$kotlin_version"
}
repositories {
    mavenCentral()
}

Body:
The solution is to add this to your module's build.gradle:

kapt {
    correctErrorTypes = true
}


问:
Picking up a Sequence out of a matrix
I would like to find a way to pick the correct "11" out of my matrix.
You start from upper-left end, by [1, 1], and move to the direction from left to right rowwise.

Each time you see the combination "01" or "00", you should keep on moving from left to right till you find some "11".

In the example 1 the correct solution would be the "11" on the position [1, 3].

```<code># Example 1:
(R)

#       [,1] [,2] [,3]
# [1,]   01   01   11
# [2,]   11   01   11
# [3,]   01   11   10
</code>```

Once you have a "10" you must change the line and start from the second line.
In the example 2 the code must end up with the result "11" on the [2, 1] position.

```<code># Example 2:
(R1)

#       [,1] [,2] [,3]
# [1,]   01   10   11
# [2,]   11   01   11
# [3,]   01   11   10
</code>```

The command below would work for the second example, but not for the first one.

```<code>which(R == "11",  arr.ind = T)
</code>```

I am looking for the position of the correct "11" in the matrix. Any idea would be highly appreciated!

p.s.
For replication of R and R1:

```<code>R <- structure(c("01", "11", "01", "01", "01", "11", "11", "11", "10"), .Dim = c(3L, 3L))
R1 <- structure(c("01", "11", "01", "10", "01", "11", "11", "11", "10"), .Dim = c(3L, 3L))
</code>```

答:
Here's another little function that does it for you:

```<code>foo <- function(mat, a, b) {
  res <- t(apply(mat, 1, function(x) replace(x, cumsum(x == a) > 0, NA)))
  res <- which(res == b, arr.ind = TRUE)
  res[order(res[,1], res[,2]),][1,]
}

foo(R, "10", "11")
#row col
#  1   3
foo(R1, "10", "11")
#row col
#  2   1
</code>```

This works by-row and replaces any elements after a "10" with NA and then gets the first "11" occurence.

Title: Picking up a Sequence out of a matrix

Body:
I would like to find a way to pick the correct "11" out of my matrix.
You start from upper-left end, by [1, 1], and move to the direction from left to right rowwise.

Each time you see the combination "01" or "00", you should keep on moving from left to right till you find some "11".

In the example 1 the correct solution would be the "11" on the position [1, 3].

# Example 1:
(R)

#       [,1] [,2] [,3]
# [1,]   01   01   11
# [2,]   11   01   11
# [3,]   01   11   10

Once you have a "10" you must change the line and start from the second line.
In the example 2 the code must end up with the result "11" on the [2, 1] position.

# Example 2:
(R1)

#       [,1] [,2] [,3]
# [1,]   01   10   11
# [2,]   11   01   11
# [3,]   01   11   10

The command below would work for the second example, but not for the first one.

which(R == "11",  arr.ind = T)

I am looking for the position of the correct "11" in the matrix. Any idea would be highly appreciated!

p.s.
For replication of R and R1:

R <- structure(c("01", "11", "01", "01", "01", "11", "11", "11", "10"), .Dim = c(3L, 3L))
R1 <- structure(c("01", "11", "01", "10", "01", "11", "11", "11", "10"), .Dim = c(3L, 3L))

Body:
Here's another little function that does it for you:

foo <- function(mat, a, b) {
  res <- t(apply(mat, 1, function(x) replace(x, cumsum(x == a) > 0, NA)))
  res <- which(res == b, arr.ind = TRUE)
  res[order(res[,1], res[,2]),][1,]
}

foo(R, "10", "11")
#row col
#  1   3
foo(R1, "10", "11")
#row col
#  2   1

This works by-row and replaces any elements after a "10" with NA and then gets the first "11" occurence.


问:
Amazon RDS MySQL instance performs very slow
I have published my website on Amazon EC2 (Singapore region) and I have used MySQL RDS instance for the data storage. Everything is working very fine except performance.

I seems that, my all queries, especially the select statement, is performing very slowly. If I check this issue on my local PC, there it is working very well. But when I am trying to get data from RDS instance, it is very slow. Some of the select statements takes 2-3 seconds to fetch data.

I have properly tuned up all table indexes, and normalized/de-normalized as required. I have made all necessary settings on RDS custom parameter group (eg. max_connection, buffer etc). I don't know if I am missing something, but it didn't work for me - performance didn't increase.

So, can someone please help me with this issue?

答:
For me, it was nothing to do with MySQL but rather the instance type I was on t2.medium. The problem is I ran out of CPU credits because the load on the DB was too high and the balance kept going down until finally, I was getting far fewer credits hourly than were needed.

Here is what I saw in RDS CloudWatch under CPU Credit Usage:

If you have the same problem it may be time to switch to a different instance. Here is the list of instance types:

https://aws.amazon.com/rds/instance-types/

Hope this helps.

ContentLicense: CC BY-SA 4.0


问:
Will Firebase Realtime Database Sync when the device comes online, But the Application is not opened?
I am trying out Firebase Realtime Database. I have a created a node users, In that I have created a node user_1. The JSON is like the one below

```<code>{
  "user_1" : {
    "firstName" : "User",
    "lastName" : "Last",
    "middleName" : "S"
  }
}
</code>```

I have enabled Offline Persistence & the Sync enabled for that particular Node user_1.

```<code>FirebaseDatabase.getInstance().setPersistenceEnabled(true);
FirebaseDatabase.getInstance().getReference().child("users").child("user_1").keepSynced(true);
</code>```

Firstly , I opened the App & synched the user_1 data. Then I killed the Application, But the Device is still connected to internet. I made changes to the user_1 node in the Firebase Console. After sometime , I have disconnected to internet. I opened the app again, listened to that node user_1. But the offline data is not synced with the latest data from Firebase Server. Does that mean , keepSynced() will only work when the Application is in Foreground ?

答:
When you call keepSynced(true), the Firebase Realtime Database client synchronizes the data at that location while your app is active.

If you force-kill the app, the client will not be active anymore and it won't synchronize anymore.

It may continue to synchronize for a while when your back goes into the background. Whether it does this and for how long depends on the Android version and device manufacturer. Given their efforts to reduce background data usage (to improve battery life), I'd recommend not relying on this.

Body:
I am trying out Firebase Realtime Database. I have a created a node users, In that I have created a node user_1. The JSON is like the one below

{
  "user_1" : {
    "firstName" : "User",
    "lastName" : "Last",
    "middleName" : "S"
  }
}

I have enabled Offline Persistence & the Sync enabled for that particular Node user_1.

FirebaseDatabase.getInstance().setPersistenceEnabled(true);
FirebaseDatabase.getInstance().getReference().child("users").child("user_1").keepSynced(true);

Firstly , I opened the App & synched the user_1 data. Then I killed the Application, But the Device is still connected to internet. I made changes to the user_1 node in the Firebase Console. After sometime , I have disconnected to internet. I opened the app again, listened to that node user_1. But the offline data is not synced with the latest data from Firebase Server. Does that mean , keepSynced() will only work when the Application is in Foreground ?


问:
How to do unit testing on timer functions on a microcontroller

I am new to the concept of unit testing, and I am currently trying to get more comfortable with it.

I have to do unit testing on a timer driver for a microcontroller written in C. Now, I heard that a unit test on a function should not depend on the outcome of another function. My problem is, how can we test a function that is supposed to stop a timer in these conditions ? Don't we need to start the timer, heck, we even need to initialize it !

I would like to know at which level we need to consider our unit test ; is it at the level of one function (in that case, we get the problem above), or is it at the level of the driver itself (in that case, we can use multiple functions of the driver in one unit test) ?

I would love to hear from more experienced people their feeling about this subject, as I feel I'm going nowhere at the moment.

答:
There is pretty much only one correct way to test a timer driver:

Write a test case application that uses all functions of the driver. Leave the driver code itself completely untouched.

Important test parameters to note/document: clock speed, clock accuracy. That is, which clock source is the timer hardware getting its clock from, how fast is it and what is the expected accuracy? You'll probably want to test the driver against a proper crystal oscillator and not some built-in RC oscillator. That way you can rule out clock inaccuracy and see what the driver latency is. Internal PLLs/FLLs in the system clock can also have a certain inaccuracy.

In the test application, set some GPIO pins wherever you expect the timer to stop etc. Possibly from a callback function, depending on how the driver is written.

Measure the actual time with an oscilloscope. This is mandatory, you can't test such code without one. Period.

There's not much more to it. Optionally, if you want a more in-depth test, you could include some manner of code coverage to see if all parts of the driver code are executed at some point.


问:
ReactJS: onClick() sorting for dynamically rendered  elements
I am printing the data fetched from an API into a table, and I am facing some difficulties to sort the column values, alphabetically and numerically. If the columns data within the API consists of numerical values, i.e. 10.01, 333.01, 8.99 or 100.88, etc. to sort it ascending from 0 -> 100 on first click and on the second click descending 100 -> 0 and in the same logic for alphabetically values, i.e a-z && Z-A and reverse versa.

The function that I am familiar with onclick="sortTable(0)", doesn't function in the same way in React, as I used to code it in javaScript. Probably I am misleading the ES6 standard, but I am not sure.

Here is my code sample with onclick="sortTable(0)", but it's doesn't function well:

```<code>class App extends React.Component
{
    constructor()
    {
        super();
        this.state = {
            rows: [],
            columns: [],
            clicked: false
        }

        this.handleClick = this.handleClick.bind( this );
    }

    handleClick()
    {
        this.setState( {
            clicked: true
        } );
    }

     sortTable( n )
{
            var table, columns, switching, i, x, y, shouldSwitch, dir, switchcount = 0;
            table = document.getElementById( "datagrid" );
            switching = true;
            //Set the sorting direction to ascending:
            dir = "asc";
            /*Make a loop that will continue until
            no switching has been done:*/
            while ( switching )
            {
                //start by saying: no switching is done:
                switching = false;
                columns = table.getElementsByTagName( "TH" );
                /*Loop through all table rows (except the
                first, which contains table headers):*/
                for ( i = 1; i < ( columns.length - 1 ); i++ )
                {
                    //start by saying there should be no switching:
                    shouldSwitch = false;
                    /*Get the two elements you want to compare,
                    one from current row and one from the next:*/
                    x = columns[i].getElementsByTagName( "TH" )[n];
                    y = columns[i + 1].getElementsByTagName( "TH" )[n];
                    /*check if the two rows should switch place,
                    based on the direction, asc or desc:*/
                    if ( dir == "asc" )
                    {
                        if ( x.innerHTML.toLowerCase() > y.innerHTML.toLowerCase() )
                        {
                            //if so, mark as a switch and break the loop:
                            shouldSwitch = true;
                            break;
                        }
                    } else if ( dir == "desc" )
                    {
                        if ( x.innerHTML.toLowerCase() < y.innerHTML.toLowerCase() )
                        {
                            //if so, mark as a switch and break the loop:
                            shouldSwitch = true;
                            break;
                        }
                    }
                }
                if ( shouldSwitch )
                {
                    /*If a switch has been marked, make the switch
                    and mark that a switch has been done:*/
                    rows[i].parentNode.insertBefore( rows[i + 1], rows[i] );
                    switching = true;
                    //Each time a switch is done, increase this count by 1:
                    switchcount++;
                } else
                {
                    /*If no switching has been done AND the direction is "asc",
                    set the direction to "desc" and run the while loop again.*/
                    if ( switchcount == 0 && dir == "asc" )
                    {
                        dir = "desc";
                        switching = true;
                    }
                }
            }
        }

    componentDidMount()
    {

        fetch( "http://ickata.net/sag/api/staff/bonuses/" )
            .then( function ( response )
            {
                return response.json();
            } )
            .then( data =>
            {
                this.setState( { rows: data.rows, columns: data.columns } );
            } );

    }

    render()
    {

        return (
            <div id="container" className="container">
                <h1>Final Table with React JS</h1>
                <table className="datagrid">
                    <thead>
                        <tr> {
                            this.state.columns.map(( column, index ) =>
                            {
                                return ( <th onClick={this.handleClick}>{column}</th> )
                            }
                            )
                        }
                        </tr>
                    </thead>
                    <tbody> {
                        this.state.rows.map( row => (
                            <tr>{row.map( cell => (
                                <td>{typeof cell === 'number' ? cell.toFixed( 2 ) : cell}</td>
                            ) )}
                            </tr>
                        ) )
                    }
                    </tbody>
                </table>
            </div>
        )
    }
}

ReactDOM.render( <div id="container"><App /></div>, document.querySelector( 'body' ) );
</code>```

You are welcome to contribute directly to my Repo: Fetching API data into a table

My example, right after the onclick="sortTable(0)" has been used, doesn't htow any errors in the console, but it prints the same result. I guess I am not handling correct the {column}	 elements.

Unfortunately I was not able to find related documentation at ReactJs.org

It's doesn't function the onClick event at all, so that I can't debug the sor functionality either.

Any suggestions will be appreciated!

答:
onClick = () => this.sortable(0). If you are using any kind of loop in that case you have to pass index to another function to pass through correct value of index. see this link for explanation
React OnClick for item not working</p>

Title: ReactJS: onClick() sorting for dynamically rendered <th> elements

Body:
I am printing the data fetched from an API into a table, and I am facing some difficulties to sort the column values, alphabetically and numerically. If the columns data within the API consists of numerical values, i.e. 10.01, 333.01, 8.99 or 100.88, etc. to sort it ascending from 0 -> 100 on first click and on the second click descending 100 -> 0 and in the same logic for alphabetically values, i.e a-z && Z-A and reverse versa.

The function that I am familiar with onclick="sortTable(0)", doesn't function in the same way in React, as I used to code it in javaScript. Probably I am misleading the ES6 standard, but I am not sure.

Here is my code sample with onclick="sortTable(0)", but it's doesn't function well:

class App extends React.Component
{
    constructor()
    {
        super();
        this.state = {
            rows: [],
            columns: [],
            clicked: false
        }

        this.handleClick = this.handleClick.bind( this );
    }

    handleClick()
    {
        this.setState( {
            clicked: true
        } );
    }

     sortTable( n )
{
            var table, columns, switching, i, x, y, shouldSwitch, dir, switchcount = 0;
            table = document.getElementById( "datagrid" );
            switching = true;
            //Set the sorting direction to ascending:
            dir = "asc";
            /*Make a loop that will continue until
            no switching has been done:*/
            while ( switching )
            {
                //start by saying: no switching is done:
                switching = false;
                columns = table.getElementsByTagName( "TH" );
                /*Loop through all table rows (except the
                first, which contains table headers):*/
                for ( i = 1; i < ( columns.length - 1 ); i++ )
                {
                    //start by saying there should be no switching:
                    shouldSwitch = false;
                    /*Get the two elements you want to compare,
                    one from current row and one from the next:*/
                    x = columns[i].getElementsByTagName( "TH" )[n];
                    y = columns[i + 1].getElementsByTagName( "TH" )[n];
                    /*check if the two rows should switch place,
                    based on the direction, asc or desc:*/
                    if ( dir == "asc" )
                    {
                        if ( x.innerHTML.toLowerCase() > y.innerHTML.toLowerCase() )
                        {
                            //if so, mark as a switch and break the loop:
                            shouldSwitch = true;
                            break;
                        }
                    } else if ( dir == "desc" )
                    {
                        if ( x.innerHTML.toLowerCase() < y.innerHTML.toLowerCase() )
                        {
                            //if so, mark as a switch and break the loop:
                            shouldSwitch = true;
                            break;
                        }
                    }
                }
                if ( shouldSwitch )
                {
                    /*If a switch has been marked, make the switch
                    and mark that a switch has been done:*/
                    rows[i].parentNode.insertBefore( rows[i + 1], rows[i] );
                    switching = true;
                    //Each time a switch is done, increase this count by 1:
                    switchcount++;
                } else
                {
                    /*If no switching has been done AND the direction is "asc",
                    set the direction to "desc" and run the while loop again.*/
                    if ( switchcount == 0 && dir == "asc" )
                    {
                        dir = "desc";
                        switching = true;
                    }
                }
            }
        }

    componentDidMount()
    {

        fetch( "http://ickata.net/sag/api/staff/bonuses/" )
            .then( function ( response )
            {
                return response.json();
            } )
            .then( data =>
            {
                this.setState( { rows: data.rows, columns: data.columns } );
            } );

    }

    render()
    {

        return (

Final Table with React JS

 {
                            this.state.columns.map(( column, index ) =>
                            {
                                return ( {column}	 )
                            }
                            )
                        }

 {
                        this.state.rows.map( row => (

{row.map( cell => (
                                {typeof cell === 'number' ? cell.toFixed( 2 ) : cell}
                            ) )}

                        ) )
                    }

        )
    }
}

ReactDOM.render(
<App />
, document.querySelector( 'body' ) );

You are welcome to contribute directly to my Repo: Fetching API data into a table

My example, right after the onclick="sortTable(0)" has been used, doesn't htow any errors in the console, but it prints the same result. I guess I am not handling correct the {column}	 elements.

Unfortunately I was not able to find related documentation at ReactJs.org

It's doesn't function the onClick event at all, so that I can't debug the sor functionality either.

Any suggestions will be appreciated!


问:
DropQueue mechanism for RX.net
I came across a back pressure issue with RX.net I can't find a solution for. I have an observable real-time stream of log messages.

```<code>var logObservable = /* Observable stream of log messages */
</code>```

Which I want to expose via a TCP interface which serializes the real-time log messages from the logObservable before they are sent over the wire. So I do the following:

```<code>foreach (var message in logObservable.ToEnumerable())
{
   // 1. Serialize message
   // 2. Send it over the wire.
}
</code>```

The problem arises with the .ToEnumerable() if a back pressure scenario happens e.g. if the client on the other end pauses the stream. The problem is that .ToEnumerable() caches the items which result in a lot of memory usage. I'm looking for a mechanism something like a DropQueue which only buffers, let say, the last 10 messages e.g.

```<code>var observableStream = logObservable.DropQueue(10).ToEnumerable();
</code>```

Is this the right way to way to solve this issue? And do you know to implement such a mechanism to avoid possible back pressure issue?

答:
My DropQueue implementation:

```<code>    public static IEnumerable<TSource> ToDropQueue<TSource>(
        this IObservable<TSource> source,
        int queueSize,
        Action backPressureNotification = null,
        CancellationToken token = default(CancellationToken))
    {
        var queue = new BlockingCollection<TSource>(new ConcurrentQueue<TSource>(), queueSize);
        var isBackPressureNotified = false;

        var subscription = source.Subscribe(
            item =>
            {
                var isBackPressure = queue.Count == queue.BoundedCapacity;

                if (isBackPressure)
                {
                    queue.Take(); // Dequeue an item to make space for the next one

                    // Fire back-pressure notification if defined
                    if (!isBackPressureNotified && backPressureNotification != null)
                    {
                        backPressureNotification();
                        isBackPressureNotified = true;
                    }
                }
                else
                {
                    isBackPressureNotified = false;
                }

                queue.Add(item);
            },
            exception => queue.CompleteAdding(),
            () => queue.CompleteAdding());

        token.Register(() => { subscription.Dispose(); });

        using (new CompositeDisposable(subscription, queue))
        {
            foreach (var item in queue.GetConsumingEnumerable())
            {
                yield return item;
            }
        }
    }
</code>```

Title: DropQueue mechanism for RX.net

Body:
I came across a back pressure issue with RX.net I can't find a solution for. I have an observable real-time stream of log messages.

var logObservable = /* Observable stream of log messages */

Which I want to expose via a TCP interface which serializes the real-time log messages from the logObservable before they are sent over the wire. So I do the following:

foreach (var message in logObservable.ToEnumerable())
{
   // 1. Serialize message
   // 2. Send it over the wire.
}

The problem arises with the .ToEnumerable() if a back pressure scenario happens e.g. if the client on the other end pauses the stream. The problem is that .ToEnumerable() caches the items which result in a lot of memory usage. I'm looking for a mechanism something like a DropQueue which only buffers, let say, the last 10 messages e.g.

var observableStream = logObservable.DropQueue(10).ToEnumerable();

Is this the right way to way to solve this issue? And do you know to implement such a mechanism to avoid possible back pressure issue?

Body:
My DropQueue implementation:

    public static IEnumerable<TSource> ToDropQueue<TSource>(
        this IObservable<TSource> source,
        int queueSize,
        Action backPressureNotification = null,
        CancellationToken token = default(CancellationToken))
    {
        var queue = new BlockingCollection<TSource>(new ConcurrentQueue<TSource>(), queueSize);
        var isBackPressureNotified = false;

        var subscription = source.Subscribe(
            item =>
            {
                var isBackPressure = queue.Count == queue.BoundedCapacity;

                if (isBackPressure)
                {
                    queue.Take(); // Dequeue an item to make space for the next one

                    // Fire back-pressure notification if defined
                    if (!isBackPressureNotified && backPressureNotification != null)
                    {
                        backPressureNotification();
                        isBackPressureNotified = true;
                    }
                }
                else
                {
                    isBackPressureNotified = false;
                }

                queue.Add(item);
            },
            exception => queue.CompleteAdding(),
            () => queue.CompleteAdding());

        token.Register(() => { subscription.Dispose(); });

        using (new CompositeDisposable(subscription, queue))
        {
            foreach (var item in queue.GetConsumingEnumerable())
            {
                yield return item;
            }
        }
    }


问:
JavaScript working in Firefox but not other browsers
I am fiddling with this piece of code to try to understand how parts of it work.  Everything seems to be working as expected in Firefox, however the Login button does not work in any other browser.  When I inspect it in Chrome it is saying:

Uncaught SyntaxError: Unexpected token u in JSON at position 0

at JSON.parse ()

at CheckUsername (alt.html:24)

at HTMLInputElement.onclick (alt.html:72)

And before that it was complaining about the CookieVars variable being undefined (I think, I cannot get it to replicate that error again).

I have tried Googling the issue but some of the explanations are way over my head or seem to not be relevant to my situation.

Can someone tell me how come this works in Firefox and not any other browser?  What the issue is and how it can be fixed?

Your assistance is appreciated.

```<code><!DOCTYPE html>
<html>
<head>
  <title></title>
  <meta charset="UTF-8">
</head>
<script>
function NewMember() {
    var CookieVars = {};

    CookieVars.username = document.getElementById("UsersName").value;
    CookieVars.password = document.getElementById("PassWord").value;

    var jsonString = JSON.stringify(CookieVars);

    document.cookie = "MembersDetails=" + jsonString;
    alert("Thank you, you are now registered.");
    ClearTextBoxes();
}

function CheckUsername() {
    var nameValueArray = document.cookie.split("=");
    var CookieVars = JSON.parse(nameValueArray[1]);
    var UsersNameVar = document.getElementById("UsersName").value;

    if (CookieVars.username == UsersNameVar) {
       CheckPassword();
            } else {
                alert("Username not recognised, please register.");
    }
}

function CheckPassword() {
   var nameValueArray = document.cookie.split("=");
   var CookieVars = JSON.parse(nameValueArray[1]);
   var PassWordVar = document.getElementById("PassWord").value;
   if (CookieVars.password == PassWordVar) {
      document.getElementById("message").innerHTML = "You are now logged in, welcome.";
   } else {
      alert("Incorrect Password.");
   }
}

function ClearTextBoxes() {
    document.getElementById("UsersName").value = "";
    document.getElementById("PassWord").value = "";
}

</script>
<body>
  <table border="3">
    <tr>
      <td>
        Username:
      </td>
      <td>
        <input type="text" id="UsersName">
      </td>
    </tr>
    <tr>
      <td>
        Password:
      </td>
      <td>
        <input type="text" id="PassWord">
      </td>
    </tr>
    <tr>
      <td colspan="2">
        <input type="button" value="Register" onclick="NewMember()">
        <input type="button" value="Login" onclick="CheckUsername()">
        <input type="button" value="Clear Boxes" onclick="ClearTextBoxes()">
      </td>
    </tr>
  </table>
    <p id="message"></p>
<img src="" alt="">
</body>
</html>
</code>```

答: Chrome doesn't support cookies for local files (or, like Peter Lyons mentioned, localhost*) unless you start it with the --enable-file-cookies flag. You can read a discussion about it at http://code.google.com/p/chromium/issues/detail?id=535.*Chrome does support cookies if you use the local IP address (127.0.0.1) directly. so in the localhost case, that could be an easier workaround.</p>

Body:
I am fiddling with this piece of code to try to understand how parts of it work.  Everything seems to be working as expected in Firefox, however the Login button does not work in any other browser.  When I inspect it in Chrome it is saying:

Uncaught SyntaxError: Unexpected token u in JSON at position 0

at JSON.parse ()

at CheckUsername (alt.html:24)

at HTMLInputElement.onclick (alt.html:72)

And before that it was complaining about the CookieVars variable being undefined (I think, I cannot get it to replicate that error again).

I have tried Googling the issue but some of the explanations are way over my head or seem to not be relevant to my situation.

Can someone tell me how come this works in Firefox and not any other browser?  What the issue is and how it can be fixed?

Your assistance is appreciated.

<!DOCTYPE html>

  <title></title>
  <meta charset="UTF-8">

        Username:

        <input type="text" id="UsersName">

        Password:

        <input type="text" id="PassWord">

        <input type="button" value="Register" onclick="NewMember()">
        <input type="button" value="Login" onclick="CheckUsername()">
        <input type="button" value="Clear Boxes" onclick="ClearTextBoxes()">


问:
Find a character in a data frame and change adjacent rows
I have a large data frame with 250,000 rows and 35 columns. A simpler sample can be generated by the following code:

```<code>data.frame(a=letters[sample(10,26,replace = T)],b=letters[1:26],c=letters[26:1])
</code>```

I want to search for every occurrence of a chosen character, let's say "h" and then change the cell containing "h" and 5 rows above "h" to NA.

答:
I don't know if it's the most elegant or simple way, but I think it answers your question.

```<code>set.seed(100)
df <-data.frame(a=letters[sample(10,26,replace = T)],b=letters[1:26],c=letters[26:1])

repNa <- function(col, char) {
    col[unique(unlist(sapply(which(col==char),
                             FUN=function(x) rep(ifelse(x>4,(x-4),1):x))
                      ))
        ] <- NA
    return(col)
}

df
as.data.frame(apply(df, MARGIN=2, function(x) repNa(x, "h")))
</code>```

The repNa function is not very complex, the most important part is unique(unlist(sapply(which(col==char),FUN=function(x) rep(ifelse(x>4,(x-4),1):x)))), with which build a vector with the positions to replace in a certain column.

Input:

```<code>   a b c
1  d a z
2  c b y
3  f c x
4  a d w
5  e e v
6  e f u
7  i g t
8  d h s
9  f i r
10 b j q
11 g k p
12 i l o
13 c m n
14 d n m
15 h o l
16 g p k
17 c q j
18 d r i
19 d s h
20 g t g
21 f u f
22 h v e
23 f w d
24 h x c
25 e y b
26 b z a
</code>```

Output:

```<code>      a    b    c
1     d    a    z
2     c    b    y
3     f    c    x
4     a <NA>    w
5     e <NA>    v
6     e <NA>    u
7     i <NA>    t
8     d <NA>    s
9     f    i    r
10    b    j    q
11 <NA>    k    p
12 <NA>    l    o
13 <NA>    m    n
14 <NA>    n    m
15 <NA>    o <NA>
16    g    p <NA>
17    c    q <NA>
18 <NA>    r <NA>
19 <NA>    s <NA>
20 <NA>    t    g
21 <NA>    u    f
22 <NA>    v    e
23 <NA>    w    d
24 <NA>    x    c
25    e    y    b
26    b    z    a
</code>```

Body:
I have a large data frame with 250,000 rows and 35 columns. A simpler sample can be generated by the following code:

data.frame(a=letters[sample(10,26,replace = T)],b=letters[1:26],c=letters[26:1])

I want to search for every occurrence of a chosen character, let's say "h" and then change the cell containing "h" and 5 rows above "h" to NA.

Body:
I don't know if it's the most elegant or simple way, but I think it answers your question.

set.seed(100)
df <-data.frame(a=letters[sample(10,26,replace = T)],b=letters[1:26],c=letters[26:1])

repNa <- function(col, char) {
    col[unique(unlist(sapply(which(col==char),
                             FUN=function(x) rep(ifelse(x>4,(x-4),1):x))
                      ))
        ] <- NA
    return(col)
}

df
as.data.frame(apply(df, MARGIN=2, function(x) repNa(x, "h")))

The repNa function is not very complex, the most important part is unique(unlist(sapply(which(col==char),FUN=function(x) rep(ifelse(x>4,(x-4),1):x)))), with which build a vector with the positions to replace in a certain column.

Input:

   a b c
1  d a z
2  c b y
3  f c x
4  a d w
5  e e v
6  e f u
7  i g t
8  d h s
9  f i r
10 b j q
11 g k p
12 i l o
13 c m n
14 d n m
15 h o l
16 g p k
17 c q j
18 d r i
19 d s h
20 g t g
21 f u f
22 h v e
23 f w d
24 h x c
25 e y b
26 b z a

Output:

      a    b    c
1     d    a    z
2     c    b    y
3     f    c    x
4     a <NA>    w
5     e <NA>    v
6     e <NA>    u
7     i <NA>    t
8     d <NA>    s
9     f    i    r
10    b    j    q
11 <NA>    k    p
12 <NA>    l    o
13 <NA>    m    n
14 <NA>    n    m
15 <NA>    o <NA>
16    g    p <NA>
17    c    q <NA>
18 <NA>    r <NA>
19 <NA>    s <NA>
20 <NA>    t    g
21 <NA>    u    f
22 <NA>    v    e
23 <NA>    w    d
24 <NA>    x    c
25    e    y    b
26    b    z    a


问:
failing to load ROracle: unable to load shared object ROracle.so: libclntsh.so.11.1 No such file or directory
So I can't load ROracle. I am indeed very new to this so any information is appreciated and any info regarding what further information to give would be helpful as well.

```<code>> library(ROracle)
Error in dyn.load(file, DLLpath = DLLpath, ...) :
  unable to load shared object '~/R/x86_64-pc-linux-gnu-library/2.14/ROracle/libs/ROracle.so':
  libclntsh.so.11.1: cannot open shared object file: No such file or directory
Error: package/namespace load failed for ‘ROracle’
</code>```

ROracle.so is exactly where it says it is. libclntsh.so.11.1 can be found at /usr/lib/oracle/11.2/client64/lib/libclntsh.so.11.1. This is the result of .libPaths:

```<code>> .libPaths()
[1] "/home/nguiller/R/x86_64-pc-linux-gnu-library/2.14" "/usr/local/lib/R/site-library"                     "/usr/lib/R/site-library"
[4] "/usr/lib/R/library"                                "/usr/lib/rstudio/R/library"
</code>```

My .Renviron file

```<code>LD_LIBRARY_PATH="/usr/lib/oracle/11.2/client64/lib:/home/nguiller/Downloads/instantclient_11_2"
ORACLE_HOME="/usr/lib/oracle/11.2/client64/:/home/nguiller/Downloads/instantclient_11_2"
OCI_LIB="/usr/lib/oracle/11.2/client64/lib"
</code>```

I had a lot of trouble installing ROracle to begin with due to OCI libraries but it eventually worked with R CMD INSTALL --configure-ags='--with-oci-lib=/usr/lib/oracle/11.2/client64/lib --with-oci-inc=/usr/include/oracle/11.2/client64' ROracle_1.1-8.tar.gz

Let me know how I can help.

答:
Set this in /etc/rstudio/rserver.conf

```<code>rsession-ld-library-
path=/usr/lib64/R/lib:/home/oracle/app/oracle/product/12.1.0/client_1/lib
</code>```

Then restart Rserver

```<code>sudo rstudio-server stop
sudo rstudio-server start
</code>```

This helped me.

Body:
So I can't load ROracle. I am indeed very new to this so any information is appreciated and any info regarding what further information to give would be helpful as well.

> library(ROracle)
Error in dyn.load(file, DLLpath = DLLpath, ...) :
  unable to load shared object '~/R/x86_64-pc-linux-gnu-library/2.14/ROracle/libs/ROracle.so':
  libclntsh.so.11.1: cannot open shared object file: No such file or directory
Error: package/namespace load failed for ‘ROracle’

ROracle.so is exactly where it says it is. libclntsh.so.11.1 can be found at /usr/lib/oracle/11.2/client64/lib/libclntsh.so.11.1. This is the result of .libPaths:

> .libPaths()
[1] "/home/nguiller/R/x86_64-pc-linux-gnu-library/2.14" "/usr/local/lib/R/site-library"                     "/usr/lib/R/site-library"
[4] "/usr/lib/R/library"                                "/usr/lib/rstudio/R/library"

My .Renviron file

LD_LIBRARY_PATH="/usr/lib/oracle/11.2/client64/lib:/home/nguiller/Downloads/instantclient_11_2"
ORACLE_HOME="/usr/lib/oracle/11.2/client64/:/home/nguiller/Downloads/instantclient_11_2"
OCI_LIB="/usr/lib/oracle/11.2/client64/lib"

I had a lot of trouble installing ROracle to begin with due to OCI libraries but it eventually worked with R CMD INSTALL --configure-ags='--with-oci-lib=/usr/lib/oracle/11.2/client64/lib --with-oci-inc=/usr/include/oracle/11.2/client64' ROracle_1.1-8.tar.gz

Let me know how I can help.

Body:
Set this in /etc/rstudio/rserver.conf

rsession-ld-library-
path=/usr/lib64/R/lib:/home/oracle/app/oracle/product/12.1.0/client_1/lib

Then restart Rserver

sudo rstudio-server stop
sudo rstudio-server start

This helped me.


问:
How to mock the webservice response of RestTemplate?
I'd like to write an integration test on my whole application, and want to mock only one specific method: the RestTemplate that I use to send some data to an external webservice and receive the response.

I want to read the response instead from a local file (to mock and mimic the external server response, so it is always the same).

My local file should just contain thejson/xml response that in production the external webserver would respond with.

Question: how can I mock an external xml response?

```<code>@Service
public class MyBusinessClient {
      @Autowired
      private RestTemplate template;

      public ResponseEntity<ProductsResponse> send(Req req) {
               //sends request to external webservice api
               return template.postForEntity(host, req, ProductsResponse.class);
      }
}

@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
public class Test {

   @Test
   public void test() {
        String xml = loadFromFile("productsResponse.xml");
        //TODO how can I tell RestTemplate to assume that the external webserver responded with the value in xml variable?
   }
}
</code>```

答:
You can implement mocking framework like Mockito for this:

So, in your resttemplate mock you would have:

```<code>when(restTemplate.postForEntity(...))
    .thenAnswer(answer(401));
</code>```

and answer implementation something like:

```<code>private Answer answer(int httpStatus) {
    return (invocation) -> {
        if (httpStatus >= 400) {
            throw new RestClientException(...);
        }
        return <whatever>;
    };
}
</code>```

For further reading follow Mockito

Body:
I'd like to write an integration test on my whole application, and want to mock only one specific method: the RestTemplate that I use to send some data to an external webservice and receive the response.

I want to read the response instead from a local file (to mock and mimic the external server response, so it is always the same).

My local file should just contain thejson/xml response that in production the external webserver would respond with.

Question: how can I mock an external xml response?

@Service
public class MyBusinessClient {
      @Autowired
      private RestTemplate template;

      public ResponseEntity<ProductsResponse> send(Req req) {
               //sends request to external webservice api
               return template.postForEntity(host, req, ProductsResponse.class);
      }
}

@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
public class Test {

   @Test
   public void test() {
        String xml = loadFromFile("productsResponse.xml");
        //TODO how can I tell RestTemplate to assume that the external webserver responded with the value in xml variable?
   }
}

Body:
You can implement mocking framework like Mockito for this:

So, in your resttemplate mock you would have:

when(restTemplate.postForEntity(...))
    .thenAnswer(answer(401));

and answer implementation something like:

private Answer answer(int httpStatus) {
    return (invocation) -> {
        if (httpStatus >= 400) {
            throw new RestClientException(...);
        }
        return <whatever>;
    };
}

For further reading follow Mockito


问:
ngStyle with 'checked' state in ngFor loop
I have a list of checkboxes that are asign to different departments(every department has it's own color) when box is unchecked only a border is in the color of department when checked backgroud is changed to the asign color

box-shadow works how it should but can not make background to change (stayes blue-ish),
this is my code at the moment:

```<code>  <label class="custom-control custom-checkbox" *ngFor="let department of departments">
        <input type="checkbox" class="custom-control-input" [ngStyle]="{'background-color':checked===true? department.color:'white'}">
        <span class="custom-control-indicator" [ngStyle]="{'box-shadow': '0 0 1px 1px' + department.color}" >  </span>
        <span class="custom-control-description text-capitalize">{{department.id}}</span>
      </label>
</code>```

答:
well, I found a solution without using :before or :after which seams like a less of a hassle (in case someone searching for alternative solution):

```<code> <label class="custom-control custom-checkbox" *ngFor="let department of departments">
        <input type="checkbox" class="custom-control-input" (click)=gotChecked($event,customBox,department.color)>

        <span class="custom-control-indicator" [ngStyle]="{'box-shadow': '0 0 1px 1px' + department.color}" >  </span>
        <span class="custom-control-indicator" #customBox></span>
        <span class="custom-control-description text-capitalize">{{department.id}}</span>
      </label>
</code>```

and:

```<code>gotChecked($event: Event, customBox: HTMLSpanElement, color: string) {
let isChecked = (<HTMLInputElement>event.target).checked
console.log(isChecked)
if (isChecked) {
  customBox.style.backgroundColor = color
} else {
  customBox.style.backgroundColor = 'transparent'
}
</code>```

}

Body:
I have a list of checkboxes that are asign to different departments(every department has it's own color) when box is unchecked only a border is in the color of department when checked backgroud is changed to the asign color

box-shadow works how it should but can not make background to change (stayes blue-ish),
this is my code at the moment:

        <input type="checkbox" class="custom-control-input" [ngStyle]="{'background-color':checked===true? department.color:'white'}">

        {{department.id}}

Body:
well, I found a solution without using :before or :after which seams like a less of a hassle (in case someone searching for alternative solution):

 <label class="custom-control custom-checkbox" *ngFor="let department of departments">
        <input type="checkbox" class="custom-control-input" (click)=gotChecked($event,customBox,department.color)>

        <span class="custom-control-indicator" [ngStyle]="{'box-shadow': '0 0 1px 1px' + department.color}" >  </span>
        <span class="custom-control-indicator" #customBox></span>
        <span class="custom-control-description text-capitalize">{{department.id}}</span>
      </label>

and:

gotChecked($event: Event, customBox: HTMLSpanElement, color: string) {
let isChecked = (<HTMLInputElement>event.target).checked
console.log(isChecked)
if (isChecked) {
  customBox.style.backgroundColor = color
} else {
  customBox.style.backgroundColor = 'transparent'
}

}


问:
What are the differences between CAS and Keycloak?
What are the differences between CAS (Central Authentication Service) and Keycloak (Identity and Access Management)?</p>

答: CAS doesn't support OAuth2 but Keycloak does. It is a big difference.</p>


问:
How to tear down Selenium (3.8) and close IE browser window?
I simply cannot get Selenium to clean up after navigating to a page. (Without the Navigate().GoToURL(), it tears down nicely.) I understand the supposed difference between Close(), Quit(), and Dispose(). I've tried every combination I could think of. I must be missing something. If I have to shut them down myself --if that's the solution... I honestly have no clue, but that's fine. I would just like to know if I am missing something in terms of using Selenium. Any help greatly appreciated. </p>

```<code>// no iexplore windows open

IWebDriver f = new InternetExplorerDriver();

f.Navigate().GoToUrl("http://abcdxpq.com");

f.Close();
f.Quit();
f.Dispose();

// iexplore window left open (http://abcdxpq.com)
</code>```

答:
Figured out what I was doing wrong, or at least what works --given that I believe Quit() is supposed to close all? Anyhow, assuming Quit doesn't quite close all the windows, I still assumed that instantiating and then navigating would only create one window to shut down... it obviously creates 2 :) My bad. This shuts everything down. But maybe there is a problem with the driver, if Quit() is supposed to do the trick?</p>

```<code>IWebDriver f = new InternetExplorerDriver();

f.Close(); // <- this is what I added. this works for me. nothing left open.

f.Navigate().GoToUrl("http://abcdxpq.com");

f.Quit();
</code>```

Body:
I simply cannot get Selenium to clean up after navigating to a page. (Without the Navigate().GoToURL(), it tears down nicely.) I understand the supposed difference between Close(), Quit(), and Dispose(). I've tried every combination I could think of. I must be missing something. If I have to shut them down myself --if that's the solution... I honestly have no clue, but that's fine. I would just like to know if I am missing something in terms of using Selenium. Any help greatly appreciated.

// no iexplore windows open

IWebDriver f = new InternetExplorerDriver();

f.Navigate().GoToUrl("http://abcdxpq.com");

f.Close();
f.Quit();
f.Dispose();

// iexplore window left open (http://abcdxpq.com)

Body:
Figured out what I was doing wrong, or at least what works --given that I believe Quit() is supposed to close all? Anyhow, assuming Quit doesn't quite close all the windows, I still assumed that instantiating and then navigating would only create one window to shut down... it obviously creates 2 :) My bad. This shuts everything down. But maybe there is a problem with the driver, if Quit() is supposed to do the trick?

IWebDriver f = new InternetExplorerDriver();

f.Close(); // <- this is what I added. this works for me. nothing left open.

f.Navigate().GoToUrl("http://abcdxpq.com");

f.Quit();


问:
Angular 2: Rendering angular html components from webservice
I am looking for how to add html which is a return of the web service, in angular. The problem is that the angular directives do not rendered. here is my source code

```<code>//tohtml.directive.ts

import { Directive, ElementRef, OnInit } from '@angular/core';
@Directive({
  selector: '[appToHtml]'
})
export class ToHtmlDirective {
constructor( private el: ElementRef) {}

tohtml() {
  //it is assumed that this is the return of the webservice
  this.el.nativeElement.innerHTML = '<a
  [routerLink]="/link/to/page">helpful!
   </a>';
  }
}
</code>```

Code for component.html

```<code><div id="wrapper">

<h1 appToHtml>
  Hello World!
</h1>
</div>
</code>```

the code works, but the rendering of the [routerLink] does not work, pleaseee hellppp !!!

答:
With the latest angular version for me only this module works fine: https://www.npmjs.com/package/ngx-dynamic-template
v2.1.24 for angular4, v.2.3.0 is for angular5</p>

Body:
I am looking for how to add html which is a return of the web service, in angular. The problem is that the angular directives do not rendered. here is my source code

//tohtml.directive.ts

import { Directive, ElementRef, OnInit } from '@angular/core';
@Directive({
  selector: '[appToHtml]'
})
export class ToHtmlDirective {
constructor( private el: ElementRef) {}

tohtml() {
  //it is assumed that this is the return of the webservice
  this.el.nativeElement.innerHTML = 'helpful!
   ';
  }
}

Code for component.html

  Hello World!

the code works, but the rendering of the [routerLink] does not work, pleaseee hellppp !!!


问:
Replace and Rearrange string in javascript
I have an input string

```<code>this.name in ['Sachin','Rahul','Anil']
</code>```

If I find " in " in the above string, I need to replace this as below

```<code>['Sachin','Rahul','Anil'].indexOf(this.name) > -1
</code>```

Similarly, If I have an input string containing not in

```<code>this.name not in ['Sachin','Rahul','Anil']
</code>```

If " not in " is found, I need to replace it as

```<code>['Sachin','Rahul','Anil'].indexOf(this.name)  < 0
</code>```

Is it possible to achieve this in javascript?

答:
I understood you want to transpile keyword in into something that you wrote and add a not keyword which will be corresponding to that expression.

So... you can't achieve it in pure browser js without using some string parsing technique.
But you can go on with transpilers (which can be programmable in js), for example babel. In google you want to search phase "transpiling custom js".
Some article using babel

Body:
I have an input string

this.name in ['Sachin','Rahul','Anil']

If I find " in " in the above string, I need to replace this as below

['Sachin','Rahul','Anil'].indexOf(this.name) > -1

Similarly, If I have an input string containing not in

this.name not in ['Sachin','Rahul','Anil']

If " not in " is found, I need to replace it as

['Sachin','Rahul','Anil'].indexOf(this.name)  < 0

Is it possible to achieve this in javascript?


问:
Making extensible Grails applications
Is there a way to make a Grails application extensible without giving out the source code to the application? The idea being that I want end users to be able to add functionality through custom made modules.

I found this, but near the bottom it says:

It is still unclear to me how an extension could add a plugin it needs or modify the Spring or ApplicationContext on the fly without a restart. The Grails roadmap suggests that there would be a hot-deployable plugin infrastructure in place soon, which might solve this question.

The closest thing I found on the Grails Roadmap is this (as a "theme" for Grails 2.0):

Take modular development with plugins to the next level by allowing modular deployment with OSGi

Would this be what I am looking for?

答: Check out the Binary Artifacts plugin, which allows you to create artifacts without distributing the source code. If you create a combination of interfaces, extension points, and documentation then you should be able to let others use and extend your functionality without distributing your code.</p>

ContentLicense: CC BY-SA 2.5

Title: Making extensible Grails applications


问:
Add send date to HTML mail in TYPO3 powermail
Is it possible to add the send date to the HTML mail which is sent?

Thanks in Advance

答:
It is not possible to use the mail variable like {mail.crdate} in RTE or in HTML-Template because the mail object is not yet persisted (saved) at the moment when the mails are sent.
Using a format.date ViewHelper as a Workarround should help: {f:format.date(date:'now', format:'%d.%m.%Y %H:%M')}


问:
mkdir x levels down
I have a folder for contracts on multiple states and each state folder has multiple contracts:

```<code>D:\Workspace\Contracts\State1\Contract1_number_date
D:\Workspace\Contracts\State1\Contract2_number_date
D:\Workspace\Contracts\State2\Contract1_number_date`
etc...
</code>```

I need to make 3 folders for each contract:

```<code>D:\Workspace\Contracts\State1\Contract1_number_date\folder1
D:\Workspace\Contracts\State1\Contract1_number_date\folder2
D:\Workspace\Contracts\State1\Contract1_number_date\folder3
D:\Workspace\Contracts\State1\Contract2_number_date\folder1
D:\Workspace\Contracts\State1\Contract2_number_date\folder2
D:\Workspace\Contracts\State1\Contract2_number_date\folder3
D:\Workspace\Contracts\State2\Contract1_number_date\folder1
D:\Workspace\Contracts\State2\Contract1_number_date\folder2
D:\Workspace\Contracts\State2\Contract1_number_date\folder3
</code>```

I found out that \..\ goes one level up, so mkdir D:\Workspace\Contracts\..\folder1 makes D:\Workspace\folder1, but I have no idea how to go 1 or 10 folders down.

答:
Here's some code using For loops to achieve your goal:

@Echo Off
Set "BaseDir=%~1"
Set "NumStates=%~2"
Set "NumContracts=%~3"
Set "NumFolders=%~4"

If Not Exist "%BaseDir%\" Exit/B
For %%A In (NumStates NumContracts NumFolders) Do If Not Defined %%A Exit/B

If /I Not "%CD%"=="%BaseDir%" CD /D "%BaseDir%"

For /L %%A In (1,1,%NumStates%) Do For /L %%B In (1,1,%NumContracts%
) Do For /L %%C In (1,1,%NumFolders%
) Do If Not Exist "State%%A\Contract%%B_number_date\folder%%C\" (
    MD "State%%A\Contract%%B_number_date\folder%%C")
```

<p>You would run your script, named <code>MakeDirs.cmd</code>, from the command line like this:</p>

<pre class="lang-bat prettyprint-override"><code>"MakeDirs.cmd" "D:\Workspace\Contracts" 17 8 3
</code>```

The above should create 3 directories for 8 Contracts and 17 States inside D:\Workspace\Contracts.

Title: mkdir x levels down

Body:
I have a folder for contracts on multiple states and each state folder has multiple contracts:

D:\Workspace\Contracts\State1\Contract1_number_date
D:\Workspace\Contracts\State1\Contract2_number_date
D:\Workspace\Contracts\State2\Contract1_number_date`
etc...

I need to make 3 folders for each contract:

D:\Workspace\Contracts\State1\Contract1_number_date\folder1
D:\Workspace\Contracts\State1\Contract1_number_date\folder2
D:\Workspace\Contracts\State1\Contract1_number_date\folder3
D:\Workspace\Contracts\State1\Contract2_number_date\folder1
D:\Workspace\Contracts\State1\Contract2_number_date\folder2
D:\Workspace\Contracts\State1\Contract2_number_date\folder3
D:\Workspace\Contracts\State2\Contract1_number_date\folder1
D:\Workspace\Contracts\State2\Contract1_number_date\folder2
D:\Workspace\Contracts\State2\Contract1_number_date\folder3

I found out that \..\ goes one level up, so mkdir D:\Workspace\Contracts\..\folder1 makes D:\Workspace\folder1, but I have no idea how to go 1 or 10 folders down.

Body:
Here's some code using For loops to achieve your goal:

@Echo Off
Set "BaseDir=%~1"
Set "NumStates=%~2"
Set "NumContracts=%~3"
Set "NumFolders=%~4"

If Not Exist "%BaseDir%\" Exit/B
For %%A In (NumStates NumContracts NumFolders) Do If Not Defined %%A Exit/B

If /I Not "%CD%"=="%BaseDir%" CD /D "%BaseDir%"

For /L %%A In (1,1,%NumStates%) Do For /L %%B In (1,1,%NumContracts%
) Do For /L %%C In (1,1,%NumFolders%
) Do If Not Exist "State%%A\Contract%%B_number_date\folder%%C\" (
    MD "State%%A\Contract%%B_number_date\folder%%C")

You would run your script, named MakeDirs.cmd, from the command line like this:

"MakeDirs.cmd" "D:\Workspace\Contracts" 17 8 3

The above should create 3 directories for 8 Contracts and 17 States inside D:\Workspace\Contracts.


问:
counting unique factors in r
I would like to know the number of unique dams which gave birth on each of the birth dates recorded. My data frame is similar to this one:

```<code>dam <- c("2A11","2A11","2A12","2A12","2A12","4D23","4D23","1X23")
bdate <- c("2009-10-01","2009-10-01","2009-10-01","2009-10-01",
           "2009-10-01","2009-10-03","2009-10-03","2009-10-03")
mydf <- data.frame(dam,bdate)
mydf
#    dam      bdate
# 1 2A11 2009-10-01
# 2 2A11 2009-10-01
# 3 2A12 2009-10-01
# 4 2A12 2009-10-01
# 5 2A12 2009-10-01
# 6 4D23 2009-10-03
# 7 4D23 2009-10-03
# 8 1X23 2009-10-03
</code>```

I used aggregate(dam ~ bdate, data=mydf, FUN=length) but it counts all the dams that gave birth on a particular date

```<code>bdate dam
1 2009-10-01   5
2 2009-10-03   3
</code>```

Instead, I need to have something like this:

```<code>mydf2
  bdate      dam
1 2009-10-01  2
2 2009-10-03  2
</code>```

Your help is very much appreciated!

答:
In dplyr you can use n_distinct :

```<code>library(tidyverse)
mydf %>%
  group_by(bdate) %>%
  summarize(dam = n_distinct(dam))
</code>```

Title: counting unique factors in r

Body:
I would like to know the number of unique dams which gave birth on each of the birth dates recorded. My data frame is similar to this one:

dam <- c("2A11","2A11","2A12","2A12","2A12","4D23","4D23","1X23")
bdate <- c("2009-10-01","2009-10-01","2009-10-01","2009-10-01",
           "2009-10-01","2009-10-03","2009-10-03","2009-10-03")
mydf <- data.frame(dam,bdate)
mydf
#    dam      bdate
# 1 2A11 2009-10-01
# 2 2A11 2009-10-01
# 3 2A12 2009-10-01
# 4 2A12 2009-10-01
# 5 2A12 2009-10-01
# 6 4D23 2009-10-03
# 7 4D23 2009-10-03
# 8 1X23 2009-10-03

I used aggregate(dam ~ bdate, data=mydf, FUN=length) but it counts all the dams that gave birth on a particular date

bdate dam
1 2009-10-01   5
2 2009-10-03   3

Instead, I need to have something like this:

mydf2
  bdate      dam
1 2009-10-01  2
2 2009-10-03  2

Your help is very much appreciated!

Body:
In dplyr you can use n_distinct :

library(tidyverse)
mydf %>%
  group_by(bdate) %>%
  summarize(dam = n_distinct(dam))


问:
Trigger for progress bar 100%
I build a small App for myself to save and display some data in a GUI on my iPhone.

To see the sync status of the data I've got a progress bar:

```<code>class ViewController: UIViewController, UICollectionViewDataSource, UICollectionViewDelegate {
    ...
    @IBOutlet weak var syncHealthProgress: UIProgressView!
    ...
}
</code>```

The data is synced with url requests encapsulated in a separate class from which the progress bar (call-by-reference parameter) is updated:

```<code> class ApiService {
     ...
     // function to sync some data, called multiple times from UIViewController
     class func syncQlData(progressBar: UIProgressView) -> Void {
         ...
         let task = URLSession.shared.dataTask(with: request as URLRequest) {
             data, response, error in

             // update progress bar
             DispatchQueue.main.async() {
                 // increment progress bar
                 progressBar.progress += (1 / Float(ViewController.progressBarSteps))
             }
         }
     }
 }
</code>```

Problem: The API calls are asynchronous. But when the sync is finished I what to do some task like updating the data in GUI and save the synced data to local storage.

I tried to use Key-Value-Observing on the syncHealthProgress but it doesn't take effekt on the .progress property.

Is there any way to trigger an action from within the UIViewController when the progress bar is on 100%?

答:
Use delegate for that.

In ApiService above class implement

```<code>protocol ApiServiceDelegate: class {
   func updateProgressBar()
}
</code>```

and add a property inside class

```<code>weak var apiServiceDelegate: ApiServiceDelegate!
</code>```

in your syncQLData call the updateProgressBar() like

```<code>let task = URLSession.shared.dataTask(with: request as URLRequest) {
         data, response, error in

         // update progress bar
         self. apiServiceDelegate.updateProgressBar()

}
</code>```

In your ViewController (where the progress bar is) add the protocol like

```<code>class ViewController: UIViewController, UICollectionViewDataSource, UICollectionViewDelegate, ApiServiceDelegate
</code>```

Where you instantiating your ApiService you have to set the delegate.

I think you do something like

```<code>let apiService = ApiService()
apiService.syncQlData(syncHealthProgress)
</code>```

you have to change that to

```<code>let apiService = ApiService()
apiService.apiServiceDelegate = self
apiService.syncQlData(syncHealthProgress)
</code>```

Now you can implement the function of the delegate in ViewController like

```<code>func updateProgressBar() {
   syncHealthProgress.progress += (1 / Float(progressBarSteps))
}
</code>```

Title: Trigger for progress bar 100%

Body:
I build a small App for myself to save and display some data in a GUI on my iPhone.

To see the sync status of the data I've got a progress bar:

class ViewController: UIViewController, UICollectionViewDataSource, UICollectionViewDelegate {
    ...
    @IBOutlet weak var syncHealthProgress: UIProgressView!
    ...
}

The data is synced with url requests encapsulated in a separate class from which the progress bar (call-by-reference parameter) is updated:

 class ApiService {
     ...
     // function to sync some data, called multiple times from UIViewController
     class func syncQlData(progressBar: UIProgressView) -> Void {
         ...
         let task = URLSession.shared.dataTask(with: request as URLRequest) {
             data, response, error in

             // update progress bar
             DispatchQueue.main.async() {
                 // increment progress bar
                 progressBar.progress += (1 / Float(ViewController.progressBarSteps))
             }
         }
     }
 }

Problem: The API calls are asynchronous. But when the sync is finished I what to do some task like updating the data in GUI and save the synced data to local storage.

I tried to use Key-Value-Observing on the syncHealthProgress but it doesn't take effekt on the .progress property.

Is there any way to trigger an action from within the UIViewController when the progress bar is on 100%?

Body:
Use delegate for that.

In ApiService above class implement

protocol ApiServiceDelegate: class {
   func updateProgressBar()
}

and add a property inside class

weak var apiServiceDelegate: ApiServiceDelegate!

in your syncQLData call the updateProgressBar() like

let task = URLSession.shared.dataTask(with: request as URLRequest) {
         data, response, error in

         // update progress bar
         self. apiServiceDelegate.updateProgressBar()

}

In your ViewController (where the progress bar is) add the protocol like

class ViewController: UIViewController, UICollectionViewDataSource, UICollectionViewDelegate, ApiServiceDelegate

Where you instantiating your ApiService you have to set the delegate.

I think you do something like

let apiService = ApiService()
apiService.syncQlData(syncHealthProgress)

you have to change that to

let apiService = ApiService()
apiService.apiServiceDelegate = self
apiService.syncQlData(syncHealthProgress)

Now you can implement the function of the delegate in ViewController like

func updateProgressBar() {
   syncHealthProgress.progress += (1 / Float(progressBarSteps))
}


问:
ViewController unresponsive for 2-3 seconds after being pushed
What could cause a viewController to be unresponsive for 2-3 seconds after being pushed? The tableView doesn't scroll, the searchbar can't be tapped.

There's no heavy code on viewDidLoad/viewWillAppear. No complex layouts. Just a simple tableView (even non populating in makes no difference).

答: Under the Runtime API Checking section, ensure that the Main Thread Checker is enabled to see if you are executing ui methods in a non-UI thread


问:
Rails 3, updated_at is 1 day ahead?
For some reason when updating a record, updated_at is getting updated as 2011-01-23, even though Date.today is returning 2011-01-22. Why are these different? Is there a way to set them to be the same?

Thanks!

答: Did you set your time zone in the config/environment.rb file?</p>

Title: Rails 3, updated_at is 1 day ahead?


问:
com.google.gson.internal.LinkedTreeMap cannot be cast to my class
I have some problems with getting my object from a JSON string.

I got the class Product

```<code>public class Product {
    private String mBarcode;
    private String mName;
    private String mPrice;

    public Product(String barcode, String name, String price) {
        mBarcode = barcode;
        mName = name;
        mPrice = price;
    }

    public int getBarcode() {
        return Integer.parseInt(mBarcode);
    }

    public String getName() {
        return mName;
    }

    public double getPrice() {
        return Double.parseDouble(mPrice);
    }
}
</code>```

From my server I get an ArrayList<Product> in JSON String representation. For example:

```<code>[{"mBarcode":"123","mName":"Apfel","mPrice":"2.7"},
{"mBarcode":"456","mName":"Pfirsich","mPrice":"1.1111"},
{"mBarcode":"89325982","mName":"Birne","mPrice":"1.5555"}]
</code>```

This String is generated like this:

```<code>public static <T> String arrayToString(ArrayList<T> list) {
    Gson g = new Gson();
    return g.toJson(list);
}
</code>```

To get my Object back I use this function:

```<code>public static <T> ArrayList<T> stringToArray(String s) {
    Gson g = new Gson();
    Type listType = new TypeToken<ArrayList<T>>(){}.getType();
    ArrayList<T> list = g.fromJson(s, listType);
    return list;
}
</code>```

But when calling

```<code>String name = Util.stringToArray(message).get(i).getName();
</code>```

I get the error
com.google.gson.internal.LinkedTreeMap cannot be cast to object.Product

What am I doing wrong? It looks like it created a List of LinkedTreeMaps but how do i convert those into my Product Object?

答:
To add to the answers already mentioned here, if you have a generic class that handles, say, HTTP calls, it maybe useful to pass Class<T> as part of the constructor.

To give a little more detail, this happens because Java cannot infer the Class<T> during runtime with just T. It needs the actual solid class to make the determination.

So, if you have something like this, like I do:

```<code>class HttpEndpoint<T> implements IEndpoint<T>
</code>```

you can allow the inheriting code to also send the class<T>, since at that point is it clear what T is.

```<code>public HttpEndpoint(String baseurl, String route, Class<T> cls) {
    this.baseurl = baseurl;
    this.route = route;
    this.cls = cls;
}
</code>```

inheriting class:

```<code>public class Players extends HttpEndpoint<Player> {

    public Players() {
        super("http://127.0.0.1:8080", "/players",  Player.class);
    }
}
</code>```

while not entirely a clean solution, it does keep the code packaged up and you don't have to Class<T> between methods.

Body:
I have some problems with getting my object from a JSON string.

I got the class Product

public class Product {
    private String mBarcode;
    private String mName;
    private String mPrice;

    public Product(String barcode, String name, String price) {
        mBarcode = barcode;
        mName = name;
        mPrice = price;
    }

    public int getBarcode() {
        return Integer.parseInt(mBarcode);
    }

    public String getName() {
        return mName;
    }

    public double getPrice() {
        return Double.parseDouble(mPrice);
    }
}

From my server I get an ArrayList<Product> in JSON String representation. For example:

[{"mBarcode":"123","mName":"Apfel","mPrice":"2.7"},
{"mBarcode":"456","mName":"Pfirsich","mPrice":"1.1111"},
{"mBarcode":"89325982","mName":"Birne","mPrice":"1.5555"}]

This String is generated like this:

public static <T> String arrayToString(ArrayList<T> list) {
    Gson g = new Gson();
    return g.toJson(list);
}

To get my Object back I use this function:

public static <T> ArrayList<T> stringToArray(String s) {
    Gson g = new Gson();
    Type listType = new TypeToken<ArrayList<T>>(){}.getType();
    ArrayList<T> list = g.fromJson(s, listType);
    return list;
}

But when calling

String name = Util.stringToArray(message).get(i).getName();

I get the error
com.google.gson.internal.LinkedTreeMap cannot be cast to object.Product

What am I doing wrong? It looks like it created a List of LinkedTreeMaps but how do i convert those into my Product Object?

Body:
To add to the answers already mentioned here, if you have a generic class that handles, say, HTTP calls, it maybe useful to pass Class<T> as part of the constructor.

To give a little more detail, this happens because Java cannot infer the Class<T> during runtime with just T. It needs the actual solid class to make the determination.

So, if you have something like this, like I do:

class HttpEndpoint<T> implements IEndpoint<T>

you can allow the inheriting code to also send the class<T>, since at that point is it clear what T is.

public HttpEndpoint(String baseurl, String route, Class<T> cls) {
    this.baseurl = baseurl;
    this.route = route;
    this.cls = cls;
}

inheriting class:

public class Players extends HttpEndpoint<Player> {

    public Players() {
        super("http://127.0.0.1:8080", "/players",  Player.class);
    }
}

while not entirely a clean solution, it does keep the code packaged up and you don't have to Class<T> between methods.


问:
How can I display Arabic data in Crystal Reports?
I am using Crystal Reports 10. The reports are obtaining data from an Oracle 10G database. We have some data in Arabic. When I try to display the Arabic data it is showing as ?.

Any ideas on what I can do to display this correctly?

答:
Make sure you have Arabic support installed in Windows.

Add the correct LANG and NLS_LANG to your registry (for me it's ARABIC__QATAR.AR8MSWIN1256)

LastEditorDisplayName: Omar Kooheji

OwnerDisplayName: Osama ALASSIRY


问:
Using Higher order functions instead of two loops
I wanted to use higher order functions such as Map, Filter, Reduce.

My problem is I have an array which is not organised so I had to perform a loop operation to get the result I wanted. An array has two fields one is _id and totalCount which is an array the length will be minimum 0 to 3.

The totalCount each iteration consists of two fields one is orderstatus and another is total I want to perform a normal if else condition if orderstatus is "Merchant" or "driver" or "user" I want to take that iterated total and store it in my array like MerchantCount.

This is my code:

```<code>var arr = [{
   _id: "2017-12-08",
   totalcount: [{
     orderstatus: "MERCHANT",
     total: 1
   }]
 },
 {
   _id: "2017-12-02",
   totalcount: [{
     orderstatus: "USER",
     total: 2
   }]
 },
 {
   _id: "2017-12-06",
   totalcount: [{
     orderstatus: "DRIVER",
     total: 1
   }]
 },
 {
   _id: "2017-12-07",
   totalcount: [{
     orderstatus: "MERCHANT",
     total: 3
   }]
 },
 {
   _id: "2017-12-04",
   totalcount: [{
       orderstatus: "DRIVER",
       total: 1
     },
     {
       orderstatus: "MERCHANT",
       total: 2
     },
     {
       orderstatus: "USER",
       total: 1
     }
   ]
 }
]
</code>```

The loop am performing:

```<code>for (let i = 0; i < recentUserCount.length; i++) {
  for (let j = 0; j < recentUserCount[i].totalcount.length; j++) {
    if (recentUserCount[i].totalcount[j].usertype == "DRIVER") {
      recentUserCount[i].DRIVERCount = recentUserCount[i].totalcount[j].total;
    } else if (recentUserCount[i].totalcount[j].usertype == "USER") {
      recentUserCount[i].USERCount = recentUserCount[i].totalcount[j].total;
    } else if (recentUserCount[i].totalcount[j].usertype == "MERCHANT") {
      recentUserCount[i].MERCHANTCount = recentUserCount[i].totalcount[j].total;
    }
  }
}
</code>```

The result will be roughly like below:

```<code>    0 : {_id: "2017-12-08", totalcount: Array(1), MERCHANTCount: 3, $$hashKey: "object:316"}
    1 : {_id: "2017-12-07", totalcount: Array(1), MERCHANTCount: 3, $$hashKey: "object:317"}
    2 : {_id: "2017-12-06", totalcount: Array(1), DRIVERCount: 1, $$hashKey: "object:318"}
    3 : {_id: "2017-12-04", totalcount: Array(3), DRIVERCount: 1, MERCHANTCount: 2, USERCount: 1, …}
</code>```

I want the same operation to be performed using Map/Filter or Reduce method.

答:
Pretty easy with ES6 syntax and map/reduce,
Full functional snippet:

var arr = [{_id:"2017-12-08",totalcount:[{orderstatus:"MERCHANT",total:1}]},{_id:"2017-12-02",totalcount:[{orderstatus:"USER",total:2}]},{_id:"2017-12-06",totalcount:[{orderstatus:"DRIVER",total:1}]},{_id:"2017-12-07",totalcount:[{orderstatus:"MERCHANT",total:3}]},{_id:"2017-12-04",totalcount:[{orderstatus:"DRIVER",total:1},{orderstatus:"MERCHANT",total:2},{orderstatus:"USER",total:1}]}];

  const result = arr
      .map(({_id, totalcount}) => ({
        totalcount,
        _id,
        ...totalcount.reduce((acc, {orderstatus, total}) =>
          ({...acc, [`${orderstatus}count`]: total}), {})
        }))

console.log(result)```
</div>
</div>
</p>

<p>https://jsbin.com/kiwalozuxa/edit?html,js,console,output</p>

<p>EDIT: The spread operator (...) is used to spread the keys/values of an objet (or values of an array). <code>totcalcount.reduce</code> here return an object:</p>

```{
  x: "x",
  y: "y"
}
```

<p>Since it's not technically valid in javascript to have an objet of this form:</p>

```{
  a: "a",
  b: "b",
  {
    x: "x",
    y: "y"
  }
}
```

<p>I use the spread operator to merge my "child" object into the parent objet and produce:</p>

```{
  a: "a",
  b: "b",
  x: "x",
  y: "y"
}
```

I use the same technique in the reducer.

Body:
I wanted to use higher order functions such as Map, Filter, Reduce.

My problem is I have an array which is not organised so I had to perform a loop operation to get the result I wanted. An array has two fields one is _id and totalCount which is an array the length will be minimum 0 to 3.

The totalCount each iteration consists of two fields one is orderstatus and another is total I want to perform a normal if else condition if orderstatus is "Merchant" or "driver" or "user" I want to take that iterated total and store it in my array like MerchantCount.

This is my code:

var arr = [{
   _id: "2017-12-08",
   totalcount: [{
     orderstatus: "MERCHANT",
     total: 1
   }]
 },
 {
   _id: "2017-12-02",
   totalcount: [{
     orderstatus: "USER",
     total: 2
   }]
 },
 {
   _id: "2017-12-06",
   totalcount: [{
     orderstatus: "DRIVER",
     total: 1
   }]
 },
 {
   _id: "2017-12-07",
   totalcount: [{
     orderstatus: "MERCHANT",
     total: 3
   }]
 },
 {
   _id: "2017-12-04",
   totalcount: [{
       orderstatus: "DRIVER",
       total: 1
     },
     {
       orderstatus: "MERCHANT",
       total: 2
     },
     {
       orderstatus: "USER",
       total: 1
     }
   ]
 }
]

The loop am performing:

for (let i = 0; i < recentUserCount.length; i++) {
  for (let j = 0; j < recentUserCount[i].totalcount.length; j++) {
    if (recentUserCount[i].totalcount[j].usertype == "DRIVER") {
      recentUserCount[i].DRIVERCount = recentUserCount[i].totalcount[j].total;
    } else if (recentUserCount[i].totalcount[j].usertype == "USER") {
      recentUserCount[i].USERCount = recentUserCount[i].totalcount[j].total;
    } else if (recentUserCount[i].totalcount[j].usertype == "MERCHANT") {
      recentUserCount[i].MERCHANTCount = recentUserCount[i].totalcount[j].total;
    }
  }
}

The result will be roughly like below:

    0 : {_id: "2017-12-08", totalcount: Array(1), MERCHANTCount: 3, $$hashKey: "object:316"}
    1 : {_id: "2017-12-07", totalcount: Array(1), MERCHANTCount: 3, $$hashKey: "object:317"}
    2 : {_id: "2017-12-06", totalcount: Array(1), DRIVERCount: 1, $$hashKey: "object:318"}
    3 : {_id: "2017-12-04", totalcount: Array(3), DRIVERCount: 1, MERCHANTCount: 2, USERCount: 1, …}

I want the same operation to be performed using Map/Filter or Reduce method.

Body:
Pretty easy with ES6 syntax and map/reduce,
Full functional snippet:

var arr = [{_id:"2017-12-08",totalcount:[{orderstatus:"MERCHANT",total:1}]},{_id:"2017-12-02",totalcount:[{orderstatus:"USER",total:2}]},{_id:"2017-12-06",totalcount:[{orderstatus:"DRIVER",total:1}]},{_id:"2017-12-07",totalcount:[{orderstatus:"MERCHANT",total:3}]},{_id:"2017-12-04",totalcount:[{orderstatus:"DRIVER",total:1},{orderstatus:"MERCHANT",total:2},{orderstatus:"USER",total:1}]}];

  const result = arr
      .map(({_id, totalcount}) => ({
        totalcount,
        _id,
        ...totalcount.reduce((acc, {orderstatus, total}) =>
          ({...acc, [`${orderstatus}count`]: total}), {})
        }))

console.log(result)

https://jsbin.com/kiwalozuxa/edit?html,js,console,output

EDIT: The spread operator (...) is used to spread the keys/values of an objet (or values of an array). totcalcount.reduce here return an object:

{
  x: "x",
  y: "y"
}

Since it's not technically valid in javascript to have an objet of this form:

{
  a: "a",
  b: "b",
  {
    x: "x",
    y: "y"
  }
}

I use the spread operator to merge my "child" object into the parent objet and produce:

{
  a: "a",
  b: "b",
  x: "x",
  y: "y"
}

I use the same technique in the reducer.