问:
Oracle Package Body Compile Errors: SQL Statement Ignored, table or view does not exist
I need to wrap a SQL script I wrote into a package because... work.

I get really lost in PL/SQL, and have no idea what I'm doing wrong:

```<code>    CREATE OR REPLACE PACKAGE F_LOG_ARCHIVE_PKG AS
      PROCEDURE LOG_ARCHIVE;
    END F_LOG_ARCHIVE_PKG;

    /************************ F_BUSINESS_IDENTIFIER ********************************/
    /
    CREATE OR REPLACE PACKAGE BODY F_LOG_ARCHIVE_PKG AS
    PROCEDURE LOG_ARCHIVE IS
    BEGIN
        INSERT INTO LOGARC.F_BUSINESS_IDENTIFIER ("ID",
          "SERVICE_ID",
          "OPERATION_ID",
          "BUSINESS_IDENTIFIER_NAME",
          "BUSINESS_IDENTIFIER_VALUE",
          "EXCEPTION_ROW_ID",
          "ARCHIVE_DATE")
        SELECT DISTINCT ORIGINAL."ID",
          ORIGINAL.SERVICE_ID,
          ORIGINAL.OPERATION_ID,
          ORIGINAL.BUSINESS_IDENTIFIER_NAME,
          ORIGINAL.BUSINESS_IDENTIFIER_VALUE,
          ORIGINAL.EXCEPTION_ROW_ID,
          sysdate
        FROM LOGUSR.F_BUSINESS_IDENTIFIER ORIGINAL
        --Latest exception date based on service id and operation id
        INNER JOIN (SELECT F_EXCEPTION.SERVICE_ID,
                  F_SERVICE_OPERATION_NAME.ID AS OPERATION_ID,
                  MAX(RECORD_CREATED_DATE) AS RECORD_CREATED_DATE,
                  MAX(EXCEPTION_DATE) AS EXCEPTION_DATE
                  FROM LOGUSR.F_EXCEPTION
                  INNER JOIN LOGUSR.F_SERVICE_OPERATION_NAME
                  ON F_EXCEPTION.OPERATION_NAME = F_SERVICE_OPERATION_NAME.OPERATION_NAME
                  GROUP BY F_EXCEPTION.SERVICE_ID,F_SERVICE_OPERATION_NAME.ID) EXCEPTION_DATE
          ON ORIGINAL.SERVICE_ID = EXCEPTION_DATE.SERVICE_ID
          AND ORIGINAL.OPERATION_ID = EXCEPTION_DATE.OPERATION_ID
        --Service name to join to F_SERVICE_LOGSTATUS table
        INNER JOIN LOGUSR.F_SERVICE_NAME
          ON ORIGINAL.SERVICE_ID = F_SERVICE_NAME.ID
        --Operation name to join to F_SERVICE_LOGSTATUS table
        INNER JOIN LOGUSR.F_SERVICE_OPERATION_NAME
          ON ORIGINAL.OPERATION_ID = F_SERVICE_OPERATION_NAME.ID
        --Archive strategy
        INNER JOIN LOGUSR.F_SERVICE_LOGSTATUS
          ON F_SERVICE_NAME.SERVICE_NAME = F_SERVICE_LOGSTATUS.SERVICE_NAME
          AND F_SERVICE_OPERATION_NAME.OPERATION_NAME = F_SERVICE_LOGSTATUS.OPERATION_NAME
        WHERE F_SERVICE_LOGSTATUS.ARCHIVE_FLAG = 'Y'
        AND F_SERVICE_LOGSTATUS.ARCHIVE_DAYS <= (sysdate-EXCEPTION_DATE.EXCEPTION_DATE);
</code>```

SNIP

```<code>    END LOG_ARCHIVE;
    END F_LOG_ARCHIVE_PKG;
</code>```

Errors returned:

Error(4,5): PL/SQL: SQL Statement ignored
Error(4,24): PL/SQL: ORA-00942: table or view does not exist

The DBA recently updated to role to give the user write access to both schemas.

答:
Your package references tables in two schemas, LOGUSR and LOGARC. When we build a package we can only reference objects in our schema (the package owner) and objects in other schemas where privileges have been granted to us directly. Privileges granted through a role are no good for this, (because of the Oracle security model).

You say,

"The DBA recently updated to role to give the user write access to both schemas."

So, depending on which schema owns your package you need to ask your DBA to  grant you privileges on the other schema's objects.

Body:
I need to wrap a SQL script I wrote into a package because... work.

I get really lost in PL/SQL, and have no idea what I'm doing wrong:

    CREATE OR REPLACE PACKAGE F_LOG_ARCHIVE_PKG AS
      PROCEDURE LOG_ARCHIVE;
    END F_LOG_ARCHIVE_PKG;

    /************************ F_BUSINESS_IDENTIFIER ********************************/
    /
    CREATE OR REPLACE PACKAGE BODY F_LOG_ARCHIVE_PKG AS
    PROCEDURE LOG_ARCHIVE IS
    BEGIN
        INSERT INTO LOGARC.F_BUSINESS_IDENTIFIER ("ID",
          "SERVICE_ID",
          "OPERATION_ID",
          "BUSINESS_IDENTIFIER_NAME",
          "BUSINESS_IDENTIFIER_VALUE",
          "EXCEPTION_ROW_ID",
          "ARCHIVE_DATE")
        SELECT DISTINCT ORIGINAL."ID",
          ORIGINAL.SERVICE_ID,
          ORIGINAL.OPERATION_ID,
          ORIGINAL.BUSINESS_IDENTIFIER_NAME,
          ORIGINAL.BUSINESS_IDENTIFIER_VALUE,
          ORIGINAL.EXCEPTION_ROW_ID,
          sysdate
        FROM LOGUSR.F_BUSINESS_IDENTIFIER ORIGINAL
        --Latest exception date based on service id and operation id
        INNER JOIN (SELECT F_EXCEPTION.SERVICE_ID,
                  F_SERVICE_OPERATION_NAME.ID AS OPERATION_ID,
                  MAX(RECORD_CREATED_DATE) AS RECORD_CREATED_DATE,
                  MAX(EXCEPTION_DATE) AS EXCEPTION_DATE
                  FROM LOGUSR.F_EXCEPTION
                  INNER JOIN LOGUSR.F_SERVICE_OPERATION_NAME
                  ON F_EXCEPTION.OPERATION_NAME = F_SERVICE_OPERATION_NAME.OPERATION_NAME
                  GROUP BY F_EXCEPTION.SERVICE_ID,F_SERVICE_OPERATION_NAME.ID) EXCEPTION_DATE
          ON ORIGINAL.SERVICE_ID = EXCEPTION_DATE.SERVICE_ID
          AND ORIGINAL.OPERATION_ID = EXCEPTION_DATE.OPERATION_ID
        --Service name to join to F_SERVICE_LOGSTATUS table
        INNER JOIN LOGUSR.F_SERVICE_NAME
          ON ORIGINAL.SERVICE_ID = F_SERVICE_NAME.ID
        --Operation name to join to F_SERVICE_LOGSTATUS table
        INNER JOIN LOGUSR.F_SERVICE_OPERATION_NAME
          ON ORIGINAL.OPERATION_ID = F_SERVICE_OPERATION_NAME.ID
        --Archive strategy
        INNER JOIN LOGUSR.F_SERVICE_LOGSTATUS
          ON F_SERVICE_NAME.SERVICE_NAME = F_SERVICE_LOGSTATUS.SERVICE_NAME
          AND F_SERVICE_OPERATION_NAME.OPERATION_NAME = F_SERVICE_LOGSTATUS.OPERATION_NAME
        WHERE F_SERVICE_LOGSTATUS.ARCHIVE_FLAG = 'Y'
        AND F_SERVICE_LOGSTATUS.ARCHIVE_DAYS <= (sysdate-EXCEPTION_DATE.EXCEPTION_DATE);

SNIP

    END LOG_ARCHIVE;
    END F_LOG_ARCHIVE_PKG;

Errors returned:

Error(4,5): PL/SQL: SQL Statement ignored
Error(4,24): PL/SQL: ORA-00942: table or view does not exist

The DBA recently updated to role to give the user write access to both schemas.


来源: stackexchange

问:
Creating a list of dictionaries modifying just one values at each step
I have a python dictionary which describes a set of parameters like this:

```<code>params = {'V0': 0.040239623194206875, 'theta': 0.2133407345978868,
 'omega': 0.8624391468911115, 'kappa': 0.8632687388218084,
 'rho': -0.7680944602881048}
</code>```

Each parameter in the set has a constant number which represent its variation. From such set I want to construct a list of dictionaries until I have 100 sets of parameters. The logic behind is that I want for example change params['V0'] to

```<code>params['V0'] += deltaV0
params['V0'] -= deltaV0
</code>```

with the other values fixed, obtaining another 2 different dictionaries to add to my list. My problem is that I can't manage to transform my idea in code. The framework should be something like:

```<code>good_set = [params]

while len(good_set) < 100:

good_set.append(new params)
</code>```

How can I efficiently obtain new dictionaries from the initial one? I need to simultaneously obtain 2 new dictionaries from the initial one for each parameters ( because the variation is added and subtracted each time), so in total for each iteration I should add to my list 5*2=10 dictionaries. I red some question about dict comprehension but they didn't give me an input to solve my problem

答:
Well you just need to create a .copy of the dict, and then change it suitably. For exmaple:

```<code>In [3]: params = {'V0': 0.040239623194206875, 'theta': 0.2133407345978868,
   ...:  'omega': 0.8624391468911115, 'kappa': 0.8632687388218084,
   ...:  'rho': -0.7680944602881048}
   ...:

In [4]: results = []

In [5]: import random

In [6]: for _ in xrange(100):
   ...:     sample_params = params.copy()
   ...:     sample_params['V0'] += random.random()
   ...:     results.append(sample_params)
</code>```

I've used random.random() as the delta value, you can have custom logic to modify in which manner required.

If your delta are constant, and they can either be added, subtracted or not considered for test case generation, you can try

```<code>params = {'V0': 0.040239623194206875, 'theta': 0.2133407345978868,
 'omega': 0.8624391468911115, 'kappa': 0.8632687388218084,
 'rho': -0.7680944602881048}

import random

delta = {'V0': random.random(),
'theta': random.random(),
'omega': random.random(),
'kappa': random.random(),
'rho': random.random()}

list_of_params = [ {key: params[key] + random.randint(-1, 1) * delta[key] for key in params} for _ in xrange(100)]
</code>```

Here, the delta are stored in a dict, and random.randint(-1, 1) takes care of randomly adding, subtracting, or ignoring the particular delta.

ContentLicense: CC BY-SA 3.0

Body:
I have a python dictionary which describes a set of parameters like this:

params = {'V0': 0.040239623194206875, 'theta': 0.2133407345978868,
 'omega': 0.8624391468911115, 'kappa': 0.8632687388218084,
 'rho': -0.7680944602881048}

Each parameter in the set has a constant number which represent its variation. From such set I want to construct a list of dictionaries until I have 100 sets of parameters. The logic behind is that I want for example change params['V0'] to

params['V0'] += deltaV0
params['V0'] -= deltaV0

with the other values fixed, obtaining another 2 different dictionaries to add to my list. My problem is that I can't manage to transform my idea in code. The framework should be something like:

good_set = [params]

while len(good_set) < 100:

good_set.append(new params)

How can I efficiently obtain new dictionaries from the initial one? I need to simultaneously obtain 2 new dictionaries from the initial one for each parameters ( because the variation is added and subtracted each time), so in total for each iteration I should add to my list 5*2=10 dictionaries. I red some question about dict comprehension but they didn't give me an input to solve my problem

Body:
Well you just need to create a .copy of the dict, and then change it suitably. For exmaple:

In [3]: params = {'V0': 0.040239623194206875, 'theta': 0.2133407345978868,
   ...:  'omega': 0.8624391468911115, 'kappa': 0.8632687388218084,
   ...:  'rho': -0.7680944602881048}
   ...:

In [4]: results = []

In [5]: import random

In [6]: for _ in xrange(100):
   ...:     sample_params = params.copy()
   ...:     sample_params['V0'] += random.random()
   ...:     results.append(sample_params)

