问:
Controlling blinking of LED based on value returned by a function
I wrote a code to blink LED, based on the value returned by a function. If the function "blinktheLED" returns TRUE, then the LED have to blink and if the value returned is False, then the LED don't blink. What i wanted to do is, I want the LED to blink or not blink based on the value returned by the function.  Currently when i run the code, LED just blink once and stops rather than keep on blinking as the function is returning TRUE . Any suggestions will be highly appreciated.

```<code>set_accepted_list = set(['1','3','112','29'])
set_list_LED_id   = set(['1','3'])
def blinktheLED(set_accepted_list,set_list_LED_id):
    if len(set_accepted_list &  set_list_LED_id) >0:
        print"yes,open the gate"                  #it will print, when i run the code
        return True
    else:
        print"no,donot open the gate"
        return False

def code_controlling_gate(True):
    connected = False
    ser = serial.Serial("COM11",9600)
    while not connected:
       serin = ser.read()
       connected = True
    ser.write('1')
    while ser.read() == '1':
       ser.read()
    ser.close()
</code>```

Arduino code:

```<code>void setup() {
Serial.begin(9600);
pinMode(10,OUTPUT);
Serial.write('1');
}
void loop() {
  Serial.read();
  if(Serial.available()>0){
    digitalWrite(10,HIGH);
    delay(500);
    digitalWrite(10,LOW);
    delay(500);
  }
  else{
    Serial.available()==0;
  }
}
</code>```

答:
Well it looks as though your Arduino loop blinking code is running based only on the condition Serial.available() and has no connection at all to the value that might be coming off the serial port.  Your Serial.read() is at the end of that block; it should be at the beginning and you should blink or not blink based on the value you receive.

I'm not sure that's the only problem here, but certainly you need to make that change to make it work as you describe.

More tips:

Make sure your serial sender is sending what you think by using a terminal emulator or a trusted device to verify that you're sending what you think you're sending.  You can tinker with the Arduino side all day long and if your sender isn't sending the right data, you'll just be frustrated.  Another PC and a null modem cable can be invaluable here.

Make sure all the serial parameters are the same.  speed, parity, databits all have to match.  Check both sides of the connection to make sure.  I don't see anywhere in your code where you're setting databits, parity or stopbits.

Once you get this working, if you have other projects that will use serial communications, consider making an Arduino that does just this -- make it a trusted device so that you can rule out these problems with a trusted device.  I have a microcontroller on a permanent board set up to do exactly this, blink when it's getting 9600 bps serial traffic.  That's my RS232 Hello World" device.  ;)

On the Arduino side, consider commenting out the conditional code around the blinking so that the loop does nothing but blink the LED the way you want.  That way you know at least that is working.  Like:

```<code>digitalWrite(10,HIGH);
delay(500);
digitalWrite(10,LOW);
delay(500);
</code>```

Finally, in your code, you're doing a Serial.read() but not saving the value anywhere to compare it.  You only need one character to save off a '1' or '0' so assign the result of Serial.read() to a variable and then act on its value in your loop.

Body:
I wrote a code to blink LED, based on the value returned by a function. If the function "blinktheLED" returns TRUE, then the LED have to blink and if the value returned is False, then the LED don't blink. What i wanted to do is, I want the LED to blink or not blink based on the value returned by the function.  Currently when i run the code, LED just blink once and stops rather than keep on blinking as the function is returning TRUE . Any suggestions will be highly appreciated.

set_accepted_list = set(['1','3','112','29'])
set_list_LED_id   = set(['1','3'])
def blinktheLED(set_accepted_list,set_list_LED_id):
    if len(set_accepted_list &  set_list_LED_id) >0:
        print"yes,open the gate"                  #it will print, when i run the code
        return True
    else:
        print"no,donot open the gate"
        return False

def code_controlling_gate(True):
    connected = False
    ser = serial.Serial("COM11",9600)
    while not connected:
       serin = ser.read()
       connected = True
    ser.write('1')
    while ser.read() == '1':
       ser.read()
    ser.close()

Arduino code:

void setup() {
Serial.begin(9600);
pinMode(10,OUTPUT);
Serial.write('1');
}
void loop() {
  Serial.read();
  if(Serial.available()>0){
    digitalWrite(10,HIGH);
    delay(500);
    digitalWrite(10,LOW);
    delay(500);
  }
  else{
    Serial.available()==0;
  }
}

Body:
Well it looks as though your Arduino loop blinking code is running based only on the condition Serial.available() and has no connection at all to the value that might be coming off the serial port.  Your Serial.read() is at the end of that block; it should be at the beginning and you should blink or not blink based on the value you receive.

I'm not sure that's the only problem here, but certainly you need to make that change to make it work as you describe.

More tips:

Make sure your serial sender is sending what you think by using a terminal emulator or a trusted device to verify that you're sending what you think you're sending.  You can tinker with the Arduino side all day long and if your sender isn't sending the right data, you'll just be frustrated.  Another PC and a null modem cable can be invaluable here.

Make sure all the serial parameters are the same.  speed, parity, databits all have to match.  Check both sides of the connection to make sure.  I don't see anywhere in your code where you're setting databits, parity or stopbits.

Once you get this working, if you have other projects that will use serial communications, consider making an Arduino that does just this -- make it a trusted device so that you can rule out these problems with a trusted device.  I have a microcontroller on a permanent board set up to do exactly this, blink when it's getting 9600 bps serial traffic.  That's my RS232 Hello World" device.  ;)

On the Arduino side, consider commenting out the conditional code around the blinking so that the loop does nothing but blink the LED the way you want.  That way you know at least that is working.  Like:

digitalWrite(10,HIGH);
delay(500);
digitalWrite(10,LOW);
delay(500);

Finally, in your code, you're doing a Serial.read() but not saving the value anywhere to compare it.  You only need one character to save off a '1' or '0' so assign the result of Serial.read() to a variable and then act on its value in your loop.


来源: stackexchange

问:
What are the best keyboard macros for programming in windows?
I like putting shortcuts of the form "g - google.lnk" in my start menu so google is two keystrokes away. Win, g.

My eight or so most frequent applications go there.

I also make links to my solution files I am always opening "x - Popular Project.lnk"

Are there any better ways to automate opening frequently used applications?

答:
For shortcuts I use Launchy

For macros I use AutoHotKey

Others will suggest SlickRun for shortcuts also.

ContentLicense: CC BY-SA 2.5

OwnerDisplayName: hometoast


问:
Quick and dirty solution for communication between processes in different machines
I have two processes written in java in two machines within my network that should pass simple chunks of data to each other.

I'm looking for a quick and dirty way (without resorting to writing files and polling for changes on network share files)

答:
The question is not clear. Are you looking for an API or library to use?
Do the two machines know each other's address to begin with or do they need to discover each other? </p>

<p>You can use JMS for most communications, but all machines have to be familiar with a "broker process" that is running separately. </p>

OwnerDisplayName: Dani

Body:
The question is not clear. Are you looking for an API or library to use?
Do the two machines know each other's address to begin with or do they need to discover each other?

You can use JMS for most communications, but all machines have to be familiar with a "broker process" that is running separately.

OwnerDisplayName: Uri


问:
Alternative to .SendKeys
I am new at VBA and my research tells that I should not use .SendKeys because it is unreliable. What alternative code should I use for the following?

Application.SendKeys ("{Home}")

答:
This looks to select the cell to the far left of the active selection, so with error handling:</p>

```<code>On Error Resume Next
Application.Goto Cells(ActiveCell.Row, 1)
</code>```

ContentLicense: CC BY-SA 3.0

Title: Alternative to .SendKeys

Body:
This looks to select the cell to the far left of the active selection, so with error handling:

On Error Resume Next
Application.Goto Cells(ActiveCell.Row, 1)


问:
How to play google drive video in jwplayer?
I have been trying fro 2 days to play the googledrive video in jwplayer but no avail. I have watched video tutorials from youtube also tried so many links to do this task but still no success. This is what I am trying.

upload video(mp4) in the folder
make the video and folder public
get the folder id and video name and replace with this link
https://googledrive.com/host/folderid/filename

but it is not working at all.any help?

答:
Just provide this link as MP4 source :

http://docs.google.com/uc?id=VIDEO_ID

The VIDEO_ID itself is found in the part of your link as shown below:

https://drive.google.com/file/d/VIDEO_ID/view

(in your case VIDEO_ID begins "0BxqS" and ends with "xbEU")

Edit : (make sure you specify type: "mp4" so JW Player knows the data type).

```<code>jwplayer("player").setup ({

file:   "https://docs.google.com/uc?id=0BzIpsk3FR4R1NjlnTWVDOHB2MTQ",
type:   "mp4",
width:  640,
height: 360,

});
</code>```

Body:
Just provide this link as MP4 source :

http://docs.google.com/uc?id=VIDEO_ID

The VIDEO_ID itself is found in the part of your link as shown below:

https://drive.google.com/file/d/VIDEO_ID/view

(in your case VIDEO_ID begins "0BxqS" and ends with "xbEU")

Edit : (make sure you specify type: "mp4" so JW Player knows the data type).

jwplayer("player").setup ({

file:   "https://docs.google.com/uc?id=0BzIpsk3FR4R1NjlnTWVDOHB2MTQ",
type:   "mp4",
width:  640,
height: 360,

});


问:
Is it okay to have a very long .htaccess file?
I am giving out URLs to people on a website, that actually point to something ugly (on the same website).

http://www.mydomain.com/cool-URL

actually points to

http://www.mydomain.com/boring.php?id=478547&sessid=34734asdf7&otherboringdetails

I'm planning to achieve this by modifying the .htaccess file whenever needed. I'm going to make the PHP script write to the .htaccess file, adding a new rewrite rule whenever there is a new hand-out of a url (from an admin area a non-programmer can control [specify the URL title for this new entry, admin : it will be assigned automagically]).

Is this going to be a problem, especially after 1000 or so such URLs? What is the actual number that is acceptable? Because, I can picture this: the server receives a request for a URL, then it searches the .htaccess file for the right page for this url, and finally sends the user to the right page. If this is anything like Database searching, it might take a long time for the user to actually get to the right page...

Any pointers on this, please?

答: It should be fine. You just might experience server lag when it gets really long. I would look into mod_rewrite specs, you might be able to automate the forwards with a few line & regex function. I don't know enough about the url variables that will be passed to give you an example.</p>


问:
Write a recursive function that takes an array and displays the elements in reverse order without starting the index of the array at the end
My question is: Am I doing this right or not?
Because no one can tell me exactly...

Write a recursive function that takes an array and displays the elements in reverse order
without starting the index of the array at the end. (In other words, don’t write the equivalent of
a loop that starts printing at the end of the array.)

```<code>int bleah(int arr[], int number)
{
    cout << arr[number] << ' ';
    if (number <= 0)
    {
        return 1;
    }
    cout << arr[number] << ' ';
    return bleah(arr, number - 1);
}

int main()
{
    int arr[31] = {0};
    for (int i = 0; i <= 30; i++)
    {
        arr[i] = i;
    }
    bleah(arr, 30);

    cin.get();
    cin.ignore();
    return 0;
}
</code>```

答:
A complete running code (along with main method). I understand it's bit difficult for a beginner in the starting. Don't bother about harsh comments here.
I have used a vector rather than traditional array just to make things simpler and readable:</p>

