问:
no viable alternative error in python with nifi executescript
I am scraping a page (e.g., facebook page ) using python script and want to pass on each post to be written to a file (something like gettwitter process). I am using Apache Nifi ExecuteScript processor to call the python script.

However, I am getting SyntaxError: no viable alternative at input

I can successfully transfer data between processors  but when I try to add the scrapping code I keep getting error. I am using python version 2.7.8. As I understand executeScript uses jython internally and jython can translate python code.

Below is the code which works fine with python  outside nifi if we remove the nifi related code (inner class and flow file).

```<code>import urllib2
import json
import datetime
import csv
import time
import sys
import traceback
from org.apache.nifi.processor.io import OutputStreamCallback
from org.python.core.util import StringUtil

class WriteContentCallback(OutputStreamCallback):
    def __init__(self, content):
        self.content_text = content

    def process(self, outputStream):
        try:
            outputStream.write(StringUtil.toBytes(self.content_text))
        except:
            traceback.print_exc(file=sys.stdout)
            raise

#app_id = "<FILL IN>"
#app_secret = "<FILL IN>" # DO NOT SHARE WITH ANYONE!
page_id = "dsssssss"
#page_id = raw_input("Please Paste Public Page Name:")

#access_token = app_id + "|" + app_secret

access_token = "sdfsdfsf%sdfsdf"

#access_token = raw_input("Please Paste Your Access Token:")

def scrapeFacebookPageFeedStatus(page_id, access_token):
    flowFile = session.create()
    flowFile = session.write(flowFile, WriteContentCallback("Hello there this is my data")
    #flowFile = session.write()
    #session.transfer(flowFile, REL_SUCCESS)

        has_next_page = False
        num_processed = 0   # keep a count on how many we've processed
        scrape_starttime = datetime.datetime.now()

        while has_next_page:
            print "Scraping %s Facebook Page: %s\n" % (page_id, scrape_starttime)
            has_next_page = False

        print "\nDone!\n%s Statuses Processed in %s" % \
                (num_processed, datetime.datetime.now() - scrape_starttime)

if __name__ == '__main__':
    #scrapeFacebookPageFeedStatus(page_id, access_token)
    flowFile = session.create()
    flowFile = session.write(flowFile, WriteContentCallback("Hello there this is my data")
    session.transfer(flowFile, REL_SUCCESS)
</code>```

Below is the full trace of the error

```<code>> 2017-04-02 16:19:22,817 ERROR [Timer-Driven Process Thread-10]
> o.a.nifi.processors.script.ExecuteScript
> ExecuteScript[id=a62f4b97-8fd7-15cd-95b9-505e1b960805]
> ExecuteScript[id=a62f4b97-8fd7-15cd-95b9-505e1b960805] failed to
> process due to org.apache.nifi.processor.exception.ProcessException:
> javax.script.ScriptException: SyntaxError: no viable alternative at
> input 'has_next_page' in <script> at line number 178 at column number
> 8; rolling back session:
> org.apache.nifi.processor.exception.ProcessException:
> javax.script.ScriptException: SyntaxError: no viable alternative at
> input 'has_next_page' in <script> at line number 178 at column number
> 8 2017-04-02 16:19:22,819 ERROR [Timer-Driven Process Thread-10]
> o.a.nifi.processors.script.ExecuteScript
> org.apache.nifi.processor.exception.ProcessException:
> javax.script.ScriptException: SyntaxError: no viable alternative at
> input 'has_next_page' in <script> at line number 178 at column number
> 8
>         at org.apache.nifi.processors.script.ExecuteScript.onTrigger(ExecuteScript.java:214)
> ~[nifi-scripting-processors-1.1.0.2.1.1.0-2.jar:1.1.0.2.1.1.0-2]
>         at org.apache.nifi.controller.StandardProcessorNode.onTrigger(StandardProcessorNode.java:1099)
> [nifi-framework-core-1.1.0.2.1.1.0-2.jar:1.1.0.2.1.1.0-2]
>         at org.apache.nifi.controller.tasks.ContinuallyRunProcessorTask.call(ContinuallyRunProcessorTask.java:136)
> [nifi-framework-core-1.1.0.2.1.1.0-2.jar:1.1.0.2.1.1.0-2]
>         at org.apache.nifi.controller.tasks.ContinuallyRunProcessorTask.call(ContinuallyRunProcessorTask.java:47)
> [nifi-framework-core-1.1.0.2.1.1.0-2.jar:1.1.0.2.1.1.0-2]
>         at org.apache.nifi.controller.scheduling.TimerDrivenSchedulingAgent$1.run(TimerDrivenSchedulingAgent.java:132)
> [nifi-framework-core-1.1.0.2.1.1.0-2.jar:1.1.0.2.1.1.0-2]
>         at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511)
> [na:1.8.0_77]
>         at java.util.concurrent.FutureTask.runAndReset(FutureTask.java:308)
> [na:1.8.0_77]
>         at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.access$301(ScheduledThreadPoolExecutor.java:180)
> [na:1.8.0_77]
>         at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.run(ScheduledThreadPoolExecutor.java:294)
> [na:1.8.0_77]
>         at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
> [na:1.8.0_77]
>         at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
> [na:1.8.0_77]
>         at java.lang.Thread.run(Thread.java:745) [na:1.8.0_77] Caused by: javax.script.ScriptException: SyntaxError: no viable alternative
> at input 'has_next_page' in <script> at line number 178 at column
> number 8
>         at org.python.jsr223.PyScriptEngine.scriptException(PyScriptEngine.java:190)
> ~[jython-standalone-2.7.0.jar:na]
>         at org.python.jsr223.PyScriptEngine.compileScript(PyScriptEngine.java:75)
> ~[jython-standalone-2.7.0.jar:na]
>         at org.python.jsr223.PyScriptEngine.eval(PyScriptEngine.java:31)
> ~[jython-standalone-2.7.0.jar:na]
>         at javax.script.AbstractScriptEngine.eval(AbstractScriptEngine.java:264)
> ~[na:1.8.0_77]
>         at org.apache.nifi.processors.script.impl.JythonScriptEngineConfigurator.eval(JythonScriptEngineConfigurator.java:59)
> ~[nifi-scripting-processors-1.1.0.2.1.1.0-2.jar:1.1.0.2.1.1.0-2]
>         at org.apache.nifi.processors.script.ExecuteScript.onTrigger(ExecuteScript.java:204)
> ~[nifi-scripting-processors-1.1.0.2.1.1.0-2.jar:1.1.0.2.1.1.0-2]
>         ... 11 common frames omitted Caused by: org.python.core.PySyntaxError: null
>         at org.python.core.ParserFacade.fixParseError(ParserFacade.java:95)
> ~[jython-standalone-2.7.0.jar:na]
>         at org.python.core.ParserFacade.parseExpressionOrModule(ParserFacade.java:136)
> ~[jython-standalone-2.7.0.jar:na]
>         at org.python.util.PythonInterpreter.compile(PythonInterpreter.java:320)
> ~[jython-standalone-2.7.0.jar:na]
>         at org.python.util.PythonInterpreter.compile(PythonInterpreter.java:316)
> ~[jython-standalone-2.7.0.jar:na]
>         at org.python.util.PythonInterpreter.compile(PythonInterpreter.java:308)
> ~[jython-standalone-2.7.0.jar:na]
>         at org.python.jsr223.PyScriptEngine.compileScript(PyScriptEngine.java:70)
> ~[jython-standalone-2.7.0.jar:na]
>         ... 15 common frames omitted
</code>```

Appreciate your guidance. Thanks.

答:
From the source code it appears you are missing a closing parenthesis on the following line:

```<code>flowFile = session.write(flowFile, WriteContentCallback("Hello there this is my data")
</code>```

If you are still getting errors after that, it is likely that one of the imported modules contains (or depends on) native (CPython) modules rather than pure Python. The former is not supported in Jython, imported modules must be pure Python code. See this related SO post for more details.

Body:
I am scraping a page (e.g., facebook page ) using python script and want to pass on each post to be written to a file (something like gettwitter process). I am using Apache Nifi ExecuteScript processor to call the python script.

However, I am getting SyntaxError: no viable alternative at input

I can successfully transfer data between processors  but when I try to add the scrapping code I keep getting error. I am using python version 2.7.8. As I understand executeScript uses jython internally and jython can translate python code.

Below is the code which works fine with python  outside nifi if we remove the nifi related code (inner class and flow file).

import urllib2
import json
import datetime
import csv
import time
import sys
import traceback
from org.apache.nifi.processor.io import OutputStreamCallback
from org.python.core.util import StringUtil

class WriteContentCallback(OutputStreamCallback):
    def __init__(self, content):
        self.content_text = content

    def process(self, outputStream):
        try:
            outputStream.write(StringUtil.toBytes(self.content_text))
        except:
            traceback.print_exc(file=sys.stdout)
            raise

#app_id = "<FILL IN>"
#app_secret = "<FILL IN>" # DO NOT SHARE WITH ANYONE!
page_id = "dsssssss"
#page_id = raw_input("Please Paste Public Page Name:")

#access_token = app_id + "|" + app_secret

access_token = "sdfsdfsf%sdfsdf"

#access_token = raw_input("Please Paste Your Access Token:")