I've used random.random() as the delta value, you can have custom logic to modify in which manner required.

If your delta are constant, and they can either be added, subtracted or not considered for test case generation, you can try

params = {'V0': 0.040239623194206875, 'theta': 0.2133407345978868,
 'omega': 0.8624391468911115, 'kappa': 0.8632687388218084,
 'rho': -0.7680944602881048}

import random

delta = {'V0': random.random(),
'theta': random.random(),
'omega': random.random(),
'kappa': random.random(),
'rho': random.random()}

list_of_params = [ {key: params[key] + random.randint(-1, 1) * delta[key] for key in params} for _ in xrange(100)]

Here, the delta are stored in a dict, and random.randint(-1, 1) takes care of randomly adding, subtracting, or ignoring the particular delta.


问:
Python script not picking up the correct date selected in the excel Macro
I am trying to run a macro in excel that generates monthly reports.The macro calls the python script without any problems. However no matter the month i choose in the macro the python script always runs for January.

This is where i select the month:

When the python script runs it is always January:

Here is the code in python script.

```<code>#Read the month and year selected in the Monthly Report
pathOfMonthlyReportFile = os.sep.join((os.path.expanduser("~"),
'Desktop'))+'\Monthly Activity Report - Template.xlsm'
wb = openpyxl.load_workbook(pathOfMonthlyReportFile, keep_vba=True)
sheet = wb.get_sheet_by_name('Macro')
MonthOfMonthlyReport = sheet['G10'].value
YearOfMonthlyReport = sheet['J10'].value
print(MonthOfMonthlyReport)

if MonthOfMonthlyReport == "January":
 MonthNumber = 1
elif MonthOfMonthlyReport == "February":
 MonthNumber = 2
elif MonthOfMonthlyReport == "March":
 MonthNumber = 3
elif MonthOfMonthlyReport == "April":
 MonthNumber = 4
elif MonthOfMonthlyReport == "May":
 MonthNumber = 5
elif MonthOfMonthlyReport == "June":
 MonthNumber = 6
elif MonthOfMonthlyReport == "July":
 MonthNumber = 7
elif MonthOfMonthlyReport == "August":
 MonthNumber = 8
elif MonthOfMonthlyReport == "September":
 MonthNumber = 9
elif MonthOfMonthlyReport == "October":
 MonthNumber = 10
elif MonthOfMonthlyReport == "November":
 MonthNumber = 11
elif MonthOfMonthlyReport == "December":
 MonthNumber = 12

MonthlyReportDate =
now.replace(month=MonthNumber,year=int(YearOfMonthlyReport))
if MonthNumber == 12:
last_day_of_month = MonthlyReportDate.replace(day = 31, month=MonthNumber,
year=int(YearOfMonthlyReport))
else:
last_day_of_month = MonthlyReportDate.replace(day=1, month=MonthNumber+1,
year=int(YearOfMonthlyReport)) - datetime.timedelta(days=1)

if MonthNumber >= 10:
    stringenddate = "%s-%s-%s" % (MonthlyReportDate.year,
MonthlyReportDate.month,last_day_of_month.day)
    stringstartdate = "%s-%s-01" % (MonthlyReportDate.year,
MonthlyReportDate.month)
else:
    stringenddate = "%s-0%s-%s" % (MonthlyReportDate.year,
MonthlyReportDate.month,last_day_of_month.day)
    stringstartdate = "%s-0%s-01" % (MonthlyReportDate.year,
MonthlyReportDate.month)

print(stringenddate)

MonthRange = [1,2,3,4,5,6,7,8,9,10,11,12]
ThreeMonthsAgo = 0

for i in range(len(MonthRange)):
   if MonthRange[i] == MonthNumber:
    ThreeMonthsAgo = MonthRange[i-2] #**************
print(ThreeMonthsAgo)

if ThreeMonthsAgo<MonthNumber:
if ThreeMonthsAgo >=10:
    stringthreemonthsagodate = "%s-%s-01"%(MonthlyReportDate.year,
ThreeMonthsAgo)
else:
    stringthreemonthsagodate = "%s-0%s-01"%(MonthlyReportDate.year,
ThreeMonthsAgo)

if ThreeMonthsAgo > MonthNumber:
if ThreeMonthsAgo >=10:
    stringthreemonthsagodate = "%s-%s-01"%(MonthlyReportDate.year - 1,
ThreeMonthsAgo)
else:
    stringthreemonthsagodate = "%s-0%s-01"%(MonthlyReportDate.year - 1,
ThreeMonthsAgo)

date_ranges = [(stringstartdate,
                stringenddate)]
data_ranges_for_three_months = [(stringthreemonthsagodate, stringenddate)]
</code>```

It should run for the selected month but it runs only for the month of January.
I don't really get an error message but it is just not the right month.

It's been fixed. The solution is a bit embarrassing but i'll post it.All i had to do was whenever i change the month in macro, i need to save the .xlsm and then run it.

答:
Run this code in the Excel spreadsheet:

```<code>Sub TestMe()
    MsgBox Worksheets("Macro").Range("G10")
End Sub
</code>```

If you do not get "March", then you are most probably not referencing to G10 but to something else.
Furthermore, you are openning the excel file through Python with enabled VBA. Are you sure, that whenever you open it, it does not reset back to January? This is called Event().

Body:
I am trying to run a macro in excel that generates monthly reports.The macro calls the python script without any problems. However no matter the month i choose in the macro the python script always runs for January.

This is where i select the month:

When the python script runs it is always January:

Here is the code in python script.

#Read the month and year selected in the Monthly Report
pathOfMonthlyReportFile = os.sep.join((os.path.expanduser("~"),
'Desktop'))+'\Monthly Activity Report - Template.xlsm'
wb = openpyxl.load_workbook(pathOfMonthlyReportFile, keep_vba=True)
sheet = wb.get_sheet_by_name('Macro')
MonthOfMonthlyReport = sheet['G10'].value
YearOfMonthlyReport = sheet['J10'].value
print(MonthOfMonthlyReport)

if MonthOfMonthlyReport == "January":
 MonthNumber = 1
elif MonthOfMonthlyReport == "February":
 MonthNumber = 2
elif MonthOfMonthlyReport == "March":
 MonthNumber = 3
elif MonthOfMonthlyReport == "April":
 MonthNumber = 4
elif MonthOfMonthlyReport == "May":
 MonthNumber = 5
elif MonthOfMonthlyReport == "June":
 MonthNumber = 6
elif MonthOfMonthlyReport == "July":
 MonthNumber = 7
elif MonthOfMonthlyReport == "August":
 MonthNumber = 8
elif MonthOfMonthlyReport == "September":
 MonthNumber = 9
elif MonthOfMonthlyReport == "October":
 MonthNumber = 10
elif MonthOfMonthlyReport == "November":
 MonthNumber = 11
elif MonthOfMonthlyReport == "December":
 MonthNumber = 12

MonthlyReportDate =
now.replace(month=MonthNumber,year=int(YearOfMonthlyReport))
if MonthNumber == 12:
last_day_of_month = MonthlyReportDate.replace(day = 31, month=MonthNumber,
year=int(YearOfMonthlyReport))
else:
last_day_of_month = MonthlyReportDate.replace(day=1, month=MonthNumber+1,
year=int(YearOfMonthlyReport)) - datetime.timedelta(days=1)

if MonthNumber >= 10:
    stringenddate = "%s-%s-%s" % (MonthlyReportDate.year,
MonthlyReportDate.month,last_day_of_month.day)
    stringstartdate = "%s-%s-01" % (MonthlyReportDate.year,
MonthlyReportDate.month)
else:
    stringenddate = "%s-0%s-%s" % (MonthlyReportDate.year,
MonthlyReportDate.month,last_day_of_month.day)
    stringstartdate = "%s-0%s-01" % (MonthlyReportDate.year,
MonthlyReportDate.month)

print(stringenddate)

MonthRange = [1,2,3,4,5,6,7,8,9,10,11,12]
ThreeMonthsAgo = 0

for i in range(len(MonthRange)):
   if MonthRange[i] == MonthNumber:
    ThreeMonthsAgo = MonthRange[i-2] #**************
print(ThreeMonthsAgo)

if ThreeMonthsAgo<MonthNumber:
if ThreeMonthsAgo >=10:
    stringthreemonthsagodate = "%s-%s-01"%(MonthlyReportDate.year,
ThreeMonthsAgo)
else:
    stringthreemonthsagodate = "%s-0%s-01"%(MonthlyReportDate.year,
ThreeMonthsAgo)

if ThreeMonthsAgo > MonthNumber:
if ThreeMonthsAgo >=10:
    stringthreemonthsagodate = "%s-%s-01"%(MonthlyReportDate.year - 1,
ThreeMonthsAgo)
else:
    stringthreemonthsagodate = "%s-0%s-01"%(MonthlyReportDate.year - 1,
ThreeMonthsAgo)

date_ranges = [(stringstartdate,
                stringenddate)]
data_ranges_for_three_months = [(stringthreemonthsagodate, stringenddate)]

It should run for the selected month but it runs only for the month of January.
I don't really get an error message but it is just not the right month.

It's been fixed. The solution is a bit embarrassing but i'll post it.All i had to do was whenever i change the month in macro, i need to save the .xlsm and then run it.

Body:
Run this code in the Excel spreadsheet:

Sub TestMe()
    MsgBox Worksheets("Macro").Range("G10")
End Sub

If you do not get "March", then you are most probably not referencing to G10 but to something else.
Furthermore, you are openning the excel file through Python with enabled VBA. Are you sure, that whenever you open it, it does not reset back to January? This is called Event().


问:
Running subprocess in iOS?
Is it possible to launch a new sub-process in iOS? (from regular application)
If possible, how to do that?</p>

答: While it may be possible with jailbreak apps, the SDK does not allow that. You are only allowed your own application's process. It can operate in the background (for a limited amount of time) and/or have however many threads of its own as you say, but they all have to belong to that one process.</p>

ContentLicense: CC BY-SA 2.5

Title: Running subprocess in iOS?


问:
Why does leaflet output grey map?
I run simple examples of leaflet package in R like:

```<code>library(leaflet)
library(ggmap)

>somePlace <-ggmap::geocode("Vienna")
Information from URL : http://maps.googleapis.com/maps/api/geocode/json?address=Vienna&sensor=false
>somePlace
lon      lat
1 16.37382 48.20817
>leaflet(somePlace) %>% addTiles() %>% addMarkers()
</code>```

Map shows grey space with a blue marker:

No trace of OSM spatial visualisation. Could you point out where is the problem?

Thanks in advance for constructive discussion!

My configuration:
R version 3.2.4 (2016-03-10),
Platform: x86_64-w64-mingw32/x64 (64-bit),
Windows Server 2012 x64 (build 9200), ggmap_2.6.1, leaflet_1.0.1.

Similar problems (but without a suitable solution):
R leaflet package produces blank (grey) map [Ubuntu 14.04]
R leaflet RStudio Viewer blank (grey) map [Windows 7]

答:
Try replacing

```<code>addTiles()
</code>```

with

```<code>addProviderTiles(providers$OpenStreetMap)
</code>```

Seems to force leaflet to provide the tiles to knitr's html.

Title: Why does leaflet output grey map?

Body:
I run simple examples of leaflet package in R like:

library(leaflet)
library(ggmap)

>somePlace <-ggmap::geocode("Vienna")
Information from URL : http://maps.googleapis.com/maps/api/geocode/json?address=Vienna&sensor=false
>somePlace
lon      lat
1 16.37382 48.20817
>leaflet(somePlace) %>% addTiles() %>% addMarkers()

Map shows grey space with a blue marker:

No trace of OSM spatial visualisation. Could you point out where is the problem?

Thanks in advance for constructive discussion!

My configuration:
R version 3.2.4 (2016-03-10),
Platform: x86_64-w64-mingw32/x64 (64-bit),
Windows Server 2012 x64 (build 9200), ggmap_2.6.1, leaflet_1.0.1.

Similar problems (but without a suitable solution):
R leaflet package produces blank (grey) map [Ubuntu 14.04]
R leaflet RStudio Viewer blank (grey) map [Windows 7]

