问:
Click on points in a leaflet map as input for a plot in shiny
Using the example below, I am trying to figure out a way to add functionality to my shiny app such that the following works:

Click on a point on the map

This changes the plot according to station AND

Inputs the corresponding station into the "Click on Station" sidebar

Basically I'd like to be able either click on the map for a station OR input the station manually with a keyboard.

Is this possible with leaflet? I've seen references to using plotly which may be ultimate solution but I'd love to leaflet if possible in no small part because I have already done a lot of work with leaflet. This is similar to thisquestion though there is working example here:

```<code>library(shiny)
library(leaflet)
library(shinydashboard)
library(ggplot2)
library(dplyr)

data("quakes")
shinyApp(
  ui = dashboardPage(title = "Station Lookup",
                     dashboardHeader(title = "Test"),
                     dashboardSidebar(
                       sidebarMenu(
                         menuItem("Data Dashboard", tabName = "datavis", icon = icon("dashboard")),
                         menuItem("Select by station number", icon = icon("bar-chart-o"),
                                  selectizeInput("stations", "Click on Station", choices = levels(factor(quakes$stations)), selected = 10, multiple = TRUE)
                         )
                       )
                     ),
                     dashboardBody(
                       tabItems(
                         tabItem(tabName = "datavis",
                                 h4("Map and Plot"),
                                 fluidRow(box(width= 4,  leafletOutput("map")),
                                          box(width = 8, plotOutput("plot")))
                         )
                       )
                     )
  ),

  server = function(input, output) {

    ## Sub data
    quakes_sub <- reactive({

      quakes[quakes$stations %in% input$stations,]

    })

    output$plot <- renderPlot({

      ggplot(quakes_sub(), aes(x = depth, y = mag))+
        geom_point()

    })

    output$map <- renderLeaflet({
      leaflet(quakes) %>%
        addTiles() %>%
        addCircleMarkers(lng = ~long, lat = ~lat, layerId = ~stations, color = "blue", radius = 3) %>%
        addCircles(lng = ~long, lat = ~lat, weight = 1,
                   radius = 1, label = ~stations,
                   popup = ~paste(stations, "<br>",
                                  depth, "<br>",
                                  mag)
        )

    })

  }
)
</code>```

答:
You can use input$map_marker_click and updateSelectInput():

Edit: Added functionality that stations can be deleted from selectInput() as suggested by OP in the comments.

(Dont forget to add session to your sever function).

```<code>observeEvent(input$stations,{
  updateSelectInput(session, "stations", "Click on Station",
                    choices = levels(factor(quakes$stations)),
                    selected = c(input$stations))
})

observeEvent(input$map_marker_click, {
  click <- input$map_marker_click
  station <- quakes[which(quakes$lat == click$lat & quakes$long == click$lng), ]$stations
  updateSelectInput(session, "stations", "Click on Station",
                    choices = levels(factor(quakes$stations)),
                    selected = c(input$stations, station))
})
</code>```

However, this functionality is partly overwritten by the popup event(?). As i see it there is an inner blue circle (darker blue) that if clicked produces the popup. However, the input$map_marker_click only works if you click the outer (light blue) circle. I would report it as a bug,...

Body:
Using the example below, I am trying to figure out a way to add functionality to my shiny app such that the following works:

Click on a point on the map

This changes the plot according to station AND

Inputs the corresponding station into the "Click on Station" sidebar

Basically I'd like to be able either click on the map for a station OR input the station manually with a keyboard.

Is this possible with leaflet? I've seen references to using plotly which may be ultimate solution but I'd love to leaflet if possible in no small part because I have already done a lot of work with leaflet. This is similar to thisquestion though there is working example here:

library(shiny)
library(leaflet)
library(shinydashboard)
library(ggplot2)
library(dplyr)

data("quakes")
shinyApp(
  ui = dashboardPage(title = "Station Lookup",
                     dashboardHeader(title = "Test"),
                     dashboardSidebar(
                       sidebarMenu(
                         menuItem("Data Dashboard", tabName = "datavis", icon = icon("dashboard")),
                         menuItem("Select by station number", icon = icon("bar-chart-o"),
                                  selectizeInput("stations", "Click on Station", choices = levels(factor(quakes$stations)), selected = 10, multiple = TRUE)
                         )
                       )
                     ),
                     dashboardBody(
                       tabItems(
                         tabItem(tabName = "datavis",
                                 h4("Map and Plot"),
                                 fluidRow(box(width= 4,  leafletOutput("map")),
                                          box(width = 8, plotOutput("plot")))
                         )
                       )
                     )
  ),

  server = function(input, output) {

    ## Sub data
    quakes_sub <- reactive({

      quakes[quakes$stations %in% input$stations,]

    })

    output$plot <- renderPlot({

      ggplot(quakes_sub(), aes(x = depth, y = mag))+
        geom_point()

    })

    output$map <- renderLeaflet({
      leaflet(quakes) %>%
        addTiles() %>%
        addCircleMarkers(lng = ~long, lat = ~lat, layerId = ~stations, color = "blue", radius = 3) %>%
        addCircles(lng = ~long, lat = ~lat, weight = 1,
                   radius = 1, label = ~stations,
                   popup = ~paste(stations, "
",
                                  depth, "
",
                                  mag)
        )

    })

  }
)

Body:
You can use input$map_marker_click and updateSelectInput():

Edit: Added functionality that stations can be deleted from selectInput() as suggested by OP in the comments.

(Dont forget to add session to your sever function).

observeEvent(input$stations,{
  updateSelectInput(session, "stations", "Click on Station",
                    choices = levels(factor(quakes$stations)),
                    selected = c(input$stations))
})

observeEvent(input$map_marker_click, {
  click <- input$map_marker_click
  station <- quakes[which(quakes$lat == click$lat & quakes$long == click$lng), ]$stations
  updateSelectInput(session, "stations", "Click on Station",
                    choices = levels(factor(quakes$stations)),
                    selected = c(input$stations, station))
})

However, this functionality is partly overwritten by the popup event(?). As i see it there is an inner blue circle (darker blue) that if clicked produces the popup. However, the input$map_marker_click only works if you click the outer (light blue) circle. I would report it as a bug,...


来源: stackexchange

问:
PHP ISSUE: Dynamic Load HTML - setting the value of input in PHP - storing in PHP variable
[ ISSUE ]:
I have created a function in php that dynamically loads html blocks of code depending on the parameters I pass, the function will be utilized to load text-boxes in one page and in another page to display the answers retrieved from the text-boxes. Example:

```<code>function chapterOne($param1, $param2) {
    echo 'Welcome';
    echo 'My name is '. $param1;
    echo 'I am from ' . $param2;
}

# The form is going to return $name or $loc values if
# any text-box is forgotten empty when form is submitted
# ---------------------------------------------------------
$p1 = '<input type="text" placeholder="name" value="<?php echo $name; ?>" >';
$p2 = '<input type="text" placeholder="loc"  value="<?php echo $loc;  ?>" >';
echo chapterOne($p1,$p2);
</code>```

The issue is that the value shows the php code instead of the placeholder, but only happens dynamically, when I test regular it works. Any thoughts or feedback how to overcome this issue?

Textbox example:

答:
Use Concatenation .

```<code>$p1 = '<input type="text" placeholder="name" value="' . $name . '" >';
$p2 = '<input type="text" placeholder="loc"  value="' . $loc . '" >';
echo chapterOne($p1,$p2);
</code>```

ContentLicense: CC BY-SA 3.0

Body:
[ ISSUE ]:
I have created a function in php that dynamically loads html blocks of code depending on the parameters I pass, the function will be utilized to load text-boxes in one page and in another page to display the answers retrieved from the text-boxes. Example:

function chapterOne($param1, $param2) {
    echo 'Welcome';
    echo 'My name is '. $param1;
    echo 'I am from ' . $param2;
}

# The form is going to return $name or $loc values if
# any text-box is forgotten empty when form is submitted
# ---------------------------------------------------------
$p1 = '<input type="text" placeholder="name" value="<?php echo $name; ?>" >';
$p2 = '<input type="text" placeholder="loc"  value="<?php echo $loc;  ?>" >';
echo chapterOne($p1,$p2);

The issue is that the value shows the php code instead of the placeholder, but only happens dynamically, when I test regular it works. Any thoughts or feedback how to overcome this issue?

Textbox example:

Body:
Use Concatenation .

$p1 = '<input type="text" placeholder="name" value="' . $name . '" >';
$p2 = '<input type="text" placeholder="loc"  value="' . $loc . '" >';
echo chapterOne($p1,$p2);


问:
openpyxl KeyError Worksheet {0} does not exist
I know you probably have seen this title, but please dont mark as duplicate as my error is different. I am making an excel comparing program with openpyxl and using tkinter to make the UI more friendly. Here is my code:

```<code>import openpyxl
from tkinter import *
from tkinter.filedialog import askopenfilename
from openpyxl.utils import get_column_letter, column_index_from_string

f1 = ''
f2 = ''
sheet1 = ''
sheet2 = ''

root = Tk()
root.configure(background='light green')
root.geometry("500x500")
root.wm_title("BananaCell")

e1 = Text(root, width=15, height=1)
e1.pack()
e1.place(x=70, y=150)

e2 = Text(root, width=15, height=1)
e2.pack()
e2.place(x=300, y=150)

def destroy():
    root.destroy()

def get_1():
    inputValue = e1.get("1.0", "end-1c")
    print(inputValue)

def get_2():
    inputValue2 = e2.get("1.0", "end-1c")
    print(inputValue2)

bf = Button(root, text="Enter", width=6, height=0, command=get_1)
bf.pack()
bf.place(x=15, y=147)

bf = Button(root, text="Enter", width=6, height=0, command=get_2)
bf.pack()
bf.place(x=430, y=147)

def askForFileName1():
    global f1
    f1 = askopenfilename(title="Select Workbook 1")
    print(str(f1))

def askForFileName2():
    global f2
    f2 = askopenfilename(title="Select Workbook 2")
    print(str(f2))

sheet1 = e1.get("1.0", "end-1c")
sheet2 = e2.get("1.0", "end-1c")

b = Button(root, text="Workbook 1", width=12, height=2, command=askForFileName1)
b.pack()
b.place(x=100, y=100)

b2 = Button(root, text="Workbook 2", width=12, height=2, command=askForFileName2)
b2.pack()
b2.place(x=300, y=100)

mainloop()

wb = openpyxl.load_workbook(str(f1))
wb1 = openpyxl.load_workbook(str(f2))

ws = wb.get_sheet_by_name(str(sheet1))
ws1 = wb1.get_sheet_by_name(str(sheet2))

col1 = input('Column letter from Sheet 1 to compare from: ')
col2 = input('Column letter  from Sheet 2 to compare from: ')

for (col, col_1) in zip(ws.iter_cols(min_col = column_index_from_string(col1), max_col=column_index_from_string(col1)), ws1.iter_cols(min_col = column_index_from_string(col2), max_col=column_index_from_string(col2))):
    for (cell, cell_1) in zip(col, col_1):
       if cell.value != cell_1.value and cell.row == cell_1.row:
           print('Row ' + str(cell.row) + ' ' + str(cell.value) + ' is not
equal to ' + str(cell_1.value) + ' ' + 'Row ' + str(cell_1.row))

exit_if = input('Press x to exit when you\'re ready: ')
</code>```

Everything runs fine until I get to the line with: ws = wb.get_sheet_by_name(str(sheet1)). After that line it gives me the error:

```<code>raise KeyError("Worksheet {0} does not exist.".format(key))
KeyError: 'Worksheet  does not exist.'
</code>```

Can anyone fix this? any help would be much appreciated.

答:
```<code>def get_1():
    global sheet1
    sheet1 = e1.get("1.0", "end-1c")
    print(sheet1)

def get_2():
    global sheet2
    sheet2 = e2.get("1.0", "end-1c")
    print(sheet2)
</code>```