def scrapeFacebookPageFeedStatus(page_id, access_token):
    flowFile = session.create()
    flowFile = session.write(flowFile, WriteContentCallback("Hello there this is my data")
    #flowFile = session.write()
    #session.transfer(flowFile, REL_SUCCESS)

        has_next_page = False
        num_processed = 0   # keep a count on how many we've processed
        scrape_starttime = datetime.datetime.now()

        while has_next_page:
            print "Scraping %s Facebook Page: %s\n" % (page_id, scrape_starttime)
            has_next_page = False

        print "\nDone!\n%s Statuses Processed in %s" % \
                (num_processed, datetime.datetime.now() - scrape_starttime)

if __name__ == '__main__':
    #scrapeFacebookPageFeedStatus(page_id, access_token)
    flowFile = session.create()
    flowFile = session.write(flowFile, WriteContentCallback("Hello there this is my data")
    session.transfer(flowFile, REL_SUCCESS)

Below is the full trace of the error

> 2017-04-02 16:19:22,817 ERROR [Timer-Driven Process Thread-10]
> o.a.nifi.processors.script.ExecuteScript
> ExecuteScript[id=a62f4b97-8fd7-15cd-95b9-505e1b960805]
> ExecuteScript[id=a62f4b97-8fd7-15cd-95b9-505e1b960805] failed to
> process due to org.apache.nifi.processor.exception.ProcessException:
> javax.script.ScriptException: SyntaxError: no viable alternative at
> input 'has_next_page' in

Body:
From the source code it appears you are missing a closing parenthesis on the following line:

flowFile = session.write(flowFile, WriteContentCallback("Hello there this is my data")

If you are still getting errors after that, it is likely that one of the imported modules contains (or depends on) native (CPython) modules rather than pure Python. The former is not supported in Jython, imported modules must be pure Python code. See this related SO post for more details.


来源: stackexchange

问:
PHP Search multidimensional array for value & get corresponding element value
I am using PHP & I have a multi dimensional array which I need to search to see if the value of a "key" exists and if it does then get the value of the "field". Here's my array:

```<code>Array
(
    [0] => Array
    (
        [key] => 31
        [field] => CONSTRUCTN
        [value] => LFD_CONSTRUCTION_2
    )
    [1] => Array
    (
        [key] => 32
        [field] => COOLING
        value] => LFD_COOLING_1
    )
)
</code>```

I want to be able to search the array for the "key" value of 31. If it exists, then I want to be able to extract the corresponding "field" value of "CONSTRUCTN".

I've tried using array_search(31, $myArray) but it does not work...

答:
```<code>function searchMultiArray($val, $array) {
  foreach ($array as $element) {
    if ($element['key'] == $val) {
      return $element['field'];
    }
  }
  return null;
}
</code>```

And then:

```<code>searchMultiArray(31, $myArray);
</code>```

Should return "CONSTRUCTN".

ContentLicense: CC BY-SA 3.0

Body:
I am using PHP & I have a multi dimensional array which I need to search to see if the value of a "key" exists and if it does then get the value of the "field". Here's my array:

Array
(
    [0] => Array
    (
        [key] => 31
        [field] => CONSTRUCTN
        [value] => LFD_CONSTRUCTION_2
    )
    [1] => Array
    (
        [key] => 32
        [field] => COOLING
        value] => LFD_COOLING_1
    )
)

I want to be able to search the array for the "key" value of 31. If it exists, then I want to be able to extract the corresponding "field" value of "CONSTRUCTN".

I've tried using array_search(31, $myArray) but it does not work...

Body:
function searchMultiArray($val, $array) {
  foreach ($array as $element) {
    if ($element['key'] == $val) {
      return $element['field'];
    }
  }
  return null;
}

And then:

searchMultiArray(31, $myArray);

Should return "CONSTRUCTN".


问:
How to check if User Input is present in CSV Python
I am trying create a program that will ask for user input for a city and gender and Test their input to make sure it is valid and corresponds to values within the a CSV that has city name and different gender population.

How do I check if the userinput for both gender and city name are within the csv file. I want to create it in the way that the if the user does not put a valid year or gender. it will tell the user to choose a different city and or year.

Here is what the CSV looks like:

```<code>name,gen_male,gen_female
Tokyo,5000,4500
San_Francsico,400,500
Manila,600,700
New_York,8000,9000
Paris,5600,5600
Chicago,500,6000
</code>```

Can anyone help me to figure out a way to check user input if a given value is within the csv file.

Here is my script:

```<code>import csv

with open('C:/Users/PycharmProjects/CityGen.csv') as csvfile:
    reader = csv.DictReader(csvfile)
    city = raw_input('Which city?:')
    gender = raw_input('What gender?:')
    yearPop = 'gen_' + year

    try:
        for row in reader:
            if row['name'] == city:
                print row[yearPop]
    except ValueError:
        print 'incorrect value'
</code>```

答:
I would first read the csv file and save it into a dictionary with the city name as key and the value is a tuple (or maybe a named tuple?) tuple[0] is gen_male, and tuple[1] is gen_female. Then ask the user to input city's name, look it up in the dictionary, if its there, then ask him to input the gender and check if its valid for that city.</p>

```<code>with open('C:/Users/PycharmProjects/CityGen.csv') as csvfile:
    reader = csv.DictReader(csvfile)
    dictionary = {}

    for row in reader:
        city = row[0]
        genders = tuple(row[1:])
        dict1 = {city: genders}
        dictionary.update(dict1)

    city = raw_input('Which city?:')
    if city in dictionary:
        gender = raw_input('What gender?:')
        if gender in dictionary[city]:
            # gender and city are valid
        else:
            # gender is not valid
    else:
        # city is not valid
</code>```

Body:
I am trying create a program that will ask for user input for a city and gender and Test their input to make sure it is valid and corresponds to values within the a CSV that has city name and different gender population.

How do I check if the userinput for both gender and city name are within the csv file. I want to create it in the way that the if the user does not put a valid year or gender. it will tell the user to choose a different city and or year.

Here is what the CSV looks like:

name,gen_male,gen_female
Tokyo,5000,4500
San_Francsico,400,500
Manila,600,700
New_York,8000,9000
Paris,5600,5600
Chicago,500,6000

Can anyone help me to figure out a way to check user input if a given value is within the csv file.

Here is my script:

import csv

with open('C:/Users/PycharmProjects/CityGen.csv') as csvfile:
    reader = csv.DictReader(csvfile)
    city = raw_input('Which city?:')
    gender = raw_input('What gender?:')
    yearPop = 'gen_' + year

    try:
        for row in reader:
            if row['name'] == city:
                print row[yearPop]
    except ValueError:
        print 'incorrect value'

Body:
I would first read the csv file and save it into a dictionary with the city name as key and the value is a tuple (or maybe a named tuple?) tuple[0] is gen_male, and tuple[1] is gen_female. Then ask the user to input city's name, look it up in the dictionary, if its there, then ask him to input the gender and check if its valid for that city.

with open('C:/Users/PycharmProjects/CityGen.csv') as csvfile:
    reader = csv.DictReader(csvfile)
    dictionary = {}

    for row in reader:
        city = row[0]
        genders = tuple(row[1:])
        dict1 = {city: genders}
        dictionary.update(dict1)

    city = raw_input('Which city?:')
    if city in dictionary:
        gender = raw_input('What gender?:')
        if gender in dictionary[city]:
            # gender and city are valid
        else:
            # gender is not valid
    else:
        # city is not valid


问:
Child height in SplitLayoutPanel
I've got a SplitLayoutPanel. In the North cell, I've got a ScrollPanel
with a tree on it.
I want this ScrollPanel height to be the same of the north cell, so
when the tree expand, a scroll appears. The size of this ScrollPanel
must changed when the north cell is resized.
I've tried with RequireResizes but parent does not send size
information... An ideal approach should be that ProvidesSize widgets call onResize method with available size for the RequiresSize widget children

I'm very confused. How to configure SplitLayoutPanel to have cell
children resized ?

Thanks

答:
Create a class that extends Composite and implement RequiresResize; like so:

```<code>public class MyScrollPanel extends Composite implements RequiresResize {
 private ScrollPanel scrollPanel;

 public MyScrollPanel() {
  scrollPanel = new ScrollPanel();
  initWidget(scrollPanel);
 }

 public void onResize() {
  // do something to your scrollpanel
 }

}
</code>```

Then add MyScrollPanel to the north cell in your SplitLayoutPanel.

EDIT

 However. It turns out ScrollPanel already has the desired behavior by default. A ScrollPanel added to a SplitLayoutPanel cell will automatically fill the size of the cell, even on resize. And any ScrollPanel child widget larger than available space will cause a scrollbar to appear.

But make sure you're adding the SplitLayoutPanel to the RootLayoutPanel by doing
RootLayoutPanel.get().add(splitLayoutPanel);

ContentLicense: CC BY-SA 2.5

Title: Child height in SplitLayoutPanel

Body:
Create a class that extends Composite and implement RequiresResize; like so:

public class MyScrollPanel extends Composite implements RequiresResize {
 private ScrollPanel scrollPanel;

 public MyScrollPanel() {
  scrollPanel = new ScrollPanel();
  initWidget(scrollPanel);
 }

 public void onResize() {
  // do something to your scrollpanel
 }

}

Then add MyScrollPanel to the north cell in your SplitLayoutPanel.

EDIT

 However. It turns out ScrollPanel already has the desired behavior by default. A ScrollPanel added to a SplitLayoutPanel cell will automatically fill the size of the cell, even on resize. And any ScrollPanel child widget larger than available space will cause a scrollbar to appear.

But make sure you're adding the SplitLayoutPanel to the RootLayoutPanel by doing
RootLayoutPanel.get().add(splitLayoutPanel);


问:
making all input fields borders red when no one at least was filled in
I am not good enough with javascript. Simply I have a form with some input fields. The user has to fill in at least one of them. I had already found the right code to do this. This code tells the user there is an error using an alert message. But I want to make all input fields borders red instead of this alert message using the same code.

HTML

```<code><form  id="myform" action="" method="post">
    <input name="destination" class="form-control" type="text" >
    <input name="thingstodo" class="form-control" type="text">
    <input name="gsearch" class="form-control" type="text">
    <button type="submit" name="search">Search</button>
</form>
</code>```

JavaScript

```<code>$(function(){
  $("#myform").submit(function(){

    var valid=0;
    $(this).find('input[type=text]').each(function(){
        if($(this).val() != "") valid+=1;
    });

    if(valid){
        return true;
    }
    else {
        alert("error: you must fill in at least one field");
        return false;
    }
  });
});
</code>```

Thanks

答:
You can do it by setting the CSS style. This is done most easily with jQuery syntax.</p>

```<code>$(function(){
  $("#myform").submit(function(){

    var valid = 0;
    $(this).find('input[type=text]').each(function(){
      if($(this).val() != "") {
        valid++;
        $(this).css("border-color", "initial");
      }
      else {
        $(this).css("border-color", "red");
      }
    });

    if (valid > 0) { return true; }
    else { return false; }
  });
});
</code>```

Body:
I am not good enough with javascript. Simply I have a form with some input fields. The user has to fill in at least one of them. I had already found the right code to do this. This code tells the user there is an error using an alert message. But I want to make all input fields borders red instead of this alert message using the same code.

HTML

<form  id="myform" action="" method="post">
    <input name="destination" class="form-control" type="text" >
    <input name="thingstodo" class="form-control" type="text">
    <input name="gsearch" class="form-control" type="text">
    <button type="submit" name="search">Search</button>
</form>

JavaScript

$(function(){
  $("#myform").submit(function(){

    var valid=0;
    $(this).find('input[type=text]').each(function(){
        if($(this).val() != "") valid+=1;
    });

    if(valid){
        return true;
    }
    else {
        alert("error: you must fill in at least one field");
        return false;
    }
  });
});

Thanks

Body:
You can do it by setting the CSS style. This is done most easily with jQuery syntax.

$(function(){
  $("#myform").submit(function(){

    var valid = 0;
    $(this).find('input[type=text]').each(function(){
      if($(this).val() != "") {
        valid++;
        $(this).css("border-color", "initial");
      }
      else {
        $(this).css("border-color", "red");
      }
    });

    if (valid > 0) { return true; }
    else { return false; }
  });
});


问:
Use of Casting on a parameter
IFrame it is an interface (That I should not modify) and Frame it is the extended class.

I need to use casting or instance of to reffer to use f as Frame instead os IFrame.

How can I achieve this?

```<code>public class Frame implements IFrame{
    private int numRows;
    private char code[][];
@Override
   public void replace(IFrame f) {
        for (int i=0; i<numRows; i++){
            for (int o=0; o<numRows; o++){

               (Frame f).code[i][o] = this.code[i][o];

                }
            }
        }
    }
</code>```

答:
You need another set of parantheses for the cast:

```<code>public void replace(IFrame f) {
    for (int i = 0; i < numRows; i++) {
        for (int o = 0; o < numRows; o++) {
            ((Frame) f).code[i][o] = this.code[i][o];
        }
    }
}
</code>```

It is also advisable to verify the runtime type of the parameter in the very first statement of the method, and react appropriately, e.g.:

```<code>    if (!(f instanceof Frame))
        throw new IllegalArgumentException("Need an instance of Frame. Got an instance of " + f.getClass().getName() + ".");
</code>```

A performance optimized verison of the array copying can be achieved by using System.arraycopy:

```<code>for (int i = 0; i < numRows; i++) {
    System.arraycopy(this.code[i], 0, ((Frame) f).code[i], 0, numRows);
}
</code>```

Title: Use of Casting on a parameter

Body:
IFrame it is an interface (That I should not modify) and Frame it is the extended class.

I need to use casting or instance of to reffer to use f as Frame instead os IFrame.

How can I achieve this?

public class Frame implements IFrame{
    private int numRows;
    private char code[][];
@Override
   public void replace(IFrame f) {
        for (int i=0; i<numRows; i++){
            for (int o=0; o<numRows; o++){

               (Frame f).code[i][o] = this.code[i][o];

                }
            }
        }
    }

Body:
You need another set of parantheses for the cast:

public void replace(IFrame f) {
    for (int i = 0; i < numRows; i++) {
        for (int o = 0; o < numRows; o++) {
            ((Frame) f).code[i][o] = this.code[i][o];
        }
    }
}

It is also advisable to verify the runtime type of the parameter in the very first statement of the method, and react appropriately, e.g.:

    if (!(f instanceof Frame))
        throw new IllegalArgumentException("Need an instance of Frame. Got an instance of " + f.getClass().getName() + ".");

A performance optimized verison of the array copying can be achieved by using System.arraycopy:

for (int i = 0; i < numRows; i++) {
    System.arraycopy(this.code[i], 0, ((Frame) f).code[i], 0, numRows);
}


问:
Spring setter dependency injection and immutable object
We know that spring team suggests using setter injection over field injection:

http://docs.spring.io/spring/docs/3.1.x/spring-framework-reference/html/beans.html#d0e2778

Which is what also needed to do unit testing by injecting mock.

However, one thing really is bothering me is that as the spring beans are singletons, so if in some part of the code, the singleton beans are reconfigured by injecting different dependency using the setter methods, then other parts of the code are going to be affected which might be unwanted. For instance, in some part of the code a particular clock instance is injected but may be that particular kind of clock is undesirable in other parts of the code.

So it looks like setter injection leaves some door open for risky business. At the same time we need to a mechanism to inject some mock during testing. How can we strike a balance?

Besides as we know that mutable objects are undesirable:

http://www.javapractices.com/topic/TopicAction.do?Id=15

Then is it not bad to use setter methods available for singleton beans?

答:
Sounds a bit confusing here, on one hand you say:

unit testing by injecting mock

Here you could use use Mockito or a standard JUnit test to create your instance and inject the appropriate dependencies.

But then you go on to say:

other parts of the code are going to be affected which might be unwanted

Not quite unit testing, but you can use Spring Test support with @DirtiesContext to ensure that if you change the dependencies in one test, then the context will get reloaded for the next test.

Should you really need to change an instance field but don't have a setter, as a last resort you can still use ReflectionTestUtils to update the field during the test.


问:
The best way to load several csv files as a single data set
I have a folder with many csv files with the same format (same table structure but different data). I want to have all of the data from these csv files as a single data set inside my SSIS package. My current solution is this: Create a helping table in SQL Server and use a For Each Container to load all the files into the table. Then load this table as the single data set you want in the SSIS package.

However, I would highly prefer a method that does not depend on creating such an extra table in my SQL Server. I was thinking that there might be a better way of doing this using C# and Script component. Does anybody has any suggestions?

答:
How about:

```<code>var allCsv = Directory.EnumerateFiles("Src-Path", ".*csv", SearchOption.TopDirectoryOnly);
string[] header = { File.ReadLines(allCsv.First()).First(l => !string.IsNullOrWhiteSpace(l)) };
var mergedData = allCsv
    .SelectMany(csv => File.ReadLines(csv)
        .SkipWhile(l => string.IsNullOrWhiteSpace(l)).Skip(1)); // skip header of each file
File.WriteAllLines("Dest-Path", header.Concat(mergedData));
</code>```

Just note that you have to add using  System.Linq;

Body:
How about:

var allCsv = Directory.EnumerateFiles("Src-Path", ".*csv", SearchOption.TopDirectoryOnly);
string[] header = { File.ReadLines(allCsv.First()).First(l => !string.IsNullOrWhiteSpace(l)) };
var mergedData = allCsv
    .SelectMany(csv => File.ReadLines(csv)
        .SkipWhile(l => string.IsNullOrWhiteSpace(l)).Skip(1)); // skip header of each file
File.WriteAllLines("Dest-Path", header.Concat(mergedData));

Just note that you have to add using  System.Linq;


问:
MATLAB Error: Maximum Variable Size Allowed on the Device Is Exceeded
I am trying to train a CNN model using 3 classes and around 500 images in each class. The size of the images are [965*995*1]. When I run the code I get an error saying "Maximum variable size allowed on the device is exceeded."

The model gives an error "Out of memory on device. To view more detail about available memory on the GPU, use 'gpuDevice()'.If the problem persists, reset the GPU by calling 'gpuDevice(1)"when I resize the images to [128 *128].

It runs fine when I resize the images to [64*64].

How can I go around this issue?

Note: The system has 16GB of RAM.

答:
First, you are probably limited by the size of RAM of your GPU and not your CPU.

So if you need to process large images set ConvNet to run on the CPU instead of the GPU.

In general in the latest MATLAB releases MathWorks added the option to define a limitation on Variable size as a function of the RAM.

You can access it by going:

Preferences -> Workspace

You will there the following:

 Workspace Settings">

You'll have the option to limit the size of variables according to your RAM.

In your case setting it to 100% means the largest (CPU) variable is 16GB.

If you uncheck the limit MATLAB will use the Page File for larger size variables.

Yet this is not recommended as you will be limited by the speed of your Hard Drive.

You can read more at Resolve "Out of Memory" Errors.

Body:
First, you are probably limited by the size of RAM of your GPU and not your CPU.

So if you need to process large images set ConvNet to run on the CPU instead of the GPU.

In general in the latest MATLAB releases MathWorks added the option to define a limitation on Variable size as a function of the RAM.

You can access it by going:

Preferences -> Workspace

You will there the following:

You'll have the option to limit the size of variables according to your RAM.

In your case setting it to 100% means the largest (CPU) variable is 16GB.

If you uncheck the limit MATLAB will use the Page File for larger size variables.

Yet this is not recommended as you will be limited by the speed of your Hard Drive.

You can read more at Resolve "Out of Memory" Errors.


问:
Full text search on a table
How to enable and perform a "full text" search on a table in SQL Server 2005?

I did not quite understand the solution in: How do I use full text search across multiple tables, SQL Server 2005

答: You can also have a look at http://msdn.microsoft.com/en-us/library/ms142583.aspx</p>

OwnerDisplayName: Nick

Title: Full text search on a table


问:
use GenericAPIView for different seriailizers based on different condition
Due to the use of different serializers based on certain condition, i preferred to use APIView and override get function. I was content with APIView but now that i need pagination feature, I am having trouble to make it happen. That is why i want to switch to GenericAPIView but due to the use of multiple serializer I have no idea how can i do it.

```<code>class ItemsAPIView(APIView):
    permission_classes = (permissions.IsAuthenticated,)
    pagination_class = api_settings.DEFAULT_PAGINATION_CLASS

    def get(self, request, format=None):
        """
        Return a list of all devices of this user.
        """
        reply = {}
        try:
            products = BaseItem.objects.owned_items().filter(owner=request.user)
            reply['data'] = OwnedItemSerializer(products, many=True).data

            items = BaseItem.objects.dev_items().filter(owner=request.user)
            reply['data'].extend(ItemSerializer(items, many=True).data)

        except:
            reply['data'] = []
        return Response(reply, status.HTTP_200_OK)
</code>```

UPDATE

Another way i tried is

```<code>class ItemsAPIView(APIView):
    permission_classes = (permissions.IsAuthenticated,)
    pagination_class = api_settings.DEFAULT_PAGINATION_CLASS

    def get(self, request, format=None):
        """
        Return a list of all items with product of this user.
        """
        reply = {}
        print ('request', request.META.get('REMOTE_ADDR'))
        try:
            products = BaseItem.objects.owned_items().filter(owner=request.user)
            reply['data'] = OwnedItemSerializer(products, many=True).data

            items = BaseItem.objects.dev_items().filter(owner=request.user)
            page = self.paginate_queryset(items)
            print ('page', page) # i always get None even when pass url as api/items?page=1
            if page is not None:
                reply['data'].extend(ItemSerializer(page, many=True).data)
            reply['data'].extend(ItemSerializer(items, many=True).data)

        except:
            reply['data'] = []
        return Response(reply, status.HTTP_200_OK)

    @property
    def paginator(self):
        """
        The paginator instance associated with the view, or `None`.
        """
        if not hasattr(self, '_paginator'):
            print (hasattr(self, '_paginator'))
            if self.pagination_class is None:
                self._paginator = None
            else:
                self._paginator = self.pagination_class()
        return self._paginator

    def paginate_queryset(self, queryset):
        """
        Return a single page of results, or `None` if pagination is disabled.
        """
        print ('queryset', queryset)
        if self.paginator is None:
            return None
        return self.paginator.paginate_queryset(queryset, self.request, view=self)

    def get_paginated_response(self, data):
        """
        Return a paginated style `Response` object for the given output data.
        """
        assert self.paginator is not None
        return self.paginator.get_paginated_response(data)
</code>```

No any way is working. Where have i done mistake?

答:
Do you really need two serializers ?

I think it may be a better choice to use a single Serializer with a custom to_representation:

```<code>class ItemSerializer(ModelSerializer):
   # Your fields

   def to_representation(self, instance):
       data = super(ItemSerializer, self).to_representation(instance)
       request = self.context.get('request')
       if request and instance.is_owned_by(request.user):
           return self.owner_to_representation(data, instance) # TO IMPLEMENT
       return data
</code>```

Then, you can use a generic view. Your code is cleaner, simpler and you do not have to worry about the pagination:

```<code>class ItemList(generics.ListAPIView):
    serializer_class = ItemSerializer
    permission_classes = (permissions.IsAuthenticated,)

    def get_queryset(self):
        return BaseItem.objects.owned_items()| BaseItem.objects.dev_items()
</code>```

Body:
Due to the use of different serializers based on certain condition, i preferred to use APIView and override get function. I was content with APIView but now that i need pagination feature, I am having trouble to make it happen. That is why i want to switch to GenericAPIView but due to the use of multiple serializer I have no idea how can i do it.

class ItemsAPIView(APIView):
    permission_classes = (permissions.IsAuthenticated,)
    pagination_class = api_settings.DEFAULT_PAGINATION_CLASS

    def get(self, request, format=None):
        """
        Return a list of all devices of this user.
        """
        reply = {}
        try:
            products = BaseItem.objects.owned_items().filter(owner=request.user)
            reply['data'] = OwnedItemSerializer(products, many=True).data

            items = BaseItem.objects.dev_items().filter(owner=request.user)
            reply['data'].extend(ItemSerializer(items, many=True).data)

        except:
            reply['data'] = []
        return Response(reply, status.HTTP_200_OK)

UPDATE

Another way i tried is

class ItemsAPIView(APIView):
    permission_classes = (permissions.IsAuthenticated,)
    pagination_class = api_settings.DEFAULT_PAGINATION_CLASS

    def get(self, request, format=None):
        """
        Return a list of all items with product of this user.
        """
        reply = {}
        print ('request', request.META.get('REMOTE_ADDR'))
        try:
            products = BaseItem.objects.owned_items().filter(owner=request.user)
            reply['data'] = OwnedItemSerializer(products, many=True).data

            items = BaseItem.objects.dev_items().filter(owner=request.user)
            page = self.paginate_queryset(items)
            print ('page', page) # i always get None even when pass url as api/items?page=1
            if page is not None:
                reply['data'].extend(ItemSerializer(page, many=True).data)
            reply['data'].extend(ItemSerializer(items, many=True).data)

        except:
            reply['data'] = []
        return Response(reply, status.HTTP_200_OK)

    @property
    def paginator(self):
        """
        The paginator instance associated with the view, or `None`.
        """
        if not hasattr(self, '_paginator'):
            print (hasattr(self, '_paginator'))
            if self.pagination_class is None:
                self._paginator = None
            else:
                self._paginator = self.pagination_class()
        return self._paginator

    def paginate_queryset(self, queryset):
        """
        Return a single page of results, or `None` if pagination is disabled.
        """
        print ('queryset', queryset)
        if self.paginator is None:
            return None
        return self.paginator.paginate_queryset(queryset, self.request, view=self)

    def get_paginated_response(self, data):
        """
        Return a paginated style `Response` object for the given output data.
        """
        assert self.paginator is not None
        return self.paginator.get_paginated_response(data)

No any way is working. Where have i done mistake?

Body:
Do you really need two serializers ?

I think it may be a better choice to use a single Serializer with a custom to_representation:

class ItemSerializer(ModelSerializer):
   # Your fields

   def to_representation(self, instance):
       data = super(ItemSerializer, self).to_representation(instance)
       request = self.context.get('request')
       if request and instance.is_owned_by(request.user):
           return self.owner_to_representation(data, instance) # TO IMPLEMENT
       return data

Then, you can use a generic view. Your code is cleaner, simpler and you do not have to worry about the pagination:

class ItemList(generics.ListAPIView):
    serializer_class = ItemSerializer
    permission_classes = (permissions.IsAuthenticated,)

    def get_queryset(self):
        return BaseItem.objects.owned_items()| BaseItem.objects.dev_items()


问:
Start firefox and close after few minutes with batch file
i have a small script that starts waits 60 seconds,starts firefox and runs a imacros script
but the problem is i want to close firefox after 60 seconds and start it again through loop.But what this script does is .It waits for me to close firefox.Then starts 60 seconds timer and then loops the script.

What i want to do is .It should not wait for me to close firefox and directly force closes firefox after 60 seconds and runs in loop

```<code>  @Echo off
:loop
cls
taskkill /f /im Firefox.exe
cls
taskkill /f /im crashreporter.exe
cls
timeout /T 60
    start ""
"C:\Program Files (x86)\Mozilla Firefox\firefox.exe" imacros://run/?m=l4lyt.iim
timeout /T 60
goto loop
</code>```

What am i doing wrong?why does it waits for me to close firefox instead of directly going to next line.
i.e

timeout /T 60

答:
You had the start command on a separate line from firefox.exe, therefore it launched a command prompt window and then called firefox.exe instead of executing it.

Additionally you don't need to use cls to clear the screen, instead use >nul 2>&1 to suppress output from the taskkill command(s)

Updated script:

```<code>@echo off
    start "" "C:\Program Files (x86)\Mozilla Firefox\firefox.exe" imacros://run/?m=l4lyt.iim
    timeout /T 60
    taskkill /f /t /im Firefox.exe /im crashreporter.exe >nul 2>&1
%0
</code>```

Body:
i have a small script that starts waits 60 seconds,starts firefox and runs a imacros script
but the problem is i want to close firefox after 60 seconds and start it again through loop.But what this script does is .It waits for me to close firefox.Then starts 60 seconds timer and then loops the script.

What i want to do is .It should not wait for me to close firefox and directly force closes firefox after 60 seconds and runs in loop

  @Echo off
:loop
cls
taskkill /f /im Firefox.exe
cls
taskkill /f /im crashreporter.exe
cls
timeout /T 60
    start ""
"C:\Program Files (x86)\Mozilla Firefox\firefox.exe" imacros://run/?m=l4lyt.iim
timeout /T 60
goto loop

What am i doing wrong?why does it waits for me to close firefox instead of directly going to next line.
i.e

timeout /T 60

Body:
You had the start command on a separate line from firefox.exe, therefore it launched a command prompt window and then called firefox.exe instead of executing it.

Additionally you don't need to use cls to clear the screen, instead use >nul 2>&1 to suppress output from the taskkill command(s)

Updated script:

@echo off
    start "" "C:\Program Files (x86)\Mozilla Firefox\firefox.exe" imacros://run/?m=l4lyt.iim
    timeout /T 60
    taskkill /f /t /im Firefox.exe /im crashreporter.exe >nul 2>&1
%0


问:
SAXParseException XML document structures must start and end within the same entity
So I know using this API, some of my xml files which are produced on a server might be generated wrongly or without closing some tags, or badly structured.
Now my code is working fine, but for certain files, some of these xml files throw these error, below is block of error

```<code>org.xml.sax.SAXParseException; systemId: file:///E:/ARCHIVED_LOGS/BACKUP_LOG_190317_0000/trace_file.xml; lineNumber: 201; columnNumber: 105; XML document structures must start and end within the same entity.
    at com.sun.org.apache.xerces.internal.util.ErrorHandlerWrapper.createSAXParseException(Unknown Source)
    at com.sun.org.apache.xerces.internal.util.ErrorHandlerWrapper.fatalError(Unknown Source)
    at com.sun.org.apache.xerces.internal.impl.XMLErrorReporter.reportError(Unknown Source)
    at com.sun.org.apache.xerces.internal.impl.XMLErrorReporter.reportError(Unknown Source)
    at com.sun.org.apache.xerces.internal.impl.XMLScanner.reportFatalError(Unknown Source)
    at com.sun.org.apache.xerces.internal.impl.XMLDocumentFragmentScannerImpl.endEntity(Unknown Source)
    at com.sun.org.apache.xerces.internal.impl.XMLDocumentScannerImpl.endEntity(Unknown Source)
    at com.sun.org.apache.xerces.internal.impl.XMLEntityManager.endEntity(Unknown Source)
    at com.sun.org.apache.xerces.internal.impl.XMLEntityScanner.load(Unknown Source)
    at com.sun.org.apache.xerces.internal.impl.XMLEntityScanner.peekChar(Unknown Source)
    at com.sun.org.apache.xerces.internal.impl.XMLDocumentFragmentScannerImpl$FragmentContentDriver.next(Unknown Source)
    at com.sun.org.apache.xerces.internal.impl.XMLDocumentScannerImpl.next(Unknown Source)
    at com.sun.org.apache.xerces.internal.impl.XMLDocumentFragmentScannerImpl.scanDocument(Unknown Source)
    at com.sun.org.apache.xerces.internal.parsers.XML11Configuration.parse(Unknown Source)
    at com.sun.org.apache.xerces.internal.parsers.XML11Configuration.parse(Unknown Source)
</code>```

So is there a way to process these files without fixing the issue on them using SAX parser API?

I was thinking of processing those files line by line but that is a pain.

Also is there a way similar to skipping dtd validation as seen below

```<code>   SAXParserFactory factory = SAXParserFactory.newInstance();

   factory.setValidating(false);
   factory.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false);
   SAXParser saxParser = factory.newSAXParser();
</code>```

Thank you :)

答:
You can't use a conforming XML parser to process a non-conforming (non-)XML document.

You can use a non-conforming parser - for example an HTML parser - and it might offer the SAX parser API - but whether you can find a parser that accepts the particular flavour of non-XML that is being thrown at you is an open question, since you haven't given us any kind of specification for this non-XML language.

Body:
So I know using this API, some of my xml files which are produced on a server might be generated wrongly or without closing some tags, or badly structured.
Now my code is working fine, but for certain files, some of these xml files throw these error, below is block of error

org.xml.sax.SAXParseException; systemId: file:///E:/ARCHIVED_LOGS/BACKUP_LOG_190317_0000/trace_file.xml; lineNumber: 201; columnNumber: 105; XML document structures must start and end within the same entity.
    at com.sun.org.apache.xerces.internal.util.ErrorHandlerWrapper.createSAXParseException(Unknown Source)
    at com.sun.org.apache.xerces.internal.util.ErrorHandlerWrapper.fatalError(Unknown Source)
    at com.sun.org.apache.xerces.internal.impl.XMLErrorReporter.reportError(Unknown Source)
    at com.sun.org.apache.xerces.internal.impl.XMLErrorReporter.reportError(Unknown Source)
    at com.sun.org.apache.xerces.internal.impl.XMLScanner.reportFatalError(Unknown Source)
    at com.sun.org.apache.xerces.internal.impl.XMLDocumentFragmentScannerImpl.endEntity(Unknown Source)
    at com.sun.org.apache.xerces.internal.impl.XMLDocumentScannerImpl.endEntity(Unknown Source)
    at com.sun.org.apache.xerces.internal.impl.XMLEntityManager.endEntity(Unknown Source)
    at com.sun.org.apache.xerces.internal.impl.XMLEntityScanner.load(Unknown Source)
    at com.sun.org.apache.xerces.internal.impl.XMLEntityScanner.peekChar(Unknown Source)
    at com.sun.org.apache.xerces.internal.impl.XMLDocumentFragmentScannerImpl$FragmentContentDriver.next(Unknown Source)
    at com.sun.org.apache.xerces.internal.impl.XMLDocumentScannerImpl.next(Unknown Source)
    at com.sun.org.apache.xerces.internal.impl.XMLDocumentFragmentScannerImpl.scanDocument(Unknown Source)
    at com.sun.org.apache.xerces.internal.parsers.XML11Configuration.parse(Unknown Source)
    at com.sun.org.apache.xerces.internal.parsers.XML11Configuration.parse(Unknown Source)

So is there a way to process these files without fixing the issue on them using SAX parser API?

I was thinking of processing those files line by line but that is a pain.

Also is there a way similar to skipping dtd validation as seen below

   SAXParserFactory factory = SAXParserFactory.newInstance();

   factory.setValidating(false);
   factory.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false);
   SAXParser saxParser = factory.newSAXParser();

