问:
Can I yield to a child process and return the response in Node.js?
In short, I've run into an issue where multiple parallel GET requests to my Node.js server cause the server to get "clogged up" and hang, thus resulting in timeouts for the clients (503, service unavailable).

After a lot of performance analysis, I've realized it's a CPU issue. The specific request (we'll call it GET /foo) queries data from multiple services over HTTP, and then does a lot of computation, and returns the results to the client, like this:

Client request GET /foo

/foo controller queries data over HTTP from multiple other services`

/foo controller then does a bunch of iterations over the data to compile some output for the client

Step 3 takes around 2 seconds to complete. However, if I send 2 requests in parallel to /foo, each client will receive their response in about 4 seconds. When I run the app in a cluster using more cores, the requests run much faster, but not quite what I want.

Seems like I have several options here:

pre-compute the response (ideally would like to avoid this for now, since it will require a whole "cache invalidation" scheme), or

/foo sends the CPU-blocking computation asynchronously to another process (using Heroku, so that would be another dyno), and then I can use a websocket or something to push the results to the client (again, very complex for my situation), or

somehow yield to a child process in the request and return the results to the client

Would love to do something like option 3. Something like this:

```<code>get('/foo', function*(request) {
  // I/O, so not blocking the event loop (I think)
  let data = yield getData(request)

  // make this happen in a different process
  let response = yield doSomeHeavyProcessing(data)

  return response
})
</code>```

I've omitted a lot of implementation details above, but if it's necessary to know, I'm using Koa and Node.js 6.

Ideally, doSomeHeavyProcessing would do the CPU-intensive computation in some separate process, and when it's done, still send the results back in a "synchronous" fashion to the request client.

Been trying to wrap my head around child processes, web workers, fibers, etc., and have been doing some basic "hello worlds" with these to get them to do basically the above, but to no avail. Can post more details if necessary.

答:
Here are some approaches that you can try:

1.
Split blocking computation in small chunks and use setImmediate to place the next chunk of work at the end of the event queue. So computation is no longer blocking and other requests can be processed.

2.
Microsoft recently released napajs. As stated in their README

As it evolves, we find it useful to complement Node.js in CPU-bound tasks, with the capability of executing JavaScript in multiple V8 isolates and communicating between them.

I haven't tried it, but it looks very promising:

```<code>var napa = require('napajs');
var zone1 = napa.zone.create('zone1', { workers: 4 });

get('/foo', function*(request) {
  let data = yield getData(request)

  let response = yield zone1.execute(doSomeHeavyProcessing, [data])

  return response
})
</code>```

3. If nothing of the above is enough and you need to spread the load across multiple machines, then you probably couldn't avoid using some sort of message queue to distribute work to different servers. In this case check out ZeroMQ. It is extremely easy to use from node, and you can implement any kind of distributed messaging pattern with it.

Body:
In short, I've run into an issue where multiple parallel GET requests to my Node.js server cause the server to get "clogged up" and hang, thus resulting in timeouts for the clients (503, service unavailable).

After a lot of performance analysis, I've realized it's a CPU issue. The specific request (we'll call it GET /foo) queries data from multiple services over HTTP, and then does a lot of computation, and returns the results to the client, like this:

Client request GET /foo

/foo controller queries data over HTTP from multiple other services`

/foo controller then does a bunch of iterations over the data to compile some output for the client

Step 3 takes around 2 seconds to complete. However, if I send 2 requests in parallel to /foo, each client will receive their response in about 4 seconds. When I run the app in a cluster using more cores, the requests run much faster, but not quite what I want.

Seems like I have several options here:

pre-compute the response (ideally would like to avoid this for now, since it will require a whole "cache invalidation" scheme), or

/foo sends the CPU-blocking computation asynchronously to another process (using Heroku, so that would be another dyno), and then I can use a websocket or something to push the results to the client (again, very complex for my situation), or

somehow yield to a child process in the request and return the results to the client

Would love to do something like option 3. Something like this:

get('/foo', function*(request) {
  // I/O, so not blocking the event loop (I think)
  let data = yield getData(request)

  // make this happen in a different process
  let response = yield doSomeHeavyProcessing(data)

  return response
})

I've omitted a lot of implementation details above, but if it's necessary to know, I'm using Koa and Node.js 6.

Ideally, doSomeHeavyProcessing would do the CPU-intensive computation in some separate process, and when it's done, still send the results back in a "synchronous" fashion to the request client.

Been trying to wrap my head around child processes, web workers, fibers, etc., and have been doing some basic "hello worlds" with these to get them to do basically the above, but to no avail. Can post more details if necessary.

Body:
Here are some approaches that you can try:

1.
Split blocking computation in small chunks and use setImmediate to place the next chunk of work at the end of the event queue. So computation is no longer blocking and other requests can be processed.

2.
Microsoft recently released napajs. As stated in their README

As it evolves, we find it useful to complement Node.js in CPU-bound tasks, with the capability of executing JavaScript in multiple V8 isolates and communicating between them.

I haven't tried it, but it looks very promising:

var napa = require('napajs');
var zone1 = napa.zone.create('zone1', { workers: 4 });

get('/foo', function*(request) {
  let data = yield getData(request)

  let response = yield zone1.execute(doSomeHeavyProcessing, [data])

  return response
})

3. If nothing of the above is enough and you need to spread the load across multiple machines, then you probably couldn't avoid using some sort of message queue to distribute work to different servers. In this case check out ZeroMQ. It is extremely easy to use from node, and you can implement any kind of distributed messaging pattern with it.


来源: stackexchange

问:
Function createInterface with readline
I want to create a communication between two clients using the matrix server, and the readline package.

I create a customer :

```<code>var myUserId = "@nina:my.domain.name";
var myAccessToken = "nina";
var sdk = require("matrix-js-sdk");
var clc = require("cli-color");
var matrixClient = sdk.createClient({
  baseUrl: "http://localhost:8448",
  idBaseUrl: "https://vector.im",
  accessToken: myAccessToken,
  userId: myUserId
});
</code>```

And I create an interface :

```<code>var readline = require("readline");
var rl = readline.createInterface({
  input: process.stdin,
  output: process.stdout,
  completer: completer
});
rl.setPrompt("$ ");`
</code>```

I get this error : ERROR TypeError: readline.createInterface is not a function

答:
From your comment - you have installed:

```<code>"@types/node": "~6.0.60"
"ts-node": "~3.0.4"
"readline": "^1.3.0"
</code>```

readline package does not contain createInterface method.
Native nodejs also contain package called readline which is covered by the one prom npm repository.

You should simply uninstall readline, so the native node package will be used.

ContentLicense: CC BY-SA 3.0

Title: Function createInterface with readline

Body:
I want to create a communication between two clients using the matrix server, and the readline package.

I create a customer :

var myUserId = "@nina:my.domain.name";
var myAccessToken = "nina";
var sdk = require("matrix-js-sdk");
var clc = require("cli-color");
var matrixClient = sdk.createClient({
  baseUrl: "http://localhost:8448",
  idBaseUrl: "https://vector.im",
  accessToken: myAccessToken,
  userId: myUserId
});

And I create an interface :

var readline = require("readline");
var rl = readline.createInterface({
  input: process.stdin,
  output: process.stdout,
  completer: completer
});
rl.setPrompt("$ ");`

I get this error : ERROR TypeError: readline.createInterface is not a function

Body:
From your comment - you have installed:

"@types/node": "~6.0.60"
"ts-node": "~3.0.4"
"readline": "^1.3.0"

readline package does not contain createInterface method.
Native nodejs also contain package called readline which is covered by the one prom npm repository.

You should simply uninstall readline, so the native node package will be used.


问:
Fill a CAShapeLayer with Gradient in swift?
I have filled the circle boundary with CAShapeLayer.Now i am giving my CAShape color as red but i want to give it as a gradient color.Please tell me how can i do this?</p>

```<code>circlePath = UIBezierPath(arcCenter: centerPoint, radius: circleRadius, startAngle: CGFloat(1.5 * M_PI), endAngle: CGFloat(-0.5 * M_PI), clockwise: false)

        //add gradient to the below
        progressCircle = CAShapeLayer ()
        progressCircle.path = circlePath?.cgPath
        progressCircle.strokeColor = UIColor.red.cgColor
        progressCircle.fillColor = UIColor.clear.cgColor
        progressCircle.lineWidth = 4.0
        progressCircle.strokeStart = 0
        progressCircle.strokeEnd = 0.7

        let gradient: CAGradientLayer = CAGradientLayer()
        let startingColorOfGradient = UIColor(colorLiteralRed: 50/255, green: 189/255, blue: 170/255, alpha: 1.0).cgColor
        let endingColorOFGradient = UIColor(colorLiteralRed: 133/255, green: 210/255, blue: 230/255, alpha: 1.0).cgColor
        gradient.startPoint = CGPoint(x: 1.0, y: 0.5)
        gradient.endPoint = CGPoint(x: 0.0, y: 0.5)
        gradient.colors = [startingColorOfGradient , endingColorOFGradient]

        circle.layer.addSublayer(progressCircle)
circle.layer.addSublayer(gradient)
</code>```

答:
I think you're missing the gradient frame, the gradient locations and you should add it to the layer's mask. The following example works for me:

```<code>let gradient = CAGradientLayer()
gradient.startPoint = CGPoint(x: 1, y: 0.5)
gradient.endPoint = CGPoint(x: 0, y: 0.5)
gradient.frame = CGRect(x: 0, y: 0, width: yourWidth, height: yourHeight)
gradient.colors = [
    UIColor(white: 1, alpha: 0.1).cgColor,
    UIColor(white: 1, alpha: 0.5).cgColor,
    UIColor(white: 1, alpha: 0.9).cgColor
]
gradient.locations = [
    0.0,
    0.5,
    1.0
]
circle.layer.mask = gradient
</code>```

Hope this helps!

Body:
I have filled the circle boundary with CAShapeLayer.Now i am giving my CAShape color as red but i want to give it as a gradient color.Please tell me how can i do this?

circlePath = UIBezierPath(arcCenter: centerPoint, radius: circleRadius, startAngle: CGFloat(1.5 * M_PI), endAngle: CGFloat(-0.5 * M_PI), clockwise: false)

        //add gradient to the below
        progressCircle = CAShapeLayer ()
        progressCircle.path = circlePath?.cgPath
        progressCircle.strokeColor = UIColor.red.cgColor
        progressCircle.fillColor = UIColor.clear.cgColor
        progressCircle.lineWidth = 4.0
        progressCircle.strokeStart = 0
        progressCircle.strokeEnd = 0.7

        let gradient: CAGradientLayer = CAGradientLayer()
        let startingColorOfGradient = UIColor(colorLiteralRed: 50/255, green: 189/255, blue: 170/255, alpha: 1.0).cgColor
        let endingColorOFGradient = UIColor(colorLiteralRed: 133/255, green: 210/255, blue: 230/255, alpha: 1.0).cgColor
        gradient.startPoint = CGPoint(x: 1.0, y: 0.5)
        gradient.endPoint = CGPoint(x: 0.0, y: 0.5)
        gradient.colors = [startingColorOfGradient , endingColorOFGradient]

        circle.layer.addSublayer(progressCircle)
circle.layer.addSublayer(gradient)

Body:
I think you're missing the gradient frame, the gradient locations and you should add it to the layer's mask. The following example works for me:

let gradient = CAGradientLayer()
gradient.startPoint = CGPoint(x: 1, y: 0.5)
gradient.endPoint = CGPoint(x: 0, y: 0.5)
gradient.frame = CGRect(x: 0, y: 0, width: yourWidth, height: yourHeight)
gradient.colors = [
    UIColor(white: 1, alpha: 0.1).cgColor,
    UIColor(white: 1, alpha: 0.5).cgColor,
    UIColor(white: 1, alpha: 0.9).cgColor
]
gradient.locations = [
    0.0,
    0.5,
    1.0
]
circle.layer.mask = gradient

Hope this helps!


问:
Compiler design, creating a language. How?
The Dragon book
is a famous book for designing a compiler. Is there another book like that or a great article about that? And what're the keywords about compilers? I wanna know how a new language is created.</p>

答:
This book gives you an overview of programming paradigms and may be useful:
http://www.amazon.com/Concepts-Techniques-Models-Computer-Programming/dp/0262220695</p>

ContentLicense: CC BY-SA 2.5


问:
how to generate an array collection without sorting in javascript?
I have an array like below,

```<code>var array=[];
array[0]={id:BBB,Name:"BBB"}
array[1]={id:AAA,Name:"AAA"}
</code>```

and I want to convert this array into an array collection like below

```<code>var collection={}
array.forEach(function(arr){
  collection[arr.id]=true;
});
Output : collection={AAA:true,BBB:true} // this is output is sorted in alphabetic order, actually what i want is like below,

Output : collection={BBB:true,AAA:true} // this is the expected result
</code>```

How to achieve this?

答:
TL;DR

That's an object, not an "array collection." While object properties have order (which is not alphabetical), it's usually not useful and best to largely ignore that fact. You're probably looking at this in devtools and expanding the display of an object; in that view, devtools will likely show you the properties alphabetically to make it easy for you to find what you're looking for.

More detail than necessary

You're adding entries to an object (not an "array collection"). The order of properties in an object is complex (they do have order as of ES2015), but basically for an object's "own" properties that order is the order in which you added them (except things that look like integer indexes are handled differently).

However, if you look at an expanded representation of an object in devtools, it may well show you the object's properties alphabetically. That's just a convenience feature for you, it doesn't mean the object's properties are in that order.

For instance:

var o = {};
o.b = 42;
o.c = 42;
o.a = 42;
console.log("object", o);
console.log("json", JSON.stringify(o));```
<pre class="snippet-code-html lang-html prettyprint-override"><code>Open the browser's devtools, then hit Run.</code>```

On Chrome, when I run that, I see this:

Note the order, b, c, a — the order I added the properties.

But if I expand that object with the little arrow:

In the expanded view, it shows them as a, b, c — alphabetic for convenience.

Also note that the JSON is in object order (this is required by the spec, so while JSON doesn't have order at all, JSON created by serializing a JavaScript object with JSON.stringify will, on a compliant JavaScript engine, list the properties in object order).

The order of object properties is not something it's usually useful to use; they're too hard to control. If you want order, use an array. But as it seems you don't want order, that's fine, just don't worry about the order the resulting object's properties appear to be in.

Body:
I have an array like below,

var array=[];
array[0]={id:BBB,Name:"BBB"}
array[1]={id:AAA,Name:"AAA"}

and I want to convert this array into an array collection like below

var collection={}
array.forEach(function(arr){
  collection[arr.id]=true;
});
Output : collection={AAA:true,BBB:true} // this is output is sorted in alphabetic order, actually what i want is like below,

Output : collection={BBB:true,AAA:true} // this is the expected result

How to achieve this?

Body:
TL;DR

That's an object, not an "array collection." While object properties have order (which is not alphabetical), it's usually not useful and best to largely ignore that fact. You're probably looking at this in devtools and expanding the display of an object; in that view, devtools will likely show you the properties alphabetically to make it easy for you to find what you're looking for.

More detail than necessary

You're adding entries to an object (not an "array collection"). The order of properties in an object is complex (they do have order as of ES2015), but basically for an object's "own" properties that order is the order in which you added them (except things that look like integer indexes are handled differently).

However, if you look at an expanded representation of an object in devtools, it may well show you the object's properties alphabetically. That's just a convenience feature for you, it doesn't mean the object's properties are in that order.

For instance:

var o = {};
o.b = 42;
o.c = 42;
o.a = 42;
console.log("object", o);
console.log("json", JSON.stringify(o));

Open the browser's devtools, then hit Run.

On Chrome, when I run that, I see this:

Note the order, b, c, a — the order I added the properties.

But if I expand that object with the little arrow:

In the expanded view, it shows them as a, b, c — alphabetic for convenience.

Also note that the JSON is in object order (this is required by the spec, so while JSON doesn't have order at all, JSON created by serializing a JavaScript object with JSON.stringify will, on a compliant JavaScript engine, list the properties in object order).

The order of object properties is not something it's usually useful to use; they're too hard to control. If you want order, use an array. But as it seems you don't want order, that's fine, just don't worry about the order the resulting object's properties appear to be in.


问:
PL/SQL Program that uses a Cursor to Rank
I'm trying to use the SQL statement in here and put it into a cursor. Unfortunately, I am unable to use the Rank() function for this particular assignment. </p>

```<code>CREATE or REPLACE PROCEDURE RankGPA
IS
  vSnum   student.snum%type;
  vSname  student.sname%type;
  vGPA    student.GPA%type;
  vMajor  student.major%type;
  CURSOR rankGPA_cursor IS
    SELECT s1.snum, s1.sname, s1.gpa, count( s2.gpa ) + 1 as rank, s1.major
    FROM students s1
    LEFT JOIN students s2
    ON s1.GPA < s2.GPA
    GROUP BY s1.snum, s1.sname, s1.gpa, s1.Major
    ORDER BY 4;
BEGIN
  OPEN rankGPA_cursor;
  FETCH rankGPA_cursor INTO vSnum, vSname, vGPA, vMajor;
END;
</code>```

<p>I'm trying to get an output like this: </p>

```<code>Rank SNUM  SNAME  GPA  MAJOR
**** ****  *****  ***  *****
1    101   Bob    4     ENGR
2    102   Cari   3.5   ENGL
</code>```

答:
The phrasing in your comment is a bit confusing, but it sounds like they want you to have a local variable to act as the 'rank' by counting the rows as they are fetched, something like:

```<code>DECLARE
  counter pls_integer := 0;
  CURSOR rankGPA_cursor IS
    SELECT s.snum, s.sname, s.gpa, s.major
    FROM students s
    ORDER BY s.gpa DESC;
BEGIN
  FOR rankGPA_row IN rankGPA_cursor LOOP
    counter := counter + 1;
    dbms_output.put_line(counter
      ||' '|| rankGPA_row.snum
      ||' '|| rankGPA_row.sname
      ||' '|| rankGPA_row.gpa
      ||' '|| rankGPA_row.major
    );
  END LOOP;
END;
/
</code>```

Each time the loop the counter variable is increased. Because the cursor query is ordered by GPA descending the first row fetched has the highest GPA and the counter is 1 at that point.

Using dbms_output for this is bad practise as in the real world you won't know if the client has that enabled, and you have to do some work to format the printed results neatly. But then this is contrived anyway.

You also need to consider how you want to rank things if two students have the same GPA, which seems likely. This will currently rank tied students arbitrarily. You could change the order by clause to add, say, secondary sorting by name; but students with tied scores will still get different ranks. It's certainly possible to give them the same rank even with this method, by keeping track of the last-seen GPA and only incrementing the rank/counter if the new row's value is different form the previous one. I don't know what you're expected to produce though.

You can use any style of cursor for this; explicit or implicit, and with the cursor-for-loop or with explicit open-fetch in a loop-close if you prefer.

Body:
I'm trying to use the SQL statement in here and put it into a cursor. Unfortunately, I am unable to use the Rank() function for this particular assignment.

CREATE or REPLACE PROCEDURE RankGPA
IS
  vSnum   student.snum%type;
  vSname  student.sname%type;
  vGPA    student.GPA%type;
  vMajor  student.major%type;
  CURSOR rankGPA_cursor IS
    SELECT s1.snum, s1.sname, s1.gpa, count( s2.gpa ) + 1 as rank, s1.major
    FROM students s1
    LEFT JOIN students s2
    ON s1.GPA < s2.GPA
    GROUP BY s1.snum, s1.sname, s1.gpa, s1.Major
    ORDER BY 4;
BEGIN
  OPEN rankGPA_cursor;
  FETCH rankGPA_cursor INTO vSnum, vSname, vGPA, vMajor;
END;

I'm trying to get an output like this:

Rank SNUM  SNAME  GPA  MAJOR
**** ****  *****  ***  *****
1    101   Bob    4     ENGR
2    102   Cari   3.5   ENGL

Body:
The phrasing in your comment is a bit confusing, but it sounds like they want you to have a local variable to act as the 'rank' by counting the rows as they are fetched, something like:

DECLARE
  counter pls_integer := 0;
  CURSOR rankGPA_cursor IS
    SELECT s.snum, s.sname, s.gpa, s.major
    FROM students s
    ORDER BY s.gpa DESC;
BEGIN
  FOR rankGPA_row IN rankGPA_cursor LOOP
    counter := counter + 1;
    dbms_output.put_line(counter
      ||' '|| rankGPA_row.snum
      ||' '|| rankGPA_row.sname
      ||' '|| rankGPA_row.gpa
      ||' '|| rankGPA_row.major
    );
  END LOOP;
END;
/

Each time the loop the counter variable is increased. Because the cursor query is ordered by GPA descending the first row fetched has the highest GPA and the counter is 1 at that point.

Using dbms_output for this is bad practise as in the real world you won't know if the client has that enabled, and you have to do some work to format the printed results neatly. But then this is contrived anyway.

You also need to consider how you want to rank things if two students have the same GPA, which seems likely. This will currently rank tied students arbitrarily. You could change the order by clause to add, say, secondary sorting by name; but students with tied scores will still get different ranks. It's certainly possible to give them the same rank even with this method, by keeping track of the last-seen GPA and only incrementing the rank/counter if the new row's value is different form the previous one. I don't know what you're expected to produce though.

You can use any style of cursor for this; explicit or implicit, and with the cursor-for-loop or with explicit open-fetch in a loop-close if you prefer.


问:
SQL query for a user input match using python connection
```<code>def showPatient():

    patient_lname = input("\nEnter the last name of the patient "
                    "you would like to search for: \n")

    query = c.execute("SELECT CONCAT(fname, " ", mi, " ", lname) "
                  "FROM Patients WHERE lname LIKE ?)", (patient_lname,))
</code>```

Prompts with an error message in showPatient

"FROM Patients WHERE lname LIKE ?)", (patient_lname,))

sqlite3.OperationalError: near ",": syntax error

```<code>    resultset = c.fetchall()

    if not resultset:
        print("Sorry, the last name you entered does not match any patients "
              "in the hospital.") #if there are no results this is printed
    else:
        for result in resultset:
            result = ' '.join(result)
            print("\n\t", result)
</code>```

答:
You are using Python strings delimited with ". In this particular execute() call, you have four of them; the resulting SQL statement looks like this:

SELECT CONCAT(fname, , mi, , lname)
FROM Patients WHERE lname LIKE ?)
```

In SQL, you should delimit strings with '. (And the standard SQL way of concatenating strings is the || operator, and you have a superfluous ).)

Body:
def showPatient():

    patient_lname = input("\nEnter the last name of the patient "
                    "you would like to search for: \n")

    query = c.execute("SELECT CONCAT(fname, " ", mi, " ", lname) "
                  "FROM Patients WHERE lname LIKE ?)", (patient_lname,))

Prompts with an error message in showPatient

"FROM Patients WHERE lname LIKE ?)", (patient_lname,))

sqlite3.OperationalError: near ",": syntax error

    resultset = c.fetchall()

    if not resultset:
        print("Sorry, the last name you entered does not match any patients "
              "in the hospital.") #if there are no results this is printed
    else:
        for result in resultset:
            result = ' '.join(result)
            print("\n\t", result)

Body:
You are using Python strings delimited with ". In this particular execute() call, you have four of them; the resulting SQL statement looks like this:

SELECT CONCAT(fname, , mi, , lname)
FROM Patients WHERE lname LIKE ?)

In SQL, you should delimit strings with '. (And the standard SQL way of concatenating strings is the || operator, and you have a superfluous ).)


问:
How to replace spring property placeholders in a simple java program
I am working with Java and spring boot apps. I have a property file which needs to be added as environmental variables for a docker image at run time. Some of the properties are filtered through the existing Environment when they are used via placeholders as below.

```<code>app.name=MyApp
app.description=${app.name} is a Spring Boot application
</code>```

I am writing a sample java file to read this property file and create a map object with some filtered properties. In this process how can I replace the placeholders with the actual property values?

I have tried looking for a key and replacing using getProperty method. But I would like to avoid looking up hard coded property key names in order to avoid maintenance difficulties.
Thanks in advance.

答:
I would create a new Properties descendant, with a method that gets a property value, and replaces any references, if any.

Something like this:

```<code>class MyProperties extends Properties
{
    // Constructors, as needed
    private Pettern p = Pattern.compile("\\$\\{([^}]+)\\}");
    public String getString(final String key)
    {
        final String value = getProperty(key);
        if (null == value)
            return null;
        final StringBuffer result = new StringBuffer();
        final Matcher m = p.matcher(value);
        while (m.find())
        {
            final String refKey = m.group(1);
            final String refValue = getProperty(refKey);
            m.appendReplacement(result, null == refValue ? refKey : refValue);
        }
        m.appendTail(result);
        return result.toString();
    }
}
</code>```

Body:
I am working with Java and spring boot apps. I have a property file which needs to be added as environmental variables for a docker image at run time. Some of the properties are filtered through the existing Environment when they are used via placeholders as below.

app.name=MyApp
app.description=${app.name} is a Spring Boot application

I am writing a sample java file to read this property file and create a map object with some filtered properties. In this process how can I replace the placeholders with the actual property values?

I have tried looking for a key and replacing using getProperty method. But I would like to avoid looking up hard coded property key names in order to avoid maintenance difficulties.
Thanks in advance.

Body:
I would create a new Properties descendant, with a method that gets a property value, and replaces any references, if any.

Something like this:

class MyProperties extends Properties
{
    // Constructors, as needed
    private Pettern p = Pattern.compile("\\$\\{([^}]+)\\}");
    public String getString(final String key)
    {
        final String value = getProperty(key);
        if (null == value)
            return null;
        final StringBuffer result = new StringBuffer();
        final Matcher m = p.matcher(value);
        while (m.find())
        {
            final String refKey = m.group(1);
            final String refValue = getProperty(refKey);
            m.appendReplacement(result, null == refValue ? refKey : refValue);
        }
        m.appendTail(result);
        return result.toString();
    }
}


问:
Java: duplicate method signature in nested class
Hopefully this question hasn't already been asked. I've had a look around but haven't found a similar post.

Experimenting in Java I've noticed that there is no restriction on having duplicate method signatures in a nested class, which seems counter-intuitive.

For example, if I create class A containing a method with the signature int x() and later add a nested class B containing an identical method, the compiler seems to have no problem with it. My initial assumption was that it would complain that x is already defined. Perhaps I'm missing something obvious that explains why this is allowed?

```<code>class A {
    int x() {
        return 1;
    }

    class B {
        int x() {
            return 2;
        }
    }
}
</code>```

Subsequently, is there any way to access class A's method x from within the scope of class B, or is it permanently hidden by the method x of the local scope?

Edit: I appreciate that the core of the question is the same as this post, however, I was more interested in understanding why this behaviour is allowed as it wasn't immediately clear to me.

答: Why would the compiler complain? They are two different classes, they just happen to be nested. </p>

Body:
Hopefully this question hasn't already been asked. I've had a look around but haven't found a similar post.

Experimenting in Java I've noticed that there is no restriction on having duplicate method signatures in a nested class, which seems counter-intuitive.

For example, if I create class A containing a method with the signature int x() and later add a nested class B containing an identical method, the compiler seems to have no problem with it. My initial assumption was that it would complain that x is already defined. Perhaps I'm missing something obvious that explains why this is allowed?

class A {
    int x() {
        return 1;
    }

    class B {
        int x() {
            return 2;
        }
    }
}

Subsequently, is there any way to access class A's method x from within the scope of class B, or is it permanently hidden by the method x of the local scope?

Edit: I appreciate that the core of the question is the same as this post, however, I was more interested in understanding why this behaviour is allowed as it wasn't immediately clear to me.


问:
How to check if one textbox value should be less than another textbox value and also the sum of both values should not be greater than 1
How to check if one text box value should be less than another text box value and also the sum of both values should not be greater than 1 in javascript</p>

答:
Here is a simple example.

function check()
{
   var input1 = Number(document.getElementById( "input1" ).value);
   var input2 = Number(document.getElementById( "input2" ).value);

   if ( input1 >= input2 || input1 + input2 != 1 )
   {
      console.log( "Error! Invalid value" );
   }
   else
   {
      console.log( "Success! Valid value" );
   }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code>Input 1 (less value) <input id="input1" value="0"> <br><br>
Input 2 (more value) <input id="input2" value="1"> <br><br>

<button onclick="check()">Check</button></code>```

Body:
Here is a simple example.

function check()
{
   var input1 = Number(document.getElementById( "input1" ).value);
   var input2 = Number(document.getElementById( "input2" ).value);

   if ( input1 >= input2 || input1 + input2 != 1 )
   {
      console.log( "Error! Invalid value" );
   }
   else
   {
      console.log( "Success! Valid value" );
   }
}

Input 1 (less value) <input id="input1" value="0"> <br><br>
Input 2 (more value) <input id="input2" value="1"> <br><br>

<button onclick="check()">Check</button>


答:
Subsequently, is there any way to access class A's method x from within the scope of class B, or is it permanently hidden by the method x of the local scope?

```<code>A.this.x()
</code>```

Title: Java: duplicate method signature in nested class

Body:
Subsequently, is there any way to access class A's method x from within the scope of class B, or is it permanently hidden by the method x of the local scope?

A.this.x()


问:
Can't use Bootstrap in PHP file
I'm fetching some data from a MySQL database onto a WebPage. I came up with a simple PHP page that queries the database and shows the query in the form of a table and it works just fine.

However, when I try to add bootstrap to the page and style it, the entire page stops working.

Here's my index.php

```<code><!DOCTYPE html>
<html>
<head>
<title>MakersBox</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
</head>
<body>
<center>
<h1>Sensor Testing Dashboard</h1>
<div class="container">
<?php
echo "<table class='table table-hover' align=center>";
 echo "<thead><tr><th>Sensor Id</th><th>Temperature</th><th>Light</th><th>Last Updated</th></tr></thead>";

class TableRows extends RecursiveIteratorIterator {
    function __construct($it) {
        parent::__construct($it, self::LEAVES_ONLY);
    }

    function current() {
        return "<td>" . parent::current(). "</td>";
    }

    function beginChildren() {
        echo "<tr>";
    }

    function endChildren() {
        echo "</tr>" . "\n";
    }
}

$servername = "localhost";
$username = "root";
$password = "paanikiboond";
$dbname = "testbox1";

try {
    $conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
    $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    $stmt = $conn->prepare("SELECT * FROM sensor ORDER BY LastUpdate DESC LIMIT 1");
    $stmt->execute();

    // set the resulting array to associative
    $result = $stmt->setFetchMode(PDO::FETCH_ASSOC);

    foreach(new TableRows(new RecursiveArrayIterator($stmt->fetchAll())) as $k=>$v) {
        echo $v;
    }
}
catch(PDOException $e) {
    echo "Error: " . $e->getMessage();
}
$conn = null;
echo "</table>";
</div>

$url1=$_SERVER['REQUEST_URI'];
header("Refresh: 3600 ; URL=$url1");
?>

</body>
</html>
</code>```

Any idea what I may be doing wrong here?

答:
I tried your code. I only find these three mistakes:

You must use echo for build HTML code from PHP and then close your
div container

```<code>   $conn = null;
   echo "</table>";

   //wrong way expecting statement
   </div>

   //correct way for use HTML inside PHP tags
   echo "</div>";
</code>```

The line where you add a header "refresh" generate a warning because
"Cannot modify header information - headers already sent"

```<code>   $url1=$_SERVER['REQUEST_URI'];
   header("Refresh: 3600 ; URL=$url1");
</code>```

You use  tag that it's deprecated so you should use CSS instead and you not close this tag

Title: Can't use Bootstrap in PHP file

Body:
I'm fetching some data from a MySQL database onto a WebPage. I came up with a simple PHP page that queries the database and shows the query in the form of a table and it works just fine.

However, when I try to add bootstrap to the page and style it, the entire page stops working.

Here's my index.php

<!DOCTYPE html>

<title>MakersBox</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">

Sensor Testing Dashboard

<?php
echo "
";
 echo "

Sensor Id	Temperature	Light	Last Updated

";

class TableRows extends RecursiveIteratorIterator {
    function __construct($it) {
        parent::__construct($it, self::LEAVES_ONLY);
    }

    function current() {
        return "" . parent::current(). "	";
    }

    function beginChildren() {
        echo "
";
    }

    function endChildren() {
        echo "
" . "\n";
    }
}

$servername = "localhost";
$username = "root";
$password = "paanikiboond";
$dbname = "testbox1";

try {
    $conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
    $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    $stmt = $conn->prepare("SELECT * FROM sensor ORDER BY LastUpdate DESC LIMIT 1");
    $stmt->execute();

    // set the resulting array to associative
    $result = $stmt->setFetchMode(PDO::FETCH_ASSOC);

    foreach(new TableRows(new RecursiveArrayIterator($stmt->fetchAll())) as $k=>$v) {
        echo $v;
    }
}
catch(PDOException $e) {
    echo "Error: " . $e->getMessage();
}
$conn = null;
echo "
";

$url1=$_SERVER['REQUEST_URI'];
header("Refresh: 3600 ; URL=$url1");
?>

Any idea what I may be doing wrong here?

Body:
I tried your code. I only find these three mistakes:

You must use echo for build HTML code from PHP and then close your
div container

   $conn = null;
   echo "</table>";

   //wrong way expecting statement
   </div>

   //correct way for use HTML inside PHP tags
   echo "</div>";

The line where you add a header "refresh" generate a warning because
"Cannot modify header information - headers already sent"

   $url1=$_SERVER['REQUEST_URI'];
   header("Refresh: 3600 ; URL=$url1");

You use <center> tag that it's deprecated so you should use CSS instead and you not close this tag


问:
MySQL, count the number of "filled" fields in a table
MySQL (table):

```<code>+----+------+
| id | text |
+----+------+
| 1  |      |
+----+------+
| 2  | blah |
+----+------+
| 3  |      |
+----+------+
| 4  | blah |
+----+------+
| 5  | blah |
+----+------+
</code>```

PHP:

```<code>$a = mysql_query("SELECT COUNT(*) AS count1 FROM `table`");
$b = mysql_fetch_assoc($a);

echo $b['count1'];
</code>```

Output:

```<code>5
</code>```

However, I also want to count the text fields which are filled - within the same query, if possible.

Result:

```<code>5 in total
3 with filled text fields
</code>```

答:
This can be accomplished quite nicely with sub-queries.

```<code>SELECT COUNT(id) AS id, COUNT(SELECT text FROM 'table' WHERE text IS NOT NULL) AS t FROM 'table'
</code>```

Note to self: start proofreading your work before submitting it.

Body:
MySQL (table):

+----+------+
| id | text |
+----+------+
| 1  |      |
+----+------+
| 2  | blah |
+----+------+
| 3  |      |
+----+------+
| 4  | blah |
+----+------+
| 5  | blah |
+----+------+

PHP:

$a = mysql_query("SELECT COUNT(*) AS count1 FROM `table`");
$b = mysql_fetch_assoc($a);

echo $b['count1'];

Output:

5

However, I also want to count the text fields which are filled - within the same query, if possible.

Result:

5 in total
3 with filled text fields

Body:
This can be accomplished quite nicely with sub-queries.

SELECT COUNT(id) AS id, COUNT(SELECT text FROM 'table' WHERE text IS NOT NULL) AS t FROM 'table'

Note to self: start proofreading your work before submitting it.


问:
Give CSS property to parent td using CSS
I have referred to many options but still I am not able to apply CSS to my parent container. My table structure is like:

```<code><td>
  <div id="div1">
      <div id="div2" class="colorMe"></div>
  </div>
</td>
</code>```

Now according to above structure if div2 has class colorMe then I want to color the entire td background in yellow.

I have used CSS like this but not working:

```<code>td > div> div.colorMe {
background-color:yellow;
}
</code>```

Can you please tell me how I can color my td using css?

答: There is currently no possibility to apply CSS Rules to a parent element. There is in fact the :has Pseudoclass, which is exactly for this kind of issues, but at the moment (Nov 2017) it is not supported by any browser. The only way to achieve this would be with Javascript.

Body:
I have referred to many options but still I am not able to apply CSS to my parent container. My table structure is like:

Now according to above structure if div2 has class colorMe then I want to color the entire td background in yellow.

I have used CSS like this but not working:

td > div> div.colorMe {
background-color:yellow;
}

Can you please tell me how I can color my td using css?


问:
Using custom font in android TextView using xml
I have added a custom font file to my assets/fonts folder. How do I use it from my XML?

I can use it from code as follows:

```<code>TextView text = (TextView) findViewById(R.id.textview03);
Typeface tf = Typeface.createFromAsset(getAssets(), "fonts/Molot.otf");
text.setTypeface(tf);
</code>```

Can't I do it from XML using an android:typeface="/fonts/Molot.otf" attribute?

答:
I know this is an old question, but i've found a much easier solution.

First declare your TextView in xml as usual.
Put your font (TTF or TTC) in the asset folder

app\src\main\assets\

Then just set the typeface for your text view in your onCreate method.

```<code>@Override
    protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_name);

    TextView textView = findViewById(R.id.my_textView);
    Typeface typeface = Typeface.createFromAsset(getAssets(), "fontName.ttf");
    textView.setTypeface(typeface);
}
</code>```

Done.

Body:
I have added a custom font file to my assets/fonts folder. How do I use it from my XML?

I can use it from code as follows:

TextView text = (TextView) findViewById(R.id.textview03);
Typeface tf = Typeface.createFromAsset(getAssets(), "fonts/Molot.otf");
text.setTypeface(tf);

Can't I do it from XML using an android:typeface="/fonts/Molot.otf" attribute?

Body:
I know this is an old question, but i've found a much easier solution.

First declare your TextView in xml as usual.
Put your font (TTF or TTC) in the asset folder

app\src\main\assets\

Then just set the typeface for your text view in your onCreate method.

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

    TextView textView = findViewById(R.id.my_textView);
    Typeface typeface = Typeface.createFromAsset(getAssets(), "fontName.ttf");
    textView.setTypeface(typeface);
}