Body:
Try replacing

addTiles()

with

addProviderTiles(providers$OpenStreetMap)

Seems to force leaflet to provide the tiles to knitr's html.


问:
How do i remove files from the Pending Changes list in TFS when those files have been deleted locally
as the question says...does anyone know how I can remove these files? I didn't commit the changes in TFS before I deleted them locally and now they always appear in the Pending Changes window...I'd like to get rid of them

thanks

答:
Go to show all files.
The deleted files will be shown.
Delete them.
Done.</p>


问:
How to hide table rows when the value is null
I am creating a project in eclipse where I want to display values input into a form in a table. I want the table to only display the rows which have values, but cannot work out how to do this. So far I have just added multiple rows and am using display:none in order to not display them, but I do not cannot think of a way to get the th:text="${name1}" to display.

Here is an example of the way I am doing it so far:

```<code><table id="table">
    <tr id="tableRow">
      <th class="tableHeader">Name</th>
      <th class="tableHeader">Description</th>
    </tr>
    <tr id="tableRow" style="display:none">
      <td class="tableCell" th:text="${name1}"></td>
      <td class="tableCell" th:text="${description1}"></td>
    </tr>
    <tr id="tableRow" style="display:none">
      <td class="tableCell" th:text="${name2}"></td>
      <td class="tableCell" th:text="${description2}"></td>
    </tr>
    <tr id="tableRow" style="display:none">
      <td class="tableCell" th:text="${name3}"></td>
      <td class="tableCell" th:text="${description3}"></td>
    </tr>
</table>
</code>```

I am relatively new to coding and so any help would be appreciated.

答:
I found a good way to do it using th:each:

```<code>    <table id="table">
        <tr id="tableRow">
            <th class="tableHeader">Name</th>
            <th class="tableHeader">Description</th>
        </tr>
        <tr id="tableRow" th:each="inputMap : ${InputMap}">
            <td class="tableCell" th:text="${inputMap.value.name}"></td>
            <td class="tableCell" th:text="${inputMap.value.description}"></td>
        </tr>
    </table>
</code>```

The ${InputMap} comes from my controller:

```<code>@GetMapping("/tablePage")
public void getTableData(Model model) {

    inputRepository.findAll().forEach(inputObject -> {
        inputMap.put(inputObject.id, inputObject);
    });

    if (inputMap != null){
        inputMap.forEach((id, i) -> {
            model.addAttribute(id + "name", id + i.getName());
            model.addAttribute(id + "description", id + i.getDescription());
        });
    }

    model.addAttribute("InputMap", inputMap);
}
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I am creating a project in eclipse where I want to display values input into a form in a table. I want the table to only display the rows which have values, but cannot work out how to do this. So far I have just added multiple rows and am using display:none in order to not display them, but I do not cannot think of a way to get the th:text="${name1}" to display.

Here is an example of the way I am doing it so far:

      Name
      Description

I am relatively new to coding and so any help would be appreciated.

Body:
I found a good way to do it using th:each:

    <table id="table">
        <tr id="tableRow">
            <th class="tableHeader">Name</th>
            <th class="tableHeader">Description</th>
        </tr>
        <tr id="tableRow" th:each="inputMap : ${InputMap}">
            <td class="tableCell" th:text="${inputMap.value.name}"></td>
            <td class="tableCell" th:text="${inputMap.value.description}"></td>
        </tr>
    </table>

The ${InputMap} comes from my controller:

@GetMapping("/tablePage")
public void getTableData(Model model) {

    inputRepository.findAll().forEach(inputObject -> {
        inputMap.put(inputObject.id, inputObject);
    });

    if (inputMap != null){
        inputMap.forEach((id, i) -> {
            model.addAttribute(id + "name", id + i.getName());
            model.addAttribute(id + "description", id + i.getDescription());
        });
    }

    model.addAttribute("InputMap", inputMap);
}


问:
How to use \copy in psql after connecting to a database via URI in a batch file?
I want to make a .bat file that will go to a directory, change code page (beacuse my folders contain characters from my native language) then open database in psql and then using \copy export some tables from DB to folder on my computer, then quit database and close the command. If I do it manually it works like a charm, but .bat file stops after entering database.

```<code>    cd C:\Program Files\PostgreSQL\9.6\bin
    chcp 1250
    psql "postgres://<heres_my_URI>"
    \copy <table_name> to 'G:\<path>\name.csv' with
 DELIMITER ',' header csv;
    \copy <table_name> to 'G:\<path>\name.csv' with
 DELIMITER ',' header csv;
    \q
    exit
</code>```

I want the .bat file to download csv's to the path and close itself after.

But .bat is doing fine until it enters database, then it just shows:

```<code><mydatabase_name> =>
</code>```

and until I press \q or

```<code>\copy <table_name> to 'G:\<path>\name.csv' with
     DELIMITER ',' header csv;
</code>```

manually, nothing will happen. After I quit DB, it shows me all the errors about \copy not being recognizable. How do I make it work? Thanks for help :)

答:
You need to put all statements to execute by psql in a separate file, not in
the main .bat file:

.bat file:

```<code>chcp 1250
psql "postgres://<heres_my_URI>" -f script.sql
exit
</code>```

script.sql:

```<code>\copy <table_name> to 'G:\<path>\name.csv' with  DELIMITER ',' header csv
\copy <table_name> to 'G:\<path>\name.csv' with  DELIMITER ',' header csv
</code>```

Make sure that each \copy command fits in a single line, because it must. It doesn't have to be ended with a semi-colon though.

Body:
I want to make a .bat file that will go to a directory, change code page (beacuse my folders contain characters from my native language) then open database in psql and then using \copy export some tables from DB to folder on my computer, then quit database and close the command. If I do it manually it works like a charm, but .bat file stops after entering database.

    cd C:\Program Files\PostgreSQL\9.6\bin
    chcp 1250
    psql "postgres://<heres_my_URI>"
    \copy <table_name> to 'G:\<path>\name.csv' with
 DELIMITER ',' header csv;
    \copy <table_name> to 'G:\<path>\name.csv' with
 DELIMITER ',' header csv;
    \q
    exit

I want the .bat file to download csv's to the path and close itself after.

But .bat is doing fine until it enters database, then it just shows:

<mydatabase_name> =>

and until I press \q or

\copy <table_name> to 'G:\<path>\name.csv' with
     DELIMITER ',' header csv;

manually, nothing will happen. After I quit DB, it shows me all the errors about \copy not being recognizable. How do I make it work? Thanks for help :)

Body:
You need to put all statements to execute by psql in a separate file, not in
the main .bat file:

.bat file:

chcp 1250
psql "postgres://<heres_my_URI>" -f script.sql
exit

script.sql:

\copy <table_name> to 'G:\<path>\name.csv' with  DELIMITER ',' header csv
\copy <table_name> to 'G:\<path>\name.csv' with  DELIMITER ',' header csv

Make sure that each \copy command fits in a single line, because it must. It doesn't have to be ended with a semi-colon though.


问:
Logback JaninoEventEvaluator to direct log events to a specific appender
I have a logback-test xml as follows. I wanted to filter out any logs from package org.jdbcds from console and from GENERIC_LOG_FILE and have them in a seperate file under appender SQLFILE. But neither of them works. All the logs from org.jdbcdslog logged in console and in GENERIC_LOG_FILE, but not under the file given in appender SQLFILE. Please help.

```<code>  <configuration scan="true">
    <appender name="CONSOLE" class="ch.qos.logback.core.ConsoleAppender">
        <encoder>
           <pattern>%d{yyyy-MM-dd HH:mm:ss}|%level|%logger|%msg%n</pattern>
        </encoder>
        <filter class="ch.qos.logback.core.filter.EvaluatorFilter">
          <evaluator>
              <expression>return logger.startsWith("org.jdbcdslog")</expression>
           </evaluator>
          <OnMatch>DENY</OnMatch>
          <OnMismatch>NEUTRAL</OnMismatch>
        </filter>
    </appender>
    <appender name="GENERAL_LOG_FILE" class="ch.qos.logback.core.rolling.RollingFileAppender">
          <append>true</append>
           <encoder>
                <pattern>%d{yyyy-MM-dd HH:mm:ss}|%level|%logger|%msg%n</pattern>
           </encoder>
            <filter class="ch.qos.logback.core.filter.EvaluatorFilter">
                <evaluator>
                    <expression>return logger.startsWith("org.jdbcdslog")</expression>
                </evaluator>
                <OnMatch>DENY</OnMatch>
                <OnMismatch>NEUTRAL</OnMismatch>
            </filter>
            <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
                <fileNamePattern>${user.home}/server.abacus.%d{yyyy-MM-dd}.log</fileNamePattern>
                <maxHistory>14</maxHistory>
            </rollingPolicy>
   </appender>
   <appender name="SQLFILE" class="ch.qos.logback.core.rolling.RollingFileAppender">
        <append>true</append>
        <!--<filter class="ch.qos.logback.core.filter.EvaluatorFilter">
            <evaluator>
                <expression>message.contains("TestFinished()")</expression>
            </evaluator>
            <OnMatch>DENY</OnMatch>
            <OnMismatch>NEUTRAL</OnMismatch>
        </filter>-->
        <filter class="ch.qos.logback.core.filter.EvaluatorFilter">
            <evaluator>
                <expression>return logger.startsWith("org.jdbcdslog");</expression>
            </evaluator>
            <OnMatch>ACCEPT</OnMatch>
            <OnMismatch>DENY</OnMismatch>
        </filter>
        <encoder>
            <pattern>%d{yyyy-MM-dd HH:mm:ss}|%level|%logger|%msg%n</pattern>
        </encoder>
        <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
            <!-- daily rollover -->
            <fileNamePattern>${user.home}/all_query.abacus.%d{yyyy-MM-dd}.log</fileNamePattern>
            <maxHistory>14</maxHistory>
        </rollingPolicy>
    </appender>
    <logger name="org.jdbcdslog.SlowQueryLogger" level="INFO"/>
    <logger name="org.jdbcdslog.StatementLogger" level="INFO"/>
    <root level="INFO">
      <appender-ref ref="CONSOLE" />
      <appender-ref ref="GENERAL_LOG_FILE" />
      <appender-ref ref="ERROR_LOG_FILE" />
      <appender-ref ref="PERF_LOG_FILE" />
      <appender-ref ref="SQLFILE" />
      <appender-ref ref="SLOWQUERY_SQLFILE" />
   </root>