```<code>#include <iostream>
#include <vector>

using namespace std;
//Typedef the vector to a simple name, array
typedef vector<int> array;

//The actual, recursive function
void printReverse(const array arr, const unsigned int index){
    //The base condition of recursion
    if(index != arr.size()){
        printReverse(arr, index+1);
        cout << arr[index] <<" ";
    }
}

int main()
{
    int size;
    cout << "Enter size of the array: ";
    cin >> size;
    array arr;

    cout << "Enter elements: ";
    for(int i=0; i<size; i++){
        int a;
        cin >> a;
        arr.push_back(a); //add the input to the array(or vector)
    }
    //The recursive function call(starting with index 0)
    printReverse(arr, 0);
    return 0;
}
</code>```

Body:
My question is: Am I doing this right or not?
Because no one can tell me exactly...

Write a recursive function that takes an array and displays the elements in reverse order
without starting the index of the array at the end. (In other words, don’t write the equivalent of
a loop that starts printing at the end of the array.)

int bleah(int arr[], int number)
{
    cout << arr[number] << ' ';
    if (number <= 0)
    {
        return 1;
    }
    cout << arr[number] << ' ';
    return bleah(arr, number - 1);
}

int main()
{
    int arr[31] = {0};
    for (int i = 0; i <= 30; i++)
    {
        arr[i] = i;
    }
    bleah(arr, 30);

    cin.get();
    cin.ignore();
    return 0;
}

Body:
A complete running code (along with main method). I understand it's bit difficult for a beginner in the starting. Don't bother about harsh comments here.
I have used a vector rather than traditional array just to make things simpler and readable:

#include <iostream>
#include <vector>

using namespace std;
//Typedef the vector to a simple name, array
typedef vector<int> array;

//The actual, recursive function
void printReverse(const array arr, const unsigned int index){
    //The base condition of recursion
    if(index != arr.size()){
        printReverse(arr, index+1);
        cout << arr[index] <<" ";
    }
}

int main()
{
    int size;
    cout << "Enter size of the array: ";
    cin >> size;
    array arr;

    cout << "Enter elements: ";
    for(int i=0; i<size; i++){
        int a;
        cin >> a;
        arr.push_back(a); //add the input to the array(or vector)
    }
    //The recursive function call(starting with index 0)
    printReverse(arr, 0);
    return 0;
}


问:
Extra margin in canvas
I'm trying to make a canvas that fits perfectly in a square browser. The problem is keep getting this extra margin at the top and left of the screen  and I'm unable to get rid of it. Any idea how I can fix this?

Code

```<code><!DOCTYPE HTML>
<html>
<head>
    <meta charset="utf-8">
</head>
<style type="text/css">

#gameCanvas {
    background-color: blue;
}

</style>

<canvas id="gameCanvas"></canvas>
<script type="text/javascript">
    var canvas = document.getElementById("gameCanvas");
    canvas.width = window.innerWidth;
    canvas.height = window.innerWidth;
</script>
<script src="cocos2d.js"></script>
</body>
</html>
</code>```

答:
As @Katherine Huang said, browsers have default stylesheets that include margins, padding...

You can set this:

```<code>html, body{
    margin:0;
    padding:0;
}
#gameCanvas{
    margin:0;
    padding:0;
    background-color: blue;
}
</code>```

Now you will have to set specific margins and paddings on every new element inside the body, becouse by default they will have 0.

Title: Extra margin in canvas

Body:
I'm trying to make a canvas that fits perfectly in a square browser. The problem is keep getting this extra margin at the top and left of the screen  and I'm unable to get rid of it. Any idea how I can fix this?

Code

<!DOCTYPE HTML>

    <meta charset="utf-8">

<canvas id="gameCanvas"></canvas>

Body:
As @Katherine Huang said, browsers have default stylesheets that include margins, padding...

You can set this:

html, body{
    margin:0;
    padding:0;
}
#gameCanvas{
    margin:0;
    padding:0;
    background-color: blue;
}

Now you will have to set specific margins and paddings on every new element inside the body, becouse by default they will have 0.


问:
deleting duplicate valuesand storing the oldest date value using mysql
How do I delete records from the following table:

so that the result is  as follows:

.stack.imgur.com/BE87A.jpg

答:
This keeps only that records, which have lowest clockintime for each employee of each day.

Another records will removed (just for clarify, that you need actually remove rows and not only filter at SELECT).

So, if you need actually remove, then you can use this query:

```<code>delete your_table from your_table
inner join (
    select empid, `date`, min(clockintime) as minclockintime
    from your_table
    group by  empid, `date`
) sub
on your_table.empid = sub.empid and your_table.`date` = sub.`date` and your_table.clockintime > sub.minclockintime
</code>```

Well, subquery gets lowest/min clockintime for each employee for each date.

Then from table deleted all rows, when employee and date match with subquery, but clockintime is higher, than that minimal time from subquery.

This means that for every employee and day, only rows with lowest/min clockintime
 are remained, another rows deleted.

This is simply, just realize subquery result and then think about on clause, thats it.

Body:
This keeps only that records, which have lowest clockintime for each employee of each day.

Another records will removed (just for clarify, that you need actually remove rows and not only filter at SELECT).

So, if you need actually remove, then you can use this query:

delete your_table from your_table
inner join (
    select empid, `date`, min(clockintime) as minclockintime
    from your_table
    group by  empid, `date`
) sub
on your_table.empid = sub.empid and your_table.`date` = sub.`date` and your_table.clockintime > sub.minclockintime

Well, subquery gets lowest/min clockintime for each employee for each date.

Then from table deleted all rows, when employee and date match with subquery, but clockintime is higher, than that minimal time from subquery.

This means that for every employee and day, only rows with lowest/min clockintime
 are remained, another rows deleted.

This is simply, just realize subquery result and then think about on clause, thats it.


问:
how to deal with components inside components in angular?
Maybe It's simple question but I've been searching for a while and I don't find how to do something like this in angular :

```<code><Parent>
  <Child1>
  <Child2>
</Parent>
</code>```

And Define the behavior of the children in the parent component. Is That possible ?

答:
I think that ng-content is the thing you searching for

from blog of todd moto

```<code>// my-component.component.ts
import { Component } from '@angular/core';

@Component({
selector: 'my-parent-component',
template: `
  <div class="my-parent-component">
     <ng-content></ng-content>
  </div>
`
})
export class MyComponent {}
</code>```

this way you can host inside component another component (or anything else)

```<code>import {Component} from 'angular2/core';
import {MyComponent} from './my-component.component';
import {MyChildComponent} from './my-component.component';
@Component({
selector: 'my-app',
template: `
<div class="app">
  <my-parent-component>
    <my-child-component></my-child-component>
    <my-child-component></my-child-component>
  </my-parent-component>
 </div>
 `,
 directives: [
   MyComponent,MyChildComponent//this is old angular 2.0.0-beta.10 syntax
 ]
})
 export class AppComponent {

 }
</code>```

see this plunk

Body:
Maybe It's simple question but I've been searching for a while and I don't find how to do something like this in angular :

<Parent>
  <Child1>
  <Child2>
</Parent>

And Define the behavior of the children in the parent component. Is That possible ?

Body:
I think that ng-content is the thing you searching for

from blog of todd moto

// my-component.component.ts
import { Component } from '@angular/core';

@Component({
selector: 'my-parent-component',
template: `
  <div class="my-parent-component">
     <ng-content></ng-content>
  </div>
`
})
export class MyComponent {}

this way you can host inside component another component (or anything else)

import {Component} from 'angular2/core';
import {MyComponent} from './my-component.component';
import {MyChildComponent} from './my-component.component';
@Component({
selector: 'my-app',
template: `
<div class="app">
  <my-parent-component>
    <my-child-component></my-child-component>
    <my-child-component></my-child-component>
  </my-parent-component>
 </div>
 `,
 directives: [
   MyComponent,MyChildComponent//this is old angular 2.0.0-beta.10 syntax
 ]
})
 export class AppComponent {

 }

see this plunk


问:
Clojure - Adding pairs of numbers in a vector
I have a vector [1 2 3 4]. Is there a way of adding each pair to get [(+ 1 2) (+ 2 3) (+ 3 4)]

I tried

```<code>(loop [x 0]
  (when (< x (count y))
    (+ (nth y x) (nth y (+ 1 x)))
    (recur (+ x 1))))
</code>```

But I get an out of bounds error IndexOutOfBoundsException   clojure.lang.PersistentVector.arrayFor (PersistentVector.java:158)

答:
This is one way:

```<code>(->> [1 2 3 4]
     (partition 2 1)
     (mapv (partial reduce +)))
;;=> [3 5 7]
</code>```

The main problem I see with the approach you were taking is that there is no accumulator in the loop recur form. Another problem is that you are using when rather than if.

Body:
I have a vector [1 2 3 4]. Is there a way of adding each pair to get [(+ 1 2) (+ 2 3) (+ 3 4)]

I tried

(loop [x 0]
  (when (< x (count y))
    (+ (nth y x) (nth y (+ 1 x)))
    (recur (+ x 1))))

But I get an out of bounds error IndexOutOfBoundsException   clojure.lang.PersistentVector.arrayFor (PersistentVector.java:158)

Body:
This is one way:

(->> [1 2 3 4]
     (partition 2 1)
     (mapv (partial reduce +)))
;;=> [3 5 7]

The main problem I see with the approach you were taking is that there is no accumulator in the loop recur form. Another problem is that you are using when rather than if.


问:
Why my EditText copy/paste menu is under the EditText? How change the z-order of popup window?
NOTE

If someone know how to order (z-order) Windows added via windowmanager, i will also accept the answer because it's will answer all the question. Actually i only find to do windowManager.removeView(MyView) following immediatly by windowManager.addView(MyView) to put a view in front of the other, but this is not ideal because it's visually remove and add the view. it's look crazy that their is no build in function in android to do such a simple think.

I create a view (linearlayout) that contain an EditText. I add this view in the activity via WindowManager.addView (view, Layout_Params);

but i have problem that every popup the edittext will generate (like copy/past menu or word suggestion menu) will be under other views, under even their owning EditText view (not on the picture the edittext have a transparent background)

ill be

i create the views (ie: LinearLayout) with theses layout params :

```<code>protected WindowManager.LayoutParams createLayoutParams() {
    WindowManager.LayoutParams p = new WindowManager.LayoutParams();
    p.gravity = Gravity.LEFT | Gravity.TOP;
    p.width = 0;
    p.height = 0;
    p.format = PixelFormat.TRANSLUCENT;
    p.softInputMode = WindowManager.LayoutParams.SOFT_INPUT_STATE_UNCHANGED;
    p.flags = NOT_FOCUSABLE_FLAGS;
    // TYPE_APPLICATION allows for popups in browser windows (like edit menus)
    p.type = WindowManager.LayoutParams.TYPE_APPLICATION;
    p.token = null;

    return p;
}
</code>```

and i show the view (who contain just an edittext) like this :

```<code>    private final WindowManager mWindowManager;
    mWindowManager = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);

    WindowManager.LayoutParams lp = createLayoutParams();
    mWindowManager.addView(view, lp);
</code>```

so how to make the popup connected to the editText in front of everything ?

This question can also maybe help a little (about z-order of window view): How work the z-order of view (ie: window) added via WindowManager?