Thank you :)


问:
After Insert data macro not running
I have a table tblEmp with a After Insert data macro defined. However, the event is not working. what I am missing here?

答:
Simply move your logic to the BeforeChange trigger which is the state before any record (new or existing) is saved. Your logic attempts to change field values in AfterInsert which is after the save mode. Also, be sure to not include the table identifier, tblEmp, in referencing column name in macro:

In fact, had you clicked the Application Errors on status bar in lower right after your current attempt, the outputted system table indicates the issue since you are in read-only mode after inserting:

EditRecord failed because the default alias represents a record which
  is read only.

Title: After Insert data macro not running


问:
ANTLR What is simpliest way to realize python like indent-depending grammar?
I am trying realize python like indent-depending grammar.

Source example:

```<code>ABC QWE
  CDE EFG
  EFG CDE
    ABC
  QWE ZXC
</code>```

As i see, what i need is to realize two tokens INDENT and DEDENT, so i could write something like:

```<code>grammar mygrammar;
text: (ID | block)+;
block: INDENT (ID|block)+ DEDENT;
INDENT: ????;
DEDENT: ????;
</code>```

Is there any simple way to realize this using ANTLR?

(I'd prefer, if it's possible, to use standard ANTLR lexer.)

答:
There is a relatively simple way to do this ANTLR, which I wrote as an experiment: DentLexer.g4. This solution is different from the others mentioned on this page that were written by Kiers and Shavit. It integrates with the runtime solely via an override of the Lexer's nextToken() method. It does its work by examining tokens: (1) a NEWLINE token triggers the start of a "keep track of indentation" phase; (2) whitespace and comments, both set to channel HIDDEN, are counted and ignored, respectively, during that phase; and, (3) any non-HIDDEN token ends the phase. Thus controlling the indentation logic is a simple matter of setting a token's channel.

