问:
Change the appearance of labels and input fields (from a Model Form) used in a DJango template
I am using a script below (that resides in a DJango template) to display input fields that are associated with a particular Model Form. The purpose of this template is to add and modify data for a Model.

The name of the template is : model_name_form.html (ex: customer_form.html for the Model representation of the table Customer)

In order to add/modify data, the Model Form is being used.

The problem is that when using the script below, a type of default presentation is being used for the fields. In my case, the fields need to be more customized.

The customized labels and input fields make the form look much nicer.

I start out with this (which is in the template that displays the form):

```<code>   {% for field in form %}
        <div class="form-group">
            <div class="col-sm-offset-2 col-sm-10">
                <span class="text-danger small"> {{ field.errors }} </span>
            </div>
            <label class="control-label col-sm-2"> {{ field.label_tag }} </label>
            <div class="col-sm-10"> {{ field }} </div>
        </div>
    {% endfor %}
</code>```

Which turns into this:

```<code><div class="form-group">

   <div class="col-sm-offset-2 col-sm-10">

     <span class="text-danger small">
     </span>

   </div>

   <label class="control-label col-sm-2">
      <label for="id_companyname">Company Name:</label>

   </label>
   <div class="col-sm-10">

      <input name="companyname" id="id_companyname" type="text" maxlength="30">

   </div>

</div>
</code>```

But what is needed is a label/input presentation similar to the following:

```<code><div class="form-group">
     <label>Default Input Group</label>
           <div class="input-group">
                <input class="form-control" placeholder="Username" aria-describedby="sizing-addon1" type="text">
                <span class="input-group-addon" id="sizing-addon1">@</span>
           </div>
</div>
</code>```

How can one control the attributes associated with :

```<code>{{ field.errors }}
{{ field.label_tag }}
{{ field }}  <<< especially this one
</code>```

For example, one can see above,  {{ field }} produces

```<code><input name="companyname" id="id_companyname" type="text" maxlength="30">
</code>```

But what is needed is:

```<code><input class="form-control" placeholder="Username" aria-describedby="sizing-addon1" type="text">
</code>```

How can one control the way labels and input fields are presented?

TIA

答:
You can use widget attributes to have more control over the HTML output, for example:

```<code>class MyModelForm(ModelForm):

     class Meta:
        model = MyModel
        fields = '__all__'
        widgets = {
            'my_field': TextInput(attrs = {
                'placeholder': 'Ingrese el contacto',
                'class': 'form-control',
                'data-validation': 'custom',

            }),
            'my_other_field': Select(attrs = {
                'class': 'form-control selectpicker',
                'data-live-search': 'true',
                'title': 'Elegir un tipo',
                'data-validation': 'required',
                'data-validation-error-msg': 'Debe elegir una de las opciones.',
            }),
</code>```

In your case you could do:

```<code>        widgets = {
            'my_field': TextInput(attrs = {
                'placeholder': 'Username',
                'class': 'form-control',
                'aria-describedby': 'sizing-addon1',

            }),
</code>```

For more control, you can use custom template filters, or even try the library django crispy forms, but it adds a layer of complexity that maybe is not needed.

Body:
I am using a script below (that resides in a DJango template) to display input fields that are associated with a particular Model Form. The purpose of this template is to add and modify data for a Model.

The name of the template is : model_name_form.html (ex: customer_form.html for the Model representation of the table Customer)

In order to add/modify data, the Model Form is being used.

The problem is that when using the script below, a type of default presentation is being used for the fields. In my case, the fields need to be more customized.

The customized labels and input fields make the form look much nicer.

I start out with this (which is in the template that displays the form):

   {% for field in form %}

                 {{ field.errors }}

             {{ field.label_tag }}

 {{ field }}

    {% endfor %}

Which turns into this:

      Company Name:

      <input name="companyname" id="id_companyname" type="text" maxlength="30">

But what is needed is a label/input presentation similar to the following:

     Default Input Group

                <input class="form-control" placeholder="Username" aria-describedby="sizing-addon1" type="text">
                @

How can one control the attributes associated with :

{{ field.errors }}
{{ field.label_tag }}
{{ field }}  <<< especially this one

For example, one can see above,  {{ field }} produces

<input name="companyname" id="id_companyname" type="text" maxlength="30">

But what is needed is:

<input class="form-control" placeholder="Username" aria-describedby="sizing-addon1" type="text">

How can one control the way labels and input fields are presented?

TIA

Body:
You can use widget attributes to have more control over the HTML output, for example:

class MyModelForm(ModelForm):

     class Meta:
        model = MyModel
        fields = '__all__'
        widgets = {
            'my_field': TextInput(attrs = {
                'placeholder': 'Ingrese el contacto',
                'class': 'form-control',
                'data-validation': 'custom',

            }),
            'my_other_field': Select(attrs = {
                'class': 'form-control selectpicker',
                'data-live-search': 'true',
                'title': 'Elegir un tipo',
                'data-validation': 'required',
                'data-validation-error-msg': 'Debe elegir una de las opciones.',
            }),

In your case you could do:

        widgets = {
            'my_field': TextInput(attrs = {
                'placeholder': 'Username',
                'class': 'form-control',
                'aria-describedby': 'sizing-addon1',

            }),

For more control, you can use custom template filters, or even try the library django crispy forms, but it adds a layer of complexity that maybe is not needed.


来源: stackexchange

问:
How to use PIL paste with mask?
I am trying to use PIL paste() function. I want to put in a mask as well but I keep getting this error:

ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()

```<code>canvases[0].paste(mnist_images[i],
                  box=tuple(map(lambda p: int(round(p)), positions[i])), mask=mask)
</code>```

The code works without a mask. Mask is a numpy array. I have not seen an example with mask and the documentation is not clear.

https://pillow.readthedocs.io/en/latest/reference/Image.html#PIL.Image.Image.paste

If a mask is given, this method updates only the regions indicated by the mask. You can use either "1", "L", or "RGBA" images (in the latter case, the alpha band is used as mask). Where the mask is 255, the given image is copied as is. Where the mask is 0, the current value is preserved. Intermediate values will mix the two images together, including their alpha channels if they have them.

I dont have RGBA so how do I use "1" or "L"?

答:
The mask has to also be a PIL Image. This isn't explicitly mentioned in the docs, but it does state:

You can use either “1”, “L” or “RGBA” images (in the latter case, the alpha band is used as mask). Where the mask is 255, the given image is copied as is. Where the mask is 0, the current value is preserved. Intermediate values will mix the two images together, including their alpha channels if they have them.

So this hints that they need to be PIL Images. From the Pillow concepts page:

The mode of an image defines the type and depth of a pixel in the
  image. The current release supports the following standard modes:

1 (1-bit pixels, black and white, stored with one pixel per byte)

  L (8-bit pixels, black and white)

  ...

The fix then is to simply turn your mask to a PIL Image with

```<code>mask = Image.fromarray(mask)
</code>```

However, do note that for a binary mask, PIL expects the mask to have only 0 and 255 inside it as it states above (values between will blend). So if your mask is a numpy bool type, then you'd want to do something like:

```<code>mask = Image.fromarray(np.uint8(255*mask))
</code>```

For e.g.:

```<code>>>> import numpy as np
>>> import cv2
>>> from PIL import Image
>>> img = Image.fromarray(np.uint8(255*np.random.rand(400, 400, 3)))
>>> sub_img = Image.fromarray(np.uint8(255*np.ones((200, 200, 3))))
>>> mask = Image.fromarray(np.uint8(255*(np.random.rand(200, 200) > 0.7)))
>>> img.paste(sub_img, (0, 0), mask)
</code>```

Here I've pasted the white sub_img over img at the top left, and masked out ~70% of the pixels from the pasting operation, so only ~30% of the pixels in the region actually come out as white.

ContentLicense: CC BY-SA 4.0

Title: How to use PIL paste with mask?

Body:
I am trying to use PIL paste() function. I want to put in a mask as well but I keep getting this error:

ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()

canvases[0].paste(mnist_images[i],
                  box=tuple(map(lambda p: int(round(p)), positions[i])), mask=mask)

The code works without a mask. Mask is a numpy array. I have not seen an example with mask and the documentation is not clear.

https://pillow.readthedocs.io/en/latest/reference/Image.html#PIL.Image.Image.paste

If a mask is given, this method updates only the regions indicated by the mask. You can use either "1", "L", or "RGBA" images (in the latter case, the alpha band is used as mask). Where the mask is 255, the given image is copied as is. Where the mask is 0, the current value is preserved. Intermediate values will mix the two images together, including their alpha channels if they have them.

I dont have RGBA so how do I use "1" or "L"?

Body:
The mask has to also be a PIL Image. This isn't explicitly mentioned in the docs, but it does state:

You can use either “1”, “L” or “RGBA” images (in the latter case, the alpha band is used as mask). Where the mask is 255, the given image is copied as is. Where the mask is 0, the current value is preserved. Intermediate values will mix the two images together, including their alpha channels if they have them.

So this hints that they need to be PIL Images. From the Pillow concepts page:

The mode of an image defines the type and depth of a pixel in the
  image. The current release supports the following standard modes:

1 (1-bit pixels, black and white, stored with one pixel per byte)

  L (8-bit pixels, black and white)

  ...

The fix then is to simply turn your mask to a PIL Image with

mask = Image.fromarray(mask)

However, do note that for a binary mask, PIL expects the mask to have only 0 and 255 inside it as it states above (values between will blend). So if your mask is a numpy bool type, then you'd want to do something like:

mask = Image.fromarray(np.uint8(255*mask))

For e.g.:

>>> import numpy as np
>>> import cv2
>>> from PIL import Image
>>> img = Image.fromarray(np.uint8(255*np.random.rand(400, 400, 3)))
>>> sub_img = Image.fromarray(np.uint8(255*np.ones((200, 200, 3))))
>>> mask = Image.fromarray(np.uint8(255*(np.random.rand(200, 200) > 0.7)))
>>> img.paste(sub_img, (0, 0), mask)

Here I've pasted the white sub_img over img at the top left, and masked out ~70% of the pixels from the pasting operation, so only ~30% of the pixels in the region actually come out as white.

ContentLicense: CC BY-SA 3.0


问:
R Error in get: object '.xts_chob' not found
I am trying to execute the following code -

```<code>library(dplyr) ; library(rgdal) ; library(leaflet);
crimes <- read.csv("crime_data.csv", header = T) %>%
  filter(borough == "Manchester",
         date == "2015-11-01") %>%
  group_by(category, lsoa, borough) %>%
  summarise(n = n()) %>%
  rename(LSOA11CD = lsoa) %>%
  as.data.frame()
lsoa <- readOGR("manchester_lsoa.geojson", "OGRGeoJSON")
ui <- shinyUI(fluidPage(
  fluidRow(
    column(7, offset = 1,
           br(),
           div(h4(textOutput("title"), align = "center"), style = "color:black"),
           div(h5(textOutput("period"), align = "center"), style = "color:black"),
           br())),
  fluidRow(
    column(7, offset = 1,
           leafletOutput("map", height="530"),
           br(),
           actionButton("reset_button", "Reset view")),
    column(3,
           uiOutput("category", align = "left")))
))
server <- (function(input, output, session) {
  output$category <- renderUI({
    radioButtons("category", "Select a crime category:",
                 choices = levels(crimes$category),
                 selected = "Burglary")
  })
  selected <- reactive({
    subset(crimes,
           category==input$category)
  })
  output$title <- renderText({
    req(input$category)
    paste0(input$category, " offences by LSOA in Manchester")
  })
  output$period <- renderText({
    req(input$category)
    paste("during November 2015")
  })
  lat <- 53.442788; lng <- -2.244708; zoom <- 11
  output$map <- renderLeaflet({
    leaflet() %>%
      addProviderTiles("CartoDB.Positron") %>%
      setView(lat = lat, lng = lng, zoom = zoom)
  })
  observe({
    lsoa@data <- left_join(lsoa@data, selected())
    lsoa$rate <- round((lsoa$n / lsoa$pop_All.Ag) * 1000, 1)
    qpal <- colorQuantile("YlGn", lsoa$rate, n = 5, na.color = "#bdbdbd")
    popup <- paste0("<strong>LSOA: </strong>",
                    lsoa$LSOA11CD,
                    "<br><strong>Category: </strong>",
                    lsoa$category,
                    "<br><strong>Rate: </strong>",
                    lsoa$rate)
    leafletProxy("map", data = lsoa) %>%
      addProviderTiles("CartoDB.Positron") %>%
      clearShapes() %>%
      clearControls() %>%
      addPolygons(data = lsoa, fillColor = ~qpal(rate), fillOpacity = 0.7,
                  color = "white", weight = 2, popup = popup) %>%
      addLegend(pal = qpal, values = ~rate, opacity = 0.7,
                position = 'bottomright',
                title = paste0(input$category, "<br>", " per 1,000 population"))
  })
  observe({
    input$reset_button
    leafletProxy("map") %>% setView(lat = lat, lng = lng, zoom = zoom)
  })
})
shinyApp(ui, server)
</code>```

and I get this error

```<code>Warning in is.na(e2) :
  is.na() applied to non-(list or vector) of type 'NULL'
Joining, by = "LSOA11CD"
Warning: Column `LSOA11CD` joining factors with different levels, coercing to character vector
Warning: Error in get: object '.xts_chob' not found
ERROR: [on_request_read] connection reset by peer
</code>```

The links to the required files are this and this

Can someone please tell me what the error is? Is the error due to leaflet package? Or is it because of other packages? And also can someone give me the solution to the error as well?

答:
Probe using an old version of 'xts', for example install the version 0.9:</p>

```<code>require(devtools)
install_version("xts", version = "0.9-7", repos = "http://cran.us.r-project.org")
</code>```

Body:
I am trying to execute the following code -

library(dplyr) ; library(rgdal) ; library(leaflet);
crimes <- read.csv("crime_data.csv", header = T) %>%
  filter(borough == "Manchester",
         date == "2015-11-01") %>%
  group_by(category, lsoa, borough) %>%
  summarise(n = n()) %>%
  rename(LSOA11CD = lsoa) %>%
  as.data.frame()
lsoa <- readOGR("manchester_lsoa.geojson", "OGRGeoJSON")
ui <- shinyUI(fluidPage(
  fluidRow(
    column(7, offset = 1,
           br(),
           div(h4(textOutput("title"), align = "center"), style = "color:black"),
           div(h5(textOutput("period"), align = "center"), style = "color:black"),
           br())),
  fluidRow(
    column(7, offset = 1,
           leafletOutput("map", height="530"),
           br(),
           actionButton("reset_button", "Reset view")),
    column(3,
           uiOutput("category", align = "left")))
))
server <- (function(input, output, session) {
  output$category <- renderUI({
    radioButtons("category", "Select a crime category:",
                 choices = levels(crimes$category),
                 selected = "Burglary")
  })
  selected <- reactive({
    subset(crimes,
           category==input$category)
  })
  output$title <- renderText({
    req(input$category)
    paste0(input$category, " offences by LSOA in Manchester")
  })
  output$period <- renderText({
    req(input$category)
    paste("during November 2015")
  })
  lat <- 53.442788; lng <- -2.244708; zoom <- 11
  output$map <- renderLeaflet({
    leaflet() %>%
      addProviderTiles("CartoDB.Positron") %>%
      setView(lat = lat, lng = lng, zoom = zoom)
  })
  observe({
    lsoa@data <- left_join(lsoa@data, selected())
    lsoa$rate <- round((lsoa$n / lsoa$pop_All.Ag) * 1000, 1)
    qpal <- colorQuantile("YlGn", lsoa$rate, n = 5, na.color = "#bdbdbd")
    popup <- paste0("LSOA: ",
                    lsoa$LSOA11CD,
                    "
Category: ",
                    lsoa$category,
                    "
Rate: ",
                    lsoa$rate)
    leafletProxy("map", data = lsoa) %>%
      addProviderTiles("CartoDB.Positron") %>%
      clearShapes() %>%
      clearControls() %>%
      addPolygons(data = lsoa, fillColor = ~qpal(rate), fillOpacity = 0.7,
                  color = "white", weight = 2, popup = popup) %>%
      addLegend(pal = qpal, values = ~rate, opacity = 0.7,
                position = 'bottomright',
                title = paste0(input$category, "
", " per 1,000 population"))
  })
  observe({
    input$reset_button
    leafletProxy("map") %>% setView(lat = lat, lng = lng, zoom = zoom)
  })
})
shinyApp(ui, server)

and I get this error

Warning in is.na(e2) :
  is.na() applied to non-(list or vector) of type 'NULL'
Joining, by = "LSOA11CD"
Warning: Column `LSOA11CD` joining factors with different levels, coercing to character vector
Warning: Error in get: object '.xts_chob' not found
ERROR: [on_request_read] connection reset by peer

The links to the required files are this and this

Can someone please tell me what the error is? Is the error due to leaflet package? Or is it because of other packages? And also can someone give me the solution to the error as well?

Body:
Probe using an old version of 'xts', for example install the version 0.9:

require(devtools)
install_version("xts", version = "0.9-7", repos = "http://cran.us.r-project.org")


问:
Get variable name from argument/parameter in class function
I try to get the name of the variable, which I passed to a function.

```<code>class A():
  def __init__(self):
    self.a = 1

class B():
  def __init__(self):
    self.b = A()
    self.c = A()

  def doSomething(self, hello):
    print(hello)

B().doSomething(B().b)
<__main__.A object at 0x7f67571a3d68>
</code>```

What I want is that I can identify in the function B().doSomething(), that the variable is b. Is this possible? One restriction is that in the function B().doSomething() only instance variables of B are passed.

For example in peewee (https://github.com/coleifer/peewee), a MySQL ORM in python, they build expressions for filtering like:

```<code>B.select().where(B.b == True)
</code>```

And somehow they are able to identify, that b is passed. Because otherwise the query can not be build properly.

I know they are using static variables in the class, is this maybe the trick?

Thanks for helping! :)

答:
Going by your B().doSomething(B().b) example call I'm going to assume you're attempting to determine if the variable hello is equivalent to the variable b declared on the class B object.

In which case, all you need to do is call the self reference. self refers to the instance of the object that you're working with and every method defined within a class automatically gets reference to the object's self as a method attribute.

Thus, to determine if the the object b variable is equal to the hello parameter all you need to do is if self.b == hello: #do code

Body:
I try to get the name of the variable, which I passed to a function.

class A():
  def __init__(self):
    self.a = 1

class B():
  def __init__(self):
    self.b = A()
    self.c = A()

  def doSomething(self, hello):
    print(hello)

B().doSomething(B().b)
<__main__.A object at 0x7f67571a3d68>

What I want is that I can identify in the function B().doSomething(), that the variable is b. Is this possible? One restriction is that in the function B().doSomething() only instance variables of B are passed.

For example in peewee (https://github.com/coleifer/peewee), a MySQL ORM in python, they build expressions for filtering like:

B.select().where(B.b == True)

And somehow they are able to identify, that b is passed. Because otherwise the query can not be build properly.

I know they are using static variables in the class, is this maybe the trick?

Thanks for helping! :)


问:
How to solve comparing structs as key map c++
None topic solved my problem of comparing structs as key map in C++.

Structs code following:

```<code>struct XYZ{
  int x, y, z;
}

struct XYZComp{
  bool operator()(const XYZ& l, const XYZ& r)
  {
    return ((l.x==r.x)&&(l.y==r.y)&&(l.z==r.z));
  }
}
</code>```

Main looks like

```<code>int main()
{
  map<XYZ, int, XYZComp> m;
  m.insert(std::make_pair<XYZ,int>({1,2,3}, 1)); //ok

  map<XYZ, int, XYZComp>::iterator it = m.find({1,0,3});
  if(it!=m.end())
  {
    std::cout<<"Key exists in map";
  }
  else
  {
    m.insert(std::make_pair<XYZ,int>({1,0,3}, 1));
    //never come here
    //compiler thinks key already exists in map
  }

return 0;
}
</code>```

I just tried without XYZComparer but it still doesn't work.

```<code>struct XYZ{
  int x,y,z;
  bool operator==(const XYZ& xyz)
  {
    return (x=xyz.x) && (y=xyz.y) && (z=xyz.z);
  }
  bool operator<(const XYZ& xyz)
  {
    return (x>xyz.x) && (y>xyz.y) && (z>xyz.z);
  }
}
</code>```

How to solve comparing these structs XYZ while i am trying existing item in map.

Edit: Compiler thinks structs are the same when at least one number is correct.

答:
The std::map uses < to order items.  Thus your struct XYZComp needs to supply a user-defined operator <.

A very simple solution is to use std::tie:

```<code>#include <tuple>
//..
struct XYZComp
{
    int x,y,z;
    bool operator < (const XYZComp& xyz)
    {
       return std::tie(x, y, z) < std::tie(xyz.x, xyz.y, xyz.z);
    }
    //...
};
</code>```

The std::tie introduces lexicographical ordering to your struct's elements.

You could do the same thing by cascading down the < comparisons, but then the code becomes longer and is easier to make a mistake:

```<code>struct XYZComp
{
    int x,y,z;
    bool operator < (const XYZComp& xyz)
    {
       if ( x < xyz.x )
         return true;
       if ( x == xyz.x &&  y < xyz.y )
         return true;
       if ( x == xyz.x && y == xyz.y )
           return z < xyz.z;
       return false;
   }
    //...
};
</code>```

Body:
None topic solved my problem of comparing structs as key map in C++.

Structs code following:

struct XYZ{
  int x, y, z;
}

struct XYZComp{
  bool operator()(const XYZ& l, const XYZ& r)
  {
    return ((l.x==r.x)&&(l.y==r.y)&&(l.z==r.z));
  }
}

Main looks like

int main()
{
  map<XYZ, int, XYZComp> m;
  m.insert(std::make_pair<XYZ,int>({1,2,3}, 1)); //ok

  map<XYZ, int, XYZComp>::iterator it = m.find({1,0,3});
  if(it!=m.end())
  {
    std::cout<<"Key exists in map";
  }
  else
  {
    m.insert(std::make_pair<XYZ,int>({1,0,3}, 1));
    //never come here
    //compiler thinks key already exists in map
  }

return 0;
}

I just tried without XYZComparer but it still doesn't work.

struct XYZ{
  int x,y,z;
  bool operator==(const XYZ& xyz)
  {
    return (x=xyz.x) && (y=xyz.y) && (z=xyz.z);
  }
  bool operator<(const XYZ& xyz)
  {
    return (x>xyz.x) && (y>xyz.y) && (z>xyz.z);
  }
}

How to solve comparing these structs XYZ while i am trying existing item in map.

Edit: Compiler thinks structs are the same when at least one number is correct.

Body:
The std::map uses < to order items.  Thus your struct XYZComp needs to supply a user-defined operator <.

A very simple solution is to use std::tie:

#include <tuple>
//..
struct XYZComp
{
    int x,y,z;
    bool operator < (const XYZComp& xyz)
    {
       return std::tie(x, y, z) < std::tie(xyz.x, xyz.y, xyz.z);
    }
    //...
};

The std::tie introduces lexicographical ordering to your struct's elements.

You could do the same thing by cascading down the < comparisons, but then the code becomes longer and is easier to make a mistake:

struct XYZComp
{
    int x,y,z;
    bool operator < (const XYZComp& xyz)
    {
       if ( x < xyz.x )
         return true;
       if ( x == xyz.x &&  y < xyz.y )
         return true;
       if ( x == xyz.x && y == xyz.y )
           return z < xyz.z;
       return false;
   }
    //...
};


问:
does git retain some knowledge of what time the commit was made
As I understand it, commits that don't show up in git log can still exist in the repository. I've checked this myself, by doing git show id-of-squashed-commit

My question is, does git store some knowledge of what time the commit was made?

Use case: Say you hired a coder to work on the weekdays, but suspect all the work gets done in the weekends. The coder squashes commits before push to GitHub. But can those hidden commits contain some timing information?

答:
Yes: each commit has two time stamps attached, the "author" timestamp and the "committer" timestamp.

There are numerous pitfalls with trying to use these, though:

They're under control of the author/committer.

They're subject to erroneous computer clocks.

They may be difficult to interpret (they have time zone offsets).

Even if they're accurate, you must have the commit objects.

Because Git is distributed, and committers can commit within their own repositories, they can make a series of commits, then git squash the series of commits to make a new commit, then git push only the new commit.  In this case you don't have the original commits anywhere: they are only in the committer's repository, not on GitHub and not in your clone either.


问:
React Native: setState triggers unwanted Tab change in Tab Navigator
Something does not make sense with my code.
I am using React Native to create a app.
In that app I am using a Tab Navigator.
It works fine until I call this.setState which for some reason triggers a unwanted Tab change from one tab to the other.

Why would setState trigger a Tab change??

This is my code:

```<code>import React from 'react';
import { StyleSheet, Text, View, FlatList, TextInput, StatusBar, Button } from 'react-native';
import { TabNavigator } from 'react-navigation';
import { Constants } from 'expo'
import { purple, white } from './utils/colors'

const R = require('ramda')

function CustomStatusBar({ backgroundColor, ...props }){
  return (
    <View style={{backgroundColor, height: Constants.statusBarHeight}}>
      <StatusBar translucent backgroundColor={backgroundColor} {...props} />
    </View>
  )
}

export default class App extends React.Component {

  constructor(props){
    super(props)

    this.handleDeckTitle = this.handleDeckTitle.bind(this)
  }

  state = {
    title: ''
  }

  renderItem = (sample) => {
    console.log('renderItem', sample)

    return <Text>SAMPLE DATA</Text>
  }

  handleDeckTitle(e){
    console.log('handleDeckTitle')
    console.log('e', e)
    console.log('this.state', this.state)

    this.setState((prevState, props) => ({
      title: e
    }));
  }

  submitDeckTitle(){
    console.log('submitDeckTitle')

  }
  render() {

    console.log('R', R)

    const Decks = () => {
      return (
        <View>
          <CustomStatusBar backgroundColor={purple} barStyle='light-content' />
          <Text>Decks!</Text>
        </View>
      )

    }

    const NewDeck = () => {

      return (
        <View>
          <CustomStatusBar backgroundColor={purple} barStyle='light-content' />
          <Text>What is the title of your new deck?</Text>
          <TextInput style = {styles.input} onChangeText={this.handleDeckTitle}/>
          <Button onPress={this.submitDeckTitle} title="Submit" />
        </View>
      )

    }

    const Tabs = TabNavigator({
      Decks: {
        screen: Decks
      },
      'New Deck': {
        screen: NewDeck
      },
    });

    return (

      <Tabs />

    );
  }
}

const styles = StyleSheet.create({
  container: {
    paddingTop: 23,
    flex: 1,
    backgroundColor: '#fff',
    alignItems: 'center',
    justifyContent: 'center',
  },
  input: {
      margin: 15,
      height: 40,
      borderColor: '#7a42f4',
      borderWidth: 1
   },
});
</code>```

I don't see what is wrong with this code.
In fact I think it should just work normally but it does not.
It triggers a tab change when I call handleDeckTitle which then calls this.setState

答:
Got it to work now.

I changed the part that calls setState to be be a Separate Component with its own state.

Here is the code:

```<code>import React from 'react';
import { StyleSheet, Text, View, FlatList, TextInput, StatusBar, Button } from 'react-native';
import { TabNavigator } from 'react-navigation';
import { Constants } from 'expo'
import { purple, white } from './utils/colors'

const R = require('ramda')

function CustomStatusBar({ backgroundColor, ...props }){
  return (
    <View style={{backgroundColor, height: Constants.statusBarHeight}}>
      <StatusBar translucent backgroundColor={backgroundColor} {...props} />
    </View>
  )
}

const Decks = () => {
  return (
    <View>
      <CustomStatusBar backgroundColor={purple} barStyle='light-content' />
      <Text>Decks!</Text>
    </View>
  )

}

class NewDeck extends React.Component {
  constructor(props){
    super(props)
    this.handleDeckTitle = this.handleDeckTitle.bind(this)
  }

  state = {
    title: ''
  }

  handleDeckTitle(e){
    console.log('handleDeckTitle')
    console.log('e', e)
    console.log('this.state', this.state)

    this.setState((prevState, props) => ({
      title: e
    }));
  }

  render(){
    return (

          <View>
            <CustomStatusBar backgroundColor={purple} barStyle='light-content' />
            <Text>What is the title of your new deck?</Text>
            <TextInput style = {styles.input} onChangeText={this.handleDeckTitle}/>
            <Button onPress={this.submitDeckTitle} title="Submit" />
          </View>
        )

  }
}

const Tabs = TabNavigator({
  Decks: {
    screen: Decks
  },
  'New Deck': {
    screen: NewDeck
  },
});

export default class App extends React.Component {

  constructor(props){
    super(props)

    // this.handleDeckTitle = this.handleDeckTitle.bind(this)
  }

  state = {
    title: ''
  }

  renderItem = (sample) => {
    console.log('renderItem', sample)

    return <Text>SAMPLE DATA</Text>
  }

  submitDeckTitle(){
    console.log('submitDeckTitle')

  }
  render() {

    console.log('R', R)

    return (

      <Tabs />

    );
  }
}

const styles = StyleSheet.create({
  container: {
    paddingTop: 23,
    flex: 1,
    backgroundColor: '#fff',
    alignItems: 'center',
    justifyContent: 'center',
  },
  input: {
      margin: 15,
      height: 40,
      borderColor: '#7a42f4',
      borderWidth: 1
   },
});
</code>```

Body:
Something does not make sense with my code.
I am using React Native to create a app.
In that app I am using a Tab Navigator.
It works fine until I call this.setState which for some reason triggers a unwanted Tab change from one tab to the other.

Why would setState trigger a Tab change??

This is my code:

import React from 'react';
import { StyleSheet, Text, View, FlatList, TextInput, StatusBar, Button } from 'react-native';
import { TabNavigator } from 'react-navigation';
import { Constants } from 'expo'
import { purple, white } from './utils/colors'

const R = require('ramda')

function CustomStatusBar({ backgroundColor, ...props }){
  return (
    <View style={{backgroundColor, height: Constants.statusBarHeight}}>
      <StatusBar translucent backgroundColor={backgroundColor} {...props} />
    </View>
  )
}

export default class App extends React.Component {

  constructor(props){
    super(props)

    this.handleDeckTitle = this.handleDeckTitle.bind(this)
  }

  state = {
    title: ''
  }

  renderItem = (sample) => {
    console.log('renderItem', sample)

    return <Text>SAMPLE DATA</Text>
  }

  handleDeckTitle(e){
    console.log('handleDeckTitle')
    console.log('e', e)
    console.log('this.state', this.state)

    this.setState((prevState, props) => ({
      title: e
    }));
  }

  submitDeckTitle(){
    console.log('submitDeckTitle')

  }
  render() {

    console.log('R', R)

    const Decks = () => {
      return (
        <View>
          <CustomStatusBar backgroundColor={purple} barStyle='light-content' />
          <Text>Decks!</Text>
        </View>
      )

    }

    const NewDeck = () => {

      return (
        <View>
          <CustomStatusBar backgroundColor={purple} barStyle='light-content' />
          <Text>What is the title of your new deck?</Text>
          <TextInput style = {styles.input} onChangeText={this.handleDeckTitle}/>
          <Button onPress={this.submitDeckTitle} title="Submit" />
        </View>
      )

    }

    const Tabs = TabNavigator({
      Decks: {
        screen: Decks
      },
      'New Deck': {
        screen: NewDeck
      },
    });

    return (

      <Tabs />

    );
  }
}

const styles = StyleSheet.create({
  container: {
    paddingTop: 23,
    flex: 1,
    backgroundColor: '#fff',
    alignItems: 'center',
    justifyContent: 'center',
  },
  input: {
      margin: 15,
      height: 40,
      borderColor: '#7a42f4',
      borderWidth: 1
   },
});

I don't see what is wrong with this code.
In fact I think it should just work normally but it does not.
It triggers a tab change when I call handleDeckTitle which then calls this.setState

Body:
Got it to work now.

I changed the part that calls setState to be be a Separate Component with its own state.

Here is the code:

import React from 'react';
import { StyleSheet, Text, View, FlatList, TextInput, StatusBar, Button } from 'react-native';
import { TabNavigator } from 'react-navigation';
import { Constants } from 'expo'
import { purple, white } from './utils/colors'

const R = require('ramda')

function CustomStatusBar({ backgroundColor, ...props }){
  return (
    <View style={{backgroundColor, height: Constants.statusBarHeight}}>
      <StatusBar translucent backgroundColor={backgroundColor} {...props} />
    </View>
  )
}

const Decks = () => {
  return (
    <View>
      <CustomStatusBar backgroundColor={purple} barStyle='light-content' />
      <Text>Decks!</Text>
    </View>
  )

}

class NewDeck extends React.Component {
  constructor(props){
    super(props)
    this.handleDeckTitle = this.handleDeckTitle.bind(this)
  }

  state = {
    title: ''
  }

  handleDeckTitle(e){
    console.log('handleDeckTitle')
    console.log('e', e)
    console.log('this.state', this.state)

    this.setState((prevState, props) => ({
      title: e
    }));
  }

  render(){
    return (

          <View>
            <CustomStatusBar backgroundColor={purple} barStyle='light-content' />
            <Text>What is the title of your new deck?</Text>
            <TextInput style = {styles.input} onChangeText={this.handleDeckTitle}/>
            <Button onPress={this.submitDeckTitle} title="Submit" />
          </View>
        )

  }
}

const Tabs = TabNavigator({
  Decks: {
    screen: Decks
  },
  'New Deck': {
    screen: NewDeck
  },
});

export default class App extends React.Component {

  constructor(props){
    super(props)

    // this.handleDeckTitle = this.handleDeckTitle.bind(this)
  }

  state = {
    title: ''
  }

  renderItem = (sample) => {
    console.log('renderItem', sample)

    return <Text>SAMPLE DATA</Text>
  }

  submitDeckTitle(){
    console.log('submitDeckTitle')

  }
  render() {

    console.log('R', R)

    return (

      <Tabs />

    );
  }
}

const styles = StyleSheet.create({
  container: {
    paddingTop: 23,
    flex: 1,
    backgroundColor: '#fff',
    alignItems: 'center',
    justifyContent: 'center',
  },
  input: {
      margin: 15,
      height: 40,
      borderColor: '#7a42f4',
      borderWidth: 1
   },
});


问:
Jboss fuse missing osgi.wiring.package
When I start my Jboss fuse server this error pops up

```<code>ERROR: Bundle cxf-basic [293] Error starting mvn:org.fusesource.example/cxf-basic/1.0-SNAPSHOT (org.osgi.framework.BundleException: Unresolved constraint in bundle cxf-basic [293]: Unable to resolve 293.0: missing requirement [293.0] osgi.wiring.package; (&(osgi.wiring.package=META-INF.cxf)(version>=2.6.0)(!(version>=3.0.0))))
</code>```

org.osgi.framework.BundleException: Unresolved constraint in bundle cxf-basic [293]: Unable to resolve 293.0: missing requirement [293.0] osgi.wiring.package; (&(osgi.wiring.package=META-INF.cxf)(version>=2.6.0)(!(version>=3.0.0)))
        at org.apache.felix.framework.Felix.resolveBundleRevision(Felix.java:4002)
        at org.apache.felix.framework.Felix.startBundle(Felix.java:2045)
        at org.apache.felix.framework.Felix.setActiveStartLevel(Felix.java:1299)
        at org.apache.felix.framework.FrameworkStartLevelImpl.run(FrameworkStartLevelImpl.java:304)
        at java.lang.Thread.run(Thread.java:748)

my suspect is there's missing/conflicted version of osgi.wiring package, but how do I check?

Oh Hi guys, another update I finally got into my hawtio, the bundle gives me this error logs

I was able to do everything normally if I run the program as java application, but when I deploy to fuse this errors pops up

答:
What's the JBoss FUSE version you are using?

The META-INF.cxf was exported by all-in-one cxf-bundle, however this was deprecated for very long time. We now use small CXF bundles for each module in CXF.

So the cxf-basic bundle shouldn't Import Package META-INF.cxf anymore if you wanna it works in the latest JBoss FUSE.

Freeman

Title: Jboss fuse missing osgi.wiring.package

Body:
When I start my Jboss fuse server this error pops up

ERROR: Bundle cxf-basic [293] Error starting mvn:org.fusesource.example/cxf-basic/1.0-SNAPSHOT (org.osgi.framework.BundleException: Unresolved constraint in bundle cxf-basic [293]: Unable to resolve 293.0: missing requirement [293.0] osgi.wiring.package; (&(osgi.wiring.package=META-INF.cxf)(version>=2.6.0)(!(version>=3.0.0))))

org.osgi.framework.BundleException: Unresolved constraint in bundle cxf-basic [293]: Unable to resolve 293.0: missing requirement [293.0] osgi.wiring.package; (&(osgi.wiring.package=META-INF.cxf)(version>=2.6.0)(!(version>=3.0.0)))
        at org.apache.felix.framework.Felix.resolveBundleRevision(Felix.java:4002)
        at org.apache.felix.framework.Felix.startBundle(Felix.java:2045)
        at org.apache.felix.framework.Felix.setActiveStartLevel(Felix.java:1299)
        at org.apache.felix.framework.FrameworkStartLevelImpl.run(FrameworkStartLevelImpl.java:304)
        at java.lang.Thread.run(Thread.java:748)

my suspect is there's missing/conflicted version of osgi.wiring package, but how do I check?

Oh Hi guys, another update I finally got into my hawtio, the bundle gives me this error logs

I was able to do everything normally if I run the program as java application, but when I deploy to fuse this errors pops up


问:
Python: Create an array of substrings from an array
I grabbed an array from the lines of a txt file. The problem is I only need the end of these lines. I'm still pretty new to Python so I'm not sure how to put these concepts together. Below is my best attempt, the first part works but the second falls apart.</p>

```<code> with open("prices.txt") as f:
        readline = f.readlines()

 for seatCapacity in readline:
        seatCapacity = readline[10:]
</code>```

答:
I guess, you want like this.

```<code>with open("prices.txt") as f:
     for line in f:
     seatCapacity = line[10:]
</code>```

you can refer this solution: How should I read a file line-by-line in Python?

Body:
I grabbed an array from the lines of a txt file. The problem is I only need the end of these lines. I'm still pretty new to Python so I'm not sure how to put these concepts together. Below is my best attempt, the first part works but the second falls apart.

 with open("prices.txt") as f:
        readline = f.readlines()

 for seatCapacity in readline:
        seatCapacity = readline[10:]

Body:
I guess, you want like this.

with open("prices.txt") as f:
     for line in f:
     seatCapacity = line[10:]

you can refer this solution: How should I read a file line-by-line in Python?


问:
How to run once function on scroll up and scroll down event?
How to run doSomething() once when scrolling up or scrolling down?

```<code>window.onscroll = function(e) {
   // scrolling up
   if(this.oldScroll > this.scrollY){
      doSomething();
   // scrolling down
   } else {
      doSomething();
   }
   this.oldScroll = this.scrollY;
};
</code>```

The doSomething() bind some elements and I don't want to do repeat binds. I Just want when on scrolling up, bind once and when on scrolling down bind once.

答:
If you mean, your function should be executed once per each scroll event, then your code should do the job already.

However, if you mean you want your function to only be executed first time when the user scrolls, the code can look like this:

```<code>window.onscroll = function(e) {
  if (this.oldScroll > this.scrollY) {
     doSomething();
  } else {
     doSomethingElse();
  }
  this.oldScroll = this.scrollY;

  delete window.onscroll;
};
</code>```

Do NOT rely on any kind of "flag variables" as it is proposed above. It is a very bad practice in this scenario!

Body:
How to run doSomething() once when scrolling up or scrolling down?

window.onscroll = function(e) {
   // scrolling up
   if(this.oldScroll > this.scrollY){
      doSomething();
   // scrolling down
   } else {
      doSomething();
   }
   this.oldScroll = this.scrollY;
};

The doSomething() bind some elements and I don't want to do repeat binds. I Just want when on scrolling up, bind once and when on scrolling down bind once.

Body:
If you mean, your function should be executed once per each scroll event, then your code should do the job already.

However, if you mean you want your function to only be executed first time when the user scrolls, the code can look like this:

window.onscroll = function(e) {
  if (this.oldScroll > this.scrollY) {
     doSomething();
  } else {
     doSomethingElse();
  }
  this.oldScroll = this.scrollY;

  delete window.onscroll;
};

Do NOT rely on any kind of "flag variables" as it is proposed above. It is a very bad practice in this scenario!


问:
How to check non-selectable slots on fullcalendar
I have a different range of available hours for every single day, for example:

monday 4th from 9:00 to 14:00

monday 4th from 16:00 to 18:00

thursday 5th from 9:30 to 15:00

wednesday 6th from 10:00 to 12:00

wednesday 6th from 16:00 to 18:00

...

monday 11th from 12:00 to 14:00

monday 11th from 15:00 to 17:30

...

These ranges can change from a day to another. They're stored on a database and I render them on the calendar using the "rendering: background" property.

The user can only create events on these ranges. When the user clicks inside a "rendering: background" range they can see a modal window that prompts the user for creating a new event.

My problem is: when I click on the calendar outside a "rendering: background" slot -let's say on monday 4th at 14:30h- the modal window is shown. How can I avoid this? When the user clicks outside a non-permitted slot I want they to show an error message, not the modal window.

This is my code:

```<code>$('#calendar').fullCalendar({
        // put your options and callbacks here
        height: 1055,
        //aspectRatio: 0.5,
        allDaySlot: false,
        slotEventOverlap: false,
        header: {
            left: '',
            center: '',
            right: ''
        },
        columnHeader: false,
        columnFormat: 'Class type',
        defaultView: 'agendaDay',
        weekends: false,
        selectable: true,
        eventRender: my_render_function,
        },
        select: function (start, end, jsEvent) {  // click on empty time slot
        // code to show my modal for creating a new event
        ...
        ...
        $('#myModal').modal('show');
        },
        selectOverlap: function (event) {
            // Here you will get all background events which are on same time.
            return event.rendering === 'background';
        },
        businessHours: {
            // days of week. an array of zero-based day of week integers (0=Sunday)
            dow: [1, 2, 3, 4, 5], // Monday - Thursday
            start: '09:00', // a start time (10am in this example)
            end: '18:00', // an end time (6pm in this example)
        },
        minTime: '09:00:00',
        maxTime: '18:00:00',
        eventSources: [
            {
                url: '/agenda/my_existent_events'
                }
            },
            {
                url: '/agenda/mybackground_events_with_colors'
            }
        ],
    })
</code>```

I've tested this solution but it doesn't work for me:
Detect click on background event
Any suggestion will be welcome. Thanks in advance!

答:
You can use SelectAllow option.

It Provides you with Exact programmatic control over where the user can select.

```<code>function(selectInfo)
</code>```

This callback will be called for every new potential selection as the user is dragging.

The callback function will receive information about where the user is attempting to select (selectInfo) and must return either true or false.

The selectInfo object will have the following properties:

start (a Moment)

end exclusive end date/time (a Moment)

resourceId if you are using a Resource View

Additionally, you can look into the options available related to select here

Hope that helps you out

Body:
I have a different range of available hours for every single day, for example:

monday 4th from 9:00 to 14:00

monday 4th from 16:00 to 18:00

thursday 5th from 9:30 to 15:00

wednesday 6th from 10:00 to 12:00

wednesday 6th from 16:00 to 18:00

...

monday 11th from 12:00 to 14:00

monday 11th from 15:00 to 17:30

...

These ranges can change from a day to another. They're stored on a database and I render them on the calendar using the "rendering: background" property.

The user can only create events on these ranges. When the user clicks inside a "rendering: background" range they can see a modal window that prompts the user for creating a new event.

My problem is: when I click on the calendar outside a "rendering: background" slot -let's say on monday 4th at 14:30h- the modal window is shown. How can I avoid this? When the user clicks outside a non-permitted slot I want they to show an error message, not the modal window.

This is my code:

$('#calendar').fullCalendar({
        // put your options and callbacks here
        height: 1055,
        //aspectRatio: 0.5,
        allDaySlot: false,
        slotEventOverlap: false,
        header: {
            left: '',
            center: '',
            right: ''
        },
        columnHeader: false,
        columnFormat: 'Class type',
        defaultView: 'agendaDay',
        weekends: false,
        selectable: true,
        eventRender: my_render_function,
        },
        select: function (start, end, jsEvent) {  // click on empty time slot
        // code to show my modal for creating a new event
        ...
        ...
        $('#myModal').modal('show');
        },
        selectOverlap: function (event) {
            // Here you will get all background events which are on same time.
            return event.rendering === 'background';
        },
        businessHours: {
            // days of week. an array of zero-based day of week integers (0=Sunday)
            dow: [1, 2, 3, 4, 5], // Monday - Thursday
            start: '09:00', // a start time (10am in this example)
            end: '18:00', // an end time (6pm in this example)
        },
        minTime: '09:00:00',
        maxTime: '18:00:00',
        eventSources: [
            {
                url: '/agenda/my_existent_events'
                }
            },
            {
                url: '/agenda/mybackground_events_with_colors'
            }
        ],
    })

I've tested this solution but it doesn't work for me:
Detect click on background event
Any suggestion will be welcome. Thanks in advance!

Body:
You can use SelectAllow option.

It Provides you with Exact programmatic control over where the user can select.

function(selectInfo)

This callback will be called for every new potential selection as the user is dragging.

The callback function will receive information about where the user is attempting to select (selectInfo) and must return either true or false.

The selectInfo object will have the following properties:

start (a Moment)

end exclusive end date/time (a Moment)

resourceId if you are using a Resource View

Additionally, you can look into the options available related to select here

Hope that helps you out


问:
Javascript: lexical scoping issue using new keyword constructor
i have problem about scoping in javascipt. I tried to create new object using the "new" keyword without any problem. The code looks like this

```<code>"use strict";

 function Person() {
     this.name = "john doe";
     console.log(this.name);
 }

 Var foo = new Person()
</code>```

The problem i encountered is when i try to add inner function the scope of the name variable becomes undefined inside the inner function

```<code> "use strict";

 function Person() {
         this.name = "john doe";

         Function speak() {
                   console.log("my name is" + this.name);
         }

         speak();
  }

  var foo = new Person();

 //error: "cannot read property 'name' of undefined"
</code>```

Can somebody explained what seems to be the problem? Thank guys

答:
You can also give speak the same scope as this. It should be noted that this will also make it a public function, so speak can be called from outside of the Person class.

function Person() {
    this.name = "john doe";

    this.speak = function() {
        console.log("my name is " + this.name);
    };

    this.speak();
}

var foo = new Person();```

Body:
i have problem about scoping in javascipt. I tried to create new object using the "new" keyword without any problem. The code looks like this

"use strict";

 function Person() {
     this.name = "john doe";
     console.log(this.name);
 }

 Var foo = new Person()

The problem i encountered is when i try to add inner function the scope of the name variable becomes undefined inside the inner function

 "use strict";

 function Person() {
         this.name = "john doe";

         Function speak() {
                   console.log("my name is" + this.name);
         }

         speak();
  }

  var foo = new Person();

 //error: "cannot read property 'name' of undefined"

Can somebody explained what seems to be the problem? Thank guys


问:
Color Gradient on datapoints based on rows in gnuplot
I Have a dataset with a whole bunch of rows corresponding to points (x,y) on the plane. I want to plot this collection of points with a gradient so the first point in the list is blue, and as it plots more and more points from the list it shifts to red.

Is there any way to do this in gnuplot? Any advice would be appreciated.

答:
You can use the linecolor palette z option to do this. For example, if you have a datafile test.dat that looks like

```<code>1   1
2   2
3   3
4   4
</code>```

then you can do

```<code>unset key
set palette defined ( 0 "blue", 1 "red" )
plot "test.dat" u 1:2:0 w p pt 7 ps 3 lc palette z
</code>```

Body:
You can use the linecolor palette z option to do this. For example, if you have a datafile test.dat that looks like

1   1
2   2
3   3
4   4

then you can do

unset key
set palette defined ( 0 "blue", 1 "red" )
plot "test.dat" u 1:2:0 w p pt 7 ps 3 lc palette z


问:
How do I iterate over a slice of nested list?
I have this nested list:

```<code>nested = [[1, 1, 1], [2, 2, 2], [3, 3, 3]]
</code>```

I wanted to subtract 1 from the first 2 elements of the inner list so I tried it with list comprehension:

```<code>nested = [[x - 1 for x in stack[0:2]] for stack in nested]
</code>```

It did give me back the first 2 elements subtracted by 1 for the inner lists but it removed the last element completely

```<code>nested = [[0, 0], [1, 1], [2, 2]]
</code>```

I thought that by slicing the list, it will not affect the other element. However in this case it didn't work. Can someone explain this to me?

答:
Another option is to use numpy which does this sort of slicing naturally

```<code>import numpy as np
nested = np.array([[1, 1, 1], [2, 2, 2], [3, 3, 3]])

nested[:,:2] -= 1
</code>```

returns

```<code>array([[0, 0, 1],
       [1, 1, 2],
       [2, 2, 3]])
</code>```

Body:
I have this nested list:

nested = [[1, 1, 1], [2, 2, 2], [3, 3, 3]]

I wanted to subtract 1 from the first 2 elements of the inner list so I tried it with list comprehension:

nested = [[x - 1 for x in stack[0:2]] for stack in nested]

It did give me back the first 2 elements subtracted by 1 for the inner lists but it removed the last element completely

nested = [[0, 0], [1, 1], [2, 2]]

I thought that by slicing the list, it will not affect the other element. However in this case it didn't work. Can someone explain this to me?

Body:
Another option is to use numpy which does this sort of slicing naturally

import numpy as np
nested = np.array([[1, 1, 1], [2, 2, 2], [3, 3, 3]])

nested[:,:2] -= 1

returns

array([[0, 0, 1],
       [1, 1, 2],
       [2, 2, 3]])


问:
Why can you still modify a List<> when it has the "in" parameter modifier in C# 7.2
Earlier this week, C# 7.2 was released with the new feature of "in" parameter modifier see release notes here

The details provided in the release notes are:"The in modifier on parameters, to specify that an argument is passed by reference but not modified by the called method."

There is not a lot of documentation out on this new feature yet, so I have been trying it out. Seems to work as expected for primitive types, and prevents access to object properties. However, for lists you can still call the methods to modify a List (i.e. Add, Remove, Reverse) and you can actually modify an element directly.

```<code>    static void Main(string[] args)
    {
        var test = new List<int>();
        test.Add(5);
        Console.WriteLine(test[0]);
        TestMethod(test);
        Console.WriteLine(test[0]);
    }

    public static void TestMethod(in List<int> myList)
    {
        myList[0] = 10;
        myList.Add(7);
        myList.Remove(2);
    }
</code>```

My question is, why can still modify collections when using the "in" parameter modifier?

答:
The in modifier only restricts assigning to the reference, but the List<T> is still accessible and mutable. Basically it works like ref readonly.

You can't do myList = new List<int>.

Body:
Earlier this week, C# 7.2 was released with the new feature of "in" parameter modifier see release notes here

The details provided in the release notes are:"The in modifier on parameters, to specify that an argument is passed by reference but not modified by the called method."

There is not a lot of documentation out on this new feature yet, so I have been trying it out. Seems to work as expected for primitive types, and prevents access to object properties. However, for lists you can still call the methods to modify a List (i.e. Add, Remove, Reverse) and you can actually modify an element directly.

    static void Main(string[] args)
    {
        var test = new List<int>();
        test.Add(5);
        Console.WriteLine(test[0]);
        TestMethod(test);
        Console.WriteLine(test[0]);
    }

    public static void TestMethod(in List<int> myList)
    {
        myList[0] = 10;
        myList.Add(7);
        myList.Remove(2);
    }

My question is, why can still modify collections when using the "in" parameter modifier?


问:
Visual Studio 2010 default zoom level
Is there a way to set the default zoom level in Visual Studio 2010?  The problem is that I find font size 10 to be too small, but font size 11 is too big.  It just so happens that 90% zoom level with font size 11 gives the perfect size I am looking for.  I would like to be able to have VS automatically always zoom the editor to 90%.</p>

答:
The VSCommands Lite extension appears to do this, judging by this blog post.

I don't think there's any way to do this other than using/writing an extension; macros don't appear to have access to the zoom controls.

If you wanted to write your own custom extension to do this you'd probably be looking at using the IWpfTextView interface.

Another good option is Presentation Zoom.

ContentLicense: CC BY-SA 2.5

Title: Visual Studio 2010 default zoom level


答:
B().b is not an instance variable of B; rather, it is an instance variable of A. In your constructor in B, you may have meant self.a to be an instance of B or self.a to be an instance of B. If this is your general idea, you can implement a boolean overloading method to destinguish between the two. In the case of your code, it may be best to create a third class, C, to check what class an attribute that is passed to doSomething belongs to:

```<code>class A():
   def __init__(self):
     self.a = 1
   def __bool__(self):
        return True

class B():
   def __init__(self):
     self.b = 1
   def __bool__(self):
     return False

class C():
   def __init__(self):
       self.a = A()
       self.b = B()
   def doSomething(self, hello):
       if not hello:
           print("instance of a got passed")
       else:
          print("instance of b got passed")

C().doSomething(C().b)
</code>```

Output:

```<code>instance of b got passed
</code>```

Title: Get variable name from argument/parameter in class function

Body:
I try to get the name of the variable, which I passed to a function.

class A():
  def __init__(self):
    self.a = 1

class B():
  def __init__(self):
    self.b = A()
    self.c = A()

  def doSomething(self, hello):
    print(hello)

B().doSomething(B().b)
<__main__.A object at 0x7f67571a3d68>

What I want is that I can identify in the function B().doSomething(), that the variable is b. Is this possible? One restriction is that in the function B().doSomething() only instance variables of B are passed.

For example in peewee (https://github.com/coleifer/peewee), a MySQL ORM in python, they build expressions for filtering like:

B.select().where(B.b == True)

And somehow they are able to identify, that b is passed. Because otherwise the query can not be build properly.

I know they are using static variables in the class, is this maybe the trick?

Thanks for helping! :)

Body:
B().b is not an instance variable of B; rather, it is an instance variable of A. In your constructor in B, you may have meant self.a to be an instance of B or self.a to be an instance of B. If this is your general idea, you can implement a boolean overloading method to destinguish between the two. In the case of your code, it may be best to create a third class, C, to check what class an attribute that is passed to doSomething belongs to:

class A():
   def __init__(self):
     self.a = 1
   def __bool__(self):
        return True

class B():
   def __init__(self):
     self.b = 1
   def __bool__(self):
     return False

class C():
   def __init__(self):
       self.a = A()
       self.b = B()
   def doSomething(self, hello):
       if not hello:
           print("instance of a got passed")
       else:
          print("instance of b got passed")

C().doSomething(C().b)

Output:

instance of b got passed


问:
Apache can't access Python's module 'numpy' - linux
I run apache2 on Ubuntu 17.10. Inside a php file there is:

```<code><?php
exec("python3 test_python.py 2>&1",$res);
for ($i=0; $i < sizeof($res); $i++) {
  echo $res[$i] . '<br>';
}
?>
</code>```

and inside test_python.py there is:

```<code>import numpy as np
print("it works from here.");
</code>```

Unfortunately, the result i get is:

Traceback (most recent call last):
File "test_python.py", line 1, in
import numpy as np
ModuleNotFoundError: No module named 'numpy'

When i run the script my self through terminal like:

```<code>python3 test_python.py
</code>```

it works fine. I suspect there's a problem with permissions but I haven't found a solution yet.

答:
This looks like a PATH/PYTHONPATH issue. The python3 you are running from your interactive shell might not be the same as the one Apache/PHP runs; and/or the sys.path might differ in both cases, so numpy is found in one case, but not the other.

The safest and the most robust way for running your Python script with dependencies, is to create a virtual environment with virtualenv, activate it, install your deps there:

```<code>cd /path/to/project             # go to your project dir
virtualenv -p python3 env       # create python3-based virtual environment
. env/bin/activate              # activate the virtual environment in env/
pip install numpy               # install all dependencies
deactivate                      # deactivate env
</code>```

and then simply run your Python script from PHP by invoking python from the virtual environment just created (env/bin/python):

```<code><?php
exec("/path/to/project/env/bin/python test_python.py 2>&1", $res);
...
</code>```

All packages installed inside the virtual environment will now be available in test_python.py.

To add other packages, just activate your virtual env again, and pip install there.

Body:
I run apache2 on Ubuntu 17.10. Inside a php file there is:

<?php
exec("python3 test_python.py 2>&1",$res);
for ($i=0; $i < sizeof($res); $i++) {
  echo $res[$i] . '
';
}
?>

and inside test_python.py there is:

import numpy as np
print("it works from here.");

Unfortunately, the result i get is:

Traceback (most recent call last):
File "test_python.py", line 1, in
import numpy as np
ModuleNotFoundError: No module named 'numpy'

When i run the script my self through terminal like:

python3 test_python.py

it works fine. I suspect there's a problem with permissions but I haven't found a solution yet.

Body:
This looks like a PATH/PYTHONPATH issue. The python3 you are running from your interactive shell might not be the same as the one Apache/PHP runs; and/or the sys.path might differ in both cases, so numpy is found in one case, but not the other.

The safest and the most robust way for running your Python script with dependencies, is to create a virtual environment with virtualenv, activate it, install your deps there:

cd /path/to/project             # go to your project dir
virtualenv -p python3 env       # create python3-based virtual environment
. env/bin/activate              # activate the virtual environment in env/
pip install numpy               # install all dependencies
deactivate                      # deactivate env

and then simply run your Python script from PHP by invoking python from the virtual environment just created (env/bin/python):

<?php
exec("/path/to/project/env/bin/python test_python.py 2>&1", $res);
...

All packages installed inside the virtual environment will now be available in test_python.py.

To add other packages, just activate your virtual env again, and pip install there.


问:
BigQuery - Datetime vs Timestamp
I looked on the documentation for google big query data types, checking the differences between TimeStamp to Datetime data types.

As I understand the main difference is:

Unlike Timestamps, a DATETIME object does not refer to an absolute instance in time. Instead, it is the civil time, or the time that a user would see on a watch or calendar.

So when should I use Timestamp/Datetime?

Thanks

答:
In most cases you will want to use the timestamp data type. It refers to an absolute point in time. BigQuery interprets any timezone information and represents the time internally as a UTC timestamp.

Very rarely would you use a datetime data type, which is a date and a time but no time zone. The example I like to give is that you'd use a datetime to represent pi day, 2017, since it occurs at 2017-03-14 15:09:26.535898 in each time zone separately.

Title: BigQuery - Datetime vs Timestamp


Title: How do I iterate over a slice of nested list?

Body:
You can use enumerate:

nested = [[1, 1, 1], [2, 2, 2], [3, 3, 3]]
new_nested = [[a-1 if i == 0 or i == 1 else a for i, a in enumerate(b)] for b in nested]

Output:

[[0, 0, 1], [1, 1, 2], [2, 2, 3]]

Edit: alternative, with map:

nested = [[1, 1, 1], [2, 2, 2], [3, 3, 3]]
new_nested = [map(lambda x:x-1, i[:2])+[i[-1]] for i in nested]

Output:

[[0, 0, 1], [1, 1, 2], [2, 2, 3]]


问:
Python Pandas Get a Cumulative Sum (cumsum) which excludes the current row
I am trying to get a cumulative count of a given column that excludes the current row in the dataframe.

My code is shown below. The problem with using cumsum() only is that it includes the current row in the count.

I want df['ExAnte Good Year Count'] to calculate cumsum on an ExAnte basis - ie. excluding the current row from the count.

```<code>d = {
      'Year':[2000, 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008],
      'Good Year':[1, 0, 1, 0, 0, 1, 1, 1, 0]
      'Year Type':['X', 'Y', 'Z', 'Z', 'Z', 'X', 'Y', 'Z', 'Z']
    }

df = pd.DataFrame(d, columns=['Year','Good Year'])
df['ExAnte Good Year Count'] = df['Good Year'].cumsum()
</code>```

UPDATED QUERY:
I would also like to count the cumsum of 'Good Years', grouped by Year Type. I have tried...

```<code>'df['Good Year'].groupby(['Year Type']).shift().cumsum()'
</code>```

...but I get an error which says 'KeyError:'Year Type'

答:
```<code>df['Yourcol']=df.groupby('Year Type',sort=False)['Good Year'].apply(lambda x : x.shift().cumsum())
df
Out[283]:
   Good Year  Year Year Type  Yourcol
0          1  2000         X      NaN
1          0  2001         Y      NaN
2          1  2002         Z      NaN
3          0  2003         Z      1.0
4          0  2004         Z      1.0
5          1  2005         X      1.0
6          1  2006         Y      0.0
7          1  2007         Z      1.0
8          0  2008         Z      2.0
</code>```

Body:
I am trying to get a cumulative count of a given column that excludes the current row in the dataframe.

My code is shown below. The problem with using cumsum() only is that it includes the current row in the count.

I want df['ExAnte Good Year Count'] to calculate cumsum on an ExAnte basis - ie. excluding the current row from the count.

d = {
      'Year':[2000, 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008],
      'Good Year':[1, 0, 1, 0, 0, 1, 1, 1, 0]
      'Year Type':['X', 'Y', 'Z', 'Z', 'Z', 'X', 'Y', 'Z', 'Z']
    }

df = pd.DataFrame(d, columns=['Year','Good Year'])
df['ExAnte Good Year Count'] = df['Good Year'].cumsum()

UPDATED QUERY:
I would also like to count the cumsum of 'Good Years', grouped by Year Type. I have tried...

'df['Good Year'].groupby(['Year Type']).shift().cumsum()'

...but I get an error which says 'KeyError:'Year Type'


问:
preg replace everything BUT digits over 5 in length
I have a string:

3 pk. Ready-Dough White Loaves Included $3.99 - 47500 - 00892, 48101

I want to keep only groups of digits longer than 5 characters, and if possible, any dashes or commas between them.

e.g.

47500-00892,48101

My first step was to strip out groups of digits < 4:

preg_replace('/\d{1,4}/', '', $string);

My thinking was "replace any block of digits from 1 to 4 with nothing", but that doesn't do exactly what I thought. Maybe I'm just missing an operator?

Then I was going to strip out all letters and all punctuation except , and -. In my example I would've been left with a starting - because of it being in a string, but a trim() would've been fine to clean that up.

Any help is appreciated!

答:
Since there's no reason to perform a replacement, you can use preg_match_all to take what you want and reduce the result array:

```<code>$re = '/\d{5,}(?:(?=\s*([-,])\s*\d{5}))?/';
$str = '3 pk. Ready-Dough White Loaves Included $3.99 - 47500 - 00892, 48101';

if ( preg_match_all($re, $str, $matches, PREG_SET_ORDER) ) {
    $result = array_reduce($matches, function ($c,$i) { return $c . implode('', $i); });
    echo $result;
}
</code>```

Body:
Since there's no reason to perform a replacement, you can use preg_match_all to take what you want and reduce the result array:

$re = '/\d{5,}(?:(?=\s*([-,])\s*\d{5}))?/';
$str = '3 pk. Ready-Dough White Loaves Included $3.99 - 47500 - 00892, 48101';

if ( preg_match_all($re, $str, $matches, PREG_SET_ORDER) ) {
    $result = array_reduce($matches, function ($c,$i) { return $c . implode('', $i); });
    echo $result;
}


问:
Java - Query does not return results

java.sql.SQLException: Query does not return results

This is the error I get when running my code.

I am making a tic-tac-toe game to run off of a database. I'm making an empty board with this code.

Any ideas of why the database is not being updated??

```<code>//INSERT SPACE
    String space1 = "INSERT INTO space(row,column,contents) VALUES (?,?,?)";
    String space2 = "INSERT INTO space(row,column,contents) VALUES (?,?,?)";
    String space3 = "INSERT INTO space(row,column,contents) VALUES (?,?,?)";
    String space4 = "INSERT INTO space(row,column,contents) VALUES (?,?,?)";
    String space5 = "INSERT INTO space(row,column,contents) VALUES (?,?,?)";
    String space6 = "INSERT INTO space(row,column,contents) VALUES (?,?,?)";
    String space7 = "INSERT INTO space(row,column,contents) VALUES (?,?,?)";
    String space8 = "INSERT INTO space(row,column,contents) VALUES (?,?,?)";
    String space9 = "INSERT INTO space(row,column,contents) VALUES (?,?,?)";

    /**
     *  Inserts empty space into space 1
     */
    try {
        PreparedStatement preparedStatement = connectDatabase.getConnection().prepareStatement(space1);
        preparedStatement.setInt(1,0);
        preparedStatement.setInt(2,0);
        preparedStatement.setString(3, "e");

        ResultSet resultSet = preparedStatement.executeQuery();

        resultSet.close();

    } catch (SQLException e) {
        e.printStackTrace();
    }
</code>```

答:
```<code>ResultSet resultSet = preparedStatement.executeUpdate();
                                               ^^^^^^
</code>```

ExecuteUpdate is the method to use for non-results-returning DML.

Title: Java - Query does not return results

Body:
java.sql.SQLException: Query does not return results

This is the error I get when running my code.

I am making a tic-tac-toe game to run off of a database. I'm making an empty board with this code.

Any ideas of why the database is not being updated??

//INSERT SPACE
    String space1 = "INSERT INTO space(row,column,contents) VALUES (?,?,?)";
    String space2 = "INSERT INTO space(row,column,contents) VALUES (?,?,?)";
    String space3 = "INSERT INTO space(row,column,contents) VALUES (?,?,?)";
    String space4 = "INSERT INTO space(row,column,contents) VALUES (?,?,?)";
    String space5 = "INSERT INTO space(row,column,contents) VALUES (?,?,?)";
    String space6 = "INSERT INTO space(row,column,contents) VALUES (?,?,?)";
    String space7 = "INSERT INTO space(row,column,contents) VALUES (?,?,?)";
    String space8 = "INSERT INTO space(row,column,contents) VALUES (?,?,?)";
    String space9 = "INSERT INTO space(row,column,contents) VALUES (?,?,?)";

    /**
     *  Inserts empty space into space 1
     */
    try {
        PreparedStatement preparedStatement = connectDatabase.getConnection().prepareStatement(space1);
        preparedStatement.setInt(1,0);
        preparedStatement.setInt(2,0);
        preparedStatement.setString(3, "e");

        ResultSet resultSet = preparedStatement.executeQuery();

        resultSet.close();

    } catch (SQLException e) {
        e.printStackTrace();
    }

Body:
ResultSet resultSet = preparedStatement.executeUpdate();
                                               ^^^^^^

ExecuteUpdate is the method to use for non-results-returning DML.


问:
Where in a HATEOAS architecture do you specify the HTTP verbs?
I was reading an article on HATEOAS and while I understand the idea of providing the URLs for further actions in the response, I don't see where you specify what HTTP verbs should usedto interact with those URLs.

For example, from What is HATEOAS and why is it important for my REST API?, how from this response

```<code>GET /account/12345 HTTP/1.1

HTTP/1.1 200 OK
<?xml version="1.0"?>
<account>
    <account_number>12345</account_number>
    <balance currency="usd">100.00</balance>
    <link rel="deposit" href="/account/12345/deposit" />
    <link rel="withdraw" href="/account/12345/withdraw" />
    <link rel="transfer" href="/account/12345/transfer" />
    <link rel="close" href="/account/12345/close" />
</account
</code>```

do you know if I should issue an HTTP PUT or POST to /account/12345/close?

答:
Your question has a lot of answers on Stackoverlow, but most of them skirt the reason you are asking, and I suspect you always find them partially disatisfying.

If we take Roy Fielding at his word, it is impossible to write most commercial interactive Client-apps as SOA RESTful/HATEOAS using HTTP/HTML. It might be possible in other mediums, I can't say.

So the practical answer is "look it up in the documentation" and "write your Client with that app-knowledge in it" with a side-helping of "ignore the fact that we're breaking Fielding's rules by doing that".

I tend to design JSON responses that provide this approach:

```<code>GET /account/12345 HTTP/1.1
{
    "account": {
        "number": "12345",
        "currency": "usd",
        "balance": "100.00",
        "deposit": {
            "href": "/account/12345/deposit",
            "action": "POST"
        },
        "withdraw": {
            "href": "/account/12345/withdraw",
            "action": "POST"
        },
        "transfer": {
            "href": "/account/12345/transfer",
            "action": "POST"
        },
        "close": {
            "href": "/account/12345/close",
            "action": "DELETE"
        }
    }
}
</code>```

... adding additional properties to the design as needed, but these are the basics.

I believe this allows the consuming Client(s) to be written in a RESTful way, but in so doing I am using the Response Body, which Fielding says is not what he intended.

I'd offer this explanation seperate to the answer though:

Fielding says "I am getting frustrated by the number of people calling any HTTP-based interface a REST API." (http://roy.gbiv.com/untangled/2008/rest-apis-must-be-hypertext-driven).

Note how he so stridently says "any" HTTP-based interface.

The most relevant segment in his 'lecture' is this:

"A REST API should be entered with no prior knowledge beyond the initial URI (bookmark) and set of standardized media types that are appropriate for the intended audience (i.e., expected to be understood by any client that might use the API). From that point on, all application state transitions must be driven by client selection of server-provided choices that are present in the received representations or implied by the user’s manipulation of those representations. The transitions may be determined (or limited by) the client’s knowledge of media types and resource communication mechanisms, both of which may be improved on-the-fly (e.g., code-on-demand). [Failure here implies that out-of-band information is driving interaction instead of hypertext.]"

He says this because an HTTP/HTML app URI media-type is just "text/html", and where is the Verb in that? There isn't one. A URI cannot tell you what Verb something requires for use/navigation, ergo you cannot use just the in-band data alone to construct the 'next' navigation dynamically in your Client.

He explained that he believes we render our URI's as part of CDATA that includes the "method" or that the context of the URI would self-evidently provide it, like the FORM element does. He explicitly rails against the OpenSocialst REST API stating that it is not RESTful.

Here: “anchor elements with an href attribute create a hypertext link that, when selected, invokes a retrieval request (GET) on the URI corresponding to the CDATA-encoded href attribute.” Identifiers, methods, and media types are orthogonal concerns — methods are not given meaning by the media type. Instead, the media type tells the client either what method to use (e.g., anchor implies GET) or how to determine the method to use (e.g., form element says to look in method attribute). The client should already know what the methods mean (they are universal) and how to dereference a URI.

Note that he says the Client should already know what the methods mean, he does not say that the Client should already know what they are - which is why you asked your question. A lot of people struggle with this, because we don't in fact build our apps like this in most SOA environments.

Like a lot of engineers, I just wish Fielding would come out with a clarification or re-statement, but not only has he not done so, he has published two further admonishments to us as engineers, doubling-down on his statement, saying that we should stop calling our API's RESTful and accept that we're building RPC's.

I think the JSON elements-like approach is a reasoble bridge, but I have no answer to the fact that we're using the Request Body to do it, not relying on the Media Type to imply it.

Finally, there is a newer Verb in HTTP called OPTIONS which, for a given URI, would return the allowed Verb actions list. I think Fielding had a hand in writing this HTTP revision. That would allow a Client to generically construct URI navigations without the forbidden internal app knowledge. But that has three issues I can think of in the practical world:

You would have to code a mechanism into your Service Aggregation to make that call for every URI you try to return, and since much data contains many URI's (_links in HAL) that adds a lot of extra 'hops' into your Service Response construction. We'd probably all complain about that.

Virtually no SOA site claiming to be RESTful actually implements an OPTIONS verb-method-call for you to do this enquiry with anyway.

We would all complain about the 'unecessary' extra calls it adds (especially in the eCommerce world) to a Client's processing and its tendency to push us beyond SLA requirements.

Body:
I was reading an article on HATEOAS and while I understand the idea of providing the URLs for further actions in the response, I don't see where you specify what HTTP verbs should usedto interact with those URLs.

For example, from What is HATEOAS and why is it important for my REST API?, how from this response

GET /account/12345 HTTP/1.1

HTTP/1.1 200 OK
<?xml version="1.0"?>
<account>
    <account_number>12345</account_number>
    <balance currency="usd">100.00</balance>
    <link rel="deposit" href="/account/12345/deposit" />
    <link rel="withdraw" href="/account/12345/withdraw" />
    <link rel="transfer" href="/account/12345/transfer" />
    <link rel="close" href="/account/12345/close" />
</account

do you know if I should issue an HTTP PUT or POST to /account/12345/close?

Body:
Your question has a lot of answers on Stackoverlow, but most of them skirt the reason you are asking, and I suspect you always find them partially disatisfying.

If we take Roy Fielding at his word, it is impossible to write most commercial interactive Client-apps as SOA RESTful/HATEOAS using HTTP/HTML. It might be possible in other mediums, I can't say.

So the practical answer is "look it up in the documentation" and "write your Client with that app-knowledge in it" with a side-helping of "ignore the fact that we're breaking Fielding's rules by doing that".

I tend to design JSON responses that provide this approach:

GET /account/12345 HTTP/1.1
{
    "account": {
        "number": "12345",
        "currency": "usd",
        "balance": "100.00",
        "deposit": {
            "href": "/account/12345/deposit",
            "action": "POST"
        },
        "withdraw": {
            "href": "/account/12345/withdraw",
            "action": "POST"
        },
        "transfer": {
            "href": "/account/12345/transfer",
            "action": "POST"
        },
        "close": {
            "href": "/account/12345/close",
            "action": "DELETE"
        }
    }
}

... adding additional properties to the design as needed, but these are the basics.

I believe this allows the consuming Client(s) to be written in a RESTful way, but in so doing I am using the Response Body, which Fielding says is not what he intended.

I'd offer this explanation seperate to the answer though:

Fielding says "I am getting frustrated by the number of people calling any HTTP-based interface a REST API." (http://roy.gbiv.com/untangled/2008/rest-apis-must-be-hypertext-driven).

Note how he so stridently says "any" HTTP-based interface.

The most relevant segment in his 'lecture' is this:

"A REST API should be entered with no prior knowledge beyond the initial URI (bookmark) and set of standardized media types that are appropriate for the intended audience (i.e., expected to be understood by any client that might use the API). From that point on, all application state transitions must be driven by client selection of server-provided choices that are present in the received representations or implied by the user’s manipulation of those representations. The transitions may be determined (or limited by) the client’s knowledge of media types and resource communication mechanisms, both of which may be improved on-the-fly (e.g., code-on-demand). [Failure here implies that out-of-band information is driving interaction instead of hypertext.]"

He says this because an HTTP/HTML app URI media-type is just "text/html", and where is the Verb in that? There isn't one. A URI cannot tell you what Verb something requires for use/navigation, ergo you cannot use just the in-band data alone to construct the 'next' navigation dynamically in your Client.

He explained that he believes we render our URI's as part of CDATA that includes the "method" or that the context of the URI would self-evidently provide it, like the FORM element does. He explicitly rails against the OpenSocialst REST API stating that it is not RESTful.

Here: “anchor elements with an href attribute create a hypertext link that, when selected, invokes a retrieval request (GET) on the URI corresponding to the CDATA-encoded href attribute.” Identifiers, methods, and media types are orthogonal concerns — methods are not given meaning by the media type. Instead, the media type tells the client either what method to use (e.g., anchor implies GET) or how to determine the method to use (e.g., form element says to look in method attribute). The client should already know what the methods mean (they are universal) and how to dereference a URI.

Note that he says the Client should already know what the methods mean, he does not say that the Client should already know what they are - which is why you asked your question. A lot of people struggle with this, because we don't in fact build our apps like this in most SOA environments.

Like a lot of engineers, I just wish Fielding would come out with a clarification or re-statement, but not only has he not done so, he has published two further admonishments to us as engineers, doubling-down on his statement, saying that we should stop calling our API's RESTful and accept that we're building RPC's.

I think the JSON elements-like approach is a reasoble bridge, but I have no answer to the fact that we're using the Request Body to do it, not relying on the Media Type to imply it.

Finally, there is a newer Verb in HTTP called OPTIONS which, for a given URI, would return the allowed Verb actions list. I think Fielding had a hand in writing this HTTP revision. That would allow a Client to generically construct URI navigations without the forbidden internal app knowledge. But that has three issues I can think of in the practical world:

You would have to code a mechanism into your Service Aggregation to make that call for every URI you try to return, and since much data contains many URI's (_links in HAL) that adds a lot of extra 'hops' into your Service Response construction. We'd probably all complain about that.

Virtually no SOA site claiming to be RESTful actually implements an OPTIONS verb-method-call for you to do this enquiry with anyway.

We would all complain about the 'unecessary' extra calls it adds (especially in the eCommerce world) to a Client's processing and its tendency to push us beyond SLA requirements.


问:
How to count words in a textarea if the word has a space
I have a text input and a text area.  I want to count the number of times the text input value occurs in the text area.  The following code works fine when the text input value doesn't have any spaces before or after.  But when it has spaces, I'm getting a null even if it occurs in the text area.  For example:

```<code>text input value: "dog"
text area value: "dog"
I get "1" in the console log.
</code>```

However

```<code>text input value: "dog_"
text area value: "dog_"
I get "null" in the console log.
</code>```

How do I get it so if I type  "dog_" in the text input and there is a  "dog_" in the text area, the count will be "1"

```<code>function testCount() {

var textVal = document.getElementById("textInput").value;
var textArea = document.getElementById("textArea").value;
var regex = new RegExp("\\b" + textVal + "\\b",'gi');
var count = textArea.match(regex).length;

console.log(count);

}
</code>```

I've tried various RegExp but they didn't solve the problem.  Thanks.

答:
You are using Regex word boundaries \b in your regex but word boundaries do not include preceding or proceeding trailing spaces.

As stated in this stackoverflow post;

\b is similar to [^a-zA-Z0-9_] i.e \b would check for anything except
  word

This post also shows an alternative to word boundaries for searching including preceding and proceeding trailing spaces.

Try changing

```<code>var regex = new RegExp("\\b" + textVal + "\\b",'gi');
</code>```

to

```<code>var regex = new RegExp("(?<=\s|^)" + textVal + "(?=\s|$)", 'gi');
</code>```

or even

```<code>var regex = new RegExp("(?:^|\s|$)" + textVal + "(?:^|\s|$)", 'gi');
</code>```

The third code snippet is not as strict as the second one, but may be a little more compatible if you have issues with the second snippet.

Here is a working example:

function testCount() {
  var textVal = document.getElementById("textInput").value;
  var textArea = document.getElementById("textArea").value;
  var regex = new RegExp("(?<=\s|^)" + textVal + "(?=\s|$)", 'gi');
  var match = textArea.match(regex);
  var count = match ? match.length : 0;

  console.log(count);
}

document.getElementById('btn').addEventListener("click", testCount);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><input type="text" id="textInput">
<button id="btn">
  Count
</button>
<textarea id="textArea"></textarea></code>```

Body:
I have a text input and a text area.  I want to count the number of times the text input value occurs in the text area.  The following code works fine when the text input value doesn't have any spaces before or after.  But when it has spaces, I'm getting a null even if it occurs in the text area.  For example:

text input value: "dog"
text area value: "dog"
I get "1" in the console log.

However

text input value: "dog_"
text area value: "dog_"
I get "null" in the console log.

How do I get it so if I type  "dog_" in the text input and there is a  "dog_" in the text area, the count will be "1"

function testCount() {

var textVal = document.getElementById("textInput").value;
var textArea = document.getElementById("textArea").value;
var regex = new RegExp("\\b" + textVal + "\\b",'gi');
var count = textArea.match(regex).length;

console.log(count);

}

I've tried various RegExp but they didn't solve the problem.  Thanks.

Body:
You are using Regex word boundaries \b in your regex but word boundaries do not include preceding or proceeding trailing spaces.

As stated in this stackoverflow post;

\b is similar to [^a-zA-Z0-9_] i.e \b would check for anything except
  word

This post also shows an alternative to word boundaries for searching including preceding and proceeding trailing spaces.

Try changing

var regex = new RegExp("\\b" + textVal + "\\b",'gi');

to

var regex = new RegExp("(?<=\s|^)" + textVal + "(?=\s|$)", 'gi');

or even

var regex = new RegExp("(?:^|\s|$)" + textVal + "(?:^|\s|$)", 'gi');

The third code snippet is not as strict as the second one, but may be a little more compatible if you have issues with the second snippet.

Here is a working example:

function testCount() {
  var textVal = document.getElementById("textInput").value;
  var textArea = document.getElementById("textArea").value;
  var regex = new RegExp("(?<=\s|^)" + textVal + "(?=\s|$)", 'gi');
  var match = textArea.match(regex);
  var count = match ? match.length : 0;

  console.log(count);
}

document.getElementById('btn').addEventListener("click", testCount);

<input type="text" id="textInput">
<button id="btn">
  Count
</button>
<textarea id="textArea"></textarea>


答:
You should use preparedStatement.executeUpdate() instead. See the docs here.

The method .executeQuery() is only used for SELECT operations, or in general for any queries that return something. If, instead, you want to modify your database, you must use .executeUpdate() instead.

Title: Java - Query does not return results


问:
Moving from Swing to Web Applications
I am decent (or so I like to think) when it comes to making java swing applications, but I want to make the jump to web applications.

The problem lies with the fact that there's so much going on and so much different terminology being thrown around. I have no idea where to begin and it seems very daunting.

I've read up on a few things such as JSP and GWT, but I still can't seem to be able to make the jump. My question is: is there a specific flow used when making a web application to make everything seem to connect better, and if possible, could you recommend a good starting point for someone like me that comes from a solely desktop gui environment and wants to start developing web apps? Thanks for the help!

答: Both Swing and Web application still rely upon java keywords and terminology. java web technology work better when you use a framework . I suggest you start with Spring. It has MVC library that you can use, plus spring mvc has a large community online. However, Java Servlet is quite similar with what you have learn in java.</p>

Title: Moving from Swing to Web Applications


问:
How would I fix this multi-table query to select only the rows that are needed?
I'm trying to make a query that selects all messages from a specific user and all of that user's friends. This query almost works, but the first part causes issues because it ends up selecting all rows from 'friends.' I'm thinking I need to use some sort of JOIN for this to work as needed, but I don't have enough experience with JOINS to make this work after experimenting for over an hour now.</p>

```<code>SELECT a.*
  FROM messages a, friends b
 WHERE a.username = '$user' OR b.username = '$user' && b.friend = a.username
 ORDER BY a.id DESC
 LIMIT 5
</code>```

答:
Maybe something like this would work:</p>

```<code>   SELECT m.*
     FROM messages m
LEFT JOIN friends f
       ON m.username = f.username
    WHERE m.username = "$user"
       OR f.friend = "$user"
</code>```

Body:
I'm trying to make a query that selects all messages from a specific user and all of that user's friends. This query almost works, but the first part causes issues because it ends up selecting all rows from 'friends.' I'm thinking I need to use some sort of JOIN for this to work as needed, but I don't have enough experience with JOINS to make this work after experimenting for over an hour now.

SELECT a.*
  FROM messages a, friends b
 WHERE a.username = '$user' OR b.username = '$user' && b.friend = a.username
 ORDER BY a.id DESC
 LIMIT 5

Body:
Maybe something like this would work:

   SELECT m.*
     FROM messages m
LEFT JOIN friends f
       ON m.username = f.username
    WHERE m.username = "$user"
       OR f.friend = "$user"


问:
How to set Kerning Character Spacing in WPF RichTextBox?
I cannot find how to set horizontal character spacing in a RichTextBox.

Hello, World!
H e l l o ,  W o r l d !

I can only set vertical Line Height using C#.

```<code>Paragraph p = new Paragraph();
p.LineHeight = 50;

rtb1.Document = new FlowDocument(p);

p.Inlines.Add(new Run("Hello, World!"));
</code>```

And outer margin with XAML.

```<code><RichTextBox x:Name="rtb1"
       HorizontalAlignment="Left"
       Height="600"
       Width="300"
       Margin="188,61,0,0"
       VerticalAlignment="Top">
     <RichTextBox.Resources>
         <Style TargetType="{x:Type Paragraph}">
             <Setter Property="Margin" Value="50"/>
         </Style>
     </RichTextBox.Resources>
 </RichTextBox>
</code>```

答:
The most common options you have are:

Control.FontStretch

Glyphs

but here on SO a user found a nice (although potentially performance intensive) alternative to both (read the accepted answer):

How can I specify letter spacing or kerning, in a WPF TextBox?

Body:
I cannot find how to set horizontal character spacing in a RichTextBox.

Hello, World!
H e l l o ,  W o r l d !

I can only set vertical Line Height using C#.

Paragraph p = new Paragraph();
p.LineHeight = 50;

rtb1.Document = new FlowDocument(p);

p.Inlines.Add(new Run("Hello, World!"));

And outer margin with XAML.

<RichTextBox x:Name="rtb1"
       HorizontalAlignment="Left"
       Height="600"
       Width="300"
       Margin="188,61,0,0"
       VerticalAlignment="Top">
     <RichTextBox.Resources>

     </RichTextBox.Resources>
 </RichTextBox>


问:
Bash ranges of non digit or letters
I played around with bash {..} constructs today. I knew

```<code>{a..z}
</code>```

would generate all letters,

```<code>{0..9}
</code>```

digits etc. (numbers in general obviously), but By mistake I got

```<code>{Z..a}
</code>```

yielding:

```<code>Z [  ] ^ _ ` a
</code>```

The characters in between "Z" (90) and "a" (97) are the ASCII 91-96. The astute reader will notice there is a character missing - "\", 92. I'm guessing because of it's special nature. Is this expected behavior as output? Specifically, I'm guessing the \ is being used to escape the space in front of it after substitution, but @John1024 notes that:

```<code>echo {Z..a}a
</code>```

will complain on missing backticks, while the previous version (no a) does not. How exactly is substitution working? Is there a bug?

Second, I guessed the range operator is cooler than I thought and can do any range of ASCII characters I choose, but {[.._} for example fails. Am I missing something to make this work or is this just a curiosity? Are there any more ranges besides letters/digits I can use? and if not, why not do nothing (fail, echo as is) for 'jumping' from caps to lower?

答:
A special variable obase can be used with bc to print almost any character range(s):

```<code>for n in {91..95}; do printf "\x$(echo "obase=16; $n" | bc)"; done
</code>```

Result:

```<code>[\]^_
</code>```

↳ https://www.gnu.org/software/bc/manual/html_mono/bc.html#TOC6

Title: Bash ranges of non digit or letters

Body:
I played around with bash {..} constructs today. I knew

{a..z}

would generate all letters,

{0..9}

digits etc. (numbers in general obviously), but By mistake I got

{Z..a}

yielding:

Z [  ] ^ _ ` a

The characters in between "Z" (90) and "a" (97) are the ASCII 91-96. The astute reader will notice there is a character missing - "\", 92. I'm guessing because of it's special nature. Is this expected behavior as output? Specifically, I'm guessing the \ is being used to escape the space in front of it after substitution, but @John1024 notes that:

echo {Z..a}a

will complain on missing backticks, while the previous version (no a) does not. How exactly is substitution working? Is there a bug?

Second, I guessed the range operator is cooler than I thought and can do any range of ASCII characters I choose, but {[.._} for example fails. Am I missing something to make this work or is this just a curiosity? Are there any more ranges besides letters/digits I can use? and if not, why not do nothing (fail, echo as is) for 'jumping' from caps to lower?

Body:
A special variable obase can be used with bc to print almost any character range(s):

for n in {91..95}; do printf "\x$(echo "obase=16; $n" | bc)"; done

Result:

[\]^_

↳ https://www.gnu.org/software/bc/manual/html_mono/bc.html#TOC6


问:
how to temporarily disable a package in a project from compiling in Java EE IDE
How can I temporarily disable a package in a project from compiling in Java EE IDE?
The package has some source files that I want to prevent from compiling temporarily.

答:
To disable a class/package in Eclipse:

Right click the class file/package;

Hover over "Build Path";

Then click "Exclude";

Done.

It's about the same to enable a class/package in Eclipse:

Right click the class file/package;

Hover over "Build Path";

Then click "Include";

Done.