答: Their is actually no way to order (z-order) windows added via windowmanager. The only way is to remove the window and to add it back again.</p>

Body:
NOTE

If someone know how to order (z-order) Windows added via windowmanager, i will also accept the answer because it's will answer all the question. Actually i only find to do windowManager.removeView(MyView) following immediatly by windowManager.addView(MyView) to put a view in front of the other, but this is not ideal because it's visually remove and add the view. it's look crazy that their is no build in function in android to do such a simple think.

I create a view (linearlayout) that contain an EditText. I add this view in the activity via WindowManager.addView (view, Layout_Params);

but i have problem that every popup the edittext will generate (like copy/past menu or word suggestion menu) will be under other views, under even their owning EditText view (not on the picture the edittext have a transparent background)

ill be

i create the views (ie: LinearLayout) with theses layout params :

protected WindowManager.LayoutParams createLayoutParams() {
    WindowManager.LayoutParams p = new WindowManager.LayoutParams();
    p.gravity = Gravity.LEFT | Gravity.TOP;
    p.width = 0;
    p.height = 0;
    p.format = PixelFormat.TRANSLUCENT;
    p.softInputMode = WindowManager.LayoutParams.SOFT_INPUT_STATE_UNCHANGED;
    p.flags = NOT_FOCUSABLE_FLAGS;
    // TYPE_APPLICATION allows for popups in browser windows (like edit menus)
    p.type = WindowManager.LayoutParams.TYPE_APPLICATION;
    p.token = null;

    return p;
}

and i show the view (who contain just an edittext) like this :

    private final WindowManager mWindowManager;
    mWindowManager = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);

    WindowManager.LayoutParams lp = createLayoutParams();
    mWindowManager.addView(view, lp);

so how to make the popup connected to the editText in front of everything ?

This question can also maybe help a little (about z-order of window view): How work the z-order of view (ie: window) added via WindowManager?


问:
TeamCity - how to combine VCS Triggers
Here is the situation: in git repo I have 3 folders:
A
B
C
If changes were made to A or C, build must be started. In any other case, if changes were made to B as well, it should not be started. How to achieve such behavior with TeamCity VCS Trigger(s)?</p>

答:
I did not found the way to "prevent build from start if there are changes in particular folder". Build will be started. But I decided to make the workaround and skip actual execution of next steps if the changes in B folder have been detected. Below is the script which gives me environment variable to gracefully avoid next build steps execution.

This script is based on TeamCity environment variable

%system.teamcity.build.changedFiles.file%

IMPORTANT: don't use -:B (in my case -:lisp) trigger rule, otherwise you will not be able to detect changes in this folder from script.

The script:

#!/bin/bash

listFiles=$(echo %system.teamcity.build.changedFiles.file%)
echo "List files from $listFiles"
echo "--------------------------"
cat $listFiles
echo "--------------------------"
lispFound=$(cat $listFiles | grep -c '^src\/lisp\/*.')
echo "LISP CHANGES WERE DETECTED: $lispFound time(s)"
echo "##teamcity[setParameter name='env.LISP_CHANGES_DETECTED' value ='$lispFound']"```
</div>
</div>
</p>

<p>As the result, the %env.LISP_CHANGES_DETECTED% with number of changed files will be available at any next step. In my case next step is Ant, and can detect in any target if should just echo "nothing to do" and go out. Here is the exmple of execution log:</p>

<p><img src="https://i.stack.imgur.com/z6DeG.png" alt="enter image description here"></p>

<p>IMPROVEMENT:
As described here Can I cancel a TeamCity build from my msbuild script?</p>

<p>Execution may be gracefully stopped right from the script, you will need to add call to cancel execution:</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code>curl -v -u user:password --request POST "http://teamcity:8111/app/rest/builds/<buildLocator>" --data "<buildCancelRequest comment='' readdIntoQueue='false' />" --header "Content-Type: application/xml"</code>```

Title: TeamCity - how to combine VCS Triggers

Body:
I did not found the way to "prevent build from start if there are changes in particular folder". Build will be started. But I decided to make the workaround and skip actual execution of next steps if the changes in B folder have been detected. Below is the script which gives me environment variable to gracefully avoid next build steps execution.

This script is based on TeamCity environment variable

%system.teamcity.build.changedFiles.file%

IMPORTANT: don't use -:B (in my case -:lisp) trigger rule, otherwise you will not be able to detect changes in this folder from script.

The script:

#!/bin/bash

listFiles=$(echo %system.teamcity.build.changedFiles.file%)
echo "List files from $listFiles"
echo "--------------------------"
cat $listFiles
echo "--------------------------"
lispFound=$(cat $listFiles | grep -c '^src\/lisp\/*.')
echo "LISP CHANGES WERE DETECTED: $lispFound time(s)"
echo "##teamcity[setParameter name='env.LISP_CHANGES_DETECTED' value ='$lispFound']"

As the result, the %env.LISP_CHANGES_DETECTED% with number of changed files will be available at any next step. In my case next step is Ant, and can detect in any target if should just echo "nothing to do" and go out. Here is the exmple of execution log:

IMPROVEMENT:
As described here Can I cancel a TeamCity build from my msbuild script?

Execution may be gracefully stopped right from the script, you will need to add call to cancel execution:

curl -v -u user:password --request POST "http://teamcity:8111/app/rest/builds/<buildLocator>" --data "<buildCancelRequest comment='' readdIntoQueue='false' />" --header "Content-Type: application/xml"


问:
Passing multiple types to std::function C++
I am currently working on a little library and ran into a error. What I am basically trying to do is have syntax like so:

```<code>Client client("", true);

client.on("ready", [](User object) {
    object.test();
});

client.run();
</code>```

and when I call
_eventManager->emit("ready", new User())
The client.on(); method is suppose to fire with the given object I pass in. The object that I pass can be a variety of classes.

The way I design it so that I use a base class called "Object" and all the classes that I want to pass onto emit would be derived from Object. However I get an error when trying to do this:

error C2664: 'void Discord::Client::on(const std::string &,const std::function<void (Discord::Object)> &)': cannot convert argument 2 from 'main::<lambda_54cb69ba8322d42f33e22a0f4f4926a4>' to 'const std::function<void (Discord::Object)> &'
2>  z:\projects\visual studio 2015\discord\test\source\example1.cpp(12): note: Reason: cannot convert from 'main::<lambda_54cb69ba8322d42f33e22a0f4f4926a4>' to 'const std::function<void (Discord::Object)>'
2>  z:\projects\visual studio 2015\discord\test\source\example1.cpp(12): note: No user-defined-conversion operator available that can perform this conversion, or the operator cannot be called

I am clueless on what I did wrong.
Code:

```<code>struct Event {
    std::string name;
    std::function<void(Object object)> function;
};

void Client::on(const std::string& name, const std::function<void(Object object)>& function) {
    _eventManager->add(name, function);
}

void Client::run() {
    User object;

    _eventManager->emit("ready", object);
}

void EventManager::add(const std::string& name, const std::function<void(Object object)>& function) {
    Event event;
    event.name = name;
    event.function = function;

    _events.push_back(event);
}

void EventManager::emit(const std::string& name, const Object& object) {
    for (unsigned int i = 0; i < _events.size(); i++) {
        Event& event = _events[i];

        if (event.name == name) {
            event.function(object);
        }
    }
}
</code>```

Error
Thank you in advance.

答:
Can also try something like the below.. I made the parameters pointers to prevent Slicing, but the actual solution to the issue is the createFunc function which binds the passed in lambda to an internal one that calls the passed in lambda. It ensures that the classes passed in are derived from Object.

```<code>#include <iostream>
#include <functional>
#include <vector>

class Object;

struct Event {
    std::string name;
    std::function<void(Object* object)> function;
};

class Client
{
private:
    std::vector<Event> events;

public:
    void on(const std::string& name, const std::function<void(Object* object)>& function)
    {
        this->events.push_back(Event{name, function});
    }

    void run()
    {
        for (Event &e : events)
        {
            e.function(nullptr);
        }
    }
};

class Object
{
};

class User : public Object
{

};

template<typename T>
typename std::enable_if<std::is_base_of<Object, T>::value, std::function<void(Object*)>>::type
createFunc(std::function<void(T*)> func)
{
    auto call = [](std::function<void(T*)> func, Object *ptr)
    {
        func(dynamic_cast<T *>(ptr));
    };

    return std::bind(call, func, std::placeholders::_1);
}

int main(int argc, const char * argv[]) {

    Client c;

    auto lambda = [](User* usr) {
        std::cout<<"Lambda called\n";
    };

    c.on("Hello", createFunc<User>(lambda));
    c.run();

    return 0;
}
</code>```

CreateFunc is essentially the same as:

```<code>template<typename T>
void callFuncHelper(std::function<void(T*)> func, Object *ptr)
{
    func(dynamic_cast<T*>(ptr));
};

template<typename T>
typename std::enable_if<std::is_base_of<Object, T>::value, std::function<void(Object*)>>::type
createFunc(std::function<void(T*)> func)
{
    return std::bind(callFuncHelper<T>, func, std::placeholders::_1);
}
</code>```

and works like:

```<code>Client c;

auto lambda = [](User* usr) {
    std::cout<<"Lambda called\n";
};

c.on("Hello", createFunc<User>(lambda));
c.run();
</code>```

Why? Because I couldn't find another way to deduce the lambda parameter so you have to pass it in as a template argument.

Body:
I am currently working on a little library and ran into a error. What I am basically trying to do is have syntax like so:

Client client("", true);

client.on("ready", [](User object) {
    object.test();
});

client.run();

and when I call
_eventManager->emit("ready", new User())
The client.on(); method is suppose to fire with the given object I pass in. The object that I pass can be a variety of classes.

The way I design it so that I use a base class called "Object" and all the classes that I want to pass onto emit would be derived from Object. However I get an error when trying to do this:

error C2664: 'void Discord::Client::on(const std::string &,const std::function<void (Discord::Object)> &)': cannot convert argument 2 from 'main::<lambda_54cb69ba8322d42f33e22a0f4f4926a4>' to 'const std::function<void (Discord::Object)> &'
2>  z:\projects\visual studio 2015\discord\test\source\example1.cpp(12): note: Reason: cannot convert from 'main::<lambda_54cb69ba8322d42f33e22a0f4f4926a4>' to 'const std::function<void (Discord::Object)>'
2>  z:\projects\visual studio 2015\discord\test\source\example1.cpp(12): note: No user-defined-conversion operator available that can perform this conversion, or the operator cannot be called

I am clueless on what I did wrong.
Code:

struct Event {
    std::string name;
    std::function<void(Object object)> function;
};

void Client::on(const std::string& name, const std::function<void(Object object)>& function) {
    _eventManager->add(name, function);
}

void Client::run() {
    User object;

    _eventManager->emit("ready", object);
}

void EventManager::add(const std::string& name, const std::function<void(Object object)>& function) {
    Event event;
    event.name = name;
    event.function = function;

    _events.push_back(event);
}

void EventManager::emit(const std::string& name, const Object& object) {
    for (unsigned int i = 0; i < _events.size(); i++) {
        Event& event = _events[i];

        if (event.name == name) {
            event.function(object);
        }
    }
}

Error
Thank you in advance.