</code>```

Update 1:

Here is the modified XML

```<code><configuration scan="true">
    <appender name="CONSOLE" class="ch.qos.logback.core.ConsoleAppender">
        <encoder>
            <pattern>%d{yyyy-MM-dd HH:mm:ss}|%level|%logger|%msg%n</pattern>
        </encoder>
    </appender>
    <appender name="GENERAL_LOG_FILE" class="ch.qos.logback.core.rolling.RollingFileAppender">
        <append>true</append>
        <filter class="ch.qos.logback.core.filter.EvaluatorFilter">
            <evaluator>
                <expression>message.contains("TestFinished()")</expression>
            </evaluator>
            <OnMatch>DENY</OnMatch>
            <OnMismatch>NEUTRAL</OnMismatch>
        </filter>
        <filter class="ch.qos.logback.core.filter.EvaluatorFilter">
            <evaluator>
                <expression>return logger.startsWith("Perf");</expression>
            </evaluator>
            <OnMatch>DENY</OnMatch>
            <OnMismatch>ACCEPT</OnMismatch>
        </filter>
        <encoder>
            <pattern>%d{yyyy-MM-dd HH:mm:ss}|%level|%logger|%msg%n</pattern>
        </encoder>
        <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
            <fileNamePattern>${user.home}/server.abacus.%d{yyyy-MM-dd}.log</fileNamePattern>
            <maxHistory>14</maxHistory>
        </rollingPolicy>
    </appender>
    <appender name="ERROR_LOG_FILE" class="ch.qos.logback.core.rolling.RollingFileAppender">
        <filter class="ch.qos.logback.core.filter.EvaluatorFilter">
            <evaluator>
                <expression>message.contains("TestFinished()")</expression>
            </evaluator>
            <OnMatch>DENY</OnMatch>
            <OnMismatch>NEUTRAL</OnMismatch>
        </filter>
        <filter class="ch.qos.logback.classic.filter.LevelFilter">
            <level>ERROR</level>
            <onMatch>ACCEPT</onMatch>
            <onMismatch>DENY</onMismatch>
        </filter>
        <append>true</append>
        <encoder>
            <pattern>%d{yyyy-MM-dd HH:mm:ss}|%level|%logger|%msg%n</pattern>
        </encoder>
        <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
            <fileNamePattern>${user.home}/server.abacus.error.%d{yyyy-MM-dd}.log</fileNamePattern>
            <maxHistory>14</maxHistory>
        </rollingPolicy>
    </appender>
    <appender name="PERF_LOG_FILE"
        class="ch.qos.logback.core.rolling.RollingFileAppender">
        <append>true</append>
        <filter class="ch.qos.logback.core.filter.EvaluatorFilter">
            <evaluator>
                <expression>message.contains("TestFinished()")</expression>
            </evaluator>
            <OnMatch>DENY</OnMatch>
            <OnMismatch>NEUTRAL</OnMismatch>
        </filter>
        <filter class="ch.qos.logback.core.filter.EvaluatorFilter">
            <evaluator>
                <expression>return logger.startsWith("Perf");</expression>
            </evaluator>
            <OnMatch>ACCEPT</OnMatch>
            <OnMismatch>DENY</OnMismatch>
        </filter>
        <encoder>
            <pattern>%d{yyyy-MM-dd HH:mm:ss}|%level|%logger|%msg%n</pattern>
        </encoder>
        <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
            <!-- daily rollover -->
            <fileNamePattern>${user.home}/perf.abacus.%d{yyyy-MM-dd}.log</fileNamePattern>
            <maxHistory>14</maxHistory>
        </rollingPolicy>
    </appender>
    <appender name="SQLFILE"
        class="ch.qos.logback.core.rolling.RollingFileAppender">
        <append>true</append>
        <encoder>
            <pattern>%d{yyyy-MM-dd HH:mm:ss}|%level|%logger|%msg%n</pattern>
        </encoder>
        <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
            <!-- daily rollover -->
            <fileNamePattern>${user.home}/all_query.%d{yyyy-MM-dd}.log</fileNamePattern>
            <maxHistory>14</maxHistory>
        </rollingPolicy>
    </appender>
    <appender name="SLOWQUERY_SQLFILE"
        class="ch.qos.logback.core.rolling.RollingFileAppender">
        <append>true</append>
        <encoder>
            <pattern>%d{yyyy-MM-dd HH:mm:ss}|%level|%logger|%msg%n</pattern>
        </encoder>
        <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
            <fileNamePattern>${user.home}/slow_query.%d{yyyy-MM-dd}.log</fileNamePattern>
            <maxHistory>14</maxHistory>
        </rollingPolicy>
    </appender>
    <logger name="ab.xyz" level="INFO" />
    <logger name="bd.xyz" level="INFO" />
    <logger name="net.sf.hibernate" level="WARN" />
    <logger name="org.springframework" level="WARN" />
    <logger name="jdbc.sqlonly" level="ERROR" />
    <logger name="Perf" level="INFO" />
    <logger name="org.jdbcdslog.SlowQueryLogger" level="INFO" additivity="false">
        <appender-ref ref="SLOWQUERY_SQLFILE" />
    </logger>
    <logger name="org.jdbcdslog.StatementLogger" level="INFO" additivity="false">
        <appender-ref ref="SQLFILE" />
    </logger>
    <logger name="org.jdbcdslog.ConnectionLogger" level="ERROR"/>
    <logger name="org.jdbcdslog.ResultSetLogger" level="ERROR"/>

    <root level="INFO">
        <appender-ref ref="CONSOLE" />
        <appender-ref ref="GENERAL_LOG_FILE" />
        <appender-ref ref="ERROR_LOG_FILE" />
        <appender-ref ref="PERF_LOG_FILE" />
    </root>

</configuration>
</code>```

Update 2:

```<code><configuration scan="true">
    <appender name="CONSOLE" class="ch.qos.logback.core.ConsoleAppender">
        <encoder>
            <pattern>%d{yyyy-MM-dd HH:mm:ss}|%level|%logger|%msg%n</pattern>
        </encoder>
    </appender>
    <appender name="GENERAL_LOG_FILE" class="ch.qos.logback.core.rolling.RollingFileAppender">
        <append>true</append>
        <filter class="ch.qos.logback.core.filter.EvaluatorFilter">
            <evaluator>
                <expression>message.contains("TestFinished()")</expression>
            </evaluator>
            <OnMatch>DENY</OnMatch>
            <OnMismatch>NEUTRAL</OnMismatch>
        </filter>
        <filter class="ch.qos.logback.core.filter.EvaluatorFilter">
            <evaluator>
                <expression>return logger.startsWith("Perf");</expression>
            </evaluator>
            <OnMatch>DENY</OnMatch>
            <OnMismatch>ACCEPT</OnMismatch>
        </filter>
        <encoder>
            <pattern>%d{yyyy-MM-dd HH:mm:ss}|%level|%logger|%msg%n</pattern>
        </encoder>
        <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
            <fileNamePattern>${user.home}/server.abacus.%d{yyyy-MM-dd}.log</fileNamePattern>
            <maxHistory>14</maxHistory>
        </rollingPolicy>
    </appender>
    <appender name="ERROR_LOG_FILE" class="ch.qos.logback.core.rolling.RollingFileAppender">
        <filter class="ch.qos.logback.core.filter.EvaluatorFilter">
            <evaluator>
                <expression>message.contains("TestFinished()")</expression>
            </evaluator>
            <OnMatch>DENY</OnMatch>
            <OnMismatch>NEUTRAL</OnMismatch>
        </filter>
        <filter class="ch.qos.logback.classic.filter.LevelFilter">
            <level>ERROR</level>
            <onMatch>ACCEPT</onMatch>
            <onMismatch>DENY</onMismatch>
        </filter>
        <append>true</append>
        <encoder>
            <pattern>%d{yyyy-MM-dd HH:mm:ss}|%level|%logger|%msg%n</pattern>
        </encoder>
        <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
            <fileNamePattern>${user.home}/server.abacus.error.%d{yyyy-MM-dd}.log</fileNamePattern>
            <maxHistory>14</maxHistory>
        </rollingPolicy>
    </appender>
    <appender name="PERF_LOG_FILE"
        class="ch.qos.logback.core.rolling.RollingFileAppender">
        <append>true</append>
        <filter class="ch.qos.logback.core.filter.EvaluatorFilter">
            <evaluator>
                <expression>message.contains("TestFinished()")</expression>
            </evaluator>
            <OnMatch>DENY</OnMatch>
            <OnMismatch>NEUTRAL</OnMismatch>
        </filter>
        <filter class="ch.qos.logback.core.filter.EvaluatorFilter">
            <evaluator>
                <expression>return logger.startsWith("Perf");</expression>
            </evaluator>
            <OnMatch>ACCEPT</OnMatch>
            <OnMismatch>DENY</OnMismatch>
        </filter>
        <encoder>
            <pattern>%d{yyyy-MM-dd HH:mm:ss}|%level|%logger|%msg%n</pattern>
        </encoder>
        <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
            <!-- daily rollover -->
            <fileNamePattern>${user.home}/perf.abacus.%d{yyyy-MM-dd}.log</fileNamePattern>
            <maxHistory>14</maxHistory>
        </rollingPolicy>
    </appender>
    <appender name="SQLFILE"
        class="ch.qos.logback.core.rolling.RollingFileAppender">
        <append>true</append>
        <encoder>
            <pattern>%d{yyyy-MM-dd HH:mm:ss}|%level|%logger|%msg%n</pattern>
        </encoder>
        <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
            <!-- daily rollover -->
            <fileNamePattern>${user.home}/all_query.%d{yyyy-MM-dd}.log</fileNamePattern>
            <maxHistory>14</maxHistory>
        </rollingPolicy>
    </appender>
    <appender name="SLOWQUERY_SQLFILE"
        class="ch.qos.logback.core.rolling.RollingFileAppender">
        <append>true</append>
        <encoder>
            <pattern>%d{yyyy-MM-dd HH:mm:ss}|%level|%logger|%msg%n</pattern>
        </encoder>
        <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
            <fileNamePattern>${user.home}/slow_query.%d{yyyy-MM-dd}.log</fileNamePattern>
            <maxHistory>14</maxHistory>
        </rollingPolicy>
    </appender>
    <logger name="ab.xyz" level="INFO" />
    <logger name="cd.xyz" level="INFO" />
    <logger name="net.sf.hibernate" level="WARN" />
    <logger name="org.springframework" level="WARN" />
    <logger name="jdbc.sqlonly" level="ERROR" />
    <logger name="Perf" level="INFO" />
    <logger name="org.jdbcdslog.SlowQueryLogger" level="INFO" additivity="false">
        <appender-ref ref="SLOWQUERY_SQLFILE" />
    </logger>
    <logger name="org.jdbcdslog.StatementLogger" level="INFO" additivity="false">
        <appender-ref ref="SQLFILE" />
    </logger>
    <logger name="org.jdbcdslog.ConnectionLogger" level="ERROR"/>
    <logger name="org.jdbcdslog.ResultSetLogger" level="ERROR"/>

    <root level="INFO">
        <appender-ref ref="CONSOLE" />
        <appender-ref ref="GENERAL_LOG_FILE" />
        <appender-ref ref="ERROR_LOG_FILE" />
        <appender-ref ref="PERF_LOG_FILE" />
        <appender-ref ref="SQLFILE" />
        <appender-ref ref="SLOWQUERY_SQLFILE" />
    </root>
</configuration>
</code>```

答:
In order to achieve this:

I wanted to filter out any logs from package org.jdbcds from console and from GENERIC_LOG_FILE and have them in a seperate file under appender SQLFILE

I don't think you need to use Janino, you can instead associate the org.jdbcds logger with the SQLFILE appender and use additivity=false to prevent this logger from being forwarded to other appenders.

For example:

```<code><!-- direct logging from org.jdbcds to the SQLFILE appender and _only_ to the SQLFILE appender -->
<logger name="org.jdbcds" additivity="false">
    <appender-ref ref="SQLFILE" />
