问:
Type Creation and Execution
I have created a type to print experience of employees from employees table for 5 employees with one incorrect id. I have created an exception to skip it but I am not getting the result for it. What mistake have I done? Please refer my query and tell the error.

```<code>CREATE OR REPLACE TYPE emp_id_typ IS TABLE OF NUMBER;
/

CREATE OR REPLACE TYPE emp_exp_typ IS TABLE OF NUMBER;
/

CREATE OR REPLACE PROCEDURE exp_sp ( p_empid   IN  emp_id_typ
                                   , p_exp     OUT emp_exp_typ)
IS
v_exp   NUMBER;
BEGIN
    FOR i IN p_empid.FIRST..p_empid.COUNT
    LOOP
    p_exp.EXTEND;
    SELECT ROUND(MONTHS_BETWEEN(SYSDATE, hire_date)/12) INTO v_exp FROM employees
     WHERE employee_id = p_empid(i);
    p_exp(p_exp.LAST) := v_exp;
    END LOOP;
    EXCEPTION
    WHEN OTHERS THEN
        v_exp := NVL(v_exp, 'NULL');
END exp_sp;
/

DECLARE
    v_empid emp_id_typ := emp_id_typ( );
    v_exp   emp_exp_typ := emp_exp_typ( );
BEGIN
    v_empid := emp_id_typ(101, 102, 52, 100, 206);
    FOR i IN v_empid.FIRST..v_empid.COUNT
    LOOP
    exp_sp(v_empid(i), v_exp(i));
    dbms_output.put_line(v_empid(i), v_exp(i));
    END LOOP;
END;
/
</code>```

Thanks in advance...

答:
You have several errors in both the procedure and the anonymous block. In the procedure:

You haven't initialised the OUT p_exp collection. As it's an OUT parameter you have to do it inside the procedure. (Alternatively make it IN OUT).