Body:
Can also try something like the below.. I made the parameters pointers to prevent Slicing, but the actual solution to the issue is the createFunc function which binds the passed in lambda to an internal one that calls the passed in lambda. It ensures that the classes passed in are derived from Object.

#include <iostream>
#include <functional>
#include <vector>

class Object;

struct Event {
    std::string name;
    std::function<void(Object* object)> function;
};

class Client
{
private:
    std::vector<Event> events;

public:
    void on(const std::string& name, const std::function<void(Object* object)>& function)
    {
        this->events.push_back(Event{name, function});
    }

    void run()
    {
        for (Event &e : events)
        {
            e.function(nullptr);
        }
    }
};

class Object
{
};

class User : public Object
{

};

template<typename T>
typename std::enable_if<std::is_base_of<Object, T>::value, std::function<void(Object*)>>::type
createFunc(std::function<void(T*)> func)
{
    auto call = [](std::function<void(T*)> func, Object *ptr)
    {
        func(dynamic_cast<T *>(ptr));
    };

    return std::bind(call, func, std::placeholders::_1);
}

int main(int argc, const char * argv[]) {

    Client c;

    auto lambda = [](User* usr) {
        std::cout<<"Lambda called\n";
    };

    c.on("Hello", createFunc<User>(lambda));
    c.run();

    return 0;
}

CreateFunc is essentially the same as:

template<typename T>
void callFuncHelper(std::function<void(T*)> func, Object *ptr)
{
    func(dynamic_cast<T*>(ptr));
};

template<typename T>
typename std::enable_if<std::is_base_of<Object, T>::value, std::function<void(Object*)>>::type
createFunc(std::function<void(T*)> func)
{
    return std::bind(callFuncHelper<T>, func, std::placeholders::_1);
}

and works like:

Client c;

auto lambda = [](User* usr) {
    std::cout<<"Lambda called\n";
};

c.on("Hello", createFunc<User>(lambda));
c.run();

Why? Because I couldn't find another way to deduce the lambda parameter so you have to pass it in as a template argument.


问:
JavaScript - compare two arrays with limited values/elements
I have an array of a few numbers or strings, eg.

```<code>[4.3, 1.2, 4.5, 3.9]

['I', 'the', 'sheriff', 'shot']
</code>```

The users re-arrange the elements in a specific order. For example, in an ascending order:

```<code>[1.2, 3.9, 4.3, 4.5]
</code>```

and to create a valid sentence:

```<code>['I', 'shot', 'the', 'sheriff']
</code>```

I have those predefined answers stored in an object. How do I compare the arrays with user generated order with the ones with correct order of elements. I have seen other answers on how to compare arrays but my question does not require a wide range of 'what if....' that other answers had. The elements are generated by the app so no unexpected input would be there, no undefined values, no empty elements, etc. Users do not input anything. They just rearrange tiles with those elements.

What's the best way to compare the arrays to determine if the users have rearranged the boxes in the right way.

My first attempt is incorrect as it always seems to be outputing 'BINGO' even if the order is incorrect:

```<code>if (this.props.squares === correctOrder) {
      console.log("BINGO");
    }
</code>```

答:
You could store the wanted order in an object, where the values of the first array are the keys and ththe sorted indices the values.

For checking if in right order, just check the items array with the objects value and the actual index.

var items = [1.2, 3.9, 4.3, 4.5],
    order = items.reduce((o, k, i) => (o[k] = i, o), {});

// check
items.every((k, i) => order[k] === i) && console.log('bingo');```

Body:
I have an array of a few numbers or strings, eg.

[4.3, 1.2, 4.5, 3.9]

['I', 'the', 'sheriff', 'shot']

The users re-arrange the elements in a specific order. For example, in an ascending order:

[1.2, 3.9, 4.3, 4.5]

and to create a valid sentence:

['I', 'shot', 'the', 'sheriff']

I have those predefined answers stored in an object. How do I compare the arrays with user generated order with the ones with correct order of elements. I have seen other answers on how to compare arrays but my question does not require a wide range of 'what if....' that other answers had. The elements are generated by the app so no unexpected input would be there, no undefined values, no empty elements, etc. Users do not input anything. They just rearrange tiles with those elements.

What's the best way to compare the arrays to determine if the users have rearranged the boxes in the right way.

My first attempt is incorrect as it always seems to be outputing 'BINGO' even if the order is incorrect:

if (this.props.squares === correctOrder) {
      console.log("BINGO");
    }


问:
Music Playback in Visual Basic .NET
I am trying to create a desktop application that will play and pause music files the user has selected. However, the built-in audio playback (My.Computer.Audio) only plays .wav files, and it only has functions to play and stop.

I need something that can play, pause, stop, and hopefully read MP3 tags. I have looked into the VLC and Bass APIs, but I have no idea how to implement and use them. If anyone knows how to use said APIs, that would be great. I don't have a lot of experience, so please explain everything needed to import and utilize those APIs.

UPDATE: I am currently using an invisible Windows Media Player control, but it's slow and bulky.
Thanks

答:
There are several options to integrate media playback into your application.

Personally, I would recommend using the VLC as it is well-documented, versatile and straight forward to use.

During installation of the VLC-Software, make sure that the ActiveX-Control option is checked. On your Visual Studio Project Settings page, go to "References", click "Add" and select "COM Objects" on the left hand side and in the list select the VLC-Control.

You can add the control directly to you form. If it is not displayed inside your toolbox, right click the toolbox list, choose select/add controls; once again select "COM Objects" on the left hand side and check the VLC-Control.

If it is not listed there, choose Browse and select axvlc.dll from VLC installation directory.

Example: Toolbox / Choose Items dialog / Section "COM-Components" on Microsoft Visual Studio 2015

Title: Music Playback in Visual Basic .NET


问:
Evaluatejsonpath returning complete array
I have got json file with nested structure. I use splitjson first and then evaluatejsonpath processor to select element I am interested in. Works fine with single element to be returned but when I add more properties and change to flow file attribute. It returns the array from splitjson processor. Any help much appreciated </p>

答: Your JSONPath in SplitJson needs to point to an array to be split. If, after that, your EvaluateJsonPath points at a field that is an array, the array will be returned. If you want a flow file for each element in that array, you'll need another SplitJson processor. If your EvaluateJsonPath is putting the result(s) in an attribute, the flow file content will remain the same (i.e. the contents of the original incoming flow file). The current version of NiFi has a jsonPath function in Expression Language (https://nifi.apache.org/docs/nifi-docs/html/expression-language-guide.html#jsonpath) that you can use to manipulate the JSON content in the attribute.</p>


问:
if-else depends on whether T is a complete type
How to check whether a certain type is a complete type in a certain .cpp?

```<code>template<class T>class Test{
    //some fields
    void(*functor)(T*) =[](T*){};
    //^ will be written by some .cpp that can access T as complete-type
    T* t=nullptr;
    void fComplete(){
        delete t;     //faster
        /** ^ some code that use complete type*/
    }
    void fForward(){
        functor(t);   //slower
        /** ^ some code that forward declaration is enough*/
    }
    void f(){
        /*if(T is complete type){
            fComplete();
        }else fForward();*/
    }
};
</code>```

demo

It will be useful when I want to <s>prematurely</s> optimize a delete function in my custom smart pointer.

Can anyone confirm that it is impossible?

I am not asking for a workaround (but I don't mind) - this question is just my curiosity.

答:
There's a rule in C++ called ODR. The very basics of this rule (from my understanding)  is that something can have as many declarations as you want, but only one definition. It seems simple, but with templates and inline function, is quite easy to break it.

With templates, multiple definition is inevitable. Instantiation of the same template will happen in all translation unit that uses it. It seems against the one definition rule, but for inline and templated entities, the rule is extended. Here's a paragraph on cppreference:

There can be more than one definition in a program, as long as each
  definition appears in a different translation unit, of each of the
  following: class type, enumeration type, inline function with external
  linkage inline variable with external linkage (since C++17), class
  template, non-static function template, static data member of a class
  template, member function of a class template, partial template
  specialization, as long as all of the following is true:

each definition consists of the same sequence of tokens (typically, appears in the same header file)

name lookup from within each definition finds the same entities (after overload-resolution), except that constants with internal or
  no linkage may refer to different objects as long as they are not
  ODR-used and have the same values in every definition.

overloaded operators, including conversion, allocation, and    deallocation functions refer to the same function from each

  definition (unless referring to one defined within the definition)

the language linkage is the same (e.g. the include file isn't inside    an extern "C" block)

the three rules above apply to every default argument used in each    definition

if the definition is for a class with an implicitly-declared    constructor, every translation unit where it is odr-used must call
  the same constructor for the base and members

if the definition is for a template, then all these requirements    apply to both names at the point of definition and dependent names at
  the point of instantiation

If all these requirements are satisfied, the program behaves as if
  there is only one definition in the entire program. Otherwise, the
  behavior is undefined.

In short, if any function template expands to slightly different things in some translation units, you end up in the UB land. Trust me, debugging ODR violation is the worst, because your program might work for a long time, and suddenly crash when changing some compilation options, like optimisations.

In your particular case, you want to detect if a type is complete or not to change the definition of a function. Since in some places you might have a complete type and instantiate that function, you'll end up with multiple and different definition of that function.

Be careful with macros too. If some macro definition changes in only some translation and you use that macro in a template or inline function, you violate ODR, since the function won't consist of the exact same tokens.

Now, I acknowledge that other answers also are useful indeed. Detecting whether a type is complete is not entirely useless. I use it in my code.  I use it to provide nice diagnostics with static_assert, which even some implementations of the STL do (unique_ptr destructor in GCC's STL).

Body:
How to check whether a certain type is a complete type in a certain .cpp?

template<class T>class Test{
    //some fields
    void(*functor)(T*) =[](T*){};
    //^ will be written by some .cpp that can access T as complete-type
    T* t=nullptr;
    void fComplete(){
        delete t;     //faster
        /** ^ some code that use complete type*/
    }
    void fForward(){
        functor(t);   //slower
        /** ^ some code that forward declaration is enough*/
    }
    void f(){
        /*if(T is complete type){
            fComplete();
        }else fForward();*/
    }
};

demo

It will be useful when I want to <s>prematurely</s> optimize a delete function in my custom smart pointer.

Can anyone confirm that it is impossible?

I am not asking for a workaround (but I don't mind) - this question is just my curiosity.


问:
flash UI, how to drag symbol with tween
I want to drag symbol that has a tween. As soon as I drag, tween gets messed up, since flash thinks I want to manually adjust tween. No, I just changed size of stage and want to tween start and end same way but in different position. You could drag by tween line, but this particular tween just changes opacity so no luck. Is there some shift-control-something key sequence to drag symbol with tween intact?</p>

答:
If you mean:

you have a symbol on a timeline and this symbol has at least two instances on the timeline, connected by a timline tween.

then you cannot move either end or any part of that tween independently without affecting the tween.  A timeline tween gets its parameters (ie starting x, starting alpha etc) from the movieclip's properties.  If you move a movieclip instance that is the start of your tween, you are changing that movieclip's parameters (ie, x, y etc), thus affecting the outcome of your tween.

To move around a movieclip tweened on a timeline across multiple instances, you need to turn on edit Multiple frames, and onion all from the selections at the bottom of the timeline panel (down by the horizontal scrollbar).

EDIT

In regards to your comment, my suggestion is indeed your solution, and attached is a screenshot of the "onion all"!

(click link to see screen shot, i can;t seem to put it right in this message)

alt text

Title: flash UI, how to drag symbol with tween


问:
How to access functions defined in ES6 module in a browser's JavaScript console?
I have a function that is defined in an ES6 module (sender.js) as follows:

```<code>function send() {
   // do stuff
}
export {send};
</code>```

This module is then used in the application's main JavaScript file app.js as follows:

```<code>import {send} from "./sender"
</code>```

The send function is available in the app.js file, however it is not in Firefox's Javascript console:

```<code>> send
ReferenceError: send is not defined
</code>```

How can I import the send function in the JavaScript console?

答:
You can set the specific function as global by assigning it to the global object –
in browsers it's window.

```<code>// To make one function available in the browser:
import { send } from "./sender.js"; // Might omit `.js` if using a bundler.
window.send = send;