</logger>
</code>```

Body:
I have a logback-test xml as follows. I wanted to filter out any logs from package org.jdbcds from console and from GENERIC_LOG_FILE and have them in a seperate file under appender SQLFILE. But neither of them works. All the logs from org.jdbcdslog logged in console and in GENERIC_LOG_FILE, but not under the file given in appender SQLFILE. Please help.

  <configuration scan="true">
    <appender name="CONSOLE" class="ch.qos.logback.core.ConsoleAppender">
        <encoder>
           <pattern>%d{yyyy-MM-dd HH:mm:ss}|%level|%logger|%msg%n</pattern>
        </encoder>
        <filter class="ch.qos.logback.core.filter.EvaluatorFilter">
          <evaluator>
              <expression>return logger.startsWith("org.jdbcdslog")</expression>
           </evaluator>
          <OnMatch>DENY</OnMatch>
          <OnMismatch>NEUTRAL</OnMismatch>
        </filter>
    </appender>
    <appender name="GENERAL_LOG_FILE" class="ch.qos.logback.core.rolling.RollingFileAppender">
          <append>true</append>
           <encoder>
                <pattern>%d{yyyy-MM-dd HH:mm:ss}|%level|%logger|%msg%n</pattern>
           </encoder>
            <filter class="ch.qos.logback.core.filter.EvaluatorFilter">
                <evaluator>
                    <expression>return logger.startsWith("org.jdbcdslog")</expression>
                </evaluator>
                <OnMatch>DENY</OnMatch>
                <OnMismatch>NEUTRAL</OnMismatch>
            </filter>
            <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
                <fileNamePattern>${user.home}/server.abacus.%d{yyyy-MM-dd}.log</fileNamePattern>
                <maxHistory>14</maxHistory>
            </rollingPolicy>
   </appender>
   <appender name="SQLFILE" class="ch.qos.logback.core.rolling.RollingFileAppender">
        <append>true</append>

        <filter class="ch.qos.logback.core.filter.EvaluatorFilter">
            <evaluator>
                <expression>return logger.startsWith("org.jdbcdslog");</expression>
            </evaluator>
            <OnMatch>ACCEPT</OnMatch>
            <OnMismatch>DENY</OnMismatch>
        </filter>
        <encoder>
            <pattern>%d{yyyy-MM-dd HH:mm:ss}|%level|%logger|%msg%n</pattern>
        </encoder>
        <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">

            <fileNamePattern>${user.home}/all_query.abacus.%d{yyyy-MM-dd}.log</fileNamePattern>
            <maxHistory>14</maxHistory>
        </rollingPolicy>
    </appender>
    <logger name="org.jdbcdslog.SlowQueryLogger" level="INFO"/>
    <logger name="org.jdbcdslog.StatementLogger" level="INFO"/>
    <root level="INFO">
      <appender-ref ref="CONSOLE" />
      <appender-ref ref="GENERAL_LOG_FILE" />
      <appender-ref ref="ERROR_LOG_FILE" />
      <appender-ref ref="PERF_LOG_FILE" />
      <appender-ref ref="SQLFILE" />
      <appender-ref ref="SLOWQUERY_SQLFILE" />
   </root>

Update 1:

Here is the modified XML

<configuration scan="true">
    <appender name="CONSOLE" class="ch.qos.logback.core.ConsoleAppender">
        <encoder>
            <pattern>%d{yyyy-MM-dd HH:mm:ss}|%level|%logger|%msg%n</pattern>
        </encoder>
    </appender>
    <appender name="GENERAL_LOG_FILE" class="ch.qos.logback.core.rolling.RollingFileAppender">
        <append>true</append>
        <filter class="ch.qos.logback.core.filter.EvaluatorFilter">
            <evaluator>
                <expression>message.contains("TestFinished()")</expression>
            </evaluator>
            <OnMatch>DENY</OnMatch>
            <OnMismatch>NEUTRAL</OnMismatch>
        </filter>
        <filter class="ch.qos.logback.core.filter.EvaluatorFilter">
            <evaluator>
                <expression>return logger.startsWith("Perf");</expression>
            </evaluator>
            <OnMatch>DENY</OnMatch>
            <OnMismatch>ACCEPT</OnMismatch>
        </filter>
        <encoder>
            <pattern>%d{yyyy-MM-dd HH:mm:ss}|%level|%logger|%msg%n</pattern>
        </encoder>
        <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
            <fileNamePattern>${user.home}/server.abacus.%d{yyyy-MM-dd}.log</fileNamePattern>
            <maxHistory>14</maxHistory>
        </rollingPolicy>
    </appender>
    <appender name="ERROR_LOG_FILE" class="ch.qos.logback.core.rolling.RollingFileAppender">
        <filter class="ch.qos.logback.core.filter.EvaluatorFilter">
            <evaluator>
                <expression>message.contains("TestFinished()")</expression>
            </evaluator>
            <OnMatch>DENY</OnMatch>
            <OnMismatch>NEUTRAL</OnMismatch>
        </filter>
        <filter class="ch.qos.logback.classic.filter.LevelFilter">
            <level>ERROR</level>
            <onMatch>ACCEPT</onMatch>
            <onMismatch>DENY</onMismatch>
        </filter>
        <append>true</append>
        <encoder>
            <pattern>%d{yyyy-MM-dd HH:mm:ss}|%level|%logger|%msg%n</pattern>
        </encoder>
        <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
            <fileNamePattern>${user.home}/server.abacus.error.%d{yyyy-MM-dd}.log</fileNamePattern>
            <maxHistory>14</maxHistory>
        </rollingPolicy>
    </appender>
    <appender name="PERF_LOG_FILE"
        class="ch.qos.logback.core.rolling.RollingFileAppender">
        <append>true</append>
        <filter class="ch.qos.logback.core.filter.EvaluatorFilter">
            <evaluator>
                <expression>message.contains("TestFinished()")</expression>
            </evaluator>
            <OnMatch>DENY</OnMatch>
            <OnMismatch>NEUTRAL</OnMismatch>
        </filter>
        <filter class="ch.qos.logback.core.filter.EvaluatorFilter">
            <evaluator>
                <expression>return logger.startsWith("Perf");</expression>
            </evaluator>
            <OnMatch>ACCEPT</OnMatch>
            <OnMismatch>DENY</OnMismatch>
        </filter>
        <encoder>
            <pattern>%d{yyyy-MM-dd HH:mm:ss}|%level|%logger|%msg%n</pattern>
        </encoder>
        <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">

            <fileNamePattern>${user.home}/perf.abacus.%d{yyyy-MM-dd}.log</fileNamePattern>
            <maxHistory>14</maxHistory>
        </rollingPolicy>
    </appender>
    <appender name="SQLFILE"
        class="ch.qos.logback.core.rolling.RollingFileAppender">
        <append>true</append>
        <encoder>
            <pattern>%d{yyyy-MM-dd HH:mm:ss}|%level|%logger|%msg%n</pattern>
        </encoder>
        <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">

            <fileNamePattern>${user.home}/all_query.%d{yyyy-MM-dd}.log</fileNamePattern>
            <maxHistory>14</maxHistory>
        </rollingPolicy>
    </appender>
    <appender name="SLOWQUERY_SQLFILE"
        class="ch.qos.logback.core.rolling.RollingFileAppender">
        <append>true</append>
        <encoder>
            <pattern>%d{yyyy-MM-dd HH:mm:ss}|%level|%logger|%msg%n</pattern>
        </encoder>
        <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
            <fileNamePattern>${user.home}/slow_query.%d{yyyy-MM-dd}.log</fileNamePattern>
            <maxHistory>14</maxHistory>
        </rollingPolicy>
    </appender>
    <logger name="ab.xyz" level="INFO" />
    <logger name="bd.xyz" level="INFO" />
    <logger name="net.sf.hibernate" level="WARN" />
    <logger name="org.springframework" level="WARN" />
    <logger name="jdbc.sqlonly" level="ERROR" />
    <logger name="Perf" level="INFO" />
    <logger name="org.jdbcdslog.SlowQueryLogger" level="INFO" additivity="false">
        <appender-ref ref="SLOWQUERY_SQLFILE" />
    </logger>
    <logger name="org.jdbcdslog.StatementLogger" level="INFO" additivity="false">
        <appender-ref ref="SQLFILE" />
    </logger>
    <logger name="org.jdbcdslog.ConnectionLogger" level="ERROR"/>
    <logger name="org.jdbcdslog.ResultSetLogger" level="ERROR"/>

    <root level="INFO">
        <appender-ref ref="CONSOLE" />
        <appender-ref ref="GENERAL_LOG_FILE" />
        <appender-ref ref="ERROR_LOG_FILE" />
        <appender-ref ref="PERF_LOG_FILE" />
    </root>

</configuration>

Update 2:

<configuration scan="true">
    <appender name="CONSOLE" class="ch.qos.logback.core.ConsoleAppender">
        <encoder>
            <pattern>%d{yyyy-MM-dd HH:mm:ss}|%level|%logger|%msg%n</pattern>
        </encoder>
    </appender>
    <appender name="GENERAL_LOG_FILE" class="ch.qos.logback.core.rolling.RollingFileAppender">
        <append>true</append>
        <filter class="ch.qos.logback.core.filter.EvaluatorFilter">
            <evaluator>
                <expression>message.contains("TestFinished()")</expression>
            </evaluator>
            <OnMatch>DENY</OnMatch>
            <OnMismatch>NEUTRAL</OnMismatch>
        </filter>
        <filter class="ch.qos.logback.core.filter.EvaluatorFilter">
            <evaluator>
                <expression>return logger.startsWith("Perf");</expression>
            </evaluator>
            <OnMatch>DENY</OnMatch>
            <OnMismatch>ACCEPT</OnMismatch>
        </filter>
        <encoder>
            <pattern>%d{yyyy-MM-dd HH:mm:ss}|%level|%logger|%msg%n</pattern>
        </encoder>
        <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
            <fileNamePattern>${user.home}/server.abacus.%d{yyyy-MM-dd}.log</fileNamePattern>
            <maxHistory>14</maxHistory>
        </rollingPolicy>
    </appender>
    <appender name="ERROR_LOG_FILE" class="ch.qos.logback.core.rolling.RollingFileAppender">
        <filter class="ch.qos.logback.core.filter.EvaluatorFilter">
            <evaluator>
                <expression>message.contains("TestFinished()")</expression>
            </evaluator>
            <OnMatch>DENY</OnMatch>
            <OnMismatch>NEUTRAL</OnMismatch>
        </filter>
        <filter class="ch.qos.logback.classic.filter.LevelFilter">
            <level>ERROR</level>
            <onMatch>ACCEPT</onMatch>
            <onMismatch>DENY</onMismatch>
        </filter>
        <append>true</append>
        <encoder>
            <pattern>%d{yyyy-MM-dd HH:mm:ss}|%level|%logger|%msg%n</pattern>
        </encoder>
        <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
            <fileNamePattern>${user.home}/server.abacus.error.%d{yyyy-MM-dd}.log</fileNamePattern>
            <maxHistory>14</maxHistory>
        </rollingPolicy>
    </appender>
    <appender name="PERF_LOG_FILE"
        class="ch.qos.logback.core.rolling.RollingFileAppender">
        <append>true</append>
        <filter class="ch.qos.logback.core.filter.EvaluatorFilter">
            <evaluator>
                <expression>message.contains("TestFinished()")</expression>
            </evaluator>
            <OnMatch>DENY</OnMatch>
            <OnMismatch>NEUTRAL</OnMismatch>
        </filter>
        <filter class="ch.qos.logback.core.filter.EvaluatorFilter">
            <evaluator>
                <expression>return logger.startsWith("Perf");</expression>
            </evaluator>
            <OnMatch>ACCEPT</OnMatch>
            <OnMismatch>DENY</OnMismatch>
        </filter>
        <encoder>
            <pattern>%d{yyyy-MM-dd HH:mm:ss}|%level|%logger|%msg%n</pattern>
        </encoder>
        <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">

            <fileNamePattern>${user.home}/perf.abacus.%d{yyyy-MM-dd}.log</fileNamePattern>
            <maxHistory>14</maxHistory>
        </rollingPolicy>
    </appender>
    <appender name="SQLFILE"
        class="ch.qos.logback.core.rolling.RollingFileAppender">
        <append>true</append>
        <encoder>
            <pattern>%d{yyyy-MM-dd HH:mm:ss}|%level|%logger|%msg%n</pattern>
        </encoder>
        <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">

            <fileNamePattern>${user.home}/all_query.%d{yyyy-MM-dd}.log</fileNamePattern>
            <maxHistory>14</maxHistory>
        </rollingPolicy>
    </appender>
    <appender name="SLOWQUERY_SQLFILE"
        class="ch.qos.logback.core.rolling.RollingFileAppender">
        <append>true</append>
        <encoder>
            <pattern>%d{yyyy-MM-dd HH:mm:ss}|%level|%logger|%msg%n</pattern>
        </encoder>
        <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
            <fileNamePattern>${user.home}/slow_query.%d{yyyy-MM-dd}.log</fileNamePattern>
            <maxHistory>14</maxHistory>
        </rollingPolicy>
    </appender>
    <logger name="ab.xyz" level="INFO" />
    <logger name="cd.xyz" level="INFO" />
    <logger name="net.sf.hibernate" level="WARN" />
    <logger name="org.springframework" level="WARN" />
    <logger name="jdbc.sqlonly" level="ERROR" />
    <logger name="Perf" level="INFO" />
    <logger name="org.jdbcdslog.SlowQueryLogger" level="INFO" additivity="false">
        <appender-ref ref="SLOWQUERY_SQLFILE" />
    </logger>
    <logger name="org.jdbcdslog.StatementLogger" level="INFO" additivity="false">
        <appender-ref ref="SQLFILE" />
    </logger>
    <logger name="org.jdbcdslog.ConnectionLogger" level="ERROR"/>
    <logger name="org.jdbcdslog.ResultSetLogger" level="ERROR"/>

    <root level="INFO">
        <appender-ref ref="CONSOLE" />
        <appender-ref ref="GENERAL_LOG_FILE" />
        <appender-ref ref="ERROR_LOG_FILE" />
        <appender-ref ref="PERF_LOG_FILE" />
        <appender-ref ref="SQLFILE" />
        <appender-ref ref="SLOWQUERY_SQLFILE" />
    </root>
</configuration>

Body:
In order to achieve this:

I wanted to filter out any logs from package org.jdbcds from console and from GENERIC_LOG_FILE and have them in a seperate file under appender SQLFILE

I don't think you need to use Janino, you can instead associate the org.jdbcds logger with the SQLFILE appender and use additivity=false to prevent this logger from being forwarded to other appenders.

For example:

<!-- direct logging from org.jdbcds to the SQLFILE appender and _only_ to the SQLFILE appender -->
<logger name="org.jdbcds" additivity="false">
    <appender-ref ref="SQLFILE" />
</logger>


问:
returning single result using LINQ
I have a query

```<code>row.GetChildRows("EventCategoryRelation")
  .Where(categoryRow => categoryRow["event_id"].ToString() == eventObject.EventId.ToString())
  .Select(x => Int32.Parse(x["category_id"].ToString()))