Your exception handler terminates the loop, so the v_exp you set in there is never used, and the p_exp collection is incomplete. (It's also bad practise to use when others.)

You can't assign a string like ``NULL'` to a number variable or collection. Either assign an a magic number that represents an error to the caller, or leave it null.

```<code>CREATE OR REPLACE PROCEDURE exp_sp ( p_empid   IN  emp_id_typ
                                   , p_exp     OUT emp_exp_typ)
IS
  v_exp   NUMBER;
BEGIN
  -- have to initialise p_exp
  p_exp := emp_exp_typ();
  -- better to use either 1..count, or first..last; don't mix them
  --FOR i IN p_empid.FIRST..p_empid.COUNT
  FOR i IN p_empid.FIRST..p_empid.LAST
  LOOP
    p_exp.EXTEND;
    -- you want the exception handler to deal with this row then continue,
    -- so use a nested block
    BEGIN
      SELECT ROUND(MONTHS_BETWEEN(SYSDATE, hire_date)/12) INTO v_exp FROM employees
      WHERE employee_id = p_empid(i);
    EXCEPTION
      WHEN OTHERS THEN
        -- you can't assign a string to a number
        --v_exp := NVL(v_exp, 'NULL');
        -- just an example as not clear what you need
        v_exp := -1;
    END; -- nested block with exception handler
    p_exp(p_exp.LAST) := v_exp;
  END LOOP;
END exp_sp;
/
</code>```

And in your anonymous block:

The initialisation of v_exp is redundant as the procedure argument is OUT. Not an error but pointless.

You are calling the procedure inside the loop, passing a single element; it should be called once outside the loop and passed the whole collection(s).

Your call to dbms_output.put_line is wrong; that only takes a single argument, so you have to build a string up e.g. with concatenation.

```<code>DECLARE
  v_empid emp_id_typ := emp_id_typ( );
  -- assignment is redundant
  -- v_exp   emp_exp_typ := emp_exp_typ( );
  v_exp   emp_exp_typ;
BEGIN
  v_empid := emp_id_typ(101, 102, 52, 100, 206);
  -- moved this call up, without indexing
  exp_sp(v_empid, v_exp);
  -- better to use either 1..count, or first..last; don't mix them
  -- FOR i IN v_empid.FIRST..v_empid.COUNT
  FOR i IN v_empid.FIRST..v_empid.LAST
  LOOP
    --exp_sp(v_empid(i), v_exp(i));
    -- fixed call to dbms_output
    dbms_output.put_line(v_empid(i) ||': '|| v_exp(i));
  END LOOP;
END;
/
</code>```

which gets:

```<code>101: 28
102: 25
52: -1
100: 30
206: 24

PL/SQL procedure successfully completed.
</code>```

I need not to print the third variable as it is not in the table.

You can test the v_exp value for the magic number (or null, which is safer, but the procedure needs to be modified slightly for that), and only print the results which  you need:

```<code>...
  FOR i IN v_empid.FIRST..v_empid.LAST
  LOOP
    IF v_exp(i) != -1 THEN
      dbms_output.put_line(v_empid(i) ||': '|| v_exp(i));
    END IF;
  END LOOP;
...
</code>```

which gets:

```<code>101: 28
102: 25
100: 30
206: 24

PL/SQL procedure successfully completed.
</code>```

Title: Type Creation and Execution

Body:
I have created a type to print experience of employees from employees table for 5 employees with one incorrect id. I have created an exception to skip it but I am not getting the result for it. What mistake have I done? Please refer my query and tell the error.

CREATE OR REPLACE TYPE emp_id_typ IS TABLE OF NUMBER;
/

CREATE OR REPLACE TYPE emp_exp_typ IS TABLE OF NUMBER;
/

CREATE OR REPLACE PROCEDURE exp_sp ( p_empid   IN  emp_id_typ
                                   , p_exp     OUT emp_exp_typ)
IS
v_exp   NUMBER;
BEGIN
    FOR i IN p_empid.FIRST..p_empid.COUNT
    LOOP
    p_exp.EXTEND;
    SELECT ROUND(MONTHS_BETWEEN(SYSDATE, hire_date)/12) INTO v_exp FROM employees
     WHERE employee_id = p_empid(i);
    p_exp(p_exp.LAST) := v_exp;
    END LOOP;
    EXCEPTION
    WHEN OTHERS THEN
        v_exp := NVL(v_exp, 'NULL');
END exp_sp;
/

DECLARE
    v_empid emp_id_typ := emp_id_typ( );
    v_exp   emp_exp_typ := emp_exp_typ( );
BEGIN
    v_empid := emp_id_typ(101, 102, 52, 100, 206);
    FOR i IN v_empid.FIRST..v_empid.COUNT
    LOOP
    exp_sp(v_empid(i), v_exp(i));
    dbms_output.put_line(v_empid(i), v_exp(i));
    END LOOP;
END;
/

Thanks in advance...

Body:
You have several errors in both the procedure and the anonymous block. In the procedure:

You haven't initialised the OUT p_exp collection. As it's an OUT parameter you have to do it inside the procedure. (Alternatively make it IN OUT).

Your exception handler terminates the loop, so the v_exp you set in there is never used, and the p_exp collection is incomplete. (It's also bad practise to use when others.)

You can't assign a string like ``NULL'` to a number variable or collection. Either assign an a magic number that represents an error to the caller, or leave it null.

CREATE OR REPLACE PROCEDURE exp_sp ( p_empid   IN  emp_id_typ
                                   , p_exp     OUT emp_exp_typ)
IS
  v_exp   NUMBER;
BEGIN
  -- have to initialise p_exp
  p_exp := emp_exp_typ();
  -- better to use either 1..count, or first..last; don't mix them
  --FOR i IN p_empid.FIRST..p_empid.COUNT
  FOR i IN p_empid.FIRST..p_empid.LAST
  LOOP
    p_exp.EXTEND;
    -- you want the exception handler to deal with this row then continue,
    -- so use a nested block
    BEGIN
      SELECT ROUND(MONTHS_BETWEEN(SYSDATE, hire_date)/12) INTO v_exp FROM employees
      WHERE employee_id = p_empid(i);
    EXCEPTION
      WHEN OTHERS THEN
        -- you can't assign a string to a number
        --v_exp := NVL(v_exp, 'NULL');
        -- just an example as not clear what you need
        v_exp := -1;
    END; -- nested block with exception handler
    p_exp(p_exp.LAST) := v_exp;
  END LOOP;
END exp_sp;
/

And in your anonymous block:

The initialisation of v_exp is redundant as the procedure argument is OUT. Not an error but pointless.

You are calling the procedure inside the loop, passing a single element; it should be called once outside the loop and passed the whole collection(s).

Your call to dbms_output.put_line is wrong; that only takes a single argument, so you have to build a string up e.g. with concatenation.

DECLARE
  v_empid emp_id_typ := emp_id_typ( );
  -- assignment is redundant
  -- v_exp   emp_exp_typ := emp_exp_typ( );
  v_exp   emp_exp_typ;
BEGIN
  v_empid := emp_id_typ(101, 102, 52, 100, 206);
  -- moved this call up, without indexing
  exp_sp(v_empid, v_exp);
  -- better to use either 1..count, or first..last; don't mix them
  -- FOR i IN v_empid.FIRST..v_empid.COUNT
  FOR i IN v_empid.FIRST..v_empid.LAST
  LOOP
    --exp_sp(v_empid(i), v_exp(i));
    -- fixed call to dbms_output
    dbms_output.put_line(v_empid(i) ||': '|| v_exp(i));
  END LOOP;
END;
/

which gets:

101: 28
102: 25
52: -1
100: 30
206: 24

PL/SQL procedure successfully completed.

I need not to print the third variable as it is not in the table.

You can test the v_exp value for the magic number (or null, which is safer, but the procedure needs to be modified slightly for that), and only print the results which  you need:

...
  FOR i IN v_empid.FIRST..v_empid.LAST
  LOOP
    IF v_exp(i) != -1 THEN
      dbms_output.put_line(v_empid(i) ||': '|| v_exp(i));
    END IF;
  END LOOP;
...

which gets:

101: 28
102: 25
100: 30
206: 24

PL/SQL procedure successfully completed.


来源: stackexchange

问:
reading all json files and file content in dir and sub dir
I have folder, where json files gets created for every date, and in date for every hours.

I am able to read all the file names by:

```<code>for root, dirs, files in os.walk(rootdir):
    for name in files:
        if name.endswith((".json")):
            print name
</code>```

Root path is /home/ubuntu/Desktop/temp/06-56-10/27
In this path there are sub folder for every hour. This subfolder contains json files.
here, name prints all json file name. But it does not give entire path of the file, so I could not read it.

Any help apprecited

答:
```<code>for root, dirs, files in os.walk(rootdir):
    for name in files:
        if name.endswith((".json")):
            print name
            full_path = os.path.join(root, name)
</code>```

The full path will give you the complete path of the file.

ContentLicense: CC BY-SA 3.0

Body:
I have folder, where json files gets created for every date, and in date for every hours.

I am able to read all the file names by:

for root, dirs, files in os.walk(rootdir):
    for name in files:
        if name.endswith((".json")):
            print name

Root path is /home/ubuntu/Desktop/temp/06-56-10/27
In this path there are sub folder for every hour. This subfolder contains json files.
here, name prints all json file name. But it does not give entire path of the file, so I could not read it.

Any help apprecited

Body:
for root, dirs, files in os.walk(rootdir):
    for name in files:
        if name.endswith((".json")):
            print name
            full_path = os.path.join(root, name)

The full path will give you the complete path of the file.


问:
Hibernate Spring MVC Extremely Slow
I'm building manager web project with Spring MVC , Hibernate and MySQL. When i write the code to list all the regency i have in database. It run very fast in couple first times, but when i reload the page repeatedly (8 - 10 times), my page just keep the loading mode and no sign of stopping. First, i use MSSQL Server then i change to MySQL, nothing changed, i turn off the firewall, still not working.

This my dispatcher-servlet.xml:

```<code><mvc:resources mapping="/resources/**" location="/WEB-INF/resources/" cache-  period="31556926"/>
<mvc:annotation-driven />
<context:component-scan base-package="com.hinet.storage" />

<bean id="viewResolver"
      class="org.springframework.web.servlet.view.UrlBasedViewResolver"
      p:viewClass=" org.springframework.web.servlet.view.tiles3.TilesView"/>

<bean id="tilesConfigurer"
      class="org.springframework.web.servlet.view.tiles3.TilesConfigurer"
      p:definitions="/WEB-INF/tiles/tiles.xml"/>

<bean id="propertyConfigurer"
    class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
  <property name="location" value="/WEB-INF/database.properties" />
</bean>

<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource">
    <property name="driverClassName" value="${jdbc.driverClassName}" />
    <property name="url" value="${jdbc.url}" />
    <property name="username" value="${jdbc.username}" />
    <property name="password" value="${jdbc.password}" />
</bean>

<bean id="sessionFactory" class="org.springframework.orm.hibernate5.LocalSessionFactoryBean">
    <property name="dataSource" ref="dataSource" />
    <property name="packagesToScan" value="com.hinet.storage" />
    <property name="hibernateProperties">
        <props>
            <prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
            <prop key="hibernate.current_session_context_class">thread</prop>
            <prop key="hibernate.show_sql">false</prop>
            <prop key="configurationClass">org.hibernate.cfg.AnnotationConfiguration</prop>
            <prop key="hibernate.format_sql">true</prop>
            <prop key="hibernate.use_sql_comments">true</prop>
            <prop key="hibernate.generate_statistics">true</prop>
        </props>
    </property>
 </bean>
</code>```

And this is RengencyDAOImpl:

```<code>@Repository("regencyDAO")
@Transactional
public class RegencyDAOImpl extends BaseDAOImpl implements RegencyDAO{

    @Override
    public List<Regency> getRegencies() {
        String sql = "from Regency as re where re.isDelete != true";
        Query query = this.openSession().createQuery(sql, Regency.class);
        List<Regency> regencies = query.list();
        return regencies;
    }
}
</code>```

It has given me headache in the past few days! Does anyone know the
  reason that cause this problem?

答:
I think you exhaust your datasource (i.e opening without closing connection).
What does openSession() do? I think it should be something like getCurrentSession().
If you open new session, you should close it.

Title: Hibernate Spring MVC Extremely Slow

Body:
I'm building manager web project with Spring MVC , Hibernate and MySQL. When i write the code to list all the regency i have in database. It run very fast in couple first times, but when i reload the page repeatedly (8 - 10 times), my page just keep the loading mode and no sign of stopping. First, i use MSSQL Server then i change to MySQL, nothing changed, i turn off the firewall, still not working.

This my dispatcher-servlet.xml:

<mvc:resources mapping="/resources/**" location="/WEB-INF/resources/" cache-  period="31556926"/>
<mvc:annotation-driven />
<context:component-scan base-package="com.hinet.storage" />

<bean id="viewResolver"
      class="org.springframework.web.servlet.view.UrlBasedViewResolver"
      p:viewClass=" org.springframework.web.servlet.view.tiles3.TilesView"/>

<bean id="tilesConfigurer"
      class="org.springframework.web.servlet.view.tiles3.TilesConfigurer"
      p:definitions="/WEB-INF/tiles/tiles.xml"/>

<bean id="propertyConfigurer"
    class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
  <property name="location" value="/WEB-INF/database.properties" />
</bean>

<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource">
    <property name="driverClassName" value="${jdbc.driverClassName}" />
    <property name="url" value="${jdbc.url}" />
    <property name="username" value="${jdbc.username}" />
    <property name="password" value="${jdbc.password}" />
</bean>

<bean id="sessionFactory" class="org.springframework.orm.hibernate5.LocalSessionFactoryBean">
    <property name="dataSource" ref="dataSource" />
    <property name="packagesToScan" value="com.hinet.storage" />
    <property name="hibernateProperties">
        <props>
            <prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
            <prop key="hibernate.current_session_context_class">thread</prop>
            <prop key="hibernate.show_sql">false</prop>
            <prop key="configurationClass">org.hibernate.cfg.AnnotationConfiguration</prop>
            <prop key="hibernate.format_sql">true</prop>
            <prop key="hibernate.use_sql_comments">true</prop>
            <prop key="hibernate.generate_statistics">true</prop>
        </props>
    </property>
 </bean>

And this is RengencyDAOImpl:

@Repository("regencyDAO")
@Transactional
public class RegencyDAOImpl extends BaseDAOImpl implements RegencyDAO{

    @Override
    public List<Regency> getRegencies() {
        String sql = "from Regency as re where re.isDelete != true";
        Query query = this.openSession().createQuery(sql, Regency.class);
        List<Regency> regencies = query.list();
        return regencies;
    }
}

It has given me headache in the past few days! Does anyone know the
  reason that cause this problem?


问:
add parameters in ssrs url in report viewer
Hello I have ssrs report and I want to pass parameters within URL is it possible?

report link: http://serverName/reports/reportname

it is possible when I access link like below
http://servername/ReportServer/Pages/ReportViewer.aspx%2fReportName&rs:Command=Render&ParamerterName = abc
but I want to achieve for link  http://serverName/reports/reportname

can someone please help

答:
This is a variant I use. This passes concatenated parameters/one parameter from a cell in Excel to the SSRS report (each parameter separated by "-") and opens the report in another Excel workbook. The SSRS report is coded to split the parameter into its constituent parts.</p>

```<code>http://myserver/Pages/ReportViewer.aspx?%2fMyreports%2fmyfolders%2fmyreport&rs:Command=Render&rs:format=EXCEL&rc:target=_blank&myparam=xxxxx
</code>```

Body:
This is a variant I use. This passes concatenated parameters/one parameter from a cell in Excel to the SSRS report (each parameter separated by "-") and opens the report in another Excel workbook. The SSRS report is coded to split the parameter into its constituent parts.

http://myserver/Pages/ReportViewer.aspx?%2fMyreports%2fmyfolders%2fmyreport&rs:Command=Render&rs:format=EXCEL&rc:target=_blank&myparam=xxxxx


问:
Export Excel range/sheet to formatted text file
I have been tasked with creating a reusable process for our Finance Dept to upload our payroll to the State(WI) for reporting. I need to create something that takes a sheet or range in Excel and creates a specifically formatted text file.

THE FORMAT

Column 1 - A Static Number, never changes, position 1-10

Column 2 - A Dynamic Param filled at runtime for Quarter/Year, position 11-13

Column 3 - SSN, no hyphens or spaces,
filled from column A, position 14-22

Column 4 - Last Name, filled from
column B, Truncated at 10, Left
Justify & fill with blanks, position
23-32

Column 5 - First Name, filled from C,
Truncate at 8, Left Justify & fill
with blanks, position 33-40

Column 6 - Total Gross Wages/Quarter,
filled from D, strip all formatting,
Right Justify Zero Fill, position
41-49

Column 7 - A Static Code, never
changes, position 50-51

Column 8 - BLANKS, Fill with blanks,
position 52-80

I have, I assume, 3 options:

VBA

.NET

SQL

I had explored the .NET method first but I just couldn't find decent documentation to get me going.  I still like this one but I digress.

Next I have some VBA that will dump a Sheet to a fixed width Text.  I am currently pursuing this which leads, finally, to my actual question.

How do I transform a Range of text in Excel?  Do I need to coy it over to another sheet and then pass over that data with the neccesarry formatting functions the run my Dump to text routine?  I currently had planned to have a function for each column but I am having trouble figuring out how to take the next step.  I am fairly new at Office programming and developing in general so any insight will be greatly appreciated.

The SQL option would be my fall back as I have done similar exports from SQL in the past.  I just prefer the other two on the, "I don't want to be responsible for running this," principle.

Thanks in advance for any time given.

答:
Using VBA seems like the way to go to me. This lets you write a macro that takes care of all of the various formatting options and should, hopefully, be simple enough for your finance people to run themselves.

You said you need something that takes a sheet or range in Excel. The first column never changes so we can store that in the macro, columns 3-7 come from the spreadsheet and column 8 is just blank. That leaves column 2 (the quarter/year as QYY) as an issue. If the quarter/year is specified somewhere in the workbook (e.g. stored in a cell, as a worksheet name, as part of the workbook title) then we can just read it in. Otherwise you will need to find some method for specifying the quarter/year when the macro runs (e.g. pop up a dialog box and ask the user to input it)

Some simple code (we'll worry about how to call this later):

```<code>Sub ProduceStatePayrollReportFile(rngPayrollData As Range, strCompanyNo As String, _
    strQuarterYear As String, strRecordCode As String, strOutputFile As String)
</code>```

The parameters are fairly obvious: the range that holds the data, the company number for column 1, the quarter/year for column 2, the fixed code for column 7 and the file we want to output the results to

```<code>' Store the file handle for the output file
Dim fnOutPayrollReport As Integer
' Store each line of the output file
Dim strPayrollReportLine As String
' Use to work through each row in the range
Dim indexRow As Integer
</code>```

To output to a file in VBA we need to get a file handle so we need a variable to store that in. We'll build up each line of the report in the report line string and use the row index to work through the range

```<code>' Store the raw SSN, last name, first name and wages data
Dim strRawSSN As String
Dim strRawLastName As String
Dim strRawFirstName As String
Dim strRawWages As String
Dim currencyRawWages As Currency

' Store the corrected SSN, last name, first name and wages data
Dim strCleanSSN As String
Dim strCleanLastName As String
Dim strCleanFirstName As String
Dim strCleanWages As String
</code>```

These sets of variables store the raw data from the worksheet and the cleaned data to be output to the file respectively. Naming them "raw" and "clean" makes it easier to spot errors where you accidentally output raw data instead of cleaned data. We will need to change the raw wages from a string value to a numeric value to help with the formatting

```<code>' Open up the output file
fnOutPayrollReport = FreeFile()
Open strOutputFile For Output As #fnOutPayrollReport
</code>```

FreeFile() gets the next available file handle and we use that to link to the file

```<code>' Work through each row in the range
For indexRow = 1 To rngPayrollData.Rows.Count
    ' Reset the output report line to be empty
    strPayrollReportLine = ""
    ' Add the company number to the report line (assumption: already correctly formatted)
    strPayrollReportLine = strPayrollReportLine & strCompanyNo
    ' Add in the quarter/year (assumption: already correctly formatted)
    strPayrollReportLine = strPayrollReportLine & strQuarterYear
</code>```

In our loop to work through each row, we start by clearing out the output string and then adding in the values for columns 1 and 2

```<code>' Get the raw SSN data, clean it and append to the report line
strRawSSN = rngPayrollData.Cells(indexRow, 1)
strCleanSSN = cleanFromRawSSN(strRawSSN)
strPayrollReportLine = strPayrollReportLine & strCleanSSN
</code>```

The .Cells(indexRow, 1) part just means the left-most column of the range at the row specified by indexRow. If the ranges starts in column A (which does not have to be the case) then this just means A. We'll need to write the cleanFromRawSSN function ourselves later

```<code>' Get the raw last and first names, clean them and append them
strRawLastName = rngPayrollData.Cells(indexRow, 2)
strCleanLastName = Format(Left$(strRawLastName, 10), "!@@@@@@@@@@")
strPayrollReportLine = strPayrollReportLine & strCleanLastName

strRawFirstName = rngPayrollData.Cells(indexRow, 3)
strCleanFirstName = Format(Left$(strRawFirstName, 8), "!@@@@@@@@")
strPayrollReportLine = strPayrollReportLine & strCleanFirstName
</code>```

Left$(string, length) truncates the string to the given length. The format picture !@@@@@@@@@@ formats a string as exactly ten characters long, left justified (the ! signifies left justify) and padded with spaces

```<code>' Read in the wages data, convert to numeric data, lose the decimal, clean it and append it
strRawWages = rngPayrollData.Cells(indexRow, 4)
currencyRawWages = CCur(strRawWages)
currencyRawWages = currencyRawWages * 100
strCleanWages = Format(currencyRawWages, "000000000")
strPayrollReportLine = strPayrollReportLine & strCleanWages
</code>```

We convert it to currency so that we can multiply by 100 to move the cents value to the left of the decimal point. This makes it much easier to use Format to generate the correct value. This will not produce correct output for wages >= $10 million but that's a limitation of the file format used for reporting. The 0 in the format picture pads with 0s surprisingly enough

```<code>' Append the fixed code for column 7 and the spaces for column 8
strPayrollReportLine = strPayrollReportLine & strRecordCode
strPayrollReportLine = strPayrollReportLine & CStr(String(29, " "))

' Output the line to the file
Print #fnOutPayrollReport, strPayrollReportLine
</code>```

The String(number, char) function produces a Variant with a sequence of number of the specified char. CStr turns the Variant into a string. The Print # statement outputs to the file without any additional formatting

```<code>Next indexRow

' Close the file
Close #fnOutPayrollReport

End Sub
</code>```

Loop round to the next row in the range and repeat. When we have processed all of the rows, close the file and end the macro

We still need two things: a cleanFromRawSSN function and a way to call the macro with the relevant data.

```<code>Function cleanFromRawSSN(strRawSSN As String) As String

' Used to index the raw SSN so we can process it one character at a time
Dim indexRawChar As Integer

' Set the return string to be empty
cleanFromRawSSN = ""

' Loop through the raw data and extract the correct characters
For indexRawChar = 1 To Len(strRawSSN)
    ' Check for hyphen
    If (Mid$(strRawSSN, indexRawChar, 1) = "-") Then
        ' do nothing
    ' Check for space
    ElseIf (Mid$(strRawSSN, indexRawChar, 1) = " ") Then
        ' do nothing
    Else
        ' Output character
        cleanFromRawSSN = cleanFromRawSSN & Mid$(strRawSSN, indexRawChar, 1)
    End If
Next indexRawChar

' Check for correct length and return empty string if incorrect
If (Len(cleanFromRawSSN) <> 9) Then
    cleanFromRawSSN = ""
End If

End Function
</code>```

Len returns the length of a string and Mid$(string, start, length) returns length characters from string beginning at start. This function could be improved as it doesn't currently check for non-numeric data

To call the macro:

```<code>Sub CallPayrollReport()

ProduceStatePayrollReportFile Application.Selection, "1234560007", "109", "01", "C:\payroll109.txt"

End Sub
</code>```

This is the simplest way to call it. The Range is whatever the user has selected on the active worksheet in the active workbook and the other values are hard-coded. The user should select the range they want to output to the file then go Tools > Macro > Run and choose CallPayrollReport. For this to work, the macro would either need to be part of the workbook containg the data or in a different workbook which had been loaded before the user calls the macro.

Someone would need to change the hard-coded value of the quarter/year before each quarter's report was generated. As stated earlier, if the quarter/year is already stored in the workbook somewhere then it's better to read that in rather than hard-coding it

Hope that makes sense and is of some use

ContentLicense: CC BY-SA 2.5

LastEditorDisplayName: Mark Nold

Body:
Using VBA seems like the way to go to me. This lets you write a macro that takes care of all of the various formatting options and should, hopefully, be simple enough for your finance people to run themselves.

You said you need something that takes a sheet or range in Excel. The first column never changes so we can store that in the macro, columns 3-7 come from the spreadsheet and column 8 is just blank. That leaves column 2 (the quarter/year as QYY) as an issue. If the quarter/year is specified somewhere in the workbook (e.g. stored in a cell, as a worksheet name, as part of the workbook title) then we can just read it in. Otherwise you will need to find some method for specifying the quarter/year when the macro runs (e.g. pop up a dialog box and ask the user to input it)

Some simple code (we'll worry about how to call this later):

Sub ProduceStatePayrollReportFile(rngPayrollData As Range, strCompanyNo As String, _
    strQuarterYear As String, strRecordCode As String, strOutputFile As String)

The parameters are fairly obvious: the range that holds the data, the company number for column 1, the quarter/year for column 2, the fixed code for column 7 and the file we want to output the results to

' Store the file handle for the output file
Dim fnOutPayrollReport As Integer
' Store each line of the output file
Dim strPayrollReportLine As String
' Use to work through each row in the range
Dim indexRow As Integer

To output to a file in VBA we need to get a file handle so we need a variable to store that in. We'll build up each line of the report in the report line string and use the row index to work through the range

' Store the raw SSN, last name, first name and wages data
Dim strRawSSN As String
Dim strRawLastName As String
Dim strRawFirstName As String
Dim strRawWages As String
Dim currencyRawWages As Currency

' Store the corrected SSN, last name, first name and wages data
Dim strCleanSSN As String
Dim strCleanLastName As String
Dim strCleanFirstName As String
Dim strCleanWages As String

These sets of variables store the raw data from the worksheet and the cleaned data to be output to the file respectively. Naming them "raw" and "clean" makes it easier to spot errors where you accidentally output raw data instead of cleaned data. We will need to change the raw wages from a string value to a numeric value to help with the formatting

' Open up the output file
fnOutPayrollReport = FreeFile()
Open strOutputFile For Output As #fnOutPayrollReport

FreeFile() gets the next available file handle and we use that to link to the file

' Work through each row in the range
For indexRow = 1 To rngPayrollData.Rows.Count
    ' Reset the output report line to be empty
    strPayrollReportLine = ""
    ' Add the company number to the report line (assumption: already correctly formatted)
    strPayrollReportLine = strPayrollReportLine & strCompanyNo
    ' Add in the quarter/year (assumption: already correctly formatted)
    strPayrollReportLine = strPayrollReportLine & strQuarterYear

In our loop to work through each row, we start by clearing out the output string and then adding in the values for columns 1 and 2

' Get the raw SSN data, clean it and append to the report line
strRawSSN = rngPayrollData.Cells(indexRow, 1)
strCleanSSN = cleanFromRawSSN(strRawSSN)
strPayrollReportLine = strPayrollReportLine & strCleanSSN

The .Cells(indexRow, 1) part just means the left-most column of the range at the row specified by indexRow. If the ranges starts in column A (which does not have to be the case) then this just means A. We'll need to write the cleanFromRawSSN function ourselves later

' Get the raw last and first names, clean them and append them
strRawLastName = rngPayrollData.Cells(indexRow, 2)
strCleanLastName = Format(Left$(strRawLastName, 10), "!@@@@@@@@@@")
strPayrollReportLine = strPayrollReportLine & strCleanLastName

strRawFirstName = rngPayrollData.Cells(indexRow, 3)
strCleanFirstName = Format(Left$(strRawFirstName, 8), "!@@@@@@@@")
strPayrollReportLine = strPayrollReportLine & strCleanFirstName

Left$(string, length) truncates the string to the given length. The format picture !@@@@@@@@@@ formats a string as exactly ten characters long, left justified (the ! signifies left justify) and padded with spaces

' Read in the wages data, convert to numeric data, lose the decimal, clean it and append it
strRawWages = rngPayrollData.Cells(indexRow, 4)
currencyRawWages = CCur(strRawWages)
currencyRawWages = currencyRawWages * 100
strCleanWages = Format(currencyRawWages, "000000000")
strPayrollReportLine = strPayrollReportLine & strCleanWages

We convert it to currency so that we can multiply by 100 to move the cents value to the left of the decimal point. This makes it much easier to use Format to generate the correct value. This will not produce correct output for wages >= $10 million but that's a limitation of the file format used for reporting. The 0 in the format picture pads with 0s surprisingly enough

' Append the fixed code for column 7 and the spaces for column 8
strPayrollReportLine = strPayrollReportLine & strRecordCode
strPayrollReportLine = strPayrollReportLine & CStr(String(29, " "))

' Output the line to the file
Print #fnOutPayrollReport, strPayrollReportLine

The String(number, char) function produces a Variant with a sequence of number of the specified char. CStr turns the Variant into a string. The Print # statement outputs to the file without any additional formatting

Next indexRow

' Close the file
Close #fnOutPayrollReport

End Sub

Loop round to the next row in the range and repeat. When we have processed all of the rows, close the file and end the macro

We still need two things: a cleanFromRawSSN function and a way to call the macro with the relevant data.

Function cleanFromRawSSN(strRawSSN As String) As String

' Used to index the raw SSN so we can process it one character at a time
Dim indexRawChar As Integer

' Set the return string to be empty
cleanFromRawSSN = ""

' Loop through the raw data and extract the correct characters
For indexRawChar = 1 To Len(strRawSSN)
    ' Check for hyphen
    If (Mid$(strRawSSN, indexRawChar, 1) = "-") Then
        ' do nothing
    ' Check for space
    ElseIf (Mid$(strRawSSN, indexRawChar, 1) = " ") Then
        ' do nothing
    Else
        ' Output character
        cleanFromRawSSN = cleanFromRawSSN & Mid$(strRawSSN, indexRawChar, 1)
    End If
Next indexRawChar

' Check for correct length and return empty string if incorrect
If (Len(cleanFromRawSSN) <> 9) Then
    cleanFromRawSSN = ""
End If

End Function

Len returns the length of a string and Mid$(string, start, length) returns length characters from string beginning at start. This function could be improved as it doesn't currently check for non-numeric data

To call the macro:

Sub CallPayrollReport()

ProduceStatePayrollReportFile Application.Selection, "1234560007", "109", "01", "C:\payroll109.txt"

End Sub

This is the simplest way to call it. The Range is whatever the user has selected on the active worksheet in the active workbook and the other values are hard-coded. The user should select the range they want to output to the file then go Tools > Macro > Run and choose CallPayrollReport. For this to work, the macro would either need to be part of the workbook containg the data or in a different workbook which had been loaded before the user calls the macro.

Someone would need to change the hard-coded value of the quarter/year before each quarter's report was generated. As stated earlier, if the quarter/year is already stored in the workbook somewhere then it's better to read that in rather than hard-coding it

Hope that makes sense and is of some use

OwnerDisplayName: barrowc


问:
Android opengles 2d culling
Anyone have links to tutorials on this topic? I cannot seem to find any related to 2d culling. Or if anyone here could explain how it's done. I use gluOrtho2D and gluLookAt currently.</p>

答: If you mean geometry culling, then wouldn't it be just as simple as checking if the polygon you are drawing lies outside of the rectangle defined by your gluOrtho2D and gluLookAt? If it's outside, then don't draw it.</p>

Title: Android opengles 2d culling


问:
ResultSet Meta data return TimeStamp instead of Date Oracle JDBC
I Have a Table WRITE_DATE_DATA having column DATE_DATA (DATE type) and TIMESTAMP_DATA (TIMESTAMP(6) Type).

When I am executing:

```<code>ResultSet rsmeta = ps.executeQuery("Select DATE_DATA,TIMESTAMP_DATA from WRITE_DATE_DATA")
ResultSetMetaData rsmeta = resultSet.getMetaData()  ;
int imax = rsmeta.getColumnCount() ;
HashMap<String, Integer> hmRsColTypes = new HashMap<String, Integer>();
for ( int ii = 0 ; ii < imax ; ii++ )
{
  String strColumn = rsmeta.getColumnName(ii+1);
  System.out.println(rsmeta.getColumnType(ii+1));// line 1
  System.out.println(rsmeta.getColumnType(ii+1));// line 2
}
</code>```

Output:

at line 1 - TIMESTAMP_DATA

at line 2 -93 Type for java.sql.TimeStamp

at line 1 -     DATE_DATA

at line one - 93 Type for java.sql.TimeStamp

Expected data type for DATE_DATE will be 91 Type for java.sql.Date

Why is ResultSetMetaData returning the wrong data type TimeStamp instead of Date data type?

Is this expected behavior, if yes then please share document or should i do something else to handle it.

答:
The output shown is correct. An Oracle DATE is a java.sql.Timestamp (java.sql.Types.TIMESTAMP) as far as JDBC (and the SQL standard) is concerned as it has both a date and time component.

An Oracle DATE is simply not a date as defined in JDBC and the SQL standard. Use of java.sql.Date (and java.sql.Types.DATE) is for types that have only a date component (day, month, year).

See also: Difference between oracle DATE and TIMESTAMP

Body:
I Have a Table WRITE_DATE_DATA having column DATE_DATA (DATE type) and TIMESTAMP_DATA (TIMESTAMP(6) Type).

When I am executing:

ResultSet rsmeta = ps.executeQuery("Select DATE_DATA,TIMESTAMP_DATA from WRITE_DATE_DATA")
ResultSetMetaData rsmeta = resultSet.getMetaData()  ;
int imax = rsmeta.getColumnCount() ;
HashMap<String, Integer> hmRsColTypes = new HashMap<String, Integer>();
for ( int ii = 0 ; ii < imax ; ii++ )
{
  String strColumn = rsmeta.getColumnName(ii+1);
  System.out.println(rsmeta.getColumnType(ii+1));// line 1
  System.out.println(rsmeta.getColumnType(ii+1));// line 2
}

Output:

at line 1 - TIMESTAMP_DATA

at line 2 -93 Type for java.sql.TimeStamp

at line 1 -     DATE_DATA

at line one - 93 Type for java.sql.TimeStamp

Expected data type for DATE_DATE will be 91 Type for java.sql.Date

Why is ResultSetMetaData returning the wrong data type TimeStamp instead of Date data type?

Is this expected behavior, if yes then please share document or should i do something else to handle it.


问:
Owl Carousel AutoPlayTimeout Does Not Scroll Smoothly
I'm having a bit of an issue getting the autoplayTimeout to scroll smoothly on the page.  It stops after it loads the first 5 images and scrolls the next one in and it is very jerky.  You can see an example here at the bottom of the page .

Here are my settings within the javascript:

```<code><script type="text/javascript">
        $(document).ready(function() {
            $("#owl-demo").owlCarousel({
                autoplay: true,
                items: 5,
                autoplayHoverPause: true,
                autoplayTimeout: 10,
                autoplaySpeed: 1000,
                fluidSpeed:true,
                itemsDesktop : [1199,3],
                itemsDesktopSmall: [979,3],
                itemsMobile: [479,1],
                navigation: false,
                dots: false,
                loop: true
                });

        });

    </script>
</code>```

I'm not sure if I'm using the right combination of settings.

答:
Using smartSpeed property :

```<code>$("#owl-demo").owlCarousel({ autoplay: true, smartSpeed: 2500 });
</code>```

Body:
I'm having a bit of an issue getting the autoplayTimeout to scroll smoothly on the page.  It stops after it loads the first 5 images and scrolls the next one in and it is very jerky.  You can see an example here at the bottom of the page .

Here are my settings within the javascript:

I'm not sure if I'm using the right combination of settings.

Body:
Using smartSpeed property :

$("#owl-demo").owlCarousel({ autoplay: true, smartSpeed: 2500 });


问:
Hamburger Icon Not showing
When I use to change Hamburger Icon to Back Icon while add a new fragment it's Perfectly working. Here is my code

```<code>supportActionBar!!.setDisplayHomeAsUpEnabled(true)
supportActionBar!!.setDisplayShowHomeEnabled(true)
</code>```

But when I press back button and close the fragment then it not change to hamburger icon

```<code>supportActionBar!!.setDisplayHomeAsUpEnabled(false)
supportActionBar!!.setDisplayShowHomeEnabled(false)
</code>```

NOTE: I dont have drawer layout. I use this library: yarolegovich/SlidingRootNav

答:
This is expected behaviour, it won't automatically change when you are doing:
actionBar.setDisplayHomeAsUpEnabled(true);

One solution would be to handle it for yourself. Just change the icon manually

actionBar.setDisplayHomeAsUpEnabled(true);
actionBar.setHomeAsUpIndicator(R.drawable.back);

and on back pressed, change it to hamburger icon:

actionBar.setDisplayHomeAsUpEnabled(true);
actionBar.setHomeAsUpIndicator(R.drawable.hamburger_icon);

Hope this helps. Cheers.

Title: Hamburger Icon Not showing

Body:
When I use to change Hamburger Icon to Back Icon while add a new fragment it's Perfectly working. Here is my code

supportActionBar!!.setDisplayHomeAsUpEnabled(true)
supportActionBar!!.setDisplayShowHomeEnabled(true)

But when I press back button and close the fragment then it not change to hamburger icon

supportActionBar!!.setDisplayHomeAsUpEnabled(false)
supportActionBar!!.setDisplayShowHomeEnabled(false)

NOTE: I dont have drawer layout. I use this library: yarolegovich/SlidingRootNav


问:
Angular Service and HttpClient Type does not exist
I am trying to get a service working in Angular 5. This is what I have:

```<code>import { Injectable } from '@angular/core';

@Injectable()
export class DataService {

  constructor() { }

  getData() {
    // don't use 'any', type your data instead!
    return this.httpClient.get<any>('./assets/data.json');
  }

}
</code>```

I'm getting the following error:

Property HttpClient does not exist on type DataService.

What am I missing?

答:
Try like this :

readmore about httpClient here

```<code>import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';

@Injectable()
export class DataService {

  constructor(private httpClient: HttpClient) { }

  getData() {
    // don't use 'any', type your data instead!
    return this.httpClient.get<any>('./assets/data.json');
  }

}
</code>```

Body:
I am trying to get a service working in Angular 5. This is what I have:

import { Injectable } from '@angular/core';

@Injectable()
export class DataService {

  constructor() { }

  getData() {
    // don't use 'any', type your data instead!
    return this.httpClient.get<any>('./assets/data.json');
  }

}

I'm getting the following error:

Property HttpClient does not exist on type DataService.

What am I missing?

Body:
Try like this :

readmore about httpClient here

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';

@Injectable()
export class DataService {

  constructor(private httpClient: HttpClient) { }

  getData() {
    // don't use 'any', type your data instead!
    return this.httpClient.get<any>('./assets/data.json');
  }

}


问:
Is loop a good choice instead of what I have created?
I am learning JS by my own and I have created first little script :). Script is counting the number of signs for the tag tittle of a webpage to be between 50 and 60 etc.... Below there is one button that resets all the data in the script and its working 100% but I have a question -  Can I use some kind of loop instead of that code that I have created? A loop that will be reseting all elements below. Thx for Your help :) and advice...</p>

```<code>// reset Title tag check
document.getElementById("resetTitleBtn").addEventListener("click", function(){
  document.getElementById('inputTitleTag').value = "";
  document.getElementById('titleTag').innerHTML = "";
  document.getElementById('example').innerHTML = "";
  document.getElementById("tytul").style.color = "";
  document.getElementById("good").innerHTML = "";
});
</code>```

答:
You might consider using classes to identify different elements requiring common initialization and select them that way.

```<code>var resetValueEls     = document.getElementsByClassName('initValue');
var resetInnerHTMLEls = document.getElementsByClassName('initInnerHTML');
var resetColorEls     = document.getElementsByClassName('initColor');

Array.prototype.forEach.call(resetValueEls,     function(x) {x.value     = ""})
Array.prototype.forEach.call(resetInnerHTMLEls, function(x) {x.innerHTML = ""})
Array.prototype.forEach.call(resetColorEls,     function(x) {x.style.color = ""})
</code>```

then, each HTML tag that requires initialization gets a class or combination thereof e.g.
.

The benefit of this strategy is that if you have many tags to initialize, despite having many ids, you have a small number of classes to keep track of in your initializer.

Body:
I am learning JS by my own and I have created first little script :). Script is counting the number of signs for the tag tittle of a webpage to be between 50 and 60 etc.... Below there is one button that resets all the data in the script and its working 100% but I have a question -  Can I use some kind of loop instead of that code that I have created? A loop that will be reseting all elements below. Thx for Your help :) and advice...