Done.

ContentLicense: CC BY-SA 4.0


问:
How to turn off the alarm?
My App goes like this:

When you first start the app, you'll see a button. Connecting or disconnecting the AC charger doesn't affect anything until you hit that Start button.

When you tap the Start button, the "service" is started.

Now if you remove the AC charger you will hear an alarm sound.

Connecting the AC with the device again should stop the alarm but it does NOT.

Now removing the AC again starts another alarm. The alarms overlap.

Can you help me find the bug?

Thanks

My work so far:

AndroidManifest.xml

```<code><?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.yousef.mustafa.antitheft">

    <application
        android:allowBackup="true"
        android:icon="@mipmap/antitheft"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/antitheft"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

        <receiver android:name=".PowerConnectionReceiver">

        </receiver>

    </application>

</manifest>
</code>```

MainActivity.java

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

    Button startServiceButton;
    PowerConnectionReceiver powerConnectionReceiver;
    BroadcastReceiver powerDisconnectedBroadcastReceiver;
    BroadcastReceiver powerConnectedBroadcastReceiver;

    @Override
    protected void onCreate(final Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        powerConnectionReceiver = new PowerConnectionReceiver(true);
        startServiceButton = (ToggleButton) findViewById(R.id.startServiceButton);

        powerDisconnectedBroadcastReceiver = new PowerConnectionReceiver(true);
        powerConnectedBroadcastReceiver = new PowerConnectionReceiver(false);

        startServiceButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (startServiceButton.isActivated()) {
                    unregisterReceiver(powerDisconnectedBroadcastReceiver);
                    unregisterReceiver(powerConnectedBroadcastReceiver);
                    Toast.makeText(MainActivity.this, "Service stopped", Toast.LENGTH_SHORT).show();
                    startServiceButton.setActivated(false);
                } else {
                    monitorBatteryChanges();
                }
            }
        });
    }

    private void monitorBatteryChanges() {

        IntentFilter powerDisconnectedIntentFilter = new IntentFilter("android.intent.action.ACTION_POWER_DISCONNECTED");
        registerReceiver(powerDisconnectedBroadcastReceiver, powerDisconnectedIntentFilter);

        IntentFilter powerConnectedIntentFilter = new IntentFilter("android.intent.action.ACTION_POWER_CONNECTED");
        registerReceiver(powerConnectedBroadcastReceiver, powerConnectedIntentFilter);

        Toast.makeText(MainActivity.this, "Service started", Toast.LENGTH_SHORT).show();
        startServiceButton.setActivated(true);
    }

}
</code>```

PowerConnectionReceiver.java

```<code>public class PowerConnectionReceiver extends BroadcastReceiver {

    MediaPlayer mediaPlayer = new MediaPlayer();

    // Determine whether the AC is disconnected or not
    private boolean POWER_DISCONNECTED = true;

    PowerConnectionReceiver(boolean disconnected) {
        this.POWER_DISCONNECTED = disconnected;
    }

    @Override
    public void onReceive(Context context, Intent intent) {
        if (POWER_DISCONNECTED) {
            mediaPlayer = MediaPlayer.create(context, R.raw.alarm_2);
            Toast.makeText(context, "Alarm started", Toast.LENGTH_SHORT).show();
            mediaPlayer.start();
            mediaPlayer.setLooping(true);
            //POWER_DISCONNECTED = false;
        } else {
            try {
                if (mediaPlayer.isPlaying()) {
                    mediaPlayer.stop();
                    mediaPlayer.release();
                    Toast.makeText(context, "Alarm stopped", Toast.LENGTH_SHORT).show();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }

        }
    }
}
</code>```

答:
I was finally able to find a solution.

MainActivity.java

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

    Button startServiceButton;
    BroadcastReceiver powerConnectionBroadcastReceiver;
    IntentFilter powerDisconnectedIntentFilter = new IntentFilter("android.intent.action.ACTION_POWER_DISCONNECTED");
    IntentFilter powerConnectedIntentFilter = new IntentFilter("android.intent.action.ACTION_POWER_CONNECTED");

    @Override
    protected void onCreate(final Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        startServiceButton = (ToggleButton) findViewById(R.id.startServiceButton);
        powerConnectionBroadcastReceiver = new PowerConnectionBroadcastReceiver();

        startServiceButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (startServiceButton.isActivated()) {
                    unregisterReceiver(powerConnectionBroadcastReceiver);
                    startServiceButton.setActivated(false);
                    Toast.makeText(MainActivity.this, "Service stopped", Toast.LENGTH_SHORT).show();
                } else {
                    monitorBatteryChanges();
                }
            }
        });
    }

    private void monitorBatteryChanges() {
        registerReceiver(powerConnectionBroadcastReceiver, powerDisconnectedIntentFilter);
        registerReceiver(powerConnectionBroadcastReceiver, powerConnectedIntentFilter);
        startServiceButton.setActivated(true);
        Toast.makeText(MainActivity.this, "Service started", Toast.LENGTH_SHORT).show();
    }
}
</code>```

PowerConnectionBroadcastReceiver.java

```<code>public class PowerConnectionBroadcastReceiver extends BroadcastReceiver {

    MediaPlayer mediaPlayer;

    @Override
    public void onReceive(Context context, Intent intent) {

        String action = intent.getAction();

        if (action.equals(Intent.ACTION_POWER_DISCONNECTED)) {
            mediaPlayer = MediaPlayer.create(context, R.raw.alarm_1);
            mediaPlayer.start();
            mediaPlayer.setLooping(true);
            Toast.makeText(context, "Alarm started", Toast.LENGTH_SHORT).show();
        } else {
            try {
                if (mediaPlayer != null)
                mediaPlayer.release();
                Toast.makeText(context, "Alarm stopped", Toast.LENGTH_SHORT).show();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}
</code>```

It may not be the best solution but it works :)