Both of the solutions mentioned on this page require a NEWLINE token to also grab all the subsequent whitespace, but in doing so can't handle multi-line comments interrupting that whitespace. Dent, instead, keeps NEWLINE and whitespace tokens separate and can handle multi-line comments.

Your grammar would be set up something like below. Note that the NEWLINE and WS lexer rules have actions that control the pendingDent state and keep track of indentation level with the indentCount variable.

```<code>grammar MyGrammar;

tokens { INDENT, DEDENT }

@lexer::members {
    // override of nextToken(), see Dent.g4 grammar on github
    // https://github.com/wevrem/wry/blob/master/grammars/Dent.g4
}

script : ( NEWLINE | statement )* EOF ;

statement
    :   simpleStatement
    |   blockStatements
    ;

simpleStatement : LEGIT+ NEWLINE ;

blockStatements : LEGIT+ NEWLINE INDENT statement+ DEDENT ;

NEWLINE : ( '\r'? '\n' | '\r' ) {
    if (pendingDent) { setChannel(HIDDEN); }
    pendingDent = true;
    indentCount = 0;
    initialIndentToken = null;
} ;

WS : [ \t]+ {
    setChannel(HIDDEN);
    if (pendingDent) { indentCount += getText().length(); }
} ;

BlockComment : '/*' ( BlockComment | . )*? '*/' -> channel(HIDDEN) ;   // allow nesting comments
LineComment : '//' ~[\r\n]* -> channel(HIDDEN) ;

LEGIT : ~[ \t\r\n]+ ~[\r\n]*;   // Replace with your language-specific rules...
</code>```