// reset Title tag check
document.getElementById("resetTitleBtn").addEventListener("click", function(){
  document.getElementById('inputTitleTag').value = "";
  document.getElementById('titleTag').innerHTML = "";
  document.getElementById('example').innerHTML = "";
  document.getElementById("tytul").style.color = "";
  document.getElementById("good").innerHTML = "";
});

Body:
You might consider using classes to identify different elements requiring common initialization and select them that way.

var resetValueEls     = document.getElementsByClassName('initValue');
var resetInnerHTMLEls = document.getElementsByClassName('initInnerHTML');
var resetColorEls     = document.getElementsByClassName('initColor');

Array.prototype.forEach.call(resetValueEls,     function(x) {x.value     = ""})
Array.prototype.forEach.call(resetInnerHTMLEls, function(x) {x.innerHTML = ""})
Array.prototype.forEach.call(resetColorEls,     function(x) {x.style.color = ""})

then, each HTML tag that requires initialization gets a class or combination thereof e.g. <DIV class="initInnerHTML initColor"/>.

The benefit of this strategy is that if you have many tags to initialize, despite having many ids, you have a small number of classes to keep track of in your initializer.


问:
Statsmodel Probplot Tick customization
I've created a cumulative probability plot with StatsModels in Python, but there are way too many ticks on the axis.

