text:
Q: Is there a well-known term for the synonym or near-synonym "telescoping" words? This has been rattling around in the back of my mind for many years (way before Stack Exchange came into existence), so it's a relief to finally ask the question.
There are words that can be "contracted" by removing one or more letter(s) (without changing the order of the letters) to form a shorter word with the same meaning, or one very close to it.
The two strongest examples I can think of right now are:
rapscallion -> rascal
and
satiate -> sate
This is a slightly weaker example:
rapine -> rape
Even though "rape" has come, in modern usage, to refer almost exclusively to a sexual crime, it can still be used in a more literary (and purposefully anachronistic) sense to mean "the plunder and pillage of a country or region". In that sense, "rape" can be used in a similar fashion to "rapine"; in any case, the two words are etymologically related to the Latin rapere which is tied to the archaic usage.
Another weaker example:
transliterate -> translate
These words are near-synonyms, but there is a definite difference in their meaning. Still, I guess this pair would qualify, albeit in a looser sense.
I wanted to exclude some relatively trivial examples, such as:
(inflammable -> flammable)
(perambulate -> ambulate)
and so forth. So I've imposed the additional rule (arbitrary though it may seem) that the "stripped" letters must not come from the start or the end of the word, but only from its middle.
Acronyms and portmanteaus are also excluded, as are "slangier" contractions e.g.:
(modulator-demodulator -> modem)
(motor-hotel -> motel)
(certitude or certainty or certificate -> cert)
I guess the long-short forms of the same word would form a linguistic doublet. I've coined the term "telescoping word" to describe the long form that "collapses" into the short form with letter deletion sans anagramming.
My question is: has this phenomenon already been studied? If so, what name have authorities given it? Is there already an existing reference or resource on it? Thanks in advance.
(This is not a duplicate of Is there a term for a word inside another word?, as that is asking about the more general phenomenon of words (not necessarily synonyms) occurring within larger words. In fact, the question specifically mentions "kangaroo word" and states that a broader scope is being sought.)

A: I think kangaroo word is the closest term for this.

A playful term for a word that carries within it a synonym of itself--such as regulate (rule), indolent (idle), and encourage (urge).
It's generally believed that the synonym (called a joey) should be the same part of speech as the kangaroo word and its letters should appear in order.
http://grammar.about.com/od/il/g/kangaroowordterm.htm

There are also twin kangaroos and anti-kangaroo words.

Twin kangaroos are kangaroo words containing two joey words (for example: container features both tin and can). In contrast, an anti-kangaroo word is a word that contains its antonym; for example: covert carries overt, animosity carries amity.
[Wikipedia]


text:
Q: Bootstrap Carousel Example Not Displaying Text Hey guys I am working on messing with some boot strap feature and am having some issues with the carousel element.
I am trying to use this example -> https://getbootstrap.com/docs/4.5/examples/carousel/
and the issue that I am having is that my code has the carousel but the text above the blue button is not showing up...
What my page looks like
Here is my code (just copied the example)
I think the issue must be with my css or bootstrap files

<!DOCTYPE html>

        <meta charset="utf-8">

     <link href="css/bootstrap.css" rel="stylesheet">
     <link href="main.css" rel="stylesheet" type="text/css">
        <link href="css/basic-template.css" rel="stylesheet">

        <link href="#" rel="favicon"/>

        <title>Title - Home</title>

    Carousel
    <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarCollapse" aria-controls="navbarCollapse" aria-expanded="false" aria-label="Toggle navigation">

    </button>

          Home (current)

          Link

          Disabled

      <form class="form-inline mt-2 mt-md-0">
        <input class="form-control mr-sm-2" type="text" placeholder="Search" aria-label="Search">
        <button class="btn btn-outline-success my-2 my-sm-0" type="submit">Search</button>
      </form>

        <svg class="bd-placeholder-img" width="100%" height="100%" xmlns="http://www.w3.org/2000/svg" preserveAspectRatio="xMidYMid slice" focusable="false" role="img"><rect width="100%" height="100%" fill="#777"></rect></svg>

Example headline.

Cras justo odio, dapibus ac facilisis in, egestas eget quam. Donec id elit non mi porta gravida at eget metus. Nullam id dolor id nibh ultricies vehicula ut id elit.

Sign up today

        <svg class="bd-placeholder-img" width="100%" height="100%" xmlns="http://www.w3.org/2000/svg" preserveAspectRatio="xMidYMid slice" focusable="false" role="img"><rect width="100%" height="100%" fill="#777"></rect></svg>

Another example headline.

Cras justo odio, dapibus ac facilisis in, egestas eget quam. Donec id elit non mi porta gravida at eget metus. Nullam id dolor id nibh ultricies vehicula ut id elit.

Learn more

        <svg class="bd-placeholder-img" width="100%" height="100%" xmlns="http://www.w3.org/2000/svg" preserveAspectRatio="xMidYMid slice" focusable="false" role="img"><rect width="100%" height="100%" fill="#777"></rect></svg>

One more for good measure.

Cras justo odio, dapibus ac facilisis in, egestas eget quam. Donec id elit non mi porta gravida at eget metus. Nullam id dolor id nibh ultricies vehicula ut id elit.

Browse gallery

      Previous

      Next

        <svg class="bd-placeholder-img rounded-circle" width="140" height="140" xmlns="http://www.w3.org/2000/svg" preserveAspectRatio="xMidYMid slice" focusable="false" role="img" aria-label="Placeholder: 140x140"><title>Placeholder</title><rect width="100%" height="100%" fill="#777"></rect><text x="50%" y="50%" fill="#777" dy=".3em">140x140</text></svg>

Heading

Donec sed odio dui. Etiam porta sem malesuada magna mollis euismod. Nullam id dolor id nibh ultricies vehicula ut id elit. Morbi leo risus, porta ac consectetur ac, vestibulum at eros. Praesent commodo cursus magna.

View details »

        <svg class="bd-placeholder-img rounded-circle" width="140" height="140" xmlns="http://www.w3.org/2000/svg" preserveAspectRatio="xMidYMid slice" focusable="false" role="img" aria-label="Placeholder: 140x140"><title>Placeholder</title><rect width="100%" height="100%" fill="#777"></rect><text x="50%" y="50%" fill="#777" dy=".3em">140x140</text></svg>

Heading

Duis mollis, est non commodo luctus, nisi erat porttitor ligula, eget lacinia odio sem nec elit. Cras mattis consectetur purus sit amet fermentum. Fusce dapibus, tellus ac cursus commodo, tortor mauris condimentum nibh.

View details »

        <svg class="bd-placeholder-img rounded-circle" width="140" height="140" xmlns="http://www.w3.org/2000/svg" preserveAspectRatio="xMidYMid slice" focusable="false" role="img" aria-label="Placeholder: 140x140"><title>Placeholder</title><rect width="100%" height="100%" fill="#777"></rect><text x="50%" y="50%" fill="#777" dy=".3em">140x140</text></svg>

Heading

Donec sed odio dui. Cras justo odio, dapibus ac facilisis in, egestas eget quam. Vestibulum id ligula porta felis euismod semper. Fusce dapibus, tellus ac cursus commodo, tortor mauris condimentum nibh, ut fermentum massa justo sit amet risus.

View details »

First featurette heading. It'll blow your mind.

Donec ullamcorper nulla non metus auctor fringilla. Vestibulum id ligula porta felis euismod semper. Praesent commodo cursus magna, vel scelerisque nisl consectetur. Fusce dapibus, tellus ac cursus commodo.

        <svg class="bd-placeholder-img bd-placeholder-img-lg featurette-image img-fluid mx-auto" width="500" height="500" xmlns="http://www.w3.org/2000/svg" preserveAspectRatio="xMidYMid slice" focusable="false" role="img" aria-label="Placeholder: 500x500"><title>Placeholder</title><rect width="100%" height="100%" fill="#eee"></rect><text x="50%" y="50%" fill="#aaa" dy=".3em">500x500</text></svg>

Oh yeah, it's that good. See for yourself.

Donec ullamcorper nulla non metus auctor fringilla. Vestibulum id ligula porta felis euismod semper. Praesent commodo cursus magna, vel scelerisque nisl consectetur. Fusce dapibus, tellus ac cursus commodo.

        <svg class="bd-placeholder-img bd-placeholder-img-lg featurette-image img-fluid mx-auto" width="500" height="500" xmlns="http://www.w3.org/2000/svg" preserveAspectRatio="xMidYMid slice" focusable="false" role="img" aria-label="Placeholder: 500x500"><title>Placeholder</title><rect width="100%" height="100%" fill="#eee"></rect><text x="50%" y="50%" fill="#aaa" dy=".3em">500x500</text></svg>

And lastly, this one. Checkmate.

Donec ullamcorper nulla non metus auctor fringilla. Vestibulum id ligula porta felis euismod semper. Praesent commodo cursus magna, vel scelerisque nisl consectetur. Fusce dapibus, tellus ac cursus commodo.

        <svg class="bd-placeholder-img bd-placeholder-img-lg featurette-image img-fluid mx-auto" width="500" height="500" xmlns="http://www.w3.org/2000/svg" preserveAspectRatio="xMidYMid slice" focusable="false" role="img" aria-label="Placeholder: 500x500"><title>Placeholder</title><rect width="100%" height="100%" fill="#eee"></rect><text x="50%" y="50%" fill="#aaa" dy=".3em">500x500</text></svg>

Back to top

© 2017-2020 Company, Inc. · Privacy · Terms

A: Missing carousel css in your code.
<link href="https://getbootstrap.com/docs/4.5/examples/carousel/carousel.css" rel="stylesheet">
This help to set height of carousel item.
.carousel-item {
    height: 32rem;
}

<!DOCTYPE html>

        <meta charset="utf-8">

    <link href="https://getbootstrap.com/docs/4.5/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-9aIt2nRpC12Uk9gS9baDl411NQApFmC26EwAOH8WgZl5MYYxFfc+NcPb1dKGj7Sk" crossorigin="anonymous">
     <link href="main.css" rel="stylesheet" type="text/css">
        <link href="css/basic-template.css" rel="stylesheet">
        <link href="https://getbootstrap.com/docs/4.5/examples/carousel/carousel.css" rel="stylesheet">

        <link href="#" rel="favicon"/>

        <title>Title - Home</title>

    Carousel
    <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarCollapse" aria-controls="navbarCollapse" aria-expanded="false" aria-label="Toggle navigation">

    </button>

          Home (current)

          Link

          Disabled

      <form class="form-inline mt-2 mt-md-0">
        <input class="form-control mr-sm-2" type="text" placeholder="Search" aria-label="Search">
        <button class="btn btn-outline-success my-2 my-sm-0" type="submit">Search</button>
      </form>

        <svg class="bd-placeholder-img" width="100%" height="100%" xmlns="http://www.w3.org/2000/svg" preserveAspectRatio="xMidYMid slice" focusable="false" role="img"><rect width="100%" height="100%" fill="#777"></rect></svg>

Example headline.

Cras justo odio, dapibus ac facilisis in, egestas eget quam. Donec id elit non mi porta gravida at eget metus. Nullam id dolor id nibh ultricies vehicula ut id elit.

Sign up today

        <svg class="bd-placeholder-img" width="100%" height="100%" xmlns="http://www.w3.org/2000/svg" preserveAspectRatio="xMidYMid slice" focusable="false" role="img"><rect width="100%" height="100%" fill="#777"></rect></svg>

Another example headline.

Cras justo odio, dapibus ac facilisis in, egestas eget quam. Donec id elit non mi porta gravida at eget metus. Nullam id dolor id nibh ultricies vehicula ut id elit.

Learn more

        <svg class="bd-placeholder-img" width="100%" height="100%" xmlns="http://www.w3.org/2000/svg" preserveAspectRatio="xMidYMid slice" focusable="false" role="img"><rect width="100%" height="100%" fill="#777"></rect></svg>

One more for good measure.