When you call the following lines

```<code>sheet1 = e1.get("1.0", "end-1c")
sheet2 = e2.get("1.0", "end-1c")
</code>```

at that time, there is nothing in e1 and e2.
So u have to call it in a function like for the filenames.

Moreover, you should use Entry widget for getting inputs

Body:
I know you probably have seen this title, but please dont mark as duplicate as my error is different. I am making an excel comparing program with openpyxl and using tkinter to make the UI more friendly. Here is my code:

import openpyxl
from tkinter import *
from tkinter.filedialog import askopenfilename
from openpyxl.utils import get_column_letter, column_index_from_string

f1 = ''
f2 = ''
sheet1 = ''
sheet2 = ''

root = Tk()
root.configure(background='light green')
root.geometry("500x500")
root.wm_title("BananaCell")

e1 = Text(root, width=15, height=1)
e1.pack()
e1.place(x=70, y=150)

e2 = Text(root, width=15, height=1)
e2.pack()
e2.place(x=300, y=150)

def destroy():
    root.destroy()

def get_1():
    inputValue = e1.get("1.0", "end-1c")
    print(inputValue)

def get_2():
    inputValue2 = e2.get("1.0", "end-1c")
    print(inputValue2)

bf = Button(root, text="Enter", width=6, height=0, command=get_1)
bf.pack()
bf.place(x=15, y=147)

bf = Button(root, text="Enter", width=6, height=0, command=get_2)
bf.pack()
bf.place(x=430, y=147)

def askForFileName1():
    global f1
    f1 = askopenfilename(title="Select Workbook 1")
    print(str(f1))

def askForFileName2():
    global f2
    f2 = askopenfilename(title="Select Workbook 2")
    print(str(f2))

sheet1 = e1.get("1.0", "end-1c")
sheet2 = e2.get("1.0", "end-1c")

b = Button(root, text="Workbook 1", width=12, height=2, command=askForFileName1)
b.pack()
b.place(x=100, y=100)

b2 = Button(root, text="Workbook 2", width=12, height=2, command=askForFileName2)
b2.pack()
b2.place(x=300, y=100)

mainloop()

wb = openpyxl.load_workbook(str(f1))
wb1 = openpyxl.load_workbook(str(f2))

ws = wb.get_sheet_by_name(str(sheet1))
ws1 = wb1.get_sheet_by_name(str(sheet2))

col1 = input('Column letter from Sheet 1 to compare from: ')
col2 = input('Column letter  from Sheet 2 to compare from: ')