</code>```

This query returns an IEnumerable. I am expecting an 'int'

Help me modify my LINQ query

答:
Depending on your data add .FirstOrDefault, .SingleOrDefault(), .First() etc.

```<code>ow.GetChildRows("EventCategoryRelation")
  .Where(categoryRow => categoryRow["event_id"].ToString() == eventObject.EventId.ToString())
  .Select(x => Int32.Parse(x["category_id"].ToString())).FirstOrDefault()
</code>```

When you expect multiple rows, use First (FirstOrDefault if you dont want an exception if there is no data returned).  Multiple rows will throw an exception on Single or SingleOrDefault.

Title: returning single result using LINQ

Body:
I have a query

row.GetChildRows("EventCategoryRelation")
  .Where(categoryRow => categoryRow["event_id"].ToString() == eventObject.EventId.ToString())
  .Select(x => Int32.Parse(x["category_id"].ToString()))

This query returns an IEnumerable. I am expecting an 'int'

Help me modify my LINQ query

Body:
Depending on your data add .FirstOrDefault, .SingleOrDefault(), .First() etc.

ow.GetChildRows("EventCategoryRelation")
  .Where(categoryRow => categoryRow["event_id"].ToString() == eventObject.EventId.ToString())
  .Select(x => Int32.Parse(x["category_id"].ToString())).FirstOrDefault()

When you expect multiple rows, use First (FirstOrDefault if you dont want an exception if there is no data returned).  Multiple rows will throw an exception on Single or SingleOrDefault.


问:
Count number of Special Character in Unix Shell
I have a delimited file that is separated by octal \036 or Hexadecimal value 1e.

I need to count the number of delimiters on each line using a bash shell script.

I was trying to use awk, not sure if this is the best way.

Sample Input (| is a representation of \036)

```<code>Example|Running|123|
</code>```

Expected output:

```<code>3
</code>```

答:
Awk may not be the best tool for this.  Gnu grep has a cool -o option that prints each matching pattern on a separate line.  You can then count how many matching lines are generated for each input line, and that's the count of your delimiters.  E.g. (where ^^ in the file is actually hex 1e)

```<code>$ cat -v i
a^^b^^c
d^^e^^f^^g

$ grep -n -o $'\x1e' i | uniq -c
      2 1:
      3 2:
</code>```

if you remove the uniq -c you can see how it's working.  You'll get "1" printed twice because there are two matching patterns on the first line.  Or try it with some regular ascii characters and it becomes clearer what the -o and -n options are doing.

If you want to print the line number followed by the field count for that line, I'd do something like:

```<code>$grep -n -o $'\x1e' i | tr -d ':' | uniq -c | awk '{print $2 " " $1}'
1 2
2 3
</code>```

This assumes that every line in the file contains at least one delimiter.  If that's not the case, here's another approach that's probably faster too:

```<code>$ tr -d -c $'\x1e\n' < i | awk '{print length}'
2
3
0
0
0
</code>```

This uses tr to delete (-d) all characters that are not (-c) 1e or \n.  It then pipes that stream of data to awk which just counts how many characters are left on each line.  If you want the line number, add " | cat -n" to the end.

Body:
I have a delimited file that is separated by octal \036 or Hexadecimal value 1e.

I need to count the number of delimiters on each line using a bash shell script.

I was trying to use awk, not sure if this is the best way.

Sample Input (| is a representation of \036)

Example|Running|123|

Expected output:

3

Body:
Awk may not be the best tool for this.  Gnu grep has a cool -o option that prints each matching pattern on a separate line.  You can then count how many matching lines are generated for each input line, and that's the count of your delimiters.  E.g. (where ^^ in the file is actually hex 1e)

$ cat -v i
a^^b^^c
d^^e^^f^^g

$ grep -n -o $'\x1e' i | uniq -c
      2 1:
      3 2:

if you remove the uniq -c you can see how it's working.  You'll get "1" printed twice because there are two matching patterns on the first line.  Or try it with some regular ascii characters and it becomes clearer what the -o and -n options are doing.

If you want to print the line number followed by the field count for that line, I'd do something like:

$grep -n -o $'\x1e' i | tr -d ':' | uniq -c | awk '{print $2 " " $1}'
1 2
2 3

This assumes that every line in the file contains at least one delimiter.  If that's not the case, here's another approach that's probably faster too:

$ tr -d -c $'\x1e\n' < i | awk '{print length}'
2
3
0
0
0

This uses tr to delete (-d) all characters that are not (-c) 1e or \n.  It then pipes that stream of data to awk which just counts how many characters are left on each line.  If you want the line number, add " | cat -n" to the end.


问:
Pandas: chunking of a dictionary of dataframes based on time
I have a dictionary of dataframes where each dataframe has price and timestamp columns. something like this {'A':df1, 'B':df2}

I need to build a function which can slice up the dataframes inside the dict in chunks of H hours of the timestamp and then pass this dict of dataframes to another function(which does some computation) for every chunk.

How do I go forward with this?

For example

```<code>def foo(dict_of_dataframes):
    for id, df in dict_of_dataframes.items():
        do_something()

def boo(dict_of_dataframes, chunksize):
    """
    Needs to chunk up the @dict_of_dataframes in @chunksize hours
    and needs to call foo function on these chunks of
    @dicts_of_dataframes
    """
</code>```

Sample data:

```<code>df1:
Time                       Price
2017-03-07 09:47:31+00:00  100
2017-03-07 11:27:31+00:00  120
2017-03-07 14:47:31+00:00  150
2017-03-07 17:17:31+00:00  135
2017-03-07 20:57:31+00:00  200
2017-03-08 03:27:31+00:00  120
2017-03-08 09:57:31+00:00  100
2017-03-08 11:27:31+00:00  150

df2:
Time                       Price
2017-03-07 09:07:31+00:00  200
2017-03-07 10:27:31+00:00  300
2017-03-07 12:47:31+00:00  100
2017-03-07 17:47:31+00:00  250
2017-03-07 22:27:31+00:00  300
2017-03-08 01:57:31+00:00  500
2017-03-08 02:57:31+00:00  500
2017-03-08 10:27:31+00:00  100
</code>```

I need help with the boo function. How does one go forward with this?

Also is there any specific term for these kinds of boo functions which simulate other function calling. I've seen these a few times, If you could point to a resource which explains how to design these 'function caller' functions, I'd really appreciate that.

答:
I think what you actually want can be achieved using resample - basically a groupby for datetimes. Assuming you need transaction sum within 6 hours, you can use this:

```<code>def boo(dict_dfs, hours):
    return {k: v.resample(f'{hours}H').sum() for k,v in dict_dfs.items()}
</code>```

now, if you 100% sure you need dicts instead, use groupby:

```<code>def boo(dict_dfs, hours):
    return {k:{hr:v for hr, v in df.groupby(Grouper(key='Time', freq=f'{hours}H'))} for k, df in dict_dfs.items()}
</code>```

Btw, if you want to loop through {key, value} on dicts, use dict.items(), not dict itself.

And one more note: I saw many times people overcomplicating their data structures. Most of the time you don't need dict of dataframes - you can use one dataframe, just having a category column or even a multi-index (like, [category, Time] multi-index in your case. With that, you'll get more reusable, fast and clean code!

Body:
I have a dictionary of dataframes where each dataframe has price and timestamp columns. something like this {'A':df1, 'B':df2}

I need to build a function which can slice up the dataframes inside the dict in chunks of H hours of the timestamp and then pass this dict of dataframes to another function(which does some computation) for every chunk.

How do I go forward with this?

For example

def foo(dict_of_dataframes):
    for id, df in dict_of_dataframes.items():
        do_something()

def boo(dict_of_dataframes, chunksize):
    """
    Needs to chunk up the @dict_of_dataframes in @chunksize hours
    and needs to call foo function on these chunks of
    @dicts_of_dataframes
    """

Sample data:

df1:
Time                       Price
2017-03-07 09:47:31+00:00  100
2017-03-07 11:27:31+00:00  120
2017-03-07 14:47:31+00:00  150
2017-03-07 17:17:31+00:00  135
2017-03-07 20:57:31+00:00  200
2017-03-08 03:27:31+00:00  120
2017-03-08 09:57:31+00:00  100
2017-03-08 11:27:31+00:00  150

df2:
Time                       Price
2017-03-07 09:07:31+00:00  200
2017-03-07 10:27:31+00:00  300
2017-03-07 12:47:31+00:00  100
2017-03-07 17:47:31+00:00  250
2017-03-07 22:27:31+00:00  300
2017-03-08 01:57:31+00:00  500
2017-03-08 02:57:31+00:00  500
2017-03-08 10:27:31+00:00  100

I need help with the boo function. How does one go forward with this?

Also is there any specific term for these kinds of boo functions which simulate other function calling. I've seen these a few times, If you could point to a resource which explains how to design these 'function caller' functions, I'd really appreciate that.

Body:
I think what you actually want can be achieved using resample - basically a groupby for datetimes. Assuming you need transaction sum within 6 hours, you can use this:

def boo(dict_dfs, hours):
    return {k: v.resample(f'{hours}H').sum() for k,v in dict_dfs.items()}

now, if you 100% sure you need dicts instead, use groupby:

def boo(dict_dfs, hours):
    return {k:{hr:v for hr, v in df.groupby(Grouper(key='Time', freq=f'{hours}H'))} for k, df in dict_dfs.items()}

Btw, if you want to loop through {key, value} on dicts, use dict.items(), not dict itself.

And one more note: I saw many times people overcomplicating their data structures. Most of the time you don't need dict of dataframes - you can use one dataframe, just having a category column or even a multi-index (like, [category, Time] multi-index in your case. With that, you'll get more reusable, fast and clean code!


问:
How to disable pydev code analysis and keep pylint code analysis
In PyDev <= 5.6.0 I could disable the PyDev code analysis while still having PyLint do its work. I assume this was because PyLint was decoupled from the PyDev code analysis (it also had its own place in the PyDev->Editor Preferences).

Nowadays, PyLint seems to be integrated in PyDevs analysis. So, unfortunately, if I uncheck "Do code analysis?" there, I not only disable PyDev's, but also PyLint's code analysis, no matter if I choose "Use Pylint?" or not.

Is there any way to have PyLint running and PyDev's code analysis deactived at the same time in the current PyDev version?

答:
This is probably a side-effect on the improvements done in PyDev 5.7.0.

Please report this at https://www.brainwy.com/tracker/PyDev as I think those settings should really be decoupled (i.e.: this is a bug and should be fixed).

So, now that we agree that they should be decoupled, I'm curious on why exactly would you like only the PyLint code analysis and not the PyDev one -- my rationale here is that the PyDev code analysis is much faster, works on unsaved files, usually has less false positives and in the current version the same report from PyDev or PyLint should be reported only once.


答:
Add a First() clause to the query:

```<code>row.GetChildRows("EventCategoryRelation")
  .Where(categoryRow => categoryRow["event_id"].ToString() == eventObject.EventId.ToString())
  .Select(x => Int32.Parse(x["category_id"].ToString()))
  .First()
