问:
RESTful client in order to test my POST method
I am working on the RESTful cloud application in java and once I implemented all the methods for POST, DELETE, PUT and GET, i need to test them through a simple java client. I successfully tested the GET and DELETE in the following manner:

```<code>String findById = target.path("..").path("..").path("17").request()
.accept(MediaType.APPLICATION_JSON).get(String.class).toString();
System.out.println(findById);
</code>```

But now when I want to try the PUT and POST, I can not make it work. I tried the following:

```<code>String addBook = target.path("..").path("..").queryParam("author", "OO")
                .queryParam("language", "OO")
                .queryParam("publisher", "OO")
                .queryParam("subject", "OO")
                .queryParam("title", "OO")
                .queryParam("isbn", "OO").request().accept(MediaType.APPLICATION_JSON)
                .post(String.class);
</code>```

The error says that .post is expecting "The method post(Entity, Class) in the type SyncInvoker is not applicable for the arguments (String, Class)".

So my question is what the Entity should be and how should I specify it? Client project is running separately and not on the main(server) project.

答:
You cannot use query param to send a post request.
You have to use a post body, that can be in different content types, like JSON.
You have to change your code to something like this: </p>

```<code>Map<String, Object> body = new HashMap<>();
body.put("language", "OO");
.....
String json = (new ObjectMapper()).writeValueAsString(body);
Entity<String> entity = javax.ws.rs.client.Entity.json(json);
String result = client.target(fullUrl).request().method("POST", entity, String.class);
</code>```

Body:
I am working on the RESTful cloud application in java and once I implemented all the methods for POST, DELETE, PUT and GET, i need to test them through a simple java client. I successfully tested the GET and DELETE in the following manner:

String findById = target.path("..").path("..").path("17").request()
.accept(MediaType.APPLICATION_JSON).get(String.class).toString();
System.out.println(findById);

But now when I want to try the PUT and POST, I can not make it work. I tried the following:

String addBook = target.path("..").path("..").queryParam("author", "OO")
                .queryParam("language", "OO")
                .queryParam("publisher", "OO")
                .queryParam("subject", "OO")
                .queryParam("title", "OO")
                .queryParam("isbn", "OO").request().accept(MediaType.APPLICATION_JSON)
                .post(String.class);

The error says that .post is expecting "The method post(Entity, Class) in the type SyncInvoker is not applicable for the arguments (String, Class)".

So my question is what the Entity should be and how should I specify it? Client project is running separately and not on the main(server) project.

Body:
You cannot use query param to send a post request.
You have to use a post body, that can be in different content types, like JSON.
You have to change your code to something like this:

Map<String, Object> body = new HashMap<>();
body.put("language", "OO");
.....
String json = (new ObjectMapper()).writeValueAsString(body);
Entity<String> entity = javax.ws.rs.client.Entity.json(json);
String result = client.target(fullUrl).request().method("POST", entity, String.class);


来源: stackexchange

问:
where to place python file when it execute with php?
i am finding problem in passing string from php to python code.i think my code is fine but may be in problem of path of python file.so suggest me where i have to place python file when it execute with php file.thank u so much in advance

here is my code:-

test.php

```<code><?php
$s= "what is your name";
$output= shell_exec('xampp/htdocs/fbchat/public/test.py ' .$s);
echo $output;
?>
</code>```

test.py

```<code>import sys
x= sys.argv[1]
print x
</code>```

答:
You can place your python script any where, but you need to provide its full path name(exact location).

Assuming your file is in C drive of your computer:

Try this:

```<code>shell_exec('python c://xampp/htdocs/fbchat/public/test.py ' . $s);
</code>```

ContentLicense: CC BY-SA 3.0

Body:
i am finding problem in passing string from php to python code.i think my code is fine but may be in problem of path of python file.so suggest me where i have to place python file when it execute with php file.thank u so much in advance

here is my code:-

test.php

<?php
$s= "what is your name";
$output= shell_exec('xampp/htdocs/fbchat/public/test.py ' .$s);
echo $output;
?>

test.py

import sys
x= sys.argv[1]
print x

Body:
You can place your python script any where, but you need to provide its full path name(exact location).

Assuming your file is in C drive of your computer:

Try this:

shell_exec('python c://xampp/htdocs/fbchat/public/test.py ' . $s);


问:
Permission dialogs
In my AndroidManifest.xml:

```<code><uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
</code>```

But when I have installed my App-APK, I must setting up the permissions in my Android OS in the settings manually (Settings > Apps > myApp > Permissions > Storage).

How can I get that the permissions setting up automatically. Or the user of my App must confirm it in a dialog?

答:
Copy given class in your project.

```<code>package com.betaiit.helper;

import android.Manifest;
import android.annotation.TargetApi;
import android.app.Activity;
import android.content.Context;
import android.content.DialogInterface;
import android.content.pm.PackageManager;
import android.os.Build;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AlertDialog;

/**
 * Created by Sathish Gadde on 08/05/17.
*/
public class Utility {

public static final int MY_PERMISSIONS_REQUEST_READ_EXTERNAL_STORAGE = 123;
public static final int MY_PERMISSIONS_REQUEST_WRITE_EXTERNAL_STORAGE = 124;

/**
 * Check READ_EXTERNAL_STORAGE Permission
 */
@TargetApi(Build.VERSION_CODES.JELLY_BEAN)
public static boolean checkPermission_ReadExternalStorage(final Context context) {
    int currentAPIVersion = Build.VERSION.SDK_INT;
    if (currentAPIVersion >= Build.VERSION_CODES.M) {
        if (ContextCompat.checkSelfPermission(context, Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
            if (ActivityCompat.shouldShowRequestPermissionRationale((Activity) context, Manifest.permission.READ_EXTERNAL_STORAGE)) {
                AlertDialog.Builder alertBuilder = new AlertDialog.Builder(context);
                alertBuilder.setCancelable(true);
                alertBuilder.setTitle("Permission necessary");
                alertBuilder.setMessage("External storage permission is necessary");
                alertBuilder.setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
                    @TargetApi(Build.VERSION_CODES.JELLY_BEAN)
                    public void onClick(DialogInterface dialog, int which) {
                        ActivityCompat.requestPermissions((Activity) context, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, MY_PERMISSIONS_REQUEST_READ_EXTERNAL_STORAGE);
                    }
                });
                AlertDialog alert = alertBuilder.create();
                alert.show();

            } else {
                ActivityCompat.requestPermissions((Activity) context, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, MY_PERMISSIONS_REQUEST_READ_EXTERNAL_STORAGE);
            }
            return false;
        } else {
            return true;
        }
    } else {
        return true;
    }

}

/**
 * Check WRITE_EXTERNAL_STORAGE Permission
 */
@TargetApi(Build.VERSION_CODES.JELLY_BEAN)
public static boolean checkPermission_WriteExternalStorage(final Context context) {
    int currentAPIVersion = Build.VERSION.SDK_INT;
    if (currentAPIVersion >= Build.VERSION_CODES.M) {
        if (ContextCompat.checkSelfPermission(context, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
            if (ActivityCompat.shouldShowRequestPermissionRationale((Activity) context, Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
                AlertDialog.Builder alertBuilder = new AlertDialog.Builder(context);
                alertBuilder.setCancelable(true);
                alertBuilder.setTitle("Permission necessary");
                alertBuilder.setMessage("External storage permission is necessary");
                alertBuilder.setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
                    @TargetApi(Build.VERSION_CODES.JELLY_BEAN)
                    public void onClick(DialogInterface dialog, int which) {
                        ActivityCompat.requestPermissions((Activity) context, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, MY_PERMISSIONS_REQUEST_WRITE_EXTERNAL_STORAGE);
                    }
                });
                AlertDialog alert = alertBuilder.create();
                alert.show();

            } else {
                ActivityCompat.requestPermissions((Activity) context, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, MY_PERMISSIONS_REQUEST_WRITE_EXTERNAL_STORAGE);
            }
            return false;
        } else {
            return true;
        }
    } else {
        return true;
    }

}

}
</code>```

Now check permission from your activity :

```<code>    Utility.checkPermission_ReadExternalStorage(context);
    Utility.checkPermission_WriteExternalStorage(context);
</code>```

Now check permisson from your Fragment :

```<code>    Utility.checkPermission_ReadExternalStorage(getActivity());
    Utility.checkPermission_WriteExternalStorage(getActivity());
</code>```

Title: Permission dialogs

Body:
In my AndroidManifest.xml:

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />

But when I have installed my App-APK, I must setting up the permissions in my Android OS in the settings manually (Settings > Apps > myApp > Permissions > Storage).

How can I get that the permissions setting up automatically. Or the user of my App must confirm it in a dialog?

Body:
Copy given class in your project.

package com.betaiit.helper;

import android.Manifest;
import android.annotation.TargetApi;
import android.app.Activity;
import android.content.Context;
import android.content.DialogInterface;
import android.content.pm.PackageManager;
import android.os.Build;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AlertDialog;

/**
 * Created by Sathish Gadde on 08/05/17.
*/
public class Utility {

public static final int MY_PERMISSIONS_REQUEST_READ_EXTERNAL_STORAGE = 123;
public static final int MY_PERMISSIONS_REQUEST_WRITE_EXTERNAL_STORAGE = 124;

/**
 * Check READ_EXTERNAL_STORAGE Permission
 */
@TargetApi(Build.VERSION_CODES.JELLY_BEAN)
public static boolean checkPermission_ReadExternalStorage(final Context context) {
    int currentAPIVersion = Build.VERSION.SDK_INT;
    if (currentAPIVersion >= Build.VERSION_CODES.M) {
        if (ContextCompat.checkSelfPermission(context, Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
            if (ActivityCompat.shouldShowRequestPermissionRationale((Activity) context, Manifest.permission.READ_EXTERNAL_STORAGE)) {
                AlertDialog.Builder alertBuilder = new AlertDialog.Builder(context);
                alertBuilder.setCancelable(true);
                alertBuilder.setTitle("Permission necessary");
                alertBuilder.setMessage("External storage permission is necessary");
                alertBuilder.setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
                    @TargetApi(Build.VERSION_CODES.JELLY_BEAN)
                    public void onClick(DialogInterface dialog, int which) {
                        ActivityCompat.requestPermissions((Activity) context, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, MY_PERMISSIONS_REQUEST_READ_EXTERNAL_STORAGE);
                    }
                });
                AlertDialog alert = alertBuilder.create();
                alert.show();

            } else {
                ActivityCompat.requestPermissions((Activity) context, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, MY_PERMISSIONS_REQUEST_READ_EXTERNAL_STORAGE);
            }
            return false;
        } else {
            return true;
        }
    } else {
        return true;
    }

}