I want there to be only be tick marks at 0.1, 10, 50, 90, 99, and 99.9. Anyone know how to make this work? I tried using the code below but it only gives me the first n number of ticks, making it pretty useless (See figure below.)

```<code>import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
import matplotlib.ticker as ticker
import statsmodels.api as sm

csv = pd.read_csv('cumProbMaxData.csv')
data = csv.values.tolist()

flat_list = [item for sublist in data for item in sublist]
fig,ax = plt.subplots()

x = np.array(flat_list)
pp_x = sm.ProbPlot(x, fit=True)
figure = pp_x.probplot(exceed=False, ax=ax, marker='.', color='k', markersize=12)

plt.xlabel('Cumulative Probability (%)')
plt.ylabel('Maximum CO$_2$ Flux (g m$^-$$^2$ d$^-$$^1$)')
tick_spacing=5
ax.xaxis.set_major_locator(ticker.MaxNLocator(tick_spacing))

plt.tight_layout()
plt.show()
</code>```

答:
Statsmodels ProbPlot plots the data in their real units. It is only the axes ticks which are then changed as to show some percentage value. This is in general bad style but of course you have to live with it if you want to use ProbPlot.

A solution for the problem of showing less ticks on such a plot which uses a FixedLocator and FixedFormatter would be to subsample the shown ticks. The ticklabels you want to show are at indices locs = [0,3,6,10,14,17,20] (you want to show the ticklabel 0, 3, 6, etc.).
You can use this list to select from the shown ticks only those in the list as shown below.

```<code>import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
import statsmodels.api as sm

x = np.random.randn(200)

fig,ax = plt.subplots()

pp_x = sm.ProbPlot(x, fit=True)
pp_x.probplot(exceed=False, ax=ax, marker='.', color='k', markersize=12)

locs = [0,3,6,10,14,17,20]
ax.set_xticklabels(np.array(ax.xaxis.get_major_formatter().seq)[locs])
ax.set_xticks(ax.get_xticks()[locs])

plt.tight_layout()
plt.show()
</code>```