</code>```

You may want to use FirstOfDefault() in case there are no results, as First() will throw an exception in such a case.

Title: returning single result using LINQ

Body:
Add a First() clause to the query:

row.GetChildRows("EventCategoryRelation")
  .Where(categoryRow => categoryRow["event_id"].ToString() == eventObject.EventId.ToString())
  .Select(x => Int32.Parse(x["category_id"].ToString()))
  .First()

You may want to use FirstOfDefault() in case there are no results, as First() will throw an exception in such a case.


问:
Threejs edge helper
I'm new to Threejs and I have been using the EdgesHelper which achieves the look I want for now. But I have two questions...

What is the default edge width/how is it calculated?

Can the edge width be changed...

I have searched around and I'm pretty sure that due to some limitation (not of threejs of Windows I believe) that there is no simple method to change the thickness of the edges (?).  Alot of the examples I found that have thicker edges would only work on a particular geometry (e.g. doesn't seem universal).

Perhaps I am wrong but I would have thought that this would be a very common requirement? Rather then spend hours/days/weeks trying to get what i want myself (which I'm not even sure I personally would be able to do), does anyone know of a way to have control over the edge thickness, an existing example or a library that someone has already done that can work on any shape (any imported obj for example)

Many thanks

答: Coming back to this as Wilt mentioned there are other threads on this.  Basically you cannot change the thickness due to a limitation in ANGLE, there are some work around like the THREE.MeshLine (also mentioned in the link Wilt stated) but i found most work aroudns had some limitations for what I wanted</p>

Title: Threejs edge helper


问:
Canvas scaler issue - displaying differently in browser and on phone
I have this issue with my canvas scaler. I'm designing in Unity on my PC where it correctly displays how it's supposed to look. However, it looks very different in both the browser on my PC and on my android phone.

PC - Unity:

PC browser / Android phone (OnePlus 5):

Unity scene:

Canvas scaler settings:

Everything is inside my canvas. I've tried tweaking the canvas scaler settings over and over again but with no luck. What could I be doing wrong? I'm using Unity 5.6.3p1.

答:
The canvas scaling looks to be working as expected.

However have you set your anchors correctly?

I would anchor your four buttons/images to each adjacent corner.

I would then anchor your center image to the center top and center bottom of the canvas.

Then when you switch screen size, the canvas scaler will keep things in relative place to the display screen.

See the unity docs on how to manage anchors.

UI Anchors:
https://docs.unity3d.com/Manual/UIBasicLayout.html

UI Multi Resolutions:
https://docs.unity3d.com/Manual/HOWTO-UIMultiResolution.html


问:
How can I check if this object into a JSON document is a simple object or an array using JavaScript?
I am not so into JavaScript and I have the following problem. To solve this problem I can use only pure old JavaScript (not library or framework).

I have a JSON document like this:

```<code>{
    "Commodity": {
        "CommodityInMarket": {
            "market_info": {
                "market_id": 5,
                "market_name": "Tambacounda Market N2",
                "available_market_count": 1
            },
            "commodity_info": {
                "commodity_details_id": 1,
                "commodity_name_en": "Rice-Asia",
                "commodity_name": "Rice-Asia",
                "image_link": "https://firebasestorage.googleapis.com/v0/b/fao-digital-services-portfolio.appspot.com/o/img%2Ficons%2Fagrimarket%2Fcommodity%2Friz.png?alt=media&token=c35e7648-1793-423b-acd2-52d8a1e58c53",
                "description": "Rice-Asia"
            },
            "price_info": {
                "price_serie_id": 29,
                "today_avg_price": 9.3000,
                "yesterday_avg_price": 9.6000,
                "currency": "XOF",
                "measure_unit": "kilogram"
            }
        }
    }
}
</code>```

As you can see this document contains a Commodity object.

In some case it is a simple object (as in the previous code snippet), in some other case it can be an array (this document is returned by a service in this way), so something like this:

```<code>{
    "Commodity": {
        "CommodityInMarket": [{
            .....................................
            .....................................
            .....................................
        },
        {
            .....................................
            .....................................
            .....................................
        }]
    }
}
</code>```

How can I check if this Commodity object into my JSON document is a simple object or an array? I need to do something like this:

If it is a simple object put true into a boolean variable. How can I implement this behavior?

答:
Taken from this answer:

The method given in the ECMAScript standard to find the class of Object is to use the toString method from Object.prototype.

```<code>if (Object.prototype.toString.call(obj.Commodity.CommodityInMarket) === '[object Array]') {
  //Loop through obj.Commodity.CommodityInMarket
} else {
  //It's an object, just access directly
}
</code>```

Another way could be to just automatically convert it to an array, and always loop through it:

```<code>if (!Object.prototype.toString.call(obj.Commodity.CommodityInMarket) === '[object Array]') {
  obj.Commodity.CommodityInMarket = [obj.Commodity.CommodityInMarket];
}
//obj.Commodity.CommodityInMarket should now always be an array
</code>```

Body:
I am not so into JavaScript and I have the following problem. To solve this problem I can use only pure old JavaScript (not library or framework).

I have a JSON document like this:

{
    "Commodity": {
        "CommodityInMarket": {
            "market_info": {
                "market_id": 5,
                "market_name": "Tambacounda Market N2",
                "available_market_count": 1
            },
            "commodity_info": {
                "commodity_details_id": 1,
                "commodity_name_en": "Rice-Asia",
                "commodity_name": "Rice-Asia",
                "image_link": "https://firebasestorage.googleapis.com/v0/b/fao-digital-services-portfolio.appspot.com/o/img%2Ficons%2Fagrimarket%2Fcommodity%2Friz.png?alt=media&token=c35e7648-1793-423b-acd2-52d8a1e58c53",
                "description": "Rice-Asia"
            },
            "price_info": {
                "price_serie_id": 29,
                "today_avg_price": 9.3000,
                "yesterday_avg_price": 9.6000,
                "currency": "XOF",
                "measure_unit": "kilogram"
            }
        }
    }
}

As you can see this document contains a Commodity object.

In some case it is a simple object (as in the previous code snippet), in some other case it can be an array (this document is returned by a service in this way), so something like this:

{
    "Commodity": {
        "CommodityInMarket": [{
            .....................................
            .....................................
            .....................................
        },
        {
            .....................................
            .....................................
            .....................................
        }]
    }
}

How can I check if this Commodity object into my JSON document is a simple object or an array? I need to do something like this:

If it is a simple object put true into a boolean variable. How can I implement this behavior?

Body:
Taken from this answer:

The method given in the ECMAScript standard to find the class of Object is to use the toString method from Object.prototype.

if (Object.prototype.toString.call(obj.Commodity.CommodityInMarket) === '[object Array]') {
  //Loop through obj.Commodity.CommodityInMarket
} else {
  //It's an object, just access directly
}

Another way could be to just automatically convert it to an array, and always loop through it:

if (!Object.prototype.toString.call(obj.Commodity.CommodityInMarket) === '[object Array]') {
  obj.Commodity.CommodityInMarket = [obj.Commodity.CommodityInMarket];
}
//obj.Commodity.CommodityInMarket should now always be an array


问:
HTML Different styles

Can anyone tell me what is the difference between the two styles of html code written below.

```<code>return '<div id='suggestionId' class="autocomplete-suggestion">No Message Found</div>';
</code>```

Vs

```<code>var autoCompleteSuggestion;
 autoCompleteSuggestion = $('<div/>').attr({id: 'suggestionId'}).addClass('suggestion').html('No Message Found');
return autoCompleteSuggestion;
</code>```

Results are same, the below mentioned script what kind of scripting is it called. Would like to know more

答:
The first one is hard-coded vanilla javascript. The second one uses the jQuery api to build the string.

Also, your first one uses quotes incorrectly. But it looks like that's not intentional.

Title: HTML Different styles

Body:
Can anyone tell me what is the difference between the two styles of html code written below.

return '
No Message Found
';

Vs

var autoCompleteSuggestion;
 autoCompleteSuggestion = $('
').attr({id: 'suggestionId'}).addClass('suggestion').html('No Message Found');
return autoCompleteSuggestion;

Results are same, the below mentioned script what kind of scripting is it called. Would like to know more


问:
Postgres select by array element range
In my table I've got column facebook where I store  facebook data ( comment count, share count etc.) and It's an array. For example:

```<code>{{total_count,14},{comment_count,0},{comment_plugin_count,0},{share_count,12},{reaction_count,2}}
</code>```

Now I'm trying to SELECT rows that facebook total_count is between 5 and 10. I've tried this:

```<code>SELECT * FROM pl where regexp_matches(array_to_string(facebook, ' '), '(\d+).*')::numeric[] BETWEEN 5 and 10;
</code>```

But I'm getting an error:

ERROR:  operator does not exist: numeric[] >= integer

Any ideas?

答:
There is no need to convert the array to text and use regexp. You can access a particular element of the array, e.g.:

```<code>with pl(facebook) as (
values ('{{total_count,14},{comment_count,0},{comment_plugin_count,0},{share_count,12},{reaction_count,2}}'::text[])
)

select facebook[1][2] as total_count
from pl;

 total_count
-------------
 14
(1 row)
</code>```

Your query may look like this:

```<code>select *
from pl
where facebook[1][2]::numeric between 5 and 10
</code>```

Update. You could avoid the troubles described in the comments if you would use the word null instead of empty strings ''''.

```<code>with pl(id, facebook) as (
values
    (1, '{{total_count,14},{comment_count,0}}'::text[]),
    (2, '{{total_count,null},{comment_count,null}}'::text[]),
    (3, '{{total_count,7},{comment_count,10}}'::text[])
)

select *
from pl
where facebook[1][2]::numeric between 5 and 10

 id |               facebook
----+--------------------------------------
  3 | {{total_count,7},{comment_count,10}}
(1 row)
</code>```

However, it would be unfair to leave your problems without an additional comment. The case is suitable as an example for the lecture How not to use arrays in Postgres. You have at least a few better options. The most performant and natural is to simply use regular integer columns:

```<code>create table pl (
    ...
    facebook_total_count integer,
    facebook_comment_count integer,
    ...
    );
</code>```

If for some reason you need to separate this data from others in the table, create a new secondary table with a foreign key to the main table.

If for some mysterious reason you have to store the data in a single column, use the jsonb type, example:

```<code>with pl(id, facebook) as (
values
    (1, '{"total_count": 14, "comment_count": 0}'::jsonb),
    (2, '{"total_count": null, "comment_count": null}'::jsonb),
    (3, '{"total_count": 7, "comment_count": 10}'::jsonb)
)

