问:
Compound nodes overlap while using grid layout in cytoscape.js
I am using cytoscape.js for my visualization project in which I have to show a Hierarchical structure with compound nodes.

So I initially used Cose-Bilkent layout which worked like a charm but the requirement is that all the child nodes of a parent must be in a single row. So I tried to tweak around a bit but couldn't get the exact result.

Then I tried to use grid layout by giving hardcoded row and column numbers and I got the exact result but as my data is dynamic I realized its difficult to assign row numbers and column numbers on my own.

Here is the data I used,

```<code>elements: [ // list of graph elements to start with
            { // node a
                data: { id: 'X1', label: 'X1'}
            },
            {
                data: { id: 'X2', label: 'X2'}
            },
            {
                data: { id: 'X3', label: 'X3'}
            },
            {
                data: { id: 'X4', label: 'X4'}
            },
            {
                data: { id: 'X5', label: 'X5'}
            },
            {
                data: { id: 'X6', label: 'X6'}
            },
            {
                data: { id: 'X7', label: 'X7'}
            },
            {
                data: { id: 'X8', label: 'X8'}
            },
            {
                data: { id: 'X9', label: 'X9'}
            },
            {
                  data: { id: 'X10', label: 'X10'}
            },
            {
                data: { id: 'X1e1',label: 'e1', parent: 'X1', row: '1' ,col: '1'}
            },
            {
                data: { id: 'X1e5',label: 'e5', parent: 'X1', row: '1',col: '2'}
            },
            {
                data: { id: 'X1e6',label: 'e6', parent: 'X1', row: '1',col: '3'}
            },
            {
                data: { id: 'X2e2',label: 'e2', parent: 'X2', row: '3',col: '1'}
            },
            {
                data: { id: 'X2e3',label: 'e3', parent: 'X2', row: '3',col: '2'}
             },
            {
                data: { id: 'X3e4',label: 'e4', parent: 'X3', row: '4',col: '1'}
            },
            {
                data: { id: 'X4e5',label: 'e5', parent: 'X4', row: '2',col: '1'}
            },
            {
                data: { id: 'X4e6',label: 'e6', parent: 'X4', row: '2',col: '2'}
            },
            {
                data: { id: 'X5e7',label: 'e7', parent: 'X5', row: '7',col: '1'}
            },
            {
                data: { id: 'X6e8',label: 'e8', parent: 'X6', row: '5',col: '1'}
            },
            {
                data: { id: 'X6e9',label: 'e9', parent: 'X6', row: '5',col: '2'}
            },
            {
                data: { id: 'X7e10',label: 'e10', parent: 'X7', row: '7',col: '2'}
            },
            {
                data: { id: 'X7e11',label: 'e11', parent: 'X7', row: '7',col: '3'}
            },
            {
                data: { id: 'X7e12',label: 'e12', parent: 'X7', row: '7',col: '4'}
            },
            {
                data: { id: 'X8e13',label: 'e13', parent: 'X8', row: '6',col: '1'}
            },
            {
                data: { id: 'X8e14',label: 'e14', parent: 'X8', row: '6',col: '2'}
            },
            {
                data: { id: 'X8e15',label: 'e15', parent: 'X8', row: '6',col: '3'}
            },
            {
                data: { id: 'X8e16',label: 'e16', parent: 'X8', row: '6',col: '4'}
            },
            {
                data: { id: 'X9e17',label: 'e17', parent: 'X9', row: '8',col: '1'}
            },
            {
                data: { id: 'X10e18',label: 'e18', parent: 'X10', row: '8',col: '2'}
            },
            {
                data: { id: 'X1e5X4e5', source:'X1e5', target:'X4e5'}
            },
            {
                data: { id: 'X1e6X4e6', source:'X1e6', target:'X4e6'}
            },
            {
                data: { id: 'X1e1X2', source:'X1e1', target:'X2'}
            },
            {
                data: { id: 'X2e3X3', source:'X2e3', target:'X3'}
            },
            {
                data: { id: 'X4e5X5', source:'X4e5', target:'X5'}
            },
            {
                data: { id: 'X4e6X6', source:'X4e6', target:'X6'}
            },
            {
                data: { id: 'X6X8e16', source:'X6', target:'X8e16'}
            },
            {
                data: { id: 'X6e9X8', source:'X6e9', target:'X8'}
            },
            {
                data: { id: 'X6e8X7', source:'X6e8', target:'X7'}
            },
            {
                data: { id: 'X6X7e12', source:'X6', target:'X7e12'}
            }
        ]
</code>```

and layout

```<code>layout:{
            name: 'grid',
            fit: true,
            position: function( node ){ return {row:node.data('row'), col:node.data('col') }}
        }
</code>```

And here is the result I got(and also expected) by setting manual rows and columns

Any help would be appreciated. Thanks

答:
Well there are two extensions, which would achieve just what you need:

even-parents

no-overlap

Coincidentally, both come from the same person, so this should not be a problem at all, all you have to do from there is to apply the right styles for the application to look like your example:

document.addEventListener("DOMContentLoaded", function() {
  var cy = (window.cy = cytoscape({
    container: document.getElementById("cy"),
    layout: {
      name: "evenParent"
    },
    style: [{
        selector: "node",
        style: {
          "content": "data(id)",
          "background-color": "#ad1a66"
        }
      },
      {
        selector: ":parent",
        style: {
          "background-opacity": 0.333
        }
      },
      {
        selector: "edge",
        style: {
          width: 3,
          "line-color": "#ad1a66"
        }
      },
      {
        selector: "edge.meta",
        style: {
          width: 2,
          "line-color": "red"
        }
      },
      {
        selector: ":selected",
        style: {
          "border-width": 3,
          "border-color": "#DAA520"
        }
      }
    ],
    elements: {
      nodes: [{
          data: {
            id: "Jerry",
            name: "Jerry"
          }
        },
        {
          data: {
            id: "Elaine",
            name: "Elaine"
          }
        },
        {
          data: {
            id: "Kramer",
            name: "Kramer"
          }
        },
        {
          data: {
            id: "George",
            name: "George"
          }
        },
        {
          data: {
            id: "Martin",
            name: "Martin"
          }
        },
        {
          data: {
            id: "Philippe",
            name: "Philippe"
          }
        },
        {
          data: {
            id: "Louis",
            name: "Louis"
          }
        },
        {
          data: {
            id: "Genevieve",
            name: "Genevieve"
          }
        },
        {
          data: {
            id: "Leo",
            name: "Leo"
          }
        },
        {
          data: {
            id: "Larry",
            name: "Larry"
          }
        },
        {
          data: {
            id: "Logaina",
            name: "Logaina"
          }
        }
      ],
      edges: [{
          data: {
            source: "Jerry",
            target: "Elaine"
          }
        },
        {
          data: {
            source: "Jerry",
            target: "Kramer"
          }
        },
        {
          data: {
            source: "Jerry",
            target: "George"
          }
        },
        {
          data: {
            source: "Elaine",
            target: "Martin"
          }
        },
        {
          data: {
            source: "Elaine",
            target: "Philippe"
          }
        },
        {
          data: {
            source: "Elaine",
            target: "Louis"
          }
        },
        {
          data: {
            source: "Elaine",
            target: "Genevieve"
          }
        },
        {
          data: {
            source: "Elaine",
            target: "Leo"
          }
        },
        {
          data: {
            source: "Kramer",
            target: "Larry"
          }
        },
        {
          data: {
            source: "Kramer",
            target: "Logaina"
          }
        }
      ]
    }
  }));

  // demo your collection ext
  cy.nodes().noOverlap({
    padding: 5
  });
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>body {
  font: 14px helvetica neue, helvetica, arial, sans-serif;
}

#cy {
  height: 100%;
  width: 100%;
  position: absolute;
  left: 0;
  top: 0;
}</code>```

```

Body:
I am using cytoscape.js for my visualization project in which I have to show a Hierarchical structure with compound nodes.

So I initially used Cose-Bilkent layout which worked like a charm but the requirement is that all the child nodes of a parent must be in a single row. So I tried to tweak around a bit but couldn't get the exact result.

Then I tried to use grid layout by giving hardcoded row and column numbers and I got the exact result but as my data is dynamic I realized its difficult to assign row numbers and column numbers on my own.

Here is the data I used,

elements: [ // list of graph elements to start with
            { // node a
                data: { id: 'X1', label: 'X1'}
            },
            {
                data: { id: 'X2', label: 'X2'}
            },
            {
                data: { id: 'X3', label: 'X3'}
            },
            {
                data: { id: 'X4', label: 'X4'}
            },
            {
                data: { id: 'X5', label: 'X5'}
            },
            {
                data: { id: 'X6', label: 'X6'}
            },
            {
                data: { id: 'X7', label: 'X7'}
            },
            {
                data: { id: 'X8', label: 'X8'}
            },
            {
                data: { id: 'X9', label: 'X9'}
            },
            {
                  data: { id: 'X10', label: 'X10'}
            },
            {
                data: { id: 'X1e1',label: 'e1', parent: 'X1', row: '1' ,col: '1'}
            },
            {
                data: { id: 'X1e5',label: 'e5', parent: 'X1', row: '1',col: '2'}
            },
            {
                data: { id: 'X1e6',label: 'e6', parent: 'X1', row: '1',col: '3'}
            },
            {
                data: { id: 'X2e2',label: 'e2', parent: 'X2', row: '3',col: '1'}
            },
            {
                data: { id: 'X2e3',label: 'e3', parent: 'X2', row: '3',col: '2'}
             },
            {
                data: { id: 'X3e4',label: 'e4', parent: 'X3', row: '4',col: '1'}
            },
            {
                data: { id: 'X4e5',label: 'e5', parent: 'X4', row: '2',col: '1'}
            },
            {
                data: { id: 'X4e6',label: 'e6', parent: 'X4', row: '2',col: '2'}
            },
            {
                data: { id: 'X5e7',label: 'e7', parent: 'X5', row: '7',col: '1'}
            },
            {
                data: { id: 'X6e8',label: 'e8', parent: 'X6', row: '5',col: '1'}
            },
            {
                data: { id: 'X6e9',label: 'e9', parent: 'X6', row: '5',col: '2'}
            },
            {
                data: { id: 'X7e10',label: 'e10', parent: 'X7', row: '7',col: '2'}
            },
            {
                data: { id: 'X7e11',label: 'e11', parent: 'X7', row: '7',col: '3'}
            },
            {
                data: { id: 'X7e12',label: 'e12', parent: 'X7', row: '7',col: '4'}
            },
            {
                data: { id: 'X8e13',label: 'e13', parent: 'X8', row: '6',col: '1'}
            },
            {
                data: { id: 'X8e14',label: 'e14', parent: 'X8', row: '6',col: '2'}
            },
            {
                data: { id: 'X8e15',label: 'e15', parent: 'X8', row: '6',col: '3'}
            },
            {
                data: { id: 'X8e16',label: 'e16', parent: 'X8', row: '6',col: '4'}
            },
            {
                data: { id: 'X9e17',label: 'e17', parent: 'X9', row: '8',col: '1'}
            },
            {
                data: { id: 'X10e18',label: 'e18', parent: 'X10', row: '8',col: '2'}
            },
            {
                data: { id: 'X1e5X4e5', source:'X1e5', target:'X4e5'}
            },
            {
                data: { id: 'X1e6X4e6', source:'X1e6', target:'X4e6'}
            },
            {
                data: { id: 'X1e1X2', source:'X1e1', target:'X2'}
            },
            {
                data: { id: 'X2e3X3', source:'X2e3', target:'X3'}
            },
            {
                data: { id: 'X4e5X5', source:'X4e5', target:'X5'}
            },
            {
                data: { id: 'X4e6X6', source:'X4e6', target:'X6'}
            },
            {
                data: { id: 'X6X8e16', source:'X6', target:'X8e16'}
            },
            {
                data: { id: 'X6e9X8', source:'X6e9', target:'X8'}
            },
            {
                data: { id: 'X6e8X7', source:'X6e8', target:'X7'}
            },
            {
                data: { id: 'X6X7e12', source:'X6', target:'X7e12'}
            }
        ]

and layout

layout:{
            name: 'grid',
            fit: true,
            position: function( node ){ return {row:node.data('row'), col:node.data('col') }}
        }

And here is the result I got(and also expected) by setting manual rows and columns

Any help would be appreciated. Thanks

Body:
Well there are two extensions, which would achieve just what you need:

even-parents

no-overlap

Coincidentally, both come from the same person, so this should not be a problem at all, all you have to do from there is to apply the right styles for the application to look like your example:

document.addEventListener("DOMContentLoaded", function() {
  var cy = (window.cy = cytoscape({
    container: document.getElementById("cy"),
    layout: {
      name: "evenParent"
    },
    style: [{
        selector: "node",
        style: {
          "content": "data(id)",
          "background-color": "#ad1a66"
        }
      },
      {
        selector: ":parent",
        style: {
          "background-opacity": 0.333
        }
      },
      {
        selector: "edge",
        style: {
          width: 3,
          "line-color": "#ad1a66"
        }
      },
      {
        selector: "edge.meta",
        style: {
          width: 2,
          "line-color": "red"
        }
      },
      {
        selector: ":selected",
        style: {
          "border-width": 3,
          "border-color": "#DAA520"
        }
      }
    ],
    elements: {
      nodes: [{
          data: {
            id: "Jerry",
            name: "Jerry"
          }
        },
        {
          data: {
            id: "Elaine",
            name: "Elaine"
          }
        },
        {
          data: {
            id: "Kramer",
            name: "Kramer"
          }
        },
        {
          data: {
            id: "George",
            name: "George"
          }
        },
        {
          data: {
            id: "Martin",
            name: "Martin"
          }
        },
        {
          data: {
            id: "Philippe",
            name: "Philippe"
          }
        },
        {
          data: {
            id: "Louis",
            name: "Louis"
          }
        },
        {
          data: {
            id: "Genevieve",
            name: "Genevieve"
          }
        },
        {
          data: {
            id: "Leo",
            name: "Leo"
          }
        },
        {
          data: {
            id: "Larry",
            name: "Larry"
          }
        },
        {
          data: {
            id: "Logaina",
            name: "Logaina"
          }
        }
      ],
      edges: [{
          data: {
            source: "Jerry",
            target: "Elaine"
          }
        },
        {
          data: {
            source: "Jerry",
            target: "Kramer"
          }
        },
        {
          data: {
            source: "Jerry",
            target: "George"
          }
        },
        {
          data: {
            source: "Elaine",
            target: "Martin"
          }
        },
        {
          data: {
            source: "Elaine",
            target: "Philippe"
          }
        },
        {
          data: {
            source: "Elaine",
            target: "Louis"
          }
        },
        {
          data: {
            source: "Elaine",
            target: "Genevieve"
          }
        },
        {
          data: {
            source: "Elaine",
            target: "Leo"
          }
        },
        {
          data: {
            source: "Kramer",
            target: "Larry"
          }
        },
        {
          data: {
            source: "Kramer",
            target: "Logaina"
          }
        }
      ]
    }
  }));

  // demo your collection ext
  cy.nodes().noOverlap({
    padding: 5
  });
});

body {
  font: 14px helvetica neue, helvetica, arial, sans-serif;
}

#cy {
  height: 100%;
  width: 100%;
  position: absolute;
  left: 0;
  top: 0;
}