Thanks for the help.

Title: How to turn off the alarm?

Body:
My App goes like this:

When you first start the app, you'll see a button. Connecting or disconnecting the AC charger doesn't affect anything until you hit that Start button.

When you tap the Start button, the "service" is started.

Now if you remove the AC charger you will hear an alarm sound.

Connecting the AC with the device again should stop the alarm but it does NOT.

Now removing the AC again starts another alarm. The alarms overlap.

Can you help me find the bug?

Thanks

My work so far:

AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.yousef.mustafa.antitheft">

    <application
        android:allowBackup="true"
        android:icon="@mipmap/antitheft"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/antitheft"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

        <receiver android:name=".PowerConnectionReceiver">

        </receiver>

    </application>

</manifest>

MainActivity.java

public class MainActivity extends AppCompatActivity {

    Button startServiceButton;
    PowerConnectionReceiver powerConnectionReceiver;
    BroadcastReceiver powerDisconnectedBroadcastReceiver;
    BroadcastReceiver powerConnectedBroadcastReceiver;

    @Override
    protected void onCreate(final Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        powerConnectionReceiver = new PowerConnectionReceiver(true);
        startServiceButton = (ToggleButton) findViewById(R.id.startServiceButton);

        powerDisconnectedBroadcastReceiver = new PowerConnectionReceiver(true);
        powerConnectedBroadcastReceiver = new PowerConnectionReceiver(false);

        startServiceButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (startServiceButton.isActivated()) {
                    unregisterReceiver(powerDisconnectedBroadcastReceiver);
                    unregisterReceiver(powerConnectedBroadcastReceiver);
                    Toast.makeText(MainActivity.this, "Service stopped", Toast.LENGTH_SHORT).show();
                    startServiceButton.setActivated(false);
                } else {
                    monitorBatteryChanges();
                }
            }
        });
    }

    private void monitorBatteryChanges() {

        IntentFilter powerDisconnectedIntentFilter = new IntentFilter("android.intent.action.ACTION_POWER_DISCONNECTED");
        registerReceiver(powerDisconnectedBroadcastReceiver, powerDisconnectedIntentFilter);

        IntentFilter powerConnectedIntentFilter = new IntentFilter("android.intent.action.ACTION_POWER_CONNECTED");
        registerReceiver(powerConnectedBroadcastReceiver, powerConnectedIntentFilter);

        Toast.makeText(MainActivity.this, "Service started", Toast.LENGTH_SHORT).show();
        startServiceButton.setActivated(true);
    }

}