Cras justo odio, dapibus ac facilisis in, egestas eget quam. Donec id elit non mi porta gravida at eget metus. Nullam id dolor id nibh ultricies vehicula ut id elit.

Browse gallery

      Previous

      Next

        <svg class="bd-placeholder-img rounded-circle" width="140" height="140" xmlns="http://www.w3.org/2000/svg" preserveAspectRatio="xMidYMid slice" focusable="false" role="img" aria-label="Placeholder: 140x140"><title>Placeholder</title><rect width="100%" height="100%" fill="#777"></rect><text x="50%" y="50%" fill="#777" dy=".3em">140x140</text></svg>

Heading

Donec sed odio dui. Etiam porta sem malesuada magna mollis euismod. Nullam id dolor id nibh ultricies vehicula ut id elit. Morbi leo risus, porta ac consectetur ac, vestibulum at eros. Praesent commodo cursus magna.

View details »

        <svg class="bd-placeholder-img rounded-circle" width="140" height="140" xmlns="http://www.w3.org/2000/svg" preserveAspectRatio="xMidYMid slice" focusable="false" role="img" aria-label="Placeholder: 140x140"><title>Placeholder</title><rect width="100%" height="100%" fill="#777"></rect><text x="50%" y="50%" fill="#777" dy=".3em">140x140</text></svg>

Heading

Duis mollis, est non commodo luctus, nisi erat porttitor ligula, eget lacinia odio sem nec elit. Cras mattis consectetur purus sit amet fermentum. Fusce dapibus, tellus ac cursus commodo, tortor mauris condimentum nibh.

View details »

        <svg class="bd-placeholder-img rounded-circle" width="140" height="140" xmlns="http://www.w3.org/2000/svg" preserveAspectRatio="xMidYMid slice" focusable="false" role="img" aria-label="Placeholder: 140x140"><title>Placeholder</title><rect width="100%" height="100%" fill="#777"></rect><text x="50%" y="50%" fill="#777" dy=".3em">140x140</text></svg>

Heading

Donec sed odio dui. Cras justo odio, dapibus ac facilisis in, egestas eget quam. Vestibulum id ligula porta felis euismod semper. Fusce dapibus, tellus ac cursus commodo, tortor mauris condimentum nibh, ut fermentum massa justo sit amet risus.

View details »

First featurette heading. It'll blow your mind.

Donec ullamcorper nulla non metus auctor fringilla. Vestibulum id ligula porta felis euismod semper. Praesent commodo cursus magna, vel scelerisque nisl consectetur. Fusce dapibus, tellus ac cursus commodo.

        <svg class="bd-placeholder-img bd-placeholder-img-lg featurette-image img-fluid mx-auto" width="500" height="500" xmlns="http://www.w3.org/2000/svg" preserveAspectRatio="xMidYMid slice" focusable="false" role="img" aria-label="Placeholder: 500x500"><title>Placeholder</title><rect width="100%" height="100%" fill="#eee"></rect><text x="50%" y="50%" fill="#aaa" dy=".3em">500x500</text></svg>

Oh yeah, it's that good. See for yourself.

Donec ullamcorper nulla non metus auctor fringilla. Vestibulum id ligula porta felis euismod semper. Praesent commodo cursus magna, vel scelerisque nisl consectetur. Fusce dapibus, tellus ac cursus commodo.

        <svg class="bd-placeholder-img bd-placeholder-img-lg featurette-image img-fluid mx-auto" width="500" height="500" xmlns="http://www.w3.org/2000/svg" preserveAspectRatio="xMidYMid slice" focusable="false" role="img" aria-label="Placeholder: 500x500"><title>Placeholder</title><rect width="100%" height="100%" fill="#eee"></rect><text x="50%" y="50%" fill="#aaa" dy=".3em">500x500</text></svg>

And lastly, this one. Checkmate.

Donec ullamcorper nulla non metus auctor fringilla. Vestibulum id ligula porta felis euismod semper. Praesent commodo cursus magna, vel scelerisque nisl consectetur. Fusce dapibus, tellus ac cursus commodo.

        <svg class="bd-placeholder-img bd-placeholder-img-lg featurette-image img-fluid mx-auto" width="500" height="500" xmlns="http://www.w3.org/2000/svg" preserveAspectRatio="xMidYMid slice" focusable="false" role="img" aria-label="Placeholder: 500x500"><title>Placeholder</title><rect width="100%" height="100%" fill="#eee"></rect><text x="50%" y="50%" fill="#aaa" dy=".3em">500x500</text></svg>

Back to top

© 2017-2020 Company, Inc. · Privacy · Terms

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to design JDBC access in Java library? We at point to implement library which hide common business logic across many applications.
Library require access to DB.
Which design decision we must take in account to do job the best (in order to reduce long term support cost)?
Previously I use Spring SimpleJdbcTemplate and plain JDBC code only and want to get simplicity as in SimpleJdbcTemplate without dependency of huge framework and to avoid version conflicts on external libraries (recall - we say about library, not application).

A: After spending several hours I found nice projects:

*

*http://jdbi.org/ - most impressive

*http://www.jooq.org/

*http://www.sql2o.org/

A: *

*use connection pool. Any server application, connection pooling is very efficient to reduce connect/disconnect db. dbcp or # of connection pooling can be considered.

*separate read/write connection.
If you are considering to scale out, i'd like to recommend separate read & write db connection.  Commonly RDBMS support read replica. So for write connection, it just can be used for db write/update/delete and read connection can be used for read transaction only. As u can imagine, % of read transaction is usually 70~90% (depends on application type)

*Before thinking about Spring JDBC or pure JDBC etc. You'd better to think about pure SQL coding or OR-Mapping (JPA, Hibernate, Mybatis etc).
There are pros & cons depends on the framework.

A: I would use spring-jdbc for database interaction. Libraries may have dependencies. Use Maven and there will be no versioning problem. Spring-jdbc is not huge.


text:
Q: Open3D - Crop Pointcloud with Polygon Volume everyone,
I would like to crop and save out an area from a point cloud and save it.
I have the BBox Coordinats (maxx,maxy,minx,miny), which are the MaxP and MinP of the Pointcloud and want to make a polygon out of it. With bbox_to_Polygon(MaxP,MinP)  the BBox coordinates are converted into corner points. These should be used to create two polygons. Out of this i had made a Polyhedron with pyny3D.
Now i can feed
open3d.visualization.SelectionPolygonVolume() with a Volume, i thought.
I dont wanna use a JSON-File like described in the Open3d Docs Crop from Cloud. So I found this How to Create a open3d.visualization.SelectionPolygonVolume Object Without Loading a json Filel.
Why is orthogonal_axis="Y"? Why not just the "Z"-axis?
In example of JSON-File the Y values are 0. I would suggest because of orthogonal_axis="Y" but i dont understand why? Don´t we need a PolygonVolume?
I would appreciate some help.
I am working with Google Colab and Jupyter Notebook
Python 3.6
#Vertics Poyhedrol to create a PolygonVolume
bounding_polygon = np.array([

#Vertics Polygon 1
        [488.8989868164062, 612.208984375, 286.5320129394531],
        [485.114990234375, 612.208984375, 286.5320129394531],
        [485.114990234375, 605.0880126953125, 286.5320129394531],
        [488.8989868164062, 605.0880126953125, 286.5320129394531],
#Vertics Polygon2
        [488.89898681640625, 612.208984375, 291.6619873046875],
        [485.114990234375, 612.208984375, 291.6619873046875],
        [485.114990234375, 605.0880126953125, 291.6619873046875],
        [488.89898681640625, 605.0880126953125, 291.6619873046875]]).astype("float64")

vol = o3d.visualization.SelectionPolygonVolume()
vol.orthogonal_axis = "Y"
vol.axis_max = 500
vol.axis_min = 700
vol.bounding_polygon = o3d.utility.Vector3dVector(bounding_polygon)

comp = vol.crop_point_cloud(pcd)
comp

#Since I took the MaxP and MinP of the Pointcloud as BBCoords I would expect the same number of points. But I get this:
#`geometry::PointCloud with 0 points`

Here is the whole Code
import numpy as np
import pyny3d
import pyny3d.geoms as pyny
import open3d as o3d
from open3d import JVisualizer

path_incloud = ('/gdrive/My Drive/Colab Notebooks/Georeferenzierung/BildGeoreferenzieren/PointCloud/PointCloudFormats/Kranfundament - Cloud.ply')
pcd = o3d.io.read_point_cloud(path_incloud)
print("Input Cloud:", pcd)

visualizer = JVisualizer()
visualizer.add_geometry(pcd)
visualizer.show()

def bbox_to_Polygon(MaxP,MinP):

      p1= [MaxP[0], MaxP[1], MinP[2]]
      p2= [MaxP[0],MinP[1],MinP[2]]
      p3= [MinP[0],MaxP[1],MinP[2]]
      p4= MinP
      p5= MaxP
      p6= [MinP[0],MaxP[1],MaxP[2]]
      p7= [MinP[0],MinP[1],MaxP[2]]
      p8= [MaxP[0],MinP[1], MaxP[2]]

      listPoints1 = [p1,p3,p4,p2]
      print(listPoints1)

      listPoints2 = [p5,p6,p7,p8]
      print(listPoints2)
      return  listPoints1,listPoints2

MaxP = MaxPoint_PointCloud
MinP = MinPoint_PointCloud

listPointsPoly1 , listPointsPoly2  = bbox_to_Polygon(MaxP= MaxP, MinP=MinP)

poly1 = pyny.Polygon(np.array(listPoints1))
poly2 = pyny.Polygon(np.array(listPoints2))

poly1.plot()
poly2.plot()

polyhedron = pyny.Polyhedron.by_two_polygons(poly1, poly2)

polyhedron.plot('b')

MaxP = MaxPoint_PointCloud
MinP = MinPoint_PointCloud

#Vertics Poyhedrol to create a PolygonVolume
bounding_polygon = np.array([
#Vertics Polygon 1
        [488.8989868164062, 612.208984375, 286.5320129394531],
        [485.114990234375, 612.208984375, 286.5320129394531],
        [485.114990234375, 605.0880126953125, 286.5320129394531],
        [488.8989868164062, 605.0880126953125, 286.5320129394531],
#Vertics Polygon2
    [488.89898681640625, 612.208984375, 291.6619873046875],
    [485.114990234375, 612.208984375, 291.6619873046875],
    [485.114990234375, 605.0880126953125, 291.6619873046875],
    [488.89898681640625, 605.0880126953125, 291.6619873046875]]).astype("float64")

vol = o3d.visualization.SelectionPolygonVolume()
vol.orthogonal_axis = "Y"
vol.axis_max = 1000
vol.axis_min = -1000
vol.bounding_polygon = o3d.utility.Vector3dVector(bounding_polygon)

comp = vol.crop_point_cloud(pcd)
print("Cropped Cloud",comp)

A: This post helped me get decently far to crop a point cloud within the bounds of a cuboid.  I also consistently ran into geometry::PointCloud with 0 points using vol.crop_point_cloud(pcd) and couldn't get it working, but I found a different solution.
I ended up referencing this PR #1218 to use an open3d.geometry.OrientedBoundingBox cuboid volume to crop the point cloud.  The code below creates a 200m x 200m "tile" cuboid around a start_position, which corresponds to an ego vehicle start pose within a point cloud, and filters the points that only lie within the tile.
import json
import numpy as np
import open3d as o3d

CUBOID_EXTENT_METERS = 200

METERS_BELOW_START = 5
METERS_ABOVE_START = 30