Title: Statsmodel Probplot Tick customization

Body:
I've created a cumulative probability plot with StatsModels in Python, but there are way too many ticks on the axis.

I want there to be only be tick marks at 0.1, 10, 50, 90, 99, and 99.9. Anyone know how to make this work? I tried using the code below but it only gives me the first n number of ticks, making it pretty useless (See figure below.)

import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
import matplotlib.ticker as ticker
import statsmodels.api as sm

csv = pd.read_csv('cumProbMaxData.csv')
data = csv.values.tolist()

flat_list = [item for sublist in data for item in sublist]
fig,ax = plt.subplots()

x = np.array(flat_list)
pp_x = sm.ProbPlot(x, fit=True)
figure = pp_x.probplot(exceed=False, ax=ax, marker='.', color='k', markersize=12)

plt.xlabel('Cumulative Probability (%)')
plt.ylabel('Maximum CO$_2$ Flux (g m$^-$$^2$ d$^-$$^1$)')
tick_spacing=5
ax.xaxis.set_major_locator(ticker.MaxNLocator(tick_spacing))

plt.tight_layout()
plt.show()

Body:
Statsmodels ProbPlot plots the data in their real units. It is only the axes ticks which are then changed as to show some percentage value. This is in general bad style but of course you have to live with it if you want to use ProbPlot.

A solution for the problem of showing less ticks on such a plot which uses a FixedLocator and FixedFormatter would be to subsample the shown ticks. The ticklabels you want to show are at indices locs = [0,3,6,10,14,17,20] (you want to show the ticklabel 0, 3, 6, etc.).
You can use this list to select from the shown ticks only those in the list as shown below.

import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
import statsmodels.api as sm

x = np.random.randn(200)

fig,ax = plt.subplots()

pp_x = sm.ProbPlot(x, fit=True)
pp_x.probplot(exceed=False, ax=ax, marker='.', color='k', markersize=12)

locs = [0,3,6,10,14,17,20]
ax.set_xticklabels(np.array(ax.xaxis.get_major_formatter().seq)[locs])
ax.set_xticks(ax.get_xticks()[locs])

plt.tight_layout()
plt.show()


问:
Quotation marks not shown on display
In my string xml file I have a line like this:

```<code><string name="infoHeader">random "text" here</string>
</code>```

But it is only displayed as

random text here

on the phone's display, that is, without the quotation marks.

I read about it via Google, and tried some HTML styling:

```<code><string name="infoHeader">random "text" here</string>
</code>```

And then used:

```<code>String hej = res.getString(R.string.infoHeader);
Spanned marked_up = Html.fromHtml(hej);
((TextView)findViewById(R.id.infoHeader)).setText(marked_up, BufferType.SPANNABLE);
</code>```

But it still doesn't work. I tried some other HTML, like text, and that works just fine. What's wrong?

答:
I'm not sure what's going on, but I tried a few other ways of escaping.

This worked for me:

```<code><string name="hello">Hello \"World,\" ActivityHello!</string>
</code>```

Title: Quotation marks not shown on display

Body:
In my string xml file I have a line like this:

<string name="infoHeader">random "text" here</string>

But it is only displayed as

random text here

on the phone's display, that is, without the quotation marks.

I read about it via Google, and tried some HTML styling:

<string name="infoHeader">random "text" here</string>

And then used:

String hej = res.getString(R.string.infoHeader);
Spanned marked_up = Html.fromHtml(hej);
((TextView)findViewById(R.id.infoHeader)).setText(marked_up, BufferType.SPANNABLE);

But it still doesn't work. I tried some other HTML, like text, and that works just fine. What's wrong?

Body:
I'm not sure what's going on, but I tried a few other ways of escaping.

This worked for me:

<string name="hello">Hello \"World,\" ActivityHello!</string>


问:
How to group jquery array
I have two arrays that I need to merge together, they look like so:

```<code>var array1 =
[
  {x: "1/12/2011", y: 4149.9}
  {x: "2/12/2011", y: 4094.5}
  {x: "3/12/2011", y: 3606.8}
]
</code>```

and

```<code>var array2 =
[
  {x: "1/12/2011", z: 3500}
  {x: "2/12/2011", z: 3600}
  {x: "3/12/2011", z: 3700}
]
</code>```

I would like to merge them based on x where all properties are kept in the final object.

Expected output:

```<code>var excpected =
[
  {x: "1/12/2011", y: 4149.9, z: 3500}
  {x: "2/12/2011", y: 4094.5, z: 3600}
  {x: "3/12/2011", y: 3606.8, z: 3700}
]
</code>```

I've found $.extend and $.merge but haven't managed to successfully achieve what I need.  Any pointers?

Title: How to group jquery array

Body:
I have two arrays that I need to merge together, they look like so:

var array1 =
[
  {x: "1/12/2011", y: 4149.9}
  {x: "2/12/2011", y: 4094.5}
  {x: "3/12/2011", y: 3606.8}
]

and

var array2 =
[
  {x: "1/12/2011", z: 3500}
  {x: "2/12/2011", z: 3600}
  {x: "3/12/2011", z: 3700}
]

I would like to merge them based on x where all properties are kept in the final object.

Expected output:

var excpected =
[
  {x: "1/12/2011", y: 4149.9, z: 3500}
  {x: "2/12/2011", y: 4094.5, z: 3600}
  {x: "3/12/2011", y: 3606.8, z: 3700}
]

I've found $.extend and $.merge but haven't managed to successfully achieve what I need.  Any pointers?

Body:
Use Object.assign and array.prototype.map:

var array1 =
[
  {x: "1/12/2011", y: 4149.9},
  {x: "2/12/2011", y: 4094.5},
  {x: "3/12/2011", y: 3606.8}
];

var array2 =
[
  {x: "1/12/2011", z: 3500},
  {x: "2/12/2011", z: 3600},
  {x: "3/12/2011", z: 3700}
]

var merged = array1.map((e, index) => Object.assign({}, e, array2.find(a => a.x === e.x)));

console.log(merged);


问:
Binding only part of a label
How would one achieve mixing bound values with constant text in a WPF bound control?

For example, say I have a form displaying orders, and I want a label that displays text like "Order ID 1234".

I've tried things like:

```<code>text="Order ID {Binding ....}"
</code>```

Is this achievable, or do I have to do something like having more than one label in a flow control?

答:
I found another one approach. @Inferis's solution doesn't work for me and @LPCRoy's isn't elegant for me:

```<code><Label Content="{Binding Path=Order.ID, FallbackValue=Placeholder}" ContentStringFormat="Order ID {0}">
</code>```

It's my favourite at this moment, it's seems flexible and condensed.

OwnerDisplayName: Neil Barnwell

Title: Binding only part of a label

Body:
How would one achieve mixing bound values with constant text in a WPF bound control?

For example, say I have a form displaying orders, and I want a label that displays text like "Order ID 1234".

I've tried things like:

text="Order ID {Binding ....}"

Is this achievable, or do I have to do something like having more than one label in a flow control?

Body:
I found another one approach. @Inferis's solution doesn't work for me and @LPCRoy's isn't elegant for me:

<Label Content="{Binding Path=Order.ID, FallbackValue=Placeholder}" ContentStringFormat="Order ID {0}">

It's my favourite at this moment, it's seems flexible and condensed.


问:
d3.on("mouseover") event does not work with nested SVG elements
I have a nested set of  elements (SVG). The root element is the graph, and the children are elements in the graph (lines, axis, etc.). Simplified example:

```<code><g transform="translate(80,10)" id="mainGraph">
    <g class="Line">
        <path d="....."></path>
    </g>
</g>
</code>```

My problem is that if I bind a mouseover/mousemove event (with D3.on("mouseover") for example) to the mainGraph element, it only triggers if I move the mouse over one of the child elements.

One of the things I read is that there is priority of later elements, so I added .style("pointer-events","none") to all child elements, but that didn't work.

答:
I also face the same problems.

The solution is to add the css property to parent element

```<code>pointer-events: stroke;
</code>```

or

```<code>pointer-events: visibleStroke;
</code>```

Body:
I have a nested set of  elements (SVG). The root element is the graph, and the children are elements in the graph (lines, axis, etc.). Simplified example:

<g transform="translate(80,10)" id="mainGraph">
    <g class="Line">
        <path d="....."></path>
    </g>
</g>

My problem is that if I bind a mouseover/mousemove event (with D3.on("mouseover") for example) to the mainGraph element, it only triggers if I move the mouse over one of the child elements.

One of the things I read is that there is priority of later elements, so I added .style("pointer-events","none") to all child elements, but that didn't work.

Body:
I also face the same problems.

The solution is to add the css property to parent element

pointer-events: stroke;

or

pointer-events: visibleStroke;


问:
how to solve android.content.res.Resources$NotFoundException: File res/drawable/ic_paper_plane.xml from drawable resource ID #0x7f02008f?
I know this question is asking many time but i tried all of that but nothing meet my requirement i used  android:drawableLeft attribute in XML file for showing vector image in my button and its running on above API 21 but if i am running on same code in below API 21 like 19 then app got crashed, i am already add vectorDrawables.useSupportLibrary = true , and AppCompatDelegate.setCompatVectorFromResourcesEnabled(true); but both not work for me can any one help me out of this,my xml code is:

```<code><android.support.v7.widget.AppCompatButton
      android:id="@+id/shduleSms"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:drawableLeft="@drawable/ic_shedule_sms"
      android:drawablePadding="5dip"
      app:layout_constraintTop_toBottomOf="@+id/textConCount"
      android:padding="15dp"
      android:layout_marginEnd="30dp"
      android:layout_marginRight="30dp"
      app:layout_constraintRight_toRightOf="@+id/textConCount"
      android:layout_marginTop="15dp"
      android:text="@string/sendlater"
      android:textColor="@color/white"
      android:theme="@style/MyButtonTwo"
      />
</code>```

答: This error mostly occurrs due to a corrupt or unknown file. Please share your drawable source code if using an xml(vector).</p>

Body:
I know this question is asking many time but i tried all of that but nothing meet my requirement i used  android:drawableLeft attribute in XML file for showing vector image in my button and its running on above API 21 but if i am running on same code in below API 21 like 19 then app got crashed, i am already add vectorDrawables.useSupportLibrary = true , and AppCompatDelegate.setCompatVectorFromResourcesEnabled(true); but both not work for me can any one help me out of this,my xml code is:

<android.support.v7.widget.AppCompatButton
      android:id="@+id/shduleSms"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:drawableLeft="@drawable/ic_shedule_sms"
      android:drawablePadding="5dip"
      app:layout_constraintTop_toBottomOf="@+id/textConCount"
      android:padding="15dp"
      android:layout_marginEnd="30dp"
      android:layout_marginRight="30dp"
      app:layout_constraintRight_toRightOf="@+id/textConCount"
      android:layout_marginTop="15dp"
      android:text="@string/sendlater"
      android:textColor="@color/white"
      android:theme="@style/MyButtonTwo"
      />


问:
mysqlpump without database prefix
The tool mysqlpump prepends every table action with the database name like so:

```<code>INSERT INTO `database`.`table` --
</code>```

This makes the export rather limited in use. Is there a way to skip the database prefix? It would make sense, as I'm observing the many situations in which it is a limitation rather than a feature.

Attempted workarounds:

Not having figured out a sane way to do this, I've tried a dirty sed hack on the export:

```<code>sed -e "s/\`$DB\`.//g"
</code>```

This works nicely on small exports. However, on more complex databases, this will eventually cause errors. Apparently the back-ticked database cannot be reliably used as a string used exclusively as a statement prefix.

See also:

mysqlpump options