/**
 * Check WRITE_EXTERNAL_STORAGE Permission
 */
@TargetApi(Build.VERSION_CODES.JELLY_BEAN)
public static boolean checkPermission_WriteExternalStorage(final Context context) {
    int currentAPIVersion = Build.VERSION.SDK_INT;
    if (currentAPIVersion >= Build.VERSION_CODES.M) {
        if (ContextCompat.checkSelfPermission(context, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
            if (ActivityCompat.shouldShowRequestPermissionRationale((Activity) context, Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
                AlertDialog.Builder alertBuilder = new AlertDialog.Builder(context);
                alertBuilder.setCancelable(true);
                alertBuilder.setTitle("Permission necessary");
                alertBuilder.setMessage("External storage permission is necessary");
                alertBuilder.setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
                    @TargetApi(Build.VERSION_CODES.JELLY_BEAN)
                    public void onClick(DialogInterface dialog, int which) {
                        ActivityCompat.requestPermissions((Activity) context, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, MY_PERMISSIONS_REQUEST_WRITE_EXTERNAL_STORAGE);
                    }
                });
                AlertDialog alert = alertBuilder.create();
                alert.show();

            } else {
                ActivityCompat.requestPermissions((Activity) context, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, MY_PERMISSIONS_REQUEST_WRITE_EXTERNAL_STORAGE);
            }
            return false;
        } else {
            return true;
        }
    } else {
        return true;
    }

}

}

Now check permission from your activity :

    Utility.checkPermission_ReadExternalStorage(context);
    Utility.checkPermission_WriteExternalStorage(context);

Now check permisson from your Fragment :

    Utility.checkPermission_ReadExternalStorage(getActivity());
    Utility.checkPermission_WriteExternalStorage(getActivity());


问:
Passport req.isAuthenticated() always false when deployed to Heroku
I'm using passport with Nodejs. My application works as expected when I run on my localhost. When I deploy to Heroku, however, I find that the req.isAthenticated() function returns false when it should return true even though passport is finding and verifying the user and password. Here is my code which initialises express-session and passport:

```<code>app.use(cookieParser());
app.use(session({
  secret: 'foo',
  resave: true,
  saveUninitialized: true,
  cookie: {
    secure: true,
    maxAge: 3600000
    //maxAge: new Date(Date.now() + 3600000)
  }
}));

app.use(flash());
app.use(passport.initialize());
app.use(passport.session()); // persistent login sessions
</code>```

Here is how I define the local passport:

```<code>module.exports = function(passport, configIds) {
    passport.use('login', new LocalStrategy({
      usernameField: "email",
      passwordField: "password",
      passReqToCallback: true
    },
        function(req, email, password, cb) {
            //console.log('got email pwd: ' + email + ' ' + password);
        User.getByEmail(email, function(err, user) {
            if (err) {
                console.log('something went wrong in login strategy getting user: ' + err);
                return cb(err);
            }
            if (!user) {
                console.log('problem with user in local strategy');
                return cb(null, false, { message: 'cannot locate user'});
            }
            if (!User.comparePassword(user, password)) {
            console.log('incorrect password for user');
                return cb(null, false, { message: 'incorrect email or password'});
            }
          console.log('success: return the user');
            return cb(null, user);
        });
        }
    )),
</code>```

I'm reaching the success: return the user console output and once again, the req.isAuthenticated() function returns true, as expected, when I run on the localhost. I saw some comments about using https but I'm using secure sockets on both on localhost and Heroku. Here is the middleware I've defined that checks to see if the request is authenticated...

```<code>// route middleware to make sure a user is logged in
function isLoggedIn(req, res, next) {

    // if user is authenticated in the session, carry on
    if (req.isAuthenticated()) {
        next();
    } else {
        // if they aren't redirect them to the home page
        //return res.redirect('/');
        console.log('User not authenticated. Redirect to home');
        return res.status(401).redirect('/');
    }
}
</code>```

edit:
I have also checked which cookies are being stored. I can see that when running as localhost a session cookie is being stored but running from Heroku no cookie exists.

Can anyone suggest why this would work, running on localhost but break when running on Heroku?

答:
Okay, this works now and seems to have been because the proxy configuration was not set up properly, as suggested by theprogrammer in one of the comments (thanks!). See the amended code below that fixed the problem...

```<code>app.use(cookieParser());
app.enable('trust proxy'); // add this line
app.use(session({
  secret: 'secret',
  resave: true,
  saveUninitialized: true,
  proxy: true, // add this line
  cookie: {
    secure: true,
    maxAge: 3600000,
    store: new MongoStore({ url: config.DB_URL })
  }
}));
</code>```

I also added a MongoStore to save the session as suggested by robertklep. Hope this is of help to anyone facing the same problem.

Body:
I'm using passport with Nodejs. My application works as expected when I run on my localhost. When I deploy to Heroku, however, I find that the req.isAthenticated() function returns false when it should return true even though passport is finding and verifying the user and password. Here is my code which initialises express-session and passport:

app.use(cookieParser());
app.use(session({
  secret: 'foo',
  resave: true,
  saveUninitialized: true,
  cookie: {
    secure: true,
    maxAge: 3600000
    //maxAge: new Date(Date.now() + 3600000)
  }
}));

app.use(flash());
app.use(passport.initialize());
app.use(passport.session()); // persistent login sessions

Here is how I define the local passport:

module.exports = function(passport, configIds) {
    passport.use('login', new LocalStrategy({
      usernameField: "email",
      passwordField: "password",
      passReqToCallback: true
    },
        function(req, email, password, cb) {
            //console.log('got email pwd: ' + email + ' ' + password);
        User.getByEmail(email, function(err, user) {
            if (err) {
                console.log('something went wrong in login strategy getting user: ' + err);
                return cb(err);
            }
            if (!user) {
                console.log('problem with user in local strategy');
                return cb(null, false, { message: 'cannot locate user'});
            }
            if (!User.comparePassword(user, password)) {
            console.log('incorrect password for user');
                return cb(null, false, { message: 'incorrect email or password'});
            }
          console.log('success: return the user');
            return cb(null, user);
        });
        }
    )),

I'm reaching the success: return the user console output and once again, the req.isAuthenticated() function returns true, as expected, when I run on the localhost. I saw some comments about using https but I'm using secure sockets on both on localhost and Heroku. Here is the middleware I've defined that checks to see if the request is authenticated...

// route middleware to make sure a user is logged in
function isLoggedIn(req, res, next) {

    // if user is authenticated in the session, carry on
    if (req.isAuthenticated()) {
        next();
    } else {
        // if they aren't redirect them to the home page
        //return res.redirect('/');
        console.log('User not authenticated. Redirect to home');
        return res.status(401).redirect('/');
    }
}

edit:
I have also checked which cookies are being stored. I can see that when running as localhost a session cookie is being stored but running from Heroku no cookie exists.

Can anyone suggest why this would work, running on localhost but break when running on Heroku?

Body:
Okay, this works now and seems to have been because the proxy configuration was not set up properly, as suggested by theprogrammer in one of the comments (thanks!). See the amended code below that fixed the problem...

app.use(cookieParser());
app.enable('trust proxy'); // add this line
app.use(session({
  secret: 'secret',
  resave: true,
  saveUninitialized: true,
  proxy: true, // add this line
  cookie: {
    secure: true,
    maxAge: 3600000,
    store: new MongoStore({ url: config.DB_URL })
  }
}));

I also added a MongoStore to save the session as suggested by robertklep. Hope this is of help to anyone facing the same problem.


问:
Is STUN server absolutely necessary for webrtc when I have a socket.io based signaling server?
My understanding about STUN server for webrtc is that when the clients are behind the NAT (in most cases, if not all), the STUN server will help the webrtc clients to identify their addresses and ports. And I also read some article saying that a signaling server is needed for webrtc clients. The signaling server could be a web server, socket.io, or even emailing a url. My first question would be: is the STUN server the signaling server?

Actually now I built a very simple socket.io based service which broadcasts client's session descriptions to all other clients. So I believe the socket.io based server should have enough knowledge about the clients' addresses and ports information. If this is the case, why do we bother to have another STUN server?

答:
NAT(Network Address Transformation) is used to translate "Private IP', which is valid only in LAN into "Public IP" which is valid in WAN.
The problem is that "Public IP" is only visible from outside, so we need STUN or TURN server to send back "Public IP" to you.
This process enables a WebRTC peer to get a publicly accessible address for itself, and then pass that on to another peer via a signaling mechanism

A STUN server is used to get an external network address.
TURN servers are used to relay traffic if direct (peer to peer) connection fails.
for more you can also refer from below link: https://www.html5rocks.com/en/tutorials/webrtc/infrastructure/#what-is-signaling


问:
Adding JSON values into a list
I'm wanting to iterate through my JSON file, and add two values into a list.

In theory, I'm wanting to have a nested list as: ips = [["custom3","modemId"],["custom3","modemId"]] and so on. My JSON file has 171 of each custom3 and modemId values. So in theory my nested list will contain 171 lists.

I'm having trouble adding the values into a list, in which I would like to append each list together, to create 171 lists.

```<code>json1 = open('C:\\Users\\' + comp_name + '\\Documents\\Programming Projects\\Python\\Python Firmware Script\\curl\\src\\out.json')
json1_obj = json.load(json1)

for i in json1_obj['data']:
    ip = [i['custom3']['modemId']]
</code>```

A snippet of my JSON data:

```<code>{
    "data": [
        {
            "custom3": "192.168.243.132",
            "modemId": "000408"
        },
        {
            "custom3": "192.168.244.156",
            "modemId": "000310"
        }
    ]
}
</code>```

I have 171 objects as above, but I'm only showing two. From the above, I would like to create two lists and append them each into a nested list.

How do I iterate through each JSON object and create a nested list with my JSON data in Python?

答:
If you just want this

```<code>ips = [["custom3","modemId"],["custom3","modemId"]]
</code>```

Then all you need is a simple list comprehension

```<code>ips = [d.keys() for d in json1_obj['data']]
</code>```

If you want to actually get the values (in order), not the keys

```<code>ips = [ [ d['custom3'], d['modemId'] ]  for d in json1_obj['data']]
</code>```

Title: Adding JSON values into a list

Body:
I'm wanting to iterate through my JSON file, and add two values into a list.

In theory, I'm wanting to have a nested list as: ips = [["custom3","modemId"],["custom3","modemId"]] and so on. My JSON file has 171 of each custom3 and modemId values. So in theory my nested list will contain 171 lists.

I'm having trouble adding the values into a list, in which I would like to append each list together, to create 171 lists.

json1 = open('C:\\Users\\' + comp_name + '\\Documents\\Programming Projects\\Python\\Python Firmware Script\\curl\\src\\out.json')
json1_obj = json.load(json1)

for i in json1_obj['data']:
    ip = [i['custom3']['modemId']]

A snippet of my JSON data:

{
    "data": [
        {
            "custom3": "192.168.243.132",
            "modemId": "000408"
        },
        {
            "custom3": "192.168.244.156",
            "modemId": "000310"
        }
    ]
}

I have 171 objects as above, but I'm only showing two. From the above, I would like to create two lists and append them each into a nested list.

How do I iterate through each JSON object and create a nested list with my JSON data in Python?

Body:
If you just want this

ips = [["custom3","modemId"],["custom3","modemId"]]

Then all you need is a simple list comprehension

ips = [d.keys() for d in json1_obj['data']]

If you want to actually get the values (in order), not the keys

ips = [ [ d['custom3'], d['modemId'] ]  for d in json1_obj['data']]


问:
Using '~' (A.K.A. tilde) in input directive does not seem to work?
This is the first time I've tried to use a "~" in my input.
It works when I convert the "~" to an absolute path.

Proof they are the same file:

```<code>(CentOS5-Compatible) [tboyarski@login2 6-bamMetrics]$ ls ~/share/references/rRNA.ensg72.hg19.interval_list
-rw-rw-r-- 1 fcchan users 24K Dec 12  2013 /home/tboyarski/share/references/rRNA.ensg72.hg19.interval_list

(CentOS5-Compatible) [tboyarski@login2 6-bamMetrics]$ ls /genesis/extscratch/clc/references/rRNA.ensg72.hg19.interval_list
-rw-rw-r-- 1 fcchan users 24K Dec 12  2013 /genesis/extscratch/clc/references/rRNA.ensg72.hg19.interval_list

(CentOS5-Compatible) [tboyarski@login2 6-bamMetrics]$ ls /home/tboyarski/share/references/rRNA.ensg72.hg19.interval_list
-rw-rw-r-- 1 fcchan users 24K Dec 12  2013 /home/tboyarski/share/references/rRNA.ensg72.hg19.interval_list
</code>```

Doesn't work:

```<code>rule intervalList:
    input:
       "~/share/references/rRNA.ensg72.hg19.interval_list"
</code>```

Works:

```<code>rule intervalList:
    input:
       "/home/tboyarski/share/references/rRNA.ensg72.hg19.interval_list"
</code>```

I've only tried using it in the input directive at this time. I might spend a moment to see if it works as an output directive (not something I need, just curious).

Thoughts?

EDIT

@alvits Was able to point out that ~ is converted by the shell to ${HOME} before it gets evaluated. It would seem that when providing ~ to snakemake, this conversion does not occurr. Easy alternative is to just always use ${HOME}, which works both on MacOSX and Linux :).