<html>

<head>
  <script src="https://unpkg.com/cytoscape/dist/cytoscape.min.js"></script>
  <script src="https://cdn.jsdelivr.net/npm/cytoscape-even-parent@1.1.1/cytoscape-even-parent.min.js"></script>
  <script src="https://cdn.jsdelivr.net/npm/cytoscape-no-overlap@1.0.1/cytoscape-no-overlap.min.js"></script>
</head>

<body>
  <div id="cy"></div>
</body>

</html>


来源: stackexchange

问:
I can not install my Android app to my phone
I am new in android app development.
I made an android app. When I run it from Android Studio to my phone it works perfectly.
Then I back it up to my SD card and try to install it and it gives me an  "Installation failed" message.
I tried using various phones but it didn't work.

What is the problem actually?
What should I do to install my app on other phones (regarding the SDK version)?

答: In the dialog Generate Signed Bundle or APK set checkbox V1 (Jar Signature) and V2 (Full APK Signature).

ContentLicense: CC BY-SA 4.0


问:
React useState hook event handler using initial state
I'm still getting my head around react hooks but struggling to see what I'm doing wrong here. I have a component for resizing panels, onmousedown of an edge I update a value on state then have an event handler for mousemove which uses this value however it doesn't seem to be updating after the value has changed.

Here is my code:

```<code>export default memo(() => {
  const [activePoint, setActivePoint] = useState(null); // initial is null

  const handleResize = () => {
    console.log(activePoint); // is null but should be 'top|bottom|left|right'
  };

  const resizerMouseDown = (e, point) => {
    setActivePoint(point); // setting state as 'top|bottom|left|right'
    window.addEventListener('mousemove', handleResize);
    window.addEventListener('mouseup', cleanup); // removed for clarity
  };

  return (
    <div className="interfaceResizeHandler">
      {resizePoints.map(point => (
        <div
          key={ point }
          className={ `interfaceResizeHandler__resizer interfaceResizeHandler__resizer--${ point }` }
          onMouseDown={ e => resizerMouseDown(e, point) }
        />
      ))}
    </div>
  );
});
</code>```

The problem is with the handleResize function, this should be using the latest version of activePoint which would be a string top|left|bottom|right but instead is null.

答:
You have access to current state from setter function, so you could make it:</p>

```<code>const handleResize = () => {
  setActivePoint(activePoint => {
    console.log(activePoint);
    return activePoint;
  })
};
</code>```

Body:
I'm still getting my head around react hooks but struggling to see what I'm doing wrong here. I have a component for resizing panels, onmousedown of an edge I update a value on state then have an event handler for mousemove which uses this value however it doesn't seem to be updating after the value has changed.

Here is my code:

export default memo(() => {
  const [activePoint, setActivePoint] = useState(null); // initial is null

  const handleResize = () => {
    console.log(activePoint); // is null but should be 'top|bottom|left|right'
  };

  const resizerMouseDown = (e, point) => {
    setActivePoint(point); // setting state as 'top|bottom|left|right'
    window.addEventListener('mousemove', handleResize);
    window.addEventListener('mouseup', cleanup); // removed for clarity
  };

  return (

      {resizePoints.map(point => (
        <div
          key={ point }
          className={ `interfaceResizeHandler__resizer interfaceResizeHandler__resizer--${ point }` }
          onMouseDown={ e => resizerMouseDown(e, point) }
        />
      ))}

  );
});

The problem is with the handleResize function, this should be using the latest version of activePoint which would be a string top|left|bottom|right but instead is null.

Body:
You have access to current state from setter function, so you could make it:

const handleResize = () => {
  setActivePoint(activePoint => {
    console.log(activePoint);
    return activePoint;
  })
};


问:
Sass reusable keyframes with mixins and functions
I have four keyframes that look very similiar. Can I do one mixin or function and use it instead of duplicating my code? Keyframes are something like:

```<code>@keyframes ComputerLogoOuterSquare {
  0% {
    transform: translate(0, 0);
  }

  12% {
    transform: translate(0.5%, 0.5%);
  }

  50% {
    transform: translate(0.5%, 0.5%);
  }

  62% {
    transform: translate(0, 0);
  }

  100% {
    transform: translate(0, 0);
  }
}
</code>```

I tried mixin but it throws an error:

```<code>@mixin logoAnimation($name, $value) {
  @keyframes $name {
  0% {
    transform: translate(0, 0);
  }

  12% {
    transform: translate($value, $value);
  }

  50% {
    transform: translate($value, $value);
  }

  62% {
    transform: translate(0, 0);
  }

  100% {
    transform: translate(0, 0);
  }
  }
}
</code>```

答:
use interpolation to use $name like

@keyframes #{$name}

Body:
I have four keyframes that look very similiar. Can I do one mixin or function and use it instead of duplicating my code? Keyframes are something like:

@keyframes ComputerLogoOuterSquare {
  0% {
    transform: translate(0, 0);
  }

  12% {
    transform: translate(0.5%, 0.5%);
  }

  50% {
    transform: translate(0.5%, 0.5%);
  }

  62% {
    transform: translate(0, 0);
  }

  100% {
    transform: translate(0, 0);
  }
}

I tried mixin but it throws an error:

@mixin logoAnimation($name, $value) {
  @keyframes $name {
  0% {
    transform: translate(0, 0);
  }

  12% {
    transform: translate($value, $value);
  }

  50% {
    transform: translate($value, $value);
  }

  62% {
    transform: translate(0, 0);
  }

  100% {
    transform: translate(0, 0);
  }
  }
}