答:
which options do you use for mysqldump? By default, there's no database name prefix before the table name.
  E.g. mysqldump -uxx -pxxx -h xxx -P xxx --all-databases > db.sql

  mysqldump -uxx -pxxx -h xxx -P xxx db table > table.sql

Title: mysqlpump without database prefix

Body:
The tool mysqlpump prepends every table action with the database name like so:

INSERT INTO `database`.`table` --

This makes the export rather limited in use. Is there a way to skip the database prefix? It would make sense, as I'm observing the many situations in which it is a limitation rather than a feature.

Attempted workarounds:

Not having figured out a sane way to do this, I've tried a dirty sed hack on the export:

sed -e "s/\`$DB\`.//g"

This works nicely on small exports. However, on more complex databases, this will eventually cause errors. Apparently the back-ticked database cannot be reliably used as a string used exclusively as a statement prefix.

See also:

mysqlpump options


问:
Use of eval with div
I am new to asp.net and I wanted to know that is it possible to create any number of div dynamically with the use of "eval" if yes, then how?
I guess somehow like this

<div id=<%# Eval("UnitName") %>>

答:
You can use it. But you need to make sure not to use multiple div with same id, which is UnitName in your case. If you will use same UnitName with multiple div elements it will generate error. It must be unique.

```<code><div id='<%# Eval("UnitName") %>'>
</code>```

Element IDs should be unique within the entire document.

Title: Use of eval with div

Body:
You can use it. But you need to make sure not to use multiple div with same id, which is UnitName in your case. If you will use same UnitName with multiple div elements it will generate error. It must be unique.

<div id='<%# Eval("UnitName") %>'>

Element IDs should be unique within the entire document.


Title: How to group jquery array

Body:
Just use map method in combination with Object.assign

var array1 =
[
  {x: "1/12/2011", y: 4149.9},
  {x: "2/12/2011", y: 4094.5},
  {x: "3/12/2011", y: 3606.8}
]
var array2 =
[
  {x: "1/12/2011", z: 3500},
  {x: "2/12/2011", z: 3600},
  {x: "3/12/2011", z: 3700}
]
var expected = array1.map( (a,i) => Object.assign(a, array2.find(b=>b.x == a.x)));
console.log(expected);


问:
Int getting converted to double while trying to save to the db

I'm trying to save a simple form but the int value is getting turned into a double. Example: I enter the value 87, click Save, and the value gets turned into 87,00.

"" must be a number between - and +.

My jsf code for this input:

```<code><t:inputNumber label="hr.label.LeaveDay" value="#{employeeLeaveHome.entity.leaveDay}" columnClass="col-xs-6" required="true"/>
</code>```

I need it so it stays as the value I've put in. Ex: 87. I don't know why it's showing this behavior. It's defined as an int in the model.

答:
Default is to display two decimal places. Either configure it differently or do:

```<code><t:inputNumber label="hr.label.LeaveDay" value="#{employeeLeaveHome.entity.leaveDay}"
    decimalPlaces="0"/>
</code>```

So it is a displaying issue.

Body:
I'm trying to save a simple form but the int value is getting turned into a double. Example: I enter the value 87, click Save, and the value gets turned into 87,00.

"" must be a number between - and +.

My jsf code for this input:

<t:inputNumber label="hr.label.LeaveDay" value="#{employeeLeaveHome.entity.leaveDay}" columnClass="col-xs-6" required="true"/>

I need it so it stays as the value I've put in. Ex: 87. I don't know why it's showing this behavior. It's defined as an int in the model.

Body:
Default is to display two decimal places. Either configure it differently or do:

<t:inputNumber label="hr.label.LeaveDay" value="#{employeeLeaveHome.entity.leaveDay}"
    decimalPlaces="0"/>

So it is a displaying issue.


问:
Add animation delay to li automatically
I have a slideshow with CSS3 which have animation-delay in each child,
but this is not dynamic because for each tag I should add nth-child ,

Is there any way to add animation-delay automatically to li tags?

this is CSS code:

```<code>.cb-slideshow li:nth-child(2) span {
  -webkit-animation-delay: 6s;
  -moz-animation-delay: 6s;
  -o-animation-delay: 6s;
  -ms-animation-delay: 6s;
  animation-delay: 6s;
}

.cb-slideshow li:nth-child(3) span {
  -webkit-animation-delay: 12s;
  -moz-animation-delay: 12s;
  -o-animation-delay: 12s;
  -ms-animation-delay: 12s;
  animation-delay: 12s;
}

.cb-slideshow li:nth-child(4) span {
  -webkit-animation-delay: 18s;
  -moz-animation-delay: 18s;
  -o-animation-delay: 18s;
  -ms-animation-delay: 18s;
  animation-delay: 18s;
}

.cb-slideshow li:nth-child(5) span {
  -webkit-animation-delay: 24s;
  -moz-animation-delay: 24s;
  -o-animation-delay: 24s;
  -ms-animation-delay: 24s;
  animation-delay: 24s;
}

.cb-slideshow li:nth-child(6) span {
  -webkit-animation-delay: 30s;
  -moz-animation-delay: 30s;
  -o-animation-delay: 30s;
  -ms-animation-delay: 30s;
  animation-delay: 30s;
}
</code>```

I want to change this code to add 6s delay to each tags.

答:
There is no way to handle it dynamically except adding inline style dynamically or with javascript

for example

.cb-slideshow li {
  animation: FadeIn 1s linear;
  animation-fill-mode: both;
}

@keyframes FadeIn {
  0% {
    opacity: 0;
    transform: scale(.1);
  }
  85% {
    opacity: 1;
    transform: scale(1.05);
  }
  100% {
    transform: scale(1);
  }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="cb-slideshow">
  <li style="animation-delay: 1s;">test text</li>
  <li style="animation-delay: 2s;">test text</li>
  <li style="animation-delay: 3s;">test text</li>
  <li style="animation-delay: 4s;">test text</li>
  <li style="animation-delay: 5s;">test text</li>
</div></code>```

Title: Add animation delay to li automatically

Body:
I have a slideshow with CSS3 which have animation-delay in each child,
but this is not dynamic because for each tag I should add nth-child ,

Is there any way to add animation-delay automatically to li tags?

this is CSS code:

.cb-slideshow li:nth-child(2) span {
  -webkit-animation-delay: 6s;
  -moz-animation-delay: 6s;
  -o-animation-delay: 6s;
  -ms-animation-delay: 6s;
  animation-delay: 6s;
}

.cb-slideshow li:nth-child(3) span {
  -webkit-animation-delay: 12s;
  -moz-animation-delay: 12s;
  -o-animation-delay: 12s;
  -ms-animation-delay: 12s;
  animation-delay: 12s;
}

.cb-slideshow li:nth-child(4) span {
  -webkit-animation-delay: 18s;
  -moz-animation-delay: 18s;
  -o-animation-delay: 18s;
  -ms-animation-delay: 18s;
  animation-delay: 18s;
}

.cb-slideshow li:nth-child(5) span {
  -webkit-animation-delay: 24s;
  -moz-animation-delay: 24s;
  -o-animation-delay: 24s;
  -ms-animation-delay: 24s;
  animation-delay: 24s;
}

.cb-slideshow li:nth-child(6) span {
  -webkit-animation-delay: 30s;
  -moz-animation-delay: 30s;
  -o-animation-delay: 30s;
  -ms-animation-delay: 30s;
  animation-delay: 30s;
}

I want to change this code to add 6s delay to each tags.

Body:
There is no way to handle it dynamically except adding inline style dynamically or with javascript

for example

.cb-slideshow li {
  animation: FadeIn 1s linear;
  animation-fill-mode: both;
}

@keyframes FadeIn {
  0% {
    opacity: 0;
    transform: scale(.1);
  }
  85% {
    opacity: 1;
    transform: scale(1.05);
  }
  100% {
    transform: scale(1);
  }
}

<div class="cb-slideshow">
  <li style="animation-delay: 1s;">test text</li>
  <li style="animation-delay: 2s;">test text</li>
  <li style="animation-delay: 3s;">test text</li>
  <li style="animation-delay: 4s;">test text</li>
  <li style="animation-delay: 5s;">test text</li>
</div>


问:
Which Perl web framework should I use?
I would like to develop a web application using Perl.

Refer some Perl package (like Strawberry) which is simple to install. Also it should be suitable for the web application.

答:
Embperl is still being maintained, although it is kinda quiet on the mailing list.

Embperl might be an option for small sites.

It is conceptually similar to PHP, but more powerful. Fast (due to lots of C bindings), still easy to install (preferably from command line), works best with mod_perl, but a CGI operating mode is also supported.

Though, I haven't used all its advanced features (embedding xml-libs, configuring https, for instance), but it is great to use perl on the data-output side, when you have perl also on the data input side (data staging/scrubbing).

Title: Which Perl web framework should I use?


问:
identifier expected in jfreechart
I am new to JFreecharts in java.Am trying execute the code for piechart but its giving error "identifier expected and illegal start of expression".can anybody help me .</p>

```<code> import org.jfree.chart.ChartFrame;
 import org.jfree.chart.ChartFactory;
 import org.jfree.chart.JFreeChart;
 import org.jfree.data.general.DefaultPieDataset;
import org.jfree.dataset;

public class test {
/**
* The starting point for the demo.
*
* @param args ignored.
*/
// create a dataset...
DefaultPieDataset dataset = new DefaultPieDataset;
dataset.setValue("Category 1", 43.2);
dataset.setValue("Category 2", 27.9);
dataset.setValue("Category 3", 79.5);
// create a chart...
JFreeChart chart = ChartFactory.createPieChart(
"Sample Pie Chart",
dataset,
true, // legend?
true, // tooltips?
false // URLs?
);
// create and display a frame...
ChartFrame frame = new ChartFrame("First", chart);
frame.pack();
frame.setVisible(true);
}
}
}
</code>```

答:
This line doesn't refer to any class or package:

```<code>import org.jfree.dataset;
</code>```

Then your class is not well formed, there should be a constructor, and at least a main() method.  This is nothing related to JFreeChart, just basic Java programming so you should go through a good tutorial about that first.

Title: identifier expected in jfreechart

Body:
I am new to JFreecharts in java.Am trying execute the code for piechart but its giving error "identifier expected and illegal start of expression".can anybody help me .

 import org.jfree.chart.ChartFrame;
 import org.jfree.chart.ChartFactory;
 import org.jfree.chart.JFreeChart;
 import org.jfree.data.general.DefaultPieDataset;
import org.jfree.dataset;

public class test {
/**
* The starting point for the demo.
*
* @param args ignored.
*/
// create a dataset...
DefaultPieDataset dataset = new DefaultPieDataset;
dataset.setValue("Category 1", 43.2);
dataset.setValue("Category 2", 27.9);
dataset.setValue("Category 3", 79.5);
// create a chart...
JFreeChart chart = ChartFactory.createPieChart(
"Sample Pie Chart",
dataset,
true, // legend?
true, // tooltips?
false // URLs?
);
// create and display a frame...
ChartFrame frame = new ChartFrame("First", chart);
frame.pack();
frame.setVisible(true);
}
}
}

Body:
This line doesn't refer to any class or package:

import org.jfree.dataset;

Then your class is not well formed, there should be a constructor, and at least a main() method.  This is nothing related to JFreeChart, just basic Java programming so you should go through a good tutorial about that first.


问:
Spring boot fails on Eclipse + Ubuntu
When I run my spring boot project I get this error related to sfl4j. It seams that it's not finding the dependencies. I tried to add those dependencies manually on my pom.xml (it should get from sprig boot dependencies) but then it just fails further because another dependencies... I tried to run the project on another machine and ran just fine. Really weird... Here is the stack trace error

```<code>SLF4J: Failed to load class "org.slf4j.impl.StaticLoggerBinder".
SLF4J: Defaulting to no-operation (NOP) logger implementation
SLF4J: See http://www.slf4j.org/codes.html#StaticLoggerBinder for further details.
Exception in thread "main" java.lang.NoClassDefFoundError: ch/qos/logback/classic/joran/JoranConfigurator
    at java.lang.Class.getDeclaredConstructors0(Native Method)
    at java.lang.Class.privateGetDeclaredConstructors(Class.java:2671)
    at java.lang.Class.getConstructor0(Class.java:3075)
    at java.lang.Class.getConstructor(Class.java:1825)
    at org.springframework.boot.logging.LoggingSystem.get(LoggingSystem.java:169)
    at org.springframework.boot.logging.LoggingSystem.get(LoggingSystem.java:160)
    at org.springframework.boot.logging.LoggingApplicationListener.onApplicationStartingEvent(LoggingApplicationListener.java:229)
    at org.springframework.boot.logging.LoggingApplicationListener.onApplicationEvent(LoggingApplicationListener.java:209)
    at org.springframework.context.event.SimpleApplicationEventMulticaster.doInvokeListener(SimpleApplicationEventMulticaster.java:172)
    at org.springframework.context.event.SimpleApplicationEventMulticaster.invokeListener(SimpleApplicationEventMulticaster.java:165)
    at org.springframework.context.event.SimpleApplicationEventMulticaster.multicastEvent(SimpleApplicationEventMulticaster.java:139)
    at org.springframework.context.event.SimpleApplicationEventMulticaster.multicastEvent(SimpleApplicationEventMulticaster.java:122)
    at org.springframework.boot.context.event.EventPublishingRunListener.starting(EventPublishingRunListener.java:69)
    at org.springframework.boot.SpringApplicationRunListeners.starting(SpringApplicationRunListeners.java:48)
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:292)
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:1118)
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:1107)
    at br.senai.ms.talentos.TalentosApplication.main(TalentosApplication.java:11)