I was able to use the following successfully:

```<code>rule intervalList:
    input:
       "${HOME}/share/references/rRNA.ensg72.hg19.interval_list"
</code>```

Second EDIT

User pointed out what I thought was a solution was in fact not.
Solution is to not use either "~" or "${HOME}" in the input directive.

答:
You may try wrapping the path in os.path.expanduser (available after import os in your snakefile):

On Unix and Windows, return the argument with an initial component of ~ or ~user replaced by that user‘s home directory.

(Quoted from the documentation: https://docs.python.org/3/library/os.path.html#os.path.expanduser)

Body:
This is the first time I've tried to use a "~" in my input.
It works when I convert the "~" to an absolute path.

Proof they are the same file:

(CentOS5-Compatible) [tboyarski@login2 6-bamMetrics]$ ls ~/share/references/rRNA.ensg72.hg19.interval_list
-rw-rw-r-- 1 fcchan users 24K Dec 12  2013 /home/tboyarski/share/references/rRNA.ensg72.hg19.interval_list

(CentOS5-Compatible) [tboyarski@login2 6-bamMetrics]$ ls /genesis/extscratch/clc/references/rRNA.ensg72.hg19.interval_list
-rw-rw-r-- 1 fcchan users 24K Dec 12  2013 /genesis/extscratch/clc/references/rRNA.ensg72.hg19.interval_list

(CentOS5-Compatible) [tboyarski@login2 6-bamMetrics]$ ls /home/tboyarski/share/references/rRNA.ensg72.hg19.interval_list
-rw-rw-r-- 1 fcchan users 24K Dec 12  2013 /home/tboyarski/share/references/rRNA.ensg72.hg19.interval_list

Doesn't work:

rule intervalList:
    input:
       "~/share/references/rRNA.ensg72.hg19.interval_list"

Works:

rule intervalList:
    input:
       "/home/tboyarski/share/references/rRNA.ensg72.hg19.interval_list"

I've only tried using it in the input directive at this time. I might spend a moment to see if it works as an output directive (not something I need, just curious).

Thoughts?

EDIT

@alvits Was able to point out that ~ is converted by the shell to ${HOME} before it gets evaluated. It would seem that when providing ~ to snakemake, this conversion does not occurr. Easy alternative is to just always use ${HOME}, which works both on MacOSX and Linux :).

I was able to use the following successfully:

rule intervalList:
    input:
       "${HOME}/share/references/rRNA.ensg72.hg19.interval_list"

Second EDIT

User pointed out what I thought was a solution was in fact not.
Solution is to not use either "~" or "${HOME}" in the input directive.


问:
React Invariant Violation: Objects are not valid as a React child

Uncaught (in promise) Error: Objects are not valid as a React child.

labelList is an array of objects. I have added some sample data below. I am trying to map over these objects so that I can generate separate row of each object data. I tried doing multiple things such as Object.keys(labelItem).map ... but that the error is still not resolved.

```<code><tbody>
  {
    this.state.labelList.map((labelItem,index)=>{
      return (
        <tr key={ index }>
          <td>{labelItem.label}</td>
        </tr>
        )
    })
  }
</tbody>
</code>```

Data:

```<code>labelList: [
  {
    "label": "Title",
    "translation": "Titre"
  },
  {
    "label": "First Name",
    "translation": "Prenom"
  },
  {
    "label": "Last Name",
    "translation": "Nom"
  },
  {
    "label": "Marital Status",
    "translation": "Etat civil"
  },
  {
    "label": "SSN",
    "translation": ""
  },
  {
    "label": "Birth Date",
    "translation": "Date De Naissance"
  }
]
</code>```

答:
Your code works, as seen from the JS fiddle below. Inspect the value of this.state.labelList first, it might not be what you think.

var labelList = [
  {
    "label": "Title",
    "translation": "Titre"
  },
  {
    "label": "First Name",
    "translation": "Prenom"
  },
  {
    "label": "Last Name",
    "translation": "Nom"
  },
  {
    "label": "Marital Status",
    "translation": "Etat civil"
  },
  {
    "label": "SSN",
    "translation": ""
  },
  {
    "label": "Birth Date",
    "translation": "Date De Naissance"
  }
]

var Hello = React.createClass({
  render: function() {
    return

        {
          labelList.map((labelItem,index)=>{
            return (

                {labelItem.label}

              )
          })
        }

  }
});

ReactDOM.render(
  <Hello name="World" />,
  document.getElementById('container')
);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>

<div id="container">
    <!-- This element's contents will be replaced with your component. -->
</div></code>```

Body:
Uncaught (in promise) Error: Objects are not valid as a React child.

labelList is an array of objects. I have added some sample data below. I am trying to map over these objects so that I can generate separate row of each object data. I tried doing multiple things such as Object.keys(labelItem).map ... but that the error is still not resolved.

  {
    this.state.labelList.map((labelItem,index)=>{
      return (

          {labelItem.label}

        )
    })
  }

Data:

labelList: [
  {
    "label": "Title",
    "translation": "Titre"
  },
  {
    "label": "First Name",
    "translation": "Prenom"
  },
  {
    "label": "Last Name",
    "translation": "Nom"
  },
  {
    "label": "Marital Status",
    "translation": "Etat civil"
  },
  {
    "label": "SSN",
    "translation": ""
  },
  {
    "label": "Birth Date",
    "translation": "Date De Naissance"
  }
]

Body:
Your code works, as seen from the JS fiddle below. Inspect the value of this.state.labelList first, it might not be what you think.

var labelList = [
  {
    "label": "Title",
    "translation": "Titre"
  },
  {
    "label": "First Name",
    "translation": "Prenom"
  },
  {
    "label": "Last Name",
    "translation": "Nom"
  },
  {
    "label": "Marital Status",
    "translation": "Etat civil"
  },
  {
    "label": "SSN",
    "translation": ""
  },
  {
    "label": "Birth Date",
    "translation": "Date De Naissance"
  }
]

var Hello = React.createClass({
  render: function() {
    return <tbody>
        {
          labelList.map((labelItem,index)=>{
            return (
              <tr key={ index }>
                <td>{labelItem.label}</td>
              </tr>
              )
          })
        }
      </tbody>
  }
});

ReactDOM.render(
  <Hello name="World" />,
  document.getElementById('container')
);

<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>

<div id="container">
    <!-- This element's contents will be replaced with your component. -->
</div>


问:
Converting to Roman Numerals in Javascript - Weird bug
```<code>function convertToRoman(num) {

  var thisMap = {

  1:[1],
  2:[1, 1],
  3:[1, 1, 1],
  4:[1, 5],
  5:[5],
  6:[5, 1],
  7:[5, 1, 1],
  8:[5, 1, 1, 1],
  9:[1, 10],
  0:[0]

  };

  var numMap = {

  1000:"M",
  500:"D",
  100:"C",
  50:"L",
  10:"X",
  5:"V",
  1:"I"

  };

  numArr = num.toString().split("");

  var thisIndex = 1;

  var tallyArr = [];

  for (var i = numArr.length - 1; i >= 0; i--) {

   tallyArr.unshift(thisMap[numArr[i]]);

  }

  thisIndex = Math.pow(10, tallyArr.length - 1);

  checkArr = [];

  <<<BUG HERE>>>

  for (var x = 0; x < tallyArr.length; x++) {

    for (var y = 0; y < tallyArr[x].length; y++) {

      tallyArr[x][y] *= thisIndex;

    }

    thisIndex = thisIndex / 10;

  }

  <<</BUG HERE>>>

  var finalArr = [];

  for (var a = 0; a < tallyArr.length; a++) {

    for (var b = 0; b < tallyArr[a].length; b++) {

      finalArr.push(numMap[tallyArr[a][b]]);

    }

  }

  finalAnswer = finalArr.join("");

  return finalAnswer;

}