PowerConnectionReceiver.java

public class PowerConnectionReceiver extends BroadcastReceiver {

    MediaPlayer mediaPlayer = new MediaPlayer();

    // Determine whether the AC is disconnected or not
    private boolean POWER_DISCONNECTED = true;

    PowerConnectionReceiver(boolean disconnected) {
        this.POWER_DISCONNECTED = disconnected;
    }

    @Override
    public void onReceive(Context context, Intent intent) {
        if (POWER_DISCONNECTED) {
            mediaPlayer = MediaPlayer.create(context, R.raw.alarm_2);
            Toast.makeText(context, "Alarm started", Toast.LENGTH_SHORT).show();
            mediaPlayer.start();
            mediaPlayer.setLooping(true);
            //POWER_DISCONNECTED = false;
        } else {
            try {
                if (mediaPlayer.isPlaying()) {
                    mediaPlayer.stop();
                    mediaPlayer.release();
                    Toast.makeText(context, "Alarm stopped", Toast.LENGTH_SHORT).show();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }

        }
    }
}

Body:
I was finally able to find a solution.

MainActivity.java

public class MainActivity extends AppCompatActivity {

    Button startServiceButton;
    BroadcastReceiver powerConnectionBroadcastReceiver;
    IntentFilter powerDisconnectedIntentFilter = new IntentFilter("android.intent.action.ACTION_POWER_DISCONNECTED");
    IntentFilter powerConnectedIntentFilter = new IntentFilter("android.intent.action.ACTION_POWER_CONNECTED");