Caused by: java.lang.ClassNotFoundException: ch.qos.logback.classic.joran.JoranConfigurator
    at java.net.URLClassLoader.findClass(URLClassLoader.java:381)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
    at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:335)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
    ... 18 more
</code>```

==========================
Here is my entire pom.xml

http://maven.apache.org/xsd/maven-4.0.0.xsd">
    4.0.0

```<code><groupId>br.senai.ms</groupId>
<artifactId>talentos</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>

<name>talentos</name>
<description>Talentos</description>

<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>1.5.9.RELEASE</version>
    <relativePath/> <!-- lookup parent from repository -->
</parent>

<properties>
    <start-class>br.teste.Application</start-class>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
    <java.version>1.8</java.version>
</properties>

<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-cache</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-data-jpa</artifactId>
    </dependency>
    <dependency>
        <groupId>org.flywaydb</groupId>
        <artifactId>flyway-core</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-jdbc</artifactId>
    </dependency>
    <dependency>
        <groupId>org.postgresql</groupId>
        <artifactId>postgresql</artifactId>
        <scope>runtime</scope>
    </dependency>
    <dependency>
        <groupId>org.projectlombok</groupId>
        <artifactId>lombok</artifactId>
        <optional>true</optional>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-test</artifactId>
        <scope>test</scope>
    </dependency>
    <dependency>
        <groupId>com.mysema.querydsl</groupId>
        <artifactId>querydsl-apt</artifactId>
        <version>3.7.4</version>
    </dependency>
    <dependency>
        <groupId>com.mysema.querydsl</groupId>
        <artifactId>querydsl-jpa</artifactId>
        <version>3.7.4</version>
    </dependency>
    <dependency>
        <groupId>org.hibernate</groupId>
        <artifactId>hibernate-ehcache</artifactId>
    </dependency>
    <dependency>
        <groupId>net.sf.ehcache</groupId>
        <artifactId>ehcache-core</artifactId>
        <version>2.4.3</version>
    </dependency>
</dependencies>

<build>
    <plugins>
        <plugin>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-maven-plugin</artifactId>
        </plugin>
        <plugin>
            <groupId>com.mysema.maven</groupId>
            <artifactId>apt-maven-plugin</artifactId>
            <version>1.1.3</version>
            <executions>
                <execution>
                    <goals>
                        <goal>process</goal>
                    </goals>
                    <configuration>
                        <outputDirectory>target/generated-sources/java</outputDirectory>
                        <processor>com.mysema.query.apt.jpa.JPAAnnotationProcessor</processor>
                    </configuration>
                </execution>
            </executions>
        </plugin>
    </plugins>
</build>
</code>```

答: Try to delete the .m2 directory and build the project again. This might take a bit longer to build as maven downloads all the jars again.</p>

Title: Spring boot fails on Eclipse + Ubuntu

Body:
When I run my spring boot project I get this error related to sfl4j. It seams that it's not finding the dependencies. I tried to add those dependencies manually on my pom.xml (it should get from sprig boot dependencies) but then it just fails further because another dependencies... I tried to run the project on another machine and ran just fine. Really weird... Here is the stack trace error

SLF4J: Failed to load class "org.slf4j.impl.StaticLoggerBinder".
SLF4J: Defaulting to no-operation (NOP) logger implementation
SLF4J: See http://www.slf4j.org/codes.html#StaticLoggerBinder for further details.
Exception in thread "main" java.lang.NoClassDefFoundError: ch/qos/logback/classic/joran/JoranConfigurator
    at java.lang.Class.getDeclaredConstructors0(Native Method)
    at java.lang.Class.privateGetDeclaredConstructors(Class.java:2671)
    at java.lang.Class.getConstructor0(Class.java:3075)
    at java.lang.Class.getConstructor(Class.java:1825)
    at org.springframework.boot.logging.LoggingSystem.get(LoggingSystem.java:169)
    at org.springframework.boot.logging.LoggingSystem.get(LoggingSystem.java:160)
    at org.springframework.boot.logging.LoggingApplicationListener.onApplicationStartingEvent(LoggingApplicationListener.java:229)
    at org.springframework.boot.logging.LoggingApplicationListener.onApplicationEvent(LoggingApplicationListener.java:209)
    at org.springframework.context.event.SimpleApplicationEventMulticaster.doInvokeListener(SimpleApplicationEventMulticaster.java:172)
    at org.springframework.context.event.SimpleApplicationEventMulticaster.invokeListener(SimpleApplicationEventMulticaster.java:165)
    at org.springframework.context.event.SimpleApplicationEventMulticaster.multicastEvent(SimpleApplicationEventMulticaster.java:139)
    at org.springframework.context.event.SimpleApplicationEventMulticaster.multicastEvent(SimpleApplicationEventMulticaster.java:122)
    at org.springframework.boot.context.event.EventPublishingRunListener.starting(EventPublishingRunListener.java:69)
    at org.springframework.boot.SpringApplicationRunListeners.starting(SpringApplicationRunListeners.java:48)
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:292)
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:1118)
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:1107)
    at br.senai.ms.talentos.TalentosApplication.main(TalentosApplication.java:11)
Caused by: java.lang.ClassNotFoundException: ch.qos.logback.classic.joran.JoranConfigurator
    at java.net.URLClassLoader.findClass(URLClassLoader.java:381)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
    at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:335)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
    ... 18 more

==========================
Here is my entire pom.xml

http://maven.apache.org/xsd/maven-4.0.0.xsd">
    4.0.0

<groupId>br.senai.ms</groupId>
<artifactId>talentos</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>

<name>talentos</name>
<description>Talentos</description>

<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>1.5.9.RELEASE</version>
    <relativePath/>
</parent>

<properties>
    <start-class>br.teste.Application</start-class>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
    <java.version>1.8</java.version>
</properties>

<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-cache</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-data-jpa</artifactId>
    </dependency>
    <dependency>
        <groupId>org.flywaydb</groupId>
        <artifactId>flyway-core</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-jdbc</artifactId>
    </dependency>
    <dependency>
        <groupId>org.postgresql</groupId>
        <artifactId>postgresql</artifactId>
        <scope>runtime</scope>
    </dependency>
    <dependency>
        <groupId>org.projectlombok</groupId>
        <artifactId>lombok</artifactId>
        <optional>true</optional>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-test</artifactId>
        <scope>test</scope>
    </dependency>
    <dependency>
        <groupId>com.mysema.querydsl</groupId>
        <artifactId>querydsl-apt</artifactId>
        <version>3.7.4</version>
    </dependency>
    <dependency>
        <groupId>com.mysema.querydsl</groupId>
        <artifactId>querydsl-jpa</artifactId>
        <version>3.7.4</version>
    </dependency>
    <dependency>
        <groupId>org.hibernate</groupId>
        <artifactId>hibernate-ehcache</artifactId>
    </dependency>
    <dependency>
        <groupId>net.sf.ehcache</groupId>
        <artifactId>ehcache-core</artifactId>
        <version>2.4.3</version>
    </dependency>
</dependencies>

<build>
    <plugins>
        <plugin>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-maven-plugin</artifactId>
        </plugin>
        <plugin>
            <groupId>com.mysema.maven</groupId>
            <artifactId>apt-maven-plugin</artifactId>
            <version>1.1.3</version>
            <executions>
                <execution>
                    <goals>
                        <goal>process</goal>
                    </goals>
                    <configuration>
                        <outputDirectory>target/generated-sources/java</outputDirectory>
                        <processor>com.mysema.query.apt.jpa.JPAAnnotationProcessor</processor>
                    </configuration>
                </execution>
            </executions>
        </plugin>
    </plugins>
</build>


问:
swift 4 error: load html string to webview
I tried to load a html string in my webview with the code :

```<code>let htmlFile = Bundle.main.path(forResource: "code", ofType: "html")
        let html = try! String(contentsOfFile: htmlFile!, encoding: String.Encoding.utf8)
        self.weview.loadHTMLString(html, baseURL: nil)
</code>```

I run the app, everything works fine, but if i press on a website link, i get the error in my AppDelegate: Thread 1: EXC_BAD_ACCESS (code=1, address=0x10)
Can someone give me a code for swift 4, where I can load a html string and interact with it? Would be really nice.

答:
First thing to check - go to Project Settings -> Build Phases -> Copy Bundle Resources to make sure your directory with your html-files is on the list there.

Second, load the file the way listed below. You don't have to load the content of the file.

```<code>let path = Bundle.main.path(forResource: "code", ofType: "html")!
let uri = URL(string: path)!
let request = URLRequest(url: uri)
webView.loadRequest(request)
</code>```

Also, make sure forResource param contains full path to the html file starting from your project directory

Body:
I tried to load a html string in my webview with the code :

let htmlFile = Bundle.main.path(forResource: "code", ofType: "html")
        let html = try! String(contentsOfFile: htmlFile!, encoding: String.Encoding.utf8)
        self.weview.loadHTMLString(html, baseURL: nil)

I run the app, everything works fine, but if i press on a website link, i get the error in my AppDelegate: Thread 1: EXC_BAD_ACCESS (code=1, address=0x10)
Can someone give me a code for swift 4, where I can load a html string and interact with it? Would be really nice.

Body:
First thing to check - go to Project Settings -> Build Phases -> Copy Bundle Resources to make sure your directory with your html-files is on the list there.

Second, load the file the way listed below. You don't have to load the content of the file.

let path = Bundle.main.path(forResource: "code", ofType: "html")!
let uri = URL(string: path)!
let request = URLRequest(url: uri)
webView.loadRequest(request)

Also, make sure forResource param contains full path to the html file starting from your project directory


问:
How to extract some data from url using Python
I have an url as follows:

```<code>https://some_url/vivi/v2/ZUxOZmVrdzJqTURxV20wQ0RvRld6SytEQWNocThwMGVnbFJ4RDQrZzJMeGRBcnhPYnUzV1pRPT0=/BE?category=PASSENGER&make=30&model=124&regmonth=3&regdate=2015-03&body=443,4781&facelift=252&seats=4&bodyHeight=443&bodyLength=443&weight=-1&engine=1394&wheeldrive=196&transmission=400
</code>```

What I need is to get the string after v2/, thus ZUxOZmVrdzJqTURxV20wQ0RvRld6SytEQWNocThwMGVnbFJ4RDQrZzJMeGRBcnhPYnUzV1pRPT0=

I use furl to extract the parameter value. I do it as follows:

```<code>furl(url).args['category'] // gives PASSENGER
</code>```

But here I do not have the name of the parameter.

How can I do that?

答:
Desired output using re.

```<code>import re