convertToRoman(88);
</code>```

So this is my function for converting a number into a Roman Numeral in Javascript. It basically formats every number into the right format using thisMap, then uses thisIndex to multiply by either 1000, 100 or 10, and then compares to numMap to get the correct Roman Numeral.

It seems to work in most of the test cases, except with 44, 99, or 3999.

In these cases, it seems to multiply the numbers by the wrong amount, so 44 becomes XLXL, when it should be XLIV.

I think the bug is between the <<>> tags I've inserted, because that is where the numbers seem to be multiplied wrong.

However, I can't spot the problem.

Thanks.

答:
```<code>var romanNumber = [
            [1, 'I'], [2, 'II'], [3, 'III'],[4, 'IV'],
            [5, 'V'], [6, 'VI'],[7, 'VII'], [8, 'VIII'],
            [9, 'IX'],[10, 'X']
];

function convertToRoman(number) {
    if (number === 0) {
      return '';
    }
    for (var i = 0; i < romanNumber.length; i++) {
      if (number === romanNumber[i][0]) {
        return romanNumber[i][1];
      }
    }
}
console.log(convertToRoman(1));
console.log(convertToRoman(2));
console.log(convertToRoman(3));
console.log(convertToRoman(4));
console.log(convertToRoman(5));
console.log(convertToRoman(6));
console.log(convertToRoman(7));
console.log(convertToRoman(8));
console.log(convertToRoman(9));
console.log(convertToRoman(10));
</code>```

Body:
function convertToRoman(num) {

  var thisMap = {

  1:[1],
  2:[1, 1],
  3:[1, 1, 1],
  4:[1, 5],
  5:[5],
  6:[5, 1],
  7:[5, 1, 1],
  8:[5, 1, 1, 1],
  9:[1, 10],
  0:[0]

  };

  var numMap = {

  1000:"M",
  500:"D",
  100:"C",
  50:"L",
  10:"X",
  5:"V",
  1:"I"

  };

  numArr = num.toString().split("");

  var thisIndex = 1;

  var tallyArr = [];

  for (var i = numArr.length - 1; i >= 0; i--) {

   tallyArr.unshift(thisMap[numArr[i]]);

  }

  thisIndex = Math.pow(10, tallyArr.length - 1);

  checkArr = [];

  <<<BUG HERE>>>

  for (var x = 0; x < tallyArr.length; x++) {

    for (var y = 0; y < tallyArr[x].length; y++) {

      tallyArr[x][y] *= thisIndex;

    }

    thisIndex = thisIndex / 10;

  }

  <<</BUG HERE>>>

  var finalArr = [];

  for (var a = 0; a < tallyArr.length; a++) {

    for (var b = 0; b < tallyArr[a].length; b++) {

      finalArr.push(numMap[tallyArr[a][b]]);

    }

  }

  finalAnswer = finalArr.join("");

  return finalAnswer;

}

convertToRoman(88);

So this is my function for converting a number into a Roman Numeral in Javascript. It basically formats every number into the right format using thisMap, then uses thisIndex to multiply by either 1000, 100 or 10, and then compares to numMap to get the correct Roman Numeral.

It seems to work in most of the test cases, except with 44, 99, or 3999.

In these cases, it seems to multiply the numbers by the wrong amount, so 44 becomes XLXL, when it should be XLIV.

I think the bug is between the <<>> tags I've inserted, because that is where the numbers seem to be multiplied wrong.

However, I can't spot the problem.

Thanks.


问:
Delete unused records from oracle table
DB version : 11.2.0.4
OS Solaris 5.10

REQUIREMENT : Delete unused records from table only after finding if the record is being accessed or not.

We have a table employee, which has 100,000 records, if anyone select a particular record/records from employee table then, the respective record's STATUS column should get updated to 'ACTIVE' value.

This is required for auditing purpose, 60 days later we will delete all the records from employee table whose STATUS column value is is NULL. how can this be achieved?

My understanding so far, correct me if I am wrong:

1) Trigger can't be used as there is no SELECT event, we only have UPDATE, INSERT, DELETE event.
2) Oracle FGA (Fine grain auditing) may not solve the purpose. or may be I am not aware, is it doable with FGA?

Table:

```<code>CREATE TABLE EMPLOYEE
(
  EMPID   NUMBER,
  NAME    VARCHAR2(20 BYTE),
  SALARY  NUMBER,
  DEPART  VARCHAR2(100 BYTE),
  STATUS  VARCHAR2(100 BYTE)
)
</code>```

sample records:

```<code>     EMPID NAME                SALARY DEPART               STATUS
---------- --------------- ---------- -------------------- ----------
       101 ALFA                  1000 IT
       102 BETA                  2000 CLERK
       103 PETER                 3000 FINANCE
       104 JOHN                  4000 IT
       105 MESSI                 5000 TECH
       106 ROMEO                 5000 TECH
       107 TERI                  5000 TECH
       108 ROBERT                5000 TECH
</code>```

Example:

If any one issue below statements

query 1: SELECT * from EMPLOYEE where name='MESSI';

the auditing should update the STATUS='ACTIVE' of empid=105

```<code>     EMPID NAME                SALARY DEPART               STATUS
---------- --------------- ---------- -------------------- ----------
       101 ALFA                  1000 IT
       102 BETA                  2000 CLERK
       103 PETER                 3000 FINANCE
       104 JOHN                  4000 IT
       105 MESSI                 5000 TECH                 'ACTIVE'
       106 ROMEO                 5000 TECH
       107 TERI                  5000 TECH
       108 ROBERT                5000 TECH
</code>```

query 2: SELECT * from EMPLOYEE where DEPART='TECH';

The auditing should update the STATUS='ACTIVE' for empid=105,106,107,108

```<code>     EMPID NAME                SALARY DEPART               STATUS
---------- --------------- ---------- -------------------- ----------
       101 ALFA                  1000 IT
       102 BETA                  2000 CLERK
       103 PETER                 3000 FINANCE
       104 JOHN                  4000 IT
       105 MESSI                 5000 TECH                 'ACTIVE'
       106 ROMEO                 5000 TECH                 'ACTIVE'
       107 TERI                  5000 TECH                 'ACTIVE'
       108 ROBERT                5000 TECH                 'ACTIVE'
</code>```

答:
The solution suggested by Oracle to achieve what to want is Known as ILM or Information Lifecycle Management.
It allows you to archive, delete, move or do specific actions depending on some criterias (Such as last access).

But be aware, it requires an additional license.

I have a suggestion :

Enable SELECT audit on the target table

Create an AFTER INSERT TRIGGER that will get the inserted line in DBA_AUDIT_TRAIL et extract SQL_TEXT if the OBJECT_NAME was your table (+others checks)

Inside this trigger, do some string operations to get the WHERE CONDITION & use it for update.

Title: Delete unused records from oracle table

Body:
DB version : 11.2.0.4
OS Solaris 5.10

REQUIREMENT : Delete unused records from table only after finding if the record is being accessed or not.

We have a table employee, which has 100,000 records, if anyone select a particular record/records from employee table then, the respective record's STATUS column should get updated to 'ACTIVE' value.

This is required for auditing purpose, 60 days later we will delete all the records from employee table whose STATUS column value is is NULL. how can this be achieved?

My understanding so far, correct me if I am wrong:

1) Trigger can't be used as there is no SELECT event, we only have UPDATE, INSERT, DELETE event.
2) Oracle FGA (Fine grain auditing) may not solve the purpose. or may be I am not aware, is it doable with FGA?

Table:

CREATE TABLE EMPLOYEE
(
  EMPID   NUMBER,
  NAME    VARCHAR2(20 BYTE),
  SALARY  NUMBER,
  DEPART  VARCHAR2(100 BYTE),
  STATUS  VARCHAR2(100 BYTE)
)

sample records:

     EMPID NAME                SALARY DEPART               STATUS
---------- --------------- ---------- -------------------- ----------
       101 ALFA                  1000 IT
       102 BETA                  2000 CLERK
       103 PETER                 3000 FINANCE
       104 JOHN                  4000 IT
       105 MESSI                 5000 TECH
       106 ROMEO                 5000 TECH
       107 TERI                  5000 TECH
       108 ROBERT                5000 TECH

Example:

If any one issue below statements

query 1: SELECT * from EMPLOYEE where name='MESSI';

the auditing should update the STATUS='ACTIVE' of empid=105

     EMPID NAME                SALARY DEPART               STATUS
---------- --------------- ---------- -------------------- ----------
       101 ALFA                  1000 IT
       102 BETA                  2000 CLERK
       103 PETER                 3000 FINANCE
       104 JOHN                  4000 IT
       105 MESSI                 5000 TECH                 'ACTIVE'
       106 ROMEO                 5000 TECH
       107 TERI                  5000 TECH
       108 ROBERT                5000 TECH

query 2: SELECT * from EMPLOYEE where DEPART='TECH';

The auditing should update the STATUS='ACTIVE' for empid=105,106,107,108

     EMPID NAME                SALARY DEPART               STATUS
---------- --------------- ---------- -------------------- ----------
       101 ALFA                  1000 IT
       102 BETA                  2000 CLERK
       103 PETER                 3000 FINANCE
       104 JOHN                  4000 IT
       105 MESSI                 5000 TECH                 'ACTIVE'
       106 ROMEO                 5000 TECH                 'ACTIVE'
       107 TERI                  5000 TECH                 'ACTIVE'
       108 ROBERT                5000 TECH                 'ACTIVE'


问:
Android - SQlite check if value in row exists
This question is similar to this and this.

I have 4 columns in my database (id, name, surname, image). I only want to check if the name that is being entered already exists in "name" column.

here is my SQLiteOpenHelper:

```<code>public class SQLiteHelper extends SQLiteOpenHelper {

public SQLiteHelper(Context context, String name, SQLiteDatabase.CursorFactory factory, int version) {
    super(context, name, factory, version);
}

public void queryData(String sql){
    SQLiteDatabase database = getWritableDatabase();
    database.execSQL(sql);
}

@Override
public void onCreate(SQLiteDatabase sqLiteDatabase) {

}

public void insertData(String name, String surname, byte[] image){
    SQLiteDatabase database = getWritableDatabase();
    String sql = "INSERT INTO STUDENTS VALUES (NULL, ?, ?, ?)";

    SQLiteStatement statement = database.compileStatement(sql);
    statement.clearBindings();

    statement.bindString(1, name);
    statement.bindString(2, surname);
    statement.bindBlob(3, image);

    statement.executeInsert();

}

@Override
public void onUpgrade(SQLiteDatabase sqLiteDatabase, int i, int i1) {

}

/*public void removeSingleContact(String name, String price, byte[] image) {

    SQLiteDatabase dbb = getWritableDatabase();
    dbb.delete(name, surname, image);

}*/

public Cursor getData(String sql){
    SQLiteDatabase database = getReadableDatabase();
    return database.rawQuery(sql, null);
}

}
</code>```

and this is how I add to SQlite;

```<code>public class AddEditStudent extends AppCompatActivity {

    public static SQLiteHelper sqLiteHelper;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_addedit_student);

        sqLiteHelper = new SQLiteHelper(this, "StudentsDB.sqlite", null, 1);

        sqLiteHelper.queryData("CREATE TABLE IF NOT EXISTS STUDENTS(Id INTEGER PRIMARY KEY AUTOINCREMENT, name VARCHAR, surname VARCHAR, image BLOB)");

            btnAdd.setOnClickListener(new View.OnClickListener() {

                    @Override
                    public void onClick(View view) {

                        if (edtName.getText().toString().trim().length() == 0) {
                            Toast.makeText(getApplicationContext(), "Please provide your students name", Toast.LENGTH_SHORT).show();

                        } else
                            try {

                                    //THIS IS WHERE I WANT TO CHECK---------

                                    sqLiteHelper.insertData(
                                            edtName.getText().toString().trim(),
                                            edtPrice.getText().toString().trim(),
                                            imageViewToByte(imageView)

                                    );

                                        Toast.makeText(getApplicationContext(), "Added successfully!", Toast.LENGTH_SHORT).show();

                                        finish();
                                    }

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

                    }
                });