    @Override
    protected void onCreate(final Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        startServiceButton = (ToggleButton) findViewById(R.id.startServiceButton);
        powerConnectionBroadcastReceiver = new PowerConnectionBroadcastReceiver();

        startServiceButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (startServiceButton.isActivated()) {
                    unregisterReceiver(powerConnectionBroadcastReceiver);
                    startServiceButton.setActivated(false);
                    Toast.makeText(MainActivity.this, "Service stopped", Toast.LENGTH_SHORT).show();
                } else {
                    monitorBatteryChanges();
                }
            }
        });
    }

    private void monitorBatteryChanges() {
        registerReceiver(powerConnectionBroadcastReceiver, powerDisconnectedIntentFilter);
        registerReceiver(powerConnectionBroadcastReceiver, powerConnectedIntentFilter);
        startServiceButton.setActivated(true);
        Toast.makeText(MainActivity.this, "Service started", Toast.LENGTH_SHORT).show();
    }
}

PowerConnectionBroadcastReceiver.java

public class PowerConnectionBroadcastReceiver extends BroadcastReceiver {

    MediaPlayer mediaPlayer;

    @Override
    public void onReceive(Context context, Intent intent) {

        String action = intent.getAction();

        if (action.equals(Intent.ACTION_POWER_DISCONNECTED)) {
            mediaPlayer = MediaPlayer.create(context, R.raw.alarm_1);
            mediaPlayer.start();
            mediaPlayer.setLooping(true);
            Toast.makeText(context, "Alarm started", Toast.LENGTH_SHORT).show();
        } else {
            try {
                if (mediaPlayer != null)
                mediaPlayer.release();
                Toast.makeText(context, "Alarm stopped", Toast.LENGTH_SHORT).show();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}

It may not be the best solution but it works :)

Thanks for the help.


问:
Passing variable to method as to add to generic arraylist - Java
I am wanting to take user data in one method and pass that data to an "add" method, as to add said data to a generic arraylist. However I receive the following error message...

add (T) in List cannot be applied to (java.lang.String)

I'm not sure if this is a static problem or not...

My simplified code:

```<code>List<T> list = new ArrayList<T>();

void dataCollection() {
    Scanner scan = new Scanner(System.in);
    System.out.println("type data");
    add(scan.next());
}

void add(T t) {
    list.add(t);
}
</code>```

答:
If you want to add Strings to your List, define it as a List<String>, not List<T>.

A List<T> might be (depending on how your class is instantiated), for example, a List<Integer>, which can't hold Strings.

If you truly need your List to be generic, you shouldn't be adding Strings to it.

Body:
I am wanting to take user data in one method and pass that data to an "add" method, as to add said data to a generic arraylist. However I receive the following error message...

add (T) in List cannot be applied to (java.lang.String)

I'm not sure if this is a static problem or not...

My simplified code:

List<T> list = new ArrayList<T>();

void dataCollection() {
    Scanner scan = new Scanner(System.in);
    System.out.println("type data");
    add(scan.next());
}

void add(T t) {
    list.add(t);
}


问:
how do I use the Rails.logger from javascript
I nside a html.erb, I want to use the logger</p>

```<code><script type="text/javascript">
  $j(function(){

    $j('#AddQuestion').click(function(){
     //Send and http transaction to the server to get the address
      $j('#dialog').dialog(
        {buttons:{OK:function (event) {
                say('You clicked the ' + $(event.target).text() + ' button' );
              },  No:function (event) {
                say('You clicked the ' + $(event.target).text() + ' button' );
              }
                }
         });

      $j('#dialog').dialog('open');

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

答: Phrogz is correct.  Here's an example of using JQuery's XHR functionality to shoot messages over to a customised logging class.  Just utilising Rails.logger instead of this custom class is a cinch.


问:
Change column type in pandas
I created a DataFrame from a list of lists:

table = [
    ['a',  '1.2',  '4.2' ],
    ['b',  '70',   '0.03'],
    ['x',  '5',    '0'   ],
]

df = pd.DataFrame(table)
```

How do I convert the columns to specific types? In this case, I want to convert columns 2 and 3 into floats.

Is there a way to specify the types while converting the list to DataFrame? Or is it better to create the DataFrame first and then loop through the columns to change the dtype for each column? Ideally I would like to do this in a dynamic way because there can be hundreds of columns, and I don't want to specify exactly which columns are of which type. All I can guarantee is that each column contains values of the same type.

答:
This below code will change the datatype of a column.

```<code>df[['col.name1', 'col.name2'...]] = df[['col.name1', 'col.name2'..]].astype('data_type')
</code>```

In place of the data type, you can give your datatype what you want, like, str, float, int, etc.

Title: Change column type in pandas

Body:
I created a DataFrame from a list of lists:

table = [
    ['a',  '1.2',  '4.2' ],
    ['b',  '70',   '0.03'],
    ['x',  '5',    '0'   ],
]

df = pd.DataFrame(table)

How do I convert the columns to specific types? In this case, I want to convert columns 2 and 3 into floats.

Is there a way to specify the types while converting the list to DataFrame? Or is it better to create the DataFrame first and then loop through the columns to change the dtype for each column? Ideally I would like to do this in a dynamic way because there can be hundreds of columns, and I don't want to specify exactly which columns are of which type. All I can guarantee is that each column contains values of the same type.

Body:
This below code will change the datatype of a column.

df[['col.name1', 'col.name2'...]] = df[['col.name1', 'col.name2'..]].astype('data_type')

In place of the data type, you can give your datatype what you want, like, str, float, int, etc.


问:
sequelize you are using sql safe update error
I am getting this error randomly . I am deleting from activeusers table on the basis of username it gives me error sometime and works smoothly sometime.
here is my code for deleting

let say

```<code> data={nickname:'asad',id:1}
 activeusers.destroy({where:{username:data.nickname} }).then(res=>{
 });
</code>```

I have turn off the sql safe update from sql workbench but problem still exists
how can i permanently get rid from this error

答:
This is a common problem with updates in MySQL.  Here is your query:

```<code>DELETE FROM ActiveUsers WHERE username = 'mazhar.hayat@ibexglobal.com'
</code>```

The error stems from that you are not using a primary key column in the WHERE clause.  You would also see this error if you had no WHERE clause at all.  MySQL has a mode which views a DML query like this as unsafe, because it is broad and runs the risk of corrupting your data.

There is a hack solution to this which might work.  You could modify the query to mention the primary key column as follows:

```<code>DELETE
FROM ActiveUser
WHERE username = 'mazhar.hayat@ibexglobal.com' AND id=id
</code>```

This might spoof MySQL into thinking the query is safe, because it mentions the primary key column id in the WHERE clause.

But what I would recommend to you is turning off safe updates mode directly in MySQL.  Edit your startup script and make sure that --safe-updates and --i-am-a-dummy are not mentioned in the script.

Edit:

If you wanted to handle this from destroy, then the query option is the only option:

```<code>Post.findAll(
    { where: ["username = ? AND id = id", data.nickname] }
).success()
</code>```

Body:
I am getting this error randomly . I am deleting from activeusers table on the basis of username it gives me error sometime and works smoothly sometime.
here is my code for deleting

let say

 data={nickname:'asad',id:1}
 activeusers.destroy({where:{username:data.nickname} }).then(res=>{
 });

I have turn off the sql safe update from sql workbench but problem still exists
how can i permanently get rid from this error

Body:
This is a common problem with updates in MySQL.  Here is your query:

DELETE FROM ActiveUsers WHERE username = 'mazhar.hayat@ibexglobal.com'

The error stems from that you are not using a primary key column in the WHERE clause.  You would also see this error if you had no WHERE clause at all.  MySQL has a mode which views a DML query like this as unsafe, because it is broad and runs the risk of corrupting your data.

There is a hack solution to this which might work.  You could modify the query to mention the primary key column as follows:

DELETE
FROM ActiveUser
WHERE username = 'mazhar.hayat@ibexglobal.com' AND id=id

This might spoof MySQL into thinking the query is safe, because it mentions the primary key column id in the WHERE clause.

But what I would recommend to you is turning off safe updates mode directly in MySQL.  Edit your startup script and make sure that --safe-updates and --i-am-a-dummy are not mentioned in the script.

Edit:

If you wanted to handle this from destroy, then the query option is the only option:

Post.findAll(
    { where: ["username = ? AND id = id", data.nickname] }
).success()


答:
Where a class is defined doesn't matter so much. Keep in mind, in the end you have

```<code>class A { int x()
</code>```

and

```<code>class A.B { int x()
</code>```

Two (almost) independent classes. The only relationship that we have here is that any instance of B needs an "enclosing" instance of A to which it belongs (because it is a non-static inner class).

And of course, you can access the "enclosing" A "stuff" from within B, for example using A.this.x().

Body:
Hopefully this question hasn't already been asked. I've had a look around but haven't found a similar post.

Experimenting in Java I've noticed that there is no restriction on having duplicate method signatures in a nested class, which seems counter-intuitive.

For example, if I create class A containing a method with the signature int x() and later add a nested class B containing an identical method, the compiler seems to have no problem with it. My initial assumption was that it would complain that x is already defined. Perhaps I'm missing something obvious that explains why this is allowed?

class A {
    int x() {
        return 1;
    }

    class B {
        int x() {
            return 2;
        }
    }
}

Subsequently, is there any way to access class A's method x from within the scope of class B, or is it permanently hidden by the method x of the local scope?

Edit: I appreciate that the core of the question is the same as this post, however, I was more interested in understanding why this behaviour is allowed as it wasn't immediately clear to me.

Body:
Where a class is defined doesn't matter so much. Keep in mind, in the end you have

class A { int x()

and

class A.B { int x()

Two (almost) independent classes. The only relationship that we have here is that any instance of B needs an "enclosing" instance of A to which it belongs (because it is a non-static inner class).

And of course, you can access the "enclosing" A "stuff" from within B, for example using A.this.x().


问:
Admob in-house ads not showing
I have set up an in-house campaign under the Admob platform. This campaign is live for almost 3 days, but I get no impressions.

The ad in question is a banner. I have set up the mediation eCMP lower than the ad but still is not showing. Any help will be appreciated.

Thanks in advance!

答: I have found the solution, you need to update your billing information from AdWords in order to serve in-house ads.</p>

Title: Admob in-house ads not showing


问:
Detect non-null reference in an array
I just asked a similar question, but then I realized I actually need something else. Since that question already has two answers, I do not want to edit my question. So here is what I actually need:

I want to detect whether a subrange of an array contains null references only. Somehow like this:

```<code>public static <T> boolean nullReferencesOnly
(T[] array, int fromInclusive, int toExclusive)
{
    for (int i = fromInclusive; i < toExclusive; ++i)
    {
        if (array[i] != null) return false;
    }
    return true;
}
</code>```

Is there a method like this in the Java library so I don't have to manually loop over the array?

答:
I think that the best solution is to take the code you have already got, change the array type to Object[] and put the method it into a "helper" class.

AFAIK, there is no method in the standard Java libraries that does what you want directly.

AFAIK, there is no method in Apache Commons or Google Collections / Guava that does what you want directly.

Solutions involving Collection.contains will fail because that method is based on equals and will give an NPE if you test for null.

Solutions involving generic frequency methods don't short-circuit when they find a null.

Solutions involving applying Predicate objects are expensive, and take more code than your solution.

Your solution is easy to read, and more efficient than any of the proposed alternatives.  The fact that it involves an explicit loop should not concern you.  After all, this is Java code you are writing ... not a FP language.

Aside - if the problem had been to test for the presence of a null element (rather than a non-null element) then one alternative would be org.springframework.util.Assert.noNullElements.

```<code>http://static.springsource.org/spring/docs/3.0.x/javadoc-api/org/springframework/util/Assert.html#noNullElements(java.lang.Object[]))
</code>```

However, this throws an exception rather than returning true or false, and this is likely to make it a poor solution ... unless you were intending to throw an exception anyway.

Title: Detect non-null reference in an array

Body:
I just asked a similar question, but then I realized I actually need something else. Since that question already has two answers, I do not want to edit my question. So here is what I actually need:

I want to detect whether a subrange of an array contains null references only. Somehow like this:

public static <T> boolean nullReferencesOnly
(T[] array, int fromInclusive, int toExclusive)
{
    for (int i = fromInclusive; i < toExclusive; ++i)
    {
        if (array[i] != null) return false;
    }
    return true;
}

Is there a method like this in the Java library so I don't have to manually loop over the array?

Body:
I think that the best solution is to take the code you have already got, change the array type to Object[] and put the method it into a "helper" class.

AFAIK, there is no method in the standard Java libraries that does what you want directly.

AFAIK, there is no method in Apache Commons or Google Collections / Guava that does what you want directly.

Solutions involving Collection.contains will fail because that method is based on equals and will give an NPE if you test for null.

Solutions involving generic frequency methods don't short-circuit when they find a null.

Solutions involving applying Predicate objects are expensive, and take more code than your solution.

Your solution is easy to read, and more efficient than any of the proposed alternatives.  The fact that it involves an explicit loop should not concern you.  After all, this is Java code you are writing ... not a FP language.

Aside - if the problem had been to test for the presence of a null element (rather than a non-null element) then one alternative would be org.springframework.util.Assert.noNullElements.

http://static.springsource.org/spring/docs/3.0.x/javadoc-api/org/springframework/util/Assert.html#noNullElements(java.lang.Object[]))

However, this throws an exception rather than returning true or false, and this is likely to make it a poor solution ... unless you were intending to throw an exception anyway.


问:
Unreal Engine HTC Vive Controller Setup
I am new to unreal engine, I have purchased HTC Vive, I want to setup motion controllers with custom 3D Objects</p>

答:
There is Proper Documentation on how to setup motion controller on epic games site. Check following link.

enter link description here

Title: Unreal Engine HTC Vive Controller Setup


问:
why do i get this TypeError: argument of type 'int' is not iterable
First I just want to set the target_x and target_y, actually reading_x and reading_y refers to an accelerometer but to make the code simpler i set the values to 400

```<code>reading_x = 400
if  reading_x > 300:
    target_x = 4
elif 100 < reading_x < 300:
    target_x = 3
elif -100 > reading_x >-300:
    target_x = 1
elif reading_x < -300:
    target_x = 0
else:
    target_x =2
reading_y = 400
if  reading_y > 300:
    target_y = 4
elif 100 < reading_y < 300:
    target_y = 3
elif -100 > reading_y >-300:
    target_y = 1
elif reading_y < -300:
    target_y = 0
else:
    target_y =2
print(target_x, target_y)

# 4, 4
</code>```

it's a game and I just set positions of different car in a 5x5 board game and create a dictionary to save their positions

```<code>nb_car = 4
car_life = 2
car_dict = {}

while len (car_dict) < nb_sm:
    for car in range (nb_sm):
        car_x = randint(0,4)
        car_y = randint(0,4)
        car_dict[car +1] = {'x':car_x, 'y':car_y, 'life': car_life }
print(car_dict)

#{1: {'life': 2, 'x': 4, 'y': 4}, 2: {'life': 2, 'x': 4, 'y': 4}, 3: {'life': 2, 'x': 4, 'y': 4}, 4: {'life': 2, 'x': 4, 'y': 4}}
</code>```

in the game i want to destroy a car so i want to check if the target_x and target_y (4,4) will destroy a car but when i write this i get the TypeError: argument of type 'int' is not iterable

```<code>target_x in sm_dict[1]['x']
</code>```

can someone please help me ?

答:
in operator expects an iterable object on the right side  but you are providing an integer, therefore error occurred

Either use

```<code>if target_x == sm_dict[1]['x']:
    #Do your stuff
</code>```

Or

```<code>car_data in sm_dict:
    if sm_dict[car_data]['x'] == target_x:
        #Do your stuff
</code>```

Body:
First I just want to set the target_x and target_y, actually reading_x and reading_y refers to an accelerometer but to make the code simpler i set the values to 400

reading_x = 400
if  reading_x > 300:
    target_x = 4
elif 100 < reading_x < 300:
    target_x = 3
elif -100 > reading_x >-300:
    target_x = 1
elif reading_x < -300:
    target_x = 0
else:
    target_x =2
reading_y = 400
if  reading_y > 300:
    target_y = 4
elif 100 < reading_y < 300:
    target_y = 3
elif -100 > reading_y >-300:
    target_y = 1
elif reading_y < -300:
    target_y = 0
else:
    target_y =2
print(target_x, target_y)

# 4, 4

it's a game and I just set positions of different car in a 5x5 board game and create a dictionary to save their positions

nb_car = 4
car_life = 2
car_dict = {}

while len (car_dict) < nb_sm:
    for car in range (nb_sm):
        car_x = randint(0,4)
        car_y = randint(0,4)
        car_dict[car +1] = {'x':car_x, 'y':car_y, 'life': car_life }
print(car_dict)

#{1: {'life': 2, 'x': 4, 'y': 4}, 2: {'life': 2, 'x': 4, 'y': 4}, 3: {'life': 2, 'x': 4, 'y': 4}, 4: {'life': 2, 'x': 4, 'y': 4}}

in the game i want to destroy a car so i want to check if the target_x and target_y (4,4) will destroy a car but when i write this i get the TypeError: argument of type 'int' is not iterable

target_x in sm_dict[1]['x']

can someone please help me ?

Body:
in operator expects an iterable object on the right side  but you are providing an integer, therefore error occurred

Either use

if target_x == sm_dict[1]['x']:
    #Do your stuff

Or

car_data in sm_dict:
    if sm_dict[car_data]['x'] == target_x:
        #Do your stuff


问:
Underline two letters separately
Is there a way to have non-continuous underline? I want the underline stop and restart (and see that visually) where I closed and reopened the  tags..

W. Raven, “al-Washshaʾ”```

答:
What if you could wrap that using span tag and then use pseudo selector to add spacing between borders below and not between characters as below,

span{
  position:relative;
}
span:before{
  content:"";
  width:40%;
  height:1px;
  background:black;
  position:absolute;
  left:0;
  bottom:0;
}
span:after{
  content:"";
  width:40%;
  height:1px;
  background:black;
  position:absolute;
  right:0;
  bottom:0;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code>W. Raven, “al-Wa<span>shsh</span>aʾ”</code>```

Title: Underline two letters separately

Body:
What if you could wrap that using span tag and then use pseudo selector to add spacing between borders below and not between characters as below,

span{
  position:relative;
}
span:before{
  content:"";
  width:40%;
  height:1px;
  background:black;
  position:absolute;
  left:0;
  bottom:0;
}
span:after{
  content:"";
  width:40%;
  height:1px;
  background:black;
  position:absolute;
  right:0;
  bottom:0;
}

W. Raven, “al-Wa<span>shsh</span>aʾ”


问:
weird looping chain of synonyms error on plsql package
i can't compile this package body because i get "looping chain of synonyms"

i don't even reference any synonyms

i have checked the table dba_synonyms, there is nothing referencing the table in the select from

to be more specific, when i comment out the cursor select portion, it compiles fine

if you notice below, i am again selecting from the same table, only for count(*), this select works fine, but not the previous one

this is on oracle 12c

```<code>create or replace
package body dm_mnmi2407_pkg
is
    procedure create_appl_process_log(
        l_user_err_message_capl in varchar2,
        process_status_code_capl in varchar2,
        linecnt_capl in int
    )
    is
        l_action_taken      varchar2(50) := 'DICE Provider Demographic Feed To BRIGHTER';
        l_module_name       varchar2(20) := 'dm_mnmi2407.sqr';
        l_p_key             int := 1;
        l_p_error           char := ' ';
    begin
        dm_common_pkg.application_process_log(  l_action_taken,
                                                l_module_name,
                                                process_status_code_capl,
                                                NULL,
                                                NULL,
                                                l_user_err_message_capl,
                                                linecnt_capl,
                                                NULL,
                                                NULL,
                                                l_p_key,
                                                l_p_error
                                            );
    end create_appl_process_log;

    procedure write_records(
        full_feed_flag_wr in char,
        last_run_tmstmp_wr in date,
        process_start_tmstmp_wr in date,
        output_dir_wr in varchar2
        )
    is
        out_file        utl_file.file_type;
        out_filename    varchar2(70) := 'cdhprovdem' || '_' || process_start_tmstmp_wr ||'.dat';
        header_record   varchar2(20) := 'H, ' || process_start_tmstmp_wr;
        trailer_record  varchar2(20);

        cursor recordset is
            select  prov_donas_id as a
                    ,replace(replace(prov_id,',',' '),' ',' ') as b
                    ,lpad(prov_type1_npi,10,'0') as c
                    ,to_char(prov_eff_date,'YYYYMMDD') as d
                    ,replace(replace(prov_fee_sched,',',' '),' ',' ') as e
                    ,dppo_advantage_network_ind as f
                    ,donas_primary_fee_sched_ind as g
                    ,to_char(prov_fee_sched_eff_date,'YYYYMMDD') as h
                    ,to_char(prov_fee_sched_inactive_date,'YYYYMMDD') as i
                    ,to_char(prov_inactive_date,'YYYYMMDD') as j
                    ,prov_type as k
                    ,replace(replace(prov_title_code,',',' '),' ',' ') as l
                    ,replace(replace(prov_first_name,',',' '),' ',' ') as m
                    ,replace(replace(prov_middle_initial,',',' '),' ',' ') as n
                    ,replace(replace(prov_last_name,',',' '),' ',' ') as o
                    ,replace(replace(prov_speclty_code,',',' '),' ',' ') as p
                    ,prov_board_cert_speclty_flag as q
                    ,Prov_board_elig_speclty_flag as r
                    ,prov_donas_license_num as s
                    ,replace(replace(prov_donas_license_state_code,',',' '),' ',' ') as t
                    ,to_char(prov_experience_start_date,'YYYYMMDD') as u
                    ,to_char(prov_birth_date,'YYYYMMDD') as v
                    ,nvl(rpad(prov_foreign_lang_string,50,' '),'') as w
                    ,prov_gender as x
                    ,replace(replace(prov_dental_school_name,',',' '),' ',' ') as y
                    ,prov_primary_license_num as z
                    ,replace(replace(prov_primary_license_state_cd,',',' '),' ',' ') as aa
                    ,prov_accepting_new_pats_flag as bb
                    ,rpad(lpad(prov_type2_npi_1,10,'0')||' '||lpad(prov_type2_npi_2,10,'0')||' '|| lpad(prov_type2_npi_3,10,'0')||' '||lpad(prov_type2_npi_4,10,'0')||' '|| lpad(prov_type2_npi_5,10,'0')||' '||lpad(prov_type2_npi_6,10,'0')||' '|| lpad(prov_type2_npi_7,10,'0')||' '||lpad(prov_type2_npi_8,10,'0')||' '|| lpad(prov_type2_npi_9,10,'0')||' '||lpad(prov_type2_npi_10,10,'0')||' '|| lpad(prov_type2_npi_11,10,'0')||' '||lpad(prov_type2_npi_12,10,'0')||' '|| lpad(prov_type2_npi_13,10,'0')||' '||lpad(prov_type2_npi_14,10,'0')||' '|| lpad(prov_type2_npi_15,10,'0'),164,' ') as cc
                    ,dental_ofc_id as kk
                    ,lpad(replace(replace(dental_ofc_tax_id,',',' '),' ',' '),9,'0') as ll
                    ,replace(replace(dental_ofc_group_name,',',' '),' ',' ') as mm
                    ,replace(replace(dental_ofc_loc_addr_1,',',' '),' ',' ') as nn
                    ,replace(replace(dental_ofc_loc_addr_2,',',' '),' ',' ') as oo
                    ,replace(replace(dental_ofc_loc_city,',',' '),' ',' ') as pp
                    ,replace(replace(dental_ofc_loc_zip_county_name,',',' '),' ',' ') as qq
                    ,replace(replace(dental_ofc_loc_state_code,',',' '),' ',' ') as rr
                    ,replace(replace(dental_ofc_loc_zip_code,',',' '),' ',' ') as ss
                    ,replace(replace(dental_ofc_loc_zip_plus_4,',',' '),' ',' ') as tt
                    ,dental_ofc_phone_num as uu
                    ,dental_ofc_elec_remit_flag as vv
                    ,nvl(rpad(dental_ofc_foreign_lang_string,50,' '),'') as ww
                    ,dental_ofc_handicap_accss_flag as xx
                    ,replace(replace(dental_ofc_pmt_addr_1,',',' '),' ',' ') as yy
                    ,replace(replace(dental_ofc_pmt_addr_2,',',' '),' ',' ') as zz
                    ,replace(replace(dental_ofc_pmt_city,',',' '),' ',' ') as aaa
                    ,replace(replace(dental_ofc_pmt_zip_county_name,',',' '),' ',' ') as bbb
                    ,replace(replace(dental_ofc_pmt_name,',',' '),' ',' ') as ccc
                    ,replace(replace(dental_ofc_pmt_state_code,',',' '),' ',' ') as ddd
                    ,replace(replace(dental_ofc_pmt_zip_code,',',' '),' ',' ') as eee
                    ,replace(replace(dental_ofc_pmt_zip_plus_4,',',' '),' ',' ') as fff
                    ,replace(replace(geo_area_code,',',' '),' ',' ') as ggg
                    ,DECODE(full_feed_flag_wr,'Y','A',last_action_ind) as hhh
            from    EXT_DICE_PROV_DEMOGRAPHIC_FEED
            where   (full_feed_flag_wr = 'Y' OR (z_update_tmstmp between last_run_tmstmp_wr and process_start_tmstmp_wr))
            and     (full_feed_flag_wr = 'N' OR last_action_ind !='D')
      ;
    begin

        out_file := utl_file.fopen(output_dir_wr,out_filename,'w');

        --write header record
        utl_file.put(out_file, header_record);

        --write detail records
        for detail_record in recordset
        loop
            detail_record :=
                a || ',' ||
                b || ',' ||
                c || ',' ||
                d || ',' ||
                e || ',' ||
                f || ',' ||
                g || ',' ||
                h || ',' ||
                i || ',' ||
                g || ',' ||
                k || ',' ||
                l || ',' ||
                m || ',' ||
                n || ',' ||
                o || ',' ||
                p || ',' ||
                q || ',' ||
                r || ',' ||
                s || ',' ||
                t || ',' ||
                u || ',' ||
                v || ',' ||
                w || ',' ||
                x || ',' ||
                y || ',' ||
                z || ',' ||
                aa || ',' ||
                bb || ',' ||
                cc || ',' ||
                kk || ',' ||
                ll || ',' ||
                mm || ',' ||
                nn || ',' ||
                oo || ',' ||
                pp || ',' ||
                qq || ',' ||
                rr || ',' ||
                ss || ',' ||
                tt || ',' ||
                uu || ',' ||
                vv || ',' ||
                ww || ',' ||
                xx || ',' ||
                yy || ',' ||
                zz || ',' ||
                aaa || ',' ||
                bbb || ',' ||
                ccc || ',' ||
                ddd || ',' ||
                eee || ',' ||
                fff || ',' ||
                ggg || ',' ||
                hhh || ',' ||
        utl_file.put_line (out_file, detail_record);
        END LOOP;

        --write trailer record
        select  count(*)
        into    linecnt
        from    EXT_DICE_PROV_DEMOGRAPHIC_FEED
        where   (full_feed_flag_wr = 'Y' OR (z_update_tmstmp between last_run_tmstmp_wr and process_start_tmstmp_wr))
        and     (full_feed_flag_wr = 'N' OR last_action_ind !='D');

        trailer_record := 'T, ' || linecnt;
        utl_file.put_line(out_file,trailer_record);

        --close file
        utl_file.fclose(out_file);

    end write_records;

    procedure create_output_file(
        full_feed_flag in char,
        last_run_tmstmp in date,
        process_start_tmstmp in date,
        output_dir in varchar2
        )
    is
        l_user_err_message  varchar2(40);
        process_status_code varchar2(5);
    begin
        l_user_err_message  := 'Brighter Provider Feed started...';
        process_status_code := 'M';
        linecnt := 0;
        create_appl_process_log(l_user_err_message, process_status_code, linecnt);

        write_records(full_feed_flag,last_run_tmstmp,process_start_tmstmp, output_dir);

        l_user_err_message  := 'Brighter Provider Feed Completed';
        process_status_code := 'M';
        create_appl_process_log(l_user_err_message, process_status_code, linecnt);
    end create_output_file;

end dm_mnmi2407_pkg;
/
show errors;
</code>```

答:
This bit doesn't look right, are you really trying to redefine your cursor iterator value?

```<code>...
    --write detail records
    for detail_record in recordset
    loop
        detail_record :=
            a || ',' ||
            b || ',' ||
            c || ',' ||
...
</code>```

I'm guessing that you really want something more like

```<code>procedure write_records ...
is
  detail_record varchar2(32000);
  ...
begin
  ...
  --write detail records
  for dr in in recordset loop
    detail_record := dr.a || ',' || dr.b || ',' ....
</code>```

Body:
i can't compile this package body because i get "looping chain of synonyms"

i don't even reference any synonyms

i have checked the table dba_synonyms, there is nothing referencing the table in the select from

to be more specific, when i comment out the cursor select portion, it compiles fine

if you notice below, i am again selecting from the same table, only for count(*), this select works fine, but not the previous one

this is on oracle 12c

create or replace
package body dm_mnmi2407_pkg
is
    procedure create_appl_process_log(
        l_user_err_message_capl in varchar2,
        process_status_code_capl in varchar2,
        linecnt_capl in int
    )
    is
        l_action_taken      varchar2(50) := 'DICE Provider Demographic Feed To BRIGHTER';
        l_module_name       varchar2(20) := 'dm_mnmi2407.sqr';
        l_p_key             int := 1;
        l_p_error           char := ' ';
    begin
        dm_common_pkg.application_process_log(  l_action_taken,
                                                l_module_name,
                                                process_status_code_capl,
                                                NULL,
                                                NULL,
                                                l_user_err_message_capl,
                                                linecnt_capl,
                                                NULL,
                                                NULL,
                                                l_p_key,
                                                l_p_error
                                            );
    end create_appl_process_log;

    procedure write_records(
        full_feed_flag_wr in char,
        last_run_tmstmp_wr in date,
        process_start_tmstmp_wr in date,
        output_dir_wr in varchar2
        )
    is
        out_file        utl_file.file_type;
        out_filename    varchar2(70) := 'cdhprovdem' || '_' || process_start_tmstmp_wr ||'.dat';
        header_record   varchar2(20) := 'H, ' || process_start_tmstmp_wr;
        trailer_record  varchar2(20);

        cursor recordset is
            select  prov_donas_id as a
                    ,replace(replace(prov_id,',',' '),' ',' ') as b
                    ,lpad(prov_type1_npi,10,'0') as c
                    ,to_char(prov_eff_date,'YYYYMMDD') as d
                    ,replace(replace(prov_fee_sched,',',' '),' ',' ') as e
                    ,dppo_advantage_network_ind as f
                    ,donas_primary_fee_sched_ind as g
                    ,to_char(prov_fee_sched_eff_date,'YYYYMMDD') as h
                    ,to_char(prov_fee_sched_inactive_date,'YYYYMMDD') as i
                    ,to_char(prov_inactive_date,'YYYYMMDD') as j
                    ,prov_type as k
                    ,replace(replace(prov_title_code,',',' '),' ',' ') as l
                    ,replace(replace(prov_first_name,',',' '),' ',' ') as m
                    ,replace(replace(prov_middle_initial,',',' '),' ',' ') as n
                    ,replace(replace(prov_last_name,',',' '),' ',' ') as o
                    ,replace(replace(prov_speclty_code,',',' '),' ',' ') as p
                    ,prov_board_cert_speclty_flag as q
                    ,Prov_board_elig_speclty_flag as r
                    ,prov_donas_license_num as s
                    ,replace(replace(prov_donas_license_state_code,',',' '),' ',' ') as t
                    ,to_char(prov_experience_start_date,'YYYYMMDD') as u
                    ,to_char(prov_birth_date,'YYYYMMDD') as v
                    ,nvl(rpad(prov_foreign_lang_string,50,' '),'') as w
                    ,prov_gender as x
                    ,replace(replace(prov_dental_school_name,',',' '),' ',' ') as y
                    ,prov_primary_license_num as z
                    ,replace(replace(prov_primary_license_state_cd,',',' '),' ',' ') as aa
                    ,prov_accepting_new_pats_flag as bb
                    ,rpad(lpad(prov_type2_npi_1,10,'0')||' '||lpad(prov_type2_npi_2,10,'0')||' '|| lpad(prov_type2_npi_3,10,'0')||' '||lpad(prov_type2_npi_4,10,'0')||' '|| lpad(prov_type2_npi_5,10,'0')||' '||lpad(prov_type2_npi_6,10,'0')||' '|| lpad(prov_type2_npi_7,10,'0')||' '||lpad(prov_type2_npi_8,10,'0')||' '|| lpad(prov_type2_npi_9,10,'0')||' '||lpad(prov_type2_npi_10,10,'0')||' '|| lpad(prov_type2_npi_11,10,'0')||' '||lpad(prov_type2_npi_12,10,'0')||' '|| lpad(prov_type2_npi_13,10,'0')||' '||lpad(prov_type2_npi_14,10,'0')||' '|| lpad(prov_type2_npi_15,10,'0'),164,' ') as cc
                    ,dental_ofc_id as kk
                    ,lpad(replace(replace(dental_ofc_tax_id,',',' '),' ',' '),9,'0') as ll
                    ,replace(replace(dental_ofc_group_name,',',' '),' ',' ') as mm
                    ,replace(replace(dental_ofc_loc_addr_1,',',' '),' ',' ') as nn
                    ,replace(replace(dental_ofc_loc_addr_2,',',' '),' ',' ') as oo
                    ,replace(replace(dental_ofc_loc_city,',',' '),' ',' ') as pp
                    ,replace(replace(dental_ofc_loc_zip_county_name,',',' '),' ',' ') as qq
                    ,replace(replace(dental_ofc_loc_state_code,',',' '),' ',' ') as rr
                    ,replace(replace(dental_ofc_loc_zip_code,',',' '),' ',' ') as ss
                    ,replace(replace(dental_ofc_loc_zip_plus_4,',',' '),' ',' ') as tt
                    ,dental_ofc_phone_num as uu
                    ,dental_ofc_elec_remit_flag as vv
                    ,nvl(rpad(dental_ofc_foreign_lang_string,50,' '),'') as ww
                    ,dental_ofc_handicap_accss_flag as xx
                    ,replace(replace(dental_ofc_pmt_addr_1,',',' '),' ',' ') as yy
                    ,replace(replace(dental_ofc_pmt_addr_2,',',' '),' ',' ') as zz
                    ,replace(replace(dental_ofc_pmt_city,',',' '),' ',' ') as aaa
                    ,replace(replace(dental_ofc_pmt_zip_county_name,',',' '),' ',' ') as bbb
                    ,replace(replace(dental_ofc_pmt_name,',',' '),' ',' ') as ccc
                    ,replace(replace(dental_ofc_pmt_state_code,',',' '),' ',' ') as ddd
                    ,replace(replace(dental_ofc_pmt_zip_code,',',' '),' ',' ') as eee
                    ,replace(replace(dental_ofc_pmt_zip_plus_4,',',' '),' ',' ') as fff
                    ,replace(replace(geo_area_code,',',' '),' ',' ') as ggg
                    ,DECODE(full_feed_flag_wr,'Y','A',last_action_ind) as hhh
            from    EXT_DICE_PROV_DEMOGRAPHIC_FEED
            where   (full_feed_flag_wr = 'Y' OR (z_update_tmstmp between last_run_tmstmp_wr and process_start_tmstmp_wr))
            and     (full_feed_flag_wr = 'N' OR last_action_ind !='D')
      ;
    begin

        out_file := utl_file.fopen(output_dir_wr,out_filename,'w');

        --write header record
        utl_file.put(out_file, header_record);

        --write detail records
        for detail_record in recordset
        loop
            detail_record :=
                a || ',' ||
                b || ',' ||
                c || ',' ||
                d || ',' ||
                e || ',' ||
                f || ',' ||
                g || ',' ||
                h || ',' ||
                i || ',' ||
                g || ',' ||
                k || ',' ||
                l || ',' ||
                m || ',' ||
                n || ',' ||
                o || ',' ||
                p || ',' ||
                q || ',' ||
                r || ',' ||
                s || ',' ||
                t || ',' ||
                u || ',' ||
                v || ',' ||
                w || ',' ||
                x || ',' ||
                y || ',' ||
                z || ',' ||
                aa || ',' ||
                bb || ',' ||
                cc || ',' ||
                kk || ',' ||
                ll || ',' ||
                mm || ',' ||
                nn || ',' ||
                oo || ',' ||
                pp || ',' ||
                qq || ',' ||
                rr || ',' ||
                ss || ',' ||
                tt || ',' ||
                uu || ',' ||
                vv || ',' ||
                ww || ',' ||
                xx || ',' ||
                yy || ',' ||
                zz || ',' ||
                aaa || ',' ||
                bbb || ',' ||
                ccc || ',' ||
                ddd || ',' ||
                eee || ',' ||
                fff || ',' ||
                ggg || ',' ||
                hhh || ',' ||
        utl_file.put_line (out_file, detail_record);
        END LOOP;

        --write trailer record
        select  count(*)
        into    linecnt
        from    EXT_DICE_PROV_DEMOGRAPHIC_FEED
        where   (full_feed_flag_wr = 'Y' OR (z_update_tmstmp between last_run_tmstmp_wr and process_start_tmstmp_wr))
        and     (full_feed_flag_wr = 'N' OR last_action_ind !='D');

        trailer_record := 'T, ' || linecnt;
        utl_file.put_line(out_file,trailer_record);

        --close file
        utl_file.fclose(out_file);

    end write_records;

    procedure create_output_file(
        full_feed_flag in char,
        last_run_tmstmp in date,
        process_start_tmstmp in date,
        output_dir in varchar2
        )
    is
        l_user_err_message  varchar2(40);
        process_status_code varchar2(5);
    begin
        l_user_err_message  := 'Brighter Provider Feed started...';
        process_status_code := 'M';
        linecnt := 0;
        create_appl_process_log(l_user_err_message, process_status_code, linecnt);

        write_records(full_feed_flag,last_run_tmstmp,process_start_tmstmp, output_dir);

        l_user_err_message  := 'Brighter Provider Feed Completed';
        process_status_code := 'M';
        create_appl_process_log(l_user_err_message, process_status_code, linecnt);
    end create_output_file;

end dm_mnmi2407_pkg;
/
show errors;

Body:
This bit doesn't look right, are you really trying to redefine your cursor iterator value?

...
    --write detail records
    for detail_record in recordset
    loop
        detail_record :=
            a || ',' ||
            b || ',' ||
            c || ',' ||
...

I'm guessing that you really want something more like

procedure write_records ...
is
  detail_record varchar2(32000);
  ...
begin
  ...
  --write detail records
  for dr in in recordset loop
    detail_record := dr.a || ',' || dr.b || ',' ....


问:
ASP.NET MVC ViewResult vs PartialViewResult
What is the difference between the controller result named ViewResult and PartialViewResult? More importantly, when is the PartialViewResult used?

答:
http://msmvps.com/blogs/luisabreu/archive/2008/09/16/the-mvc-platform-action-result-views.aspx

In practice, you’ll use the
  PartialViewResult for outputing  a
  small part of a view. That’s why you
  don’t have the master page options
  when dealing with them. On the other
  hand, you’ll use the ViewResult for
  getting a “complete” view. As you
  might expect, the Controller class
  exposes several methods that will let
  you reduce the ammount of typing
  needed for instanting these types of
  action results.

Generally speaking, ViewResult is for rendering a page with optional master, and PartialViewResult is used for user controls (likely responding to an AJAX request).

OwnerDisplayName: Diego Deberdt

LastEditorDisplayName: Diego Deberdt

OwnerDisplayName: huey