def main():
  ## Point Cloud
  points = np.array([
    ## These points lie inside the cuboid
    [-2770.94365061042, 722.0595600050154, -20.004812609192445],
    [-2755.94365061042, 710.0595600050154, -20.004812609192445],
    [-2755.94365061042, 710.0595600050154, -15.004812609192445],

    ## These points lie outside the cuboid
    [-2755.94365061042 + CUBOID_EXTENT_METERS, 710.0595600050154, -15.004812609192445],
    [-2755.94365061042, 710.0595600050154 + CUBOID_EXTENT_METERS, -15.004812609192445],
  ]).reshape([-1, 3])

  point_cloud = o3d.geometry.PointCloud()
  point_cloud.points = o3d.utility.Vector3dVector(points)

  ## Start point here corresponds to an ego vehicle position start in a point cloud
  start_position = {'x': -2755.94365061042, 'y': 722.0595600050154, 'z': -20.004812609192445}
  cuboid_points = getCuboidPoints(start_position)

  points = o3d.utility.Vector3dVector(cuboid_points)
  oriented_bounding_box = o3d.geometry.OrientedBoundingBox.create_from_points(points)
  point_cloud_crop = point_cloud.crop(oriented_bounding_box)

  # View original point cloud with the cuboid, all 5 points present
  o3d.visualization.draw_geometries([point_cloud, oriented_bounding_box])

  # View cropped point cloud with the cuboid, only 3 points present
  o3d.visualization.draw_geometries([point_cloud_crop, oriented_bounding_box])

def getCuboidPoints(start_position):
  return np.array([
    # Vertices Polygon1
    [start_position['x'] + (CUBOID_EXTENT_METERS / 2), start_position['y'] + (CUBOID_EXTENT_METERS / 2), start_position['z'] + METERS_ABOVE_START], # face-topright
    [start_position['x'] - (CUBOID_EXTENT_METERS / 2), start_position['y'] + (CUBOID_EXTENT_METERS / 2), start_position['z'] + METERS_ABOVE_START], # face-topleft
    [start_position['x'] - (CUBOID_EXTENT_METERS / 2), start_position['y'] - (CUBOID_EXTENT_METERS / 2), start_position['z'] + METERS_ABOVE_START], # rear-topleft
    [start_position['x'] + (CUBOID_EXTENT_METERS / 2), start_position['y'] - (CUBOID_EXTENT_METERS / 2), start_position['z'] + METERS_ABOVE_START], # rear-topright

    # Vertices Polygon 2
    [start_position['x'] + (CUBOID_EXTENT_METERS / 2), start_position['y'] + (CUBOID_EXTENT_METERS / 2), start_position['z'] - METERS_BELOW_START],
    [start_position['x'] - (CUBOID_EXTENT_METERS / 2), start_position['y'] + (CUBOID_EXTENT_METERS / 2), start_position['z'] - METERS_BELOW_START],
    [start_position['x'] - (CUBOID_EXTENT_METERS / 2), start_position['y'] - (CUBOID_EXTENT_METERS / 2), start_position['z'] - METERS_BELOW_START],
    [start_position['x'] + (CUBOID_EXTENT_METERS / 2), start_position['y'] - (CUBOID_EXTENT_METERS / 2), start_position['z'] - METERS_BELOW_START],
  ]).astype("float64")

if __name__ == '__main__':
  main()

A: Here's a shortened version that shows how to crop a point cloud using an np.array of vertices:
"""
corners = [[ 5.31972845 -3.21384387  0.30217625]
 [ 5.34483288 -1.13804348  0.29917539]
 [ 7.69983939 -1.16651864  0.30329364]
 [ 7.67473496 -3.24231903  0.3062945 ]
 [ 5.31845904 -3.21276837  1.03551451]
 [ 5.34356348 -1.13696798  1.03251366]
 [ 7.69856999 -1.16544314  1.03663191]
 [ 7.67346556 -3.24124353  1.03963277]]
"""
corners = np.array(...)

# Convert the corners array to have type float64
bounding_polygon = corners.astype("float64")

# Create a SelectionPolygonVolume
vol = o3d.visualization.SelectionPolygonVolume()

# You need to specify what axis to orient the polygon to.
# I choose the "Y" axis. I made the max value the maximum Y of
# the polygon vertices and the min value the minimum Y of the
# polygon vertices.
vol.orthogonal_axis = "Y"
vol.axis_max = np.max(bounding_polygon[:, 1])
vol.axis_min = np.min(bounding_polygon[:, 1])

# Set all the Y values to 0 (they aren't needed since we specified what they
# should be using just vol.axis_max and vol.axis_min).
bounding_polygon[:, 1] = 0

# Convert the np.array to a Vector3dVector
vol.bounding_polygon = o3d.utility.Vector3dVector(bounding_polygon)

# Crop the point cloud using the Vector3dVector
cropped_pcd = vol.crop_point_cloud(pcd)

# Get a nice looking bounding box to display around the newly cropped point cloud
# (This part is optional and just for display purposes)
bounding_box = cropped_pcd.get_axis_aligned_bounding_box()
bounding_box.color = (1, 0, 0)

# Draw the newly cropped PCD and bounding box
o3d.visualization.draw_geometries([cropped_pcd, bounding_box],
                                  zoom=2,
                                  front=[5, -2, 0.5],
                                  lookat=[7.67473496, -3.24231903,  0.3062945],
                                  up=[1.0, 0.0, 0.0])

Example before:

Example after (this is from the blue chunk of points in the center of the cloud):

A: You can choose any axis as orthogonal_axis. For example, if you choose Z, define your polygon with a set of points with Z=0. Then set your Z min and max, as if you extrude a volume using the polygon between Z min and max. Hope this helps.


text:
Q: MinGW. Как компилировать? Начинаю изучать GTK. Работаю в Windows10. Компилирую пример с сайта GTK:
https://developer.gnome.org/gtk3/stable/gtk-getting-started.html
#include <gtk/gtk.h>

static void
print_hello (GtkWidget *widget,
             gpointer   data)
{
  g_print ("Hello World\n");
}

static void
activate (GtkApplication *app,
          gpointer        user_data)
{
  GtkWidget *window;
  GtkWidget *button;
  GtkWidget *button_box;

  window = gtk_application_window_new (app);
  gtk_window_set_title (GTK_WINDOW (window), "Window");
  gtk_window_set_default_size (GTK_WINDOW (window), 200, 200);

  button_box = gtk_button_box_new (GTK_ORIENTATION_HORIZONTAL);
  gtk_container_add (GTK_CONTAINER (window), button_box);

  button = gtk_button_new_with_label ("Hello World");
  g_signal_connect (button, "clicked", G_CALLBACK (print_hello), NULL);
  g_signal_connect_swapped (button, "clicked", G_CALLBACK (gtk_widget_destroy), window);
  gtk_container_add (GTK_CONTAINER (button_box), button);

  gtk_widget_show_all (window);
}

int
main (int    argc,
      char **argv)
{
  GtkApplication *app;
  int status;

  app = gtk_application_new ("org.gtk.example", G_APPLICATION_FLAGS_NONE);
  g_signal_connect (app, "activate", G_CALLBACK (activate), NULL);
  status = g_application_run (G_APPLICATION (app), argc, argv);
  g_object_unref (app);

  return status;
}

gcc:
gcc `pkg-config --cflags gtk+-3.0` -o example-1 example-1.c `pkg-config --libs gtk+-3.0`

Компилируется нормально. Далее запускаю из консоли:
./example-1.exe

*

*запускается и работает как положено)

НО. При запуске из папки, вне mingw, программа выдает ошибки об отсутствующих *.dll. Далее я нашел все эти dll-ки и скопировал в папку с программой. Снова результат- программа не запускается - выдает ошибку 0xc00007b. Я сделал все на что способен на данный момент. Что еще нужно сделать, чтобы программа запустилась в Windows?
Для справки:
$ ntldd ./example-1.exe
        KERNEL32.dll => C:\WINDOWS\SYSTEM32\KERNEL32.dll (0x0000000000620000)
        msvcrt.dll => C:\WINDOWS\SYSTEM32\msvcrt.dll (0x0000000000620000)
        libgio-2.0-0.dll => F:\TCPU69\Programm\PortableApps_Platform\PortableApps\MSYS2Portable\App\msys32\mingw64\bin\libgio-2.0-0.dll (0x0000000000620000)
        libglib-2.0-0.dll => F:\TCPU69\Programm\PortableApps_Platform\PortableApps\MSYS2Portable\App\msys32\mingw64\bin\libglib-2.0-0.dll (0x0000000000db0000)
        libgobject-2.0-0.dll => F:\TCPU69\Programm\PortableApps_Platform\PortableApps\MSYS2Portable\App\msys32\mingw64\bin\libgobject-2.0-0.dll (0x0000000000db0000)
        libgtk-3-0.dll => F:\TCPU69\Programm\PortableApps_Platform\PortableApps\MSYS2Portable\App\msys32\mingw64\bin\libgtk-3-0.dll (0x00000000010d0000)

$ ls
example-1.exe  libgio-2.0-0.dll  libglib-2.0-0.dll  libgmodule-2.0-0.dll  libgobject-2.0-0.dll  libgtk-3-0.dll  libpcre-1.dll  libwinpthread-1.dll

Проверяю дальше:
$ ntldd libgio-2.0-0.dll
        libgmodule-2.0-0.dll (0x0000000000020000)
        libgobject-2.0-0.dll (0x0000000000af0000)
        ADVAPI32.dll => C:\WINDOWS\SYSTEM32\ADVAPI32.dll (0x0000000000ef0000)
        DNSAPI.dll => C:\WINDOWS\SYSTEM32\DNSAPI.dll (0x00000000010c0000)
        IPHLPAPI.DLL => C:\WINDOWS\SYSTEM32\IPHLPAPI.DLL (0x00000000001c0000)
        KERNEL32.dll => C:\WINDOWS\SYSTEM32\KERNEL32.dll (0x0000000000f90000)
        msvcrt.dll => C:\WINDOWS\SYSTEM32\msvcrt.dll (0x0000000000f90000)
        SHELL32.dll => C:\WINDOWS\SYSTEM32\SHELL32.dll (0x00000000014b0000)
        USER32.dll => C:\WINDOWS\SYSTEM32\USER32.dll (0x0000000000f90000)
        WS2_32.dll => C:\WINDOWS\SYSTEM32\WS2_32.dll (0x00000000010c0000)
        libintl-8.dll (0x00000000001c0000)
        zlib1.dll (0x00000000001c0000)
        libglib-2.0-0.dll (0x0000000000dd0000)

... видимо это они...недостающие библиотеки из комментариев))) интересно почему отсутствует адрес!?
попробую скопировать их в папку программы...и остальное аналогично...
$ ntldd libglib-2.0-0.dll
        ADVAPI32.dll => C:\WINDOWS\SYSTEM32\ADVAPI32.dll (0x0000000000620000)
        KERNEL32.dll => C:\WINDOWS\SYSTEM32\KERNEL32.dll (0x0000000000e00000)
        msvcrt.dll => C:\WINDOWS\SYSTEM32\msvcrt.dll (0x0000000000e00000)
        ole32.dll => C:\WINDOWS\SYSTEM32\ole32.dll (0x0000000000e00000)
        libwinpthread-1.dll (0x0000000000190000)
        SHELL32.dll => C:\WINDOWS\SYSTEM32\SHELL32.dll (0x0000000001230000)
        USER32.dll => C:\WINDOWS\SYSTEM32\USER32.dll (0x0000000000e00000)
        WS2_32.dll => C:\WINDOWS\SYSTEM32\WS2_32.dll (0x0000000000f30000)
        libintl-8.dll (0x0000000000190000)
        libpcre-1.dll (0x0000000000190000)
$ ntldd libgobject-2.0-0.dll
        libglib-2.0-0.dll (0x0000000000d10000)
        KERNEL32.dll => C:\WINDOWS\SYSTEM32\KERNEL32.dll (0x0000000000e30000)
        msvcrt.dll => C:\WINDOWS\SYSTEM32\msvcrt.dll (0x0000000000e30000)
        libffi-6.dll (0x0000000000020000)