</code>```

EDIT----
Thank you for the help so far. I have 2 buttons, one for update and one for insert, the problem I am facing is how will I know what row to update without using an ID. I have a gridview that is being populated by cardviews, in the cardview there is a button to edit info, please see image.

https://i.stack.imgur.com/aFJTl.png

If I click on the exit sign I do;

```<code>holder.dit.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                // Do something
                Intent editintent = new Intent(context, AddEditStudent.class);
                editintent.putExtra("studentname", finalHolder.txtName.getText().toString());
                editintent.putExtra("studentsurname", finalHolder.txtPrice.getText().toString());

                context.startActivity(editintent);
            }
        });
</code>```

then in AddEditStudent Class is where the insert and update is.

答:
As you Requested me to Help for Update of that record which Exist the
  process will be follow

First of all add this Method for update in class SQLiteHelper

```<code>public void updateData(ContentValues contentValues, String whereClause, String[] whereArgs){
    SQLiteDatabase database = getReadableDatabase();
    database.update(DATABASE_TABLE, contentValues, whereClause, whereArgs);
}
</code>```

Now Apply Changes in your If else Statement

```<code>String name = edtName.getText().toString().trim();
    String query = "Select * From STUDENTS where name = '"+name+"'";
    if(sqLiteHelper.getData(query).getCount()>0){
        Toast.makeText(getApplicationContext(), "Already Exist!", Toast.LENGTH_SHORT).show();
        ContentValues contentValues = new ContentValues();
        contentValues.put("name", name);
        contentValues.put("surname", edtPrice.getText().toString().trim());
        contentValues.put("image", imageViewToByte(imageView));

        String whereClause = "name=?";
        String[] whereArgs = new String[] {"'"+name+"'"};

        sqLiteHelper.updateData(contentValues, whereClause, whereArgs);
    }else{
        sqLiteHelper.insertData(
                name,
                edtPrice.getText().toString().trim(),
                imageViewToByte(imageView)

        );
    }
</code>```

Body:
This question is similar to this and this.

I have 4 columns in my database (id, name, surname, image). I only want to check if the name that is being entered already exists in "name" column.

here is my SQLiteOpenHelper:

public class SQLiteHelper extends SQLiteOpenHelper {

public SQLiteHelper(Context context, String name, SQLiteDatabase.CursorFactory factory, int version) {
    super(context, name, factory, version);
}

public void queryData(String sql){
    SQLiteDatabase database = getWritableDatabase();
    database.execSQL(sql);
}

@Override
public void onCreate(SQLiteDatabase sqLiteDatabase) {

}

public void insertData(String name, String surname, byte[] image){
    SQLiteDatabase database = getWritableDatabase();
    String sql = "INSERT INTO STUDENTS VALUES (NULL, ?, ?, ?)";

    SQLiteStatement statement = database.compileStatement(sql);
    statement.clearBindings();

    statement.bindString(1, name);
    statement.bindString(2, surname);
    statement.bindBlob(3, image);

    statement.executeInsert();

}

@Override
public void onUpgrade(SQLiteDatabase sqLiteDatabase, int i, int i1) {

}

/*public void removeSingleContact(String name, String price, byte[] image) {

    SQLiteDatabase dbb = getWritableDatabase();
    dbb.delete(name, surname, image);

}*/

public Cursor getData(String sql){
    SQLiteDatabase database = getReadableDatabase();
    return database.rawQuery(sql, null);
}

}

and this is how I add to SQlite;

public class AddEditStudent extends AppCompatActivity {

    public static SQLiteHelper sqLiteHelper;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_addedit_student);

        sqLiteHelper = new SQLiteHelper(this, "StudentsDB.sqlite", null, 1);

        sqLiteHelper.queryData("CREATE TABLE IF NOT EXISTS STUDENTS(Id INTEGER PRIMARY KEY AUTOINCREMENT, name VARCHAR, surname VARCHAR, image BLOB)");

            btnAdd.setOnClickListener(new View.OnClickListener() {

                    @Override
                    public void onClick(View view) {

                        if (edtName.getText().toString().trim().length() == 0) {
                            Toast.makeText(getApplicationContext(), "Please provide your students name", Toast.LENGTH_SHORT).show();

                        } else
                            try {

                                    //THIS IS WHERE I WANT TO CHECK---------

                                    sqLiteHelper.insertData(
                                            edtName.getText().toString().trim(),
                                            edtPrice.getText().toString().trim(),
                                            imageViewToByte(imageView)

                                    );

                                        Toast.makeText(getApplicationContext(), "Added successfully!", Toast.LENGTH_SHORT).show();

                                        finish();
                                    }

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

                    }
                });

EDIT----
Thank you for the help so far. I have 2 buttons, one for update and one for insert, the problem I am facing is how will I know what row to update without using an ID. I have a gridview that is being populated by cardviews, in the cardview there is a button to edit info, please see image.

https://i.stack.imgur.com/aFJTl.png

If I click on the exit sign I do;

holder.dit.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                // Do something
                Intent editintent = new Intent(context, AddEditStudent.class);
                editintent.putExtra("studentname", finalHolder.txtName.getText().toString());
                editintent.putExtra("studentsurname", finalHolder.txtPrice.getText().toString());

                context.startActivity(editintent);
            }
        });

then in AddEditStudent Class is where the insert and update is.

Body:
As you Requested me to Help for Update of that record which Exist the
  process will be follow

First of all add this Method for update in class SQLiteHelper

public void updateData(ContentValues contentValues, String whereClause, String[] whereArgs){
    SQLiteDatabase database = getReadableDatabase();
    database.update(DATABASE_TABLE, contentValues, whereClause, whereArgs);
}

Now Apply Changes in your If else Statement

String name = edtName.getText().toString().trim();
    String query = "Select * From STUDENTS where name = '"+name+"'";
    if(sqLiteHelper.getData(query).getCount()>0){
        Toast.makeText(getApplicationContext(), "Already Exist!", Toast.LENGTH_SHORT).show();
        ContentValues contentValues = new ContentValues();
        contentValues.put("name", name);
        contentValues.put("surname", edtPrice.getText().toString().trim());
        contentValues.put("image", imageViewToByte(imageView));

        String whereClause = "name=?";
        String[] whereArgs = new String[] {"'"+name+"'"};

        sqLiteHelper.updateData(contentValues, whereClause, whereArgs);
    }else{
        sqLiteHelper.insertData(
                name,
                edtPrice.getText().toString().trim(),
                imageViewToByte(imageView)

        );
    }


问:
router-view content not rendering
The router-view content of my app always remains empty () even though routing itself works perfectly and templates are correctly rendered throughout the app.

(Note: Even though there's just a import Vue from 'vue';, I'm using the standalone version of Vue.js with compilation support. The correct import is replaced by webpack.)

main.ts

```<code>import Vue from 'vue';
import Router from './services/router';
import { AppComponent } from './components/';

export default new Vue({
  el: '#app-container',
  router: Router,
  render: (context) => context(AppComponent)
});
</code>```

main.template.pug (excerpt)

```<code>body
  #app-container
</code>```

app.ts (excerpt)

```<code>@Component({
  template: require('./app.template.pug'),
  components: {
    'app-header': HeaderComponent,
    ...
  }
})
export class AppComponent extends Vue {

}
</code>```

app.template.pug

```<code>.app
  app-header
  .app-body
    app-sidebar
    main.app-content
      app-breadcrumb(:list='list')
      .container-fluid
        router-view
    app-aside
  app-footer
</code>```

services/router/index.ts (excerpt)

```<code>import Router from 'vue-router';
import { DashboardComponent } from '../../components/pages/dashboard';

Vue.use(Router);

export default new Router({
  mode: 'history',
  linkActiveClass: 'open active',
  routes: [
    {
      path: '/',
      redirect: '/dashboard',
      name: 'Home',
      children: [
        {
          path: 'dashboard',
          name: 'Dashboard',
          component: DashboardComponent
        }
      ]
    }
  ]
});
</code>```

答:
Yep.. the Home route doesn't have a component...
You could simply do:</p>

```<code>routes: [
    {
      path: '/',
      redirect: '/dashboard',
      name: 'Home',
      component: {
          template: '<router-view/>',
      },
      children: [
        {
          path: 'dashboard',
          name: 'Dashboard',
          component: DashboardComponent
        }
      ]
    }
  ]