Body:
I am trying realize python like indent-depending grammar.

Source example:

ABC QWE
  CDE EFG
  EFG CDE
    ABC
  QWE ZXC

As i see, what i need is to realize two tokens INDENT and DEDENT, so i could write something like:

grammar mygrammar;
text: (ID | block)+;
block: INDENT (ID|block)+ DEDENT;
INDENT: ????;
DEDENT: ????;

Is there any simple way to realize this using ANTLR?

(I'd prefer, if it's possible, to use standard ANTLR lexer.)

Body:
There is a relatively simple way to do this ANTLR, which I wrote as an experiment: DentLexer.g4. This solution is different from the others mentioned on this page that were written by Kiers and Shavit. It integrates with the runtime solely via an override of the Lexer's nextToken() method. It does its work by examining tokens: (1) a NEWLINE token triggers the start of a "keep track of indentation" phase; (2) whitespace and comments, both set to channel HIDDEN, are counted and ignored, respectively, during that phase; and, (3) any non-HIDDEN token ends the phase. Thus controlling the indentation logic is a simple matter of setting a token's channel.

Both of the solutions mentioned on this page require a NEWLINE token to also grab all the subsequent whitespace, but in doing so can't handle multi-line comments interrupting that whitespace. Dent, instead, keeps NEWLINE and whitespace tokens separate and can handle multi-line comments.

Your grammar would be set up something like below. Note that the NEWLINE and WS lexer rules have actions that control the pendingDent state and keep track of indentation level with the indentCount variable.

grammar MyGrammar;

tokens { INDENT, DEDENT }

@lexer::members {
    // override of nextToken(), see Dent.g4 grammar on github
    // https://github.com/wevrem/wry/blob/master/grammars/Dent.g4
}

script : ( NEWLINE | statement )* EOF ;

statement
    :   simpleStatement
    |   blockStatements
    ;

simpleStatement : LEGIT+ NEWLINE ;

blockStatements : LEGIT+ NEWLINE INDENT statement+ DEDENT ;

NEWLINE : ( '\r'? '\n' | '\r' ) {
    if (pendingDent) { setChannel(HIDDEN); }
    pendingDent = true;
    indentCount = 0;
    initialIndentToken = null;
} ;

WS : [ \t]+ {
    setChannel(HIDDEN);
    if (pendingDent) { indentCount += getText().length(); }
} ;

BlockComment : '/*' ( BlockComment | . )*? '*/' -> channel(HIDDEN) ;   // allow nesting comments
LineComment : '//' ~[\r\n]* -> channel(HIDDEN) ;

LEGIT : ~[ \t\r\n]+ ~[\r\n]*;   // Replace with your language-specific rules...

ContentLicense: CC BY-SA 4.0


问:
Unable to access unescaped html in an RSS feed
I'm using the built in RSS capabilities of Ruby (RSS::Parser.parse) in a new rails app.  The app reads several different sources of rss feeds that are outside of my control (public facing, built by others).  One of the feeds I am trying to access contains unescaped html in its description fields within the items collection.  I am able to access the feed, but when I try to access the description field within my view it appears as if nothing is there.  I at first thought I needed to use the raw helper, but the end result is the same.  Is there some special way I need to request the data or access it in the view?  The code in my controller is as follows:

```<code>@recent_activity = RSS::Parser.parse(open('http://someurl').read, false)
</code>```

The code in my view is as follows

```<code><% @recent_activity.items.each do |itm| %>
    <%= raw itm.description %>
<% end %>
</code>```

I know I could probably make this work by utilizing the raw xml capabilities and bypass the RSS object, but I'm trying to see if there is something I can do with the RSS object before going that route.

Thanks in advance for any help or suggestions.

答:
From experience I've found real world feeds are often more complex than the RSS::Parser can handle. It's been a while since I had to do anything with feeds but these come to mind:

feedtools

feedparser

The big problem you'll find is that no package will do it all correctly because the people creating the feeds are so darned inventive. You'll find all sorts of devilish text, HTML, and encoded and unencoded whatnot in the description and title fields. I ended up writing my own parser and used Nokogiri to handle the heavy lifting, with some help from loofah to strip specific undesired tags. I was parsing close to 1000 different feeds, at varying intervals, using a backing database to track last access, etags and doing all the righteous things like not pummeling sites to death if they didn't have anything new to say, and honoring their "don't bother me between these hours or days" settings.

Body:
I'm using the built in RSS capabilities of Ruby (RSS::Parser.parse) in a new rails app.  The app reads several different sources of rss feeds that are outside of my control (public facing, built by others).  One of the feeds I am trying to access contains unescaped html in its description fields within the items collection.  I am able to access the feed, but when I try to access the description field within my view it appears as if nothing is there.  I at first thought I needed to use the raw helper, but the end result is the same.  Is there some special way I need to request the data or access it in the view?  The code in my controller is as follows:

@recent_activity = RSS::Parser.parse(open('http://someurl').read, false)

The code in my view is as follows

<% @recent_activity.items.each do |itm| %>
    <%= raw itm.description %>
<% end %>

I know I could probably make this work by utilizing the raw xml capabilities and bypass the RSS object, but I'm trying to see if there is something I can do with the RSS object before going that route.

Thanks in advance for any help or suggestions.


问:
Erlang: advantages to separate relx.config?
I always had a rebar.config and a relx.config. However, I read this page by the author of Learn you some Erlang: http://howistart.org/posts/erlang/1/, and he has the relx section in his rebar.config and no relx.config. Is there a pro/con to this? Should I stick them all in one file? What is the best practice for this?

答: With Rebar3, relx is integrated From Rebar 2.x to Rebar3. Hence, there's no need to have relx.config separately unless you're using relx directly (or with another build tool like erlang.mk). </p>


问:
SAS nested do loops with arrays
Having problems understanding the following code.  This snippet is supposed to output a data set that compares target values (sasuser.ctargets) to actual values (sasuser.monthsum).  Observations are matched by month and year and populated to the targets array.  The code works exactly as it should, but to my mind it shouldn't.

Look at the nested DO loop:

Targets is indexed in the nested DO loop by year and j.  I understand that the outer loop uses three iterations (i=1 to 3): one for each value of the year variable(1997-1999).  Year, however, is declared outside of the DO loop.  So if the automatic variable _n_ creates the target array on the first iteration of the DO loop, how the hell does the targets array populate correctly for years 1998 and 1999 which are not read until subsequent iterations of the DATA step?  How is it that year works as an iterator?

```<code>data work.lookup1;
    array targets(1997:1999,12) _temporary_;
    if _n_=1 then do i=1 to 3;
        set sasuser.ctargets;
        array mnth(*) Jan--Dec;
        do j=1 to dim(mnth);
            targets(year,j)=mnth(j);
        end;
    end;
    set sasuser.monthsum(keep=salemon revcargo monthno);
    year=input(substr(salemon,4),4.);
    ctarget=targets(year,monthno);
    format ctarget dollar15.2;
run;
</code>```

答: The only way this works is if the variable YEAR is in the dataset SASUSER.CTARGETS.

Title: SAS nested do loops with arrays

Body:
Having problems understanding the following code.  This snippet is supposed to output a data set that compares target values (sasuser.ctargets) to actual values (sasuser.monthsum).  Observations are matched by month and year and populated to the targets array.  The code works exactly as it should, but to my mind it shouldn't.

Look at the nested DO loop:

Targets is indexed in the nested DO loop by year and j.  I understand that the outer loop uses three iterations (i=1 to 3): one for each value of the year variable(1997-1999).  Year, however, is declared outside of the DO loop.  So if the automatic variable _n_ creates the target array on the first iteration of the DO loop, how the hell does the targets array populate correctly for years 1998 and 1999 which are not read until subsequent iterations of the DATA step?  How is it that year works as an iterator?

data work.lookup1;
    array targets(1997:1999,12) _temporary_;
    if _n_=1 then do i=1 to 3;
        set sasuser.ctargets;
        array mnth(*) Jan--Dec;
        do j=1 to dim(mnth);
            targets(year,j)=mnth(j);
        end;
    end;
    set sasuser.monthsum(keep=salemon revcargo monthno);
    year=input(substr(salemon,4),4.);
    ctarget=targets(year,monthno);
    format ctarget dollar15.2;
run;


问:
Render to QOpenGLFramebufferObject GL_HALF_FLOAT
I want to render to a half float texture using QOpenGLFramebufferObject.
I try to create the fbo with the following code:

```<code>structureTensorTexture = new QOpenGLFramebufferObject(
    renderWidth,
    renderHeight,
    QOpenGLFramebufferObject::NoAttachment,
    GL_TEXTURE_2D,
    GL_HALF_FLOAT
);
</code>```

But when I run the program this message appears in the console:

```<code>[opengl\qopenglframebufferobject.cpp line 544] OpenGL Error: 1280
QOpenGLFramebufferObject: Framebuffer incomplete attachment.
QOpenGLFramebufferObject: Framebuffer incomplete, missing attachment.
</code>```

If I use GL_RGBA instead of GL_HALF_FLOAT the error message doesn't appear, but this doesn't fit my purpose.

How can I render to a half float texture using QT?

答:
By providing an actual OpenGL image format. GL_HALF_FLOAT is not an image format; it's an enum that represents a type. You can use that as the type in pixel transfer operations, but that's not an image format.

An image format that uses 16-bit floats would be GL_RGBA16F.

Body:
I want to render to a half float texture using QOpenGLFramebufferObject.
I try to create the fbo with the following code:

structureTensorTexture = new QOpenGLFramebufferObject(
    renderWidth,
    renderHeight,
    QOpenGLFramebufferObject::NoAttachment,
    GL_TEXTURE_2D,
    GL_HALF_FLOAT
);

But when I run the program this message appears in the console:

[opengl\qopenglframebufferobject.cpp line 544] OpenGL Error: 1280
QOpenGLFramebufferObject: Framebuffer incomplete attachment.
QOpenGLFramebufferObject: Framebuffer incomplete, missing attachment.

If I use GL_RGBA instead of GL_HALF_FLOAT the error message doesn't appear, but this doesn't fit my purpose.

How can I render to a half float texture using QT?


问:
What is the point of using ConcurrentMap.replace in this example
Here's an excerpt from Java Concurrency in Practice:

```<code>public class DelegatingVehicleTracker {

    private final ConcurrentMap<String, Point> locations;
    private final Map<String, Point> unmodifiableMap;

    public DelegatingVehicleTracker(final Map<String, Point> points) {
        this.locations = new ConcurrentHashMap<>(points);
        this.unmodifiableMap = Collections.unmodifiableMap(this.locations);
    }

    public Map<String, Point> getLocations() {
        return unmodifiableMap;
    }

    public Point getLocation(final String id) {
        return locations.get(id);
    }

    public void setLocation(final String id, final int x, final int y) {
        if (null == locations.replace(id, new Point(x, y))) {
            throw new IllegalArgumentException("Invalid vehicle name: " + id);
        }
    }
}
</code>```

My question is about the setLocation method which uses ConcurrentMap.replace. The JavaDoc of this method says that it's equivalent to:

```<code>if (map.containsKey(key)) {
     return map.put(key, value);
} else return null;
</code>```

except that the action is performed atomically.

What could go wrong if we don't use the atomic version. One possibility is that one thread sees that the map contains a given key and before it puts a new value for that key, another thread removes that key-value pair, but since the class in the example does not allow removals, this cannot happen.

Another possibility is that two threads attempt to replace the same key with different values. In that case one thread may not return the correct previous value but in the example we don't care about the previous value, the method setLocation returns void.

So, it seems as though the method could be rewritten without replace. And that is what prompted my question. In a subsequent version of the same class in the book, which almost identical to the one above, the method setLocation does not use replace, just containsKey and I was wondering if this could compromise thread safety.

答:
What could go wrong if we don't use the atomic version

Nothing.

It's stylistic. You could implement the setLocation method whatever way you want, but it just so happens that replace is a nice way to ensure that you only insert if the given location exists in the map.

In a subsequent version of the same class in the book, which almost identical to the one above, the method setLocation does not use replace, just containsKey and I was wondering if this could compromise thread safety.

It does not compromise thread safety. The assertion that the key is contained in the map cannot change in a concurrent write because given that the key is present, it will not suddenly be removed, and given that it is not present, nothing will be done.

The author decided to use contains key because the second example uses a mutable point rather than an immutable point. Recall that JCIP was written for Java 5 and such methods as computeIfPresent did not exist at the time. Therefore, the author must obtain the object it self in order to modify it. Thread safety will therefore be delegated to the mutable point rather than the vehicle tracker itself.

Body:
Here's an excerpt from Java Concurrency in Practice:

public class DelegatingVehicleTracker {

    private final ConcurrentMap<String, Point> locations;
    private final Map<String, Point> unmodifiableMap;

    public DelegatingVehicleTracker(final Map<String, Point> points) {
        this.locations = new ConcurrentHashMap<>(points);
        this.unmodifiableMap = Collections.unmodifiableMap(this.locations);
    }

    public Map<String, Point> getLocations() {
        return unmodifiableMap;
    }

    public Point getLocation(final String id) {
        return locations.get(id);
    }

    public void setLocation(final String id, final int x, final int y) {
        if (null == locations.replace(id, new Point(x, y))) {
            throw new IllegalArgumentException("Invalid vehicle name: " + id);
        }
    }
}

My question is about the setLocation method which uses ConcurrentMap.replace. The JavaDoc of this method says that it's equivalent to:

if (map.containsKey(key)) {
     return map.put(key, value);
} else return null;

except that the action is performed atomically.

What could go wrong if we don't use the atomic version. One possibility is that one thread sees that the map contains a given key and before it puts a new value for that key, another thread removes that key-value pair, but since the class in the example does not allow removals, this cannot happen.

Another possibility is that two threads attempt to replace the same key with different values. In that case one thread may not return the correct previous value but in the example we don't care about the previous value, the method setLocation returns void.

So, it seems as though the method could be rewritten without replace. And that is what prompted my question. In a subsequent version of the same class in the book, which almost identical to the one above, the method setLocation does not use replace, just containsKey and I was wondering if this could compromise thread safety.


问:
I need help with forms submit, please read for details
I would like to create a form where the user can put a number in like "12345" and when the submit button is clicked have the result be http://www.URL.com/12345</p>

答:
Do you need that data to be posted somewhere, or do you just want to jump to that location?
You could try without a form:</p>

```<code><label for="number">Number: </label>
<input type="text" id="number" /><br />
<input type="button"
    onclick="window.location='http://www.URL.com/'+document.getElementById('number').value;" />
</code>```

Body:
Do you need that data to be posted somewhere, or do you just want to jump to that location?
You could try without a form:

<label for="number">Number: </label>
<input type="text" id="number" /><br />
<input type="button"
    onclick="window.location='http://www.URL.com/'+document.getElementById('number').value;" />


问:
I am using the try in PHP but the PDO wont catch the exception
Hey for some reason i will use the try keyword in php to catch the PDO exception but it wont. I would put random incorrect details and it shows PDO Uncaught Exception and it show the connection details. It works i can execute the sql statements but when the conn details are incorrect it says uncaught PDO exception. This is for a framework i am working on.

the global file calls all the other files but il only include the database classes because thats where the problem is.

Global.php

```<code><?php
namespace App\Framework;
define('APP_VERSION', '1.0.0');
defined("START") ? null : define("START", microtime());
define('DEBUG', true);
if (DEBUG) {
  error_reporting(E_ALL);
  ini_set('display_errors', 1);
} else {
  error_reporting(0);
  ini_set('display_errors', 0);
}
include_once 'LinkConfig.php';
include_once 'LinkInterface.php';
include_once 'Link.php';
try {
  $Link = new Link(
    LinkConfig::DRIVER,
    LinkConfig::HOST,
    LinkConfig::DBNAME,
    LinkConfig::USER,
    LinkConfig::PASS,
    LinkConfig::CHARSET,
    LinkConfig::PORT
  );
} catch (PDOException $Exception) {
  die('Connection failed: ' . $Exception->getMessage());
}

?>
</code>```

This is the DB connection interface file

LinkInterface.php

```<code><?php
namespace App\Framework;
defined('START') || (header('HTTP/1.1 403 Forbidden') & die('403.14 - Directory listing denied.'));
interface ILink {
  public function __construct($Driver, $Host, $DBName, $User, $Pass, $Charset, $Port);
  public function Select($Sql, $Array = array(), $FetchMode = PDO::FETCH_ASSOC);
  public function Insert($Table, array $Data);
  public function Update($Table, $Data, $Where, $WhereBindArray = array());
  public function Delete($Table, $Where, $Bind = array(), $Limit = null);
}

?>
</code>```