$ ntldd libgtk-3-0.dll
        libgdk-3-0.dll (0x0000000001320000)
        COMCTL32.dll => C:\WINDOWS\WinSxS\amd64_microsoft.windows.common-controls_6595b64144ccf1df_5.82.17134.285_none_f956470b309229d4\COMCTL32.dll (0x0000000001a60000)
        comdlg32.dll => C:\WINDOWS\SYSTEM32\COMDLG32.dll (0x0000000001450000)
        GDI32.dll => C:\WINDOWS\SYSTEM32\GDI32.dll (0x0000000000190000)
        IMM32.dll => C:\WINDOWS\SYSTEM32\IMM32.dll (0x0000000000190000)
        KERNEL32.dll => C:\WINDOWS\SYSTEM32\KERNEL32.dll (0x0000000001790000)
        msvcrt.dll => C:\WINDOWS\SYSTEM32\msvcrt.dll (0x00000000014f0000)
        ole32.dll => C:\WINDOWS\SYSTEM32\ole32.dll (0x0000000001790000)
        SHELL32.dll => C:\WINDOWS\SYSTEM32\SHELL32.dll (0x0000000002120000)
        USER32.dll => C:\WINDOWS\SYSTEM32\USER32.dll (0x0000000001790000)
        WINSPOOL.DRV => C:\WINDOWS\SYSTEM32\WINSPOOL.DRV (0x0000000001450000)
        libatk-1.0-0.dll (0x0000000000190000)
        libcairo-gobject-2.dll (0x0000000000020000)
        libcairo-2.dll (0x0000000001450000)
        libepoxy-0.dll (0x0000000001790000)
        libgdk_pixbuf-2.0-0.dll (0x0000000000190000)
        libgio-2.0-0.dll (0x0000000001790000)
        libglib-2.0-0.dll (0x00000000018f0000)
        libgmodule-2.0-0.dll (0x0000000000020000)
        libgobject-2.0-0.dll (0x0000000000720000)
        libintl-8.dll (0x0000000000190000)
        libpango-1.0-0.dll (0x0000000000720000)
        libpangocairo-1.0-0.dll (0x0000000000190000)
        libpangowin32-1.0-0.dll (0x00000000001d0000)

И ВУАЛЯ - что получаем? Снова - ошибка про недостающие библиотеки!
Создаю новый вопрос как заскриптовать все действия по поиску и копированию  недостающих lib.Скрипт или программа для добавления недостающих библиотек

A: На официальном сайте GTK имеется инструкция для установки зависимостей с помощью MSYS2, а также перечислены зависимости:

List of GTK+ dependencies
GTK+ depends on several libraries:
  GLib
  cairo
  Pango
  ATK
  gdk-pixbuf
To run GTK+ programs you will also need:
  gettext-runtime
  fontconfig
  freetype
  expat
  libpng
  zlib

Убедитесь, что все перечисленные библиотеки необходимых версий и их зависимости имеются , а динамический линковщик в состоянии их найти. Также не забудьте о библиотеке libgcc_*.dll. Так как у Вас приложение запускается из консоли (используется MSYS2, если не ошибаюсь), то библиотеки где-то имеются, но динамический линковщик не может их найти.


text:
Q: Office 365 list data using jquery I am doing azure project in that i want to get list data from sharepoint online(Office365)
So it is possible using jquery?

A: The simplest way is to either use REST Api that works for every list in SharePoint, via /_vti_bin/ListData.svc which you could use via $.ajax or $.getJSON calls.
Or use ECMA Client Object Model API in SharePoint 2010 which enables direct access using Javascript to lists. Google-it, many examples available http://blogs.msdn.com/b/sharepointdev/archive/2011/07/19/working-with-the-ecmascript-client-object-model-jsom-in-sharepoint-2010-part-3-nikhil-sachdeva.aspx
Hope it helps,
C:\Marius

A: You'll want to take a look at the SPServices library if you're wanting to get to SharePoint list data with jQuery.  It wraps all the web services into easily accessible functions that are a snap to work with.
Since you haven't posted much detail, review the operations and post back with new questions if you have any issues, or post on the spservices discussion board.


text:
Q: Labeling a barchart with a tree of properties Given a DataFrame with a number of properties. I would like to label the ticks of a bar chart in the sense of a tree. I hope the following example and ASCII-art makes it clear:
import pandas as pd
import matplotlib.pyplot as plt

data = [
    ('foo', 'qux', 2, 2),
    ('bar', 'corge', 1, 3),
    ('foo', 'corge', 3, 2),
    ('bar', 'qux', 2, 3),
]

df = pd.DataFrame(data, columns=('A', 'B', 'U', 'V'))

df.plot.barh(stacked=True)
plt.gca().set_yticklabels(df.A + ' ' + df.B)

# Should be
#
# foo / qux     |##@@
#     \ corge   |###@@
# bar / qux     |##@@@
#     \ corge   |#@@@

The actual data consists of three properties / levels of trees from a factorial experiment.

A: Here's a proposed way using minor ticklabels to achieve the desired result:
import pandas as pd
import matplotlib.pyplot as plt
from matplotlib import ticker

data = [
    ('foo', 'qux', 2, 2),
    ('bar', 'corge', 1, 3),
    ('foo', 'corge', 3, 2),
    ('bar', 'qux', 2, 3),
]

df = pd.DataFrame(data, columns=('A', 'B', 'U', 'V'))

df = df.set_index(['A','B'])
df.sort_index(inplace=True)
# Remove the index names for the plot, or it'll be used as the axis label
df.index.names = ['','']

ax = df.plot(kind='barh', stacked=True)

minor_locator = ticker.AutoMinorLocator(2)

ax.yaxis.set_minor_locator(minor_locator)
ax.set_yticklabels(df.index.get_level_values(1))
ax.set_yticklabels(df.index.get_level_values(0).unique(), minor=True)
ax.set_yticks(np.arange(0.5, len(df), 2), minor=True)
ax.tick_params(axis='y', which='minor', direction='out', pad=50)

plt.show()