// To make all functions available:
import * as sender from "./sender.js";
window.sender = sender;

// In the browser console:
window.sender.send()
</code>```

Note that while it might be useful in debugging, you shouldn't use that in production code – see Why are global variables considered bad practice?

ContentLicense: CC BY-SA 4.0

Body:
I have a function that is defined in an ES6 module (sender.js) as follows:

function send() {
   // do stuff
}
export {send};

This module is then used in the application's main JavaScript file app.js as follows:

import {send} from "./sender"

The send function is available in the app.js file, however it is not in Firefox's Javascript console:

> send
ReferenceError: send is not defined

How can I import the send function in the JavaScript console?

Body:
You can set the specific function as global by assigning it to the global object –
in browsers it's window.

// To make one function available in the browser:
import { send } from "./sender.js"; // Might omit `.js` if using a bundler.
window.send = send;

// To make all functions available:
import * as sender from "./sender.js";
window.sender = sender;

// In the browser console:
window.sender.send()

Note that while it might be useful in debugging, you shouldn't use that in production code – see Why are global variables considered bad practice?


问:
What type of query do NamedQueries use?
I'm using netbean's option to create entity classes from database and i'm not really used to this "dialect" for a query and i wanted to learn more about it's syntax. Can someone tell me what's the name of the "dialect" or syntax of this query?</p>

```<code>@NamedQueries({
@NamedQuery(name = "Users.findAll", query = "SELECT u FROM Users u")
, @NamedQuery(name = "Users.findByUserId", query = "SELECT u FROM Users u WHERE u.userId = :userId")
, @NamedQuery(name = "Users.findByName", query = "SELECT u FROM Users u WHERE u.name= :name")
, @NamedQuery(name = "Users.findBySurname", query = "SELECT u FROM Users u WHERE u.surname= :surname")
, @NamedQuery(name = "Users.findByEmail", query = "SELECT u FROM Users u WHERE u.email = :email")
, @NamedQuery(name = "Users.findByDateOfBirth", query = "SELECT u FROM Users u WHERE u.dateob= :dateob")
, @NamedQuery(name = "Users.findByPassword", query = "SELECT u FROM Users u WHERE u.password= :password")})
</code>```

答:
It is not SQL, it is JPQL (Java Persistence Query Language), which is defined in the JPA (Java Persistence API) specification.

Implementations of JPA (eg Hibernate) will transform this to an SQL query in the right SQL dialect for the data source they are accessing.

Title: What type of query do NamedQueries use?

Body:
I'm using netbean's option to create entity classes from database and i'm not really used to this "dialect" for a query and i wanted to learn more about it's syntax. Can someone tell me what's the name of the "dialect" or syntax of this query?

@NamedQueries({
@NamedQuery(name = "Users.findAll", query = "SELECT u FROM Users u")
, @NamedQuery(name = "Users.findByUserId", query = "SELECT u FROM Users u WHERE u.userId = :userId")
, @NamedQuery(name = "Users.findByName", query = "SELECT u FROM Users u WHERE u.name= :name")
, @NamedQuery(name = "Users.findBySurname", query = "SELECT u FROM Users u WHERE u.surname= :surname")
, @NamedQuery(name = "Users.findByEmail", query = "SELECT u FROM Users u WHERE u.email = :email")
, @NamedQuery(name = "Users.findByDateOfBirth", query = "SELECT u FROM Users u WHERE u.dateob= :dateob")
, @NamedQuery(name = "Users.findByPassword", query = "SELECT u FROM Users u WHERE u.password= :password")})


问:
C# Winform and Motorola MC9090-G implementation
I really need help on implementing Motorola MC9090-G into our software application.
This is my first time to work on this project so I don't know where to start.
Any help would really be appreciated.

I already downloaded the EMDK for the barcode scanner (.net v2.4).
What I'm trying to accomplish now is just to connect the MC9090-G to my simple test application which only have a textbox in it.
Scan a barcode, Display the scanned barcode in the textbox and that's it! I'm just asking is someone could give me a step by step process on how I could do this?
Most of the help that I'm getting from the internet is deploying an application in the scanner which I don't want to do for now.
I believe that doing this would be a great stepping stone for me!
so thanks in advance! :))

答: Have you looked at Motorola's sample applications?  I found the sample applications included with the EMDK very instructive when learning this myself.  They have some very basic samples that make it pretty obvious the handful of lines of code that are needed to access the barcode scanner hardware.</p>


问:
App store link for "rate/review this app"
I want to put a "rate/review this app" feature into my app.

Is there a way to link directly to the screen in the app store where they review the app?  So the customer doesn't have to click through the main app link.  Thanks.

EDIT: starting a bounty on this due to the lack of response.  Just to make sure it is crystal clear:  I am aware that I can link to my app's page in the store, and ask the user to click from there to the "review this app" screen.  The question is whether it is possible to link directly to the "review this app" screen so they don't have to click through anything.

答:
```<code>let rateUrl = "itms-apps://itunes.apple.com/app/idYOUR_APP_ID?action=write-review"
if UIApplication.shared.canOpenURL(rateUrl) {
    UIApplication.shared.openURL(rateUrl)
}
</code>```


问:
C++ callback to class function
I'm using the Arduino IDE and the things network arduino library to create a LoRa mote.

I have created a class which should handle all the LoRa related functions. In this class I need to handle a callback if i receive a downlink message.
The ttn library has the onMessage function which I want to setup in my init function and parse another function, which are a class member, called message.
I'm getting the error "invalid use of non-static member function".

```<code>// File: LoRa.cpp
#include "Arduino.h"
#include "LoRa.h"
#include <TheThingsNetwork.h>

TheThingsNetwork ttn(loraSerial,debugSerial,freqPlan);

LoRa::LoRa(){
}

void LoRa::init(){
  // Set the callback
  ttn.onMessage(this->message);
}

// Other functions

void LoRa::message(const uint8_t *payload, size_t size, port_t port)
{
  // Stuff to do when reciving a downlink
}
</code>```

and the header file

```<code>// File: LoRa.h
#ifndef LoRa_h
#define LoRa_h

#include "Arduino.h"
#include <TheThingsNetwork.h>

// Define serial interface for communication with LoRa module
#define loraSerial Serial1
#define debugSerial Serial

// define the frequency plan - EU or US. (TTN_FP_EU868 or TTN_FP_US915)
#define freqPlan TTN_FP_EU868

class LoRa{
  // const vars

  public:
    LoRa();

    void init();

    // other functions

    void message(const uint8_t *payload, size_t size, port_t port);

  private:
    // Private functions
};

#endif
</code>```

I have tried:

```<code>ttn.onMessage(this->message);
ttn.onMessage(LoRa::message);
ttn.onMessage(message);
</code>```

However none of them worked as I had expected.

答:
You should pass arguments to massage as indicated by its prototype:

void message(const uint8_t *payload, size_t size, port_t port);

Since massage returns void, it should not be used as an argument to other functions.

Title: C++ callback to class function

Body:
I'm using the Arduino IDE and the things network arduino library to create a LoRa mote.

I have created a class which should handle all the LoRa related functions. In this class I need to handle a callback if i receive a downlink message.
The ttn library has the onMessage function which I want to setup in my init function and parse another function, which are a class member, called message.
I'm getting the error "invalid use of non-static member function".

// File: LoRa.cpp
#include "Arduino.h"
#include "LoRa.h"
#include <TheThingsNetwork.h>

TheThingsNetwork ttn(loraSerial,debugSerial,freqPlan);

LoRa::LoRa(){
}

void LoRa::init(){
  // Set the callback
  ttn.onMessage(this->message);
}

// Other functions

void LoRa::message(const uint8_t *payload, size_t size, port_t port)
{
  // Stuff to do when reciving a downlink
}

and the header file

// File: LoRa.h
#ifndef LoRa_h
#define LoRa_h

#include "Arduino.h"
#include <TheThingsNetwork.h>

// Define serial interface for communication with LoRa module
#define loraSerial Serial1
#define debugSerial Serial

// define the frequency plan - EU or US. (TTN_FP_EU868 or TTN_FP_US915)
#define freqPlan TTN_FP_EU868

class LoRa{
  // const vars

  public:
    LoRa();

    void init();

    // other functions

    void message(const uint8_t *payload, size_t size, port_t port);

  private:
    // Private functions
};

#endif

I have tried:

ttn.onMessage(this->message);
ttn.onMessage(LoRa::message);
ttn.onMessage(message);

However none of them worked as I had expected.


问:
How to display a marker on openlayers map using address only
How to display a marker using address only and not longitude and latitude</p>

答:
OpenLayers does not support geocoding out of the box.

You could use third party libraries like this one:

https://github.com/jonataswalker/ol3-geocoder

Or geocoding services like Google's Geocoding service
 or OGC OpenLS, which you can see in a working example with an OpenLayers map here:

http://dev.openlayers.org/examples/openls.html


问:
ui router is not working
I am trying out following code for angular js, but not sure where I am getting wrong.
I have included ui-router and every required details. The states are defined for business and about us. Need help to find issue.

  var formModule = angular.module("formModule",['ui.router']);

formModule.config(['$stateProvider','$urlRouterProvider',
    function ($stateProvider,$urlRouterProvider ){
       $urlRouterProvider.otherwise("/");

       $stateProvider
               .state('business',{
                   url: '/business',
                   template: 'This is sample template',
               })
                .state('aboutus', {
                    url:'/aboutus',
                    template: '

{{director.name}}

',
                    controller: 'aboutUsController',
                });

    }]);

formModule.controller('aboutUsController',['$scope', function($scope){
    $scope.directors = [{name: 'Avdhut Sonpethkar'},
                        {name: 'Sphurti Sonpethkar'},
                        {name: 'Pruthvi Sonpethkar'},];
}]);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.1/angular.js"></script>

 <script src="https://cdnjs.cloudflare.com/ajax/libs/angular-ui-router/1.0.3/angular-ui-router.js"></script>

<div class="row">
               <div class="col-sm-12">
                   <ul>
                       <li >
                           Business
                       </li>

                       <li >
                           About us
                       </li>

                   </ul>
               </div>
           </div>
           <div class="row">
               <div class="col-sm-12" ui-view>

               </div>
           </div></code>```

The code is correct as per my understanding but not sure where getting it wrong.

答:
Remove the '.' prefix in ui-sref

Business

About us

Title: ui router is not working