This is the DB connection config file.

LinkConfig.php

```<code><?php
namespace App\Framework;
defined('START') || (header('HTTP/1.1 403 Forbidden') & die('403.14 - Directory listing denied.'));
class LinkConfig {
  const DRIVER = 'mysql';
  const HOST = 'localhost';
  const DBNAME = 'test';
  const USER = 'root';
  const PASS = '';
  const CHARSET = 'utf8';
  const PORT = '3306';
  const DEBUG = true;
}

?>
</code>```

And the last file is where it all happens.

Link.php

```<code><?php
namespace App\Framework;
defined('START') || (header('HTTP/1.1 403 Forbidden') & die('403.14 - Directory listing denied.'));
use \PDO;
class Link extends PDO {
  public function __construct($Driver, $Host, $DBName, $User, $Pass, $Charset, $Port) {
    parent::__construct($Driver . ':host=' . $Host . ';port=' . $Port . ';dbname=' . $DBName . ';charset=' . $Charset, $User, $Pass);
    $this->exec('SET CHARACTER SET ' . $Charset);
    if (LinkConfig::DEBUG) {
      $this->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_WARNING);
    }
  }
  public function Select($Sql, $Array = array(), $FetchMode = PDO::FETCH_ASSOC) {
    $Sth = $this->prepare($Sql);
    foreach ($Array as $Key => $Value) {
      $Sth->bindValue(":$Key", $Value);
    }
    $Sth->execute();
    return $Sth->fetchAll($FetchMode);
  }
  public function Insert($Table, array $Data) {
    ksort($Data);
    $FieldNames = implode('`, `', array_keys($Data));
    $FieldValues = ':' . implode(', :', array_keys($Data));
    $Sth = $this->prepare("INSERT INTO $Table (`$FieldNames`) VALUES ($FieldValues)");
    foreach ($Data as $Key => $Value) {
      $Sth->bindValue(":$Key", $Value);
    }
    $Sth->execute();
  }
  public function Update($Table, $Data, $Where, $WhereBindArray = array()) {
    ksort($Data);
    $FieldDetails = null;
    foreach ($data as $Key => $Value) {
      $FieldDetails .= "`$Key`=:$Key,";
    }
    $FieldDetails = rtrim($FieldDetails, ',');
    $Sth = $this->prepare("UPDATE $Table SET $FieldDetails WHERE $Where");
    foreach ($Data as $Key => $Value) {
      $Sth->bindValue(":$Key", $Value);
    }
    foreach ($WhereBindArray as $Key => $Value) {
      $Sth->bindValue(":$Key", $Value);
    }
    $Sth->execute();
  }
  public function Delete($Table, $Where, $Bind = array(), $Limit = null) {
    $Query = "DELETE FROM $Table WHERE $Where";
    if ($Limit) {
      $Query .= " LIMIT $Limit";
    }
    $Sth = $this->prepare($Query);
    foreach ($Bind as $Key => $Value) {
      $Sth->bindValue(":$Key", $Value);
    }
    $Sth->execute();
  }
}

?>
</code>```

Is there a logical explaination why it is showing uncaught PDO exception.

This is the error message i get.

this is what it outputs Fatal error: Uncaught PDOException: PDO::__construct(): php_network_getaddresses: getaddrinfo failed: No such host is known. in C:\xampp\htdocs\vendor\Link.php:8 Stack trace: #0 C:\xampp\htdocs\vendor\Link.php(8): PDO->__construct('mysql:host=loca...', 'root', '') #1 C:\xampp\htdocs\vendor\Global.php(33): App\Framework\Link->__construct('mysql', 'localhostz', 'test', 'root', '', 'utf8', '3306') #2 {main} Next PDOException: SQLSTATE[HY000] [2002] php_network_getaddresses: getaddrinfo failed: No such host is known. in C:\xampp\htdocs\vendor\Link.php:8 Stack trace: #0 C:\xampp\htdocs\vendor\Link.php(8): PDO->__construct('mysql:host=loca...', 'root', '') #1 C:\xampp\htdocs\vendor\Global.php(33): App\Framework\Link->__construct('mysql', 'localhostz', 'test', 'root', '', 'utf8', '3306') #2 {main} thrown in C:\xampp\htdocs\vendor\Link.php on line 8

答:
So i figured it out it was the use of the namespaces by changing Global.php to:

```<code><?php
use App\Framework as Framework;
define('APP_VERSION', '1.0.0');
defined("START") ? null : define("START", microtime());
define('DEBUG', true);
if (DEBUG) {
  error_reporting(E_ALL);
  ini_set('display_errors', 1);
} else {
  error_reporting(0);
  ini_set('display_errors', 0);
}
include_once 'LinkConfig.php';
include_once 'LinkInterface.php';
include_once 'Link.php';
try {
  $Link = new Framework\Link(
    Framework\LinkConfig::DRIVER,
    Framework\LinkConfig::HOST,
    Framework\LinkConfig::DBNAME,
    Framework\LinkConfig::USER,
    Framework\LinkConfig::PASS,
    Framework\LinkConfig::CHARSET,
    Framework\LinkConfig::PORT
  );
} catch (PDOException $Exception) {
  echo 'Connection failed: ' . $Exception->getMessage();
}

?>
</code>```

Body:
Hey for some reason i will use the try keyword in php to catch the PDO exception but it wont. I would put random incorrect details and it shows PDO Uncaught Exception and it show the connection details. It works i can execute the sql statements but when the conn details are incorrect it says uncaught PDO exception. This is for a framework i am working on.

the global file calls all the other files but il only include the database classes because thats where the problem is.

Global.php

<?php
namespace App\Framework;
define('APP_VERSION', '1.0.0');
defined("START") ? null : define("START", microtime());
define('DEBUG', true);
if (DEBUG) {
  error_reporting(E_ALL);
  ini_set('display_errors', 1);
} else {
  error_reporting(0);
  ini_set('display_errors', 0);
}
include_once 'LinkConfig.php';
include_once 'LinkInterface.php';
include_once 'Link.php';
try {
  $Link = new Link(
    LinkConfig::DRIVER,
    LinkConfig::HOST,
    LinkConfig::DBNAME,
    LinkConfig::USER,
    LinkConfig::PASS,
    LinkConfig::CHARSET,
    LinkConfig::PORT
  );
} catch (PDOException $Exception) {
  die('Connection failed: ' . $Exception->getMessage());
}

?>

This is the DB connection interface file

LinkInterface.php

<?php
namespace App\Framework;
defined('START') || (header('HTTP/1.1 403 Forbidden') & die('403.14 - Directory listing denied.'));
interface ILink {
  public function __construct($Driver, $Host, $DBName, $User, $Pass, $Charset, $Port);
  public function Select($Sql, $Array = array(), $FetchMode = PDO::FETCH_ASSOC);
  public function Insert($Table, array $Data);
  public function Update($Table, $Data, $Where, $WhereBindArray = array());
  public function Delete($Table, $Where, $Bind = array(), $Limit = null);
}

?>

This is the DB connection config file.

LinkConfig.php

<?php
namespace App\Framework;
defined('START') || (header('HTTP/1.1 403 Forbidden') & die('403.14 - Directory listing denied.'));
class LinkConfig {
  const DRIVER = 'mysql';
  const HOST = 'localhost';
  const DBNAME = 'test';
  const USER = 'root';
  const PASS = '';
  const CHARSET = 'utf8';
  const PORT = '3306';
  const DEBUG = true;
}

?>

And the last file is where it all happens.

Link.php

<?php
namespace App\Framework;
defined('START') || (header('HTTP/1.1 403 Forbidden') & die('403.14 - Directory listing denied.'));
use \PDO;
class Link extends PDO {
  public function __construct($Driver, $Host, $DBName, $User, $Pass, $Charset, $Port) {
    parent::__construct($Driver . ':host=' . $Host . ';port=' . $Port . ';dbname=' . $DBName . ';charset=' . $Charset, $User, $Pass);
    $this->exec('SET CHARACTER SET ' . $Charset);
    if (LinkConfig::DEBUG) {
      $this->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_WARNING);
    }
  }
  public function Select($Sql, $Array = array(), $FetchMode = PDO::FETCH_ASSOC) {
    $Sth = $this->prepare($Sql);
    foreach ($Array as $Key => $Value) {
      $Sth->bindValue(":$Key", $Value);
    }
    $Sth->execute();
    return $Sth->fetchAll($FetchMode);
  }
  public function Insert($Table, array $Data) {
    ksort($Data);
    $FieldNames = implode('`, `', array_keys($Data));
    $FieldValues = ':' . implode(', :', array_keys($Data));
    $Sth = $this->prepare("INSERT INTO $Table (`$FieldNames`) VALUES ($FieldValues)");
    foreach ($Data as $Key => $Value) {
      $Sth->bindValue(":$Key", $Value);
    }
    $Sth->execute();
  }
  public function Update($Table, $Data, $Where, $WhereBindArray = array()) {
    ksort($Data);
    $FieldDetails = null;
    foreach ($data as $Key => $Value) {
      $FieldDetails .= "`$Key`=:$Key,";
    }
    $FieldDetails = rtrim($FieldDetails, ',');
    $Sth = $this->prepare("UPDATE $Table SET $FieldDetails WHERE $Where");
    foreach ($Data as $Key => $Value) {
      $Sth->bindValue(":$Key", $Value);
    }
    foreach ($WhereBindArray as $Key => $Value) {
      $Sth->bindValue(":$Key", $Value);
    }
    $Sth->execute();
  }
  public function Delete($Table, $Where, $Bind = array(), $Limit = null) {
    $Query = "DELETE FROM $Table WHERE $Where";
    if ($Limit) {
      $Query .= " LIMIT $Limit";
    }
    $Sth = $this->prepare($Query);
    foreach ($Bind as $Key => $Value) {
      $Sth->bindValue(":$Key", $Value);
    }
    $Sth->execute();
  }
}

?>

Is there a logical explaination why it is showing uncaught PDO exception.

This is the error message i get.

this is what it outputs Fatal error: Uncaught PDOException: PDO::__construct(): php_network_getaddresses: getaddrinfo failed: No such host is known. in C:\xampp\htdocs\vendor\Link.php:8 Stack trace: #0 C:\xampp\htdocs\vendor\Link.php(8): PDO->__construct('mysql:host=loca...', 'root', '') #1 C:\xampp\htdocs\vendor\Global.php(33): App\Framework\Link->__construct('mysql', 'localhostz', 'test', 'root', '', 'utf8', '3306') #2 {main} Next PDOException: SQLSTATE[HY000] [2002] php_network_getaddresses: getaddrinfo failed: No such host is known. in C:\xampp\htdocs\vendor\Link.php:8 Stack trace: #0 C:\xampp\htdocs\vendor\Link.php(8): PDO->__construct('mysql:host=loca...', 'root', '') #1 C:\xampp\htdocs\vendor\Global.php(33): App\Framework\Link->__construct('mysql', 'localhostz', 'test', 'root', '', 'utf8', '3306') #2 {main} thrown in C:\xampp\htdocs\vendor\Link.php on line 8

