问:
Inheritance and pointers
I have code like this:

```<code>class Human
{
    protected:
        int age;
        std::string sex;
    public:
        virtual void speak() = 0;
};
class Child:public Human
{
    public:
        void speak(){std::cout << "I am Child\n";}
};
class Man:public Human
{
    public:
        void speak(){std::cout << "I am Man\n";}
};
class Woman:public Human
{
    public:
        void speak(){std::cout << "I am Woman\n";}
};
(don't know, std::shared_ptr<Human> maybe?) operator*(std::shared_ptr<Child> &b, int x)
{
    b->setAge(b->getAge()+x);
    if(b->getAge()>18 && b->getSex()=="Man")
    {
        return (i want b to become std::shared_ptr<Man>)
    }
    if(b->getAge()>18 && b->getSex()=="Woman")
    {
        return (here I want b to become std::shared_ptr<Woman>);
    }
    return;
}
int main(){
    auto x = std::make_shared<Child>;
    x*19;
}
</code>```

I know it seems odd, but it's the simplest case i can think of, without having to write down all code i'm struggling with rn. Could someone explain, what type should overload be and how to change shared_ptr type, knowing they derive from same parent?

答:
Objects cannot change type.  A Child object will always be a Child object.  What you can do is create a new object with the properties you want and return that:

```<code>std::shared_ptr<Human> operator*(std::shared_ptr<Human> b, int x)
{
    b->setAge(b->getAge()+x);
    if(b->getAge()>18 && b->getSex()=="Man") {
        return std::make_shared<Man>(b->getAge());
    } else if(b->getAge()>18 && b->getSex()=="Woman") {
        return std::make_shared<Woman>(b->getAge());
    } else {
       return b;
    }
}

int main(){
    std::shared_ptr<Human> x = std::make_shared<Child>;
    x = x*19;
}
</code>```

This doesn't seem like a good design though.  A Human's status as a child or adult would be better represented as an attribute of the object or by a function that checks if age is greater than 18.

Title: Inheritance and pointers

Body:
I have code like this:

class Human
{
    protected:
        int age;
        std::string sex;
    public:
        virtual void speak() = 0;
};
class Child:public Human
{
    public:
        void speak(){std::cout << "I am Child\n";}
};
class Man:public Human
{
    public:
        void speak(){std::cout << "I am Man\n";}
};
class Woman:public Human
{
    public:
        void speak(){std::cout << "I am Woman\n";}
};
(don't know, std::shared_ptr<Human> maybe?) operator*(std::shared_ptr<Child> &b, int x)
{
    b->setAge(b->getAge()+x);
    if(b->getAge()>18 && b->getSex()=="Man")
    {
        return (i want b to become std::shared_ptr<Man>)
    }
    if(b->getAge()>18 && b->getSex()=="Woman")
    {
        return (here I want b to become std::shared_ptr<Woman>);
    }
    return;
}
int main(){
    auto x = std::make_shared<Child>;
    x*19;
}

I know it seems odd, but it's the simplest case i can think of, without having to write down all code i'm struggling with rn. Could someone explain, what type should overload be and how to change shared_ptr type, knowing they derive from same parent?

Body:
Objects cannot change type.  A Child object will always be a Child object.  What you can do is create a new object with the properties you want and return that:

std::shared_ptr<Human> operator*(std::shared_ptr<Human> b, int x)
{
    b->setAge(b->getAge()+x);
    if(b->getAge()>18 && b->getSex()=="Man") {
        return std::make_shared<Man>(b->getAge());
    } else if(b->getAge()>18 && b->getSex()=="Woman") {
        return std::make_shared<Woman>(b->getAge());
    } else {
       return b;
    }
}

int main(){
    std::shared_ptr<Human> x = std::make_shared<Child>;
    x = x*19;
}

This doesn't seem like a good design though.  A Human's status as a child or adult would be better represented as an attribute of the object or by a function that checks if age is greater than 18.


来源: stackexchange

问:
AutoMapper use parent class mapping in child classes
I've got two parent classes

```<code>class Settings
{
     public Field
}
</code>```

and

```<code>class SettingsDb
{
    public  FieldDB
}
</code>```

and Field mapped width  FieldDB by ForMember expression

```<code>CreateMap<SettingsDb, Settings>()
                 .ForMember(dest => dest.Field,
                 opt => opt.MapFrom(src => some lambda with src.FieldDb));
</code>```

I also have two child classes

```<code>class AdminSettings : Setting
{
inherits Field
}

class AdminSettingsDb : SettingDb
{
inherits FieldDb
}
</code>```

how can I map AdminSettings with AdminSettingsDb  without doing ForMember again for this inherited fields?

```<code>CreateMap<AdminSettings, AdminSettingsDb>();
</code>```

now this fields are empty after mapping

答:
Simpler solution</p>

```<code>   CreateMap<BaseEntity, BaseDto>()
       .ForMember(dest => dest.SomeMember, opt => opt.MapFrom(src => src.OtherMember));

    CreateMap<DerivedEntity, DerivedDto>()
        .IncludeBase<BaseEntity, BaseDto>();
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I've got two parent classes

class Settings
{
     public Field
}

and

class SettingsDb
{
    public  FieldDB
}

and Field mapped width  FieldDB by ForMember expression

CreateMap<SettingsDb, Settings>()
                 .ForMember(dest => dest.Field,
                 opt => opt.MapFrom(src => some lambda with src.FieldDb));

I also have two child classes

class AdminSettings : Setting
{
inherits Field
}

class AdminSettingsDb : SettingDb
{
inherits FieldDb
}

how can I map AdminSettings with AdminSettingsDb  without doing ForMember again for this inherited fields?

CreateMap<AdminSettings, AdminSettingsDb>();

now this fields are empty after mapping

Body:
Simpler solution

   CreateMap<BaseEntity, BaseDto>()
       .ForMember(dest => dest.SomeMember, opt => opt.MapFrom(src => src.OtherMember));

    CreateMap<DerivedEntity, DerivedDto>()
        .IncludeBase<BaseEntity, BaseDto>();


问:
Replace random value in string with random value
virus is supposed to be a string of nucleotides, and the function should return a string consisting of the same amount of nucleotides, but one is changed.

```<code>def mutate(virus):
    mutations = ['A', 'T', 'C', 'G']
    virus.split
    random.randrange(1, stop=len(virus), step=1) = random.choice(mutations)
</code>```

so for example if the virus is ATCG it should return something like ATCC or GTCG, how can I go about this, I tried making virus into a list, and replacing a random variable in it with a random of my possible mutations list.

So it should probably make a list from the string virus, do a mutation, put the list back into a string and return the string.

答:
You can generate a random index to replace at and a random value:</p>

```<code>import random
def mutate(virus):
   mutations = ['A', 'T', 'C', 'G']
   i = random.randint(0, len(virus)-1)
   val = random.choice(mutations)
   return ''.join(val if c == i else a for c, a in enumerate(virus))
</code>```

Body:
virus is supposed to be a string of nucleotides, and the function should return a string consisting of the same amount of nucleotides, but one is changed.

def mutate(virus):
    mutations = ['A', 'T', 'C', 'G']
    virus.split
    random.randrange(1, stop=len(virus), step=1) = random.choice(mutations)

so for example if the virus is ATCG it should return something like ATCC or GTCG, how can I go about this, I tried making virus into a list, and replacing a random variable in it with a random of my possible mutations list.

So it should probably make a list from the string virus, do a mutation, put the list back into a string and return the string.

Body:
You can generate a random index to replace at and a random value:

import random
def mutate(virus):
   mutations = ['A', 'T', 'C', 'G']
   i = random.randint(0, len(virus)-1)
   val = random.choice(mutations)
   return ''.join(val if c == i else a for c, a in enumerate(virus))


问:
Reading 2-D array from a file
I have a 2-D int array in file 'array.txt'. I am trying to read all the elements in the file in a two dimensional array. I am having problem in copying. It shows all the elements having value '0' after copying instead their original value. Please help me.
My code is : </p>

```<code>import java.util.*;
import java.lang.*;
import java.io.*;

public class appMainNineSix {

    /**
     * @param args
     */
    public static void main(String[] args)
        throws java.io.FileNotFoundException{
        // TODO Auto-generated method stub
        Scanner input = new Scanner (new File("src/array.txt"));
        int m = 3;
        int n = 5;
        int[][] a = new int [m][n];
        while (input.next()!=null){
            for (int i=0;i<m;i++){
                for (int j=0;j<n;j++)
                    a[i][j]= input.nextInt();
            }

        }
        //print the input matrix
        System.out.println("The input sorted matrix is : ");
        for(int i=0;i<m;i++){
            for(int j=0;j<n;j++)
                System.out.println(a[i][j]);
        }

    }

}
</code>```

答:
The problem is when u reach the end of the file it throughs an exception that no usch element exist.

```<code> public static void main(String[] args) {
    // TODO Auto-generated method stub
    try {
        Scanner input = new Scanner(new File("array.txt"));
        int m = 3;
        int n = 5;
        int[][] a = new int[m][n];
        while (input.hasNextLine()) {
            for (int i = 0; i < m; i++) {
                for (int j = 0; j < n; j++) {
                   try{//    System.out.println("number is ");
                    a[i][j] = input.nextInt();
                      System.out.println("number is "+ a[i][j]);
                    }
                   catch (java.util.NoSuchElementException e) {
                       // e.printStackTrace();
                    }
                }
            }         //print the input matrix
            System.out.println("The input sorted matrix is : ");
            for (int i = 0; i < m; i++) {
                for (int j = 0; j < n; j++) {
                    System.out.println(a[i][j]);

                }
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}
</code>```

I knew that making catch without processing the exception but it temporary works.
Please be aware I put the file outside the source folder.

ContentLicense: CC BY-SA 2.5

Title: Reading 2-D array from a file

Body:
I have a 2-D int array in file 'array.txt'. I am trying to read all the elements in the file in a two dimensional array. I am having problem in copying. It shows all the elements having value '0' after copying instead their original value. Please help me.
My code is :

import java.util.*;
import java.lang.*;
import java.io.*;

public class appMainNineSix {

    /**
     * @param args
     */
    public static void main(String[] args)
        throws java.io.FileNotFoundException{
        // TODO Auto-generated method stub
        Scanner input = new Scanner (new File("src/array.txt"));
        int m = 3;
        int n = 5;
        int[][] a = new int [m][n];
        while (input.next()!=null){
            for (int i=0;i<m;i++){
                for (int j=0;j<n;j++)
                    a[i][j]= input.nextInt();
            }

        }
        //print the input matrix
        System.out.println("The input sorted matrix is : ");
        for(int i=0;i<m;i++){
            for(int j=0;j<n;j++)
                System.out.println(a[i][j]);
        }

    }

}

Body:
The problem is when u reach the end of the file it throughs an exception that no usch element exist.

 public static void main(String[] args) {
    // TODO Auto-generated method stub
    try {
        Scanner input = new Scanner(new File("array.txt"));
        int m = 3;
        int n = 5;
        int[][] a = new int[m][n];
        while (input.hasNextLine()) {
            for (int i = 0; i < m; i++) {
                for (int j = 0; j < n; j++) {
                   try{//    System.out.println("number is ");
                    a[i][j] = input.nextInt();
                      System.out.println("number is "+ a[i][j]);
                    }
                   catch (java.util.NoSuchElementException e) {
                       // e.printStackTrace();
                    }
                }
            }         //print the input matrix
            System.out.println("The input sorted matrix is : ");
            for (int i = 0; i < m; i++) {
                for (int j = 0; j < n; j++) {
                    System.out.println(a[i][j]);

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

I knew that making catch without processing the exception but it temporary works.
Please be aware I put the file outside the source folder.


问:
AngularJS - Sorting data ascending / descending when column is clicked
I have the following view code:

```<code><tr ng-repeat="c in clients | orderBy:'code'">
    <td>{{c.firstname}} {{c.lastname}}</td>
    <td>{{c.telephone}}</td>
    <td>{{c.location}}</td>
    <td>{{c.code}}</td>
</tr>
</code>```

I want to change the orderBy:'code' when column is clicked, assume that the user clicked on the column location, i want the orderBy condition to change to 'location' instead of code, and to be in this form

```<code><tr ng-repeat="c in clients | orderBy:'location'">
</code>```

答:
write ng-click on the column and call a function like setSortByParameter and set the field sortBy.

and now write the orderBy as below.

```<code><tr ng-repeat="c in clients | orderBy:'{{sortBy}}'">
</code>```

Body:
I have the following view code:

    {{c.firstname}} {{c.lastname}}
    {{c.telephone}}
    {{c.location}}
    {{c.code}}

I want to change the orderBy:'code' when column is clicked, assume that the user clicked on the column location, i want the orderBy condition to change to 'location' instead of code, and to be in this form

Body:
write ng-click on the column and call a function like setSortByParameter and set the field sortBy.

and now write the orderBy as below.

<tr ng-repeat="c in clients | orderBy:'{{sortBy}}'">


问:
Cordova FCM plugin

I'm very new to cordova. I have installed this plugin from this page. My question is where do I put this code if I'm not using ionic?:

FCMPlugin.onTokenRefresh(function(token){
    alert( token );
});

I have managed to the token on Chrome using official firebase documentation, but the same does not work on Firefox and cordova.
If I put the above code in the index.html file it does work and I don't get errors whatsoever. I seen so many videos on Youtube that use ionic and they put this code in .ts file. When I started my project I did not use ionic. Do I need to use ionic for this plugin to work?

NB: my main aim is to get the token.

答:
as its cordova plugin there's no need to create ionic project you can write this code in your js file on cordova platform ready function

just like jquery document ready

if have just created project and installed plugin sample JavaScript will be at www/js/ folder

Title: Cordova FCM plugin


问:
Google sign-in using Javascript API without triggering popup
I am using following code for users to be able to login using their Google account via Javascript API.

HTML

Login using Google

Javascript

```<code>function gPOnLoad(){
     // G+ api loaded
     document.getElementById('gp_login').style.display = 'block';
}
function googleAuth() {
    gapi.auth.signIn({
        callback: gPSignInCallback,
        clientid: googleKey,
        cookiepolicy: "single_host_origin",
        requestvisibleactions: "http://schema.org/AddAction",
        scope: "https://www.googleapis.com/auth/plus.login email"
    })
}

function gPSignInCallback(e) {
    if (e["status"]["signed_in"]) {
        gapi.client.load("plus", "v1", function() {
            if (e["access_token"]) {
                getProfile()
            } else if (e["error"]) {
                console.log("There was an error: " + e["error"])
            }
        })
    } else {
        console.log("Sign-in state: " + e["error"])
    }
}

function getProfile() {
    var e = gapi.client.plus.people.get({
        userId: "me"
    });
    e.execute(function(e) {
        if (e.error) {
            console.log(e.message);
            return
        } else if (e.id) {
            // save profile data
        }
    })
}(function() {
    var e = document.createElement("script");
    e.type = "text/javascript";
    e.async = true;
    e.src = "https://apis.google.com/js/client:platform.js?onload=gPOnLoad";
    var t = document.getElementsByTagName("script")[0];
    t.parentNode.insertBefore(e, t)
})()
</code>```

This code is working fine.
I want to use the above code (using Javascript) to login user from their Google account without triggering a popup window. Like, user clicks the login link, asked for app permissions in the same window/tab, user grants permission, user redirected back to the page where Google login link was, profile data is saved and user is logged in.

答:
You can the use ux_mode parameter (options are 'redirect' or 'popup') and set a redirect_uri if you want to redirect to a different page.

It's also necessary to authorize the URL for the OAuth client on your google project page.

```<code>  function initClient() {
    gapi.client.init({
      apiKey: API_KEY,
      clientId: CLIENT_ID,
      discoveryDocs: DISCOVERY_DOCS,
      scope: SCOPES,
      ux_mode: 'redirect',
      //redirect_uri: custom url to redirect'
    }).then(function () {
      // Listen for sign-in state changes.
      gapi.auth2.getAuthInstance().isSignedIn.listen(updateSigninStatus);

      // Handle the initial sign-in state.
      updateSigninStatus(gapi.auth2.getAuthInstance().isSignedIn.get());
      authorizeButton.onclick = handleAuthClick;
      signoutButton.onclick = handleSignoutClick;
    });
  }
</code>```

Body:
I am using following code for users to be able to login using their Google account via Javascript API.

HTML

Login using Google

Javascript

function gPOnLoad(){
     // G+ api loaded
     document.getElementById('gp_login').style.display = 'block';
}
function googleAuth() {
    gapi.auth.signIn({
        callback: gPSignInCallback,
        clientid: googleKey,
        cookiepolicy: "single_host_origin",
        requestvisibleactions: "http://schema.org/AddAction",
        scope: "https://www.googleapis.com/auth/plus.login email"
    })
}

function gPSignInCallback(e) {
    if (e["status"]["signed_in"]) {
        gapi.client.load("plus", "v1", function() {
            if (e["access_token"]) {
                getProfile()
            } else if (e["error"]) {
                console.log("There was an error: " + e["error"])
            }
        })
    } else {
        console.log("Sign-in state: " + e["error"])
    }
}

function getProfile() {
    var e = gapi.client.plus.people.get({
        userId: "me"
    });
    e.execute(function(e) {
        if (e.error) {
            console.log(e.message);
            return
        } else if (e.id) {
            // save profile data
        }
    })
}(function() {
    var e = document.createElement("script");
    e.type = "text/javascript";
    e.async = true;
    e.src = "https://apis.google.com/js/client:platform.js?onload=gPOnLoad";
    var t = document.getElementsByTagName("script")[0];
    t.parentNode.insertBefore(e, t)
})()

This code is working fine.
I want to use the above code (using Javascript) to login user from their Google account without triggering a popup window. Like, user clicks the login link, asked for app permissions in the same window/tab, user grants permission, user redirected back to the page where Google login link was, profile data is saved and user is logged in.

Body:
You can the use ux_mode parameter (options are 'redirect' or 'popup') and set a redirect_uri if you want to redirect to a different page.

It's also necessary to authorize the URL for the OAuth client on your google project page.

  function initClient() {
    gapi.client.init({
      apiKey: API_KEY,
      clientId: CLIENT_ID,
      discoveryDocs: DISCOVERY_DOCS,
      scope: SCOPES,
      ux_mode: 'redirect',
      //redirect_uri: custom url to redirect'
    }).then(function () {
      // Listen for sign-in state changes.
      gapi.auth2.getAuthInstance().isSignedIn.listen(updateSigninStatus);

      // Handle the initial sign-in state.
      updateSigninStatus(gapi.auth2.getAuthInstance().isSignedIn.get());
      authorizeButton.onclick = handleAuthClick;
      signoutButton.onclick = handleSignoutClick;
    });
  }


问:
Remove last character from C++ string
How can I remove last character from a C++ string?

I tried st = substr(st.length()-1); But it didn't work.

答:
That's all you need:</p>

```<code>#include <string>  //string::pop_back & string::empty

if (!st.empty())
    st.pop_back();
</code>```

Title: Remove last character from C++ string

Body:
That's all you need:

#include <string>  //string::pop_back & string::empty

if (!st.empty())
    st.pop_back();


问:
Make JCheckbox bigger..?
i want to make my JCheckboxes in a JTable bigger (for Touchscreen), but it doesn't change the size.

I tried it with

setPrefferedSize

setSize

What should I do?..

答:
I assume you mean you want a bigger check box. If so then you need to create images to represent the unselected and selected icons of the check box. Then you can create a renderer and editor using these icons. Finally you would need to increase the height of each row in the table. The code might look something like:</p>

```<code>Icon normal = new ImageIcon(...);
Icon selected = new ImageIcon(...);
JTable table = new JTable(...);
table.setRowHeight(...);

TableCellRenderer renderer = table.getDefaultRenderer(Boolean.class);
JCheckBox checkBoxRenderer = (JCheckBox)renderer;
checkBoxRenderer.setIcon( normal );
checkBoxRenderer.setSelectedIcon( selected );

DefaultCellEditor editor = (DefaultCellEditor)table.getDefaultEditor(Boolean.class);
JCheckBox checkBoxEditor = (JCheckBox)editor.getComponent();
checkBoxEditor.setIcon( normal );
checkBoxEditor.setSelectedIcon( selected );
</code>```

Title: Make JCheckbox bigger..?

Body:
I assume you mean you want a bigger check box. If so then you need to create images to represent the unselected and selected icons of the check box. Then you can create a renderer and editor using these icons. Finally you would need to increase the height of each row in the table. The code might look something like:

Icon normal = new ImageIcon(...);
Icon selected = new ImageIcon(...);
JTable table = new JTable(...);
table.setRowHeight(...);

TableCellRenderer renderer = table.getDefaultRenderer(Boolean.class);
JCheckBox checkBoxRenderer = (JCheckBox)renderer;
checkBoxRenderer.setIcon( normal );
checkBoxRenderer.setSelectedIcon( selected );

DefaultCellEditor editor = (DefaultCellEditor)table.getDefaultEditor(Boolean.class);
JCheckBox checkBoxEditor = (JCheckBox)editor.getComponent();
checkBoxEditor.setIcon( normal );
checkBoxEditor.setSelectedIcon( selected );


问:
h2o python H2ODataFrame apply raising error "ValueError: unimpl bytecode instr: LOAD_CONST"
Using h2o python api and have a H2ODataFrame that raises the error

ValueError: unimpl bytecode instr: LOAD_CONST

when trying to use the apply method on the frame.

The frame in question here looks like:

```<code>predict     0_good      1_bad
0_NoDenial  0.999593    0.000407184
0_NoDenial  0.999571    0.000428798
0_NoDenial  0.998374    0.00162572
0_NoDenial  0.999343    0.000657361
0_NoDenial  0.999307    0.000693177
0_NoDenial  0.999895    0.000104678
0_NoDenial  0.999495    0.000504838
0_NoDenial  0.999627    0.000373012
0_NoDenial  0.997075    0.00292529
0_NoDenial  0.996358    0.00364194

<class 'h2o.frame.H2OFrame'>
</code>```

The code that raises the error looks like:

```<code>preds['predict'] = preds['1_bad'].apply(lambda x: '1_bad' if x > custom_thresh else '0_good', axis=1)
</code>```

With the full error looking like:

```<code>/home/mapr/anaconda2/lib/python2.7/site-packages/h2o/frame.pyc in apply(self, fun, axis)
   3034         assert_is_type(fun, FunctionType)
   3035         assert_satisfies(fun, fun.__name__ == "<lambda>")
-> 3036         res = lambda_to_expr(fun)
   3037         return H2OFrame._expr(expr=ExprNode("apply", self, 1 + (axis == 0), *res))
   3038

/home/mapr/anaconda2/lib/python2.7/site-packages/h2o/astfun.pyc in lambda_to_expr(fun)
    133     code = fun.__code__
    134     lambda_dis = _disassemble_lambda(code)
--> 135     return _lambda_bytecode_to_ast(code, lambda_dis)
    136
    137 def _lambda_bytecode_to_ast(co, ops):

/home/mapr/anaconda2/lib/python2.7/site-packages/h2o/astfun.pyc in _lambda_bytecode_to_ast(co, ops)
    147         body, s = _opcode_read_arg(s, ops, keys)
    148     else:
--> 149         raise ValueError("unimpl bytecode instr: " + instr)
    150     if s > 0:
    151         print("Dumping disassembled code: ")

ValueError: unimpl bytecode instr: LOAD_CONST
</code>```

I've never seen this kind of error before and quick googling did not tell much more. Does anyone know why this is happening and what can be done about it? Thanks.

答:
for this scenario you might just want to use the h2o ifelse() method

```<code>(preds['1_bad'] < .0005).ifelse('good','bad')
</code>```

or if you create a new column that consists of your thresholds and append it to your original frame you could do

```<code>(preds['1_bad'] < preds['my_thresholds']).ifelse('good','bad')
</code>```

Body:
Using h2o python api and have a H2ODataFrame that raises the error

ValueError: unimpl bytecode instr: LOAD_CONST

when trying to use the apply method on the frame.

The frame in question here looks like:

predict     0_good      1_bad
0_NoDenial  0.999593    0.000407184
0_NoDenial  0.999571    0.000428798
0_NoDenial  0.998374    0.00162572
0_NoDenial  0.999343    0.000657361
0_NoDenial  0.999307    0.000693177
0_NoDenial  0.999895    0.000104678
0_NoDenial  0.999495    0.000504838
0_NoDenial  0.999627    0.000373012
0_NoDenial  0.997075    0.00292529
0_NoDenial  0.996358    0.00364194

<class 'h2o.frame.H2OFrame'>

The code that raises the error looks like:

preds['predict'] = preds['1_bad'].apply(lambda x: '1_bad' if x > custom_thresh else '0_good', axis=1)

With the full error looking like:

/home/mapr/anaconda2/lib/python2.7/site-packages/h2o/frame.pyc in apply(self, fun, axis)
   3034         assert_is_type(fun, FunctionType)
   3035         assert_satisfies(fun, fun.__name__ == "<lambda>")
-> 3036         res = lambda_to_expr(fun)
   3037         return H2OFrame._expr(expr=ExprNode("apply", self, 1 + (axis == 0), *res))
   3038

/home/mapr/anaconda2/lib/python2.7/site-packages/h2o/astfun.pyc in lambda_to_expr(fun)
    133     code = fun.__code__
    134     lambda_dis = _disassemble_lambda(code)
--> 135     return _lambda_bytecode_to_ast(code, lambda_dis)
    136
    137 def _lambda_bytecode_to_ast(co, ops):

/home/mapr/anaconda2/lib/python2.7/site-packages/h2o/astfun.pyc in _lambda_bytecode_to_ast(co, ops)
    147         body, s = _opcode_read_arg(s, ops, keys)
    148     else:
--> 149         raise ValueError("unimpl bytecode instr: " + instr)
    150     if s > 0:
    151         print("Dumping disassembled code: ")

ValueError: unimpl bytecode instr: LOAD_CONST

I've never seen this kind of error before and quick googling did not tell much more. Does anyone know why this is happening and what can be done about it? Thanks.

Body:
for this scenario you might just want to use the h2o ifelse() method

(preds['1_bad'] < .0005).ifelse('good','bad')

or if you create a new column that consists of your thresholds and append it to your original frame you could do

(preds['1_bad'] < preds['my_thresholds']).ifelse('good','bad')


问:
What Is The Title of This Type of Program
In the same vein that; a graphical program someone uses is called a GUI (Graphical User Interface), a program that talks with machinery and displays statuses to an operator are called an HMI (Human Machine Interface), a program that uses a console is called a console application, what would the appropriate title for a program that runs on computer and boots at startup and only allows users to interact with the program and not whats underneath? Similar to banking software or the checkout software at grocery stores.

It will be on a Raspberry PI with a touchscreen and as soon as the PI powers on, it will load this program that covers the whole screen and doesn't allow the user to interact with the PI through desktop or console.

EDIT

I am wanting to study up on best practices for this type of program, I just don't know WHAT to search for.

答: I believe that is typically referred to as a "Kiosk program".</p>


问:
Make a vector out of slices of a large dataframe
I have a large dataframe df whose elements are zipcodes and the associated shapefiles.

There is a territory field df$V2 with around 150 territories.

For each of these territories I am running gTouches to create the adjacency matrix for the associated zip codes.  What I want ultimately is a list with 2 fields - the Territory Name (a character) and the Adjacency Matrix (a matrix) - this matrix will be a square matrix but will not be the same size for every element.  This list will have 150 elements (1 per territory).

My code looks like this (and I apologize this is definitely embarrassing but I'm a novice):

```<code>Adjacency_Matrices<-list()
for(i in 1:length(unique(as.character(df@data$V2))))
{Adjacency_Matrices[[i]][1]<-unique(as.character(df@data$V2))[i]
Adjacency_Matrices[[i]][2]<-
gTouches(df[df@data$V2==unique(as.character(df@data$V2))[i],], byid=TRUE)}
</code>```

So line 1 is looping through the length of my list of unique territories.  Line 2 is defining the first field of the list (a string).  Line 3/4 defines the second field of the string (gTouches output is a square matrix).

I get two separate errors:

1) number of items to replace is not a multiple of replacement length

2) Error in Adjacency_Matrices[[1]] : subscript out of bounds

I have googled 1 over and over and can't seem to find a way to fix this.  Number 2 I think is something I'm simply missing about how to instantiate lists in R.

Any help is appreciated and let me know if you need any clarification.

答:
Turns out I was overthinking this.

You can't define Adjacency_Matrices[[i]][1] before you've defined i itself.

All I needed was rather than try to define Adjacency_Matrices[[i]][1] then Adjacency_Matrices[[i]][2] separately I just need to use list() to define my output list.

```<code>Adjacency_Matrices<-list(
for(i in 1:length(unique(as.character(df@data$V2))))
{Adjacency_Matrices[[i]]<-list(unique(as.character(df@data$V2))[i],
gTouches(df[df@data$V2==unique(as.character(df@data$V2))[i],], byid=TRUE))}
</code>```

Body:
I have a large dataframe df whose elements are zipcodes and the associated shapefiles.

There is a territory field df$V2 with around 150 territories.

For each of these territories I am running gTouches to create the adjacency matrix for the associated zip codes.  What I want ultimately is a list with 2 fields - the Territory Name (a character) and the Adjacency Matrix (a matrix) - this matrix will be a square matrix but will not be the same size for every element.  This list will have 150 elements (1 per territory).

My code looks like this (and I apologize this is definitely embarrassing but I'm a novice):

Adjacency_Matrices<-list()
for(i in 1:length(unique(as.character(df@data$V2))))
{Adjacency_Matrices[[i]][1]<-unique(as.character(df@data$V2))[i]
Adjacency_Matrices[[i]][2]<-
gTouches(df[df@data$V2==unique(as.character(df@data$V2))[i],], byid=TRUE)}

So line 1 is looping through the length of my list of unique territories.  Line 2 is defining the first field of the list (a string).  Line 3/4 defines the second field of the string (gTouches output is a square matrix).

I get two separate errors:

1) number of items to replace is not a multiple of replacement length

2) Error in Adjacency_Matrices[[1]] : subscript out of bounds

I have googled 1 over and over and can't seem to find a way to fix this.  Number 2 I think is something I'm simply missing about how to instantiate lists in R.

Any help is appreciated and let me know if you need any clarification.

Body:
Turns out I was overthinking this.

You can't define Adjacency_Matrices[[i]][1] before you've defined i itself.

All I needed was rather than try to define Adjacency_Matrices[[i]][1] then Adjacency_Matrices[[i]][2] separately I just need to use list() to define my output list.

Adjacency_Matrices<-list(
for(i in 1:length(unique(as.character(df@data$V2))))
{Adjacency_Matrices[[i]]<-list(unique(as.character(df@data$V2))[i],
gTouches(df[df@data$V2==unique(as.character(df@data$V2))[i],], byid=TRUE))}


问:
Preparing discretization data for arules
I have a data set which is applied to discretization proceeding, and I want to coerce the data set to transactions for using arules package.

```<code>CLUST_K <- structure(list(LONGITUDE = c(118.5, 118.5, 118.5, 118.5, 118.5,
                    118.5), LATITUDE = c(-11.5, -11.5, -11.5, -11.5, -11.5, -11.5
                    ), DATE_START = structure(c(1419897600, 1419984000, 1420070400,
                    1420156800, 1420243200, 1420329600), class = c("POSIXct", "POSIXt"
                    )), DATE_END = structure(c(1420502400, 1420588800, 1420675200,
                    1420761600, 1420848000, 1420934400), class = c("POSIXct", "POSIXt"
                    )), FLAG = c(2, 1, 2, 2, 2, 2), SURFSKINTEMP = c(13L, 1L, 16L,
                    16L, 7L, 13L), SURFAIRTEMP = c(6L, 6L, 6L, 6L, 6L, 6L), TOTH2OVAP = c(5L,
                    17L, 17L, 17L, 17L, 17L), TOTO3 = c(16L, 16L, 16L, 10L, 7L, 7L
                    ), TOTCO = c(12L, 12L, 8L, 4L, 12L, 12L), TOTCH4 = c(13L, 14L,
                    6L, 6L, 11L, 7L), OLR_ARIS = c(10L, 4L, 4L, 7L, 5L, 10L), CLROLR_ARIS = c(10L,
                    4L, 4L, 7L, 5L, 10L), OLR_NOAA = c(10L, 10L, 10L, 10L, 7L, 9L
                    ), MODIS_LST = c(1L, 1L, 1L, 1L, 1L, 1L)), .Names = c("LONGITUDE",
                    "LATITUDE", "DATE_START", "DATE_END", "FLAG", "SURFSKINTEMP",
                    "SURFAIRTEMP", "TOTH2OVAP", "TOTO3", "TOTCO", "TOTCH4", "OLR_ARIS",
                    "CLROLR_ARIS", "OLR_NOAA", "MODIS_LST"), row.names = c(NA, 6L
                    ), class = "data.frame")
</code>```

from the data set CLUST_K, you can see that

```<code>    LONGITUDE LATITUDE DATE_START   DATE_END FLAG SURFSKINTEMP SURFAIRTEMP TOTH2OVAP TOTO3 TOTCO TOTCH4 OLR_ARIS    CLROLR_ARIS OLR_NOAA MODIS_LST
1     118.5    -11.5 2014-12-30 2015-01-06    2           13           6         5    16    12     13       10           10       10         1
2     118.5    -11.5 2014-12-31 2015-01-07    1            1           6        17    16    12     14        4            4       10         1
3     118.5    -11.5 2015-01-01 2015-01-08    2           16           6        17    16     8      6        4            4       10         1
4     118.5    -11.5 2015-01-02 2015-01-09    2           16           6        17    10     4      6        7            7       10         1
5     118.5    -11.5 2015-01-03 2015-01-10    2            7           6        17     7    12     11        5            5        7         1
6     118.5    -11.5 2015-01-04 2015-01-11    2           13           6        17     7    12      7       10           10        9         1
</code>```

first column to fifth column of the data set is the transaction information, and column 6 to column 15 are the transactions, and which are applied to discretization proceeding.

when I try to coerce the data set to transactions

```<code>CLUST_K_R <- CLUST_K[,6:15]
CLUST_K_R_T <- as(CLUST_K_R,"transactions")
Error in asMethod(object) :
  column(s) 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 not logical or a factor. Discretize the columns first.
</code>```

but I the data set has already applied to discretization proceeding

When I use split, it also seems not right

```<code>> s1 <- split(CLUST_K$SURFSKINTEMP, CLUST_K$SURFAIRTEMP,CLUST_K$TOTH2OVAP, CLUST_K$TOTO3)
> Tr <- as(s1,"transactions")
Warning message:
In asMethod(object) : removing duplicated items in transactions
> Tr
transactions in sparse format with
 1 transactions (rows) and
 4 items (columns)
</code>```

only 1 transactions left, but it should be 6 transactions in my case.

答:
Since you already discretized the data (via clustering), you only need to make sure that the data is encoded as nominal values (factor) not numbers (integer).</p>

```<code>for(i in 1:ncol(CLUST_K_R)) CLUST_K_R[[i]] <- as.factor(CLUST_K_R[[i]])
CLUST_K_R_T <- as(CLUST_K_R,"transactions")

summary(CLUST_K_R_T)

transactions as itemMatrix in sparse format with
 6 rows (elements/itemsets/transactions) and
 30 columns (items) and a density of 0.3333333

most frequent items:
SURFAIRTEMP=6   MODIS_LST=1  TOTH2OVAP=17      TOTCO=12   OLR_NOAA=10       (Other)
            6             6             5             4             4            35

element (itemset/transaction) length distribution:
sizes
10
 6

   Min. 1st Qu.  Median    Mean 3rd Qu.    Max.
     10      10      10      10      10      10

includes extended item information - examples:
           labels    variables levels
1  SURFSKINTEMP=1 SURFSKINTEMP      1
2  SURFSKINTEMP=7 SURFSKINTEMP      7
3 SURFSKINTEMP=13 SURFSKINTEMP     13

includes extended transaction information - examples:
  transactionID
1             1
2             2
3             3
</code>```

Body:
I have a data set which is applied to discretization proceeding, and I want to coerce the data set to transactions for using arules package.

CLUST_K <- structure(list(LONGITUDE = c(118.5, 118.5, 118.5, 118.5, 118.5,
                    118.5), LATITUDE = c(-11.5, -11.5, -11.5, -11.5, -11.5, -11.5
                    ), DATE_START = structure(c(1419897600, 1419984000, 1420070400,
                    1420156800, 1420243200, 1420329600), class = c("POSIXct", "POSIXt"
                    )), DATE_END = structure(c(1420502400, 1420588800, 1420675200,
                    1420761600, 1420848000, 1420934400), class = c("POSIXct", "POSIXt"
                    )), FLAG = c(2, 1, 2, 2, 2, 2), SURFSKINTEMP = c(13L, 1L, 16L,
                    16L, 7L, 13L), SURFAIRTEMP = c(6L, 6L, 6L, 6L, 6L, 6L), TOTH2OVAP = c(5L,
                    17L, 17L, 17L, 17L, 17L), TOTO3 = c(16L, 16L, 16L, 10L, 7L, 7L
                    ), TOTCO = c(12L, 12L, 8L, 4L, 12L, 12L), TOTCH4 = c(13L, 14L,
                    6L, 6L, 11L, 7L), OLR_ARIS = c(10L, 4L, 4L, 7L, 5L, 10L), CLROLR_ARIS = c(10L,
                    4L, 4L, 7L, 5L, 10L), OLR_NOAA = c(10L, 10L, 10L, 10L, 7L, 9L
                    ), MODIS_LST = c(1L, 1L, 1L, 1L, 1L, 1L)), .Names = c("LONGITUDE",
                    "LATITUDE", "DATE_START", "DATE_END", "FLAG", "SURFSKINTEMP",
                    "SURFAIRTEMP", "TOTH2OVAP", "TOTO3", "TOTCO", "TOTCH4", "OLR_ARIS",
                    "CLROLR_ARIS", "OLR_NOAA", "MODIS_LST"), row.names = c(NA, 6L
                    ), class = "data.frame")

from the data set CLUST_K, you can see that

    LONGITUDE LATITUDE DATE_START   DATE_END FLAG SURFSKINTEMP SURFAIRTEMP TOTH2OVAP TOTO3 TOTCO TOTCH4 OLR_ARIS    CLROLR_ARIS OLR_NOAA MODIS_LST
1     118.5    -11.5 2014-12-30 2015-01-06    2           13           6         5    16    12     13       10           10       10         1
2     118.5    -11.5 2014-12-31 2015-01-07    1            1           6        17    16    12     14        4            4       10         1
3     118.5    -11.5 2015-01-01 2015-01-08    2           16           6        17    16     8      6        4            4       10         1
4     118.5    -11.5 2015-01-02 2015-01-09    2           16           6        17    10     4      6        7            7       10         1
5     118.5    -11.5 2015-01-03 2015-01-10    2            7           6        17     7    12     11        5            5        7         1
6     118.5    -11.5 2015-01-04 2015-01-11    2           13           6        17     7    12      7       10           10        9         1

first column to fifth column of the data set is the transaction information, and column 6 to column 15 are the transactions, and which are applied to discretization proceeding.

when I try to coerce the data set to transactions

CLUST_K_R <- CLUST_K[,6:15]
CLUST_K_R_T <- as(CLUST_K_R,"transactions")
Error in asMethod(object) :
  column(s) 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 not logical or a factor. Discretize the columns first.

but I the data set has already applied to discretization proceeding

When I use split, it also seems not right

> s1 <- split(CLUST_K$SURFSKINTEMP, CLUST_K$SURFAIRTEMP,CLUST_K$TOTH2OVAP, CLUST_K$TOTO3)
> Tr <- as(s1,"transactions")
Warning message:
In asMethod(object) : removing duplicated items in transactions
> Tr
transactions in sparse format with
 1 transactions (rows) and
 4 items (columns)

only 1 transactions left, but it should be 6 transactions in my case.

Body:
Since you already discretized the data (via clustering), you only need to make sure that the data is encoded as nominal values (factor) not numbers (integer).

for(i in 1:ncol(CLUST_K_R)) CLUST_K_R[[i]] <- as.factor(CLUST_K_R[[i]])
CLUST_K_R_T <- as(CLUST_K_R,"transactions")

summary(CLUST_K_R_T)

transactions as itemMatrix in sparse format with
 6 rows (elements/itemsets/transactions) and
 30 columns (items) and a density of 0.3333333

most frequent items:
SURFAIRTEMP=6   MODIS_LST=1  TOTH2OVAP=17      TOTCO=12   OLR_NOAA=10       (Other)
            6             6             5             4             4            35

element (itemset/transaction) length distribution:
sizes
10
 6

   Min. 1st Qu.  Median    Mean 3rd Qu.    Max.
     10      10      10      10      10      10

includes extended item information - examples:
           labels    variables levels
1  SURFSKINTEMP=1 SURFSKINTEMP      1
2  SURFSKINTEMP=7 SURFSKINTEMP      7
3 SURFSKINTEMP=13 SURFSKINTEMP     13

includes extended transaction information - examples:
  transactionID
1             1
2             2
3             3


问:
create_Task(): The application called an interface that was marshalled for a different thread
I have a UWP UI that calls native code that takes a while to execute.  Upon completion, the UI needs updating.  This is my code:

```<code>auto runOpti = create_task([this] { runOptimation(); });
runOpti.then([this]{postOptimation(); });
</code>```

The postOptimation routine includes the line:

```<code>backwordCheckBox->IsChecked = params->backwards;
</code>```

Executing this like gives the error in the title.

How do I get the postOptimation to run in the UI thread?

Thanks

答:
You can use the overload of .then() that takes a task_continuation_context, and set it to task_continuation_context::get_current_winrt_context().

Using the Dispatcher (other answers) would work also, but this should compose better with PPL.

Body:
I have a UWP UI that calls native code that takes a while to execute.  Upon completion, the UI needs updating.  This is my code:

auto runOpti = create_task([this] { runOptimation(); });
runOpti.then([this]{postOptimation(); });

The postOptimation routine includes the line:

backwordCheckBox->IsChecked = params->backwards;

Executing this like gives the error in the title.

How do I get the postOptimation to run in the UI thread?

Thanks


问:
How to Cut Everything except UTF-8 Encoding in Notepad++
I have a text file similar to the following:

```<code><a style="color:#414146;" onclick="return trackOutboundLink(true,'Current Affair Page','question widget',' question click');" href="https://onlinetyari.com/hindi/question-bank/question-sentral-soyal-saileniti-i17677.html">
                                                सेण्ट्रल सोयल सैलेनिटी रिसर्च इंस्टीट्यूट (CSSRI) हरियाणा के किस जिले में स्थित
हैं ?                                                </a>
                                            </div>
                                            <div class="show-optipns light">
                                                <a class="s_option" id="options_17677" onclick="showOption('17677','1')" style="text-align:right">Show Options</a>
                                            </div>
                                            <div id="question_17677" class="question_info" name="question_info">
                                                <div id="op_1_17677" class="col-sm-6 question-option form-group cursor-pointer" onclick="showAnswer('17677',1,1)" style="float:none">
                                                    <div class="input-group regular">
                                                        <span class="input-group-addon">A</span>
                                                        <div id="checkbox1_17677" type="text" class="form-control checkbox_data" id="inputGroupSuccess3" aria-describedby="inputGroupSuccess3Status">
                                                            करनाल में                                                            <span id="chk-tick1-17677"></span>
                                                            <span id="inputGroupSuccess3Status" class="sr-only">(success)</span>
                                                        </div>
                                                    </div>
                                                </div>
                                                <div id="op_2_17677" class="col-sm-6 question-option form-group cursor-pointer" onclick="showAnswer('17677',2,1)" style="float:none">
                                                    <div class="input-group regular">
                                                        <span class="input-group-addon">B</span>
                                                        <div id="checkbox2_17677" type="text" class="form-control checkbox_data" id="inputGroupSuccess3" aria-describedby="inputGroupSuccess3Status">
                                                            महेन्द्रगढ़ में
</code>```

I want to remove everything except Hindi words, so my file remains only:

सेण्ट्रल सोयल सैलेनिटी रिसर्च इंस्टीट्यूट हरियाणा के किस जिले में स्थित
हैं ?          करनाल में            महेन्द्रगढ़ में

Is this possible with regex?

答:
Remove everything that matches this regex:

```<code>[^[:unicode:]]+
</code>```

If you want to preserve spaces, then remove everything that matches this regex instead:

```<code>[^[:unicode:]\s]+
</code>```

Then, if you want to condense all the spacing down to single spaces, do a search for:

```<code>\s+
</code>```

And replace it with a single space. Here is what that result looks like:

सेण्ट्रल सोयल सैलेनिटी रिसर्च इंस्टीट्यूट हरियाणा के किस जिले में स्थित हैं करनाल में महेन्द्रगढ़ में

ContentLicense: CC BY-SA 4.0

Body:
I have a text file similar to the following:

                                                सेण्ट्रल सोयल सैलेनिटी रिसर्च इंस्टीट्यूट (CSSRI) हरियाणा के किस जिले में स्थित
हैं ?

                                                Show Options

                                                        A

                                                            करनाल में
                                                            (success)

                                                        B

                                                            महेन्द्रगढ़ में

I want to remove everything except Hindi words, so my file remains only:

सेण्ट्रल सोयल सैलेनिटी रिसर्च इंस्टीट्यूट हरियाणा के किस जिले में स्थित
हैं ?          करनाल में            महेन्द्रगढ़ में

Is this possible with regex?

Body:
Remove everything that matches this regex:

[^[:unicode:]]+

If you want to preserve spaces, then remove everything that matches this regex instead:

[^[:unicode:]\s]+

Then, if you want to condense all the spacing down to single spaces, do a search for:

\s+

And replace it with a single space. Here is what that result looks like:

सेण्ट्रल सोयल सैलेनिटी रिसर्च इंस्टीट्यूट हरियाणा के किस जिले में स्थित हैं करनाल में महेन्द्रगढ़ में


问:
END command in GW-BASIC
I am using the AUTO command in GW-BASIC 3.23. After I type a program I want to run it. The END command won't return me to command level. I also tried CTRL-BREAK and Ctrl+C.

答:
The command to return to the command prompt from the GWBASIC editor is:</p>

```<code>system
</code>```

Title: END command in GW-BASIC

Body:
The command to return to the command prompt from the GWBASIC editor is:

system


问:
Angular - Route only on condition (Based on localStorage)
I have an Angular application using basic Routing module. The below shows my defined routes:

```<code>...
const routes: Routes = [
  { path: '', redirectTo: '/home', pathMatch: 'full' },
  { path: 'home', component: HomeComponent },
  { path: 'register', component: RegisterComponent },
  { path: 'login', component: LoginComponent },
  { path: 'dashboard', component: DashboardComponent }
];
...
</code>```

Now I want to protect my dashboard route. I want to route only when I have a localStorage object named token. How can I do it?

```<code>var local = JSON.parse(localStorage.getItem('token'));
</code>```

Something like:

```<code>...
const routes: Routes = [
  { path: '', redirectTo: '/home', pathMatch: 'full' },
  { path: 'home', component: HomeComponent },
  { path: 'register', component: RegisterComponent },
  { path: 'login', component: LoginComponent },
  { path: 'dashboard', checkLogin, component: DashboardComponent }
];
...
function checkLogin(){
    // do the logic
}
</code>```

答:
You can do that with a route guard that implements the CanActivate interface:
https://angular.io/api/router/CanActivate

The canActivate method can return a boolean if it's supposed to be checked synchronously or promise/observable if it's async. Anyway, in your case, you're just checking the localStorage so you simply return true or false based on the token.

Body:
I have an Angular application using basic Routing module. The below shows my defined routes:

...
const routes: Routes = [
  { path: '', redirectTo: '/home', pathMatch: 'full' },
  { path: 'home', component: HomeComponent },
  { path: 'register', component: RegisterComponent },
  { path: 'login', component: LoginComponent },
  { path: 'dashboard', component: DashboardComponent }
];
...

Now I want to protect my dashboard route. I want to route only when I have a localStorage object named token. How can I do it?

var local = JSON.parse(localStorage.getItem('token'));

Something like:

...
const routes: Routes = [
  { path: '', redirectTo: '/home', pathMatch: 'full' },
  { path: 'home', component: HomeComponent },
  { path: 'register', component: RegisterComponent },
  { path: 'login', component: LoginComponent },
  { path: 'dashboard', checkLogin, component: DashboardComponent }
];
...
function checkLogin(){
    // do the logic
}


问:
javascript programming with jinja values
I have a block of HTML code

```<code><td>{{stock.C4}}</td>
<td>{{stock.C5}}</td>
<td>{{stock.C6}}</td>
<td>{{stock.C7}}</td>
<td>{{stock.C8}}</td>
</code>```

{{stock.C4}} has an output of None in the html cell.
I want (maybe javascript?) code that basically says

```<code> if {{stock.C4}} == 'None'
       element.style.backgroundColor = "red"
</code>```

code that makes the cell a color based on the html/jinja value

答:
Here is a possible solution using Mustache (that requires to change your data structure) :

var stocks = [
  ["A1", "A2", "None"],
  ["None", "B2", "B3"],
  ["C1", "None", "C3"]
];

var view = {
  stocks: stocks,
  isNone: function () {
    return this == "None";
  }
};

var template = ""
+ "{{#stocks}}"
+   "
"
+     "{{#.}}"
+       "{{#isNone}}{{.}}	{{/isNone}}"
+       "{{^isNone}}{{.}}	{{/isNone}}"
+     "{{/.}}"
+   "
"
+ "{{/stocks}}"
;

var table = document.getElementById("table");
table.innerHTML = Mustache.render(template, view);```
<pre class="snippet-code-css lang-css prettyprint-override"><code>table,td{border:1px solid black;border-collapse:collapse;}
td.none{background:#ffa7b7}
td{padding:.25em}</code>```

```

Body:
I have a block of HTML code

{{stock.C4}}
{{stock.C5}}
{{stock.C6}}
{{stock.C7}}
{{stock.C8}}

{{stock.C4}} has an output of None in the html cell.
I want (maybe javascript?) code that basically says

 if {{stock.C4}} == 'None'
       element.style.backgroundColor = "red"

code that makes the cell a color based on the html/jinja value

Body:
Here is a possible solution using Mustache (that requires to change your data structure) :

var stocks = [
  ["A1", "A2", "None"],
  ["None", "B2", "B3"],
  ["C1", "None", "C3"]
];

var view = {
  stocks: stocks,
  isNone: function () {
    return this == "None";
  }
};

var template = ""
+ "{{#stocks}}"
+   "<tr>"
+     "{{#.}}"
+       "{{#isNone}}<td class=\"none\">{{.}}</td>{{/isNone}}"
+       "{{^isNone}}<td>{{.}}</td>{{/isNone}}"
+     "{{/.}}"
+   "</tr>"
+ "{{/stocks}}"
;

var table = document.getElementById("table");
table.innerHTML = Mustache.render(template, view);

table,td{border:1px solid black;border-collapse:collapse;}
td.none{background:#ffa7b7}
td{padding:.25em}

<script src="https://cdnjs.cloudflare.com/ajax/libs/mustache.js/2.3.0/mustache.min.js"></script>
<table id="table"></table>


问:
How to add pagination for custom Apiview result data in DRF
I have created a ListView in DRF 3. As database structure is complex I have written a custom query i.e. raw query to fetch the data. But as the data size is huge, it takes a lot of time to load it. So I need to implement pagination. Below is the code.</p>

```<code>class SubnetList(APIView):

    def get(self, request, format=None):
        subnet_list = get_subnet_details(None)
        return Response(subnet_list, status=status.HTTP_200_OK)

    def get_subnet_details(subnet_id=None):
        if subnet_id:
            subnets = Subnet.objects.filter(id=subnet_id).values()
        if not subnets:
            raise Http404
        else:
            subnets = Subnet.objects.values()

        subnet_list = []
        subnet_option_query = ' SELECT  ' \
                              ' options_value.id as value_id,' \
                              ' options_value.content,' \
                              ' options_option.id,' \
                              ' options_option.name' \
                              ' FROM subnets_subnetoption' \
                              ' INNER JOIN subnets_subnet ON (subnets_subnetoption.subnet_id = subnets_subnet.id)' \
                              ' INNER JOIN options_value ON (subnets_subnetoption.value_id = options_value.id)' \
                              ' INNER JOIN options_option ON (options_value.option_id = options_option.id)' \
                              ' INNER JOIN options_scope ON (options_option.scope_id = options_scope.id)' \
                              ' WHERE subnets_subnetoption.subnet_id = %s '

        try:
            for subnet in subnets:
                subnet_dictionary = collections.OrderedDict()
                subnet_dictionary['subnet_id'] = str(subnet['id'])
                subnet_dictionary['name'] = str(subnet['name'])
                subnet_dictionary['base_address'] = str(subnet['base_address'])
                subnet_dictionary['bcast_address'] = str(subnet['bcast_address'])
                subnet_dictionary['bits'] = str(subnet['bits'])
                subnet_dictionary['begin'] = str(subnet['base_address'])
                subnet_dictionary['end'] = str(subnet['bcast_address'])
                subnet_dictionary['parent_id'] = str(subnet['parent_id'])
                subnet_dictionary['vlan_common_name'] = str(subnet['vlan_common_name'])
                subnet_dictionary['admin'] = str(subnet['admin'])
                subnet_dictionary['responsible'] = str(subnet['responsible'])
                subnet_dictionary['comments'] = str(subnet['comments'])

                super_subnet = 'True' if subnet['is_physical'] else 'False'
                subnet_dictionary['is_physical'] = super_subnet
                options = SubnetOption.objects.raw(subnet_option_query % (subnet['id']))

                physical_attributes = collections.OrderedDict()
                range_attributes = collections.OrderedDict()
                gatewaydevice_attributes = collections.OrderedDict()
                securityzone_attributes = collections.OrderedDict()
                for option in options:
                    if option.name.lower() == 'provider':
                        subnet_dictionary['provider'] = str(option.value_id)
                    elif option.name.lower() == 'customer':
                        subnet_dictionary['customer'] = str(option.value_id)
                    elif option.name == 'Allocated by RIPE/ARIN/APNIC':
                        subnet_dictionary['allocated_by'] = str(option.value_id)

                    if super_subnet == 'True':
                        if option.name.lower() == 'vlan usage':
                            physical_attributes['vlan_usage'] = str(option.value_id)
                        elif option.name.lower() == 'environment':
                            physical_attributes['environment'] = str(option.value_id)
                        elif option.name.lower() == 'status':
                            physical_attributes['status'] = str(option.value_id)
                        elif option.name.lower() == 'vrf':
                            physical_attributes['vrf'] = str(option.value_id)
                        elif option.name.lower() == 'dns on demand status':
                            physical_attributes['dns_on_demand_status'] = str(option.value_id)

                        dmz = 'True' if subnet['dmz'] else 'False'
                        physical_attributes['dmz'] = dmz
        except ValueError as e:
            print(e)
            pass
        return subnet_list
</code>```

答:
First, create a file named pagination.py in your app. then copy these codes:

```<code>class LargeResultsSetPagination(PageNumberPagination):
    page_size = 1000
    page_size_query_param = 'page_size'
    max_page_size = 10000

class StandardResultsSetPagination(PageNumberPagination):
    page_size = 100
    page_size_query_param = 'page_size'
    max_page_size = 1000
</code>```

After that, you can use from those classes like example below:

```<code>class BillingRecordsView(generics.ListAPIView):
    queryset = Billing.objects.all()
    serializer_class = BillingRecordsSerializer
    pagination_class = LargeResultsSetPagination
</code>```

Body:
I have created a ListView in DRF 3. As database structure is complex I have written a custom query i.e. raw query to fetch the data. But as the data size is huge, it takes a lot of time to load it. So I need to implement pagination. Below is the code.

class SubnetList(APIView):

    def get(self, request, format=None):
        subnet_list = get_subnet_details(None)
        return Response(subnet_list, status=status.HTTP_200_OK)

    def get_subnet_details(subnet_id=None):
        if subnet_id:
            subnets = Subnet.objects.filter(id=subnet_id).values()
        if not subnets:
            raise Http404
        else:
            subnets = Subnet.objects.values()

        subnet_list = []
        subnet_option_query = ' SELECT  ' \
                              ' options_value.id as value_id,' \
                              ' options_value.content,' \
                              ' options_option.id,' \
                              ' options_option.name' \
                              ' FROM subnets_subnetoption' \
                              ' INNER JOIN subnets_subnet ON (subnets_subnetoption.subnet_id = subnets_subnet.id)' \
                              ' INNER JOIN options_value ON (subnets_subnetoption.value_id = options_value.id)' \
                              ' INNER JOIN options_option ON (options_value.option_id = options_option.id)' \
                              ' INNER JOIN options_scope ON (options_option.scope_id = options_scope.id)' \
                              ' WHERE subnets_subnetoption.subnet_id = %s '

        try:
            for subnet in subnets:
                subnet_dictionary = collections.OrderedDict()
                subnet_dictionary['subnet_id'] = str(subnet['id'])
                subnet_dictionary['name'] = str(subnet['name'])
                subnet_dictionary['base_address'] = str(subnet['base_address'])
                subnet_dictionary['bcast_address'] = str(subnet['bcast_address'])
                subnet_dictionary['bits'] = str(subnet['bits'])
                subnet_dictionary['begin'] = str(subnet['base_address'])
                subnet_dictionary['end'] = str(subnet['bcast_address'])
                subnet_dictionary['parent_id'] = str(subnet['parent_id'])
                subnet_dictionary['vlan_common_name'] = str(subnet['vlan_common_name'])
                subnet_dictionary['admin'] = str(subnet['admin'])
                subnet_dictionary['responsible'] = str(subnet['responsible'])
                subnet_dictionary['comments'] = str(subnet['comments'])

                super_subnet = 'True' if subnet['is_physical'] else 'False'
                subnet_dictionary['is_physical'] = super_subnet
                options = SubnetOption.objects.raw(subnet_option_query % (subnet['id']))

                physical_attributes = collections.OrderedDict()
                range_attributes = collections.OrderedDict()
                gatewaydevice_attributes = collections.OrderedDict()
                securityzone_attributes = collections.OrderedDict()
                for option in options:
                    if option.name.lower() == 'provider':
                        subnet_dictionary['provider'] = str(option.value_id)
                    elif option.name.lower() == 'customer':
                        subnet_dictionary['customer'] = str(option.value_id)
                    elif option.name == 'Allocated by RIPE/ARIN/APNIC':
                        subnet_dictionary['allocated_by'] = str(option.value_id)

                    if super_subnet == 'True':
                        if option.name.lower() == 'vlan usage':
                            physical_attributes['vlan_usage'] = str(option.value_id)
                        elif option.name.lower() == 'environment':
                            physical_attributes['environment'] = str(option.value_id)
                        elif option.name.lower() == 'status':
                            physical_attributes['status'] = str(option.value_id)
                        elif option.name.lower() == 'vrf':
                            physical_attributes['vrf'] = str(option.value_id)
                        elif option.name.lower() == 'dns on demand status':
                            physical_attributes['dns_on_demand_status'] = str(option.value_id)

                        dmz = 'True' if subnet['dmz'] else 'False'
                        physical_attributes['dmz'] = dmz
        except ValueError as e:
            print(e)
            pass
        return subnet_list

Body:
First, create a file named pagination.py in your app. then copy these codes:

class LargeResultsSetPagination(PageNumberPagination):
    page_size = 1000
    page_size_query_param = 'page_size'
    max_page_size = 10000

class StandardResultsSetPagination(PageNumberPagination):
    page_size = 100
    page_size_query_param = 'page_size'
    max_page_size = 1000

After that, you can use from those classes like example below:

class BillingRecordsView(generics.ListAPIView):
    queryset = Billing.objects.all()
    serializer_class = BillingRecordsSerializer
    pagination_class = LargeResultsSetPagination


问:
Wicket - Top level menu freezes on click of Context Menu
My application has top-level menu and context menu for a page which displays certain report details. On clicking this context menu icon, i will get a context menu with certain actions as shown below

Now, the problem is whenever i click this context menu and do nothing (not chosen any actions of from that context menu), the top level menu is frozen. I need to refresh the page to get it working. I am using below wicket code to deal with actions on context menu -

on click of context menu, action will be null and on click of Delete, Edit or Copy, action will go to else loop. If it goes in else loop, I am good as page will be navigated to another and top level menu works. In case of action null, where scheduleRequestHandlerAfterCurrent is being called, I am facing issue with frozen top-level menu.

```<code>@Override
    public void onRequest()
    {
        final Component component = getComponent();
        final IRequestCycle cycle = component.getRequestCycle();
        final IRequestParameters parameters = cycle.getRequest().getRequestParameters();
        final String action = parameters.getParameterValue("action").toString(null);
        if (null == action)
        {
            cycle.scheduleRequestHandlerAfterCurrent(new TextRequestHandler("application/json", "UTF-8",
                    buildResponse()));
        } else
        {
            final String target = parameters.getParameterValue("targetId").toString(null);
            if (null == target)
            {
                throw new RuntimeException(
                        String.format("Did not receive a target object identifier for action [%s].", action));
            }
            menu.getAdapter().performActionOnTarget(component, action, target);
        }
    }
</code>```

答: There was an $(document).unbind('click'); line in custom JS before showing up the context menu. This context menu was earlier designed to show on mouse right click. IN the new implementation, it was changed to show in the event of mouse click. Removing that unbind statement fixed this issue in my case..

Body:
My application has top-level menu and context menu for a page which displays certain report details. On clicking this context menu icon, i will get a context menu with certain actions as shown below

Now, the problem is whenever i click this context menu and do nothing (not chosen any actions of from that context menu), the top level menu is frozen. I need to refresh the page to get it working. I am using below wicket code to deal with actions on context menu -

on click of context menu, action will be null and on click of Delete, Edit or Copy, action will go to else loop. If it goes in else loop, I am good as page will be navigated to another and top level menu works. In case of action null, where scheduleRequestHandlerAfterCurrent is being called, I am facing issue with frozen top-level menu.

@Override
    public void onRequest()
    {
        final Component component = getComponent();
        final IRequestCycle cycle = component.getRequestCycle();
        final IRequestParameters parameters = cycle.getRequest().getRequestParameters();
        final String action = parameters.getParameterValue("action").toString(null);
        if (null == action)
        {
            cycle.scheduleRequestHandlerAfterCurrent(new TextRequestHandler("application/json", "UTF-8",
                    buildResponse()));
        } else
        {
            final String target = parameters.getParameterValue("targetId").toString(null);
            if (null == target)
            {
                throw new RuntimeException(
                        String.format("Did not receive a target object identifier for action [%s].", action));
            }
            menu.getAdapter().performActionOnTarget(component, action, target);
        }
    }


问:
ValueError: I/O operation on closed file - Beginner working with multiple files
I am just learning python (2.7) and am making a simple text maze game with multiple levels on different files:

```<code>try: #this one works perfectly, it runs the file until it quits with quit()
  execfile("....Lockdown.py")
except SystemExit:
  print "Next Level"

try: #this one doesn't work even though it is almost perfectly identical with Lockdown
  execfile("....Lockdown2.py")
except SystemExit:
  print "Next Level"

#other levels
</code>```

When it runs Lockdown2.py I get

```<code>Traceback (most recent call last):
  File LockdownGame.py ...
  #-> until execfile("....Lockdown2.py")
  File "...Lockdown2.py", line 708, in available  #available is another function
decide(raw_input("Where do you decide to head? "))

ValueError: I/O operation on closed file
</code>```

Lockdown2 (and Lockdown) works like this

```<code>#the building of the maze
def available(): #checks where the user can walk
    #looks through the entire maze to look at where the user is standing, where his back is and if there are walls in that direction
    #makes sure the user isn't facing
    print "You can walk %s." % (can_walk[0]) #cutting out how it tells this
    decide(raw_input("What direction do you decide to head? "))

def decide(dec):
    if dec == "left": #and the other three directions,
        #edits the maze and their surrounding to their new location
   else:
      print "(Write your option as it's written)"
      decide(raw_input("What direction do you decide to head? "))

available()
</code>```

It crashes after putting up the raw_input, even though it is virtually identical code to Lockdown, and it doesn't error in prints before this, or when this raw_input is in Lockdown.

答: Change quit() to sys.exit(), it will completely close off Lockdown before initiating Lockdown2

Body:
I am just learning python (2.7) and am making a simple text maze game with multiple levels on different files:

try: #this one works perfectly, it runs the file until it quits with quit()
  execfile("....Lockdown.py")
except SystemExit:
  print "Next Level"

try: #this one doesn't work even though it is almost perfectly identical with Lockdown
  execfile("....Lockdown2.py")
except SystemExit:
  print "Next Level"

#other levels

When it runs Lockdown2.py I get

Traceback (most recent call last):
  File LockdownGame.py ...
  #-> until execfile("....Lockdown2.py")
  File "...Lockdown2.py", line 708, in available  #available is another function
decide(raw_input("Where do you decide to head? "))

ValueError: I/O operation on closed file

Lockdown2 (and Lockdown) works like this

#the building of the maze
def available(): #checks where the user can walk
    #looks through the entire maze to look at where the user is standing, where his back is and if there are walls in that direction
    #makes sure the user isn't facing
    print "You can walk %s." % (can_walk[0]) #cutting out how it tells this
    decide(raw_input("What direction do you decide to head? "))

def decide(dec):
    if dec == "left": #and the other three directions,
        #edits the maze and their surrounding to their new location
   else:
      print "(Write your option as it's written)"
      decide(raw_input("What direction do you decide to head? "))

available()

It crashes after putting up the raw_input, even though it is virtually identical code to Lockdown, and it doesn't error in prints before this, or when this raw_input is in Lockdown.


问:
Semantic UI Icons-font not loading
I am building a website using the Semantic UI CSS framework, and now I want to use some of its icons.

Here is the HTML:

```<code><h1>Title<i class="lab icon"></i></h1>
</code>```

I have linked the semantic.css, but I assume I need to do something else too to get the icons working? I tried linking this too:

```<code><link href="//netdna.bootstrapcdn.com/font-awesome/4.0.3/css/font-awesome.css" rel="stylesheet">
</code>```

But it still doesn't work. What am I missing?

答:
My solution was pretty simple (once I worked it out). I had edited themes.config to use my new (yet to be built) theme. As you know it falls back to defaultso everything seemed to work OK.

```<code>/* Elements */
:
@flag       : 'supernewtheme';
@header     : 'supernewtheme';
@icon       : 'supernewtheme';
@image      : 'supernewtheme';
@input      : 'supernewtheme';
:
</code>```

Even though the console showed the Icons font loading (no 404), iti didn't work. I also checked the font was in my build folder in the correct place, it was.

Changing the theme back to default for @icon did the trick:

```<code>@icon       : 'default';
</code>```

Title: Semantic UI Icons-font not loading

Body:
I am building a website using the Semantic UI CSS framework, and now I want to use some of its icons.

Here is the HTML:

Title

I have linked the semantic.css, but I assume I need to do something else too to get the icons working? I tried linking this too:

<link href="//netdna.bootstrapcdn.com/font-awesome/4.0.3/css/font-awesome.css" rel="stylesheet">

But it still doesn't work. What am I missing?

Body:
My solution was pretty simple (once I worked it out). I had edited themes.config to use my new (yet to be built) theme. As you know it falls back to defaultso everything seemed to work OK.

/* Elements */
:
@flag       : 'supernewtheme';
@header     : 'supernewtheme';
@icon       : 'supernewtheme';
@image      : 'supernewtheme';
@input      : 'supernewtheme';
:

Even though the console showed the Icons font loading (no 404), iti didn't work. I also checked the font was in my build folder in the correct place, it was.

Changing the theme back to default for @icon did the trick:

@icon       : 'default';


问:
error CS0433: The imported type `System.Net.WebRequest' is defined multiple times
when i'm loading my C# script, i get the error message in title.

My script starts with these lines:

```<code>using System;
using System.Net;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using TradeServer.ScriptingDriver.DataObjects;
using TradeServer.ScriptingDriver.Interfaces
</code>```

;

ANd the error comes from that first line:

```<code>WebRequest request = HttpWebRequest.Create("https://drive.google.com/file/d/....");
WebResponse webResp = request.GetResponse();
System.IO.StreamReader sr = new System.IO.StreamReader(webResp.GetResponseStream());
string newestversion = sr.ReadToEnd();
</code>```

I've tried to comment out pretty much all permutations, it just does not work, creates more error codes, or always spits out error in title.

I understand from searching on Google that i have some kind of duplicate issues in my libraries, but i'm really no expert on this.

If anyone 's got a clue how to fix this. Appreciated.

答:
This sounds like it is happening because you have two different assemblies being referenced that contain a type of the same name WebRequest.

You'll want to be explicit about which assemblies' WebRequest type you want to use. In your case try:

```<code>System.Net.WebRequest request = HttpWebRequest.Create("https://drive.google.com/file/d/....");
</code>```

Update:

Here's a way to get more information about what exactly is causing this conflict. Try putting this in before the line throwing the original error. It should cause a new error but this time we should see more information about those conflicting sources.

System.Runtime.InteropServices.DefaultParameterValueAttribute x = null;

This should tell you something like:

The type 'System.Runtime.InteropServices.DefaultParameterValueAttribute' exists in both 'c:\Program Files\Reference Assemblies\Microsoft\Framework\v3.5\System.Core.dll' and .....

Body:
when i'm loading my C# script, i get the error message in title.

My script starts with these lines:

using System;
using System.Net;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using TradeServer.ScriptingDriver.DataObjects;
using TradeServer.ScriptingDriver.Interfaces

;

ANd the error comes from that first line:

WebRequest request = HttpWebRequest.Create("https://drive.google.com/file/d/....");
WebResponse webResp = request.GetResponse();
System.IO.StreamReader sr = new System.IO.StreamReader(webResp.GetResponseStream());
string newestversion = sr.ReadToEnd();

I've tried to comment out pretty much all permutations, it just does not work, creates more error codes, or always spits out error in title.

I understand from searching on Google that i have some kind of duplicate issues in my libraries, but i'm really no expert on this.

If anyone 's got a clue how to fix this. Appreciated.

Body:
This sounds like it is happening because you have two different assemblies being referenced that contain a type of the same name WebRequest.

You'll want to be explicit about which assemblies' WebRequest type you want to use. In your case try:

System.Net.WebRequest request = HttpWebRequest.Create("https://drive.google.com/file/d/....");

Update:

Here's a way to get more information about what exactly is causing this conflict. Try putting this in before the line throwing the original error. It should cause a new error but this time we should see more information about those conflicting sources.

System.Runtime.InteropServices.DefaultParameterValueAttribute x = null;

This should tell you something like:

The type 'System.Runtime.InteropServices.DefaultParameterValueAttribute' exists in both 'c:\Program Files\Reference Assemblies\Microsoft\Framework\v3.5\System.Core.dll' and .....


问:
Count number of binds on an event
I have got a child component which shows a table of data. I want to provide a "select" button on every row, but only if the table is shown in a context where the button is needed, i.e. the table might be shown either standalone or as a selection for a form field.

My idea is to use an EventEmitter for the "select" button and display the button only if there are any subscribers to the event. How is this achieved or are there any better ways to do this?

I'm using angular 2 rc.5

Edit: Example code:

```<code>@Component({directives: [Child], template: "<child (select)="onSelect()"></child>"})
class Parent {
}

@Component({selector: "child", template: "<div *ngIf="showSelect" (click)="onSelect()">select</div>"})
class Child {
    @Output("select") select: EventEmitter<any> = new EventEmitter<any>();
    get showSelect() {
        // return true if there is any subscription to Output("select")
    }
}
</code>```

The DIV in the Child component should only be shown if the parent defines a listener to this "select" event. In this case it does by binding it in the template, but it should also work if someone calls .subscribe() directly on the Child component's "select" property.

答:
select.observers.length will tell you how many subscribers there are on an EventEmitter (in this example, for an EventEmitter named 'select'). The general pattern is <myEmitter>.observers.length.

0 means you have a subscriber.

Title: Count number of binds on an event

Body:
I have got a child component which shows a table of data. I want to provide a "select" button on every row, but only if the table is shown in a context where the button is needed, i.e. the table might be shown either standalone or as a selection for a form field.

My idea is to use an EventEmitter for the "select" button and display the button only if there are any subscribers to the event. How is this achieved or are there any better ways to do this?

I'm using angular 2 rc.5

Edit: Example code:

@Component({directives: [Child], template: "<child (select)="onSelect()"></child>"})
class Parent {
}

@Component({selector: "child", template: "
select
"})
class Child {
    @Output("select") select: EventEmitter<any> = new EventEmitter<any>();
    get showSelect() {
        // return true if there is any subscription to Output("select")
    }
}

The DIV in the Child component should only be shown if the parent defines a listener to this "select" event. In this case it does by binding it in the template, but it should also work if someone calls .subscribe() directly on the Child component's "select" property.


问:
How to create Uri pointing to an local image in Silverlight?
I was wondering if it is allowed to read local images within a Silverlight client. (it is just to test a control)

```<code>var image = new BitmapImage { UriSource = new Uri("../Images/2.jpg", UriKind.Relative) };
</code>```

Would this Uri be allowed and the image created? For some reason the picture doesn't show, despite getting no compiler errors that the Uri might have been wrong...

Thanks for advice,
kave

答:
Assuming your project looks like this

```<code> - Project
      - Images
           - 2.jpg
      - Another_Folder
           - *your code file*
</code>```

, that should be fine.

Remember that

```<code>../Images/2.jpg
</code>```

is navigating to parent folder, then looking for an Images folder and a 2.jpg file.

Body:
I was wondering if it is allowed to read local images within a Silverlight client. (it is just to test a control)

var image = new BitmapImage { UriSource = new Uri("../Images/2.jpg", UriKind.Relative) };

Would this Uri be allowed and the image created? For some reason the picture doesn't show, despite getting no compiler errors that the Uri might have been wrong...

Thanks for advice,
kave

Body:
Assuming your project looks like this

 - Project
      - Images
           - 2.jpg
      - Another_Folder
           - *your code file*

, that should be fine.

Remember that

../Images/2.jpg

is navigating to parent folder, then looking for an Images folder and a 2.jpg file.


问:
java.nio.BufferOverflowException constructing byte[]
I'm building a byte array to identify an M-Bus Master and i need to do it using the secondary address.

To do it i need to build a byte[] with the identification of the address:

Identification Number (4 bytes) – A number ranging from 00000000 to
99999999 to identify the meter.

Manufacturer ID (2 bytes) – Three letters that identify the
manufacturer.

Version (1 byte) – Specifies the version of the device. The version
is manufacturer specific.

Device type (1 byte) – This field codes the device type (e.g.
electricity meter, cold water meter)

If my math is not failing me this has a total of 8 bytes.

So here is my code to do it:

```<code>public static void main(String[] args) {
    // TODO code application logic here
    MBusSerialBuilder builder = MBusConnection.newSerialBuilder("COM4").setBaudrate(2400);
    try (MBusConnection mBusConnection = builder.build()) {
        // read/write
        int primaryAddress = 253;

        byte[] idNum = ByteBuffer.allocate(4).putInt(46152604).array();
        byte version = 0xFF & 88; //only need a byte not a 4 byte int
        byte deviceType = 0xFF & 13; //only need a byte not a 4 byte int
        short manuID = createManuID("ZRI");
        //builds the message without overflow now
        byte[] data = ByteBuffer.allocate(8).put(idNum).putShort(manuID).put(version).put(deviceType).array();

        mBusConnection.write(primaryAddress, data);
        VariableDataStructure vds = mBusConnection.read(primaryAddress);
        System.out.println(vds);
    } catch (IOException ex) {
        System.out.println(ex.getLocalizedMessage());
        Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
    }
}
</code>```

Note previouslly i had

```<code>byte[] manId = ByteBuffer.allocate(2).putChar('Z').putChar('R').putChar('I').array();
</code>```

And it was returning me java.nio.BufferOverflowException.

With the recent changes the error is now on data declaration.

Even if i alloc 50 bytes

```<code>byte[] data = ByteBuffer.allocate(50).put(idNum).put(manId).putInt(88).putInt(13).array();
</code>```

Diferent error

```<code>java.lang.IndexOutOfBoundsException
</code>```

Here is some info i extracted from a log file of the seller's program.

```<code>MBus Tx_raw-><11><68><b><b><68><53><fd><52><4><26><15><46><ff><ff><ff><ff><23><16>
MBus Rx_raw-><0><aa><1><e5><0><0><0><0><0><0><0><0><0><0><0><0><0><0><0><0><0><0><0><0><0><0><0><0><0><0><0><0><0><0><0><0><0><0><0><0><0><0><0><0><0><0><0><0><0><0><0><0><0><0><0><0><0><0><0><0><0><0><0><0>
MBus Tx_raw-><5><10><7b><fd><78><16>
MBus Rx_raw-><0><aa><b7><68><b1><b1><68><8><0><72><4><26><15><46><49><6a><88><d><29><0><0><0><4><6d><34><a><27><2c><82><4><6c><21><21><82><a><6c><21><2c><4><6><0><0><0><0><84><4><6><0><0><0><0><84><a><6><0><0><0><0><4><13><4a><30><0><0>
MBus consecutive Frame [183]-><68><b1><b1><68><8><0><72><4><26><15><46><49><6a><88><d><29><0><0><0><4><6d><34><a><27><2c><82><4><6c><21><21><82><a><6c><21><2c><4><6><0><0><0><0><84><4><6><0><0><0><0><84><a><6><0><0><0><0><4><13><4a><30><0><0><2><59><8a><7><2><5d><bc><7><2><61><ce><ff><4><3b><bf><2><0><0><4><2d><4><0><0><0><4><26><b><8><0><0><84><10><6><2><0><0><0><84><14><6><0><0><0><0><84><1a><6><0><0><0><0><84><40><14><c1><6><0><0><84><44><14><0><0><0><0><84><4a><14><a9><0><0><0><84><80><40><14><10><0><0><0><84><84><40><14><0><0><0><0><84><8a><40><14><0><0><0><0><84><c0><40><14><e3><0><0><0><84><c4><40><14><0><0><0><0><84><ca><40><14><0><0><0><0><1b><16>

Readout insert->INSERT INTO LETTURE_CONTATORI_TEMP VALUES(NULL,'OK','1','1','510','07/12/2017 10:16:23','','','1512641783','0','07/12/2017 10:52','01/01/2017','01/12/2017','0','0','0','12362','1930','1980','-50','703','4','2059','2','0','0','1729','0','169','16','0','0','227','0','0','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','');
</code>```

答:
Ok, so with an offset of 65 (A) to every character you can create a mapping so-to-speak of the letters to convert them to smaller values which will fit in the 2 bytes (16 bits) whereby the values range from 0 to 25 (0=A, 1=B..., 25=Z). Since this range requires at most 5 bits, and you have a maximum of 3 characters  to convert, you only need 15 bits and can squeeze these into the 2 bytes (16 bits) required for the manufacturer id. All you have to do is apply a bit shift of 5 (size of the values) * the index of the character in your manufacturer id string.

Here is the method

```<code>  public static short createManuID(String id)
  {
      int bitMashedManuID = 0;
      id = id.toUpperCase(); //force the chars to be within 65-90
      if(id.length() == 3)
      {
          short offset = 65; //A = 0, B = 1 ... Z = 25
          //number bits needed to fit 0-25 and so values won't overlap during the bit mashing
          short bitShift = 5;
          for(int i = 0; i < id.length(); i++)
          {
              short valueOfChar = (short)id.charAt(i);
              valueOfChar -= offset; //apply the offset
              bitMashedManuID += valueOfChar << bitShift * i; //pack the bits
          }
      }
      return (short)bitMashedManuID;
  }
</code>```

Example

Z = 90, apply the offset of 65 and we get 25 (11001)

So a manufacturer id of ZZZ should look like (11001|11001|11001) which equals 26425.

```<code>System.out.println(createManuID("ZZZ")); //outputs 26425
</code>```

Your manufacturer id

```<code>Z = 90 - 65 = 25 = 11001
R = 82 - 65 = 17 = 10001
I = 73 - 65 = 8  = 01000

ZRI = |01000|10001|11001| = 8761

System.out.println(createManuID("ZRI")); //8761
</code>```

Therefore when all is said and done you can create your byte array like this without overflow and satisfying the 8 byte array length requirement.

```<code>  public static void main(String[] args)
  {
      byte[] idNum = ByteBuffer.allocate(4).putInt(46152604).array();
      byte version = 0xFF & 88; //only need a byte not a 4 byte int
      byte deviceType = 0xFF & 13; //only need a byte not a 4 byte int

      short manuID = createManuID("ZRI");
      //builds the message without overflow now
      byte[] data = ByteBuffer.allocate(8).put(idNum).putShort(manuID).put(version).put(deviceType).array();

  }
</code>```

All that's left is determine the order of the letters are going to be packed in. Currently I pack them  from right to left but depending on the device you are talking to it may require left to right which means you have the loop start at for(int i = id.length() - 1; i >= 0; i--)

Body:
I'm building a byte array to identify an M-Bus Master and i need to do it using the secondary address.

To do it i need to build a byte[] with the identification of the address:

Identification Number (4 bytes) – A number ranging from 00000000 to
99999999 to identify the meter.

Manufacturer ID (2 bytes) – Three letters that identify the
manufacturer.

Version (1 byte) – Specifies the version of the device. The version
is manufacturer specific.

Device type (1 byte) – This field codes the device type (e.g.
electricity meter, cold water meter)

If my math is not failing me this has a total of 8 bytes.

So here is my code to do it:

public static void main(String[] args) {
    // TODO code application logic here
    MBusSerialBuilder builder = MBusConnection.newSerialBuilder("COM4").setBaudrate(2400);
    try (MBusConnection mBusConnection = builder.build()) {
        // read/write
        int primaryAddress = 253;

        byte[] idNum = ByteBuffer.allocate(4).putInt(46152604).array();
        byte version = 0xFF & 88; //only need a byte not a 4 byte int
        byte deviceType = 0xFF & 13; //only need a byte not a 4 byte int
        short manuID = createManuID("ZRI");
        //builds the message without overflow now
        byte[] data = ByteBuffer.allocate(8).put(idNum).putShort(manuID).put(version).put(deviceType).array();

        mBusConnection.write(primaryAddress, data);
        VariableDataStructure vds = mBusConnection.read(primaryAddress);
        System.out.println(vds);
    } catch (IOException ex) {
        System.out.println(ex.getLocalizedMessage());
        Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
    }
}

Note previouslly i had

byte[] manId = ByteBuffer.allocate(2).putChar('Z').putChar('R').putChar('I').array();

And it was returning me java.nio.BufferOverflowException.

With the recent changes the error is now on data declaration.

Even if i alloc 50 bytes

byte[] data = ByteBuffer.allocate(50).put(idNum).put(manId).putInt(88).putInt(13).array();

Diferent error

java.lang.IndexOutOfBoundsException

Here is some info i extracted from a log file of the seller's program.

MBus Tx_raw-><11><68><68><53><fd><52><4><26><15><46><ff><ff><ff><ff><23><16>
MBus Rx_raw-><0><aa><1><e5><0><0><0><0><0><0><0><0><0><0><0><0><0><0><0><0><0><0><0><0><0><0><0><0><0><0><0><0><0><0><0><0><0><0><0><0><0><0><0><0><0><0><0><0><0><0><0><0><0><0><0><0><0><0><0><0><0><0><0><0>
MBus Tx_raw-><5><10><7b><fd><78><16>
MBus Rx_raw-><0><aa><b7><68><b1><b1><68><8><0><72><4><26><15><46><49><6a><88><d><29><0><0><0><4><6d><34><27><2c><82><4><6c><21><21><82><6c><21><2c><4><6><0><0><0><0><84><4><6><0><0><0><0><84><6><0><0><0><0><4><13><4a><30><0><0>
MBus consecutive Frame [183]-><68><b1><b1><68><8><0><72><4><26><15><46><49><6a><88><d><29><0><0><0><4><6d><34><27><2c><82><4><6c><21><21><82><6c><21><2c><4><6><0><0><0><0><84><4><6><0><0><0><0><84><6><0><0><0><0><4><13><4a><30><0><0><2><59><8a><7><2><5d><bc><7><2><61><ce><ff><4><3b><bf><2><0><0><4><2d><4><0><0><0><4><26><8><0><0><84><10><6><2><0><0><0><84><14><6><0><0><0><0><84><1a><6><0><0><0><0><84><40><14><c1><6><0><0><84><44><14><0><0><0><0><84><4a><14><a9><0><0><0><84><80><40><14><10><0><0><0><84><84><40><14><0><0><0><0><84><8a><40><14><0><0><0><0><84><c0><40><14><e3><0><0><0><84><c4><40><14><0><0><0><0><84><ca><40><14><0><0><0><0><1b><16>

Readout insert->INSERT INTO LETTURE_CONTATORI_TEMP VALUES(NULL,'OK','1','1','510','07/12/2017 10:16:23','','','1512641783','0','07/12/2017 10:52','01/01/2017','01/12/2017','0','0','0','12362','1930','1980','-50','703','4','2059','2','0','0','1729','0','169','16','0','0','227','0','0','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','');

Body:
Ok, so with an offset of 65 (A) to every character you can create a mapping so-to-speak of the letters to convert them to smaller values which will fit in the 2 bytes (16 bits) whereby the values range from 0 to 25 (0=A, 1=B..., 25=Z). Since this range requires at most 5 bits, and you have a maximum of 3 characters  to convert, you only need 15 bits and can squeeze these into the 2 bytes (16 bits) required for the manufacturer id. All you have to do is apply a bit shift of 5 (size of the values) * the index of the character in your manufacturer id string.

Here is the method

  public static short createManuID(String id)
  {
      int bitMashedManuID = 0;
      id = id.toUpperCase(); //force the chars to be within 65-90
      if(id.length() == 3)
      {
          short offset = 65; //A = 0, B = 1 ... Z = 25
          //number bits needed to fit 0-25 and so values won't overlap during the bit mashing
          short bitShift = 5;
          for(int i = 0; i < id.length(); i++)
          {
              short valueOfChar = (short)id.charAt(i);
              valueOfChar -= offset; //apply the offset
              bitMashedManuID += valueOfChar << bitShift * i; //pack the bits
          }
      }
      return (short)bitMashedManuID;
  }

Example

Z = 90, apply the offset of 65 and we get 25 (11001)

So a manufacturer id of ZZZ should look like (11001|11001|11001) which equals 26425.

System.out.println(createManuID("ZZZ")); //outputs 26425

Your manufacturer id

Z = 90 - 65 = 25 = 11001
R = 82 - 65 = 17 = 10001
I = 73 - 65 = 8  = 01000

ZRI = |01000|10001|11001| = 8761

System.out.println(createManuID("ZRI")); //8761

Therefore when all is said and done you can create your byte array like this without overflow and satisfying the 8 byte array length requirement.

  public static void main(String[] args)
  {
      byte[] idNum = ByteBuffer.allocate(4).putInt(46152604).array();
      byte version = 0xFF & 88; //only need a byte not a 4 byte int
      byte deviceType = 0xFF & 13; //only need a byte not a 4 byte int

      short manuID = createManuID("ZRI");
      //builds the message without overflow now
      byte[] data = ByteBuffer.allocate(8).put(idNum).putShort(manuID).put(version).put(deviceType).array();

  }

All that's left is determine the order of the letters are going to be packed in. Currently I pack them  from right to left but depending on the device you are talking to it may require left to right which means you have the loop start at for(int i = id.length() - 1; i >= 0; i--)


问:
Why we use a complex equation when do convert RGB to YCBCR instead of a simple one?
When I do implement RGB2YCBCR on verilog. I saw several ways to convert RGB to YCBCR. Some of it are very simple. But others are quite complex.

For example, if we use

```<code>y = (r >> 2) + (g >> 1) + (b >> 2);
</code>```

it is very easy to implement to hardware

But some people say that

```<code>y = (r*4899 + g*9617+ b*1868+ 8192) >> 14
</code>```

is faster???

I don't know why they have this equation and why a complex equation better than a simple equation. And WHY THEY USE IT instead of that simple equation.

P/S: I saw that OpenCV also uses that complex one.
Thank a lot!

答:
On processors with a multiplier and a barrel shifter, all these operations take a single clock cycle and the second formula cannot be faster (5 ops vs. 7).

The complex equation is mandated by a standard coming from the television technology, with historical and technological reasons (https://en.wikipedia.org/wiki/Rec._601).

Color spaces is a rather complex topic.

Note that the first formula is not normalized: if the input values are in range [0,1], the outputs are in [0, 10], and you should divide by 10. This would make the first formula much slower.

Body:
When I do implement RGB2YCBCR on verilog. I saw several ways to convert RGB to YCBCR. Some of it are very simple. But others are quite complex.

For example, if we use

y = (r >> 2) + (g >> 1) + (b >> 2);

it is very easy to implement to hardware

But some people say that

y = (r*4899 + g*9617+ b*1868+ 8192) >> 14

is faster???

I don't know why they have this equation and why a complex equation better than a simple equation. And WHY THEY USE IT instead of that simple equation.

P/S: I saw that OpenCV also uses that complex one.
Thank a lot!