</code>```

Title: router-view content not rendering

Body:
The router-view content of my app always remains empty () even though routing itself works perfectly and templates are correctly rendered throughout the app.

(Note: Even though there's just a import Vue from 'vue';, I'm using the standalone version of Vue.js with compilation support. The correct import is replaced by webpack.)

main.ts

import Vue from 'vue';
import Router from './services/router';
import { AppComponent } from './components/';

export default new Vue({
  el: '#app-container',
  router: Router,
  render: (context) => context(AppComponent)
});

main.template.pug (excerpt)

body
  #app-container

app.ts (excerpt)

@Component({
  template: require('./app.template.pug'),
  components: {
    'app-header': HeaderComponent,
    ...
  }
})
export class AppComponent extends Vue {

}

app.template.pug

.app
  app-header
  .app-body
    app-sidebar
    main.app-content
      app-breadcrumb(:list='list')
      .container-fluid
        router-view
    app-aside
  app-footer

services/router/index.ts (excerpt)

import Router from 'vue-router';
import { DashboardComponent } from '../../components/pages/dashboard';

Vue.use(Router);

export default new Router({
  mode: 'history',
  linkActiveClass: 'open active',
  routes: [
    {
      path: '/',
      redirect: '/dashboard',
      name: 'Home',
      children: [
        {
          path: 'dashboard',
          name: 'Dashboard',
          component: DashboardComponent
        }
      ]
    }
  ]
});

Body:
Yep.. the Home route doesn't have a component...
You could simply do:

routes: [
    {
      path: '/',
      redirect: '/dashboard',
      name: 'Home',
      component: {
          template: '<router-view/>',
      },
      children: [
        {
          path: 'dashboard',
          name: 'Dashboard',
          component: DashboardComponent
        }
      ]
    }
  ]


问:
How do I change image on hover of  that the img is in - in jQuery?
You can see the implementation here http://jsfiddle.net/xNSFA/

Right now, when you hover over the cell, it changes some of the characteristics. But the image doesn't change. The image only changes when you hover over the image specifically.

How do I get the image to change with everything else?

By the way, it doesn't HAVE to be done in jQuery. If there is a nice elegant way to do this in CSS, I would love that. But I just assumed it was impossible to do - because of the image manipulation and I didn't want to set the background of the  to be that image. I want the image inside the cell.

Thanks.

答:
You have two issues in your script.  First, you need to attach the hover to the , not the  itself.  If you run your test, you'll see that the image does change when leaving the actual image.  Second, you seem to have your replaces reversed, so that the image first changes when you leave the hover area.

Here's a version of your script with both changes..  I think this is doing what you wanted?

ContentLicense: CC BY-SA 2.5

Title: How do I change image on hover of <td> that the img is in - in jQuery?

Body:
You have two issues in your script.  First, you need to attach the hover to the <td>, not the <img> itself.  If you run your test, you'll see that the image does change when leaving the actual image.  Second, you seem to have your replaces reversed, so that the image first changes when you leave the hover area.

Here's a version of your script with both changes..  I think this is doing what you wanted?


问:
Tic Tac Toe how to tell user there is no winner?
I'm working in this project for 3 days and i can not figure out where I'm doing wrong if you can help me with i really appreciate your help.I'm trying to create a tic tac toe game .When I'm running the game if the player X or O  wins a message will pop up saying that X or O win .But if the a non of users win a message should pop up and saying there is no winner . the pop up for the winner is working perfectly but the pop up for no one win does not work.if you can help me to fix it you are really making my day.</p>

```<code>public class MainActivity extends AppCompatActivity {
MediaPlayer mediaPlayer;

int activePlayer = 0; // for x player

int[] gameState ={2,2,2,2,2,2,2,2,2}; // 2 means unplayed.

int[][] winningLocation ={{0,1,2},{3,4,5},{6,7,8},{0,3,6},{1,4,7},{2,5,8},{0,4,8},{2,4,6}};
boolean gameover =false;

public void gameLogic(View view){

    ImageView tappedView =(ImageView) view;

    int tappedLocation = Integer.parseInt(view.getTag().toString());

    if(gameState[tappedLocation]==2 && !gameover) {
        gameState[tappedLocation]=activePlayer;

        tappedView.setTranslationY(-3000f);

        if (activePlayer == 0) {

            tappedView.setImageResource(R.drawable.x);

            activePlayer = 1;

        } else if (activePlayer == 1) {
            tappedView.setImageResource(R.drawable.o);
            activePlayer = 0;
        }
        tappedView.animate().translationYBy(3000f).setDuration(500);
    }
  String mesg ="";

    for(int[]winningPostion :winningLocation){

        if(gameState[winningPostion[0]] == gameState [winningPostion[1]]
                && gameState[winningPostion[1]]== gameState [winningPostion[2]]
                && gameState[winningPostion[0]]!=2){

            if (activePlayer ==0)

                mesg = "O is the winner!";

            if(activePlayer==1)

                mesg = "X is the winner!";

            else
                gameover=true;
            mesg="there is no winner ";

            LinearLayout winnerLayout =(LinearLayout)findViewById (R.id.winnerLayout);
            winnerLayout.setVisibility(View .VISIBLE);

            TextView winnermesg = (TextView) findViewById(R.id.editText);
            winnermesg.setText(mesg);

            gameover=true;
        }
    }

}

// a method that let the players play again

public void playagain(View view){
    LinearLayout winnerLayout = (LinearLayout) findViewById(R.id.winnerLayout);
    winnerLayout.setVisibility(View.INVISIBLE);
    gameover=false;
    activePlayer=0;

    for (int i =0; i < gameState.length;i++)
        gameState[i]=2;

    GridLayout gridlayout = (GridLayout) findViewById(R.id.gridlayout);
    for(int i =0 ; i < gridlayout.getChildCount(); i++)
        ((ImageView)gridlayout.getChildAt(i)).setImageResource(0);
}
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

 // to play the song
      mediaPlayer = MediaPlayer.create(getApplicationContext(),R.raw.song);
      mediaPlayer.start();

    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);

    // to show and hide the playing again button

   LinearLayout winnerLayout = ( LinearLayout) findViewById(R.id.winnerLayout);
    winnerLayout.setVisibility(View.INVISIBLE);

   FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
    fab.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
                    .setAction("Action", null).show();
        }
    });
}

// pause and play the song when the user leaving annd returning the game
@Override
protected void onPause(){
    super.onPause();
    mediaPlayer.stop();
    mediaPlayer.release();
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.menu_main, menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    int id = item.getItemId();

    //noinspection SimplifiableIfStatement
    if (id == R.id.action_settings) {
        return true;
    }

    return super.onOptionsItemSelected(item);
}

}
</code>```

答:
Create a function that check your array :

```<code>int[] gameState ={2,2,2,2,2,2,2,2,2};
</code>```

If all are different from 2, and none of the player won, it means its a tie.

EDIT:

Use this function, that will tell if your arr, contains item:

```<code>public static boolean my_contains(int[] arr, int item) {
    for (int n : arr) {
        if (item == n) {
            return true;
        }
    }
    return false;
}
</code>```

Then do :

```<code>//Check winning position
for(int[]winningPostion :winningLocation){
    //If there is a winning position
    if(gameState[winningPostion[0]] == gameState [winningPostion[1]]
            && gameState[winningPostion[1]]== gameState[winningPostion[2]]
            && gameState[winningPostion[0]]!=2){
        //Look for the winner
        if (activePlayer ==0)
            mesg = "O is the winner!";

        if(activePlayer==1)
            mesg = "X is the winner!";

        LinearLayout winnerLayout =(LinearLayout)findViewById (R.id.winnerLayout);
        winnerLayout.setVisibility(View .VISIBLE);

        TextView winnermesg = (TextView) findViewById(R.id.editText);
        winnermesg.setText(mesg);

        gameover=true;
    }
}
//Here, all winning position have been checked, and gameover is still false
//Check if all X and O have been placed
if(!my_contains(gameSate, 2) && !gameover){
    //If so, and gameover is false, then its a tie.
    gameover=true;
    mesg="there is no winner ";

    //README : this may be the wrong layout, its up to you to change it to the good one, but it should pop your message
    LinearLayout winnerLayout =(LinearLayout)findViewById (R.id.winnerLayout);
    winnerLayout.setVisibility(View .VISIBLE);

    TextView winnermesg = (TextView) findViewById(R.id.editText);
    winnermesg.setText(mesg);
}
</code>```

Body:
I'm working in this project for 3 days and i can not figure out where I'm doing wrong if you can help me with i really appreciate your help.I'm trying to create a tic tac toe game .When I'm running the game if the player X or O  wins a message will pop up saying that X or O win .But if the a non of users win a message should pop up and saying there is no winner . the pop up for the winner is working perfectly but the pop up for no one win does not work.if you can help me to fix it you are really making my day.

public class MainActivity extends AppCompatActivity {
MediaPlayer mediaPlayer;

int activePlayer = 0; // for x player

int[] gameState ={2,2,2,2,2,2,2,2,2}; // 2 means unplayed.

int[][] winningLocation ={{0,1,2},{3,4,5},{6,7,8},{0,3,6},{1,4,7},{2,5,8},{0,4,8},{2,4,6}};
boolean gameover =false;

public void gameLogic(View view){

    ImageView tappedView =(ImageView) view;

    int tappedLocation = Integer.parseInt(view.getTag().toString());

    if(gameState[tappedLocation]==2 && !gameover) {
        gameState[tappedLocation]=activePlayer;

        tappedView.setTranslationY(-3000f);

        if (activePlayer == 0) {

            tappedView.setImageResource(R.drawable.x);

            activePlayer = 1;

        } else if (activePlayer == 1) {
            tappedView.setImageResource(R.drawable.o);
            activePlayer = 0;
        }
        tappedView.animate().translationYBy(3000f).setDuration(500);
    }
  String mesg ="";

    for(int[]winningPostion :winningLocation){

        if(gameState[winningPostion[0]] == gameState [winningPostion[1]]
                && gameState[winningPostion[1]]== gameState [winningPostion[2]]
                && gameState[winningPostion[0]]!=2){

            if (activePlayer ==0)

                mesg = "O is the winner!";

            if(activePlayer==1)

                mesg = "X is the winner!";

            else
                gameover=true;
            mesg="there is no winner ";

            LinearLayout winnerLayout =(LinearLayout)findViewById (R.id.winnerLayout);
            winnerLayout.setVisibility(View .VISIBLE);

            TextView winnermesg = (TextView) findViewById(R.id.editText);
            winnermesg.setText(mesg);

            gameover=true;
        }
    }

}

// a method that let the players play again

public void playagain(View view){
    LinearLayout winnerLayout = (LinearLayout) findViewById(R.id.winnerLayout);
    winnerLayout.setVisibility(View.INVISIBLE);
    gameover=false;
    activePlayer=0;

    for (int i =0; i < gameState.length;i++)
        gameState[i]=2;

    GridLayout gridlayout = (GridLayout) findViewById(R.id.gridlayout);
    for(int i =0 ; i < gridlayout.getChildCount(); i++)
        ((ImageView)gridlayout.getChildAt(i)).setImageResource(0);
}
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

 // to play the song
      mediaPlayer = MediaPlayer.create(getApplicationContext(),R.raw.song);
      mediaPlayer.start();

    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);

    // to show and hide the playing again button

   LinearLayout winnerLayout = ( LinearLayout) findViewById(R.id.winnerLayout);
    winnerLayout.setVisibility(View.INVISIBLE);

   FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
    fab.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
                    .setAction("Action", null).show();
        }
    });
}

// pause and play the song when the user leaving annd returning the game
@Override
protected void onPause(){
    super.onPause();
    mediaPlayer.stop();
    mediaPlayer.release();
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.menu_main, menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    int id = item.getItemId();

    //noinspection SimplifiableIfStatement
    if (id == R.id.action_settings) {
        return true;
    }

    return super.onOptionsItemSelected(item);
}

}

Body:
Create a function that check your array :

int[] gameState ={2,2,2,2,2,2,2,2,2};

If all are different from 2, and none of the player won, it means its a tie.

EDIT:

Use this function, that will tell if your arr, contains item:

public static boolean my_contains(int[] arr, int item) {
    for (int n : arr) {
        if (item == n) {
            return true;
        }
    }
    return false;
}

Then do :

//Check winning position
for(int[]winningPostion :winningLocation){
    //If there is a winning position
    if(gameState[winningPostion[0]] == gameState [winningPostion[1]]
            && gameState[winningPostion[1]]== gameState[winningPostion[2]]
            && gameState[winningPostion[0]]!=2){
        //Look for the winner
        if (activePlayer ==0)
            mesg = "O is the winner!";

        if(activePlayer==1)
            mesg = "X is the winner!";

        LinearLayout winnerLayout =(LinearLayout)findViewById (R.id.winnerLayout);
        winnerLayout.setVisibility(View .VISIBLE);

        TextView winnermesg = (TextView) findViewById(R.id.editText);
        winnermesg.setText(mesg);

        gameover=true;
    }
}
//Here, all winning position have been checked, and gameover is still false
//Check if all X and O have been placed
if(!my_contains(gameSate, 2) && !gameover){
    //If so, and gameover is false, then its a tie.
    gameover=true;
    mesg="there is no winner ";

    //README : this may be the wrong layout, its up to you to change it to the good one, but it should pop your message
    LinearLayout winnerLayout =(LinearLayout)findViewById (R.id.winnerLayout);
    winnerLayout.setVisibility(View .VISIBLE);

    TextView winnermesg = (TextView) findViewById(R.id.editText);
    winnermesg.setText(mesg);
}


问:
ReferenceError: success is not defined - Angularjs
I am getting "ReferenceError: success is not defined" when doing a Restful call from controller to my node.js back end as follows:

authControllers.js:

```<code>authControllers.controller('authCtrl', ['$scope', '$location', '$window', 'UserService', 'AuthenticationService',
function authCtrl($scope, $location, $window, UserService, AuthenticationService) {
  $scope.me = function() {
    UserService.me(function(res) {
      $scope.myDetails = res;
    }, function() {
      console.log('Failed to fetch details');
      $rootScope.error = 'Failed to fetch details';
    })
  };
}]);
</code>```

html:

```<code><div class="row" data-ng-controller="authCtrl" data-ng-init="me()">
    <div class="col-lg-12">
        <div class="panel panel-primary">
            <div class="panel-heading">
                <strong>Your Details</strong>
            </div>
            <div class="panel-body">
                <p>{{myDetails.data.username}}</p>
                <p>{{myDetails.data.email}}</p>
            </div>
        </div>
    </div>