text:
Q: Are browsers optimized for different image aspect ratios? This question might have a very complex answer, but here goes:
I have created some image sprites using a naive stacking algorithm which produces images that are 89px wide by 2000px tall. This image will be used for about 50 sprites on a page. The sprite is in .GIF format, and I know almost nothing about how GIF encodes pixels, (I don't know if it's row/column-major, or some other packing algo).
The total number of pixels in the sprite image is 178,000.
I could alter my sprite generation algorithm to produce a sprite that is 445px wide by 400 tall (same number of pixels, just creating a grid of images instead of a single column).
Does changing the configuration of the sprite produce better browser DOM load/render performance? (I'm  especially interested IE 8 and mobile browsers, like Safari on iOS)

A: As with all optimization questions ... it's hard to say without measuring it.
BUT ... based on the way GIF files are encoded I suspect that your current layout will perform 'better' than a more-even aspect ratio image.
Documentation on the GIF file format says "It is therefore likely that one scan line will end and another begin in the middle of a sub-block of image data".
Since the image data is LZW compressed, and since pixels from the same icon are more likely to be the same color (even if they are from opposite edges and one row down), it's likely that your current layout will compress better and therefore it's likely to perform better.
But I'm sure there are plenty of pathological cases where the converse is true, and equally confident that any performance gain from either layout is likely to be so small that there are undoubtedly better optimizations to go worry about.


text:
Q: With spring boot vaadin spring.jpa.open-in-view not working I have a Spring Boot based app with vaadin frontend, but the spring.jpa.open-in-view function is not working.
The spring boot version is 2.1.2.RELEASE.
As I see the OpenEntityManagerInViewInterceptor is registered correctly, but it is called once, when the application loaded.
When any backend call invoked it is not triggered.


text:
Q: Sed: output value of capturing group into a file
I'm using sed to capture text, run external commands and output value of capturing group to screen and into a file.

This is an example of command I need:
echo testme | sed -r 's/([a-z]{4}).*/'"$(echo "\1" | tee out.txt)"'/g'

That is, I need to output value (test) of capturing group (\1)  to a file.

But while on the screen I can see right text:
test

in a file I see the following:
\1

Seems that notation of capturing group doesn't expand its value when output to file instead of screen.
Please, tell me what do I do wrong and how to output value of capturing group into a file.
Please, if possible - no solutions with grep/awk. I need to do that using sed (or maybe ssed).
Thanks!

A: Basically you can do it this way but I'm not sure if it's what you really want:
echo testme | tee >(sed -r 's/([a-z]{4}).*/\1/g' > out.txt)

It would send testme unmodified on the screen while the filtered version would be sent to out.txt.
If you want to send both filtered version to screen and file, you can just use tee at the last part:
echo testme | sed -r 's/([a-z]{4}).*/\1/g' | tee out.txt

Appending versions:
echo testme | tee >(sed -r 's/([a-z]{4}).*/\1/g' >> out.txt)

echo testme | sed -r 's/([a-z]{4}).*/\1/g' | tee -a out.txt

A: This might work for you (GNU sed):
sed -r '/([a-z]{4}).*/!b;s//\1/;w out.txt' file

or:
sed -rn 's/([a-z]{4}).*/\1/p;T;s/.*/echo "&" | tee out.txt/e' file


text:
Q: Retorno de método em Java Não conheço nada de Java. Gostaria de saber como faço para pegar o valor do retorno da variável dv que está dentro do método Base10() e usá-lo no main. Alguém poderia me ajudar?
public class Boleto {

public static void main(String[] args) {

    String codBarras = "23793.44308.90010.000041.33001.250001.3.52830000008091";

}
    public class Barra{
        public int Base10(String num){
            //variáveis de instancia
            int soma = 0;
            int resto = 0;
            int dv = 0;
            String[] numeros = new String[num.length()+1];
            int multiplicador = 2;
            String aux;
            String aux2;
            String aux3;

            for (int i = num.length(); i > 0; i--) {
                //Multiplica da direita pra esquerda, alternando os algarismos 2 e 1
                if(multiplicador%2 == 0){
                    // pega cada numero isoladamente
                    numeros[i] = String.valueOf(Integer.valueOf(num.substring(i-1,i))*2);
                    multiplicador = 1;
                }else{
                    numeros[i] = String.valueOf(Integer.valueOf(num.substring(i-1,i))*1);
                    multiplicador = 2;
                }
            }
            // Realiza a soma dos campos de acordo com a regra
            for(int i = (numeros.length-1); i > 0; i--){
                aux = String.valueOf(Integer.valueOf(numeros[i]));
                if(aux.length()>1){
                    aux2 = aux.substring(0,aux.length()-1);
                    aux3 = aux.substring(aux.length()-1,aux.length());
                    numeros[i] = String.valueOf(Integer.valueOf(aux2) + Integer.valueOf(aux3));
                }
                else{
                    numeros[i] = aux;
                }
            }
            //Realiza a soma de todos os elementos do array e calcula o digito verificador
            //na base 10 de acordo com a regra.
            for(int i = numeros.length; i > 0 ; i--){
                if(numeros[i-1] != null){
                    soma += Integer.valueOf(numeros[i-1]);
                }
            }
            resto = soma%10;
            dv = 10 - resto;
            //retorna o digito verificador

            return dv;
        }
     }
 }

A: Basta fazer isso:
public static void main(String[] args) {
    String codBarras = "23793.44308.90010.000041.33001.250001.3.52830000008091";
    String codBarrasLimpo = codBarras.replace(".", "");
    int dv = Base10(codBarrasLimpo);
    System.out.println(dv);
}

A saída é 6.
Veja aqui funcionando no ideone.

Como a pergunta foi editada, aqui vão mais algumas informações:
O String codBarrasLimpo = codBarras.replace(".", ""); serve para retirar os pontos da String. O código do método Base10 não sabe lidar com eles, e por isso é importante retirá-los antes de calcular a base 10. A String original (codBarras) é preservada, o que significa que essa operação não é destrutiva, pois uma outra String (a codBarrasLimpo) sem os pontos é criada sem que a antiga (codBarras) seja danificada.
O código acima é possível se o método Base10 for estático e estando na mesma classe.
Se ele estiver em outra classe, continuando a ser estático, então você usa isso:
int dv = Barra.Base10(codBarrasLimpo);

Se ele não for estático, você vai precisar de uma instância da classe que o envolve (no caso Barra):
Barra b = new Barra();
int dv = b.Base10(codBarrasLimpo);

Entretanto, uma instância de Barra não representa nada. O método Base10 não necessita de nenhuma instância para operar. Então, a menos que você reorganize as coisas de alguma outra forma, o melhor seria deixar o método Base10 estático mesmo.
Um outro porém é que o método devia ser chamado base10. A convenção de nomenclatura do Java dita que nomes de métodos devem/deveriam ser iniciados com letra minúscula. Veja mais sobre isso aqui.

A: Chama o metodo e atribua ele à uma variavel:
x = Base10(String num)

Logo 'x' receberá o retorno do metodo;

A: public static void main(String[] args) {

    String codBarras = "23793.44308.90010.000041.33001.250001.3.52830000008091";
         int dv = Base10(codBarras){
}


text:
Q: Append OR subquery in Linq I am trying to build a simple search against some entities (EF4, if that makes any difference). Passed into my search query is a list of criteria objects. The crieteria object looks like this:
public class ClaimSearchCirtieria
{
    public Guid? FinancialYear { get; set; }
    public bool AllClaimants { get; set; }
    public IList<Guid> ClaimantIds { get; set; }
    public bool AllExpenseCategories { get; set; }
    public IList<ExpenseCategoryAndTypeCriteria> EpenseCategoryAndTypes { get; set; }
}

And the ExpenseCategoryAndTypeCriteria
public class ExpenseCategoryAndTypeCriteria
{
    public Guid ExpenseCategory { get; set; }
    public bool AllTypesInCatgeory { get; set; }
    public IList<Guid> ExpenseTypes { get; set; }
}

Searching on financial years and claimants needs to be an AND query, then I need the expense categories and expense types to be appended as an OR sub query.
In essence I'm trying to do:
select *
from claims
where <financial year> AND <Claimants> AND (expense type 1 OR expense type 2 or expense category X)

So far I've got this:
public PagedSearchResult<Claim> Search(ClaimSearchCirtieria searchCriteria, int page, int pageSize)
{
    var query = All();

    if (searchCriteria.FinancialYear.HasValue)
    {
        query = from claim in query
                where claim.FinancialYearId == searchCriteria.FinancialYear
                select claim;
    }

    if (!searchCriteria.AllClaimants)
    {
        query = from claim in query
                where searchCriteria.ClaimantIds.Contains(claim.ClaimantId)
                select claim;
    }

    if (!searchCriteria.AllExpenseCategories)
    {
        foreach (var item in searchCriteria.EpenseCategoryAndTypes)
        {
            if (item.AllTypesInCatgeory)
            {
                //Just search on the category
                query = query.Where(claim =>
                    (from transaction in claim.ClaimTransactions
                     where item.ExpenseCategory == transaction.ExpenseType.ExpenseCategoryId
                     select transaction).Count() > 0
                );
            }
            else
            {
                //Search for the specified types
                query = query.Where(claim =>
                    (from transaction in claim.ClaimTransactions
                     where item.ExpenseTypes.Contains(transaction.ExpenseTypeId)
                     select transaction).Count() > 0
                );
            }
        }
    }

    return PagedSearchResult<Claim>.Build(query, pageSize, page);
}

What I'm currently seeing is that the last expense category requested is the only expense category I get results for. Also, looking at the code, it looks like I would expect this to be building a series of AND queries, rather that the required OR.
Any pointers?

A: You can do this with LINQKit's PredicateBuilder. You need to use AsExpandable() when composing Entity Framework queries.


text:
Q: What use cases really make prometheus's summary metrics type necessary/unique? For Prometheus metrics collection, like title, I could not really find a use case which only can be done via the type Summary, seems that they all somehow can be done via the type Histogram also.
Lets take the request concurrency metrics as example, no doubt this can be perfectly done via type Summary, but i can also achieve the same effect by using type Histogram, as below:
rate(http_request_duration_seconds_sum[1s]) / rate(http_request_duration_seconds_count[1s])
The only difference I can see is: for a summary the percentiles are computed in the client, it is made of a count and sum counters (like in Histogram type) and resulting quantile values.
So I am a bit lost on what use cases really make the type Summary necessary/unique, please help to inspire me.

A: Prometheus summary metric type is useful when there is set of pre-defined percentiles, which must be exposed for some metric such as request duration or response size, and there is no need in calculating aggregate percentiles over multiple metrics. For example, if you need to measure 90th, 97th and 99th percentile for request duration on a single server, then the following metrics composing Prometheus summary would be useful to export:
http_request_duration_seconds{quantile="0.99"}
http_request_duration_seconds{quantile="0.97"}
http_request_duration_seconds{quantile="0.90"}

Another common reason why users prefer Prometheus summary type over Prometheus histogram type is that summary metrics are easier to understand and to deal with.
The summary metric type has the following limitations comparing to histogram metric type:

*

*Summary metric type doesn't allow calculating percentiles other than the already pre-defined percentiles. For example, if a summary metric exposes only 0.9 and 0.95 percentiles, then it is impossible to calculate 0.99 or 0.5 percentile from the collected data.

*Summary metric type doesn't allow calculating aggregate percentiles over multiple summary metrics. For example, if the http_request_duration_seconds{quantile="0.99"} metric is exposed individually per each server in a cluster, then it is impossible to calculate  the 99th percentile for request duration over all the servers in the cluster. Users sometimes use avg(http_request_duration_seconds{quantile="0.99"}) or max(http_request_duration_seconds{quantile="0.99"}) as a workaround, but the resulting value may be far from the actual percentile.

The histogram metric type in Prometheus also has its own issues:

*

*Too low precision for calculated percentiles when the exported histogram buckets have insufficient coverage for the measurement. For example, if http_request_duration_seconds histogram has the following buckets: [0-0.1], (0.1-1.0], (1.0-10.0] - and the majority of requests are executed in 0.5 seconds, then all these requests will go to the [0.1-1.0] bucket. But it is impossible to calculate any percentile with good precision from such a data.

*Too big number of exported buckets. When users stumble upon the first issue, the most common reaction is to create big number of buckets in order to have good coverage over the measurement. This may lead to high cardinality issues, since each bucket is exposed as a separate metric (aka time series).

*Inability to aggregate histograms with distinct sets of buckets. For example, the http_request_duration_seconds histogram may have distinct sets of buckets per each monitored service. Then it is impossible to calculate percentile for this histogram over multiple services.
These issues are solved in VictoriaMetrics histogram type - see this article for details.

A: The Summary metric is not unique, many other instrumentation systems offer similar - such as Dropwizard's Histogram type (it's a histogram internally, but exposed as a quantile). This is one reason it exists, so such types from other instrumentation systems can be mapped more cleanly.
Another reason it exists is historical. In Prometheus the Summary came before the Histogram, and the general recommendation is to use a Histogram as it's aggregatable where the Summary's quantiles are not. On the other hand histograms require you to pre-select buckets in order to be aggregatable and allow analysis over arbitrary time frames.
There is a longer comparison of the two types in the docs.


text:
Q: How to expand buttons and labels to fill the x axis in python tkinter? This is a part of code from my school project.
from tkinter import *
from tkinter.font import Font

class student_window():

    def __init__(self, master):
        self.student_win = master
        #window = Toplevel(self.master)
        self.student_win.geometry("1280x720")
        self.header1Font = Font(family='Helvetica', size=20)
        self.optionFont = Font(family='Sans Serrif', size=20)
        self.student_win.focus()
        self.show_window()

    def show_window(self):
        print("ookk")
        self.student_win.title("Student Window")
        self.option_frame = Frame(self.student_win, width=200, height=720)
        lbl_header = Label(self.option_frame,text="EXAMINATION", font=self.header1Font, fg='white', bg='#172D44').grid(row=0,column=0, sticky=NSEW)
        lbl_welcome = Label(self.option_frame, text="Welcome,", fg='#E9F1F7', bg='#2A3F54').grid(row=1,column=0)
        lbl_username = Label(self.option_frame, text="Username", fg='white', bg='#2A3F54').grid(row=2,column=0)
        lbl_header2 = Label(self.option_frame, text="STUDENT CORNER", fg='white', bg='#2A3F54').grid(row=3, column=0)
        self.btn_tests = Button(self.option_frame, text="Attempt Exam", fg='#E9F1F7', bg='#35495D', relief=FLAT)
        self.btn_tests.grid(row=4,column=0, sticky=NSEW)
        self.btn_attempts = Button(self.option_frame, text="Attempts", fg='#E9F1F7', bg='#2A3F54', relief=FLAT)
        self.btn_attempts.grid(row=5, column=0, sticky=NSEW)
        self.btn_result = Button(self.option_frame, text="Result", fg='#E9F1F7', bg='#2A3F54', relief=FLAT)
        self.btn_result.grid(row=6, column=0, sticky=NSEW)
        self.btn_goBack = Button(self.option_frame, text="Go Back", fg='#E9F1F7', bg='#2A3F54', relief=FLAT)
        self.btn_goBack.grid(row=7, column=0, sticky=NSEW)
        self.option_frame.configure(bg='#2A3F54')
        self.option_frame.grid(row=0, column=0)
        self.option_frame.grid_propagate(0)
        self.main_frame = Frame(self.student_win, width=880, height=720)
        self.main_result_frame = Frame(self.main_frame)
        self.main_result_frame.grid(row=0,column=0)
        self.attempts_frame = Frame(self.main_frame)
        self.attempts_frame.grid(row=0, column=0)
        self.test_frame = Frame(self.main_frame)
        lbl_test = Label(self.test_frame, text="In test frame").pack()
        self.test_frame.grid(row=0,column=0)
        self.main_frame.grid(row=0,column=1)
        self.main_frame.grid_propagate(0)
        self.info_frame = Frame(self.student_win, width=200, height=720)
        self.btn_username = Button(self.info_frame, text="Username", relief=FLAT)
        self.btn_username.grid(row=0,column=0)
        self.userInfo_frame = Frame(self.info_frame)
        self.info_frame.grid(row=0, column=2)
        self.info_frame.grid_propagate(0)

root = Tk()
student_window(root)
root.mainloop()

And it looks something like this.
The Student Panel for my project
The whole window is divided into three frames and want to expand each label and button of the left frame(self.option_frame) to fill  it horizontally. I tried doing sticky=EW and sticky=NSEW but still some space is left. How do I fix that?

A: You need to call self.option_frame.columnconfigure(0, weight=1) to make column 0 to use all the available horizontal space.

A: I was just trying some things and what I have found to be working is to make the label width bigger than than the frame then anchoring the text to the left.


text:
Q: How can I not display a page if a user is not logged in with PHP? I want to hide everything on a page when a user is not logged in with PHP.
Currently, I redirect the user if they are not logged in, but in case people are trying to get around the redirect, I want to make sure none of the content is displayed.
I understand that you could always use...
// Pseudo-code

if(!logged in){
    header("Location: login.php");
}else{
    echo "<html>...the whole page";
}

But this is too hard to maintain because I have to escape all quotes and code editors don't display is too well.
What can I use to just stop displaying any code if the user is not logged in.

A: In PHP you could use this in the beginning of the file you'd like to hide from visitors who are not logged in:
if(!isset($_SESSION['user'])) // The exact conditional depends on your login-system implementation
{
    header('Location: login.php'); // Instructs the visitor's browser to redirect
    exit; // <-- What you want. Prevents further code from being executed, works as a security measure.
}

Or in your pseudo-code:
if(!logged in)
    exit;


text:
Q: Why is a dash displayed as a dash on Android, but displayed as an underscore on iOS in my Flutter mobile app? My flutter app displays a - (dash) between two times.
5:30pm - 11:00pm
On Android, this displays correctly, but on iOS the dash displays as an underscore.
5:30pm _ 11:00pm
Can anyone tell me why this is and how to correct it?
children: <Widget>[
  Row(
    children: <Widget>[
      Expanded(
        flex: 51,
        child: Text(
          data[i].jobName!,
          style: TextStyle(color: kBodyText, fontSize: 16),
        ),
      ),
      Expanded(
        flex: 23,
        child: Text(
          formatJsonTime24To12(data[i].startTime!)!
              .toLowerCase(),
          style: TextStyle(color: kBodyText, fontSize: 16),
          textAlign: TextAlign.right,
        ),
      ),
      Expanded(
        flex: 3,
        child: Text(
          ' -',
          style: TextStyle(color: kBodyText, fontSize: 16),
          textAlign: TextAlign.center,
        ),
      ),
      Expanded(
        flex: 23,
        child: Text(
          formatJsonTime24To12(data[i].finishTime!)!
              .toLowerCase(),
          style: TextStyle(color: kBodyText, fontSize: 16),
          textAlign: TextAlign.right,
        ),
      ),
    ],
  ),

A: In your TextField, just set the following code:
keyboardType: TextInputType.numberWithOptions(decimal: true),
inputFormatters: [WhitelistingTextInputFormatter(new RegExp('[ -]'))],

A: It is very likely that in both cases the dash is actually display, but vertical alignment causes it to look like an underscore.
Since you are using a Row, you should try adding crossAxisAlignment: CrossAxisAlignment.baseline to all of its children.
This will tell Row to vertically align its children at their text baselines.

A: Thanks for the ideas. Turns out it was the flex values I was using. The flex value of 3 was enough on the android emulator I was using. But on the iOS simulator (iPhone 12 Pro Max), this wasn't enough and the text was word wrapping and creating a second line. The dash was on the second line. I increased the 3 to 5 and problem solved.


text:
Q: Fles SDK Spanish localization I'm trying to work with a Flex project that's localized for both English and Spanish. Flex Builder is throwing the following error:

unable to open 'C:\Program Files\Adobe\Flex Builder 3\sdks\3.2.0\frameworks\locale\es_ES'

Are there some extra files SDK files that I need to download?
As always, thanks for the help!

A: If the resource bundles are not available in the SDK, you'll need to create them yourself. There is a post here that explains how to do this.


text:
Q: Capture.output disregarding console size in r I'm trying to use capture.output to save a confusion matrix as follows:
capture.output(result, file = "F:/Results/result.txt")

*

*My confusion matrix has a lot of columns

*When I save the file, it breaks the columns as it does in the RStudio console.

*If I make the console bigger, it has enough space and does not break

*My question is:

Is it possible to have Capture.output ignore the console size and assume it's as big as possible (so it doesn't break things apart)?
If you want to try it on my specific data, I put it here as an .rds file:
https://upload.uni-jena.de/data/5f1045c6c0da81.96434142/result.rds
Here's how it looks:
In a small console (broken apart):
Confusion Matrix and Statistics

           Reference
Prediction  ATCC25922 DSM1576
  ATCC25922         2       0
  DSM1576           0       2
  DSM3871           0       0
  DSM429            0       0
  DSM498            0       0
  DSM499            0       0
  DSM501            0       0
  DSM613            0       0
  DSM8696           0       0
  DSM9031           0       0
  Gr02              0       0
  Gr05              0       0
  Gr06              0       0
  Gr07              0       0
  Gr09              0       1
  Pak56             0       0
  Pak57             0       0
  Pak58             1       0
  Pak64             0       0
  Pak66             0       0
           Reference
Prediction  DSM3871 DSM429
  ATCC25922       0      0
  DSM1576         0      1
  DSM3871         2      0
  DSM429          0      2
  DSM498          1      0
  DSM499          0      0
  DSM501          0      0
  DSM613          0      0
  DSM8696         0      0
  DSM9031         0      0
  Gr02            0      0
  Gr05            0      0
  Gr06            0      0
  Gr07            0      0
  Gr09            0      0
  Pak56           0      0
  Pak57           0      0
  Pak58           0      0
  Pak64           0      0
  Pak66           0      0
           Reference
Prediction  DSM498 DSM499
  ATCC25922      0      0
  DSM1576        0      0
  DSM3871        0      0
  DSM429         0      0
  DSM498         0      0
  DSM499         0      3
  DSM501         0      0
  DSM613         0      0
  DSM8696        0      0
  DSM9031        0      0
  Gr02           0      0
  Gr05           0      0
  Gr06           0      0
  Gr07           1      0
  Gr09           1      0
  Pak56          0      0
  Pak57          0      0
  Pak58          1      0
  Pak64          0      0
  Pak66          0      0
...

In a large console (in one piece):
Confusion Matrix and Statistics

           Reference
Prediction  ATCC25922 DSM1576 DSM3871 DSM429 DSM498 DSM499 DSM501 DSM613 DSM8696 DSM9031 Gr02 Gr05 Gr06 Gr07 Gr09 Pak56 Pak57 Pak58 Pak64 Pak66
  ATCC25922         2       0       0      0      0      0      0      0       0       0    0    0    0    0    0     0     0     0     0     0
  DSM1576           0       2       0      1      0      0      0      0       0       0    0    0    0    0    0     0     0     0     0     0
  DSM3871           0       0       2      0      0      0      0      0       0       0    0    0    0    0    0     0     0     0     0     0
  DSM429            0       0       0      2      0      0      1      0       0       0    0    0    0    0    0     0     0     0     0     0
  DSM498            0       0       1      0      0      0      0      0       0       0    0    0    0    0    0     0     0     0     0     0
  DSM499            0       0       0      0      0      3      0      0       0       1    0    0    0    0    1     0     0     0     0     0
  DSM501            0       0       0      0      0      0      2      0       0       0    0    0    0    0    0     0     0     0     0     0
  DSM613            0       0       0      0      0      0      0      3       0       0    0    0    0    0    0     0     0     0     0     0
  DSM8696           0       0       0      0      0      0      0      0       3       0    0    0    0    0    1     0     0     0     0     0
  DSM9031           0       0       0      0      0      0      0      0       0       2    0    0    0    0    0     0     0     0     0     1
  Gr02              0       0       0      0      0      0      0      0       0       0    3    0    0    0    0     0     0     0     0     0
  Gr05              0       0       0      0      0      0      0      0       0       0    0    2    0    0    0     0     0     0     0     0
  Gr06              0       0       0      0      0      0      0      0       0       0    0    1    2    0    0     0     0     0     0     0
  Gr07              0       0       0      0      1      0      0      0       0       0    0    0    0    1    0     0     1     0     0     0
  Gr09              0       1       0      0      1      0      0      0       0       0    0    0    1    0    1     0     1     0     1     0
  Pak56             0       0       0      0      0      0      0      0       0       0    0    0    0    0    0     3     0     0     0     0
  Pak57             0       0       0      0      0      0      0      0       0       0    0    0    0    0    0     0     1     1     0     0
  Pak58             1       0       0      0      1      0      0      0       0       0    0    0    0    1    0     0     0     1     1     0
  Pak64             0       0       0      0      0      0      0      0       0       0    0    0    0    0    0     0     0     0     1     0
  Pak66             0       0       0      0      0      0      0      0       0       0    0    0    0    1    0     0     0     1     0     2

A: Set options(width = 100) to enlarge the maximum number of characters on a line used in printing objects on the console.
options(width = 100)
capture.output(result, file = "F:/Results/result.txt")

Note: Don't resize the console window after setting options(width = 100). Some R consoles automatically change the value when they are resized.


text:
Q: Primefaces application stops working when click button Hello please help with the following problem
At times the network is slow and my application programmed in java with primefaces 6.0 and glassfish 3.1 stops working
When I open the page it is shown and the values of the components are load a few seconds late, when clicking on a button when the values of the whole page are not loaded, an error is presented and the application stops working.
Example:
1)The screen is presented and the values of the p: selectOneMenu are not loaded