问:
Java 8 alternative to Map.entry() for mapping values to new Map?
I got a solution to a problem I've been trying to fix for a long time.
Unfortunately, I cannot use the solution since the target java version is Java 8.

```<code>Map<List<String>, String> map = new HashMap<>();
    map.put(List.of("Los Angeles", "New York", "Chicago"), "USA");
    map.put(List.of("Toronto", "Vancover", "Montréal"), "Canada");

    Map<String, String> newMap = map.entrySet()
        .stream()
        .flatMap(entry -> entry.getKey()
            .stream()
            .map(city -> Map.entry(city, entry.getValue())))
        .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue)));
</code>```

This would return me a Map like: {New York=USA, Chicago=USA, Los Angeles=USA, Toronto=Canada}

Now my question, can I arrive at this result without using Map.entry(...) in Java 8?

答:
You can use</p>

```<code>.map(city -> new AbstractMap.SimpleEntry<>(city, entry.getValue())))
</code>```

Body:
I got a solution to a problem I've been trying to fix for a long time.
Unfortunately, I cannot use the solution since the target java version is Java 8.

Map<List<String>, String> map = new HashMap<>();
    map.put(List.of("Los Angeles", "New York", "Chicago"), "USA");
    map.put(List.of("Toronto", "Vancover", "Montréal"), "Canada");

    Map<String, String> newMap = map.entrySet()
        .stream()
        .flatMap(entry -> entry.getKey()
            .stream()
            .map(city -> Map.entry(city, entry.getValue())))
        .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue)));

This would return me a Map like: {New York=USA, Chicago=USA, Los Angeles=USA, Toronto=Canada}

Now my question, can I arrive at this result without using Map.entry(...) in Java 8?

Body:
You can use

.map(city -> new AbstractMap.SimpleEntry<>(city, entry.getValue())))


问:
How to present iOS UIActionSheet in Swift?
How can I present a UIActionSheet in Swift within an iOS app?

Here is my code for displaying a UIActionSheet:

```<code>@IBAction func downloadSheet(sender: AnyObject) {
    let optionMenu = UIAlertController(title: nil, message: "Choose Option", preferredStyle: .actionSheet)

    let saveAction = UIAlertAction(title: "Save", style: .default, handler: {
        (alert: UIAlertAction!) -> Void in
        println("Saved")
    })

    let deleteAction = UIAlertAction(title: "Delete", style: .default, handler: {
        (alert: UIAlertAction!) -> Void in
        println("Deleted")
    })

    let cancelAction = UIAlertAction(title: "Cancel", style: .cancel, handler: {
        (alert: UIAlertAction!) -> Void in
        println("Cancelled")
    })
    optionMenu.addAction(deleteAction)
    optionMenu.addAction(saveAction)
    optionMenu.addAction(cancelAction)
    self.presentViewController(optionMenu, animated: true, completion: nil)
}
</code>```

答:
Code for adding alerts to actionsheet in swift4

```<code>   *That means when we click actionsheet values(like edit/ delete..so on) it shows
   an alert option that is set with Yes or No option*

   class ViewController: UIViewController
   {

override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.
}

@IBAction func action_sheet1(_ sender: Any) {

    let action_sheet1 = UIAlertController(title: "Hi Bro", message: "Please Select an Option: ", preferredStyle: .actionSheet)

    action_sheet1.addAction(UIAlertAction(title: "Approve", style: .default , handler:{ (alert: UIAlertAction!) -> Void in
        print("User click Approve button")

        let alert = UIAlertController(title: "Approve", message: "Would you like to approve the file ", preferredStyle: UIAlertController.Style.alert)

        alert.addAction(UIAlertAction(title: "Yes", style: UIAlertAction.Style.default, handler: nil))

        alert.addAction(UIAlertAction(title: "No", style: UIAlertAction.Style.default, handler: nil))

        self.present(alert, animated: true, completion: nil)

        }))

    action_sheet1.addAction(UIAlertAction(title: "Edit", style: .default , handler:{ (alert: UIAlertAction!) -> Void in
        print("User click Edit button")

        let alert = UIAlertController(title: "Edit", message: "Would you like to edit the file ", preferredStyle: UIAlertController.Style.alert)

        alert.addAction(UIAlertAction(title: "Yes", style: UIAlertAction.Style.default, handler: nil))

        alert.addAction(UIAlertAction(title: "No", style: UIAlertAction.Style.default, handler: nil))

        self.present(alert, animated: true, completion: nil)

        }))

    action_sheet1.addAction(UIAlertAction(title: "Delete", style: .destructive , handler: { (alert: UIAlertAction!) -> Void in
        print("User click Delete button")

        let alert = UIAlertController(title: "Delete", message: "Would you like to delete the file permenently?", preferredStyle: UIAlertController.Style.alert)

        alert.addAction(UIAlertAction(title: "Yes", style: UIAlertAction.Style.default, handler: nil))

        alert.addAction(UIAlertAction(title: "No", style: UIAlertAction.Style.default, handler: nil))

        self.present(alert, animated: true, completion: nil)

        }))

    action_sheet1.addAction(UIAlertAction(title: "cancel", style: .cancel, handler:{ (alert: UIAlertAction!) -> Void in
         print("User click cancel button")

        let alert = UIAlertController(title: "Cancel", message: "Would you like to cancel?", preferredStyle: UIAlertController.Style.alert)

        alert.addAction(UIAlertAction(title: "Yes", style: UIAlertAction.Style.default, handler: nil))

        alert.addAction(UIAlertAction(title: "No", style: UIAlertAction.Style.default, handler: nil))

        self.present(alert, animated: true, completion: nil)

        }))

        self.present(action_sheet1, animated: true, completion: {
        print("completion block")
    })
}

}
</code>```

Body:
How can I present a UIActionSheet in Swift within an iOS app?

Here is my code for displaying a UIActionSheet:

@IBAction func downloadSheet(sender: AnyObject) {
    let optionMenu = UIAlertController(title: nil, message: "Choose Option", preferredStyle: .actionSheet)

    let saveAction = UIAlertAction(title: "Save", style: .default, handler: {
        (alert: UIAlertAction!) -> Void in
        println("Saved")
    })

    let deleteAction = UIAlertAction(title: "Delete", style: .default, handler: {
        (alert: UIAlertAction!) -> Void in
        println("Deleted")
    })

    let cancelAction = UIAlertAction(title: "Cancel", style: .cancel, handler: {
        (alert: UIAlertAction!) -> Void in
        println("Cancelled")
    })
    optionMenu.addAction(deleteAction)
    optionMenu.addAction(saveAction)
    optionMenu.addAction(cancelAction)
    self.presentViewController(optionMenu, animated: true, completion: nil)
}

Body:
Code for adding alerts to actionsheet in swift4

   *That means when we click actionsheet values(like edit/ delete..so on) it shows
   an alert option that is set with Yes or No option*

   class ViewController: UIViewController
   {

override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.
}

@IBAction func action_sheet1(_ sender: Any) {

    let action_sheet1 = UIAlertController(title: "Hi Bro", message: "Please Select an Option: ", preferredStyle: .actionSheet)

    action_sheet1.addAction(UIAlertAction(title: "Approve", style: .default , handler:{ (alert: UIAlertAction!) -> Void in
        print("User click Approve button")

        let alert = UIAlertController(title: "Approve", message: "Would you like to approve the file ", preferredStyle: UIAlertController.Style.alert)

        alert.addAction(UIAlertAction(title: "Yes", style: UIAlertAction.Style.default, handler: nil))

        alert.addAction(UIAlertAction(title: "No", style: UIAlertAction.Style.default, handler: nil))

        self.present(alert, animated: true, completion: nil)

        }))

    action_sheet1.addAction(UIAlertAction(title: "Edit", style: .default , handler:{ (alert: UIAlertAction!) -> Void in
        print("User click Edit button")

        let alert = UIAlertController(title: "Edit", message: "Would you like to edit the file ", preferredStyle: UIAlertController.Style.alert)

        alert.addAction(UIAlertAction(title: "Yes", style: UIAlertAction.Style.default, handler: nil))

        alert.addAction(UIAlertAction(title: "No", style: UIAlertAction.Style.default, handler: nil))

        self.present(alert, animated: true, completion: nil)

        }))

    action_sheet1.addAction(UIAlertAction(title: "Delete", style: .destructive , handler: { (alert: UIAlertAction!) -> Void in
        print("User click Delete button")

        let alert = UIAlertController(title: "Delete", message: "Would you like to delete the file permenently?", preferredStyle: UIAlertController.Style.alert)

        alert.addAction(UIAlertAction(title: "Yes", style: UIAlertAction.Style.default, handler: nil))

        alert.addAction(UIAlertAction(title: "No", style: UIAlertAction.Style.default, handler: nil))

        self.present(alert, animated: true, completion: nil)

        }))

    action_sheet1.addAction(UIAlertAction(title: "cancel", style: .cancel, handler:{ (alert: UIAlertAction!) -> Void in
         print("User click cancel button")

        let alert = UIAlertController(title: "Cancel", message: "Would you like to cancel?", preferredStyle: UIAlertController.Style.alert)

        alert.addAction(UIAlertAction(title: "Yes", style: UIAlertAction.Style.default, handler: nil))

        alert.addAction(UIAlertAction(title: "No", style: UIAlertAction.Style.default, handler: nil))

        self.present(alert, animated: true, completion: nil)

        }))

        self.present(action_sheet1, animated: true, completion: {
        print("completion block")
    })
}

}


问:
How to group factor levels?
I have a factor column with football position abbreviations, around 17 unique values with 220 observations. I want to have only three factor levels which encompass the 17 unique values.

```<code>levels(nfldraft$Pos) <- list(Linemen = c("C","OG","OT","TE","DT","DE"),
                             Small_Backs =  c("CB","WR","FS"),
                             Big_Backs = c("FB","ILB","OLB","P","QB",
                                           "RB","SS","WR"))
</code>```

is what I tried, printing nfldraft$Pos to the console shows 3 factor levels but all the values are either "Linemen" or "Small_Backs" and all the other ones are NA. Where am I going wrong?

答:
This is a good example of needing a fully reproducible example. Actually OP's code looks like it should work. Taking from @Hack-R's sample input:

```<code>my_example <- c("C","OG","OT","TE","DT","DE","CB","WR","FS",
                "FB","ILB","OLB","P","QB","RB","SS","WR")
</code>```

OP's original code works as-is:

```<code>nfldraft = list(Pos = factor(my_example))
levels(nfldraft$Pos) <- list(
  Linemen = c("C","OG","OT","TE","DT","DE"),
  Small_Backs =  c("CB","WR","FS"),
  Big_Backs = c("FB","ILB","OLB","P","QB","RB","SS","WR")
)
table(nfldraft$Pos)
#     Linemen Small_Backs   Big_Backs
#           6           2           9
</code>```

This is exactly in line with the documentation for how to use levels<-:

levels(x) <- value

value A valid value for levels(x)... For the factor method, a vector of character strings with length at least the number of levels of x, or a named list specifying how to rename the levels.

So it seems there's something else wrong with OP's input

Title: How to group factor levels?

Body:
I have a factor column with football position abbreviations, around 17 unique values with 220 observations. I want to have only three factor levels which encompass the 17 unique values.

levels(nfldraft$Pos) <- list(Linemen = c("C","OG","OT","TE","DT","DE"),
                             Small_Backs =  c("CB","WR","FS"),
                             Big_Backs = c("FB","ILB","OLB","P","QB",
                                           "RB","SS","WR"))

is what I tried, printing nfldraft$Pos to the console shows 3 factor levels but all the values are either "Linemen" or "Small_Backs" and all the other ones are NA. Where am I going wrong?

Body:
This is a good example of needing a fully reproducible example. Actually OP's code looks like it should work. Taking from @Hack-R's sample input:

my_example <- c("C","OG","OT","TE","DT","DE","CB","WR","FS",
                "FB","ILB","OLB","P","QB","RB","SS","WR")

OP's original code works as-is:

nfldraft = list(Pos = factor(my_example))
levels(nfldraft$Pos) <- list(
  Linemen = c("C","OG","OT","TE","DT","DE"),
  Small_Backs =  c("CB","WR","FS"),
  Big_Backs = c("FB","ILB","OLB","P","QB","RB","SS","WR")
)
table(nfldraft$Pos)
#     Linemen Small_Backs   Big_Backs
#           6           2           9

This is exactly in line with the documentation for how to use levels<-:

levels(x) <- value

value A valid value for levels(x)... For the factor method, a vector of character strings with length at least the number of levels of x, or a named list specifying how to rename the levels.

So it seems there's something else wrong with OP's input


问:
Converting logs to JSON format
```<code>    klog.Info("kube config file loaded ")
</code>```

is there a way to convert logs to JSON format in Go?
I tried ,

```<code>    klog.info(json.Marshal("kube config file loaded"))
</code>```

but did not got output in json.help me out

答: Klog doesnt support json formatting</p>

Title: Converting logs to JSON format

Body:
    klog.Info("kube config file loaded ")

is there a way to convert logs to JSON format in Go?
I tried ,

    klog.info(json.Marshal("kube config file loaded"))

but did not got output in json.help me out

Body: Klog doesnt support json formatting


问:
Ingress controller NodePort not reachable from outside
I have a cluster of 3 vm on which I install kubernetes and deployed some pods and services that I would like to be accessible from outside (my local pc for exemple)

I followed this tutorial https://kubernetes.github.io/ingress-nginx/deploy/#bare-metal to install my ingress controller.
I have created a service of type NodePort.
I have created a ingress that looks like this:

```<code>apiVersion: extensions/v1beta1
kind: Ingress
metadata:
  name: test-ingress
  annotations:
      kubernetes.io/ingress.class: nginx
spec:
  rules:
  - host: my.service.com
    http:
      paths:
      - path: /
        backend:
          serviceName: myservice
          servicePort: 9090
</code>```

kubectl get svc myservice gives me:

```<code>NAME        TYPE       CLUSTER-IP        EXTERNAL-IP   PORT(S)          AGE
myservice   NodePort   xxx.xxx.xxx.xxx   <none>        9090:31220/TCP   47m
</code>```

kubectl get ingress test-ingress gives me

```<code>NAME            HOSTS            ADDRESS          PORTS   AGE
test-ingress    my.service.com   xx.xxx.xxx.xxx   80      49m
</code>```

On my local computer I have added to /etc/hosts I have mapped the ip address of the ingress to the name my.service.com
When I try to ping my.service.com or directly the ip I go request timeout 100% packet loss.
I tried to reach my service visual interface with the web browser and it does not work either.

How can I investigate further why I can't access to my service from outside the cluster ?

答:
It is not possible to ping a Kubernetes service IP.

IP for services are virtual IP, thus they are not pingable.

To test you ingress, you should try to reach your service with curl instead.

Body:
I have a cluster of 3 vm on which I install kubernetes and deployed some pods and services that I would like to be accessible from outside (my local pc for exemple)

I followed this tutorial https://kubernetes.github.io/ingress-nginx/deploy/#bare-metal to install my ingress controller.
I have created a service of type NodePort.
I have created a ingress that looks like this:

apiVersion: extensions/v1beta1
kind: Ingress
metadata:
  name: test-ingress
  annotations:
      kubernetes.io/ingress.class: nginx
spec:
  rules:
  - host: my.service.com
    http:
      paths:
      - path: /
        backend:
          serviceName: myservice
          servicePort: 9090

kubectl get svc myservice gives me:

NAME        TYPE       CLUSTER-IP        EXTERNAL-IP   PORT(S)          AGE
myservice   NodePort   xxx.xxx.xxx.xxx   <none>        9090:31220/TCP   47m

kubectl get ingress test-ingress gives me

NAME            HOSTS            ADDRESS          PORTS   AGE
test-ingress    my.service.com   xx.xxx.xxx.xxx   80      49m

On my local computer I have added to /etc/hosts I have mapped the ip address of the ingress to the name my.service.com
When I try to ping my.service.com or directly the ip I go request timeout 100% packet loss.
I tried to reach my service visual interface with the web browser and it does not work either.

How can I investigate further why I can't access to my service from outside the cluster ?


问:
SwiftUI Binding to Computed Property?
I have two classes, one is the ContentView who is displaying the information from my data source. The data source is my CharacterRepository.

What I'm struggling with right now is making sure I always have a sorted list inside of my CharacterRepository.

Here's the code I have so far:

```<code>class CharacterRepository: ObservableObject {
    @Published public var characters = [Character(name: "Nott the Brave",
                                                  initiative: 23,
                                                  isActive: false),
                                        Character(name: "Caduceus Clay",
                                                  initiative: 2,
                                                  isActive: false),
                                        ...]
    ...
}
</code>```

and

```<code>struct InitiativeTrackerScreen: View {
    @EnvironmentObject var characterRepository: CharacterRepository

    var body: some View {
        NavigationView {
            VStack {
                List {
                    ForEach(characterRepository.characters) { entry in
                        CharacterListElement(character: entry)
                    }
    ...
</code>```

Now my intended approach would be something like turning the characters variable into a computed property that runs the "sorted by" function every time the get gets executed. Unfortunately, Binding to a computed property is not yet possible in SwiftUI (not sure, will it ever be?).

Can someone please help me with this? I don't want to go back to the old approach of sorting and redrawing every time something changes. That's not why I am using SwiftUI with ist sweet bindings.

答:
I like to answer by related question. For what do you ever need some binding to computed property? </p>

```<code>class CharacterRepository: ObservableObject {
    @Published public var characters = [Character(name: "Nott the Brave",
                                                  initiative: 23,
                                                  isActive: false),
                                        Character(name: "Caduceus Clay",
                                                  initiative: 2,
                                                  isActive: false),
                                        ...]
    ...
    var sorted: [Character] {
        characters.sorted()
    }
}
</code>```

<p>is all you need. </p>

Title: SwiftUI Binding to Computed Property?

Body:
I have two classes, one is the ContentView who is displaying the information from my data source. The data source is my CharacterRepository.

What I'm struggling with right now is making sure I always have a sorted list inside of my CharacterRepository.

Here's the code I have so far:

class CharacterRepository: ObservableObject {
    @Published public var characters = [Character(name: "Nott the Brave",
                                                  initiative: 23,
                                                  isActive: false),
                                        Character(name: "Caduceus Clay",
                                                  initiative: 2,
                                                  isActive: false),
                                        ...]
    ...
}

and

struct InitiativeTrackerScreen: View {
    @EnvironmentObject var characterRepository: CharacterRepository