</div>
</code>```

authServices.js:

```<code>authServices.factory('UserService',['$http', function($http) {
  return {
    me:function() {
    return $http.get(options.api.base_url + '/me').success(success).error(error)
    }
  }
}]);
</code>```

A successful nodeJs call is being received and it's returning data as well, but couldn't get it in the front end. Please help !

答:
I was starting a detailed explanation on PHP + Angular in order to solve that issue when I found that post detailing everything way better than me.

Please have a look : https://stackoverflow.com/a/39654288/3687474

Body:
I am getting "ReferenceError: success is not defined" when doing a Restful call from controller to my node.js back end as follows:

authControllers.js:

authControllers.controller('authCtrl', ['$scope', '$location', '$window', 'UserService', 'AuthenticationService',
function authCtrl($scope, $location, $window, UserService, AuthenticationService) {
  $scope.me = function() {
    UserService.me(function(res) {
      $scope.myDetails = res;
    }, function() {
      console.log('Failed to fetch details');
      $rootScope.error = 'Failed to fetch details';
    })
  };
}]);

html:

                Your Details

{{myDetails.data.username}}

{{myDetails.data.email}}

authServices.js:

authServices.factory('UserService',['$http', function($http) {
  return {
    me:function() {
    return $http.get(options.api.base_url + '/me').success(success).error(error)
    }
  }
}]);

A successful nodeJs call is being received and it's returning data as well, but couldn't get it in the front end. Please help !


问:
Working code but pycharm marks tmF and tmR in list as "local variable referenced before assignment", why is this?
I've only recently started programming so there may be a simple answer to this question but I couldn't find it on here. My code works fine for what I want to do but as I am new to this I want to get into the practice of writing good readable code. I am using PyCharm and I noticed it marked some of the code below as not defined. I understand a little about global vs local variables and I guess it has something to do with this but I can't work out why this part of the code works at all if this is the case.     </p>

```<code>if len(primerF) < 14:
    tmF = (no_A_F + no_T_F) * 2 + (no_C_F + no_G_F) * 4
    float_tmF = float(tmF)
    print("Forward primer tm: " + str(float_tmF))

elif len(primerR) > 13:
    tmR = 64.9 + 41*(no_C_R + no_G_R - 16.4) / (no_A_R + no_T_R + no_G_R +
    no_C_R)
    print("Reverse primer tm: " + str(tmR))

if len(primerR) < 14:
    tmR = (no_A_R + no_T_R) * 2 + (no_C_R + no_G_R) * 4
    print("Reverse primer tm: " + str(tmR))

elif len(primerR) > 13:
    tmR = 64.9 + 41*(no_C_R + no_G_R - 16.4) / (no_A_R + no_T_R + no_G_R +
    no_C_R)
    print("Reverse primer tm: " + str(tmR))

gc_F = (no_G_F + no_C_F)
gc_content_F = float(gc_F) / forward_length * 100
print("Forward GC content: " + str(gc_content_F) + "%")

gc__R = (no_G_R + no_C_R)
gc_content_R = float(gc__R) / reverse_length * 100
print("Reverse GC content: " + str(gc_content_R) + "%")
</code>```

<p>This block here is marked as name not defined and if I click on the bubble it says: "This inspection warns about local variables referenced before assignment". </p>

```<code>list_tm = [**tmF**, **tmR**]
high_tm = max(list_tm)
low_tm = min(list_tm)
</code>```

答:
You're setting tmF and tmR in conditional blocks that do not cover all possibilities.  For example, if primerF is >= 14, tmF will never be set before the list_tm = [tmF, tmR] statement.  This will result in a runtime error, which pycharm is warning you about.

One way to fix this is to set default values of tmF and tmR at the top of your code, or to have full conditional coverage by setting tmF and tmR in else (not just elif) blocks.

Body:
I've only recently started programming so there may be a simple answer to this question but I couldn't find it on here. My code works fine for what I want to do but as I am new to this I want to get into the practice of writing good readable code. I am using PyCharm and I noticed it marked some of the code below as not defined. I understand a little about global vs local variables and I guess it has something to do with this but I can't work out why this part of the code works at all if this is the case.

if len(primerF) < 14:
    tmF = (no_A_F + no_T_F) * 2 + (no_C_F + no_G_F) * 4
    float_tmF = float(tmF)
    print("Forward primer tm: " + str(float_tmF))

elif len(primerR) > 13:
    tmR = 64.9 + 41*(no_C_R + no_G_R - 16.4) / (no_A_R + no_T_R + no_G_R +
    no_C_R)
    print("Reverse primer tm: " + str(tmR))

if len(primerR) < 14:
    tmR = (no_A_R + no_T_R) * 2 + (no_C_R + no_G_R) * 4
    print("Reverse primer tm: " + str(tmR))

elif len(primerR) > 13:
    tmR = 64.9 + 41*(no_C_R + no_G_R - 16.4) / (no_A_R + no_T_R + no_G_R +
    no_C_R)
    print("Reverse primer tm: " + str(tmR))

gc_F = (no_G_F + no_C_F)
gc_content_F = float(gc_F) / forward_length * 100
print("Forward GC content: " + str(gc_content_F) + "%")

gc__R = (no_G_R + no_C_R)
gc_content_R = float(gc__R) / reverse_length * 100
print("Reverse GC content: " + str(gc_content_R) + "%")

This block here is marked as name not defined and if I click on the bubble it says: "This inspection warns about local variables referenced before assignment".

list_tm = [**tmF**, **tmR**]
high_tm = max(list_tm)
low_tm = min(list_tm)


问:
oracle regular expression with number matching
I have a table which contains a column 'col1' having values like

```<code>    0.23
    0.0123
   90.013
   23.31
    0.87
  100.013
</code>```

How to get the records whole values matching with any number followed by 0.01 followed by any number in Oracle? I.e.

```<code>  0.0123
 90.013
100.013
</code>```

答:
You may need the following, assuming you only have positive numbers:

```<code>select *
from (
        select '0.23'    as col1 from dual union all
        select '0.0123'          from dual union all
        select '90.013'          from dual union all
        select '23.31'           from dual union all
        select '0.87'            from dual union all
        select '100.013'         from dual
     )