2)When clicking on the first button, shows the following error:
Javascript error:
Error de lectura XML: sección CDATA no cerrada Ubicación: http://localhost:8080/....pag1.xhtml Número de línea 2, columna 43: ....pag1.xhtml:2:43
Error de lectura XML: sección CDATA no cerrada Ubicación: http://localhost:8080/....pag1 Número de línea 2, columna 43: ....pag1.xhtml:2:43
TypeError: PF(...) is undefined
Java error:
Grave: JSF1073: se ha interceptado javax.faces.event.AbortProcessingException durante el procesamiento de RENDER_RESPONSE 6 : UIComponent-ClientId=, Mensaje=java.lang.NullPointerException
Grave: java.lang.NullPointerException
javax.faces.event.AbortProcessingException: java.lang.NullPointerException
    at org.primefaces.context.PrimePartialResponseWriter.startMetadataIfNecessary(PrimePartialResponseWriter.java:303)
3)Seconds later load the values of p: selectOneMenu but the application stopped working due to the previous error.

Now if I open the screen and wait until the values of p: selectOneMenu are loaded, the screen works correctly
How can i fix this


text:
Q: Typescript base class with typed create and patch methods I want to create next api:
class BaseModel {
  // has 2 generic methods
  static create(props) { //... }

  patch(props) { //... }
}

class Foo extends BaseModel { //... }

// someProps should be typechecked
const foo = Foo.create(someProps)

// patchProps should be typechecked too
foo.patch(patchProps)

I came up with next solution (it is probably not optimal at all):
type PropType<T, P extends keyof T> = T[P];

class BaseModel {
  static create<T extends typeof BaseModel & { props: unknown }, P extends PropType<T, 'props'>>(
    this: T,
    props: P
  ): InstanceType<T> {
    const model = new this() as InstanceType<T>;

    model.patch(props);

    return model;
  }

  // @ts-ignore
  // Don't know how to type this part
  patch(props) {
    // some work, might be untyped
  }
}

class Foo extends BaseModel {
  static props: {
    someString?: string;
  };
}

// this works fine
const t = Foo.create({ someString: 'someString' });

// this is not typechecked, should throw error
t.patch({ someInvalidObject: 1 });

I do not declare props in BaseModel so it should be required to declare on children class.
How do I make patch method strongly typed?
Maybe there is some other way to make this api work?
Typescript playground link

A: We can add a generic type parameter to the base class, although that will make it difficult when inheriting the class.
Another option is the base class to have a version of the method which is basically un-callable. Then we add a the apropriate signature of patch as the return of create
type PropType<T, P extends keyof T> = T[P];

class BaseModel {
  static create<T extends typeof BaseModel & { props: unknown }, P extends PropType<T, 'props'>>(
    this: T,
    props: P
  ) {
    const model = new this() as InstanceType<T> & {
      patch(props: T['props']): void
    };

    model.patch(props);

    return model;
  }

  patch(props: Record<string, never>) {

  }
}

class Foo extends BaseModel {
  static props: {
    someString?: string;
  };
}

const t = Foo.create({ someString: 'someString' });

t.patch({ someInvalidObject: 1 }); //err
t.patch({ someString: "" }) // ok


text:
Q: Open recordset in Access 2003/2007 It's been years since I've worked in Access code and it is making me certifiably insane.
I just don't remember anything and all I want to do is open a recordset in code and nothing I've found online or any permutation of code I've tried works.
The short of it:
Dim rsSystem As Recordset
Dim sSQL As String

sSQL = "SELECT * FROM Table"
Set rsSystem = CurrentDB.OpenRecordset(sSQL)

What in the holy hell am I missing?
Thanks in advance.

A: If you declare just a Recordset without specifying if it's DAO or ADO, Access will decide on its own whether it will be DAO or ADO, depending on the order of your references:
Open a code window, go to Tools --> References, and look at the list there.
It will look something like that:

You see that in this example, there is a reference on DAO ("Microsoft DAO 3.6 Object Library") and ADO ("Microsoft ActiveX Data Objects 2.5 Library").
If you declare your Recordset without specifying the type, Access picks the first of these references (=the one that's more on top of the list) and creates a Recordset of this type.
So in this example, it will be a DAO.Recordset.
Now back to your question:
You declare your Recordset without specifying the type.
So if the first reference in your Access database is ADO, Access will create an ADODB.Recordset.
Then you open it with a DAO method, which expects a DAO.Recordset, and that's why you get the error.
There are two ways to solve your problem:

*

*Make sure that your Access database only has a reference to ADO or DAO (but not both), then you don't need to specify the type of the recordset.

*If you really need both references, always declare your recordsets as DAO.Recordset or ADODB.Recordset to make sure that it's really of the type that your code expects.

A: Examples here, for all permutations of opening a "Recordset":
http://www.vbexplorer.com/VBExplorer/vb_feature/june2000/Database_Beginner_ADO_DAO.asp
The easiest way is to use DAO on the current database. My VBA is a little rusty, but...
Dim db as DAO.Database
Dim rs as DAO.Recordset
Set db = CurrentDB
Set rs = DB.OpenRecordset("table or query name")

For ADO:
Dim rs As New ADODB.Recordset
rs.Open "tblPeople", CurrentProject.Connection, adOpenDynamic

A: Decide if you want to use ADO or DAO? Here is a DAO (more native to Access/Jet) example
dim wrk as DAO.Workspace
dim db as DAO.Database

set wrk = DBEngine.Workspaces(0)
set db = wrk.OpenDatabase(CurrentDb.Name)
Dim rsSystem as DAO.Recordset

Dim sSQL As String

sSQL = "SELECT * FROM Table"
Set rsSystem = db.OpenRecordSet(sSQL, dbOpenDynaset)

exitRoutine:
If Not (db Is Nothing) Then
     db.Close
     Set db = Nothing
End If
Set wrk = Nothing

Not sure what you want to do with this recordset.

A: Dim rsSystem As Recordset

Both the ADO and DAO object models include Recordset objects.  You can't interchange them.
Since you didn't specify which you wanted, yours could be an ADO Recordset ... which would account for the type mismatch error on the OpenRecordset method.
Set rsSystem = CurrentDB.OpenRecordset(sSQL)

That method returns a DAO Recordset, so first declare rsSytem as such.
Dim rsSystem As DAO.Recordset

A: "Table" is a reserved word in SQL. If you must name your table "table", then enclose it in square brackets: "SELECT * FROM [Table]".


text:
Q: Navigation bar not to be seen when UITableViewController is pushed onto the navigation stack Code in the view controller which is currently on a navigation controller stack. Now I want to push a UITableViewContoller onto the navigation stack. I'm using the following code:
let destinationVC = self.storyboard?.instantiateViewController(withIdentifier: "formTableVC") as! FormTableViewController

self.navigationController?.pushViewController(destinationVC, animated: true)

The UITableViewContoller shows up but the navigation bar is not shown. How to solve this issue? I want the design which has been carried forward to all the previous view controllers to be shown in the UITableViewContoller's navigation bar as well. Any help would be greatly appreciated. thank you.

A: Add the following code to viewDidLoad function of UITableViewContoller(FormTableViewController)
 Class
self.navigationController?.setNavigationBarHidden(false, animated: false)


text:
Q: When calculating how many days between 2 dates, should you include both dates in the count, or neither, or 1? I am trying to make an algorithm that counts the days between two dates, e.g. between 3/1/2012 and 3/2/2012.
What is the correct answer, or the most popular choice? Should be the one I use?
In this case, if I don't include both dates I am comparing, the days are 0; if I include one of them, the days are 1; if I include both, the days are 2.

A: I would answer 1 because they are one day apart.  There isn't a right answer to this though.  It depends on the requirements for what you want to accomplish.

A: I think it is a question of terminology and context.
If days between excludes the bounds, then the days between the two dates would be 0. Whereever this may be needed.
Date difference, i.e. how many days do I need to add to the start date to reach the end date: 1.
Or a date interval, including the bounds, e.g. how many leave days do I have from a start to an end date? Here the answer is 2.

A: I think the crux of the dilemma is that you've named the operation "calculating how many days between two dates".  Clearly there are zero days between 3/1/12 and 3/2/12, but that more likely means that you've named the calculation wrong rather than done the wrong calculation.
Date arithmetic is notoriously tricky because of all the exceptions, so you really have to be rigorous in defining your requirements.  For example, what does "now minus one day" translate into?  You might say it means whatever time it was 24 hours ago, but I think that would be wrong in most applications.  True, most days have 24 hours, but with daylight saving time one day has 23 hours and one day has 25 hours. I thank if it is noon on Sunday then now minus one day means noon on Saturday regardless of how many hours ago that was. I could go on with leap seconds and all the trouble they bring, as well as ensuring all the arithmetic identities and properties hold, but all of this is probably more work than you want to do.
Generally, when doing calendar date arithmetic people are interested in the "difference between dates".  You can visualize this by imagining a paper calendar with the dates printed on it and putting a coin or stone or other marker on the starting date.  If you are only allowed to move the marker to the immediately following date, how many moves would it take you to get to the ending date?  That is the difference between the two dates in days.
One other practical consideration, though, is whether your application really includes the end date.  It is typical for insurance contracts, for example, to not include the end date.  Policies expire at 12:01 am on the end date.  If you buy a policy that expires tomorrow, it's good for less than a day.  On the other hand, in California, a "3 day notice to pay rent or quit" eviction notice gives you more than 3 days to get out. You have until the end of the third business day after the notice is served to pay the rent.  So Wednesday + 3 days is actually Monday unless Monday is a holiday, in which case it is Tuesday and either way you get the whole final day, so a landlord cannot proceed until today > Wednesday + 3 days, i.e Tuesday or Wednesday.  So it's not a straightforward calculation.
The good news is that because it comes up so often, there are libraries you can use to do the calculations and real life situations have reasonably well defined how they want date calculations done in order to clear up just these sorts of confusions.
So you really need to do your homework and correctly specify what interval you are talking about.

A: First what would make sense in your application if both dates were the same day? In my opinion the obvious answer is 0 and if that's your answer as well then the logical conclusion is to map dates that differ by one day to 1 and not 2. If you map dates that differ by a day to 2 then you have a gap and there is no way to map dates that don't coincide to 1. From a mathematical perspective things feel more consistent if there are no gaps.

A: Ultimately, the correct answer to this is whatever your business requirements state.
However, when dealing with dates and time spans between dates, one generic way of looking at it to assume that any date that is expressed solely as a date (i.e. without a time portion) is to implicitly add 00:00 to the end of the date (midnight).
Now, calculate how many minutes of difference there is between the two date/times.  So using your example (and I'm assuming US Date format here), how many minutes to you have to add, one at a time, to 2/1/2012 00:00 before you reach 3/1/2012 00:00 ?
Once you've done that, convert your minutes to hours, then to day (divide by 60, then divide result by 24) and you'll have your number of days between the two dates.
Using this, it turns out there's 1 day between 2/1/2012 00:00 and 3/1/2012 00:00 which seems to be both logical and in accordance with the general thinking of most people here and those who design well used functions in this area (i.e. Java's java.util.Date or .NET's System.DateTime etc.)

A: Both Dates, because that is what the users expect (in most cases)
I have worked on a few projects that had to work with logic surrounding dates, and expiration of entities. And there are some pitfalls.
The nature of those pitfalls is that what makes sense to a programmer isn't necessarily what makes sense to the people using the application.
People in the business would normally say stuff like, this thing is active from the 1. to the 31. of July. Now what they mean is that both dates are are included, i.e. it should be active for 31 days, not 30. But that defies normal arithmetic rules.
So if you take the question from the end users point of view, then in my experience the answer should be that you need to include both dates when calculating the number of days.
A few examples from my work experience:
I worked at creating an online job board, and we had plenty of problems with end dates for some entity types (expiration for a job, a subscription, etc). These would be specified as the last day this entity was still valid, which is what got stored in the database. But what made sense in the code would be to have the exact time when the entity would change state, i.e. at 00:00 the following date. That lead to very complex domain logic.
At some point, I refactored the entire system, adding one day to every EndDate in the database, and then moved the logic to the presentation layer, specifying that the actual date presented to the user should be the day preceding the one in the database. This lead to much, much cleaner domain logic regarding item expiration.
When I did the next project I worked with where date/entity expiration logic was important, I created a specific Date data type to encompass these rules, including overloading comparison operators with the build in DateTime class, arithmetic operators, etc. This lead to even simpler code, as it much better reflected the domain model, and the requirements for the presentation layer to subtract one day from all end days was removed, also removing the risk that someone would forget to implement this.

A: You have to consider the context, if my working schedule is from monday to friday my boss will be a bit displeased if I only show up for 4 days.
That's because in this context, monday doesn't only stand for monday but for monday 8:30  and friday stands for friday 17:00.

A: The number of days ND between one date D1 and another date D2 is such that:
ND = D2 - D1

or:
D1 + ND = D2

A: It depends a lot on context, but in my opinion the obvious answer is to include 1 of the dates in the count.
Let's assume you count neither. And also let's assume there's an application that uses your algorithm to determine the difference of 2 dates typed by the user. In this case, the difference between 3/1/2012 and 3/2/2012 is 0. Is it then ok for the user to assume that the 2 dates are equal ? Because that's what 0 suggests: no difference between them -->> they're equal. It's probably wrong...
Let's then assume you count both. In this case, the difference will never be less than 2. Are there 2 days between 3/1/2012 and 3/2/2012 ? Certainly not. What about between 3/1/2012 and 3/1/2012 ? Again: no.
Given the fact that you only have dates as input and no time, I would do the algorithm like this:

*

*if date 1 is equal to date 2, then the answer is 0

*if date 1 is different than date 2, then the answer is the number of days between them + 1 (the "+ 1" means than one of the date is included in the count).

As I said in the beginning: this ultimately depends on your business requirements.


text:
Q: Convert static files into MySQL entries I am converting about 4000 text files that contain HTML into MySQL database entries. Seems like an easy way to do this would be to add a couple lines to the HTML to make them appear as XML files, then XSLT the XML into MySQL INSERT statements. (Building a CSV would also work, but less optimal IMHO). I've tried doing this but am having little luck getting my XSL to play nice.
I'm on a Windoze box but can SSH into my webhost and run PHP, maybe Perl. Would love to automate this as much as possible. I can build a list of the files and feed that into a script easily enough.
Filename pattern: ab12345.html (numeric portion varies from 3-6 digits)
Filename content sample--this is the entirety of the file, there are not HTML footers/headers:

What does error note "90210 Cannot Do This Thing" mean?

This error means your McWhopper drive is frazzled. Read me the number off the modem--thats the little boxy thing attached to the big boxy thing--thanks.

ab90210

MySQL columns and how I'd like them to map back to the content above
EntryID = auto increment
title = contents of #abEntryTitleText
content = contents of #abEntryParagraph
lastupdated = curdate
related = "1"
visible = "1"
sortorder = "0"
userid = "1"
views = "0"
posvotes = "1"
negvotes = "0"
score = null
emailed = null
detectrelated = "1"
metakeywords = null
metadescription = contents of #abEntryDocumentNumber
startdate = curdate
enableexpiry = "0"
expirydate = null
featured = "0"
workflowstatus = "auto_approved"

XSL that I've tried:
<xsl:transform version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform ">
<xsl:output method="html" indent="no"/>
<xsl:template match="/"><xsl:apply-templates/></xsl:template>
<xsl:template match="content">
<xsl:text>INSERT INTO questions (approved, title, description, publishDate) VALUES </xsl:text><xsl:text>(1, </xsl:text><xsl:value-of select="id(abEntryTitleText)"/><xsl:text>, </xsl:text>
<xsl:copy-of select="node()|@*"/>
<xsl:text>, </xsl:text>TODAY<xsl:text>,1, 1)</xsl:text>
</xsl:template>
</xsl:transform>

A: I'm not familiar with xsl, so I would tackle this problem using php's DOM.
IIRC it could parse html without being proper xml.
Tutortial at www.phpro.org

A: The xslt you are looking for to create an insert statement from the
 element would be
<?xml version="1.0" encoding="utf-8"?>
<xsl:stylesheet version="1.0"
    xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
    xmlns:msxsl="urn:schemas-microsoft-com:xslt"
    exclude-result-prefixes="msxsl">

    <xsl:output method="text" indent="no"/>

    <xsl:template match="div[@class='abEntry']">
INSERT INTO questions (approved, title, content, metadescription, publishDate)
VALUES (1, '<xsl:value-of select="normalize-space(*/div[@id='abEntryTitleText']/text())" />', '<xsl:value-of select="normalize-space(div[@class='abEntryParagraph']/text())" />', '<xsl:value-of select="normalize-space(div[@class='abEntryDocumentNumber']/text())" />', TODAY)
    </xsl:template>

</xsl:stylesheet>

You can modify this further to include the other constant column values.
After that you obviously need a script or application to run the xstl on each file. I could write something quickly in .Net if you like, but if you have some other tools/scripting capability handy it might be quicker to use that.


text:
Q: Slim DI container My Slim 3 application index structure is:

// Instantiate the app
$config = require __DIR__ . '/../src/config.php';
$app = new \Slim\App($config);

// Set up dependencies
require __DIR__ . '/../src/dependencies.php';

// Register middleware
require __DIR__ . '/../src/middleware.php';

// Register routes
require __DIR__ . '/../src/routes.php';

// Run app
$app->run();

I have separate worker.php file which is executed through bash script and  this file running non-stop in background ( listens for some events).
How can I inject services in my worker.php file which is not part of Slim app or $container from dependencies.php , for example i want to use Monolog logger.
dependencies:
$container = $app->getContainer();

/**@var \App\model\Model access to Model methods */
$model = new \App\model\Loan($app->getContainer()->get('settings')['db']);

$container['logger'] = function ($c) {
    $settings = $c->get('settings')['logger'];
    $logger = new Monolog\Logger($settings['name']);
    $logger->pushProcessor(new Monolog\Processor\UidProcessor());
    $logger->pushHandler(new Monolog\Handler\StreamHandler($settings['path'], Monolog\Logger::DEBUG));
    return $logger;
};

A: Easiest way is to use the same DI Container in your worker.php
Reference:
https://github.com/slimphp/Slim/blob/3.x/Slim/Container.php
$config = require __DIR__ . '/../src/config.php';
$container = new \Slim\Container($config);
require __DIR__ . '/../src/dependencies.php';

A: You Settings

return [
    'settings' => [
        'displayErrorDetails' => true,
        // 'addContentLengthHeader' => false, // Allow the web server to send the content-length header

        // Monolog settings
        'logger' => [
            'name' => 'slim-app',
            'path' => __DIR__ . '/../logs/app.log',
            'level' => \Monolog\Logger::DEBUG,
        ],

    ],
];

in you dependenices.
$container['logger'] = function ($c) {
    $settings = $c->get('settings')['logger'];
    $logger = new Monolog\Logger($settings['name']);
    $logger->pushProcessor(new Monolog\Processor\UidProcessor());
    $logger->pushHandler(new Monolog\Handler\StreamHandler($settings['path'], Monolog\Logger::DEBUG));
    return $logger;
  };

A: You can achieve this with Monolog-Cascade as followed:
In dependencies:
// Configure Monolog with Cascade
$container['logger'] = function ($c) {
    Cascade::loadConfigFromArray($c->get('settings')['loggerConfig']);
    return Cascade::logger('logger_name_here');
};

Then in your config file (example with 2 handlers):
// Monolog-Cascade settings
    'loggerConfig' => [
        'handlers' => [
            // Stdout handler
            'console' => [
                'class' => 'Monolog\Handler\StreamHandler',
                'stream' => 'php://stdout',
                'level' => 'DEBUG'
            ],
            // File handler
            'file' => [
                'class' => 'Monolog\Handler\StreamHandler',
                'stream' => __DIR__.'/../../logs/hello.log',
                'level' => 'INFO'
            ]
        ],
        'loggers' => [
            'logger_name_here' => [
                'handlers' => ['console', 'file']
            ]
        ]
    ]

You can add as many loggers, handlers, formatters, processors, etc. as you want in the config. Cascade will set up everything for you.
[Disclaimer]: I'm the main contributor of Monolog-Cascade


text:
Q: Loading texture coords for OBJMesh in DirectX9/C++ I'm trying to get textures working on my OBJMesh loader. So far, I have looked at some online tutorials on how to do this and the most obvious example is the cube/box example which I understood. But I came across this problem where a vertex may use/have more than 1 texture coords.
For example:
f 711/1/1 712/2/2 709/3/3
f 711/9/1 704/10/9 712/11/2

As you can see, the index vertex number 711 is using texture coords number 1 and 9 and index vertex number 712 uses texture coords number 2 and 11. So my question is how do I get it to work with multiple texture coords? Is there some kind of buffer I can use like the vertex buffer and indices buffer?
I am using indices for this and I have the following vertex declarations:
D3DVERTEXELEMENT9 vertexElement[] = {   {0, 0, D3DDECLTYPE_FLOAT3, D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_POSITION, 0},
                                        {0, 12, D3DDECLTYPE_FLOAT2, D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_TEXCOORD, 0},
                                        D3DDECL_END()};

device->CreateVertexDeclaration(vertexElement, &vertexDec);

And my here's my vertex structure:
struct VERTEX{
    D3DXVECTOR3 position;
    D3DXVECTOR2 uv;

    D3DCOLOR color;
};

not too sure what other code to show here, but if i'm missing thing or you guys need to see something to help me, let me know.
Thanks
EDIT: would it be better if I use FVF instead of vertex declarations?

A: With DX9, you need to un-instantiate positions with split normal and texture coordinates.
Here a sample code to do it :
#include <array>
#include <vector>
#include <utility>
#include <tuple>
#include <map>

struct Vec3f { /* put your beloved implementation here */ };
struct Vec2f { /* put your beloved implementation here */ };

// imagine your obj loaded as these set of vectors :

// the vertices separate values
using Positions = std::vector<Vec3f>;
using Normals = std::vector<Vec3f>;
using Texcoords = std::vector<Vec2f>;

// and faces information
struct VertexTriplet {
    int _pos;
    int _normal;
    int _texcoord;
    friend bool operator< ( VertexTriplet const & a, VertexTriplet const & b ) {
        return    a._pos < b._pos
               || ( a._pos == b._pos && a._normal < b._normal )
               || ( a._pos == b._pos && a._normal == b._normal && a._texcoord < b._texcoord );
    }
};

using Triangle = std::array<VertexTriplet,3>;
using Faces = std::vector<Triangle>;

// imagine your GPU friendly geometry as these two vectors
using Vertex = std::tuple<Vec3f,Vec3f,Vec2f>;
using Index = unsigned int;

using VertexBuffer = std::vector<Vertex>;
using IndexBuffer = std::vector<Index>;

using GpuObject = std::pair<VertexBuffer,IndexBuffer>;
// you can now implement the conversion :
GpuObject Convert( Positions const & positions, Normals const & normals, Texcoords const & texcoords, Faces const & faces ) {
    GpuObject result;

    // first, we create unique index for each existing triplet
    auto & indexBuffer = result.second;
    indexBuffer.reserve( faces.size() * 3 );

    std::map<VertexTriplet, Index> remap;
    Index freeIndex = 0;
    for ( auto & triangle : faces ) {
        for ( auto & vertex : triangle ) {
            auto it = remap.find( vertex );
            if ( it != remap.end() ) { // index already exists
                indexBuffer.push_back( it->second );
            } else { // create new index
                indexBuffer.push_back( freeIndex );
                remap[vertex] = freeIndex++;
            }
        }
    }

    // we now have the index buffer, we can fill the vertex buffer
    // we start by reversing the mapping from triplet to index
    // so wee can fill the memory with monotonic increasing address
    std::map< Index, VertexTriplet > reverseRemap;
    for ( auto & pair : remap ) {
        reverseRemap[pair.second] = pair.first;
    }

    auto & vertexBuffer = result.first;
    vertexBuffer.reserve( reverseRemap.size() );
    for ( auto & pair : reverseRemap ) {
        auto & triplet = pair.second;
        vertexBuffer.push_back( std::make_tuple( positions[triplet.m_pos], normals[triplet.m_normal], texcoords[triplet.m_texcoord] ) );
    }
    return result;
}
int main() {
    // read your obj file into these four vectors
    Positions positions;
    Normals normals;
    Texcoords texcoords;
    Faces faces;

    /* read the obj here */

    // then convert
    auto gpuObject = Convert( positions, normals, texcoords, faces );

    return 0;
}

Of course, we may imagine post processing of the index and vertex buffer to optimise performance. packing data to smaller type than float and unsigned, optimisation of the gpu post transform cache, ...
With DX10/11 we may imagine use the Faces vector as a vertex buffer providing three indices with the input layout ( vertex declaration new name ) and passing the positions, normals and texcoords as three shader resource view of buffer type to the vertex shader and perform the lookup directly. It should not be so suboptimal compared to an old school vertices interleaving but you should stick to the old school solution.


text:
Q: tkinter.insert to print values in next column I am having a dataframe with 6 columns, what i need from tkinter is to print data in next column everytime when first loop iterate. For eg:
xls = pd.read_excel(file)
df = pd.DataFrame(xls)

df_col = df.columns.values

tree["columns"]=(df_col)
counter = len(df)

for x in range(len(df_col)):
    tree.column(x, width=100 )
    tree.heading(x, text=df_col[x])
    for i in range(counter):
        tree.insert("" , 0, values=(df[df_col[x]][i]))

Desired Output:

What im getting from my above code is:

Any help would be appreciated. Thanks in advance.


text:
Q: Ring solution to redirect missing trailing slash urls The behavior I'm trying to implement using Ring routes is approximately described in this question.
Basically I have some URLs that end with trailing slashes, and I'm trying to create a middleware that will redirect from e.g example.com/foo to example.com/foo/ if and only if /foo/ is a valid URL and /foo is not.
I'm currently using this middleware
(defn good-response? [resp]
  (and resp (not= (:status resp) 404)))

(defn wrap-slash [handler]
  (fn [{:keys [uri] :as req}]
    (let [resp (handler req)]
      (if (or (good-response? resp) (.endsWith "/" uri))
        resp
        (let [added-slash (str uri "/")]
          (if (good-response? (handler (assoc req :uri added-slash)))
            (redirect added-slash)
            resp))))))

Which does almost everything it should: It redirects from /foo to /foo/ iff /foo/ exists and /foo does not.
My concern is that this solution will call (handler req) at least twice - once on the request for /foo and again when the client requests the redirected URL. It's not a problem now, but I could imagine it being painful to double the response time for some slow page with hundreds of DB queries or some such thing.
Is there a way to simply check if a handler exists for a given URL, without calling that handler? Could we avoid the problem entirely by say, making (:body request) lazy?

A: There is no general way in ring to check for "is this a valid uri?" without calling the whole stack handler with that uri, since there is no central list of uris, but even then handlers can decline to handle a request for any reason at all, not just based on its uri.
I would probably go the other way around; for all handlers that actually need this behavior, make them catch the "unslashed" version too and redirect then if needed/useful.
Or use a separate handler/middleware if the url should ALWAYS end in a slash given some rules and let the redirect fail if it doesn't match. Either way the end user will get a 404, so who cares, really?
But the most specific handlers are usually in the best position to make the decision.
Oh, and you probably don't just forward a POST to some other URI.

A: I fixed your code.
(defn good-response? [resp]
  (and resp (not= (:status resp) 404)))

(defn wrap-slash [handler]
  (fn [{:keys [uri] :as req}]
    (let [resp (handler req)]
      (if (or (good-response? resp) (.endsWith uri "/"))
        resp
        (let [added-slash (str uri "/")]
          (if (good-response? (handler (-> req
                                           (assoc :uri added-slash)
                                           (assoc :path-info added-slash))))
            (redirect added-slash)
            resp))))))

you need to change :path-info.