select *
from pl
where (facebook->>'total_count')::integer between 5 and 10
</code>```

hstore can be an alternative to jsonb.

All these ways are much easier to maintain and much more efficient than your current model. Time to move to the bright side of power.

Title: Postgres select by array element range

Body:
In my table I've got column facebook where I store  facebook data ( comment count, share count etc.) and It's an array. For example:

{{total_count,14},{comment_count,0},{comment_plugin_count,0},{share_count,12},{reaction_count,2}}

Now I'm trying to SELECT rows that facebook total_count is between 5 and 10. I've tried this:

SELECT * FROM pl where regexp_matches(array_to_string(facebook, ' '), '(\d+).*')::numeric[] BETWEEN 5 and 10;

But I'm getting an error:

ERROR:  operator does not exist: numeric[] >= integer

Any ideas?

Body:
There is no need to convert the array to text and use regexp. You can access a particular element of the array, e.g.:

with pl(facebook) as (
values ('{{total_count,14},{comment_count,0},{comment_plugin_count,0},{share_count,12},{reaction_count,2}}'::text[])
)

select facebook[1][2] as total_count
from pl;

 total_count
-------------
 14
(1 row)

Your query may look like this:

select *
from pl
where facebook[1][2]::numeric between 5 and 10

Update. You could avoid the troubles described in the comments if you would use the word null instead of empty strings ''''.

with pl(id, facebook) as (
values
    (1, '{{total_count,14},{comment_count,0}}'::text[]),
    (2, '{{total_count,null},{comment_count,null}}'::text[]),
    (3, '{{total_count,7},{comment_count,10}}'::text[])
)

select *
from pl
where facebook[1][2]::numeric between 5 and 10

 id |               facebook
----+--------------------------------------
  3 | {{total_count,7},{comment_count,10}}
(1 row)

However, it would be unfair to leave your problems without an additional comment. The case is suitable as an example for the lecture How not to use arrays in Postgres. You have at least a few better options. The most performant and natural is to simply use regular integer columns:

create table pl (
    ...
    facebook_total_count integer,
    facebook_comment_count integer,
    ...
    );

If for some reason you need to separate this data from others in the table, create a new secondary table with a foreign key to the main table.

If for some mysterious reason you have to store the data in a single column, use the jsonb type, example:

with pl(id, facebook) as (
values
    (1, '{"total_count": 14, "comment_count": 0}'::jsonb),
    (2, '{"total_count": null, "comment_count": null}'::jsonb),
    (3, '{"total_count": 7, "comment_count": 10}'::jsonb)
)

select *
from pl
where (facebook->>'total_count')::integer between 5 and 10

hstore can be an alternative to jsonb.

All these ways are much easier to maintain and much more efficient than your current model. Time to move to the bright side of power.


问:
How to add "node_modules" to a downloaded Git repository
I have several questions.

The most important one is what's in the title: How do I add node_modules to a downloaded Git repository? I know that "node_modules" has a lot of files and therefore cannot be held in a Git repository. Please list out step by step what I need to do on my Mac laptop.

Also, it seems like I was able to get node_modules when I create a new project like this

```<code>sudo ng new geckos.
</code>```

However, it comes with its own problems. I cannot create a new project in a directory I like. For example, I wanted to create a project in Documents/GitHub/geckos, but it didn't work. Also I got this warning:

Project name "Documents/GitHub/geckos" is not valid. New project names must start with a letter, and must contain only alphanumeric characters or dashes. When adding a dash the segment after the dash must also start with a letter.

I concluded that it's due to the / slash that I wasn't able to create a new folder. So what should I do to create a new project in the right folder I wanted it to be in?

Lastly, when I do create a new project with all the "node_modules" installed, how do I blend or add the repository that I downloaded to this new project? Is it even possible? I heard something about Git pull. How do I do that?

答:
Install what is in the package.json file using: npm install

We leave vendor files out of the repository because the packages, and their intended versions, are described in that manifest.  If you're using a newer package manager, sometimes there is a lockfile that also stores the specific versions installed.  In that case you would want to commit the lockfile as well, after testing updates, and in accordance with your team's workflow.

Body:
I have several questions.

The most important one is what's in the title: How do I add node_modules to a downloaded Git repository? I know that "node_modules" has a lot of files and therefore cannot be held in a Git repository. Please list out step by step what I need to do on my Mac laptop.

Also, it seems like I was able to get node_modules when I create a new project like this

sudo ng new geckos.

However, it comes with its own problems. I cannot create a new project in a directory I like. For example, I wanted to create a project in Documents/GitHub/geckos, but it didn't work. Also I got this warning:

Project name "Documents/GitHub/geckos" is not valid. New project names must start with a letter, and must contain only alphanumeric characters or dashes. When adding a dash the segment after the dash must also start with a letter.

I concluded that it's due to the / slash that I wasn't able to create a new folder. So what should I do to create a new project in the right folder I wanted it to be in?

Lastly, when I do create a new project with all the "node_modules" installed, how do I blend or add the repository that I downloaded to this new project? Is it even possible? I heard something about Git pull. How do I do that?


问:
NuGet is returning 503 Server Unavailable
Is there a way to load a package from an alternative server when Visual Studio Package Manager (NuGet) is responding with a "The remote server returned an error: (503) Server Unavailable" message?</p>

答:
i had also this problem, it was becouse of my network.
if you have any blocking on your Internet, (like in companies internet or etc..)
you may not allowed to download the nuget package.

try to download the package in another network, maybe it can help you!


问:
CanvasJS and multiple piecharts.
I have to create pie charts for a website. It seems to me that I can't dynamically render pie charts depending on how many I need. At max I have to render 28. So, I'm thinking that I would have to type out

```<code><script type="text/javascript">
window.onload = function () {
    var chart = new CanvasJS.Chart("chartContainer",
    {
        title:{
            text: "Gaming Consoles Sold in 2012"
        },
        legend: {
            maxWidth: 350,
            itemWidth: 120
        },
        data: [
        {
            type: "pie",
            showInLegend: true,
            legendText: "{indexLabel}",
            dataPoints: [
                { y: 4181563, indexLabel: "PlayStation 3" },
                { y: 2175498, indexLabel: "Wii" },
                { y: 3125844, indexLabel: "Xbox 360" },
                { y: 1176121, indexLabel: "Nintendo DS"},
                { y: 1727161, indexLabel: "PSP" },
                { y: 4303364, indexLabel: "Nintendo 3DS"},
                { y: 1717786, indexLabel: "PS Vita"}
            ]
        }
        ]
    });
    chart.render();
}
</script>
<script type="text/javascript" src="https://canvasjs.com/assets/script/canvasjs.min.js"></script>
</head>
<body>
<div id="chartContainer" style="height: 300px; width: 100%;"></div>
</code>```

this code 28 times. But, sometimes I won't need all 28 pie charts. So I was thinking I could hide the pie charts if they aren't needed. But, the main question is, "can I dynamically allocate canvasJS pie charts"? So I only have one main block of code that can create X amount of pie charts.

答:
Got it. So following my original comment. I hard coded the 2 tuple variable in the data section just to get the basic idea running. So the variable data was not used. But, I followed through with just simply creating an array of charts. With a naming convention of pieContainer+i. Where in my html code. I have 29 div elements with the convention pieContainer+1. </p>

```<code>var charts = [];
var data = [];

function populatePieCharts(size)
{
    for (i = 0; i < size; i++)
    {
        console.log("FFFF" + i)
        charts[i] = new CanvasJS.Chart("pieContainer" + i,
            {
                title: {
                    text: i
                },
                legend: {
                    maxWidth: 350,
                    itemWidth: 120
                },
                data: [
                    {
                        type:"pie",
                        showInLegend: true,
                        legendText: "{indexLabel}",
                        dataPoints: [
                            { y: 4181563, indexLabel: "PlayStation 3" },
                            { y: 2175498, indexLabel: "Wii" },
                            { y: 3125844, indexLabel: "Xbox 360" },
                            { y: 1176121, indexLabel: "Nintendo DS" }
                        ]
                    }]
            });
    }
    renderCharts(size)
}
function renderCharts(chartAmount)
{
    console.log(charts.length);
    for (i2 = 0; i2 < chartAmount; i2++)
    {
        charts[i2].render();
        console.log(i2);
    }
}
</code>```

<p>Which leads me to another step. Instead of hard coding the 29 div elements. I could probably just dynamically create the div elements based on the pie charts needed. </p>

Title: CanvasJS and multiple piecharts.

Body:
I have to create pie charts for a website. It seems to me that I can't dynamically render pie charts depending on how many I need. At max I have to render 28. So, I'm thinking that I would have to type out

this code 28 times. But, sometimes I won't need all 28 pie charts. So I was thinking I could hide the pie charts if they aren't needed. But, the main question is, "can I dynamically allocate canvasJS pie charts"? So I only have one main block of code that can create X amount of pie charts.

Body:
Got it. So following my original comment. I hard coded the 2 tuple variable in the data section just to get the basic idea running. So the variable data was not used. But, I followed through with just simply creating an array of charts. With a naming convention of pieContainer+i. Where in my html code. I have 29 div elements with the convention pieContainer+1.

var charts = [];
var data = [];

function populatePieCharts(size)
{
    for (i = 0; i < size; i++)
    {
        console.log("FFFF" + i)
        charts[i] = new CanvasJS.Chart("pieContainer" + i,
            {
                title: {
                    text: i
                },
                legend: {
                    maxWidth: 350,
                    itemWidth: 120
                },
                data: [
                    {
                        type:"pie",
                        showInLegend: true,
                        legendText: "{indexLabel}",
                        dataPoints: [
                            { y: 4181563, indexLabel: "PlayStation 3" },
                            { y: 2175498, indexLabel: "Wii" },
                            { y: 3125844, indexLabel: "Xbox 360" },
                            { y: 1176121, indexLabel: "Nintendo DS" }
                        ]
                    }]
            });
    }
    renderCharts(size)
}
function renderCharts(chartAmount)
{
    console.log(charts.length);
    for (i2 = 0; i2 < chartAmount; i2++)
    {
        charts[i2].render();
        console.log(i2);
    }
}

Which leads me to another step. Instead of hard coding the 29 div elements. I could probably just dynamically create the div elements based on the pie charts needed.


问:
Automatically run a command or program when I'm away from keyboard?
Is there any way to run a program when I am away from keyboard after given timeout? For example, I want my torrent application to run automatically when I am away after 30 minutes. Was trying to find everywhere, but couldn't find any tool to do that.</p>

答: What OS do you use? In Windows 7 or Vista you can create a scheduled task that will run a batch file or exe when the PC becomes idle. You can also define how long the PC has no input before it becomes idle.</p>


问:
Return key for JS Map constructor with value
I'm running into difficulty retrieving keys from a JS Map constructor.

Say you have the code below:

```<code>var myMap = new Map();

myMap.set('AK', 'Alaska');
myMap.set('CO', 'Colorado');

console.log(myMap.get('CO'))
</code>```

This console.logs 'Colorado'. I'm trying to figure out how I can do the opposite and return the key ('CO') using the value ('Colorado').

In a perfect world I could just do myMap.get('Colorado') to return 'CO' but this does not work.

答:
Do you need the map to be indexed with the abbreviations? If not, you can just set data inside of it the other way:

```<code>myMap.set('Alaska', 'AK');
</code>```

Otherwise, you're gonna need to loop through the entries of your map:

```<code>let entry;
for (entry of myMap.entries()) {
    if (entry === 'CO') {
        break;
    }
}
</code>```

Body:
I'm running into difficulty retrieving keys from a JS Map constructor.

Say you have the code below:

var myMap = new Map();

myMap.set('AK', 'Alaska');
myMap.set('CO', 'Colorado');

console.log(myMap.get('CO'))

This console.logs 'Colorado'. I'm trying to figure out how I can do the opposite and return the key ('CO') using the value ('Colorado').

In a perfect world I could just do myMap.get('Colorado') to return 'CO' but this does not work.

Body:
Do you need the map to be indexed with the abbreviations? If not, you can just set data inside of it the other way:

myMap.set('Alaska', 'AK');

Otherwise, you're gonna need to loop through the entries of your map:

let entry;
for (entry of myMap.entries()) {
    if (entry === 'CO') {
        break;
    }
}


问:
NSLocale returning wrong value in iOS 11
Starting from iOS 11.0, the following code returns "de_US" instead of "en_US":

```<code>// => Returns "de_US"
NSString *regionCode = [[NSLocale currentLocale] objectForKey:NSLocaleIdentifier];
NSLog(@"Region code: %@", regionCode);
</code>```

Below iOS 11, it returns "en_US".

My device has for language and region English / United States.
Preferred languages (despite I do not use them in my code) are in order:

English

Deutsch

French

Is it a known issue of iOS 11? Has the API changed?

答:
Found it!

It's a change behaviour starting from iOS 11.

Under iOS 11,
  [NSLocale currentLocale] only returns languages supported by your app’s localizations. If your app only supports English (as the base localization), then no matter what language the user selects on the device, currentLocale will always return English.

Under iOS 10 and earlier,  currentLocale would directly represent the
  user’s chosen language and region, regardless of what localizations
  your app supports.

More information here:

https://jaanus.com/ios-11-changes-localized-date-handling/

Maddy's stack overflow answer: https://stackoverflow.com/a/46206511/1226963

Body:
Starting from iOS 11.0, the following code returns "de_US" instead of "en_US":

// => Returns "de_US"
NSString *regionCode = [[NSLocale currentLocale] objectForKey:NSLocaleIdentifier];
NSLog(@"Region code: %@", regionCode);

Below iOS 11, it returns "en_US".

My device has for language and region English / United States.
Preferred languages (despite I do not use them in my code) are in order:

English

Deutsch

French

Is it a known issue of iOS 11? Has the API changed?