url = "https://some_url/vivi/v2/ZUxOZmVrdzJqTURxV20wQ0RvRld6SytEQWNocThwMGVnbFJ4RDQrZzJMeGRBcnhPYnUzV1pRPT0=/BE?category=PASSENGER&make=30&model=124&regmonth=3&regdate=2015-03&body=443,4781&facelift=252&seats=4&bodyHeight=443&bodyLength=443&weight=-1&engine=1394&wheeldrive=196&transmission=400"
re.findall(r'v2/(.*)/', url)
</code>```

Resulting with ['ZUxOZmVrdzJqTURxV20wQ0RvRld6SytEQWNocThwMGVnbFJ4RDQrZzJMeGRBcnhPYnUzV1pRPT0='].

But it's safer to use split() the way other mentioned, because when api version changes to v3 this re code won't work anymore.

Body:
I have an url as follows:

https://some_url/vivi/v2/ZUxOZmVrdzJqTURxV20wQ0RvRld6SytEQWNocThwMGVnbFJ4RDQrZzJMeGRBcnhPYnUzV1pRPT0=/BE?category=PASSENGER&make=30&model=124&regmonth=3&regdate=2015-03&body=443,4781&facelift=252&seats=4&bodyHeight=443&bodyLength=443&weight=-1&engine=1394&wheeldrive=196&transmission=400

What I need is to get the string after v2/, thus ZUxOZmVrdzJqTURxV20wQ0RvRld6SytEQWNocThwMGVnbFJ4RDQrZzJMeGRBcnhPYnUzV1pRPT0=

I use furl to extract the parameter value. I do it as follows:

furl(url).args['category'] // gives PASSENGER

But here I do not have the name of the parameter.

How can I do that?

Body:
Desired output using re.

import re

url = "https://some_url/vivi/v2/ZUxOZmVrdzJqTURxV20wQ0RvRld6SytEQWNocThwMGVnbFJ4RDQrZzJMeGRBcnhPYnUzV1pRPT0=/BE?category=PASSENGER&make=30&model=124&regmonth=3&regdate=2015-03&body=443,4781&facelift=252&seats=4&bodyHeight=443&bodyLength=443&weight=-1&engine=1394&wheeldrive=196&transmission=400"
re.findall(r'v2/(.*)/', url)

Resulting with ['ZUxOZmVrdzJqTURxV20wQ0RvRld6SytEQWNocThwMGVnbFJ4RDQrZzJMeGRBcnhPYnUzV1pRPT0='].

But it's safer to use split() the way other mentioned, because when api version changes to v3 this re code won't work anymore.


问:
Angular Service and HttpClient Type does not exist
I am trying to get a service working in Angular 5. This is what I have:

```<code>import { Injectable } from '@angular/core';

@Injectable()
export class DataService {

  constructor() { }

  getData() {
    // don't use 'any', type your data instead!
    return this.httpClient.get<any>('./assets/data.json');
  }

}
</code>```

I'm getting the following error:

Property HttpClient does not exist on type DataService.

What am I missing?

答:
You need to import HttpClient from the module like below

```<code>import {HttpClient} from '@angular/common/http';
</code>```

and you code should be like this

```<code>import { Injectable } from '@angular/core';
import {HttpClient} from '@angular/common/http';

@Injectable()
export class DataService {

  constructor(private httpClient: HttpClient) { }

  getData() {
    // don't use 'any', type your data instead!
    return this.httpClient.get<any>('./assets/data.json');
  }

}
</code>```

Body:
I am trying to get a service working in Angular 5. This is what I have:

import { Injectable } from '@angular/core';

@Injectable()
export class DataService {

  constructor() { }

  getData() {
    // don't use 'any', type your data instead!
    return this.httpClient.get<any>('./assets/data.json');
  }

}

I'm getting the following error:

Property HttpClient does not exist on type DataService.

What am I missing?

Body:
You need to import HttpClient from the module like below

import {HttpClient} from '@angular/common/http';

and you code should be like this

import { Injectable } from '@angular/core';
import {HttpClient} from '@angular/common/http';

@Injectable()
export class DataService {

  constructor(private httpClient: HttpClient) { }

  getData() {
    // don't use 'any', type your data instead!
    return this.httpClient.get<any>('./assets/data.json');
  }

}


问:
Submitting form after validating inputs
I have the following registration form :

```<code><form id="register-form" method="post" role="form" style="display: none;"

action="">
    <div class="form-group">
        <input type="text" name="firstname" id="firstname" tabindex="1" class="form-control" placeholder="Firstname" value="" required>
        <span class="error" id="fnError"></span>
    </div>
    <div class="form-group">
        <input type="text" name="lastname" id="lastname" tabindex="1" class="form-control" placeholder="Lastname" value=""required>
        <span class="error" id="lnError"></span>
    </div>
    <div class="form-group">
        <input type="email" name="email2" id="email2" tabindex="1" class="form-control" placeholder="Email Address" value=""required>
    </div>
    <div class="form-group">
        <input type="password" name="password2" id="password2" tabindex="2" class="form-control" placeholder="Password"required>
        <span class="error" id="pass2Error"></span>
    </div>
    <div class="form-group">
        <input type="password" name="confirm_password" id="confirm-password" tabindex="2" class="form-control" placeholder="Confirm Password" required>
        <span class="error" id="confError"></span>
    </div>
    <div class="form-group">
        <div class="row">
            <div class="col-sm-6 col-sm-offset-3">
                <input type="submit" name="register-submit" id="register-submit" tabindex="4" class="form-control btn btn-register" value="Register Now">
                <span class="throw_error" id="success"></span>
                <div id="divLoader"></div>
            </div>
            <div class="col-sm-6 col-sm-offset-3">
                <span id="result"></span>
            </div>
        </div>
    </div>
</form>
</code>```

And I am using the jquery validation plugin to validate the inputs :

```<code>jQuery.validator.setDefaults({
        debug: false,
        success: "valid"
    });
    $('#register-form').validate({
        rules:{
            firstname :{
                required : true,
                minlength : 3,
                maxlength : 15
            },
            lastname :{
                required : true,
                minlength : 3,
                maxlength : 15
            },
            email2:{
                required : true,
                email : true
            },
            password2:{
                required : true,
                minlength : 8,
                maxlength : 15
            },
            confirm_password:{
                required : true,
                minlength : 8,
                maxlength : 15,
                equalTo : "#password2"
            }
        }
    });
</code>```

When I click on the registration button, the validation of the fields is shown (all the errors on each field are shown), and the ajax code that I am using on the button press runs even if there are validation errors.
Here is my button clicked code :

```<code>$('#register-form').submit(function(event){
    var formData={
        'fn':$('#firstname').val(),
        'ln':$('#lastname').val(),
        'email':$('#email2').val(),
        'pass':$('#password2').val(),
        'action':'regUser'
    };
    $.ajax({
        type: 'POST',
        url: 'Index.php',
        data: formData,
        dataType: 'json',
        beforeSend: function () {
            $('#register-submit').attr("disabled","disabled");
            $("#divLoader").addClass("loader");
            console.log('before send');
        },
        success: function (data) {
            if(data.success){
                $('#success').fadeIn(1000).append('<p>'+data.userAdded+'</p>');
            }
            else{
                $('.throw_error').fadeIn(1000).html(data.errors[0]);
            }
        },
        error: function(){
            alert("System currently unavailable, try again later");
        },
        complete: function () {
            $('#register-submit').removeAttr('disabled');
            $('#divLoader').removeClass('loader');
        }
    });
    event.preventDefault();
});
</code>```

What I want is that when I click on the submit button and there are validation problems that the button clicked event will not be triggered, so the AJAX call doesn't start.

答:
try to name your validator as variable

```<code>var myvalidator = $('#register-form').validate({
  // ..
});
</code>```

and in form submit add check like this:

```<code>$('#register-form').submit(function(event){
  if (! myvalidator.valid() ) event.preventDefault();
  // goes to ajax
});
</code>```

ContentLicense: CC BY-SA 4.0

Title: Submitting form after validating inputs

Body:
I have the following registration form :

<form id="register-form" method="post" role="form" style="display: none;"

action="">

        <input type="text" name="firstname" id="firstname" tabindex="1" class="form-control" placeholder="Firstname" value="" required>

        <input type="text" name="lastname" id="lastname" tabindex="1" class="form-control" placeholder="Lastname" value=""required>

        <input type="email" name="email2" id="email2" tabindex="1" class="form-control" placeholder="Email Address" value=""required>

        <input type="password" name="password2" id="password2" tabindex="2" class="form-control" placeholder="Password"required>

        <input type="password" name="confirm_password" id="confirm-password" tabindex="2" class="form-control" placeholder="Confirm Password" required>

                <input type="submit" name="register-submit" id="register-submit" tabindex="4" class="form-control btn btn-register" value="Register Now">

</form>

And I am using the jquery validation plugin to validate the inputs :

jQuery.validator.setDefaults({
        debug: false,
        success: "valid"
    });
    $('#register-form').validate({
        rules:{
            firstname :{
                required : true,
                minlength : 3,
                maxlength : 15
            },
            lastname :{
                required : true,
                minlength : 3,
                maxlength : 15
            },
            email2:{
                required : true,
                email : true
            },
            password2:{
                required : true,
                minlength : 8,
                maxlength : 15
            },
            confirm_password:{
                required : true,
                minlength : 8,
                maxlength : 15,
                equalTo : "#password2"
            }
        }
    });

When I click on the registration button, the validation of the fields is shown (all the errors on each field are shown), and the ajax code that I am using on the button press runs even if there are validation errors.
Here is my button clicked code :

$('#register-form').submit(function(event){
    var formData={
        'fn':$('#firstname').val(),
        'ln':$('#lastname').val(),
        'email':$('#email2').val(),
        'pass':$('#password2').val(),
        'action':'regUser'
    };
    $.ajax({
        type: 'POST',
        url: 'Index.php',
        data: formData,
        dataType: 'json',
        beforeSend: function () {
            $('#register-submit').attr("disabled","disabled");
            $("#divLoader").addClass("loader");
            console.log('before send');
        },
        success: function (data) {
            if(data.success){
                $('#success').fadeIn(1000).append('
'+data.userAdded+'
');
            }
            else{
                $('.throw_error').fadeIn(1000).html(data.errors[0]);
            }
        },
        error: function(){
            alert("System currently unavailable, try again later");
        },
        complete: function () {
            $('#register-submit').removeAttr('disabled');
            $('#divLoader').removeClass('loader');
        }
    });
    event.preventDefault();
});

What I want is that when I click on the submit button and there are validation problems that the button clicked event will not be triggered, so the AJAX call doesn't start.

Body:
try to name your validator as variable

var myvalidator = $('#register-form').validate({
  // ..
});

and in form submit add check like this:

$('#register-form').submit(function(event){
  if (! myvalidator.valid() ) event.preventDefault();
  // goes to ajax
});