Body:
I am trying out following code for angular js, but not sure where I am getting wrong.
I have included ui-router and every required details. The states are defined for business and about us. Need help to find issue.

  var formModule = angular.module("formModule",['ui.router']);

formModule.config(['$stateProvider','$urlRouterProvider',
    function ($stateProvider,$urlRouterProvider ){
       $urlRouterProvider.otherwise("/");

       $stateProvider
               .state('business',{
                   url: '/business',
                   template: 'This is sample template',
               })
                .state('aboutus', {
                    url:'/aboutus',
                    template: '

{{director.name}}

',
                    controller: 'aboutUsController',
                });

    }]);

formModule.controller('aboutUsController',['$scope', function($scope){
    $scope.directors = [{name: 'Avdhut Sonpethkar'},
                        {name: 'Sphurti Sonpethkar'},
                        {name: 'Pruthvi Sonpethkar'},];
}]);

                           Business

                           About us

The code is correct as per my understanding but not sure where getting it wrong.

Body:
Remove the '.' prefix in ui-sref

<a ui-sref="business">Business</a>

<a ui-sref="aboutus">About us</a>


问:
Show or hide UIBarButtonItem in UIToolbar programmatically
```<code>var toolBar: UIToolbar!
let nextBarButton = UIBarButtonItem(title: "Next", style: .Plain, target: self, action: "nextButtonPressed")
self.toolBar.setItems([nextBarButton], animated: true)
</code>```

How to hide nextButton in ToolBar?
I used the following code and it did not work.

```<code>self.toolbar.items.indexOf(1).hidden = true
</code>```

答:
This answer is inspired by this answer.

I will improve on it and make all the work programmatically. No need to update/set the class of the UIBarButtonItem instance to use the new subclass anymore.

We could just add isHidden attribute to the UIBarButtonItem. Then just use it as you want.

```<code>extension UIBarButtonItem {
   var isHidden: Bool = false {
      didSet {
          isEnabled = !isHidden
          tintColor = isHidden ? UIColor.clear : UIColor.black
      }
   }
}
</code>```

In your case, after you add the extension (outside any class). You could use it as:

```<code>self.toolbar.items.indexOf(1).isHidden = true
</code>```

Body:
var toolBar: UIToolbar!
let nextBarButton = UIBarButtonItem(title: "Next", style: .Plain, target: self, action: "nextButtonPressed")
self.toolBar.setItems([nextBarButton], animated: true)

How to hide nextButton in ToolBar?
I used the following code and it did not work.

self.toolbar.items.indexOf(1).hidden = true

Body:
This answer is inspired by this answer.

I will improve on it and make all the work programmatically. No need to update/set the class of the UIBarButtonItem instance to use the new subclass anymore.

We could just add isHidden attribute to the UIBarButtonItem. Then just use it as you want.

extension UIBarButtonItem {
   var isHidden: Bool = false {
      didSet {
          isEnabled = !isHidden
          tintColor = isHidden ? UIColor.clear : UIColor.black
      }
   }
}

In your case, after you add the extension (outside any class). You could use it as:

self.toolbar.items.indexOf(1).isHidden = true


问:
Does Grizzly Project take care of buffer overflow or denial of service attacks?
I have searched a lot, but still don't understand whether using Grizzly means that I am protected against those attacks or that I should do some more effort?

Currently, the only thing I do in my program is that I deploy my resource classes (annotated by @Path - I'm using Jersey) to the Grizzly, by the following code:

```<code>final Map<String, String> initParams = new HashMap<String, String>();
initParams.put("com.sun.jersey.config.property.packages","MyServer.resources");
SelectorThread threadSelector;
try{
    threadSelector = GrizzlyWebContainerFactory.create(
 uri, initParams);
    System.out.println("Press enter to stop server...");
    System.in.read();
    threadSelector.stopEndpoint();
}catch(...){...}
</code>```

In my resource methods, I may access a list of JAXB beans which I don't specify any size for it (I don't know if it is possible to check the size at this point to avoid getting large requests-if it is possible, it will be a great help if somebody tell me!), So, I'm afraid that an attacker may send consecutive and large requests (my normal request size should be less than 6 beans!) and result to denial of service - I am just starting to learn security risks and handling them, my first attempt!

I will check the size in the request handler method's body, which is after the request is completely received by the server. Is it enough?

The Grizzly documents say that it has a good buffer management (I may be mixing buffer overflow with denial of service), but I don't know whether I should set any settings or is it by default protecting?

EDIT:

I have received a good answer to part of my question, but, I'm still looking for some hints particularly about the Grizzly or Jersey and whether there is a single point of entry in which I can make some checks for all incoming requests?

Thanks!

答:
If you are using Java you are pretty much immune from classic buffer overrun attacks, unless you are using native code libraries to process stuff you get from the net.

On the other hand, protecting yourself from denial of service attacks tends to require a whole-of-system approach.

EDIT

By "whole of system" approach, I mean one that takes account of the impact on your network bandwidth, infrastructure and back-end servers as well as just your web server.  For instance, an attack directed at your network bandwith or DNS can take you off the air irrespectively of how you implement your webserver.  At the other end, someone could target aspects of your web application; e.g. knowledge that a particular query is very expensive ... or that it leaks resources and eventually crashes your application.

(I'm not an expert on this.  I'm just trying to point out that just looking at your web server platform is not sufficient ... if you really care about defending against DDoS.)

Body:
I have searched a lot, but still don't understand whether using Grizzly means that I am protected against those attacks or that I should do some more effort?

Currently, the only thing I do in my program is that I deploy my resource classes (annotated by @Path - I'm using Jersey) to the Grizzly, by the following code:

final Map<String, String> initParams = new HashMap<String, String>();
initParams.put("com.sun.jersey.config.property.packages","MyServer.resources");
SelectorThread threadSelector;
try{
    threadSelector = GrizzlyWebContainerFactory.create(
 uri, initParams);
    System.out.println("Press enter to stop server...");
    System.in.read();
    threadSelector.stopEndpoint();
}catch(...){...}

In my resource methods, I may access a list of JAXB beans which I don't specify any size for it (I don't know if it is possible to check the size at this point to avoid getting large requests-if it is possible, it will be a great help if somebody tell me!), So, I'm afraid that an attacker may send consecutive and large requests (my normal request size should be less than 6 beans!) and result to denial of service - I am just starting to learn security risks and handling them, my first attempt!

I will check the size in the request handler method's body, which is after the request is completely received by the server. Is it enough?

The Grizzly documents say that it has a good buffer management (I may be mixing buffer overflow with denial of service), but I don't know whether I should set any settings or is it by default protecting?

EDIT:

I have received a good answer to part of my question, but, I'm still looking for some hints particularly about the Grizzly or Jersey and whether there is a single point of entry in which I can make some checks for all incoming requests?

Thanks!


问:
Clean way to implement async indexedDB in class
I have a class that loads indexedDB. Before methods in the class can access it, I need to have indexedDB loaded beforehand. Currently I'm using an init() method prior to any other method that does not have this.db initialized.

I'm looking for a cleaner way to implement what I have, which definitely isn't DRY. Essentially every method is currently implemented with the same code pattern below.

Problem points are:

The requirement of another method init() in order to properly
handle the intialization of indexedDB.