for (col, col_1) in zip(ws.iter_cols(min_col = column_index_from_string(col1), max_col=column_index_from_string(col1)), ws1.iter_cols(min_col = column_index_from_string(col2), max_col=column_index_from_string(col2))):
    for (cell, cell_1) in zip(col, col_1):
       if cell.value != cell_1.value and cell.row == cell_1.row:
           print('Row ' + str(cell.row) + ' ' + str(cell.value) + ' is not
equal to ' + str(cell_1.value) + ' ' + 'Row ' + str(cell_1.row))

exit_if = input('Press x to exit when you\'re ready: ')

Everything runs fine until I get to the line with: ws = wb.get_sheet_by_name(str(sheet1)). After that line it gives me the error:

raise KeyError("Worksheet {0} does not exist.".format(key))
KeyError: 'Worksheet  does not exist.'

Can anyone fix this? any help would be much appreciated.

Body:
def get_1():
    global sheet1
    sheet1 = e1.get("1.0", "end-1c")
    print(sheet1)

def get_2():
    global sheet2
    sheet2 = e2.get("1.0", "end-1c")
    print(sheet2)

When you call the following lines

sheet1 = e1.get("1.0", "end-1c")
sheet2 = e2.get("1.0", "end-1c")

at that time, there is nothing in e1 and e2.
So u have to call it in a function like for the filenames.

Moreover, you should use Entry widget for getting inputs


问:
How to secure .NET DLL's
What is best practice for securing DLL's for projects you are working on?  Certain DLL's I am interested in developing will have data access layer (DAL) and business logic layer (BLL) functionality.  There may be several apps that can eventually hit these DLL's to perform business specific functions.

What is the best way to secure these DLL's so they can only be used by only creator's applications?

Security for both blocking unauthorized use of the DLL's and security against possible decompilation are both desirable.

答:
If someone has access to the machine with all those assemblies, you have more to be worried about than someone reusing them, they could just go directly to the database instead of using your assembly.

If this is a desktop application or something and you're accessing the database directly then you need to re-think your application, access the data via web services or something rather than going directly to the database.

ContentLicense: CC BY-SA 2.5

Title: How to secure .NET DLL's


问:
How to get multiple inputs of String when the number of input string is n
I am working with a question for that we need to get n string inputs how to store then in n string variables.

I tried with array storing the string in each elements

Is there any other way in java ?

答: If you don't know in advance how many strings to save in memory, then you can use dynamic constructs like implementers of List (e.g.: ArrayList) if you want to store all the lists preserving the order, or Sets (e.g.: HashSet) if you don't want store duplicates and you don't care the order in which they were inserted. </p>


答:
You cannot start a php code block inside a php code block especially, inside quotes! If you want to use the variables for it, try this.</p>

```<code>$p1 = <input type="text" placeholder="name" value="'.$name.'" >
</code>```

Title: PHP ISSUE: Dynamic Load HTML - setting the value of input in PHP - storing in PHP variable

Body:
You cannot start a php code block inside a php code block especially, inside quotes! If you want to use the variables for it, try this.

$p1 = <input type="text" placeholder="name" value="'.$name.'" >


问:
JavaScript - Search object property by key and add its value to array
Let's say I have an object like this:

```<code>var object =  {
  "Defender": {
    "player-1868": {
      "birthdate": "1 July 1996",
      "club_country": "IQ",
      "club_id": 171,
      "club_name": "Erbil",
      "forename": "Burhan Jumaah",
      "id": 1868,
      "league_id": 12,
      "league_name": "Iraqi Premier League",
      "name": "Burhan Jumaah",
      "nationality": "iq",
      "nationality_full": "Iraq",
      "position": "Defender",
      "surname": "Razzaq",
      "votes": [
        "y884F42mLCVdld5V5cMeRpl11gJ2"
      ]
    }
  },
  "Goalkeeper": {
    "player-3076": {
      "birthdate": "15 December 1985",
      "club_country": "QA",
      "club_id": 1,
      "club_name": "Lekhwiya",
      "comments": [
        {
          "comment": "xxx",
          "name": "guy tester",
          "photoURL": "http://pbs.twimg.com/profile_images/855450315704979460/RGiq07D7_normal.jpg",
          "time": 1496529030321,
          "user": "y884F42mLCVdld5V5cMeRpl11gJ2"
        }
      ],
      "forename": "Qasem Abdulhamed",
      "id": 3076,
      "league_id": 1,
      "league_name": "Qatar Stars League",
      "name": "Qasem Burhan",
      "nationality": "qa",
      "nationality_full": "Qatar",
      "position": "Goalkeeper",
      "surname": "Burhan",
      "votes": [
        "y884F42mLCVdld5V5cMeRpl11gJ2"
      ]
    },
    "player-3532": {
      "birthdate": "2 April 1992",
      "club_country": "SA",
      "club_id": 18,
      "club_name": "Al Ittihad",
      "forename": "Fawaz",
      "id": 3532,
      "league_id": 2,
      "league_name": "Saudi Professional League",
      "name": "Fawaz Al Qarni",
      "nationality": "sa",
      "nationality_full": "Saudi Arabia",
      "position": "Goalkeeper",
      "surname": "Al Qarni",
      "votes": [
        "y884F42mLCVdld5V5cMeRpl11gJ2"
      ]
    }
  }
};
</code>```

How would I, using lodash, traverse through this object and add every time the property id appears inside an object key of player-xxxxxx, add that value to an array. Essentially, getting all of the player IDs in a single array?

答:
You can Array#reduce recursively on the object's keys to find the search string (player-), and create and extract the values:

var object = {"Defender":{"player-1868":{"birthdate":"1 July 1996","club_country":"IQ","club_id":171,"club_name":"Erbil","forename":"Burhan Jumaah","id":1868,"league_id":12,"league_name":"Iraqi Premier League","name":"Burhan Jumaah","nationality":"iq","nationality_full":"Iraq","position":"Defender","surname":"Razzaq","votes":["y884F42mLCVdld5V5cMeRpl11gJ2"]}},"Goalkeeper":{"player-3076":{"birthdate":"15 December 1985","club_country":"QA","club_id":1,"club_name":"Lekhwiya","comments":[{"comment":"xxx","name":"guy tester","photoURL":"http://pbs.twimg.com/profile_images/855450315704979460/RGiq07D7_normal.jpg","time":1496529030321,"user":"y884F42mLCVdld5V5cMeRpl11gJ2"}],"forename":"Qasem Abdulhamed","id":3076,"league_id":1,"league_name":"Qatar Stars League","name":"Qasem Burhan","nationality":"qa","nationality_full":"Qatar","position":"Goalkeeper","surname":"Burhan","votes":["y884F42mLCVdld5V5cMeRpl11gJ2"]},"player-3532":{"birthdate":"2 April 1992","club_country":"SA","club_id":18,"club_name":"Al Ittihad","forename":"Fawaz","id":3532,"league_id":2,"league_name":"Saudi Professional League","name":"Fawaz Al Qarni","nationality":"sa","nationality_full":"Saudi Arabia","position":"Goalkeeper","surname":"Al Qarni","votes":["y884F42mLCVdld5V5cMeRpl11gJ2"]}}};

function searchProps(searchStr, object) {
  return Object.keys(object).reduce(function(arr, key) { // reduce the objects keys to an array
    key.indexOf(searchStr) === -1 || arr.push(key.slice(searchStr.length)); // if a key contains the search string, take whatever after it

    var propValue = object[key];

    if(typeof propValue === 'object' && propValue !== null) { // if the value of the property is an array, run it through search props
      return arr.concat(searchProps(searchStr, propValue));
    }

    return arr;
  }, []);
}

var result = searchProps('player-', object);

console.log(result);```

Body:
Let's say I have an object like this:

var object =  {
  "Defender": {
    "player-1868": {
      "birthdate": "1 July 1996",
      "club_country": "IQ",
      "club_id": 171,
      "club_name": "Erbil",
      "forename": "Burhan Jumaah",
      "id": 1868,
      "league_id": 12,
      "league_name": "Iraqi Premier League",
      "name": "Burhan Jumaah",
      "nationality": "iq",
      "nationality_full": "Iraq",
      "position": "Defender",
      "surname": "Razzaq",
      "votes": [
        "y884F42mLCVdld5V5cMeRpl11gJ2"
      ]
    }
  },
  "Goalkeeper": {
    "player-3076": {
      "birthdate": "15 December 1985",
      "club_country": "QA",
      "club_id": 1,
      "club_name": "Lekhwiya",
      "comments": [
        {
          "comment": "xxx",
          "name": "guy tester",
          "photoURL": "http://pbs.twimg.com/profile_images/855450315704979460/RGiq07D7_normal.jpg",
          "time": 1496529030321,
          "user": "y884F42mLCVdld5V5cMeRpl11gJ2"
        }
      ],
      "forename": "Qasem Abdulhamed",
      "id": 3076,
      "league_id": 1,
      "league_name": "Qatar Stars League",
      "name": "Qasem Burhan",
      "nationality": "qa",
      "nationality_full": "Qatar",
      "position": "Goalkeeper",
      "surname": "Burhan",
      "votes": [
        "y884F42mLCVdld5V5cMeRpl11gJ2"
      ]
    },
    "player-3532": {
      "birthdate": "2 April 1992",
      "club_country": "SA",
      "club_id": 18,
      "club_name": "Al Ittihad",
      "forename": "Fawaz",
      "id": 3532,
      "league_id": 2,
      "league_name": "Saudi Professional League",
      "name": "Fawaz Al Qarni",
      "nationality": "sa",
      "nationality_full": "Saudi Arabia",
      "position": "Goalkeeper",
      "surname": "Al Qarni",
      "votes": [
        "y884F42mLCVdld5V5cMeRpl11gJ2"
      ]
    }
  }
};

How would I, using lodash, traverse through this object and add every time the property id appears inside an object key of player-xxxxxx, add that value to an array. Essentially, getting all of the player IDs in a single array?


问:
How do you publish/embed a swf with flexible size?
How to make the swf scale as necessary?

So far all swf embedded into a web page are fixed in size, how to make it flexible?

答: The size of a swf in a HTML page is defined by the <embed> tag and the swf application's attributes like width and height. Let's say you did not define the maxwidth and maxheight of your swf app (they default to zero which means that there is no maximum) and you set the width and height to 100%. Now, to be able to resize you swf, you only have to resize its container which can be a DIV for example. DIV can be resized easily using javascript, here is a jQuery plugin - http://jqueryui.com/demos/resizable/


问:
Java get request error using google distance matrix api
for some reason when we send a get request to the google distance matrix api we get an error saying we have exceeded our daily quota, nonetheless we haven't done even 100 request as can be seen here:

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

the code to send the get request is as follows:

```<code>public class JsonRead {

    // Coverteix tot el contingut del BufferedReader en una String per per el seu posterior tractament
    private String readAll(Reader rd) throws IOException {

        StringBuilder sb = new StringBuilder();
        int cp;

        while ((cp = rd.read()) != -1) {

            sb.append((char) cp);

        }
        return sb.toString();
    }

    //Per alguna rao, depen de quines adreçes disparen OVER_QUERY_LIMIT
    // Agafa una String que conte la direcció, fa una GET Request i retorna el contingut en format JsonObject
    public JsonObject readJsonFromUrl(String url) throws IOException {

        System.out.println(url);
        InputStream is = new URL(url).openStream();

        try {

            JsonParser par = new JsonParser();
            BufferedReader rd = new BufferedReader(new InputStreamReader(is, Charset.forName("UTF-8")));

            String jsonText = readAll(rd);

            JsonObject json = (JsonObject) par.parse(jsonText);
            return json;

        } finally {
            is.close();
        }
    }

    public JsonObject getDistancies (int inici, int fi, String adress, JsonArray bicing) throws  IOException{

        String array_adreces = "";
        JsonRead jr = new JsonRead();

        for (int i = inici; i <= fi ; i++){

            JsonObject aux = bicing.get(i).getAsJsonObject();

            if (aux.get("streetName").getAsString().contains("/")){

                array_adreces += aux.get("streetName").getAsString() + ",Barcelona" + "|";
            }
            else {

                array_adreces += aux.get("streetName").getAsString() + " " + aux.get("streetNumber").getAsString() + ",Barcelona" + "|";

            }

            array_adreces = array_adreces.replaceAll(" ", "+");

        }

        // Fem una web call que ens retorna les distancies de totes les estacions a l'adreça que l'usuari dona
        JsonObject distancies = jr.readJsonFromUrl("https://maps.googleapis.com/maps/api/distancematrix/json?origins=" + array_adreces +"&destinations=" + adress + "&mode=bicycling&language=es-ES&region=es&key=AIzaSyBc2N_mjY8w3cDiqQcra4KjF_Gm4-0ZLUI");
        return distancies;

    }
}
</code>```

As can be seen, we send a get request using a number of adresses stored in a Json file.

The Json file can be seen here: http://wservice.viabicing.cat/v2/stations

However, we think the issue might be related to the request's lenght, because when we reduce it's lenght i gives us no trouble.

Here is a resquest (I can't post two links at the moment, sorry):

```<code>https://maps.googleapis.com/maps/api/distancematrix/json?origins=Gran+Via+Corts+Catalanes+760,Barcelona|Roger+de+Flor/+Gran+Vía,Barcelona|Ali+Bei+44,Barcelona|Ribes+13,Barcelona|Pg+Lluís+Companys+11,Barcelona|Pg+Lluís+Companys+18,Barcelona|Pg+Lluís+Companys+1,Barcelona|Pg+Lluís+Companys+2,Barcelona|Marquès+de+l'Argentera+17,Barcelona|Carrer+Comerç+27,Barcelona|Trelawny+2,Barcelona|Pg+Marítim+Barceloneta+23,Barcelona|Avinguda+Litoral+16,Barcelona|Avinguda+del+Marques+Argentera+19,Barcelona|Girona+74,Barcelona|Av.+Meridiana+47,Barcelona|Av.+Meridiana+47,Barcelona|Rosselló+412,Barcelona|Rosselló+354,Barcelona|Indústria+157,Barcelona|Sant+Antoni+Maria+Claret+214,Barcelona|Sardenya+296,Barcelona|Bruc+45,Barcelona|Marina+185,Barcelona|Bruc+102,Barcelona|Dos+Maig+230,Barcelona|Provença+322,Barcelona|Marina+311,Barcelona|Provença+388,Barcelona|Diagonal+231,Barcelona|Plaça+del+Mar+72,Barcelona|Plaça+del+Mar+1,Barcelona|Baluart+58,Barcelona|Sant+Pere+Més+Alt+4,Barcelona|Sant+Ramon+de+Penyafort+1,Barcelona|Catedral+6,Barcelona|Pl.+Antonio+López+,Barcelona|Pl.+Pau+Vila+,Barcelona|Pl.+Pau+Vila+,Barcelona|Doctor+Aiguader+2,Barcelona|Pl.+Poeta+Boscà/Atlàntida,Barcelona|Ciutat+de+Granada+168,Barcelona|Av+Meridiana+80,Barcelona|Av+Meridiana+66,Barcelona|Marina++65,Barcelona|Ramon+trias+Fargas+19,Barcelona|Ramon+Trias+Fargas+,Barcelona|Meridiana+40,Barcelona|Rosa+Sensat+en+front+20,Barcelona|Av.+Paral.lel+54,Barcelona|Pl.+Vicenç+Martorell+,Barcelona|Pl.+Carles+Pi+i+Sunyer+,Barcelona|Sant+Oleguer+2,Barcelona|La+Rambla+80,Barcelona|Portal+de+Santa+Madrona+2,Barcelona|La+Rambla+2,Barcelona|Plaça+dels+Àngels+1,Barcelona|Plaça+dels+Àngels+2,Barcelona|Rambla+Catalunya++47,Barcelona|Rambla+Catalunya+42,Barcelona|Pl.+Catalunya++5,Barcelona|Pl.+Catalunya+7,Barcelona|Pl.+Catalunya+,Barcelona|Pl.+Catalunya+,Barcelona|Gran+Via+609,Barcelona|Rocafort+214,Barcelona|Rambla+Catalunya+133,Barcelona|Avda.+Litoral+,Barcelona|Villarroel+2,Barcelona|Floridablanca++145,Barcelona|Provença+215,Barcelona|Enric+Granados+99,Barcelona|Josep+Tarradellas+129,Barcelona|Josep+Tarradellas+58,Barcelona|Còrsega+216,Barcelona|Pl.+Universitat+,Barcelona|Pl.+Universitat+,Barcelona|Enric+Granados+35,Barcelona|Vilamarí+davant+61,Barcelona|Rocafort+72,Barcelona|Comte+Borrell+177,Barcelona|Diputació+152,Barcelona|Paral·lel+146,Barcelona|Viladomat+2,Barcelona|Mallorca+41,Barcelona|Londres+101,Barcelona|Rosselló+101,Barcelona|Rosselló+108,Barcelona|Comte+Borrell+119,Barcelona|Provença+241,Barcelona|Gran+Via+375,Barcelona|Gran+Via+375,Barcelona|Tarragona+103,Barcelona|Gran+Via+361,Barcelona|Tarragona+141,Barcelona|Viriat+45,Barcelona|Viriat+53,Barcelona|Tarragona+159,Barcelona|Av.+Diagonal+602,Barcelona|Av.+Diagonal+612,Barcelona|&destinations=Via+Augusta,+209,+08021+Barcelona,+Spain&mode=bicycling&language=es-ES&region=es&key=AIzaSyBc2N_mjY8w3cDiqQcra4KjF_Gm4-0ZLUI
</code>```

As you can see, using a get request for each adress isn't feasible as there ara approximately 100 adresses, is there any way to increase the accepted lenght of a get request?

If not, what's the maximum allowed lenght?

答: I think that is because we put special character in spain like ´ or ñ.

Body:
for some reason when we send a get request to the google distance matrix api we get an error saying we have exceeded our daily quota, nonetheless we haven't done even 100 request as can be seen here:

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

the code to send the get request is as follows:

public class JsonRead {

    // Coverteix tot el contingut del BufferedReader en una String per per el seu posterior tractament
    private String readAll(Reader rd) throws IOException {

        StringBuilder sb = new StringBuilder();
        int cp;

        while ((cp = rd.read()) != -1) {

            sb.append((char) cp);

        }
        return sb.toString();
    }

    //Per alguna rao, depen de quines adreçes disparen OVER_QUERY_LIMIT
    // Agafa una String que conte la direcció, fa una GET Request i retorna el contingut en format JsonObject
    public JsonObject readJsonFromUrl(String url) throws IOException {

        System.out.println(url);
        InputStream is = new URL(url).openStream();

        try {

            JsonParser par = new JsonParser();
            BufferedReader rd = new BufferedReader(new InputStreamReader(is, Charset.forName("UTF-8")));

            String jsonText = readAll(rd);

            JsonObject json = (JsonObject) par.parse(jsonText);
            return json;

        } finally {
            is.close();
        }
    }

    public JsonObject getDistancies (int inici, int fi, String adress, JsonArray bicing) throws  IOException{

        String array_adreces = "";
        JsonRead jr = new JsonRead();

        for (int i = inici; i <= fi ; i++){

            JsonObject aux = bicing.get(i).getAsJsonObject();

            if (aux.get("streetName").getAsString().contains("/")){

                array_adreces += aux.get("streetName").getAsString() + ",Barcelona" + "|";
            }
            else {

                array_adreces += aux.get("streetName").getAsString() + " " + aux.get("streetNumber").getAsString() + ",Barcelona" + "|";

            }

            array_adreces = array_adreces.replaceAll(" ", "+");

        }

        // Fem una web call que ens retorna les distancies de totes les estacions a l'adreça que l'usuari dona
        JsonObject distancies = jr.readJsonFromUrl("https://maps.googleapis.com/maps/api/distancematrix/json?origins=" + array_adreces +"&destinations=" + adress + "&mode=bicycling&language=es-ES&region=es&key=AIzaSyBc2N_mjY8w3cDiqQcra4KjF_Gm4-0ZLUI");
        return distancies;

    }
}

As can be seen, we send a get request using a number of adresses stored in a Json file.

The Json file can be seen here: http://wservice.viabicing.cat/v2/stations

However, we think the issue might be related to the request's lenght, because when we reduce it's lenght i gives us no trouble.

Here is a resquest (I can't post two links at the moment, sorry):

https://maps.googleapis.com/maps/api/distancematrix/json?origins=Gran+Via+Corts+Catalanes+760,Barcelona|Roger+de+Flor/+Gran+Vía,Barcelona|Ali+Bei+44,Barcelona|Ribes+13,Barcelona|Pg+Lluís+Companys+11,Barcelona|Pg+Lluís+Companys+18,Barcelona|Pg+Lluís+Companys+1,Barcelona|Pg+Lluís+Companys+2,Barcelona|Marquès+de+l'Argentera+17,Barcelona|Carrer+Comerç+27,Barcelona|Trelawny+2,Barcelona|Pg+Marítim+Barceloneta+23,Barcelona|Avinguda+Litoral+16,Barcelona|Avinguda+del+Marques+Argentera+19,Barcelona|Girona+74,Barcelona|Av.+Meridiana+47,Barcelona|Av.+Meridiana+47,Barcelona|Rosselló+412,Barcelona|Rosselló+354,Barcelona|Indústria+157,Barcelona|Sant+Antoni+Maria+Claret+214,Barcelona|Sardenya+296,Barcelona|Bruc+45,Barcelona|Marina+185,Barcelona|Bruc+102,Barcelona|Dos+Maig+230,Barcelona|Provença+322,Barcelona|Marina+311,Barcelona|Provença+388,Barcelona|Diagonal+231,Barcelona|Plaça+del+Mar+72,Barcelona|Plaça+del+Mar+1,Barcelona|Baluart+58,Barcelona|Sant+Pere+Més+Alt+4,Barcelona|Sant+Ramon+de+Penyafort+1,Barcelona|Catedral+6,Barcelona|Pl.+Antonio+López+,Barcelona|Pl.+Pau+Vila+,Barcelona|Pl.+Pau+Vila+,Barcelona|Doctor+Aiguader+2,Barcelona|Pl.+Poeta+Boscà/Atlàntida,Barcelona|Ciutat+de+Granada+168,Barcelona|Av+Meridiana+80,Barcelona|Av+Meridiana+66,Barcelona|Marina++65,Barcelona|Ramon+trias+Fargas+19,Barcelona|Ramon+Trias+Fargas+,Barcelona|Meridiana+40,Barcelona|Rosa+Sensat+en+front+20,Barcelona|Av.+Paral.lel+54,Barcelona|Pl.+Vicenç+Martorell+,Barcelona|Pl.+Carles+Pi+i+Sunyer+,Barcelona|Sant+Oleguer+2,Barcelona|La+Rambla+80,Barcelona|Portal+de+Santa+Madrona+2,Barcelona|La+Rambla+2,Barcelona|Plaça+dels+Àngels+1,Barcelona|Plaça+dels+Àngels+2,Barcelona|Rambla+Catalunya++47,Barcelona|Rambla+Catalunya+42,Barcelona|Pl.+Catalunya++5,Barcelona|Pl.+Catalunya+7,Barcelona|Pl.+Catalunya+,Barcelona|Pl.+Catalunya+,Barcelona|Gran+Via+609,Barcelona|Rocafort+214,Barcelona|Rambla+Catalunya+133,Barcelona|Avda.+Litoral+,Barcelona|Villarroel+2,Barcelona|Floridablanca++145,Barcelona|Provença+215,Barcelona|Enric+Granados+99,Barcelona|Josep+Tarradellas+129,Barcelona|Josep+Tarradellas+58,Barcelona|Còrsega+216,Barcelona|Pl.+Universitat+,Barcelona|Pl.+Universitat+,Barcelona|Enric+Granados+35,Barcelona|Vilamarí+davant+61,Barcelona|Rocafort+72,Barcelona|Comte+Borrell+177,Barcelona|Diputació+152,Barcelona|Paral·lel+146,Barcelona|Viladomat+2,Barcelona|Mallorca+41,Barcelona|Londres+101,Barcelona|Rosselló+101,Barcelona|Rosselló+108,Barcelona|Comte+Borrell+119,Barcelona|Provença+241,Barcelona|Gran+Via+375,Barcelona|Gran+Via+375,Barcelona|Tarragona+103,Barcelona|Gran+Via+361,Barcelona|Tarragona+141,Barcelona|Viriat+45,Barcelona|Viriat+53,Barcelona|Tarragona+159,Barcelona|Av.+Diagonal+602,Barcelona|Av.+Diagonal+612,Barcelona|&destinations=Via+Augusta,+209,+08021+Barcelona,+Spain&mode=bicycling&language=es-ES&region=es&key=AIzaSyBc2N_mjY8w3cDiqQcra4KjF_Gm4-0ZLUI

As you can see, using a get request for each adress isn't feasible as there ara approximately 100 adresses, is there any way to increase the accepted lenght of a get request?

If not, what's the maximum allowed lenght?


问:
changing scroll speed of divs?
I am trying to adjust scroll speeds of some divs depending on if an other div (image-ul) is fully above the bottom of the webpage or not.

When the div "image-ul" moves above or below the bottom edge of the browser window it does change CSS, but the scroll speeds do not change upon scrolling or scaling of the window. I also want the scroll speeds to then change.

Only when (re)loading the page do the scroll speeds change according to where "image-ul" is in relation to the bottom egde of the browser window.

What am I doing wrong? Please see example here.

So, the goal is to have different scroll speeds for divs when div "image-ul" is fully above the bowser window's bottom edge, and different scroll speeds for those divs when div "image-ul" is NOT fully above the bowser window's bottom edge.

I am already achieving moving elements at different speeds, but, as my question states, I need the speeds to change depending on if div "image-ul" is fully above the browser window's bottom egde or not.

```<code>    // Assign attribute specific "data-scroll-speed" to elements upon loading, resizing and scrolling of the webpage page. "if/else" is depending on if #image-ul is fully above the bottom edge of the browser window.
 $(document).ready(function() {
     $(window).on('load resize scroll', function() {
         var WindowScrollTop = $(this).scrollTop(),
             Div_one_top = $('#image-ul').offset().top,
             Div_one_height = $('#image-ul').outerHeight(true),
             Window_height = $(this).outerHeight(true);
         if (WindowScrollTop + Window_height >= (Div_one_top + Div_one_height)) {
             $('#sloganenglish').attr('data-scroll-speed', '4');
             $('.slogan-a-line').attr('data-scroll-speed', '5');
             $('.slogan-a-line').css('color', 'yellow');
         } else {
             $('#sloganenglish').attr('data-scroll-speed', '1');
             $('.slogan-a-line').attr('data-scroll-speed', '1');
             $('.slogan-a-line').css('color', 'red');
         }
     }).scroll();
 });
</code>```

答:
Do you mean implementing something similar to a vertical parallax scenario, where elements move at difference speeds?

Maybe so some searches for "Vertical Parallax" and have a look at some examples.

e.g.: http://ianlunn.co.uk/demos/jquery-vertical-parallax-background/

Title: changing scroll speed of divs?

Body:
I am trying to adjust scroll speeds of some divs depending on if an other div (image-ul) is fully above the bottom of the webpage or not.

When the div "image-ul" moves above or below the bottom edge of the browser window it does change CSS, but the scroll speeds do not change upon scrolling or scaling of the window. I also want the scroll speeds to then change.

Only when (re)loading the page do the scroll speeds change according to where "image-ul" is in relation to the bottom egde of the browser window.

What am I doing wrong? Please see example here.

So, the goal is to have different scroll speeds for divs when div "image-ul" is fully above the bowser window's bottom edge, and different scroll speeds for those divs when div "image-ul" is NOT fully above the bowser window's bottom edge.

I am already achieving moving elements at different speeds, but, as my question states, I need the speeds to change depending on if div "image-ul" is fully above the browser window's bottom egde or not.

    // Assign attribute specific "data-scroll-speed" to elements upon loading, resizing and scrolling of the webpage page. "if/else" is depending on if #image-ul is fully above the bottom edge of the browser window.
 $(document).ready(function() {
     $(window).on('load resize scroll', function() {
         var WindowScrollTop = $(this).scrollTop(),
             Div_one_top = $('#image-ul').offset().top,
             Div_one_height = $('#image-ul').outerHeight(true),
             Window_height = $(this).outerHeight(true);
         if (WindowScrollTop + Window_height >= (Div_one_top + Div_one_height)) {
             $('#sloganenglish').attr('data-scroll-speed', '4');
             $('.slogan-a-line').attr('data-scroll-speed', '5');
             $('.slogan-a-line').css('color', 'yellow');
         } else {
             $('#sloganenglish').attr('data-scroll-speed', '1');
             $('.slogan-a-line').attr('data-scroll-speed', '1');
             $('.slogan-a-line').css('color', 'red');
         }
     }).scroll();
 });


问:
How to combine two Highcharts chart types?
Right now I have a simple column chart with following code using Highcharts:

```<code>$(document).ready(function() {
            var options = {
                chart: {
                    renderTo: 'container',
                    type: 'column'
                },
                title: {
                    //some code
                },
                xAxis: {
                    categories: []
                },
                yAxis: {
                   //some code
                },

                plotOptions: {
                    series: {
                        borderWidth: 0,
                        dataLabels: {
                            enabled: true,
                            format: '{point.y}'
                        }
                    }
                },
                legend: {
                    //some code
                },
                series: []
            };

            $.getJSON("data/column.php", function(json) {
                options.xAxis.categories = json[0]['data'];
                options.series[0] = json[1];
                chart = new Highcharts.Chart(options);
            });
        });
</code>```

I now want to add a line chart to the same container, using exactly the same options (despite of the chart type). The date is also served via JSON.

How can I achieve this?

What I did so far:
I created a second variable "options2" with values chart and series.
Then I called

```<code>$.getJSON("data/line.php", function(json) {
                options.xAxis.categories = json[0]['data'];
                options2.series[1] = json[1];
                chart = new Highcharts.Chart(options2);
            });
</code>```

But that only shows the first column chart.

答:
Solved it by passing the series option (chart type) directly via JSON.
I added the "type:line" to the data array, which then overrides previously set options within the script tag. </p>

Body:
Right now I have a simple column chart with following code using Highcharts:

$(document).ready(function() {
            var options = {
                chart: {
                    renderTo: 'container',
                    type: 'column'
                },
                title: {
                    //some code
                },
                xAxis: {
                    categories: []
                },
                yAxis: {
                   //some code
                },

                plotOptions: {
                    series: {
                        borderWidth: 0,
                        dataLabels: {
                            enabled: true,
                            format: '{point.y}'
                        }
                    }
                },
                legend: {
                    //some code
                },
                series: []
            };

            $.getJSON("data/column.php", function(json) {
                options.xAxis.categories = json[0]['data'];
                options.series[0] = json[1];
                chart = new Highcharts.Chart(options);
            });
        });

I now want to add a line chart to the same container, using exactly the same options (despite of the chart type). The date is also served via JSON.

How can I achieve this?

What I did so far:
I created a second variable "options2" with values chart and series.
Then I called

$.getJSON("data/line.php", function(json) {
                options.xAxis.categories = json[0]['data'];
                options2.series[1] = json[1];
                chart = new Highcharts.Chart(options2);
            });

But that only shows the first column chart.


问:
Is there a Four-Per-Em Space character - but as NO-BREAK Space?
I had a look around the web but did not find something suitable, so here is my question:

Is there a Four-Per-Em Space character - but as NO-BREAK Space?

答:
The closest thing I can find in the Unicode character database is

U+202F NARROW NO-BREAK SPACE


问:
Reusing DTO for various request/response types vs explicitness of what is required / what should be returned
I started wondering on whether I am not falling into an antipattern here, so please advise on the best practices.

I am designing a REST API with a set of various endpoints and I wanted to wrap the request & response parameters into nice DTO.

For example, a few endpoints:

```<code>public async Task<JobStateResponse> GetJobState(JobStateRequest request);
public async Task<JobDownloadRespose> DownloadJob(JobDownloadRequest request);
public async Task<CreateJobResponse> CreateJob(CreateJobRequest request);
</code>```

The problem is that these requests and responses are relatively similar DTO, for example:

```<code>public class JobStateResponse{
    public int TaskId {get;set;}
    public string ExternalId {get;set;}
    public State State {get;set;}
}
public class JobDownloadResponse {
    public int TaskId {get;set;}
    public string ExternalId {get;set;}
    public string JobContent {get;set;}
}
</code>```

I thought about creating a base class for these and inheriting, but in some cases some of the properties can be redundant...
Which means that the methods don't clearly indicate what parameters are needed for them to work OK.

I mean, exposing an API endpoint with a DTO parameter that has 7 properties but only really needs 2 sounds pretty bad...

On the other hand, maintaining separate DTOs for most of the endpoints seems like an overkill as well, and also a maintenance hell.

And also the last thing I want is a complex relationship of several base-base classes for the requests as this may be an even worse maintentance problem.

So, what is the proper approach for request<>response handling?

EDIT:
Regarding the 'opinion based' flags - I am looking for best practice for handling this. I know it can be done in multiple ways, but I want to avoid a landmine / antipattern. Also, I gotta say I am pretty happy with the answers so far.

答:
You definitely want to separate DTOs per endpoint into 2 gruops: request and response ones.

Now, speaking of inheritance, you could have base Request and base Response class which would include some general, non-specific things (for example, request&response wrapper message into which you plugin your data) but you don't want to mix inheritance between request and response side.

As others already pointed out, it is a bit more code at the begining but that way you'll never hit the wall. On a contrary, mixing them will pretty soon make you have huge refactorings where you'll lose more time&nerves than starting in a clear, separate way.

Body:
I started wondering on whether I am not falling into an antipattern here, so please advise on the best practices.

I am designing a REST API with a set of various endpoints and I wanted to wrap the request & response parameters into nice DTO.

For example, a few endpoints:

public async Task<JobStateResponse> GetJobState(JobStateRequest request);
public async Task<JobDownloadRespose> DownloadJob(JobDownloadRequest request);
public async Task<CreateJobResponse> CreateJob(CreateJobRequest request);

The problem is that these requests and responses are relatively similar DTO, for example:

public class JobStateResponse{
    public int TaskId {get;set;}
    public string ExternalId {get;set;}
    public State State {get;set;}
}
public class JobDownloadResponse {
    public int TaskId {get;set;}
    public string ExternalId {get;set;}
    public string JobContent {get;set;}
}

I thought about creating a base class for these and inheriting, but in some cases some of the properties can be redundant...
Which means that the methods don't clearly indicate what parameters are needed for them to work OK.

I mean, exposing an API endpoint with a DTO parameter that has 7 properties but only really needs 2 sounds pretty bad...

On the other hand, maintaining separate DTOs for most of the endpoints seems like an overkill as well, and also a maintenance hell.

And also the last thing I want is a complex relationship of several base-base classes for the requests as this may be an even worse maintentance problem.

So, what is the proper approach for request<>response handling?

EDIT:
Regarding the 'opinion based' flags - I am looking for best practice for handling this. I know it can be done in multiple ways, but I want to avoid a landmine / antipattern. Also, I gotta say I am pretty happy with the answers so far.


问:
What do I use for a max-heap implementation in Python?
Python includes the heapq module for min-heaps, but I need a max-heap. What should I use for a max-heap implementation in Python?</p>

答:
The easiest and ideal solution

Multiply the values by -1

There you go. All the highest numbers are now the lowest and vice versa.

Just remember that when you pop an element to multiply it with -1 in order to get the original value again.

ContentLicense: CC BY-SA 4.0


问:
Getting the latest ID of an auto increment when using unit of work
I have two tables. One is the product (the basic table) and the other table is a product class (which has specific properties for the product class). I am keeping the ID of the product (from the product table) inside the specific table. The problem comes when I try to use unit of work. I have to get the ID of the added item in the product (basic) table but since I haven't commited the transaction, the ID doesn't exist (since I am using auto increment in my database). When I wasn't using unit of work I had the advantage of objects in C#, that they are reference types and I could easy get out the ID from the newly added product item (product table) right after I had saved it to the table with (context.SaveChanges() method) but now.... Any ideas?
PS: MVC</p>

答:
Do something like bellow code:</p>

```<code>            db.MyJobContext.Add(job);
            db.SaveChanges();
            //get inserted Id
            int JobId = job.Id;

            var JobProvObj = new JobProvRel();
            JobProvObj.JobId = JobId;

            foreach (int P_id in Provinces)
            {
                JobProvObj.ProvinceId = P_id;
                db.MyJobProvRelContext.Add(JobProvObj);
                db.SaveChanges();
            }
</code>```

Body:
Do something like bellow code:

            db.MyJobContext.Add(job);
            db.SaveChanges();
            //get inserted Id
            int JobId = job.Id;

            var JobProvObj = new JobProvRel();
            JobProvObj.JobId = JobId;

            foreach (int P_id in Provinces)
            {
                JobProvObj.ProvinceId = P_id;
                db.MyJobProvRelContext.Add(JobProvObj);
                db.SaveChanges();
            }


问:
Importing Excel data into C# without first row becoming column names?
I am trying to import data from excel into a datatable using c#. Here is the code I use to do so...

```<code>string ConnString = "Provider=Microsoft.Jet.OLEDB.4.0;" +
                    "Data Source=" + fileName + "; Jet OLEDB:Engine Type=5;" +
                    "Extended Properties=\"Excel 8.0;HRD=No;IMEX=1;\"";
OleDbDataAdapter SheetAdapter = new OleDbDataAdapter("select * from ["Sheet1"]", conn);
System.Data.DataTable excelData = new System.Data.DataTable();
SheetAdapter.Fill(excelData);
excelData.TableName = "excelData";

foreach (DataRow row in excelData.Rows)
{
   ProcessDataRow(row);
}
</code>```

When I look at the datatable while debugging the first row of data has become the tables column names. I don't understand why this is happening when I put HDR=No into the connection string. Is there a way to force the DataTable to not take the first row as column names?

答: I used the NPOI library for just the task you inquired about and more.  The only limitation is that it cannot yet handle the Excel 2007 format, so you are limited to the 97-2003 format.</p>

Body:
I am trying to import data from excel into a datatable using c#. Here is the code I use to do so...

string ConnString = "Provider=Microsoft.Jet.OLEDB.4.0;" +
                    "Data Source=" + fileName + "; Jet OLEDB:Engine Type=5;" +
                    "Extended Properties=\"Excel 8.0;HRD=No;IMEX=1;\"";
OleDbDataAdapter SheetAdapter = new OleDbDataAdapter("select * from ["Sheet1"]", conn);
System.Data.DataTable excelData = new System.Data.DataTable();
SheetAdapter.Fill(excelData);
excelData.TableName = "excelData";

foreach (DataRow row in excelData.Rows)
{
   ProcessDataRow(row);
}

When I look at the datatable while debugging the first row of data has become the tables column names. I don't understand why this is happening when I put HDR=No into the connection string. Is there a way to force the DataTable to not take the first row as column names?


问:
spawn EACCESS Error while running / building Android Platform on Ionic 3
As many users, i had this error when doing

```<code>ionic cordova run android -android
</code>```

or

```<code>cordova build android --verbose
</code>```

the output :

```<code>No scripts found for hook "before_build".
No scripts found for hook "before_prepare".
Checking config.xml and package.json for saved platforms that haven't been added to the project
Config.xml and package.json platforms are the same. No pkg.json modification.
Package.json and config.xml platforms are different. Updating config.xml with most current list of platforms.
PlatformApi successfully found for platform android
Checking config.xml for saved plugins that haven't been added to the project
Checking for any plugins added to the project that have not been installed in android platform
No differences found between plugins added to project and installed in android platform. Continuing...
Generating platform-specific config.xml from defaults for android at /Users/davidanquetin/GIT/MEDIATOOLS/DOMME/domme-app/platforms/android/res/xml/config.xml
Merging project's config.xml into platform-specific android config.xml
Merging and updating files from [www, platforms/android/platform_www] to platforms/android/assets/www
Wrote out android application name "Domme" to /Users/davidanquetin/GIT/MEDIATOOLS/DOMME/domme-app/platforms/android/res/values/strings.xml
Wrote out Android package name "com.pasquet.domme.all" to /Users/davidanquetin/GIT/MEDIATOOLS/DOMME/domme-app/platforms/android/src/com/pasquet/domme/all/MainActivity.java
Updating icons at platforms/android/res
Updating splash screens at platforms/android/res
This app does not have additional resource files defined
Prepared android project successfully
No scripts found for hook "after_prepare".
No scripts found for hook "before_compile".
Running command: /usr/libexec/java_home
Command finished with error code 0: /usr/libexec/java_home
ANDROID_HOME=/Users/davidanquetin/Documents/_UTILITAIRES/TECHNIQUE/android-sdk-macosx/
JAVA_HOME=/Library/Java/JavaVirtualMachines/jdk1.8.0_112.jdk/Contents/Home
Running command: "/Applications/Android Studio 3.0 Preview.app/Contents/gradle/gradle-4.0-milestone-1/bin/gradle" -p /Users/davidanquetin/GIT/MEDIATOOLS/DOMME/domme-app/platforms/android wrapper -b /Users/davidanquetin/GIT/MEDIATOOLS/DOMME/domme-app/platforms/android/wrapper.gradle
Error: spawn EACCES
</code>```

i tried many manipulations founded on the web (chmod etc...) but nothing is working..

when i try

```<code>chmod +x /Applications/Android Studio 3.0 Preview.app/Contents/gradle/gradle-4.0-milestone-1/bin/gradle
</code>```

i have :

```<code>chmod + /Applications/Android\ Studio\ 3.0\ Preview.app/Contents/gradle/gradle-4.0-milestone-1/bin/gradle
</code>```

and always the same error after building...

thanks for ideas !

UPDATE / RESOLVED

The way i resolved the problem :

delete Android Studio app

redownload and reinstall it

update java

creating a new ionic project, then update it with my previous assets / code files.

reinstall platforms with a clean installation

and...it works !
I think it is manly Android Studio removing and reinstallation which resolves the problem.

If it could help !

Body:
As many users, i had this error when doing

ionic cordova run android -android

or

cordova build android --verbose

the output :

No scripts found for hook "before_build".
No scripts found for hook "before_prepare".
Checking config.xml and package.json for saved platforms that haven't been added to the project
Config.xml and package.json platforms are the same. No pkg.json modification.
Package.json and config.xml platforms are different. Updating config.xml with most current list of platforms.
PlatformApi successfully found for platform android
Checking config.xml for saved plugins that haven't been added to the project
Checking for any plugins added to the project that have not been installed in android platform
No differences found between plugins added to project and installed in android platform. Continuing...
Generating platform-specific config.xml from defaults for android at /Users/davidanquetin/GIT/MEDIATOOLS/DOMME/domme-app/platforms/android/res/xml/config.xml
Merging project's config.xml into platform-specific android config.xml
Merging and updating files from [www, platforms/android/platform_www] to platforms/android/assets/www
Wrote out android application name "Domme" to /Users/davidanquetin/GIT/MEDIATOOLS/DOMME/domme-app/platforms/android/res/values/strings.xml
Wrote out Android package name "com.pasquet.domme.all" to /Users/davidanquetin/GIT/MEDIATOOLS/DOMME/domme-app/platforms/android/src/com/pasquet/domme/all/MainActivity.java
Updating icons at platforms/android/res
Updating splash screens at platforms/android/res
This app does not have additional resource files defined
Prepared android project successfully
No scripts found for hook "after_prepare".
No scripts found for hook "before_compile".
Running command: /usr/libexec/java_home
Command finished with error code 0: /usr/libexec/java_home
ANDROID_HOME=/Users/davidanquetin/Documents/_UTILITAIRES/TECHNIQUE/android-sdk-macosx/
JAVA_HOME=/Library/Java/JavaVirtualMachines/jdk1.8.0_112.jdk/Contents/Home
Running command: "/Applications/Android Studio 3.0 Preview.app/Contents/gradle/gradle-4.0-milestone-1/bin/gradle" -p /Users/davidanquetin/GIT/MEDIATOOLS/DOMME/domme-app/platforms/android wrapper -b /Users/davidanquetin/GIT/MEDIATOOLS/DOMME/domme-app/platforms/android/wrapper.gradle
Error: spawn EACCES

i tried many manipulations founded on the web (chmod etc...) but nothing is working..

when i try

chmod +x /Applications/Android Studio 3.0 Preview.app/Contents/gradle/gradle-4.0-milestone-1/bin/gradle

i have :

chmod + /Applications/Android\ Studio\ 3.0\ Preview.app/Contents/gradle/gradle-4.0-milestone-1/bin/gradle

and always the same error after building...

thanks for ideas !

UPDATE / RESOLVED

The way i resolved the problem :

delete Android Studio app

redownload and reinstall it

update java

creating a new ionic project, then update it with my previous assets / code files.

reinstall platforms with a clean installation

and...it works !
I think it is manly Android Studio removing and reinstallation which resolves the problem.

If it could help !


问:
Realm in IntentService - thread created crash
I have a Realm thread that is causing a crash, and I'm not sure why this isn't allowed, or how to get around it.  Here's some sample code of what's going on:

```<code>public class UploadPostService extends IntentService {

public UploadPostService() {
    super("UploadPostService");
}

@Override
protected void onHandleIntent(Intent intent) {

    String uniqueCode = intent.getStringExtra("uniqueCode");

    OurApi api = OurApi.build(this, Application.apiRoot);

    final Realm r = Realm.getDefaultInstance();

    final RealmResults<Post> thePosts = r.where(Post.class)
            .equalTo("post.code", uniqueCode)
            .findAll();

    if (thePosts != null && thePosts.size() > 0) {
         for (final Post post : thePosts) {
            api.uploadMedia(paramsToUpload, new Callback<Post>() {
                @Override
                public void success(Post postResponse, Response response) {
                    if (post.isValid()) {
                        r.beginTransaction();
                        post.setAField(blah); // CRASHES HERE
                        r.commitTransaction();
                    }
                }
         }
  etc...
</code>```

After the API finishes with the Retrofit call, It crashes on the setting of any field on the "Post" object with the exception:

```<code>"java.lang.IllegalStateException: Realm access from incorrect thread. Realm objects can only be accessed on the thread they were created."
</code>```

I'm curious what the cleanest solution to this should be?  Assuming the callback is on a different thread than the IntentService one.. I need to update the actual Post, and it's not letting me;  I've tried creating separate Realm instances, but it doesn't let me update the Post, since it's not (apparently) queried from the same instance.

This is crucial to our code, so I'm a bit stumped.  Thanks in advance for any advice!

答:
That's because IntentService runs on background thread but your api callback tries to run on the UI thread, which means it's on a different thread than where the Realm instance to which your RealmResults belongs to was opened.

Also, you were going to write into the Realm on the UI thread anyways, which is discouraged.

Use synchronous API call in IntentService. In Retrofit, it is call.execute().

I also hope you are closing the Realm instance in a finally block!

Body:
I have a Realm thread that is causing a crash, and I'm not sure why this isn't allowed, or how to get around it.  Here's some sample code of what's going on:

public class UploadPostService extends IntentService {

public UploadPostService() {
    super("UploadPostService");
}

@Override
protected void onHandleIntent(Intent intent) {

    String uniqueCode = intent.getStringExtra("uniqueCode");

    OurApi api = OurApi.build(this, Application.apiRoot);

    final Realm r = Realm.getDefaultInstance();

    final RealmResults<Post> thePosts = r.where(Post.class)
            .equalTo("post.code", uniqueCode)
            .findAll();

    if (thePosts != null && thePosts.size() > 0) {
         for (final Post post : thePosts) {
            api.uploadMedia(paramsToUpload, new Callback<Post>() {
                @Override
                public void success(Post postResponse, Response response) {
                    if (post.isValid()) {
                        r.beginTransaction();
                        post.setAField(blah); // CRASHES HERE
                        r.commitTransaction();
                    }
                }
         }
  etc...

After the API finishes with the Retrofit call, It crashes on the setting of any field on the "Post" object with the exception:

"java.lang.IllegalStateException: Realm access from incorrect thread. Realm objects can only be accessed on the thread they were created."

I'm curious what the cleanest solution to this should be?  Assuming the callback is on a different thread than the IntentService one.. I need to update the actual Post, and it's not letting me;  I've tried creating separate Realm instances, but it doesn't let me update the Post, since it's not (apparently) queried from the same instance.

This is crucial to our code, so I'm a bit stumped.  Thanks in advance for any advice!


问:
Make a new column that contains the log of the NOx concentration
enter image description here

How do I:
Make a new column that contains the log of the NOx concentration
Summarise the log NOx concentrations by calculating their daily mean. Storing the results in a new dataframe

答:
We can use

```<code>df1$lNOx <- log(df1$Nox)
aggregate(lNOx ~ Date, df1, FUN = mean, na.rm = TRUE, na.action = NULL)
</code>```

Or this can be done with tidyverse

```<code>library(tidyverse)
df2 <- df1 %>%
          mutate(lNox = log(Nox)) %>%
          group_by(Date) %>%
          summarise(lNox = mean(lNox, na.rm = TRUE))
</code>```

Body:
We can use

df1$lNOx <- log(df1$Nox)
aggregate(lNOx ~ Date, df1, FUN = mean, na.rm = TRUE, na.action = NULL)

Or this can be done with tidyverse

library(tidyverse)
df2 <- df1 %>%
          mutate(lNox = log(Nox)) %>%
          group_by(Date) %>%
          summarise(lNox = mean(lNox, na.rm = TRUE))


问:
swiperjs - how to keep prev and next slider in sight but not centered current one

I'm using swiperjs, and what to stay part of the prev slider in the window, but not center the current one

I've triedspaceBetween, centeredSlides and slidesOffsetBefore, but none of these satisfied.

here is a  demo
, can anyone help ?

答:
Your swiping library adds a swiper-slide-prev to the previous slide.

Adding

```<code>.swiper-slide-prev {
  margin-left: 55px;
}
</code>```

looks similar to what you want.
Updated fiddle https://jsfiddle.net/z33jqt4s/2/

Body:
Your swiping library adds a swiper-slide-prev to the previous slide.

Adding

.swiper-slide-prev {
  margin-left: 55px;
}

looks similar to what you want.
Updated fiddle https://jsfiddle.net/z33jqt4s/2/


问:
Read Hibernate entity identity value
Does Hibernate have an API for reading the value of an entity's identity field? In my case, this would be the Serializable value returned by the field annotated with @Id. For example, suppose I had a Person entity:

```<code>class Person {
    @Id private long id;
    // ... other fields, getters/setters, etc ...
}

Person p = new Person();
p.setId(42L);

Hibernate.unknownFunction(p); // returns 42L
</code>```

Sure I could read the annotations to find the @Id field myself, but this seems like something that might be built in.

答:
Well, if you need a method that return id in arbitrary classes, design a interface to satisfy this. for example:

```<code>public interface IdHolder {
    Integer getId();
}
</code>```

With such interface, you could make some utility methods to retrive id from arbitrary classes.

The cglib is a robust but a bit of tricky way to do it.

Title: Read Hibernate entity identity value

Body:
Does Hibernate have an API for reading the value of an entity's identity field? In my case, this would be the Serializable value returned by the field annotated with @Id. For example, suppose I had a Person entity:

class Person {
    @Id private long id;
    // ... other fields, getters/setters, etc ...
}

Person p = new Person();
p.setId(42L);

Hibernate.unknownFunction(p); // returns 42L

Sure I could read the annotations to find the @Id field myself, but this seems like something that might be built in.

Body:
Well, if you need a method that return id in arbitrary classes, design a interface to satisfy this. for example:

public interface IdHolder {
    Integer getId();
}

With such interface, you could make some utility methods to retrive id from arbitrary classes.

The cglib is a robust but a bit of tricky way to do it.


问:
"Invalid object name 'dbo.UserRoles'.System.Exception System.Data.SqlClient.SqlException
I am developing an ASP.NET Web API with SQL Server using Entity Framework for the data layer. And while I tried to fetch data from database, my request stops at dataContext returning following exception. I have verified that the UserRoles table is created in database. Database setup is local.

System.Data.Entity.Core.EntityCommandExecutionException: 'An error occurred while executing the command definition. See the inner exception for details.'

Inner Exception SqlException: Invalid object name 'dbo.UserRoles'.

答:
Open your edmx file in a text editor. If you see the tables in the file but not in the designer, try clearing out all the EntitySet nodes and EntityType nodes, save the file, then go back to Visual Studio and try the Update Model from Database again. Or before you do anything go to your Model and try right click on it -> Update model from database. Because probably your table is created on SQL but she does not exist yet in your model.</p>

```<code><edmx:StorageModels>
    <Schema Namespace="myModel.Store">
        <EntityContainer Name="MyModelStoreContainer">
            delete-> <EntitySet Name="Table1" ... />
            delete-> <EntitySet Name="Table2" ... />
        </EntityContainer>
            delete-> <EntityType Name="Table1">...</EntityType>
            delete-> <EntityType Name="Table2">...</EntityType>
  </Schema></edmx:StorageModels>
</code>```

Body:
Open your edmx file in a text editor. If you see the tables in the file but not in the designer, try clearing out all the EntitySet nodes and EntityType nodes, save the file, then go back to Visual Studio and try the Update Model from Database again. Or before you do anything go to your Model and try right click on it -> Update model from database. Because probably your table is created on SQL but she does not exist yet in your model.

<edmx:StorageModels>
    <Schema Namespace="myModel.Store">
        <EntityContainer Name="MyModelStoreContainer">
            delete-> <EntitySet Name="Table1" ... />
            delete-> <EntitySet Name="Table2" ... />
        </EntityContainer>
            delete-> <EntityType Name="Table1">...</EntityType>
            delete-> <EntityType Name="Table2">...</EntityType>
  </Schema></edmx:StorageModels>


问:
mongoose $or with mixed string and _id (ObjectId) not working
I am trying to make a method to fetch a "page" from the document base where the query matches _id or permalink.

The below code example returns a mongoose error:

'Cast to ObjectId failed for value "hello-world" at path "_id" for model "pages"'

Now, obviously the query isn't an ObjectId if the case is 'hello-world' or any other string permalink. So how do I go about using $or in this case, or is there a smarter way to go about it?

```<code>/**
 * Describes methods to create, retrieve, update, and delete pages
 * @returns void
 */
function Pages() {
    this.pages = require('../models/pages')
    this.users = require('../models/users')
    require('mongoose').connect(require('../../config/database/mongodb').url)
}

/**
 * Retrieve a page by permalink or id
 * @param {string} pageQuery - id or permalink
 * @callback {function} cFunction
 */
Pages.prototype.getOne = function(pageQuery, cFunction) {
    this.pages.findOne({$or: [{ 'permalink': pageQuery }, { '_id': pageQuery }] })
    .populate('author', 'email')
    .select('title permalink body author')
    .exec(function(error, result) {
        if (error) {
            cFunction(error)
            return
        }
        cFunction(result)
    })
}
</code>```

Pages model

```<code>const mongoose = require('mongoose'),
    Schema = mongoose.Schema,
    ObjectId = Schema.ObjectId,
    pages = new Schema({
        title: { type: String },
        permalink: { type: String, unique: true },
        body: { type: String },
        author: { type: ObjectId, ref: 'users' },
        createdAt: { type: Date },
        revisedAt: { type: Date }
    })
    .index({
        title: 'text',
        permalink: 'text',
        body: 'text'
    })
    module.exports = mongoose.model('pages', pages)
</code>```

Users model

```<code>const mongoose = require('mongoose'),
    Schema = mongoose.Schema,
    ObjectId = Schema.ObjectId,
    users = new Schema({
        email: { type: String, unique: true },
        username: { type: String, unique: true },
        password: { type: String },
        createdAt: { type: Date }
    })
    .index({
        email: 'text',
        username: 'text'
    })
module.exports = mongoose.model('users', users)
</code>```

答:
It looks like if you run new ObjectId(pageQuery) and it's not a valid ObjectId, it will throw an error telling you that (i.e. Error: Argument passed in must be a single String of 12 bytes or a string of 24 hex characters.)

In saying that, I would just use a try/catch block at the beginning of Pages.prototype.getOne to try and cast a pageQueryOid variable, and if you get to the catch block you know it's because pageQuery is not a valid ObjectId.

Using this method you no longer need an $or filter, but can just build your exact filter based on if pageQuery is a valid ObjectId. The following is just an example of what this might look like, but you can update it to meet your needs:

```<code>Pages.prototype.getOne = function(pageQuery, cFunction) {
    var ObjectId = require('mongoose').Types.ObjectId
    var pageQueryOid
    try {
      pageQueryOid = new ObjectId(pageQuery)
    } catch(err) {
      console.log("pageQuery is not a valid ObjectId...")
    }

    var filter
    if (pageQueryOid) {
      filter = { '_id': pageQueryOid }
    } else {
      filter = { 'permalink': pageQuery }
    }

    this.pages.findOne(filter)
    .populate('author', 'email')
    .select('title permalink body author')
    .exec(function(error, result) {
        if (error) {
            cFunction(error)
            return
        }
        cFunction(result)
    })
}
</code>```

Body:
I am trying to make a method to fetch a "page" from the document base where the query matches _id or permalink.

The below code example returns a mongoose error:

'Cast to ObjectId failed for value "hello-world" at path "_id" for model "pages"'

Now, obviously the query isn't an ObjectId if the case is 'hello-world' or any other string permalink. So how do I go about using $or in this case, or is there a smarter way to go about it?

/**
 * Describes methods to create, retrieve, update, and delete pages
 * @returns void
 */
function Pages() {
    this.pages = require('../models/pages')
    this.users = require('../models/users')
    require('mongoose').connect(require('../../config/database/mongodb').url)
}

/**
 * Retrieve a page by permalink or id
 * @param {string} pageQuery - id or permalink
 * @callback {function} cFunction
 */
Pages.prototype.getOne = function(pageQuery, cFunction) {
    this.pages.findOne({$or: [{ 'permalink': pageQuery }, { '_id': pageQuery }] })
    .populate('author', 'email')
    .select('title permalink body author')
    .exec(function(error, result) {
        if (error) {
            cFunction(error)
            return
        }
        cFunction(result)
    })
}

Pages model

const mongoose = require('mongoose'),
    Schema = mongoose.Schema,
    ObjectId = Schema.ObjectId,
    pages = new Schema({
        title: { type: String },
        permalink: { type: String, unique: true },
        body: { type: String },
        author: { type: ObjectId, ref: 'users' },
        createdAt: { type: Date },
        revisedAt: { type: Date }
    })
    .index({
        title: 'text',
        permalink: 'text',
        body: 'text'
    })
    module.exports = mongoose.model('pages', pages)

Users model

const mongoose = require('mongoose'),
    Schema = mongoose.Schema,
    ObjectId = Schema.ObjectId,
    users = new Schema({
        email: { type: String, unique: true },
        username: { type: String, unique: true },
        password: { type: String },
        createdAt: { type: Date }
    })
    .index({
        email: 'text',
        username: 'text'
    })
module.exports = mongoose.model('users', users)

Body:
It looks like if you run new ObjectId(pageQuery) and it's not a valid ObjectId, it will throw an error telling you that (i.e. Error: Argument passed in must be a single String of 12 bytes or a string of 24 hex characters.)

In saying that, I would just use a try/catch block at the beginning of Pages.prototype.getOne to try and cast a pageQueryOid variable, and if you get to the catch block you know it's because pageQuery is not a valid ObjectId.

Using this method you no longer need an $or filter, but can just build your exact filter based on if pageQuery is a valid ObjectId. The following is just an example of what this might look like, but you can update it to meet your needs:

Pages.prototype.getOne = function(pageQuery, cFunction) {
    var ObjectId = require('mongoose').Types.ObjectId
    var pageQueryOid
    try {
      pageQueryOid = new ObjectId(pageQuery)
    } catch(err) {
      console.log("pageQuery is not a valid ObjectId...")
    }

    var filter
    if (pageQueryOid) {
      filter = { '_id': pageQueryOid }
    } else {
      filter = { 'permalink': pageQuery }
    }

    this.pages.findOne(filter)
    .populate('author', 'email')
    .select('title permalink body author')
    .exec(function(error, result) {
        if (error) {
            cFunction(error)
            return
        }
        cFunction(result)
    })
}


答: Using separate DTO enables you to optimise data transfer by the behaviour of the data access calls, it also allows you to restrict access to properties you may not want to expose. Although it is more code, you are defining exactly what is being exposed and are in full control of that.</p>

Title: Reusing DTO for various request/response types vs explicitness of what is required / what should be returned


问:
Java File Handling DisplayOnConsole
Question – File Handling [20 pts]

Given the following data about some account information of First National bank customers:

111111  john smith   500

222222  mark smith  1500

333333  steve jones  2000

444444  mary jones  1000

```<code>           Write a Java program that:
</code>```

a.    Writes the above data into file “payroll.txt”.

b.    Reads the above data from “payroll.txt”.

c.    Displays on java console the account information of each customer as follows:

Account 1  id: 111111  name: john smith  balance: 500 $

Account 2 id: 222222  name: mark smith  balance: 1500 $

```<code> Account 3 id: 333333  name: steve jones  balance: 2000 $
</code>```

Account 4 id:444444  name: mary jones  balance: 1000 $

d.    Calculate and display the total balance of all customers:
   Total balance of all accounts is 5000 $

i could only do part a & b i need help in part c & d please

```<code>import java.io.*;
import java.util.Scanner;
public class FileHandling {
    public static void main(String[] args) throws Exception {

        PrintWriter out = new PrintWriter("payroll.txt");
        out.println("111111 john smith 500");
        out.println("222222 mark smith 1500");
        out.println("333333 steve jones 2000");
        out.println("444444 mary jones 1000");
        out.close();
        Scanner in=new Scanner("payroll.txt");
        while (in.hasNext()){
</code>```

答:
c.

```<code>System.out.println("Account 1 id 111111 name: john smith balance: 500 $");
System.out.println("Account 2 id 222222 name: mark smith balance: 1500 $");
System.out.println("Account 3 id 333333 name: steve jones balance: 2000 $");
System.out.println("Account 4 id 444444 name: mary jones balance: 1000 $");
</code>```

If you have the variables data, you can replace each id, name and balance directly from the variables using String concatenation.

d.

```<code>int totalBalance = 500 + 1500 + 2000 + 1000;
System.out.println("Total balance of all accounts is " + totalBalance + " $");
</code>```

Title: Java File Handling DisplayOnConsole

Body:
Question – File Handling [20 pts]

Given the following data about some account information of First National bank customers:

111111  john smith   500

222222  mark smith  1500

333333  steve jones  2000

444444  mary jones  1000

           Write a Java program that:

a.    Writes the above data into file “payroll.txt”.

b.    Reads the above data from “payroll.txt”.

c.    Displays on java console the account information of each customer as follows:

Account 1  id: 111111  name: john smith  balance: 500 $

Account 2 id: 222222  name: mark smith  balance: 1500 $

 Account 3 id: 333333  name: steve jones  balance: 2000 $

Account 4 id:444444  name: mary jones  balance: 1000 $

d.    Calculate and display the total balance of all customers:
   Total balance of all accounts is 5000 $

i could only do part a & b i need help in part c & d please

import java.io.*;
import java.util.Scanner;
public class FileHandling {
    public static void main(String[] args) throws Exception {

        PrintWriter out = new PrintWriter("payroll.txt");
        out.println("111111 john smith 500");
        out.println("222222 mark smith 1500");
        out.println("333333 steve jones 2000");
        out.println("444444 mary jones 1000");
        out.close();
        Scanner in=new Scanner("payroll.txt");
        while (in.hasNext()){

Body:
c.

System.out.println("Account 1 id 111111 name: john smith balance: 500 $");
System.out.println("Account 2 id 222222 name: mark smith balance: 1500 $");
System.out.println("Account 3 id 333333 name: steve jones balance: 2000 $");
System.out.println("Account 4 id 444444 name: mary jones balance: 1000 $");

If you have the variables data, you can replace each id, name and balance directly from the variables using String concatenation.

d.

int totalBalance = 500 + 1500 + 2000 + 1000;
System.out.println("Total balance of all accounts is " + totalBalance + " $");


问:
I get RecycleView in Fragment and after click on recycleview element i need to send data to this fragment and restart it
Hi i have recycleView in my fragment

```<code>@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    View view = inflater.inflate(R.layout.fragment_list_petrole, container, false);

    recyclerView = (RecyclerView)view.findViewById(R.id.recycle_view);
    allPetroles = getArguments().getParcelableArrayList("petroles");

    mLayoutManager = new LinearLayoutManager(getActivity());
    recyclerView.setLayoutManager(mLayoutManager);

    mAdapter = new RecyclerAdapter(allPetroles, getActivity());
    recyclerView.setAdapter(mAdapter);

    return view;
}
</code>```

In RecycleView adapter i set OnClickListener in onBindViewHolder, so i need after click on some raw sent back to Fragment some info(position) and then make some changes(resent this info to Activity and add some new view there on Gmaps)
This onBindViewHolder:

```<code>@Override
public void onBindViewHolder(final ViewHolder holder, final int position) {

    holder.linearClick.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            positionClick = position;
            notifyDataSetChanged();

--------------I NEED CODE HERE----------------------

        }
    });
    if (positionClick == position) {
        holder.linearClick.setSelected(true);
    }
    else {
        holder.linearClick.setSelected(false);
    }
</code>```

and i don't understand how i should this do

答:
In RecyclerAdapter :

1- add an Inner Interface :

```<code>/**********
 *
 *  Inner interface
 *
 */
public interface OnClickListener {
    void onItemClicked(Item item);
}
</code>```

2- Add a parameter in the constructor :

```<code>public RecyclerAdapter(Context context, List<Item> data, OnClickListener onClickListener) {
    mContext = context;
    mData = data;
    mListener = onClickListener
}
</code>```

3- Call the listener :

```<code>@Override
public void onBindViewHolder(final ViewHolder holder, final int position) {
    holder.linearClick.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            //positionClick = position;
            //you don't need this here : notifyDataSetChanged();
            mListener.onItemClicked(mData.get(position));
        }
    });
    if (positionClick == position) {
        holder.linearClick.setSelected(true);
    }
    else {
        holder.linearClick.setSelected(false);
    }
</code>```

Your Fragment should implements RecyclerAdapter.OnClickListener

```<code>public class YourFragment extends Fragment implements RecyclerAdapter.OnClickListener {

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_list_petrole, container, false);
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        recyclerView = (RecyclerView)view.findViewById(R.id.recycle_view);
        allPetroles = getArguments().getParcelableArrayList("petroles");

        mLayoutManager = new LinearLayoutManager(getActivity());
        recyclerView.setLayoutManager(mLayoutManager);

        mAdapter = new RecyclerAdapter(getActivity(), allPetroles, this);
        recyclerView.setAdapter(mAdapter);
    }

    @Override
    void onItemClicked(Item item) {
        // TODO put your code here
    }
}
</code>```

Body:
Hi i have recycleView in my fragment

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    View view = inflater.inflate(R.layout.fragment_list_petrole, container, false);

    recyclerView = (RecyclerView)view.findViewById(R.id.recycle_view);
    allPetroles = getArguments().getParcelableArrayList("petroles");

    mLayoutManager = new LinearLayoutManager(getActivity());
    recyclerView.setLayoutManager(mLayoutManager);

    mAdapter = new RecyclerAdapter(allPetroles, getActivity());
    recyclerView.setAdapter(mAdapter);

    return view;
}

In RecycleView adapter i set OnClickListener in onBindViewHolder, so i need after click on some raw sent back to Fragment some info(position) and then make some changes(resent this info to Activity and add some new view there on Gmaps)
This onBindViewHolder:

@Override
public void onBindViewHolder(final ViewHolder holder, final int position) {

    holder.linearClick.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            positionClick = position;
            notifyDataSetChanged();

--------------I NEED CODE HERE----------------------

        }
    });
    if (positionClick == position) {
        holder.linearClick.setSelected(true);
    }
    else {
        holder.linearClick.setSelected(false);
    }

and i don't understand how i should this do

Body:
In RecyclerAdapter :

1- add an Inner Interface :

/**********
 *
 *  Inner interface
 *
 */
public interface OnClickListener {
    void onItemClicked(Item item);
}

2- Add a parameter in the constructor :

public RecyclerAdapter(Context context, List<Item> data, OnClickListener onClickListener) {
    mContext = context;
    mData = data;
    mListener = onClickListener
}

3- Call the listener :

@Override
public void onBindViewHolder(final ViewHolder holder, final int position) {
    holder.linearClick.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            //positionClick = position;
            //you don't need this here : notifyDataSetChanged();
            mListener.onItemClicked(mData.get(position));
        }
    });
    if (positionClick == position) {
        holder.linearClick.setSelected(true);
    }
    else {
        holder.linearClick.setSelected(false);
    }

Your Fragment should implements RecyclerAdapter.OnClickListener

public class YourFragment extends Fragment implements RecyclerAdapter.OnClickListener {

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_list_petrole, container, false);
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        recyclerView = (RecyclerView)view.findViewById(R.id.recycle_view);
        allPetroles = getArguments().getParcelableArrayList("petroles");

        mLayoutManager = new LinearLayoutManager(getActivity());
        recyclerView.setLayoutManager(mLayoutManager);

        mAdapter = new RecyclerAdapter(getActivity(), allPetroles, this);
        recyclerView.setAdapter(mAdapter);
    }

    @Override
    void onItemClicked(Item item) {
        // TODO put your code here
    }
}


问:
Django: issues with importing custom Python3 class
I'm new to Django (so this is likely a Python3 question). Also, I have read the other similar questions such as Error importing Python module.

I have a directory with the following structure:

-- my_class

-- -- __init__.py

-- -- custom_class_1.py

-- -- custom_class_2.py

where in the file custom_class_2.py there are the lines:

```<code>from custom_class_1 import Custom_Class_1
class Custom_Class_2:
    self.thing = Custom_Class_1()
</code>```

i.e. one class is built upon the others.

using the solution from the previously linked question

This causes the Django server to spit up this error:

```<code>from custom_class_1 import Custom_Class_1
ImportError: No module named 'Custom_Class_1'
</code>```

which makes me think I did not follow pythonic conventions when defining a class, built on another class (but all in the same directory).

What did I do wrong and how do I fix it?

答:
Imports in a Django project should use a module path from the project root.
For example, if my_class is at the root of your Django project,
then you can import Custom_Class_2 with:

```<code>from my_class.custom_class_2 import Custom_Class_2
</code>```

By the way, it's strange to name Python modules and classes with "class" in the name.

Body:
I'm new to Django (so this is likely a Python3 question). Also, I have read the other similar questions such as Error importing Python module.

I have a directory with the following structure:

-- my_class

-- -- __init__.py

-- -- custom_class_1.py

-- -- custom_class_2.py

where in the file custom_class_2.py there are the lines:

from custom_class_1 import Custom_Class_1
class Custom_Class_2:
    self.thing = Custom_Class_1()

i.e. one class is built upon the others.

using the solution from the previously linked question

This causes the Django server to spit up this error:

from custom_class_1 import Custom_Class_1
ImportError: No module named 'Custom_Class_1'

which makes me think I did not follow pythonic conventions when defining a class, built on another class (but all in the same directory).

What did I do wrong and how do I fix it?

Body:
Imports in a Django project should use a module path from the project root.
For example, if my_class is at the root of your Django project,
then you can import Custom_Class_2 with:

from my_class.custom_class_2 import Custom_Class_2

By the way, it's strange to name Python modules and classes with "class" in the name.


问:
How to remotely change IIS Application Pool setting via PowerShell?
I am trying to use PowerShell to iterate through a list of servers and change the 'MaxProcesses' value under 'ProcessModel' (found in Advanced Settings of Application Pool in IIS)

I have already figured out how to remotely start and stop application pools but I cannot seem to nail down how to modify settings.

Your help is appreciated!

PS - I am using Get-WmiObject to build the $appPool object where I call $appPool.Stop() and $appPool.Start(). Any ways to update settings also using this object, I'd be grateful!

答:
You can use this snippet:

```<code>$computerName = 'MyServerName'
$appPoolName = 'DefaultAppPool'
</code>```

Stop application pool:

```<code>Invoke-Command -ComputerName $computerName -args $appPoolName -ScriptBlock {
    param($appPoolName)
    # Check if application pool is already stopped
    if ((Get-WebAppPoolState -name $appPoolName).value -ne 'Stopped') {
        Stop-WebAppPool -Name $appPoolName
     }
}
</code>```

Stop application pool:

```<code>Invoke-Command -ComputerName $computerName -args $appPoolName -ScriptBlock {
   param($appPoolName)
    # Check if application pool is already started
    if ((Get-WebAppPoolState -name $appPoolName).value -ne 'Started') {
        Start-WebAppPool -Name $appPoolName
     }
}
</code>```

Body:
You can use this snippet:

$computerName = 'MyServerName'
$appPoolName = 'DefaultAppPool'

Stop application pool:

Invoke-Command -ComputerName $computerName -args $appPoolName -ScriptBlock {
    param($appPoolName)
    # Check if application pool is already stopped
    if ((Get-WebAppPoolState -name $appPoolName).value -ne 'Stopped') {
        Stop-WebAppPool -Name $appPoolName
     }
}

Stop application pool:

Invoke-Command -ComputerName $computerName -args $appPoolName -ScriptBlock {
   param($appPoolName)
    # Check if application pool is already started
    if ((Get-WebAppPoolState -name $appPoolName).value -ne 'Started') {
        Start-WebAppPool -Name $appPoolName
     }
}


问:
java compareTo method implementation
currently I'm trying to find out how java's interface  "Comparable" works.
As far as I know inteface cannot have any non-static (besides default ones) methods so when we implement an interface we need to define its methods first.

But when I implement "Comparable" interface I obviously can use its compareTo method. Where is that method defined?

```<code>public static <T extends Comparable<T>> int countGreaterThan(T[] anArray, T elem) {

    int count = 0;

    for (T e : anArray)
        if (e.compareTo(elem) > 0)
            ++count;
    return count;

}
</code>```

How come that I'm able to use interface's method without even defining it?

My apoligies if there was already an answer to that question, wasn't able to find it though.

Thx.

答:
The elements of your T[] array must be of some type that implements Comparable<T> (as a result of the <T extends Comparable<T>> type bound). Therefore you can call compareTo() on elements of that array.

Where compareTo is implemented depends on which array you are passing to your method. If, for example, you pass a String[], the compareTo method of the String class will be used.

Title: java compareTo method implementation

Body:
currently I'm trying to find out how java's interface  "Comparable" works.
As far as I know inteface cannot have any non-static (besides default ones) methods so when we implement an interface we need to define its methods first.

But when I implement "Comparable" interface I obviously can use its compareTo method. Where is that method defined?

public static <T extends Comparable<T>> int countGreaterThan(T[] anArray, T elem) {

    int count = 0;

    for (T e : anArray)
        if (e.compareTo(elem) > 0)
            ++count;
    return count;

}

How come that I'm able to use interface's method without even defining it?

My apoligies if there was already an answer to that question, wasn't able to find it though.

Thx.


问:
Need help to rewrite PHP function
I have a function that parses text form posts and if there's a link in the post it'll redirect the link to a page that warns a users about external link before they click it.

```<code>function url2link($txt) {
     $setUrl = preg_replace("/(http:\/\/|(www\.))(([^\s<]{4,68})[^\s<]*)/", '<a href="/link/$2$3" rel="nofollow">$2$4</a>', $txt);
     return $setUrl;
}
</code>```

I need to modify this function by adding a check for domain in the link. If the link is from my own domain, just convert it into clickable link like this:

```<code>$setUrl = preg_replace("/(http:\/\/|(www\.))(([^\s<]{4,68})[^\s<]*)/", '<a href="http://$2$3" rel="nofollow" target="_blank">$2$4</a>', $txt);
</code>```

but if it is a link to an external domain -- make a link point to a warning page (top example).

I am sort of stuck here because I have no idea how to add this check. There could be multiple links in a post, some may have local, some external links and some a mix.

答:
OK, as it turned out preg_replace_callback was exactly what I needed in this case. php.net documentation sucks. I found another article that made it clear what it is and how it works. I modified my function but it doesn't work... What am I missing?</p>

```<code>function url2link($txt) {

$checkDomain = preg_replace_callback('/(http:\/\/|(www\.))(([^\s<]{4,68})[^\s<]*)/', 'linkDomain', $txt);

   function linkDomain($matches) {

    $host =  parse_url($matches[0], PHP_URL_HOST);
    $host =  ltrim($host, 'www.');

    if ($host == 'mydomain.com') {
        $setUrl = preg_replace("/(http:\/\/|(www\.))(([^\s<]{4,68})[^\s<]*)/", '<a href="http://$2$3">$2$4</a>', $matches[0]);
    } else {
        $setUrl = preg_replace("/(http:\/\/|(www\.))(([^\s<]{4,68})[^\s<]*)/", '<a href="/link/$2$3" rel="nofollow">$2$4</a>', $matches[0]);
    }
   }
   return $setUrl;
}
</code>```

Title: Need help to rewrite PHP function

Body:
I have a function that parses text form posts and if there's a link in the post it'll redirect the link to a page that warns a users about external link before they click it.

function url2link($txt) {
     $setUrl = preg_replace("/(http:\/\/|(www\.))(([^\s<]{4,68})[^\s<]*)/", '$2$4', $txt);
     return $setUrl;
}

I need to modify this function by adding a check for domain in the link. If the link is from my own domain, just convert it into clickable link like this:

$setUrl = preg_replace("/(http:\/\/|(www\.))(([^\s<]{4,68})[^\s<]*)/", '$2$4', $txt);

but if it is a link to an external domain -- make a link point to a warning page (top example).

I am sort of stuck here because I have no idea how to add this check. There could be multiple links in a post, some may have local, some external links and some a mix.

Body:
OK, as it turned out preg_replace_callback was exactly what I needed in this case. php.net documentation sucks. I found another article that made it clear what it is and how it works. I modified my function but it doesn't work... What am I missing?

function url2link($txt) {

$checkDomain = preg_replace_callback('/(http:\/\/|(www\.))(([^\s<]{4,68})[^\s<]*)/', 'linkDomain', $txt);

   function linkDomain($matches) {

    $host =  parse_url($matches[0], PHP_URL_HOST);
    $host =  ltrim($host, 'www.');

    if ($host == 'mydomain.com') {
        $setUrl = preg_replace("/(http:\/\/|(www\.))(([^\s<]{4,68})[^\s<]*)/", '<a href="http://$2$3">$2$4</a>', $matches[0]);
    } else {
        $setUrl = preg_replace("/(http:\/\/|(www\.))(([^\s<]{4,68})[^\s<]*)/", '<a href="/link/$2$3" rel="nofollow">$2$4</a>', $matches[0]);
    }
   }
   return $setUrl;
}