Body:
So i figured it out it was the use of the namespaces by changing Global.php to:

<?php
use App\Framework as Framework;
define('APP_VERSION', '1.0.0');
defined("START") ? null : define("START", microtime());
define('DEBUG', true);
if (DEBUG) {
  error_reporting(E_ALL);
  ini_set('display_errors', 1);
} else {
  error_reporting(0);
  ini_set('display_errors', 0);
}
include_once 'LinkConfig.php';
include_once 'LinkInterface.php';
include_once 'Link.php';
try {
  $Link = new Framework\Link(
    Framework\LinkConfig::DRIVER,
    Framework\LinkConfig::HOST,
    Framework\LinkConfig::DBNAME,
    Framework\LinkConfig::USER,
    Framework\LinkConfig::PASS,
    Framework\LinkConfig::CHARSET,
    Framework\LinkConfig::PORT
  );
} catch (PDOException $Exception) {
  echo 'Connection failed: ' . $Exception->getMessage();
}

?>


问:
Formatting calendar in Linux Terminal
I have been playing around with the Linux terminal, and here is an odd thing that I am not able to explain. When I type the following command, the calendar turns out formatted in the terminal:

```<code>echo "$(cal)"
</code>```

However, when I type the same command without quotes, the calendar isn't formatted.

```<code>echo $(cal)
</code>```

Why is that?

答:
If you type cal you will get the calendar formatted on several lines.  The man page for echo says that it "writes each given STRING to standard output, with a space between each and a newline after the last one." So, what you are seeing when you type echo $(cal) is exactly that--each line of the output of cal is being treated as a separate string and written to the standard output with a space between each.  When you say echo "$(cal)" you are getting the literal value of the output--newlines and all.

This is true of any command that returns string output--try it with ifconfig.

Hope this helps!

Title: Formatting calendar in Linux Terminal

Body:
I have been playing around with the Linux terminal, and here is an odd thing that I am not able to explain. When I type the following command, the calendar turns out formatted in the terminal:

echo "$(cal)"

However, when I type the same command without quotes, the calendar isn't formatted.

echo $(cal)

Why is that?


问:
Make an HTTP request with android
I have searched everywhere but I couldn't find my answer, is there a way to make a simple HTTP request? I want to request a PHP page / script on one of my websites but I don't want to show the webpage.

If possible I even want to do it in the background (in a BroadcastReceiver)

答:
For me, the easiest way is using library called Retrofit2

We just need to create an Interface that contain our request method, parameters, and also we can make custom header for each request :

```<code>    public interface MyService {

      @GET("users/{user}/repos")
      Call<List<Repo>> listRepos(@Path("user") String user);

      @GET("user")
      Call<UserDetails> getUserDetails(@Header("Authorization") String   credentials);

      @POST("users/new")
      Call<User> createUser(@Body User user);

      @FormUrlEncoded
      @POST("user/edit")
      Call<User> updateUser(@Field("first_name") String first,
                            @Field("last_name") String last);

      @Multipart
      @PUT("user/photo")
      Call<User> updateUser(@Part("photo") RequestBody photo,
                            @Part("description") RequestBody description);

      @Headers({
        "Accept: application/vnd.github.v3.full+json",
        "User-Agent: Retrofit-Sample-App"
      })
      @GET("users/{username}")
      Call<User> getUser(@Path("username") String username);

    }
</code>```

And the best is, we can do it asynchronously easily using enqueue method

Title: Make an HTTP request with android

Body:
For me, the easiest way is using library called Retrofit2

We just need to create an Interface that contain our request method, parameters, and also we can make custom header for each request :

    public interface MyService {

      @GET("users/{user}/repos")
      Call<List<Repo>> listRepos(@Path("user") String user);

      @GET("user")
      Call<UserDetails> getUserDetails(@Header("Authorization") String   credentials);

      @POST("users/new")
      Call<User> createUser(@Body User user);

      @FormUrlEncoded
      @POST("user/edit")
      Call<User> updateUser(@Field("first_name") String first,
                            @Field("last_name") String last);

      @Multipart
      @PUT("user/photo")
      Call<User> updateUser(@Part("photo") RequestBody photo,
                            @Part("description") RequestBody description);

      @Headers({
        "Accept: application/vnd.github.v3.full+json",
        "User-Agent: Retrofit-Sample-App"
      })
      @GET("users/{username}")
      Call<User> getUser(@Path("username") String username);

    }

And the best is, we can do it asynchronously easily using enqueue method


问:
PHP Search multidimensional array for value & get corresponding element value
I am using PHP & I have a multi dimensional array which I need to search to see if the value of a "key" exists and if it does then get the value of the "field". Here's my array:

```<code>Array
(
    [0] => Array
    (
        [key] => 31
        [field] => CONSTRUCTN
        [value] => LFD_CONSTRUCTION_2
    )
    [1] => Array
    (
        [key] => 32
        [field] => COOLING
        value] => LFD_COOLING_1
    )
)
</code>```

I want to be able to search the array for the "key" value of 31. If it exists, then I want to be able to extract the corresponding "field" value of "CONSTRUCTN".

I've tried using array_search(31, $myArray) but it does not work...

答:
I haven't tested, but I think this should do it.

```<code>function searchByKey($value, $Array){
    foreach ($Array as $innerArray) {
        if ($innerArray['key'] == $value) {
            return $innerArray['field'];
        }
    }
}
</code>```

Then calling searchByKey(31, $myArray); should return 'CONSTRUCTN'.

Body:
I am using PHP & I have a multi dimensional array which I need to search to see if the value of a "key" exists and if it does then get the value of the "field". Here's my array:

Array
(
    [0] => Array
    (
        [key] => 31
        [field] => CONSTRUCTN
        [value] => LFD_CONSTRUCTION_2
    )
    [1] => Array
    (
        [key] => 32
        [field] => COOLING
        value] => LFD_COOLING_1
    )
)

I want to be able to search the array for the "key" value of 31. If it exists, then I want to be able to extract the corresponding "field" value of "CONSTRUCTN".

I've tried using array_search(31, $myArray) but it does not work...

Body:
I haven't tested, but I think this should do it.

function searchByKey($value, $Array){
    foreach ($Array as $innerArray) {
        if ($innerArray['key'] == $value) {
            return $innerArray['field'];
        }
    }
}

Then calling searchByKey(31, $myArray); should return 'CONSTRUCTN'.


问:
Setting Activities' Background Color
I am trying to change all of my activities' background color from white to black. I have tried everything - changing windowBackground, colorBackground, background but nothing seems to be working and I know my style is working because if I changed primary, accent colors they seem to be changing. The background tag only changes the action bar's color. Here's my code for the theme (what I have so far) -

```<code><style name="Yoyo" parent="Theme.AppCompat.Light.DarkActionBar">
    <item name="colorPrimary">@color/colorPrimary</item>
    <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
    <item name="colorAccent">@color/colorAccent1</item>
    <item name="android:windowBackground">@color/darkBackground</item>
    <item name="android:colorBackground">@color/darkBackground</item>
    <item name="android:textColor">#ffffff</item>
</style>
</code>```

darkBackground is black - what I need for my app to show but its not showing.

Also, I have already tried using @drawable/my_drawable_file (in which I set black color) in windowBackground but even that doesn't work.

min sdk version - 21, target sdk version - 25

答:
Try to change background your activity root element. For example:</p>

```<code><RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="your_color">
</code>```

Title: Setting Activities' Background Color

Body:
I am trying to change all of my activities' background color from white to black. I have tried everything - changing windowBackground, colorBackground, background but nothing seems to be working and I know my style is working because if I changed primary, accent colors they seem to be changing. The background tag only changes the action bar's color. Here's my code for the theme (what I have so far) -

darkBackground is black - what I need for my app to show but its not showing.

Also, I have already tried using @drawable/my_drawable_file (in which I set black color) in windowBackground but even that doesn't work.

min sdk version - 21, target sdk version - 25

Body:
Try to change background your activity root element. For example:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="your_color">


问:
Python print adds new line and 0
Here's my issue. I'm trying to ssh to Cisco devices and pull information off. When I run my code, the print statement adds a new line with a 0 in it to the bottom of the output. Here is the output of the code followed by the output of the plink CLI input:

```<code>C:\Python30>python PLINKSSHtest.py
Enter your username: josh
Password:
plink -pw nowayjose -ssh nope@1.1.1.1 "show run | inc hostname"
hostname net-R2
0  <------------MY ISSUE

C:\Python30>plink -pw nowayjose -ssh nope@1.1.1.1 "show run | inc hostname"
hostname net-R2
  <------------WHAT I EXPECT
</code>```

Here is my code:

```<code>def read_dev():
    # Print statement here for debugging
    print ("plink -pw " + password + " -ssh " + user + "@" + HOST + " " + command)
    cur_dev = os.system("plink -pw " + password + " -ssh " + user + "@" + HOST + " " + command)
    return(cur_dev)

HOST = None
user = input("Enter your username: ")
password = getpass.getpass()
command = '"show run | inc hostname"'
HOST = '1.1.1.1'
print (read_dev())
</code>```

答:
cur_dev is getting the result code returned by the plink command, which is 0.  Your read_dev function returns this code, so print(read_dev()) prints the 0.

Just say read_dev() instead of print(read_dev()).

Title: Python print adds new line and 0

Body:
Here's my issue. I'm trying to ssh to Cisco devices and pull information off. When I run my code, the print statement adds a new line with a 0 in it to the bottom of the output. Here is the output of the code followed by the output of the plink CLI input:

C:\Python30>python PLINKSSHtest.py
Enter your username: josh
Password:
plink -pw nowayjose -ssh nope@1.1.1.1 "show run | inc hostname"
hostname net-R2
0  <------------MY ISSUE

C:\Python30>plink -pw nowayjose -ssh nope@1.1.1.1 "show run | inc hostname"
hostname net-R2
  <------------WHAT I EXPECT

Here is my code:

def read_dev():
    # Print statement here for debugging
    print ("plink -pw " + password + " -ssh " + user + "@" + HOST + " " + command)
    cur_dev = os.system("plink -pw " + password + " -ssh " + user + "@" + HOST + " " + command)
    return(cur_dev)

HOST = None
user = input("Enter your username: ")
password = getpass.getpass()
command = '"show run | inc hostname"'
HOST = '1.1.1.1'
print (read_dev())