where regexp_like(col1, '^[0-9]+\.01[0-9]*$')
</code>```

How it works:

^: the beginning of the string

[0-9]+: one or more occurrences of a
digit

\.01: exactly .01

[0-9]*: zero or more occurrences of a digit

$: the end of the string

Body:
I have a table which contains a column 'col1' having values like

    0.23
    0.0123
   90.013
   23.31
    0.87
  100.013

How to get the records whole values matching with any number followed by 0.01 followed by any number in Oracle? I.e.

  0.0123
 90.013
100.013

Body:
You may need the following, assuming you only have positive numbers:

select *
from (
        select '0.23'    as col1 from dual union all
        select '0.0123'          from dual union all
        select '90.013'          from dual union all
        select '23.31'           from dual union all
        select '0.87'            from dual union all
        select '100.013'         from dual
     )
where regexp_like(col1, '^[0-9]+\.01[0-9]*$')

How it works:

^: the beginning of the string

[0-9]+: one or more occurrences of a
digit

\.01: exactly .01

[0-9]*: zero or more occurrences of a digit

$: the end of the string


问:
Can someone explain to me how setting a set amount of pixels the scroll function can scroll down/up to using jquery works?
```<code>$(window).scroll(function(){
// scroll 100vh down on first scroll

// scroll another 100vh down on second scroll
})
</code>```

I've seen a plugin that does just this but I want to be able to understand how the logic works. Can someone please explain it to me or at least point me to a site where it can be explained further?

答:
```<code>$(window).scroll(function(){ //Function called when window is scrolled.

})
</code>```

JQuery Scroll

The scroll event is sent to an element when the user scrolls to a
  different place in the element. It applies to window objects, but also
  to scrollable frames and elements with the overflow CSS property set
  to scroll (or auto when the element's explicit height or width is less
  than the height or width of its contents).

When the width/height of a div is more than the available width/height of the device browser will provide you a scroll bar to scroll down and see overflowed elements.

Jquery scroll allows you to listen to a event when a user scrolls inside the selector provided.

It will call your handler (function) that you passed as a parameter to the scroll function of jquery.

Further, you don't need to scroll an container manually. The browser will automatically scroll the contents of the overflowed container but you may want to increase the step of scroll by the scrollbar.

How do you increase the step?

Normally, when you scroll the scrollTop property of your scrollable container changes with a fixed step (1-10px).

This scrollTop property decides how much of content is overflowed from the top of the srollable container and shows more pixels from the bottom of the container its like a viewport.

So, you can add more number of pixel to scrollTop and scroll more than default.

Checkout this answer of mine

Body:
$(window).scroll(function(){
// scroll 100vh down on first scroll

// scroll another 100vh down on second scroll
})

I've seen a plugin that does just this but I want to be able to understand how the logic works. Can someone please explain it to me or at least point me to a site where it can be explained further?

Body:
$(window).scroll(function(){ //Function called when window is scrolled.

})

JQuery Scroll

The scroll event is sent to an element when the user scrolls to a
  different place in the element. It applies to window objects, but also
  to scrollable frames and elements with the overflow CSS property set
  to scroll (or auto when the element's explicit height or width is less
  than the height or width of its contents).

When the width/height of a div is more than the available width/height of the device browser will provide you a scroll bar to scroll down and see overflowed elements.

Jquery scroll allows you to listen to a event when a user scrolls inside the selector provided.

It will call your handler (function) that you passed as a parameter to the scroll function of jquery.

Further, you don't need to scroll an container manually. The browser will automatically scroll the contents of the overflowed container but you may want to increase the step of scroll by the scrollbar.

How do you increase the step?

Normally, when you scroll the scrollTop property of your scrollable container changes with a fixed step (1-10px).

This scrollTop property decides how much of content is overflowed from the top of the srollable container and shows more pixels from the bottom of the container its like a viewport.

So, you can add more number of pixel to scrollTop and scroll more than default.

Checkout this answer of mine


问:
How to get 'secret' of registered participant using composer cli
I have registered participant as user in CA, now I would like to fetch secret of registered user. is it possible if forgotten secret? </p>

答: No. Secrets are issued one time and cannot be retrieved AFAIK.</p>


问:
c# override ToString() method in variable
Using this example code:

```<code>public class Product
{
    private Boolean _active;

    public Boolean active
    {
        get
        {
            return _active;
        }
        set
        {
            _active = value;
        }
    }
}

Product p = new Product();
p.active = true;
</code>```

How can I override the ToString() method so I can use this:

```<code>MessageBox.Show(p.active.ToString());
</code>```

答:
I`m not sure you can override it like you want. Maybe you could just use ternary operator in order to have a small evaluation, like</p>

```<code>MessageBox.Show(p.active ? 'Yes' : 'No');
</code>```

Body:
Using this example code:

public class Product
{
    private Boolean _active;

    public Boolean active
    {
        get
        {
            return _active;
        }
        set
        {
            _active = value;
        }
    }
}

Product p = new Product();
p.active = true;

How can I override the ToString() method so I can use this:

MessageBox.Show(p.active.ToString());

Body:
I`m not sure you can override it like you want. Maybe you could just use ternary operator in order to have a small evaluation, like

MessageBox.Show(p.active ? 'Yes' : 'No');


问:
How to clear browsers (IE, Firefox, Opera, Chrome) history using JavaScript or Java except from browser itself?
How to clear browsers (IE, Firefox, Opera, Chrome) history using JavaScript or Java, except clearing it from browser itself?</p>

答:
But if you want to clear the actual page you can use:

$(function () {
//replace() does not keep the originating page in the session history,
document.location.replace("/Exercises#nocache"); // clear the last entry in the history and redirect to new url
});```

This is used by some banking websites

Body:
But if you want to clear the actual page you can use:

$(function () {
//replace() does not keep the originating page in the session history,
document.location.replace("/Exercises#nocache"); // clear the last entry in the history and redirect to new url
});

This is used by some banking websites

ContentLicense: CC BY-SA 4.0


问:
Jquery - adding next button to tabs
I am trying to get the next button to tab through the tabs. Any help appreciated. The html is at the Codepen snippet.

Thanks in advance.

```<code>function tabsResponsive() {
    $('.accordion-tabs').each(function(index) {
      $(this).children('li').first().children('a').addClass('is-active').next().addClass('is-open').show();
    });
    $('.accordion-tabs').on('click', 'li > a.tab-link', function(event) {
      if (!$(this).hasClass('is-active')) {
        event.preventDefault();
        var accordionTabs = $(this).closest('.accordion-tabs');
        accordionTabs.find('.is-open').removeClass('is-open').hide();

        $(this).next().toggleClass('is-open').toggle();
        accordionTabs.find('.is-active').removeClass('is-active');
        $(this).addClass('is-active');
      } else {
        event.preventDefault();
      }
    });

  }

  function tabsNext() {
    $('.nextContaner__link').click(function() {
      $('.tab-link').each(function(index) {

        if ($(this).hasClass('is-active')) {

          $(this).removeClass('is-active');
          $(this).parent().siblings('li').next('').children('a').addClass('is-active');

        } else {
          event.preventDefault();
        }

        // $(this).removeClass('is-active');
        // $(this).parent().siblings('li').next().children('a').addClass('is-active');
      });
    });
  }
</code>```

答:
You can change your function like this:

```<code>function tabsNext() {
  $('.nextContaner__link').click(function() {

    var elem = $(".tab-link.is-active").closest(".tab-header-and-content").next(".tab-header-and-content");
    if(elem.length > 0){
      elem.find("a").trigger("click");
    }else{
      $(".tab-header-and-content").eq(0).find("a").trigger("click");
    }

  });
}
</code>```

updated pen:
https://codepen.io/anon/pen/xrwygz

Although I have used trigger("click"), you can use normal approach of adding/removing classes.

Title: Jquery - adding next button to tabs

Body:
I am trying to get the next button to tab through the tabs. Any help appreciated. The html is at the Codepen snippet.

Thanks in advance.

function tabsResponsive() {
    $('.accordion-tabs').each(function(index) {
      $(this).children('li').first().children('a').addClass('is-active').next().addClass('is-open').show();
    });
    $('.accordion-tabs').on('click', 'li > a.tab-link', function(event) {
      if (!$(this).hasClass('is-active')) {
        event.preventDefault();
        var accordionTabs = $(this).closest('.accordion-tabs');
        accordionTabs.find('.is-open').removeClass('is-open').hide();

        $(this).next().toggleClass('is-open').toggle();
        accordionTabs.find('.is-active').removeClass('is-active');
        $(this).addClass('is-active');
      } else {
        event.preventDefault();
      }
    });

  }

  function tabsNext() {
    $('.nextContaner__link').click(function() {
      $('.tab-link').each(function(index) {

        if ($(this).hasClass('is-active')) {

          $(this).removeClass('is-active');
          $(this).parent().siblings('li').next('').children('a').addClass('is-active');

        } else {
          event.preventDefault();
        }

        // $(this).removeClass('is-active');
        // $(this).parent().siblings('li').next().children('a').addClass('is-active');
      });
    });
  }

Body:
You can change your function like this:

function tabsNext() {
  $('.nextContaner__link').click(function() {

    var elem = $(".tab-link.is-active").closest(".tab-header-and-content").next(".tab-header-and-content");
    if(elem.length > 0){
      elem.find("a").trigger("click");
    }else{
      $(".tab-header-and-content").eq(0).find("a").trigger("click");
    }

  });
}

updated pen:
https://codepen.io/anon/pen/xrwygz

Although I have used trigger("click"), you can use normal approach of adding/removing classes.


问:
Java convert String of byte array to byte array
I got a byte array sent from javascript by ajax looking like this:

```<code>"89,50,4e,47,0d,0a,1a,0a,00,00,00,0d,49,48,44,52,00,00,01,98,00,00,00,e4,08,06,00 ..."
</code>```

I would like to convert this string to a byte array.
Pretty similar to this question, but using Java instead: Convert String[] to byte[] array

Edit:
This seems to work - but not sure if i am doing it right

```<code>    String[] byteData ="89,50,4e,47,0d,0a,1a,0a,00,00,00,0d,49,48,44,52,00,00,01,98,00,00,00,e4,08,06,00";
    byte[] b = new byte[byteData.length];
    for (int i = 0; i < byteData.length; i++) {
        BigInteger bla = BigInteger.valueOf(Integer.parseInt(byteData[i].trim(), 16) - 128);
        b[i] = bla.toByteArray()[0];
    }
</code>```

答:
Try below code (output is result of conversion):</p>

```<code>    String input = "89,50,4e,47,0d,0a,1a,0a,00,00,00,0d,49,48,44,52,00,00,01,98,00,00,00,e4,08";

    String[] hex = input.split(",");
    char[] chars = new char[hex.length];
    for (int i = 0; i < hex.length; i++) {
        chars[i] = (char) Integer.parseInt(hex[i], 16);
    }
    String output = new String(chars);
</code>```

Body:
I got a byte array sent from javascript by ajax looking like this:

"89,50,4e,47,0d,0a,1a,0a,00,00,00,0d,49,48,44,52,00,00,01,98,00,00,00,e4,08,06,00 ..."

I would like to convert this string to a byte array.
Pretty similar to this question, but using Java instead: Convert String[] to byte[] array

Edit:
This seems to work - but not sure if i am doing it right

    String[] byteData ="89,50,4e,47,0d,0a,1a,0a,00,00,00,0d,49,48,44,52,00,00,01,98,00,00,00,e4,08,06,00";
    byte[] b = new byte[byteData.length];
    for (int i = 0; i < byteData.length; i++) {
        BigInteger bla = BigInteger.valueOf(Integer.parseInt(byteData[i].trim(), 16) - 128);
        b[i] = bla.toByteArray()[0];
    }

Body:
Try below code (output is result of conversion):

    String input = "89,50,4e,47,0d,0a,1a,0a,00,00,00,0d,49,48,44,52,00,00,01,98,00,00,00,e4,08";

    String[] hex = input.split(",");
    char[] chars = new char[hex.length];
    for (int i = 0; i < hex.length; i++) {
        chars[i] = (char) Integer.parseInt(hex[i], 16);
    }
    String output = new String(chars);