The if (!this.db) { segment that ends up repeating itself later.

```<code>export default class Persist {
  constructor(storage) {
    if (storage) {
      this.storage = storage;
    }
    else {
      throw new Error('A storage object must be passed to new Persist()');
    }
  }

  // needed to ensure that indexedDB is initialized before other methods can access it.
  init () {
    // initialize indexedDB:
    const DBOpenRequest = this.storage.open('db', 1);

    DBOpenRequest.onupgradeneeded = () => {
      const db = DBOpenRequest.result;
      db.createObjectStore('db', { keyPath: 'id', autoIncrement: true });
    };

    return new Promise((resolve, reject) => {
      DBOpenRequest.onerror = event => {
        reject(event);
      };

      DBOpenRequest.onsuccess = event => {
        console.log(`IndexedDB successfully opened: ${event.target.result}`);
        resolve(event.result);
        this.db = DBOpenRequest.result;
      };
    });
  }

  toStorage(session) {
    if (!this.db) {
      return this.init().then(() => {
        const db = this.db;
        const tx = db.transaction('db', 'readwrite');
        const store = tx.objectStore('db');
        const putData = store.put(session.toJS());

        return new Promise((resolve, reject) => {
          putData.onsuccess = () => {
            resolve(putData.result);
          };

          putData.onerror = () => {
            reject(putData.error);
          };
        });
      });
    }

    // basically a repeat of above
    const db = this.db;
    const tx = db.transaction('db', 'readwrite');
    const store = tx.objectStore('db');
    const putData = store.put(session.toJS());

    return new Promise((resolve, reject) => {
      putData.onsuccess = () => {
        resolve(putData.result);
      };

      putData.onerror = () => {
        reject(putData.error);
      };
    });
  }
</code>```

答:
indexedDB provides asynchronous functions. indexedDB.open is an asynchronous function. It looks like you are trying to work with indexedDB in a non-asynchronous manner. Instead of storing the IDBDatabase variable as a property of the instance of your class, just return it as the resolve value and manage it external to the class.

```<code>function connect(name, version) {
  return new Promise((resolve, reject) => {
    const request = indexedDB.open(name, version);
    request.onupgradeneeded = myUpgradeHandlerFunction;
    request.onsuccess = () => resolve(request.result);
    request.onerror = () => reject(request.error);
    request.onblocked = () => { console.log('blocked'); };
  });
}

function doStuffWithConn(conn, value) {
  return new Promise((resolve, reject) => {
    const tx = conn.transaction(...);
    const store = tx.objectStore(...);
    const request = store.put(value);
    request.onsuccess = () => resolve(request.result);
    request.onerror = () => reject(request.error);
  });
}

async function putValue(value) {
  let conn;
  try {
    conn = await connect(...);
    await doStuffWithConn(conn, value);
  } catch(exception) {
    console.error(exception);
  } finally {
    if(conn)
      conn.close();
  }
}
</code>```

Body:
I have a class that loads indexedDB. Before methods in the class can access it, I need to have indexedDB loaded beforehand. Currently I'm using an init() method prior to any other method that does not have this.db initialized.

I'm looking for a cleaner way to implement what I have, which definitely isn't DRY. Essentially every method is currently implemented with the same code pattern below.

Problem points are:

The requirement of another method init() in order to properly
handle the intialization of indexedDB.

The if (!this.db) { segment that ends up repeating itself later.

export default class Persist {
  constructor(storage) {
    if (storage) {
      this.storage = storage;
    }
    else {
      throw new Error('A storage object must be passed to new Persist()');
    }
  }

  // needed to ensure that indexedDB is initialized before other methods can access it.
  init () {
    // initialize indexedDB:
    const DBOpenRequest = this.storage.open('db', 1);

    DBOpenRequest.onupgradeneeded = () => {
      const db = DBOpenRequest.result;
      db.createObjectStore('db', { keyPath: 'id', autoIncrement: true });
    };

    return new Promise((resolve, reject) => {
      DBOpenRequest.onerror = event => {
        reject(event);
      };

      DBOpenRequest.onsuccess = event => {
        console.log(`IndexedDB successfully opened: ${event.target.result}`);
        resolve(event.result);
        this.db = DBOpenRequest.result;
      };
    });
  }

  toStorage(session) {
    if (!this.db) {
      return this.init().then(() => {
        const db = this.db;
        const tx = db.transaction('db', 'readwrite');
        const store = tx.objectStore('db');
        const putData = store.put(session.toJS());

        return new Promise((resolve, reject) => {
          putData.onsuccess = () => {
            resolve(putData.result);
          };

          putData.onerror = () => {
            reject(putData.error);
          };
        });
      });
    }

    // basically a repeat of above
    const db = this.db;
    const tx = db.transaction('db', 'readwrite');
    const store = tx.objectStore('db');
    const putData = store.put(session.toJS());

    return new Promise((resolve, reject) => {
      putData.onsuccess = () => {
        resolve(putData.result);
      };

      putData.onerror = () => {
        reject(putData.error);
      };
    });
  }

Body:
indexedDB provides asynchronous functions. indexedDB.open is an asynchronous function. It looks like you are trying to work with indexedDB in a non-asynchronous manner. Instead of storing the IDBDatabase variable as a property of the instance of your class, just return it as the resolve value and manage it external to the class.

function connect(name, version) {
  return new Promise((resolve, reject) => {
    const request = indexedDB.open(name, version);
    request.onupgradeneeded = myUpgradeHandlerFunction;
    request.onsuccess = () => resolve(request.result);
    request.onerror = () => reject(request.error);
    request.onblocked = () => { console.log('blocked'); };
  });
}

function doStuffWithConn(conn, value) {
  return new Promise((resolve, reject) => {
    const tx = conn.transaction(...);
    const store = tx.objectStore(...);
    const request = store.put(value);
    request.onsuccess = () => resolve(request.result);
    request.onerror = () => reject(request.error);
  });
}

async function putValue(value) {
  let conn;
  try {
    conn = await connect(...);
    await doStuffWithConn(conn, value);
  } catch(exception) {
    console.error(exception);
  } finally {
    if(conn)
      conn.close();
  }
}


问:
search order by title youtube api
how do I order by title in php in the youtube api? In the documentation in the search.list it says order is an optional parameter. How do I order what I print by title or date?
 try {</p>

```<code>// Call the search.list method to retrieve results matching the specified
// query term.
$searchResponse = $youtube->search->listSearch('id,snippet', array(
  'q' => $_GET['q'],
  'maxResults' => $_GET['maxResults'],
));

$videos = '';
$channels = '';
$playlists = '';
// Add each result to the appropriate list, and then display the lists of
// matching videos, channels, and playlists.
foreach ($searchResponse['items'] as $searchResult) {
  switch ($searchResult['id']['snippet']) {
    case 'youtube#video':
      $videos .= sprintf('<li>title=%s link = http://youtube.com/watch?v=%s/ channelid = %s</li><br> ',
          $searchResult['snippet']['title'], $searchResult['id']['videoId'], $searchResult['snippet']['channelTitle']);
      break;
</code>```

答:
You can use the order parameter to sort by title, date, rating, relevance, videoCount, and viewCount. Take a look at the documentation for order: https://developers.google.com/youtube/v3/docs/search/list

This code sorts by title

```<code>// Call the search.list method to retrieve results matching the specified
// query term.
$searchResponse = $youtube->search->listSearch('id,snippet', array(
  'q' => $_GET['q'],
  'maxResults' => $_GET['maxResults'],
  'order' => 'title'
));
</code>```

This code sorts by date

```<code>// Call the search.list method to retrieve results matching the specified
// query term.
$searchResponse = $youtube->search->listSearch('id,snippet', array(
  'q' => $_GET['q'],
  'maxResults' => $_GET['maxResults'],
  'order' => 'date'
));
</code>```

Title: search order by title youtube api

Body:
how do I order by title in php in the youtube api? In the documentation in the search.list it says order is an optional parameter. How do I order what I print by title or date?
 try {

// Call the search.list method to retrieve results matching the specified
// query term.
$searchResponse = $youtube->search->listSearch('id,snippet', array(
  'q' => $_GET['q'],
  'maxResults' => $_GET['maxResults'],
));

$videos = '';
$channels = '';
$playlists = '';
// Add each result to the appropriate list, and then display the lists of
// matching videos, channels, and playlists.
foreach ($searchResponse['items'] as $searchResult) {
  switch ($searchResult['id']['snippet']) {
    case 'youtube#video':
      $videos .= sprintf('
title=%s link = http://youtube.com/watch?v=%s/ channelid = %s

 ',
          $searchResult['snippet']['title'], $searchResult['id']['videoId'], $searchResult['snippet']['channelTitle']);
      break;

Body:
You can use the order parameter to sort by title, date, rating, relevance, videoCount, and viewCount. Take a look at the documentation for order: https://developers.google.com/youtube/v3/docs/search/list

This code sorts by title

// Call the search.list method to retrieve results matching the specified
// query term.
$searchResponse = $youtube->search->listSearch('id,snippet', array(
  'q' => $_GET['q'],
  'maxResults' => $_GET['maxResults'],
  'order' => 'title'
));

This code sorts by date

// Call the search.list method to retrieve results matching the specified
// query term.
$searchResponse = $youtube->search->listSearch('id,snippet', array(
  'q' => $_GET['q'],
  'maxResults' => $_GET['maxResults'],
  'order' => 'date'
));


问:
Python difflib to compare two csv files and highlight the world level differences in HTML output
I am not an expertise in Python and I tried searching my best to find the answer, but couldn't find. Pardon me, If this is a duplicate question and point me in the right direction, if you can.

I am trying to compare two CSV files using Python Difflib and generating the Diff output as a HTML page. The current difflib module has the inbuilt options as -m to generate the HTML output of the two csv files side by side by highlighting the differences.

However, the difflib uses difflib.SequenceMatcher  to find the differences and create a HTML file using difflib.HtmlDiff.make_file . But, the output for that it produces is not that I want.

The output I am getting currently from the difflib is :The Default Python DIFFLIB HTML output is Here.

However, The output I want is : I am looking for a word level highlight instead of the changes that are highlighted either at character level or a sequence highlight. I am looking to highlight the WHOLE WORD if any changed that happened between old file and new file.

The changes that I want to highlight is: A word Level highlight of the text.

Please help me in this regard, whether this is really possible with difflib or do I have to use any other tools/modules. I tried using vimdiff and other plugins, but I am left with nothing. I am open to any thing here.

The code I am using is from PythonDiffLib docs page.

```<code>import sys, os, time, difflib, optparse
  def main():
   ..
   ..
   ..
    n = options.lines //I used this n = ZERO.
    fromfile, tofile = args # as specified in the usage string

    # we're passing these as arguments to the diff function
    fromdate = time.ctime(os.stat(fromfile).st_mtime)
    todate = time.ctime(os.stat(tofile).st_mtime)
    fromlines = open(fromfile, 'U').readlines()
    tolines = open(tofile, 'U').readlines()

    diff = difflib.HtmlDiff().make_file(fromlines, tolines, fromfile,
                                            tofile, context=TRUE,
                                            numlines=0)

    # we're using writelines because diff is a generator
    sys.stdout.writelines(diff)
</code>```

`
Old.csv

```<code>refno,title,author,year,price
1001,CPP,MILTON,2008,456
1002,JAVA,Gilson,2002,456
1003,Adobe Flex,2010,566
1004,General Knowledge,Sinson,2007,465
1005,Actionscript,Gilto,2008,480
</code>```

new.csv

```<code>refno,title,author,year,price
1001,CPP,MILTON,2010,456,2008
1002,JAVA,Gilson,2002
1003,Adobe Flexi,Johnson,2010,566
1004,General Knowledge,Simpson,2007,465
105,Action script,Gilto,2008,480
2000,Drama,DayoNe,,2020,560
</code>```

I am also adding the Default HTML DIFF Output and Expected HTML DIFF output below.

Default HTML DIFF Output from DIFFLIB:

```<code><html>

<head>
<meta http-equiv="Content-Type"
content="text/html; charset=ISO-8859-1" />
<title></title>
<style type="text/css">
table.diff {font-family:Courier; border:medium;}
.diff_header {background-color:#e0e0e0}
td.diff_header {text-align:right}
.diff_next {background-color:#c0c0c0}
.diff_add {background-color:#aaffaa}
.diff_chg {background-color:#ffff77}
.diff_sub {background-color:#ffaaaa}
</style>
</head>

<body>

<table class="diff" id="difflib_chg_to0__top"
cellspacing="0" cellpadding="0" rules="groups" >
<colgroup></colgroup> <colgroup></colgroup> <colgroup></colgroup>
<colgroup></colgroup> <colgroup></colgroup> <colgroup></colgroup>
<thead><tr><th class="diff_next"><br /></th><th colspan="2" class="diff_header">old.csv</th><th class="diff_next"><br /></th><th colspan="2" class="diff_header">new.csv</th></tr></thead>
<tbody>
<tr><td class="diff_next" id="difflib_chg_to0__0"><a href="#difflib_chg_to0__top">t</a></td><td class="diff_header" id="from0_2">2</td><td nowrap="nowrap">1001,CPP,MILTON,200<span class="diff_sub">8</span>,456</td><td class="diff_next"><a href="#difflib_chg_to0__top">t</a></td><td class="diff_header" id="to0_2">2</td><td nowrap="nowrap">1001,CPP,MILTON,20<span class="diff_add">1</span>0,456<span class="diff_add">,2008</span></td></tr>
<tr><td class="diff_next"></td><td class="diff_header" id="from0_3">3</td><td nowrap="nowrap">1002,JAVA,Gilson,2002<span class="diff_sub">,456</span></td><td class="diff_next"></td><td class="diff_header" id="to0_3">3</td><td nowrap="nowrap">1002,JAVA,Gilson,2002</td></tr>
<tr><td class="diff_next"></td><td class="diff_header" id="from0_4">4</td><td nowrap="nowrap">1003,Adobe Flex,2010,566</td><td class="diff_next"></td><td class="diff_header" id="to0_4">4</td><td nowrap="nowrap">1003,Adobe Flex<span class="diff_add">i,Johnson</span>,2010,566</td></tr>
<tr><td class="diff_next"></td><td class="diff_header" id="from0_5">5</td><td nowrap="nowrap">1004,General Knowledge,Si<span class="diff_chg">n</span>son,2007,465</td><td class="diff_next"></td><td class="diff_header" id="to0_5">5</td><td nowrap="nowrap">1004,General Knowledge,Si<span class="diff_chg">mp</span>son,2007,465</td></tr>
<tr><td class="diff_next"></td><td class="diff_header" id="from0_6">6</td><td nowrap="nowrap">1<span class="diff_sub">0</span>05,Actionscript,Gilto,2008,480</td><td class="diff_next"></td><td class="diff_header" id="to0_6">6</td><td nowrap="nowrap">105,Action<span class="diff_add"> </span>script,Gilto,2008,480</td></tr>
<tr><td class="diff_next"></td><td class="diff_header"></td><td nowrap="nowrap"></td><td class="diff_next"></td><td class="diff_header" id="to0_7">7</td><td nowrap="nowrap"><span class="diff_add">2000,Drama,DayoNe,,2020,560</span></td></tr>
</tbody>
</table>

</body>

</html>
</code>```

Expected  HTML DIFF Output from DIFFLIB:

```<code><html>

<head>
<meta http-equiv="Content-Type"
content="text/html; charset=ISO-8859-1" />
<title></title>
<style type="text/css">
table.diff {font-family:Courier; border:medium;}
.diff_header {background-color:#e0e0e0}
td.diff_header {text-align:right}
.diff_next {background-color:#c0c0c0}
.diff_add {background-color:#aaffaa}
.diff_chg {background-color:#ffff77}
.diff_sub {background-color:#ffaaaa}
</style>
</head>

<body>

<table class="diff" id="difflib_chg_to0__top"
cellspacing="0" cellpadding="0" rules="groups" >
<colgroup></colgroup> <colgroup></colgroup> <colgroup></colgroup>
<colgroup></colgroup> <colgroup></colgroup> <colgroup></colgroup>
<thead><tr><th class="diff_next"><br /></th><th colspan="2" class="diff_header">old.csv</th><th class="diff_next"><br /></th><th colspan="2" class="diff_header">new.csv</th></tr></thead>
<tbody>
<tr><td class="diff_next" id="difflib_chg_to0__0"><a href="#difflib_chg_to0__top">t</a></td><td class="diff_header" id="from0_2">2</td><td nowrap="nowrap">1001,CPP,MILTON,<span class="diff_sub">2008</span>,456</td><td class="diff_next"><a href="#difflib_chg_to0__top">t</a></td><td class="diff_header" id="to0_2">2</td><td nowrap="nowrap">1001,CPP,MILTON,<span class="diff_add">2010</span>,456<span class="diff_add">,2008</span></td></tr>
<tr><td class="diff_next"></td><td class="diff_header" id="from0_3">3</td><td nowrap="nowrap">1002,JAVA,Gilson,2002<span class="diff_sub">,456</span></td><td class="diff_next"></td><td class="diff_header" id="to0_3">3</td><td nowrap="nowrap">1002,JAVA,Gilson,2002</td></tr>
<tr><td class="diff_next"></td><td class="diff_header" id="from0_4">4</td><td nowrap="nowrap">1003,<span class="diff_sub">Adobe Flex</span>,2010,566</td><td class="diff_next"></td><td class="diff_header" id="to0_4">4</td><td nowrap="nowrap">1003,<span class="diff_add">Adobe Flexi</span>,<span class="diff_add">Johnson</span>,2010,566</td></tr>
<tr><td class="diff_next"></td><td class="diff_header" id="from0_5">5</td><td nowrap="nowrap">1004,General Knowledge,<span class="diff_sub">Sinson</span>,2007,465</td><td class="diff_next"></td><td class="diff_header" id="to0_5">5</td><td nowrap="nowrap">1004,General Knowledge,<span class="diff_add">Simpson</span>,2007,465</td></tr>
<tr><td class="diff_next"></td><td class="diff_header" id="from0_6">6</td><td nowrap="nowrap"><span class="diff_sub">1005</span>,<span class="diff_sub">Actionscript</span>,Gilto,2008,480</td><td class="diff_next"></td><td class="diff_header" id="to0_6">6</td><td nowrap="nowrap"><span class="diff_add">105</span>,<span class="diff_add">Action script</span>,Gilto,2008,480</td></tr>
<tr><td class="diff_next"></td><td class="diff_header"></td><td nowrap="nowrap"></td><td class="diff_next"></td><td class="diff_header" id="to0_7">7</td><td nowrap="nowrap"><span class="diff_add">2000,Drama,DayoNe,,2020,560</span></td></tr>
</tbody>
</table>

</body>

</html>
</code>```

答:
Question:  I am looking for a word level highlight

Implements class Comma_HtmlDiff, expand Highlight to Comma boundaries:

You have to Overload difflib.ndiff.

Note: Only expand the first highlighted Part is implemented.

  If difflib.ndiff highlights across Comma, this is not corrected.

```<code>class Comma_HtmlDiff(difflib.HtmlDiff):
    def __init__(self, tabsize=8, wrapcolumn=None, linejunk=None,
             charjunk=difflib.IS_CHARACTER_JUNK):
        setattr(difflib, '_ndiff', difflib.ndiff)
        setattr(difflib, 'ndiff', self.ndiff)
        super().__init__(tabsize, wrapcolumn, linejunk, charjunk)

    def ndiff(self, a, b, linejunk=None, charjunk=difflib.IS_CHARACTER_JUNK):
        _line = ''
        for line in difflib._ndiff(a, b, linejunk, charjunk):
            if line.startswith('-'):
                _d = '-'
                _line = line
            elif line.startswith('+'):
                _d = '+'
                _line = line

            if line.startswith('?'):
                dp = line.find(_d)
                if dp == -1:
                    _d = '+'
                    dp = line.find('^')
                dpl = _line.rfind(',', 0, dp)
                if dpl == -1:
                    dpl = 2
                else:
                    dpl += 1
                dpr = _line.find(',', dp)
                if dpr == dp:
                    _d = ' '
                    dpl = dp
                    dpr = dp+1

                dpw = dpr - dpl
                line = line[:dpl] + _d*dpw + line[dpr:]

            yield line

# Usage
diff = Comma_HtmlDiff().make_file(fromlines, tolines, fromfile,
                                    tofile, context=True,
                                    numlines=0)
</code>```

Output:

Tested with Python: 3.4.2

Body:
I am not an expertise in Python and I tried searching my best to find the answer, but couldn't find. Pardon me, If this is a duplicate question and point me in the right direction, if you can.

I am trying to compare two CSV files using Python Difflib and generating the Diff output as a HTML page. The current difflib module has the inbuilt options as -m to generate the HTML output of the two csv files side by side by highlighting the differences.

However, the difflib uses difflib.SequenceMatcher  to find the differences and create a HTML file using difflib.HtmlDiff.make_file . But, the output for that it produces is not that I want.

The output I am getting currently from the difflib is :The Default Python DIFFLIB HTML output is Here.

However, The output I want is : I am looking for a word level highlight instead of the changes that are highlighted either at character level or a sequence highlight. I am looking to highlight the WHOLE WORD if any changed that happened between old file and new file.

The changes that I want to highlight is: A word Level highlight of the text.

Please help me in this regard, whether this is really possible with difflib or do I have to use any other tools/modules. I tried using vimdiff and other plugins, but I am left with nothing. I am open to any thing here.

The code I am using is from PythonDiffLib docs page.

import sys, os, time, difflib, optparse
  def main():
   ..
   ..
   ..
    n = options.lines //I used this n = ZERO.
    fromfile, tofile = args # as specified in the usage string

    # we're passing these as arguments to the diff function
    fromdate = time.ctime(os.stat(fromfile).st_mtime)
    todate = time.ctime(os.stat(tofile).st_mtime)
    fromlines = open(fromfile, 'U').readlines()
    tolines = open(tofile, 'U').readlines()

    diff = difflib.HtmlDiff().make_file(fromlines, tolines, fromfile,
                                            tofile, context=TRUE,
                                            numlines=0)

    # we're using writelines because diff is a generator
    sys.stdout.writelines(diff)

`
Old.csv

refno,title,author,year,price
1001,CPP,MILTON,2008,456
1002,JAVA,Gilson,2002,456
1003,Adobe Flex,2010,566
1004,General Knowledge,Sinson,2007,465
1005,Actionscript,Gilto,2008,480

new.csv

refno,title,author,year,price
1001,CPP,MILTON,2010,456,2008
1002,JAVA,Gilson,2002
1003,Adobe Flexi,Johnson,2010,566
1004,General Knowledge,Simpson,2007,465
105,Action script,Gilto,2008,480
2000,Drama,DayoNe,,2020,560

I am also adding the Default HTML DIFF Output and Expected HTML DIFF output below.

Default HTML DIFF Output from DIFFLIB:

<meta http-equiv="Content-Type"
content="text/html; charset=ISO-8859-1" />
<title></title>

<colgroup></colgroup> <colgroup></colgroup> <colgroup></colgroup>
<colgroup></colgroup> <colgroup></colgroup> <colgroup></colgroup>

	old.csv
	new.csv

t	2	1001,CPP,MILTON,2008,456	t	2	1001,CPP,MILTON,2010,456,2008

	3	1002,JAVA,Gilson,2002,456		3	1002,JAVA,Gilson,2002

	4	1003,Adobe Flex,2010,566		4	1003,Adobe Flexi,Johnson,2010,566

	5	1004,General Knowledge,Sinson,2007,465		5	1004,General Knowledge,Simpson,2007,465

	6	1005,Actionscript,Gilto,2008,480		6	105,Action script,Gilto,2008,480

				7	2000,Drama,DayoNe,,2020,560

Expected  HTML DIFF Output from DIFFLIB:

<meta http-equiv="Content-Type"
content="text/html; charset=ISO-8859-1" />
<title></title>

<colgroup></colgroup> <colgroup></colgroup> <colgroup></colgroup>
<colgroup></colgroup> <colgroup></colgroup> <colgroup></colgroup>

	old.csv
	new.csv

t	2	1001,CPP,MILTON,2008,456	t	2	1001,CPP,MILTON,2010,456,2008

	3	1002,JAVA,Gilson,2002,456		3	1002,JAVA,Gilson,2002

	4	1003,Adobe Flex,2010,566		4	1003,Adobe Flexi,Johnson,2010,566

	5	1004,General Knowledge,Sinson,2007,465		5	1004,General Knowledge,Simpson,2007,465

	6	1005,Actionscript,Gilto,2008,480		6	105,Action script,Gilto,2008,480

				7	2000,Drama,DayoNe,,2020,560

Body:
Question:  I am looking for a word level highlight

Implements class Comma_HtmlDiff, expand Highlight to Comma boundaries:

You have to Overload difflib.ndiff.

Note: Only expand the first highlighted Part is implemented.

  If difflib.ndiff highlights across Comma, this is not corrected.

class Comma_HtmlDiff(difflib.HtmlDiff):
    def __init__(self, tabsize=8, wrapcolumn=None, linejunk=None,
             charjunk=difflib.IS_CHARACTER_JUNK):
        setattr(difflib, '_ndiff', difflib.ndiff)
        setattr(difflib, 'ndiff', self.ndiff)
        super().__init__(tabsize, wrapcolumn, linejunk, charjunk)

    def ndiff(self, a, b, linejunk=None, charjunk=difflib.IS_CHARACTER_JUNK):
        _line = ''
        for line in difflib._ndiff(a, b, linejunk, charjunk):
            if line.startswith('-'):
                _d = '-'
                _line = line
            elif line.startswith('+'):
                _d = '+'
                _line = line

            if line.startswith('?'):
                dp = line.find(_d)
                if dp == -1:
                    _d = '+'
                    dp = line.find('^')
                dpl = _line.rfind(',', 0, dp)
                if dpl == -1:
                    dpl = 2
                else:
                    dpl += 1
                dpr = _line.find(',', dp)
                if dpr == dp:
                    _d = ' '
                    dpl = dp
                    dpr = dp+1

                dpw = dpr - dpl
                line = line[:dpl] + _d*dpw + line[dpr:]

            yield line

# Usage
diff = Comma_HtmlDiff().make_file(fromlines, tolines, fromfile,
                                    tofile, context=True,
                                    numlines=0)

Output:

Tested with Python: 3.4.2