    var body: some View {
        NavigationView {
            VStack {
                List {
                    ForEach(characterRepository.characters) { entry in
                        CharacterListElement(character: entry)
                    }
    ...

Now my intended approach would be something like turning the characters variable into a computed property that runs the "sorted by" function every time the get gets executed. Unfortunately, Binding to a computed property is not yet possible in SwiftUI (not sure, will it ever be?).

Can someone please help me with this? I don't want to go back to the old approach of sorting and redrawing every time something changes. That's not why I am using SwiftUI with ist sweet bindings.

Body:
I like to answer by related question. For what do you ever need some binding to computed property?

class CharacterRepository: ObservableObject {
    @Published public var characters = [Character(name: "Nott the Brave",
                                                  initiative: 23,
                                                  isActive: false),
                                        Character(name: "Caduceus Clay",
                                                  initiative: 2,
                                                  isActive: false),
                                        ...]
    ...
    var sorted: [Character] {
        characters.sorted()
    }
}

is all you need.


问:
Javascript object literal - possible to add duplicate keys?
In javascript, is is possible to add duplicate keys in object literal? If it is, then how could one achieve it after the object has been first created.

For example:

```<code>exampleObject['key1'] = something;
exampleObject['key1'] = something else;
</code>```

How can I add the second key1 without overwriting the first key1?

答:
In javascript having keys with same name will override the previous one and it will take the latest keys valuepair defined by the user.

Eg:

```<code>var fruits = { "Mango": "1", "Apple":"2", "Mango" : "3" }
</code>```

above code will evaluate to

```<code>var fruits = { "Mango" : "3" , "Apple":"2", }
</code>```

ContentLicense: CC BY-SA 3.0

Body:
In javascript, is is possible to add duplicate keys in object literal? If it is, then how could one achieve it after the object has been first created.

For example:

exampleObject['key1'] = something;
exampleObject['key1'] = something else;

How can I add the second key1 without overwriting the first key1?

Body:
In javascript having keys with same name will override the previous one and it will take the latest keys valuepair defined by the user.

Eg:

var fruits = { "Mango": "1", "Apple":"2", "Mango" : "3" }

above code will evaluate to

var fruits = { "Mango" : "3" , "Apple":"2", }


问:
Is it possible to load new Javascript files with AJAX?
I'm building a new AJAX powered website with distinct sections.  Each section requires a new set of Javascript functions to run.  I'd rather not load every script at the start, as there might be quite a few.

Is there a way to load new scripts using AJAX and remove old ones (so as to make sure there are no compatibility issues with similar variable names or function signatures).

Thanks

Edit - JQuery is fine, it doesn't have to be old school Javascript

答:
Just Google JavaScript on Demand

http://www.google.ca/search?sourceid=chrome&ie=UTF-8&q=javascript+on+demand

For example, jQuery provides $.getScript(), see http://api.jquery.com/jQuery.getScript/


问:
Best practices for fetching and displaying many amount of data
As the title said, I'm implementing a webpage which display many chart and table with .net

(note: i dont have prior experience with .net, but i do have experience with other language. so its not that hard for me to do the implementation. The thing is I want to know whether what I'm doing is "correct" or not)

So, this page suppose to display bunch of chart and table which have different set of data. Currently I'm implementing it with MVC where the controller fetch all the data at once, and then return the view with an object that saving all those data.

it goes something like this:

Model:

```<code>public class AViewModel
{
    Public List<ClassofData1> DataForTable1 { get; set; }
    Public List<ClassofData2> DataForTable2 { get; set; }
    Public List<ClassofData3> DataForChart1 { get; set; }
    Public List<ClassofData4> DataForChart2 { get; set; }
    ... //repeat for dozen of time :)
}
</code>```

controller:

```<code>public class AController : Controller
{
    public ActionResult Index()
    {
        AViewModel DataforView = mew AViewModel();

        DataforView.DataForTable1 = Fetch1(); //im oversimplifying here, but it basically goes like this
        DataforView.DataForTable2 = Fetch2();
        DataforView.DataForChart1 = Fetch3();
        DataforView.DataForChart2 = Fetch4();
        ... //repeat for another dozen of time :)

        return View("Index", DataforView);
    }
}
</code>```

And then display everything on a HTML page.

Is it okay to implement it like that? loading all those data into a single viewmodel and "dump" it all on the HTML page.

Or should i make bunch of API which the HTML page call one by one to fetch those data, instead of loading everything at once in the index controller just like i did?

答: Which chart are you using? Can we bind it using a JSON array? if it is possible to bind it using JS then you should create different actions to fetch chart data. And bind chart from javascript jQuery.ajax() methods on document ready.</p>

Body:
As the title said, I'm implementing a webpage which display many chart and table with .net

(note: i dont have prior experience with .net, but i do have experience with other language. so its not that hard for me to do the implementation. The thing is I want to know whether what I'm doing is "correct" or not)

So, this page suppose to display bunch of chart and table which have different set of data. Currently I'm implementing it with MVC where the controller fetch all the data at once, and then return the view with an object that saving all those data.

it goes something like this:

Model:

public class AViewModel
{
    Public List<ClassofData1> DataForTable1 { get; set; }
    Public List<ClassofData2> DataForTable2 { get; set; }
    Public List<ClassofData3> DataForChart1 { get; set; }
    Public List<ClassofData4> DataForChart2 { get; set; }
    ... //repeat for dozen of time :)
}

controller:

public class AController : Controller
{
    public ActionResult Index()
    {
        AViewModel DataforView = mew AViewModel();

        DataforView.DataForTable1 = Fetch1(); //im oversimplifying here, but it basically goes like this
        DataforView.DataForTable2 = Fetch2();
        DataforView.DataForChart1 = Fetch3();
        DataforView.DataForChart2 = Fetch4();
        ... //repeat for another dozen of time :)

        return View("Index", DataforView);
    }
}

And then display everything on a HTML page.

Is it okay to implement it like that? loading all those data into a single viewmodel and "dump" it all on the HTML page.

Or should i make bunch of API which the HTML page call one by one to fetch those data, instead of loading everything at once in the index controller just like i did?


问:
Combining CoreML Object Detection and ARKit 2D Image Detection
The app detects specific 2D images (with ARKit) and has a mlmodel that detects some furnitures, the mlmodel is of type Object Detection, it is trained and works. Depending of what is detected I need to add some 3D objects to the scene or others.

I created an AR session with ARWorldTrackingConfiguration and I can detect the 2D image and in the method renderer(_:didAdd:for:) I add the 3D object and it works perfectly:

```<code>    override func viewDidAppear(_ animated: Bool) {
    super.viewWillAppear(animated)

    guard let referenceImages = ARReferenceImage.referenceImages(inGroupNamed: "AR Resources", bundle: nil) else {
        fatalError("Missing expected asset catalog resources.")
    }

    let configuration = ARWorldTrackingConfiguration()
    configuration.worldAlignment = .gravityAndHeading
    configuration.detectionImages = referenceImages
    configuration.maximumNumberOfTrackedImages = 1
    configuration.isAutoFocusEnabled = false
    sceneView.session.run(configuration, options: [.resetTracking, .removeExistingAnchors])
}
</code>```

Also, I setup the mlmodel:

```<code>override func viewDidLoad() {

    super.viewDidLoad()
    sceneView.delegate = self
    sceneView.session.delegate = self
    setupML()
}

    internal func setupML() {

    guard let modelPath = Bundle.main.url(forResource: "furnituresDetector", withExtension: "mlmodelc") else {
        fatalError("Missing model")
    }

    do {
        let coreMLModel = try VNCoreMLModel(for: MLModel(contentsOf: modelPath))
        let request = VNCoreMLRequest(model: coreMLModel) { [weak self] (request, error) in
            DispatchQueue.main.async {
                if let results = request.results {
                    print(results.count)
                }
            }
        }
        self.requests = [request]
    } catch {
        print("Core ML Model error")
    }
}
</code>```

By the moment I just want to print the number of results to see if the ml model detects something or not.

Until here everything works perfectly, I run the app and the camera shows fluid. Instead of intanciating a new camera session, I reuse the session that has been started by the ARSCNView as I found in Combining CoreML and ARKit

So my solution was use session(_:didUpdate:) to make the request to coreml model and continuously know if the model has detected something that appears in the camera.

```<code>    func session(_ session: ARSession, didUpdate frame: ARFrame) {

    DispatchQueue(label: "CoreML_request").async {
        guard let pixelBuffer = session.currentFrame?.capturedImage else {
            return
        }

        let exifOrientation = self.exifOrientationFromDeviceOrientation()

        let imageRequestHandler = VNImageRequestHandler(cvPixelBuffer: pixelBuffer, orientation: exifOrientation, options: [:])
        do {
            try imageRequestHandler.perform(self.requests)
        } catch {
            print(error)
        }
    }
}
</code>```

If I run the app it works but the problem is that the camera seems very slow and if I delete the code inside session(_:didUpdate:), the camera seems normal again. So the problem is here, I suppose that what happens is that it is not the proper place to make this request because this method is call all the time when detects a new frame in the camera.
But I don't know where to do the request or what to do. Do you have any idea?

I will update it if I found some solution.
Thanks!

答:
I found a solution. The problem is that the camera has a limited buffers available, I was enqueueing too many buffers while another Vision task was still running.

That is why the camera was slow. So, the solution is release the buffer before performing another request.

```<code>internal var currentBuffer: CVPixelBuffer?

func session(_ session: ARSession, didUpdate frame: ARFrame) {

    guard currentBuffer == nil, case .normal = frame.camera.trackingState else {
        return
    }
    self.currentBuffer = frame.capturedImage

    DispatchQueue(label: "CoreML_request").async {
        guard let pixelBuffer = session.currentFrame?.capturedImage else {
            return
        }

        let exifOrientation = self.exifOrientationFromDeviceOrientation()

        let imageRequestHandler = VNImageRequestHandler(cvPixelBuffer: pixelBuffer, orientation: exifOrientation, options: [:])
        do {
            // Release the pixel buffer when done, allowing the next buffer to be processed.
            defer { self.currentBuffer = nil }
            try imageRequestHandler.perform(self.requests)
        } catch {
            print(error)
        }
    }
}
</code>```

Here you can check the documentation:

https://developer.apple.com/documentation/arkit/recognizing_and_labeling_arbitrary_objects

Body:
The app detects specific 2D images (with ARKit) and has a mlmodel that detects some furnitures, the mlmodel is of type Object Detection, it is trained and works. Depending of what is detected I need to add some 3D objects to the scene or others.

I created an AR session with ARWorldTrackingConfiguration and I can detect the 2D image and in the method renderer(_:didAdd:for:) I add the 3D object and it works perfectly:

    override func viewDidAppear(_ animated: Bool) {
    super.viewWillAppear(animated)

    guard let referenceImages = ARReferenceImage.referenceImages(inGroupNamed: "AR Resources", bundle: nil) else {
        fatalError("Missing expected asset catalog resources.")
    }

    let configuration = ARWorldTrackingConfiguration()
    configuration.worldAlignment = .gravityAndHeading
    configuration.detectionImages = referenceImages
    configuration.maximumNumberOfTrackedImages = 1
    configuration.isAutoFocusEnabled = false
    sceneView.session.run(configuration, options: [.resetTracking, .removeExistingAnchors])
}

Also, I setup the mlmodel:

override func viewDidLoad() {

    super.viewDidLoad()
    sceneView.delegate = self
    sceneView.session.delegate = self
    setupML()
}

    internal func setupML() {

    guard let modelPath = Bundle.main.url(forResource: "furnituresDetector", withExtension: "mlmodelc") else {
        fatalError("Missing model")
    }

    do {
        let coreMLModel = try VNCoreMLModel(for: MLModel(contentsOf: modelPath))
        let request = VNCoreMLRequest(model: coreMLModel) { [weak self] (request, error) in
            DispatchQueue.main.async {
                if let results = request.results {
                    print(results.count)
                }
            }
        }
        self.requests = [request]
    } catch {
        print("Core ML Model error")
    }
}

By the moment I just want to print the number of results to see if the ml model detects something or not.

Until here everything works perfectly, I run the app and the camera shows fluid. Instead of intanciating a new camera session, I reuse the session that has been started by the ARSCNView as I found in Combining CoreML and ARKit

So my solution was use session(_:didUpdate:) to make the request to coreml model and continuously know if the model has detected something that appears in the camera.

    func session(_ session: ARSession, didUpdate frame: ARFrame) {

    DispatchQueue(label: "CoreML_request").async {
        guard let pixelBuffer = session.currentFrame?.capturedImage else {
            return
        }

        let exifOrientation = self.exifOrientationFromDeviceOrientation()

        let imageRequestHandler = VNImageRequestHandler(cvPixelBuffer: pixelBuffer, orientation: exifOrientation, options: [:])
        do {
            try imageRequestHandler.perform(self.requests)
        } catch {
            print(error)
        }
    }
}

If I run the app it works but the problem is that the camera seems very slow and if I delete the code inside session(_:didUpdate:), the camera seems normal again. So the problem is here, I suppose that what happens is that it is not the proper place to make this request because this method is call all the time when detects a new frame in the camera.
But I don't know where to do the request or what to do. Do you have any idea?

I will update it if I found some solution.
Thanks!

Body:
I found a solution. The problem is that the camera has a limited buffers available, I was enqueueing too many buffers while another Vision task was still running.

That is why the camera was slow. So, the solution is release the buffer before performing another request.

internal var currentBuffer: CVPixelBuffer?

func session(_ session: ARSession, didUpdate frame: ARFrame) {

    guard currentBuffer == nil, case .normal = frame.camera.trackingState else {
        return
    }
    self.currentBuffer = frame.capturedImage

    DispatchQueue(label: "CoreML_request").async {
        guard let pixelBuffer = session.currentFrame?.capturedImage else {
            return
        }

        let exifOrientation = self.exifOrientationFromDeviceOrientation()

        let imageRequestHandler = VNImageRequestHandler(cvPixelBuffer: pixelBuffer, orientation: exifOrientation, options: [:])
        do {
            // Release the pixel buffer when done, allowing the next buffer to be processed.
            defer { self.currentBuffer = nil }
            try imageRequestHandler.perform(self.requests)
        } catch {
            print(error)
        }
    }
}

Here you can check the documentation:

https://developer.apple.com/documentation/arkit/recognizing_and_labeling_arbitrary_objects


问:
User manually create model fields for post [django]
So I want to create a post by letting the user add a section/subtitle as they need it, but I have no idea how to go about creating this, I currently just have a  title, preview and content block in a form but want the user to be able to create as many subtitle and content blocks as they want. Any help is very much appreciated :) </p>

答:
Well that's really basic database design question... What you describe is a "one to many" relationship (one "post" has many "subtitle-plus-content"), which is implemented using a table for the "subtitle-plus-content" records, with a foreign key on the "post" table (so we know which "subtitle-plus-content" records belong to which "post" record).

In Django, this is simply done by creatin a matching model:

```<code>class Post(models.Model):
    title = models.CharField(max_lenght=xxx)
    content = models.TextField()
    # etc

class ContentBlock(models.Model):
    """ A block with additionnal subtitle and content for posts """
    post = models.ForeignKey(Post, on_delete=models.CASCADE)
    subtitle = models.CharField(max_lenght=xxx)
    content = models.TextField()
    # etc
</code>```

You'll find more documentation here

Body:
Well that's really basic database design question... What you describe is a "one to many" relationship (one "post" has many "subtitle-plus-content"), which is implemented using a table for the "subtitle-plus-content" records, with a foreign key on the "post" table (so we know which "subtitle-plus-content" records belong to which "post" record).

In Django, this is simply done by creatin a matching model:

class Post(models.Model):
    title = models.CharField(max_lenght=xxx)
    content = models.TextField()
    # etc

class ContentBlock(models.Model):
    """ A block with additionnal subtitle and content for posts """
    post = models.ForeignKey(Post, on_delete=models.CASCADE)
    subtitle = models.CharField(max_lenght=xxx)
    content = models.TextField()
    # etc

You'll find more documentation here


问:
SharePoint Navigation Menu - Multi Level
I'm looking into integrating some Telerik Components into our MOSS Installation.  I'd figure I would kill a few birds with one stone and work on the Navigation Menu first.

I'm slightly new to SharePoint, and pulling hair at some of it's oddities.

We have some requirements for our Navigation menu:

Security Trimmed

Multi-Level Navigation

As best as I can tell, there doesn't seem to be a way to get security trimming without using SharePoint's out of the box Navigation Settings.  Am I wrong?

Is there a way to get these Navigation Settings to go more than two levels deep?

EDITS

I'm using the Global Navigation, located at / > Site Settings > Modify Navigation

答:
Haven't used the Telerik control.

I suspect you should be able to accomplish this with basic properties, something like StaticDisplayLevels="2" with 2 being the number you want.

The security I believe would be handled on your datasource that the control uses.

Again, I haven't used the telerik control so I'm sure it's a bit different, looking at the product info for this control it appears to be a matter of figuring out what the properties are that you need to adjust. There must be some documentation that came with it?

OwnerDisplayName: Slipfish

ContentLicense: CC BY-SA 2.5

LastEditorDisplayName: Slipfish

OwnerDisplayName: savageguy


问:
List of List C# question or something else any pointers in coding this
I need some help in coding this in C#

I have a list of Baskets and their Global_Weights in overall Basket in Kilograms:

Basket1, Basket2, Basket3, Basket4

0.1, 0.3, 0.9,0.6

Each of the Basket consist of the following thing:

Name,Level1, level2,Local_Weights

Name: String type

Level1:Double Type

Level2:Double Type

Local_Weights:Double Type

Each Basket will consist of N number of (Name,Level1, level2,Local_Weights) and there are M Baskets
N and M are variable which will be user Input

Should I be using List of list for this or something else any pointer on how to go about coding this?

How will I be accessing the members inside each of the Basket and perform calculation on them.

答:
You could use something of this sort.</p>

```<code>Dictionary<string, List<MyClass>> var = new Dictionary<string, List<MyClass>>();//where string key is the basket name, MyClass is a class containing properties like Name,Level1, level2,Local_Weights
</code>```

Body:
You could use something of this sort.

Dictionary<string, List<MyClass>> var = new Dictionary<string, List<MyClass>>();//where string key is the basket name, MyClass is a class containing properties like Name,Level1, level2,Local_Weights


问:
Stopping a python thread running an Infinite Loop
I am new to python programming. I am trying to make a GUI with stoppable threads.
I borrowed some code from
https://stackoverflow.com/a/325528

```<code>class MyThread(threading.Thread):
    """Thread class with a stop() method. The thread itself has to check
    regularly for the stopped() condition."""

    def __init__(self, *args, **kwargs):
        super(MyThread, self).__init__(*args, **kwargs)
        self._stop = threading.Event()

    def stop(self):
        self._stop.set()

    def stopped(self):
        return self._stop.isSet()
</code>```

I have function which creates a thread for another function in another class that runs an infinite loop.

```<code>class MyClass :

    def clicked_practice(self):

        self.practicethread = MyThread(target=self.infinite_loop_method)
        self.practicethread.start()

    def infinite_loop_method()
        while True :
            // Do something

    #This doesn't seem to work and I am still stuck in the loop

    def infinite_stop(self)
        if self.practicethread.isAlive():
        self.practicethread.stop()
</code>```

I want to create a method to stop this thread .
What's happening here?

答:
import threading
import time
class MultiThreading:

    def __init__(self):
        self.thread = None
        self.started = True
    def threaded_program(self):
        while self.started:
            print("running")
            # time.sleep(10)
    def run(self):
        self.thread = threading.Thread(target=self.threaded_program, args=())
        self.thread.start()
    def stop(self):
        self.started = False
        self.thread.join()
```

Body:
I am new to python programming. I am trying to make a GUI with stoppable threads.
I borrowed some code from
https://stackoverflow.com/a/325528

class MyThread(threading.Thread):
    """Thread class with a stop() method. The thread itself has to check
    regularly for the stopped() condition."""

    def __init__(self, *args, **kwargs):
        super(MyThread, self).__init__(*args, **kwargs)
        self._stop = threading.Event()

    def stop(self):
        self._stop.set()

    def stopped(self):
        return self._stop.isSet()

I have function which creates a thread for another function in another class that runs an infinite loop.

class MyClass :

    def clicked_practice(self):

        self.practicethread = MyThread(target=self.infinite_loop_method)
        self.practicethread.start()

    def infinite_loop_method()
        while True :
            // Do something

    #This doesn't seem to work and I am still stuck in the loop

    def infinite_stop(self)
        if self.practicethread.isAlive():
        self.practicethread.stop()

I want to create a method to stop this thread .
What's happening here?


问:
SQL design pattern: which one to choose?
Concept:

I have a SAAS application. I have like 2-3 customers, more to follow. Each customer has his own database and our server connects to them depending on login information. On each of these databases there is a table, let's call it saas_table, which contains a unique column: id. There are and will be 3000 rows on each of these table at most.

My server has a database with one table: subscriptions. This table holds information about my customers, their database credentials and so on. I want to duplicate the id of the saas_table from each customer database and store it in my server database.

Approach?

Which is the better approach: creating a giant table log_table on my server's database and store the records there, or creating a table for each customer log_1_table, log_2_table, etc and store the information based on each customer? I must point that the hypothetical log_* table will be accessed very often, at least twice per session.

I think storing the ids on separate tables will have higher performance as tables will be cached in RAM. But this requires more programming and possibly new core version of my application. On the other hand, since each customer has traffic, the records from log_table will also be accessed often thus cached in RAM as well. Which is the better approach?

答:
Personally, I would never store in a tablename, information that should be stored in a column - and I think this is information that should be stored in a column. Accessing a table twice per session is fairly low usage, even for thousands of customers. The last stock trading platform I worked on would see customers hitting many tables several times per transaction, and there were hundreds of thousands of transactions per hour and a person's trading standing was calculated by looking back over billions of transactions and summing to find their current position. Your pondering about performance right now is a premature optimization, and it's distracting you from the bigger problem that you're considering creating an engineering and maintenance headache.

Chiefly, you're overlooking the fact that most ORMs and data access strategies by higher level libraries like Entity Framework is geared towards treating a table like an compiled-in object type that contains variable data (rows) of fixed proeprties (columns). Having your proposed structure of a table per customer (of what is identical information) creates a headache like:

```<code>DateTime recentLogin;
if(currentUser == "IBM")
  recentLogin = dbContext.IBMLoginLog.Max(x => x.LoginDate);
elseif(currentUser == "Microsoft")
  recentLogin = dbContext.MicrosoftLoginLog.Max(x => x.LoginDate);
elseif(currentUser == "Facebook")
  recentLogin = dbContext.FacebookLoginLog.Max(x => x.LoginDate);
...
</code>```

This app needs recompiling every time you add a new customer. It should have been like this to cope with the things you anticipate to change):

```<code>DateTime recentLogin = dbContext.LoginLog.Where(x => x.User == currentUser).Max(x => x.Logindate);
</code>```

You might say "but I can do the same with strSQL = "SELECT MAX(date) FROM " + currentUser + "LoginLog" but that's an accidental byproduct of the fact that your SQL is compiled from the string every time it's run and can hence cope with the changing table name - it's not an indication that it's a sensible or good way to design a program, in the same way that you wouldn't write some C# program, that wrote a text file containing C# to disk, compile it and run it, just to change the name of the table you're looking in:

```<code>string csharpCode = "...; DateTime recentLogin = dbContext." + currentUser + "LoginLog.Max(x => x.Logindate); ..."
File.WriteAllText(@"c:\temp\getdata.cs", csharpCode);
Process.Start("csc.exe", @"c:\temp\getdata.cs");
Process.Start("c:\temp\getdata.exe");
</code>```

(It's a stupid example; no-one would do this - except that I'm advocating that by stringing your SQL together and sending it to the SQL Server, that is exactly what's happening)

Instead, take a cue from things like Entity Framework and even SQL itself in that only certain things can be parameters:

```<code>--valid
SELECT MAX(LoginDate) FROM Logins WHERE Client = @clientName

--not valid
SELECT MAX(LoginDate) FROM @clientName+Logins

--valid, but again, that recompiling thing:
EXEC 'SELECT MAX(LoginDate) FROM ' + @clientName + 'Logins'
</code>```

Have your one table, index the client name (and maybe include other columns you'll frequently want the data of, like here I might CREATE INDEX whatever ON Login(ClientName) INCLUDE (LoginDate) to create an index that can be looked in for client name, and also the index knows the login date, so it can answer the max(logindate) query without the server needing to then hit the table and retrieve the rows it found from the index, to get the date

Body:
Personally, I would never store in a tablename, information that should be stored in a column - and I think this is information that should be stored in a column. Accessing a table twice per session is fairly low usage, even for thousands of customers. The last stock trading platform I worked on would see customers hitting many tables several times per transaction, and there were hundreds of thousands of transactions per hour and a person's trading standing was calculated by looking back over billions of transactions and summing to find their current position. Your pondering about performance right now is a premature optimization, and it's distracting you from the bigger problem that you're considering creating an engineering and maintenance headache.

Chiefly, you're overlooking the fact that most ORMs and data access strategies by higher level libraries like Entity Framework is geared towards treating a table like an compiled-in object type that contains variable data (rows) of fixed proeprties (columns). Having your proposed structure of a table per customer (of what is identical information) creates a headache like:

DateTime recentLogin;
if(currentUser == "IBM")
  recentLogin = dbContext.IBMLoginLog.Max(x => x.LoginDate);
elseif(currentUser == "Microsoft")
  recentLogin = dbContext.MicrosoftLoginLog.Max(x => x.LoginDate);
elseif(currentUser == "Facebook")
  recentLogin = dbContext.FacebookLoginLog.Max(x => x.LoginDate);
...

This app needs recompiling every time you add a new customer. It should have been like this to cope with the things you anticipate to change):

DateTime recentLogin = dbContext.LoginLog.Where(x => x.User == currentUser).Max(x => x.Logindate);

You might say "but I can do the same with strSQL = "SELECT MAX(date) FROM " + currentUser + "LoginLog" but that's an accidental byproduct of the fact that your SQL is compiled from the string every time it's run and can hence cope with the changing table name - it's not an indication that it's a sensible or good way to design a program, in the same way that you wouldn't write some C# program, that wrote a text file containing C# to disk, compile it and run it, just to change the name of the table you're looking in:

string csharpCode = "...; DateTime recentLogin = dbContext." + currentUser + "LoginLog.Max(x => x.Logindate); ..."
File.WriteAllText(@"c:\temp\getdata.cs", csharpCode);
Process.Start("csc.exe", @"c:\temp\getdata.cs");
Process.Start("c:\temp\getdata.exe");

(It's a stupid example; no-one would do this - except that I'm advocating that by stringing your SQL together and sending it to the SQL Server, that is exactly what's happening)

Instead, take a cue from things like Entity Framework and even SQL itself in that only certain things can be parameters:

--valid
SELECT MAX(LoginDate) FROM Logins WHERE Client = @clientName

--not valid
SELECT MAX(LoginDate) FROM @clientName+Logins

--valid, but again, that recompiling thing:
EXEC 'SELECT MAX(LoginDate) FROM ' + @clientName + 'Logins'

Have your one table, index the client name (and maybe include other columns you'll frequently want the data of, like here I might CREATE INDEX whatever ON Login(ClientName) INCLUDE (LoginDate) to create an index that can be looked in for client name, and also the index knows the login date, so it can answer the max(logindate) query without the server needing to then hit the table and retrieve the rows it found from the index, to get the date


问:
Django connect to IBM Cloud database
I'm new in Django. I'm trying to connect Django app to IBM Cloud db, I loaded my data IBM cloud and created credionals.

Then installed ibm_db_django

```<code>$ easy_install ibm_db_django
</code>```

Then in setting.py did import

```<code>import ibm_db_django
</code>```

Then I added credionals in settings.py

```<code>DATABASES = {
'default': {
    'ENGINE'   : 'ibm_db_django',
    'NAME'     : 'BLUDB',
    'USER'     : 'USER',
    'PASSWORD' : 'PASSWORD',
    'HOST'     : 'dashdb-txn-sbox-yp-lon02-02.services.eu-gb.bluemix.net',
    'PORT'     : '50000',
    'PROTOCOL' : 'TCPIP',
    'PCONNECT' :  True,
},
</code>```

}

Otput of python manage.py test django.contrib.auth :

```<code>    System check identified no issues (0 silenced).
</code>```

Is this enough to connect to ibm cloud db?
Now how can I test is this connected to database, and how can I generate models from database?

答:
With the versions below, I can connect python + django + ibm_db_django + Db2-on-cloud .

Running python manage.py migrate shows that the connection to Db2-on-cloud is succeeding.

Depending on versions, the python manage.py migrate might fail with the Db2-on-cloud 'lite' (free) plan, if specific database permissions are missing.

To work further with django after running the manage.py migrate successfully, please follow the online tutorial for your version of django at djangoproject.com .

I tried these versions (february 2020):

```<code>python          3.6.9  x64
pip             20.0.2
django          2.2.5
ibm_db          3.0.1
ibm_db_django   1.2.0.0a0  (lower versions always failed).
</code>```

Note: other combinations might work, your mileage may vary.

I patched the ibm_db_dbi.py to workaround an open defect as detailed on github
(https://github.com/ibmdb/python-ibmdb-django/issues/44)
 (thanks to trebor74hr )

To get the manage.py migrate step working, the three settings.py changes I made were:

(1) The installed apps may vary with your versions and your app.

```<code>  INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'django.contrib.flatpages',
    'django.contrib.redirects',
    'django.contrib.sites',

]
</code>```

(2)

```<code>DATABASES = {
  'default': {
  'ENGINE'   : 'ibm_db_django',
  'NAME'     : 'bludb',
  'USER'     : '......',
  'PASSWORD' : '...............',
  'HOST'     : 'dashdb-txn-sbox-............services....bluemix.net',
  'PORT'     : '50000',
  'PCONNECT' :  True,      #Optional property. It is true by default
  }
}
</code>```

(3)

```<code>#USE_TZ = True
   (or remove the line, the # makes it a comment ).
</code>```

Title: Django connect to IBM Cloud database

Body:
I'm new in Django. I'm trying to connect Django app to IBM Cloud db, I loaded my data IBM cloud and created credionals.

Then installed ibm_db_django

$ easy_install ibm_db_django

Then in setting.py did import

import ibm_db_django

Then I added credionals in settings.py

DATABASES = {
'default': {
    'ENGINE'   : 'ibm_db_django',
    'NAME'     : 'BLUDB',
    'USER'     : 'USER',
    'PASSWORD' : 'PASSWORD',
    'HOST'     : 'dashdb-txn-sbox-yp-lon02-02.services.eu-gb.bluemix.net',
    'PORT'     : '50000',
    'PROTOCOL' : 'TCPIP',
    'PCONNECT' :  True,
},

}

Otput of python manage.py test django.contrib.auth :

    System check identified no issues (0 silenced).

Is this enough to connect to ibm cloud db?
Now how can I test is this connected to database, and how can I generate models from database?

Body:
With the versions below, I can connect python + django + ibm_db_django + Db2-on-cloud .

Running python manage.py migrate shows that the connection to Db2-on-cloud is succeeding.

Depending on versions, the python manage.py migrate might fail with the Db2-on-cloud 'lite' (free) plan, if specific database permissions are missing.

To work further with django after running the manage.py migrate successfully, please follow the online tutorial for your version of django at djangoproject.com .

I tried these versions (february 2020):

python          3.6.9  x64
pip             20.0.2
django          2.2.5
ibm_db          3.0.1
ibm_db_django   1.2.0.0a0  (lower versions always failed).

Note: other combinations might work, your mileage may vary.

I patched the ibm_db_dbi.py to workaround an open defect as detailed on github
(https://github.com/ibmdb/python-ibmdb-django/issues/44)
 (thanks to trebor74hr )

To get the manage.py migrate step working, the three settings.py changes I made were:

(1) The installed apps may vary with your versions and your app.

  INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'django.contrib.flatpages',
    'django.contrib.redirects',
    'django.contrib.sites',

]

(2)

DATABASES = {
  'default': {
  'ENGINE'   : 'ibm_db_django',
  'NAME'     : 'bludb',
  'USER'     : '......',
  'PASSWORD' : '...............',
  'HOST'     : 'dashdb-txn-sbox-............services....bluemix.net',
  'PORT'     : '50000',
  'PCONNECT' :  True,      #Optional property. It is true by default
  }
}

(3)

#USE_TZ = True
   (or remove the line, the # makes it a comment ).


问:
Unable to connect the mongodb server while using NodeJS
MongoServerSelectionError: connect ECONNREFUSED 127.0.0.1:27017
    at Timeout._onTimeout (D:\javascriptApps\node_modules\mongodb\lib\core\sdam\topology.js:428:30)</p>

答:
The error ECONNREFUSED is nothing but the connection have been refused. There is no process endpoint listening on local 127.0.0.1:27017

Before connecting to the database, make sure to install mongodb and  start the database server.
From command prompt, go to where your mongo installations is situated and run command:

```<code>mongod --port 27017 --dbpath C:\path_to_data_folder
</code>```

You may find it useful Start MondoDB Process

Body:
The error ECONNREFUSED is nothing but the connection have been refused. There is no process endpoint listening on local 127.0.0.1:27017

Before connecting to the database, make sure to install mongodb and  start the database server.
From command prompt, go to where your mongo installations is situated and run command:

mongod --port 27017 --dbpath C:\path_to_data_folder

You may find it useful Start MondoDB Process


问:
Scala: How serialize data in JSON?
I recently started to learn Scala. I need an EASY way to SERIALIZE my data in Json. Below I will give an example of data. I tried several popular libraries: GSON, Play JSON, Circe, but did not get the result! GSON does not know how to work with Option (eg Option [String]), in Play JSON and Circe they need to describe serialization and deserialization of an abstract class (I don’t know how to get around this).</p>

```<code>// Test data

  abstract class Base(id: Long, descr: Option[String])
  case class A(id: Long, descr: Option[String], a: Option[Long]) extends Base(id, descr)
  case class B(id: Long, descr: Option[String], b: Option[Double]) extends Base(id, descr)

  case class Data(id: Long, user: Option[String], data: Option[Array[Base]])

  val test: Array[Data] = Array(
    Data(1, Some("Qqq"), None),
    Data(2, None, None),
    Data(3, Some("Zzz"), Some(
      Array(
        A(1, Some("a1"), Some(111)),
        A(2, Some("a2"), None),
        A(3, None, Some(333)),
        B(4, Some("b1"), Some(444.444)),
        B(5, Some("b2"), None),
        B(6, None, Some(666.666))
      )
    ))   )
</code>```

答:
Using circe:

```<code>  import cats.syntax.functor._
  import io.circe.{Decoder, Encoder}, io.circe.generic.auto._
  import io.circe.syntax._

  implicit val encodeBase: Encoder[Base] = Encoder.instance {
    case foo @ A(_, _, _) => foo.asJson
    case bar @ B(_, _, _) => bar.asJson
  }
</code>```

And then you can just do

```<code>  test.asJson
</code>```

Title: Scala: How serialize data in JSON?

Body:
I recently started to learn Scala. I need an EASY way to SERIALIZE my data in Json. Below I will give an example of data. I tried several popular libraries: GSON, Play JSON, Circe, but did not get the result! GSON does not know how to work with Option (eg Option [String]), in Play JSON and Circe they need to describe serialization and deserialization of an abstract class (I don’t know how to get around this).

// Test data

  abstract class Base(id: Long, descr: Option[String])
  case class A(id: Long, descr: Option[String], a: Option[Long]) extends Base(id, descr)
  case class B(id: Long, descr: Option[String], b: Option[Double]) extends Base(id, descr)

  case class Data(id: Long, user: Option[String], data: Option[Array[Base]])

  val test: Array[Data] = Array(
    Data(1, Some("Qqq"), None),
    Data(2, None, None),
    Data(3, Some("Zzz"), Some(
      Array(
        A(1, Some("a1"), Some(111)),
        A(2, Some("a2"), None),
        A(3, None, Some(333)),
        B(4, Some("b1"), Some(444.444)),
        B(5, Some("b2"), None),
        B(6, None, Some(666.666))
      )
    ))   )

Body:
Using circe:

  import cats.syntax.functor._
  import io.circe.{Decoder, Encoder}, io.circe.generic.auto._
  import io.circe.syntax._

  implicit val encodeBase: Encoder[Base] = Encoder.instance {
    case foo @ A(_, _, _) => foo.asJson
    case bar @ B(_, _, _) => bar.asJson
  }

And then you can just do

  test.asJson


问:
How to make the link inside Button change color on hover without hovering over link
My link changes color on hovering over it directly but does not change color when I hover over the button and not the link directly

```<code>btn:hover{
color: black;
}
</code>```

This does not work.

```<code>a:hover{
color:black
}
</code>```

This is working currently but does not do the job as needed.

How do I make the button change the color of the link when I hover over it?
As seen in the first image.

答:
Please try this-  </p>

```<code>btn:hover a {
  color: black;
}
</code>```

Body:
My link changes color on hovering over it directly but does not change color when I hover over the button and not the link directly

btn:hover{
color: black;
}

This does not work.

a:hover{
color:black
}

This is working currently but does not do the job as needed.

How do I make the button change the color of the link when I hover over it?
As seen in the first image.

Body:
Please try this-

btn:hover a {
  color: black;
}


问:
React material ui table won't stretch to fill
I'm experimenting with my own virtualization by using an example (rather than react-virtualized) and I'm having issues with styling

Can anyone tell me why the material table in the code sandbox below won't stretch to fit it's paper component? I'm sure there's a CSS property I need to set somewhere but I'm not sure what it is

https://codesandbox.io/s/material-ui-table-virtualization-c8tys

Any help would be appreciated

Thanks!

Adam

答:
I made an example for you. I think is something what you are looking for.

I added a custom class DataTable-tableWrapper-3 with display: table and I make each row with display: inline-table and width: 100% .

https://codesandbox.io/s/material-ui-table-virtualization-h1c2e


问:
What to do when laravel routing is duplicated in laravel
I have added two routes, as described below.

I want the following behavior.
/api/user/1 or /api/user/2 or . . . → UserController@show is excute

/api/user/auth → UserController@showAuthUser is excute

However, when call /api/user/auth, UserController@show is excuted.

How do I get what I want?

```<code>Route::get('user/{user_id}', 'Api\UserController@show');

Route::get('user/auth', 'Api\UserController@showAuthUser');
</code>```

答:
Put your routes with fixed "parameters" first :

```<code>Route::get('user/auth', 'Api\UserController@showAuthUser');
Route::get('user/{user_id}', 'Api\UserController@show');
</code>```

If you put {user_id} first, Laravel will put "auth" in your "user_id" variable

Body:
I have added two routes, as described below.

I want the following behavior.
/api/user/1 or /api/user/2 or . . . → UserController@show is excute

/api/user/auth → UserController@showAuthUser is excute

However, when call /api/user/auth, UserController@show is excuted.

How do I get what I want?

Route::get('user/{user_id}', 'Api\UserController@show');

Route::get('user/auth', 'Api\UserController@showAuthUser');

Body:
Put your routes with fixed "parameters" first :

Route::get('user/auth', 'Api\UserController@showAuthUser');
Route::get('user/{user_id}', 'Api\UserController@show');

If you put {user_id} first, Laravel will put "auth" in your "user_id" variable


问:
Python universal scraper for all postcodes on a page hidden inside javascript
I'm currently trying to create a universal web scraper which will pick up on all postcodes on a page but I'm finding it really difficult if a page hides their office locations within some javascript.

My scraper:

def parse(url):

    try:
        print(url)
        postcode_regex_pattern = r"([Gg][Ii][Rr] 0[Aa]{2})|((([A-Za-z][0-9]{1,2})|(([A-Za-z][A-Ha-hJ-Yj-y][0-9]{1,2})|(([A-Za-z][0-9][A-Za-z])|([A-Za-z][A-Ha-hJ-Yj-y][0-9][A-Za-z]?))))\s?[0-9][A-Za-z]{2})"
        compiled_pattern = re.compile(postcode_regex_pattern)
        headers = {
            'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.130 Safari/537.36',
            }
        page = requests.get(url, headers=headers)
        # print(page.status_code)
        if page.status_code == 200:
            soup = BeautifulSoup(page.text, 'lxml')
            info_to_store = {
                            'url': url,
                            'postcodes': [],
                            }
            visible_text_in_page = text_from_html(soup)
            matches = re.findall(compiled_pattern, visible_text_in_page)
            pcs = [match[1] for match in matches]
            if len(pcs) > 0:
                info_to_store['postcodes'] = list(set(pcs))
    except Exception as e:
        print('{url}: ' + str(e))
        pass
```

Two good examples that my scraper does not work on:

https://home.kpmg/uk/en/home/about/offices.html

https://www.twilio.com/company

Does anyone have any advice? I do not want to use selenium.

答:
You can use requests_html to render the page and then parse it with BeautifulSoup.

Python 3.6 and above is required.

Sample request

```<code>from requests_html import HTMLSession
session = HTMLSession()

r = session.get('https://home.kpmg/uk/en/home/about/offices.html')

</code>```

Body:
I'm currently trying to create a universal web scraper which will pick up on all postcodes on a page but I'm finding it really difficult if a page hides their office locations within some javascript.

My scraper:

def parse(url):

    try:
        print(url)
        postcode_regex_pattern = r"([Gg][Ii][Rr] 0[Aa]{2})|((([A-Za-z][0-9]{1,2})|(([A-Za-z][A-Ha-hJ-Yj-y][0-9]{1,2})|(([A-Za-z][0-9][A-Za-z])|([A-Za-z][A-Ha-hJ-Yj-y][0-9][A-Za-z]?))))\s?[0-9][A-Za-z]{2})"
        compiled_pattern = re.compile(postcode_regex_pattern)
        headers = {
            'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.130 Safari/537.36',
            }
        page = requests.get(url, headers=headers)
        # print(page.status_code)
        if page.status_code == 200:
            soup = BeautifulSoup(page.text, 'lxml')
            info_to_store = {
                            'url': url,
                            'postcodes': [],
                            }
            visible_text_in_page = text_from_html(soup)
            matches = re.findall(compiled_pattern, visible_text_in_page)
            pcs = [match[1] for match in matches]
            if len(pcs) > 0:
                info_to_store['postcodes'] = list(set(pcs))
    except Exception as e:
        print('{url}: ' + str(e))
        pass

Two good examples that my scraper does not work on:

https://home.kpmg/uk/en/home/about/offices.html

https://www.twilio.com/company

Does anyone have any advice? I do not want to use selenium.

Body:
You can use requests_html to render the page and then parse it with BeautifulSoup.

Python 3.6 and above is required.

Sample request

from requests_html import HTMLSession
session = HTMLSession()

r = session.get('https://home.kpmg/uk/en/home/about/offices.html')