问:
window.setInterval - is it possible to have more than one? how?
I have created a slideshow widget, using jQuery.UI widgets that works with window.setInterval.
I am trying to have more than one slideshow in the same page and i get the following results:

If I try invoking the same widget for both of my divs with images:

```<code>$('#div1').slideshow();
$('#div2').slideshow();
</code>```

none of them work;

I have cloned the definition of my widget and named it slideshowsmall

```<code>$('#div1').slideshow();
$('#div2').slideshowsmall();
</code>```

and only the second one works.

my widget code is in this pastebin, but i really think the problem, at least in the second try, has to do with setInterval

Thanks

答:
As per your widget code when setInterval calls the ChangeLeft/Right.. method the slideshowdiv variable always points to the last element on which slideShow is called. the reason for this is the way you are invoking change methods which is not adviceable.

Please use the below code to call your change method it should solve your problem. You will notice I am passing the slideshowdiv object to change methods.

```<code>this.options.timer = window.setInterval(function () {
                ChangeImageLeft(velocidade, slideshowdiv);
            }, intervalo);
</code>```

Let me know if you need more info.

Body:
I have created a slideshow widget, using jQuery.UI widgets that works with window.setInterval.
I am trying to have more than one slideshow in the same page and i get the following results:

If I try invoking the same widget for both of my divs with images:

$('#div1').slideshow();
$('#div2').slideshow();

none of them work;

I have cloned the definition of my widget and named it slideshowsmall

$('#div1').slideshow();
$('#div2').slideshowsmall();

and only the second one works.

my widget code is in this pastebin, but i really think the problem, at least in the second try, has to do with setInterval

Thanks

Body:
As per your widget code when setInterval calls the ChangeLeft/Right.. method the slideshowdiv variable always points to the last element on which slideShow is called. the reason for this is the way you are invoking change methods which is not adviceable.

Please use the below code to call your change method it should solve your problem. You will notice I am passing the slideshowdiv object to change methods.

this.options.timer = window.setInterval(function () {
                ChangeImageLeft(velocidade, slideshowdiv);
            }, intervalo);

Let me know if you need more info.


来源: stackexchange

问:
How do I load a canvas from an image reliabily?
I'm trying to load an png into a canvas. With the following code it seems to load 10% of the time and the rest I get a blank image. I'm not sure why it isn't working. I tried loading via array instead but I get a decode error</p>

```<code><img src="/myimage.png" id="myimage">

myimage.onload = function() {
    var ctx = mycanvas.getContext("2d");
    ctx.drawImage(myimage, 0, 0);
};
</code>```

答:
I do not see the failures you see.

myimage.onload = function() {
    var ctx = mycanvas.getContext("2d");
    ctx.drawImage(myimage, 0, 0);
};```
<pre class="snippet-code-html lang-html prettyprint-override"><code><img src="http://placekitten.com/200/300" id="myimage">

<canvas id="mycanvas" width="200" height="300"></canvas></code>```

ContentLicense: CC BY-SA 4.0

Body:
I'm trying to load an png into a canvas. With the following code it seems to load 10% of the time and the rest I get a blank image. I'm not sure why it isn't working. I tried loading via array instead but I get a decode error

myimage.onload = function() {
    var ctx = mycanvas.getContext("2d");
    ctx.drawImage(myimage, 0, 0);
};

Body:
I do not see the failures you see.

myimage.onload = function() {
    var ctx = mycanvas.getContext("2d");
    ctx.drawImage(myimage, 0, 0);
};

<img src="http://placekitten.com/200/300" id="myimage">

<canvas id="mycanvas" width="200" height="300"></canvas>


问:
ReactJS - Route works but doesn't display the page
I am new to ReactJS, having an issue on viewing the display. The route works, but I need to reload the page to display the content. Is there any possible solution without the user to force reload the page to view the content.

--App.js

```<code>import React from "react";
import {Route} from "react-router-dom";
import CssBaseline from "@material-ui/core/CssBaseline";
import "./App.css";
import Home from "./components";
import Resume from "./components/Resume"

function App() {
  return (
  <>
    <CssBaseline/>
    <Route exact path="/" component ={Home}/>
    <Route path="/resume" component ={Resume}/>
  </>
  );
}

export default App;
</code>```

-- Navbar.js

```<code>import React, {useState} from 'react';
import {Link} from 'react-router-dom';
import { makeStyles } from '@material-ui/core/styles';
import MobileRightMenuSlider from '@material-ui/core/Drawer';
import {
    AppBar,
    Toolbar,
    ListItem,
    IconButton,
    ListItemText,
    Avatar,
    Divider,
    List,
    Typography,
    Box,
    ListItemIcon
} from "@material-ui/core"
import {
    ArrowBack,
    AssignmentInd,
    Home,
    Apps,
    ContactMail
} from "@material-ui/icons"
import avatar from "../profile_icon_1.png"

// CSS STYLES
const useStyles = makeStyles(theme=>({
    menuSliderContainer: {
        width: 250,
        background: "black",
        height: "100%"
    },
    avatar: {
        display: "block",
        margin: "0.5rem auto",
        width: theme.spacing(13),
        height: theme.spacing(13)
    },
    listItem: {
        color: "cyan"
    }

}));

// Icons

const menuItems = [
    {
        listIcon: <Home/>,
        listText: "Home",
        listPath: "/"
    },
    {
        listIcon: <AssignmentInd/>,
        listText: "Resume",
        listPath: "/resume"
    },
    {
        listIcon: <Apps/>,
        listText: "Portfolio"
    },
    {
        listIcon: <ContactMail/>,
        listText: "Contacts"
    }
]

const Navbar = () => {
    const [state, setState] = useState({
        right: false
 })

const toggleSlider = (slider, open) => () => {
    setState({...state, [slider]: open});
}

    const classes = useStyles()

    const sideList = slider => (

        <Box className={classes.menuSliderContainer} component="div" onClick={toggleSlider(slider,false)}>
            <Avatar className={classes.avatar} src={avatar} alt="Glenn Java" />
            <Divider/>
            <List>
                {menuItems.map((lsItem, key) => (
                    <ListItem button key={key} component={Link} to={lsItem.listPath}>
                        <ListItemIcon className={classes.listItem}>
                            {lsItem.listIcon}
                        </ListItemIcon>
                        <ListItemText className={classes.listItem} primary={lsItem.listText} />
                    </ListItem>
                ))}
            </List>
        </Box>
    )
    return (
        <>
            <Box component="nav">
                <AppBar position ="static" style={{background: "#222"}}>
                    <Toolbar>
                        <IconButton onClick={toggleSlider("right", true)}>
                            <ArrowBack style={{color: "tomato"}}/>
                        </IconButton>
                        <Typography variant="h5" style={{color:"tan"}}>Portfolio</Typography>
                        <MobileRightMenuSlider anchor="right" open={state.right} onClose={toggleSlider("right", false)}>
                            {sideList("right")}
                        </MobileRightMenuSlider>
                    </Toolbar>
                </AppBar>
            </Box>
        </>

    )
};

export default Navbar
</code>```

-- Before Reloading
After clicking the Resume Navbar button, re-directed to this page, but without the content

-- After Reloading
After reloading the page, the content is now displayed

Found in Google Chrome Console

答:
To make it work, you need to put your <Route/> within Switch which in turn should be put under <Router>

```<code>import {
  BrowserRouter as Router,
  Switch,
  Route,
} from "react-router-dom";

    <Router>
       <Switch>
           <Route exact path="/" component ={Home}/>
           <Route path="/resume" component ={Resume}/>
        </Switch>
    </Router>
</code>```

Body:
I am new to ReactJS, having an issue on viewing the display. The route works, but I need to reload the page to display the content. Is there any possible solution without the user to force reload the page to view the content.

--App.js

import React from "react";
import {Route} from "react-router-dom";
import CssBaseline from "@material-ui/core/CssBaseline";
import "./App.css";
import Home from "./components";
import Resume from "./components/Resume"

function App() {
  return (
  <>
    <CssBaseline/>
    <Route exact path="/" component ={Home}/>
    <Route path="/resume" component ={Resume}/>
  </>
  );
}

export default App;

-- Navbar.js

import React, {useState} from 'react';
import {Link} from 'react-router-dom';
import { makeStyles } from '@material-ui/core/styles';
import MobileRightMenuSlider from '@material-ui/core/Drawer';
import {
    AppBar,
    Toolbar,
    ListItem,
    IconButton,
    ListItemText,
    Avatar,
    Divider,
    List,
    Typography,
    Box,
    ListItemIcon
} from "@material-ui/core"
import {
    ArrowBack,
    AssignmentInd,
    Home,
    Apps,
    ContactMail
} from "@material-ui/icons"
import avatar from "../profile_icon_1.png"

// CSS STYLES
const useStyles = makeStyles(theme=>({
    menuSliderContainer: {
        width: 250,
        background: "black",
        height: "100%"
    },
    avatar: {
        display: "block",
        margin: "0.5rem auto",
        width: theme.spacing(13),
        height: theme.spacing(13)
    },
    listItem: {
        color: "cyan"
    }

}));

// Icons

const menuItems = [
    {
        listIcon: <Home/>,
        listText: "Home",
        listPath: "/"
    },
    {
        listIcon: <AssignmentInd/>,
        listText: "Resume",
        listPath: "/resume"
    },
    {
        listIcon: <Apps/>,
        listText: "Portfolio"
    },
    {
        listIcon: <ContactMail/>,
        listText: "Contacts"
    }
]

const Navbar = () => {
    const [state, setState] = useState({
        right: false
 })

const toggleSlider = (slider, open) => () => {
    setState({...state, [slider]: open});
}

    const classes = useStyles()

    const sideList = slider => (

        <Box className={classes.menuSliderContainer} component="div" onClick={toggleSlider(slider,false)}>
            <Avatar className={classes.avatar} src={avatar} alt="Glenn Java" />
            <Divider/>
            <List>
                {menuItems.map((lsItem, key) => (
                    <ListItem button key={key} component={Link} to={lsItem.listPath}>
                        <ListItemIcon className={classes.listItem}>
                            {lsItem.listIcon}
                        </ListItemIcon>
                        <ListItemText className={classes.listItem} primary={lsItem.listText} />
                    </ListItem>
                ))}
            </List>
        </Box>
    )
    return (
        <>
            <Box component="nav">
                <AppBar position ="static" style={{background: "#222"}}>
                    <Toolbar>
                        <IconButton onClick={toggleSlider("right", true)}>
                            <ArrowBack style={{color: "tomato"}}/>
                        </IconButton>
                        <Typography variant="h5" style={{color:"tan"}}>Portfolio</Typography>
                        <MobileRightMenuSlider anchor="right" open={state.right} onClose={toggleSlider("right", false)}>
                            {sideList("right")}
                        </MobileRightMenuSlider>
                    </Toolbar>
                </AppBar>
            </Box>
        </>

    )
};

export default Navbar

-- Before Reloading
After clicking the Resume Navbar button, re-directed to this page, but without the content

-- After Reloading
After reloading the page, the content is now displayed

Found in Google Chrome Console

Body:
To make it work, you need to put your <Route/> within Switch which in turn should be put under <Router>

import {
  BrowserRouter as Router,
  Switch,
  Route,
} from "react-router-dom";

    <Router>
       <Switch>
           <Route exact path="/" component ={Home}/>
           <Route path="/resume" component ={Resume}/>
        </Switch>
    </Router>


问:
Is there a way to export and import the Amazon Connect - contact flow
I checked there is a way to import and export the connect json in the Amazon Connect via UI.

It is working as expected. Is there a API (AWS SDK) available for importing? We want to automate this process! Could someone tell the way for achieving this?

Anyhelp is appreciated.

Thanks,

Harry

答:
Disclaimer : I am not with Amazon Connect product team.

Looking through the  AWS CLI and boto3 docs, there is no API currently (i.e as of 03rd June, 2020) to support import and export of Amazon Connect - contact flow programmatically.

most likely because this feature is still in beta status as per Amazon Connect - Administrator guide


问:
Algorithm to return arg_min and optionally min_val
I made a simple arg min function based on a couple of STL algorithms:

```<code>template<class ForwardIt, class UnaryOperation>
ForwardIt arg_min(ForwardIt first, ForwardIt last, UnaryOperation unary_op)
{
  if (first == last) return last; //we were passed an empty container

  ForwardIt smallest = first; // iterator to the element that results in
                              // the smallest value returned by unary_op
  auto smallest_val = unary_op(*first); //the actual smallest value

  ++first;
  for (; first != last; ++first) {
    auto first_val = unary_op(*first);
    if (first_val < smallest_val) {    // if unary_op returns a smaller than our current smallest value,
      smallest = first;                // store the iterator to the arg
      smallest_val = first_val;        // and the value itself
    }
  }
  return smallest;
}
</code>```

and it works pretty fantastic. However, I knew the time would come that I'd want to get the actual min value back as well as the argument that results in that value.  I could just re-run the returned argument through the UnaryOperation function, but that's kind of sub-optimal.

I guess there are two strategies - 1) pass in a pointer to the value type that the function then fills in or 2) return a std::pair. I don't really like either option since returning the value generated by the arg min element should be optional. For option (1) my initial thought was something like:

```<code>template<class ForwardIt, class UnaryOperation, class MinVal>
ForwardIt arg_min(ForwardIt first, ForwardIt last, UnaryOperation unary_op, MinVal* p_min_val = nullptr)
{
  if (first == last) return last;

  MinVal min_val;

  if(p_min_val == nullptr){
    p_min_val = &min_val;
  }

  ForwardIt smallest = first;
  *p_smallest_val = unary_op(*first);

  ++first;
  for (; first != last; ++first) {
    auto first_val = unary_op(*first);
    if (first_val < smallest_val) {
      smallest = first;
      *p_smallest_val = first_val;
    }
  }
  return smallest;
}
</code>```

I don't think that will work because if p_min_val is nullptr then there's no way to deduce the type MinVal.

Option 2, I'm not sure how to make it return either just smallest or both smallest and min_val.

The only other thing I can thing of is just to define the function twice - once for each case.  Not a terrible option since it's pretty small--I was just wondering if there was another way. Is there?

答:
My advice? return the pair. Let the caller decide if they want the min projected value. You've already calculated it - it's a shame for you, who doesn't know the caller's intention, to throw it away.

Want just the iterator? auto iter = arg_min(first, last, op).first;

Want just the min value? auto value = *arg_min(first, last, op).first;

Want just the min projected value? auto pValue = arg_min(first, last, op).second;

Body:
I made a simple arg min function based on a couple of STL algorithms:

template<class ForwardIt, class UnaryOperation>
ForwardIt arg_min(ForwardIt first, ForwardIt last, UnaryOperation unary_op)
{
  if (first == last) return last; //we were passed an empty container

  ForwardIt smallest = first; // iterator to the element that results in
                              // the smallest value returned by unary_op
  auto smallest_val = unary_op(*first); //the actual smallest value

  ++first;
  for (; first != last; ++first) {
    auto first_val = unary_op(*first);
    if (first_val < smallest_val) {    // if unary_op returns a smaller than our current smallest value,
      smallest = first;                // store the iterator to the arg
      smallest_val = first_val;        // and the value itself
    }
  }
  return smallest;
}

and it works pretty fantastic. However, I knew the time would come that I'd want to get the actual min value back as well as the argument that results in that value.  I could just re-run the returned argument through the UnaryOperation function, but that's kind of sub-optimal.

I guess there are two strategies - 1) pass in a pointer to the value type that the function then fills in or 2) return a std::pair. I don't really like either option since returning the value generated by the arg min element should be optional. For option (1) my initial thought was something like:

template<class ForwardIt, class UnaryOperation, class MinVal>
ForwardIt arg_min(ForwardIt first, ForwardIt last, UnaryOperation unary_op, MinVal* p_min_val = nullptr)
{
  if (first == last) return last;

  MinVal min_val;

  if(p_min_val == nullptr){
    p_min_val = &min_val;
  }

  ForwardIt smallest = first;
  *p_smallest_val = unary_op(*first);

  ++first;
  for (; first != last; ++first) {
    auto first_val = unary_op(*first);
    if (first_val < smallest_val) {
      smallest = first;
      *p_smallest_val = first_val;
    }
  }
  return smallest;
}

I don't think that will work because if p_min_val is nullptr then there's no way to deduce the type MinVal.

Option 2, I'm not sure how to make it return either just smallest or both smallest and min_val.

The only other thing I can thing of is just to define the function twice - once for each case.  Not a terrible option since it's pretty small--I was just wondering if there was another way. Is there?


问:
MySQL String concatenation of Title and Name
I have 2 Tables Patient table and  Title table

Patient Table 3 Fields

```<code>PatientTableID    FirstName PatTitleLookup
1                  John      (Value Stored as integer)
2                  Mary      (Value Stored as integer)
</code>```

Title Table 2 Fields

```<code>ID  Title
1      Mr.
2      Ms.
</code>```

I want to concatenate Title and First Name

So I use this

```<code>SELECT CONCAT(`PatientTable`.`PatTitleLookup`, '. ', `PatientTable`.`FirstName`)
FROM `PatientTable`
WHERE `PatientTable`.`PatientTableID` = 1
</code>```

I get
"1.John" instead of "Mr. John"
"2.Mary" instead of "Ms. Mary"

Please advise I am sure my syntax is wrong

答:
You need to join the titles table to get the values from it. Use an on for how the data should join.

```<code>SELECT CONCAT(t.title, '. ', pt.FirstName)
FROM PatientTable as pt
join Title as t
on pt.PatTitleLookup = t.id
WHERE pt.PatientTableID = 1
</code>```

I also have used aliases (as pt, as t) here for your tables, makes referencing shorter later in queries.

Body:
I have 2 Tables Patient table and  Title table

Patient Table 3 Fields

PatientTableID    FirstName PatTitleLookup
1                  John      (Value Stored as integer)
2                  Mary      (Value Stored as integer)

Title Table 2 Fields

ID  Title
1      Mr.
2      Ms.

I want to concatenate Title and First Name

So I use this

SELECT CONCAT(`PatientTable`.`PatTitleLookup`, '. ', `PatientTable`.`FirstName`)
FROM `PatientTable`
WHERE `PatientTable`.`PatientTableID` = 1

I get
"1.John" instead of "Mr. John"
"2.Mary" instead of "Ms. Mary"

Please advise I am sure my syntax is wrong

Body:
You need to join the titles table to get the values from it. Use an on for how the data should join.

SELECT CONCAT(t.title, '. ', pt.FirstName)
FROM PatientTable as pt
join Title as t
on pt.PatTitleLookup = t.id
WHERE pt.PatientTableID = 1

I also have used aliases (as pt, as t) here for your tables, makes referencing shorter later in queries.


问:
Simple java lib for text templating?
I need to template some email texts. Nothing fancy, just replace something like @name@ with real value. No pictures, no fancy formatting etc.

What java lib could you recommend? The simplier the better.

答:
Agreed, Apache's Velocity is a good call for embedded situations.

If you want a stand-alone product, you can also use Apache's Ant.  It reduces the template within a copy task by applying substitution filters.

ContentLicense: CC BY-SA 3.0

Title: Simple java lib for text templating?


问:
How to support Zoom like Safari with WKWebView on macOS
In Safari the user can enlarge the content by using the Zoom commands, like Command +. This enlarges not only the content, including font size, but it also adjusts the content to remain between the window margins.

I want to achieve the same feature with WKWebView on macOS, but I don't know how to do that when using the loadRequest() command on the web view control.

I have tried the following, without much success:

Inject javascript like "document.getElementsByTagName('body')[0].style.webkitTextSizeAdjust='150%'". It seems that webkitTextSizeAdjust is not supported anymore on the macOS version of WKWebView, see https://trac.webkit.org/changeset/145168/webkit.

Use the magnification property. This works, but this simply enlarges (or minimises) everything, without adjusting the content to remain between the control width (viewport), like Safari does.

Please take note that I'm using loadRequest(), not loadHTMLString().

答:
I encountered the same prblem, and found a solution. You need to set an JavaScript code injection to the WkWebView configuration. The scale number needs to be set in the JavaScript code.

The full code is shown below:

```<code>NSString *jScript = @"document.body.style.zoom = 0.8";
WKUserScript *wkUScript = [[WKUserScript alloc] initWithSource:jScript injectionTime:WKUserScriptInjectionTimeAtDocumentEnd forMainFrameOnly:YES];

WKUserContentController *wkUController = [[WKUserContentController alloc] init];
[wkUController addUserScript:wkUScript];

WKWebViewConfiguration *configuration = [[WKWebViewConfiguration alloc] init];
configuration.userContentController = wkUController;

WKWebView *webContentView = [[WKWebView alloc] initWithFrame:NSMakeRect(0, 0,sizeWidth, sizeHeight) configuration:configuration];
</code>```

Body:
I encountered the same prblem, and found a solution. You need to set an JavaScript code injection to the WkWebView configuration. The scale number needs to be set in the JavaScript code.

The full code is shown below:

NSString *jScript = @"document.body.style.zoom = 0.8";
WKUserScript *wkUScript = [[WKUserScript alloc] initWithSource:jScript injectionTime:WKUserScriptInjectionTimeAtDocumentEnd forMainFrameOnly:YES];

WKUserContentController *wkUController = [[WKUserContentController alloc] init];
[wkUController addUserScript:wkUScript];

WKWebViewConfiguration *configuration = [[WKWebViewConfiguration alloc] init];
configuration.userContentController = wkUController;

WKWebView *webContentView = [[WKWebView alloc] initWithFrame:NSMakeRect(0, 0,sizeWidth, sizeHeight) configuration:configuration];


问:
JavaScript split array in half juxtapose the first half with second half
What is the method to evenly split an array into two.  Then, position the second half underneath the first all for the purpose of comparing whether or not a new final array should receive a zero or one in the slots.

var master_array = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38];

var first_half = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19];

var second_half = [20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38];

var final_usable_array_reduced = [];

So, given a form with 38 check boxes, if the 5th, 19th, 37th, and 38th check boxes were checked, the final_usable_array_reduced would be

final_usable_array_reduced = [0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1];

final_usable_array_reduced[4] = **represents the 5th or 24th box being checked**

final_usable_array_reduced[18] = **represents the 19th or 38th boxes being checked**

答:
I think you can implement this with a simple for loop over half the master_array, oring the values in the bottom half of the array with those in the top half:

var master_array = new Array(38).fill(0);
master_array[4] = 1;
master_array[18] = 1;
master_array[36] = 1;
master_array[37] = 1;

let len = master_array.length / 2;
final_usable_array_reduced = new Array(len);
for (let i = 0; i < len; i++) {
  final_usable_array_reduced[i] = master_array[i] | master_array[i + len];
}
console.log(final_usable_array_reduced);```


问:
How Can I Achieve a Singleton Subscription To router.events in Angular 9
```<code>    constructor(
    private route: ActivatedRoute,
    private router: Router,
    private viewportScroller: ViewportScroller
  ) {
    this.router.events
      .pipe(filter((e): e is Scroll => e instanceof Scroll))
      .subscribe((e) => {
        if (e.position) {
          console.log("// position navigation", e.position);
          this.viewportScroller.scrollToPosition(e.position);
        } else if (e.anchor) {
          console.log("// anchor navigation", e.anchor);
          this.viewportScroller.scrollToAnchor(e.anchor);
        } else {
          console.log("// forward navigation");
        }
      });
  }
</code>```

I have the code above (or equivalent) in an angular 9 component. When I move back and forth in the application, coming to the component again and again using forward and back navigation, I notice that the subscriptions to router.events keep mounting up... Yet there is no way to unsubscribe from the router.events for instance inside of ngOnDestroy... How can I achieve a singleton event subscription in this case?

答:
An Observable doesn't have an unsubscribe method but a Subscription does. When you call .subscribe on an Observable, it returns a Subscription object. This is what we use to unsubscribe from our Observables.

```<code>export class YourComponent implements OnDestroy {
    routerSubscription: Subscription;

    constructor(
    private route: ActivatedRoute,
    private router: Router,
    private viewportScroller: ViewportScroller
  ) {
    this.routerSubscription = this.router.events
      .pipe(filter((e): e is Scroll => e instanceof Scroll))
      .subscribe((e) => {
        if (e.position) {
          console.log("// position navigation", e.position);
          this.viewportScroller.scrollToPosition(e.position);
        } else if (e.anchor) {
          console.log("// anchor navigation", e.anchor);
          this.viewportScroller.scrollToAnchor(e.anchor);
        } else {
          console.log("// forward navigation");
        }
      });
  }

  ngOnDestroy() {
    if (this.routerSubscription) {
      this.routerSubscription.unsubscribe();
      this.routerSubscription = undefined; // just in case. If this.routerSubscription is undefined, calling .unsubscribe() on it will throw an error and halt your component
    }

  }
}
</code>```

Above is a simple example. Hope this helps

Body:
    constructor(
    private route: ActivatedRoute,
    private router: Router,
    private viewportScroller: ViewportScroller
  ) {
    this.router.events
      .pipe(filter((e): e is Scroll => e instanceof Scroll))
      .subscribe((e) => {
        if (e.position) {
          console.log("// position navigation", e.position);
          this.viewportScroller.scrollToPosition(e.position);
        } else if (e.anchor) {
          console.log("// anchor navigation", e.anchor);
          this.viewportScroller.scrollToAnchor(e.anchor);
        } else {
          console.log("// forward navigation");
        }
      });
  }

I have the code above (or equivalent) in an angular 9 component. When I move back and forth in the application, coming to the component again and again using forward and back navigation, I notice that the subscriptions to router.events keep mounting up... Yet there is no way to unsubscribe from the router.events for instance inside of ngOnDestroy... How can I achieve a singleton event subscription in this case?

Body:
An Observable doesn't have an unsubscribe method but a Subscription does. When you call .subscribe on an Observable, it returns a Subscription object. This is what we use to unsubscribe from our Observables.

export class YourComponent implements OnDestroy {
    routerSubscription: Subscription;

    constructor(
    private route: ActivatedRoute,
    private router: Router,
    private viewportScroller: ViewportScroller
  ) {
    this.routerSubscription = this.router.events
      .pipe(filter((e): e is Scroll => e instanceof Scroll))
      .subscribe((e) => {
        if (e.position) {
          console.log("// position navigation", e.position);
          this.viewportScroller.scrollToPosition(e.position);
        } else if (e.anchor) {
          console.log("// anchor navigation", e.anchor);
          this.viewportScroller.scrollToAnchor(e.anchor);
        } else {
          console.log("// forward navigation");
        }
      });
  }

  ngOnDestroy() {
    if (this.routerSubscription) {
      this.routerSubscription.unsubscribe();
      this.routerSubscription = undefined; // just in case. If this.routerSubscription is undefined, calling .unsubscribe() on it will throw an error and halt your component
    }

  }
}

Above is a simple example. Hope this helps


问:
lanterna.InputProvider.pollInput() crashes the application on launch while readInput() does not and works as expected
I am using lanterna to build a front end for my application and it requires a non-blocking input method so the displayed data can continuously refresh.

for some reason the method for non-blocking input (pollInput) crashes on calling while the blocking method of the same class (readInput) works as intended

https://github.com/CaderHancock/options

```<code>                while(itsPartyTime)
                {       try
                        {
                                 keyStroke = screen.pollInput();
                                textGraphics.putString(15,15, keyStroke.toString() );
                        }catch(Exception e){
                                textGraphics.putString(15,15, e.getMessage());
                        }
</code>```

the above crashes

if the method readInput() is used instead everything works

答:
screen.pollInput() will return null and continue on

So in your loop, most of the time it will be null, which is expected.

Body:
I am using lanterna to build a front end for my application and it requires a non-blocking input method so the displayed data can continuously refresh.

for some reason the method for non-blocking input (pollInput) crashes on calling while the blocking method of the same class (readInput) works as intended

https://github.com/CaderHancock/options

                while(itsPartyTime)
                {       try
                        {
                                 keyStroke = screen.pollInput();
                                textGraphics.putString(15,15, keyStroke.toString() );
                        }catch(Exception e){
                                textGraphics.putString(15,15, e.getMessage());
                        }

the above crashes

if the method readInput() is used instead everything works


问:
Cannot close dialog window using Javascript in Crm
I am not able to close the dialog window(on clicking the cancel button) that is opened on click event of a button in ribbon using javascript in microsoft dynamics crm 2016. I am a beginner in Crm. I will appreciate any kind of help. Thank you in advance.

Here's the code that opens the dialog:

```<code>    function NewDialog()
{
var DialogOptions = new Xrm.DialogOptions();
DialogOptions.width = 500;
DialogOptions.height = 500;
debugger;
window.parent.Xrm.Internal.openDialog(Mscrm.CrmUri.create("/WebResources/new_popupDialog").toString(), DialogOptions, null, null, CallbackFunction);
    function CallbackFunction(oReturn) {

     }
    }
</code>```

Here,s the web resource HTML code for the Dialog window:

```<code><html><head>
    <title></title>
    <script src="../ClientGlobalContext.js.aspx" type="text/javascript"></script>
<script>
</script>
    <style type="text/css">
        body {
            direction: LTR;
            margin: 0px;
            border: 0px;
            cursor: default;
            font-family: Segoe UI,Tahoma,Arial;
            font-size: 11px;
        }

        .ms-crm-RefreshDialog-Header {
            top: 0px;
            position: absolute;
            width: 96%;
            height: 75px;
            padding-top: 10px;
            background-color: #FFFFFF;
            border-bottom-color: #A4ABB2;
        }

        DIV.ms-crm-RefreshDialog-Header-Title {
            font-weight: Lighter;
            font-size: 27px;
            font-family: Segoe UI Light, Segoe UI, Tahoma, Arial;
            margin-left: 30px;
            margin-right: 30px;
            color: #262626;
        }

        .ms-crm-TextAutoEllipsis {
            overflow: hidden;
            text-overflow: ellipsis;
            white-space: nowrap;
        }

        .ms-crm-RefreshDialog-Header-Desc {
            padding-top: 4px;
            font-family: Segoe UI,Tahoma,Arial;
            margin-left: 30px;
            margin-right: 30px;
            color: #666666;
            font-size: 12px;
        }

        .ms-crm-RefreshDialog-Main {
            font-size: 12px;
            top: 90px;
            position: absolute;
            bottom: 49px;
            vertical-align: top;
            width: 95%;
            font-family: Segoe UI,Tahoma,Arial;
            color: #444444;
            background-color: #FFFFFF;
            border-bottom-color: #A4ABB2;
            right: 30px;
            left: 30px;
        }

        .ms-crm-RefreshDialog-Footer {
            position: absolute;
            bottom: 0px;
            width: 100%;
            min-width: 288px;
            height: 44px;
            text-align: right;
            background-color: #F8F8F8;
            border-top-color: #FFFFFF;
        }

        .ms-crm-RefreshDialog-Button {
            color: #444444;
            background-color: #FFFFFF;
            height: 24px;
            font-family: Segoe UI,Tahoma,Arial;
            border: 1px solid #C6C6C6;
            background-image: none;
            margin-top: 10px;
            width: auto;
            min-width: 80px;
            white-space: nowrap;
            font-size: 12px;
            line-height: 16px;
            width: 84px;
            text-align: center;
            cursor: pointer;
            background-repeat: repeat-x;
            padding-left: 5px;
            padding-right: 5px;
        }
    </style>
<meta charset="utf-8"></head>
<body>
    <div class="ms-crm-RefreshDialog-Main-Container" style="font-family: undefined;">
        <div class="ms-crm-RefreshDialog-Header" id="tdDialogHeader">
            <div title="Your dialog header" class="ms-crm-RefreshDialog-Header-Title ms-crm-TextAutoEllipsis" id="dialogHeaderTitle" style="width: 75%;">My Custom Page</div>
            <div title="Your dialog additional description" class="ms-crm-RefreshDialog-Header-Desc" id="dialogHeaderDesc">Rohit</div>
            <div class="ms-crm-RefreshDialog-Main" id="DlgHdBodyContainer">
                <form action="demo_form.asp">
                    First name:   <select id="selectmenu"><option selected="selected" value="">                    Select an option                 </option>                 <option value="option1">Option One</option>                 <option value="option2">Option Two</option>                 <option value="option1N">Option N</option>             </select><br>
                    <br>

                </form>
            </div>
        </div>
        <div class="ms-crm-RefreshDialog-Footer" id="tdDialogFooter">
            <button tabindex="1" class="ms-crm-RefreshDialog-Button" id="btnOK" style="margin-left: 8px;" onclick="window.parent.Mscrm.Utilities.setReturnValue(true); window.parent.closeWindow();" type="button">
                OK
            </button>
            <button tabindex="1" class="ms-crm-RefreshDialog-Button" id="cmdDialogCancel" style="margin-right: 30px; margin-left: 8px;" onclick="window.parent.closeWindow();" type="button">
                Cancel
            </button>
        </div>
    </div>

</body></html>
</code>```

Here's the screenshot of the dialog:

答:
You can using js to click X (close button on top right) as below from Webresource</p>

```<code>window.parent.document.getElementById('InlineDialogCloseLink').click()
</code>```

Body:
I am not able to close the dialog window(on clicking the cancel button) that is opened on click event of a button in ribbon using javascript in microsoft dynamics crm 2016. I am a beginner in Crm. I will appreciate any kind of help. Thank you in advance.

Here's the code that opens the dialog:

    function NewDialog()
{
var DialogOptions = new Xrm.DialogOptions();
DialogOptions.width = 500;
DialogOptions.height = 500;
debugger;
window.parent.Xrm.Internal.openDialog(Mscrm.CrmUri.create("/WebResources/new_popupDialog").toString(), DialogOptions, null, null, CallbackFunction);
    function CallbackFunction(oReturn) {

     }
    }

Here,s the web resource HTML code for the Dialog window:

    <title></title>

<meta charset="utf-8">

My Custom Page

Rohit

                <form action="demo_form.asp">
                    First name:   <select id="selectmenu"><option selected="selected" value="">                    Select an option                 </option>                 <option value="option1">Option One</option>                 <option value="option2">Option Two</option>                 <option value="option1N">Option N</option>             </select>

                </form>

            <button tabindex="1" class="ms-crm-RefreshDialog-Button" id="btnOK" style="margin-left: 8px;" onclick="window.parent.Mscrm.Utilities.setReturnValue(true); window.parent.closeWindow();" type="button">
                OK
            </button>
            <button tabindex="1" class="ms-crm-RefreshDialog-Button" id="cmdDialogCancel" style="margin-right: 30px; margin-left: 8px;" onclick="window.parent.closeWindow();" type="button">
                Cancel
            </button>

Here's the screenshot of the dialog:

Body:
You can using js to click X (close button on top right) as below from Webresource

window.parent.document.getElementById('InlineDialogCloseLink').click()


问:
convert vanilla javascript into react hooks
I am trying to a intergrate a materialize.css Paralex plugin into my react hook functional component. how do i do that ? here is the code </p>

```<code>document.addEventListener('DOMContentLoaded', function() {
    var elems = document.querySelectorAll('.parallax');
    var instances = M.Parallax.init(elems, options);
  });
</code>```

<p>please assist </p>

答:
This is how you do with class components:

```<code>componentDidMount() {
  var elems = document.querySelectorAll('.parallax');
  var instances = M.Parallax.init(elems, options);
}
</code>```

Functional components:

```<code>useEffect(() => {
  var elems = document.querySelectorAll('.parallax');
  var instances = M.Parallax.init(elems, options);
}, [])
</code>```

Hope this is what you needed :)

Body:
I am trying to a intergrate a materialize.css Paralex plugin into my react hook functional component. how do i do that ? here is the code

document.addEventListener('DOMContentLoaded', function() {
    var elems = document.querySelectorAll('.parallax');
    var instances = M.Parallax.init(elems, options);
  });

please assist

Body:
This is how you do with class components:

componentDidMount() {
  var elems = document.querySelectorAll('.parallax');
  var instances = M.Parallax.init(elems, options);
}

Functional components:

useEffect(() => {
  var elems = document.querySelectorAll('.parallax');
  var instances = M.Parallax.init(elems, options);
}, [])

Hope this is what you needed :)


问:
unable to connect to docker nginx container from host
centos 7.8

docker run -d -p 8080:80 --name nginxtest nginx

docker ps

CONTAINER ID IMAGE PORTS                NAMES

xxxxxxxxxxxxxx       nginx 0.0.0.0:8080->80/tcp nginxtest

curl localhost:8080

curl: (56) Recv failure: Connection reset by peer

netstat -tulpn

tcp6 0 0 :::8080 :::* LISTEN 13467/docker-proxy

Is there any other way to check what went wrong?

答: restart server, and problem solved.</p>

Body: restart server, and problem solved.


问:
How to filter FileUpload Control?
How to add filter to the fileupload control in asp.net? I want a filter for Oasis File (.000).?

Please advice me... thank you very much!

答:
You can use javascript to filter it on server side..

Try this here

Title: How to filter FileUpload Control?


问:
COPY with docker but with exclusion
In a Dockerfile, I have

```<code>COPY . .
</code>```

I want to exclude an entire directory, in my case, node_modules directory.

Something like this:

```<code>   COPY [all but **/node_modules/**] .
</code>```

Is this possible with Docker?

答:
Excluding node_modules from current directory

```<code>node_modules
</code>```

Excluding node_modules in any immediate subdirectories

```<code>*/node_modules
</code>```

Here is the official docs

Title: COPY with docker but with exclusion

Body:
In a Dockerfile, I have

COPY . .

I want to exclude an entire directory, in my case, node_modules directory.

Something like this:

   COPY [all but **/node_modules/**] .

Is this possible with Docker?

Body:
Excluding node_modules from current directory

node_modules

Excluding node_modules in any immediate subdirectories

*/node_modules

Here is the official docs


问:
Command prompt gets stuck and continues on enter key press
Does anyone come across a scenario when the command prompt is running a process and then it gets stuck and the process is also sleeping.
Then when we press Enter key in the cmd window the process continues.

Is there any way to avoid this?
or can this be handled??

答:
The other answers are wrong! The Windows console has a separate mode called "mark mode" for selecting text. In that mode the screen will be frozen, texts will go into the buffer and if the buffer is full the running process will be blocked

If quick edit mode is enabled (by default it's disabled in older Windows but enabled in Windows 10) then clicking inside the console window will activate mark mode and result in what you observed

It's very easy to accidentally click the console and stop the command. When you press Enter or Esc the selected text will be copied to clipboard and mark mode will be exited, therefore the process will run again. Priority is absolutely irrelevant here because if the buffer is full then the process is blocked forever until you exit mark mode, regardless of the priority. The console does nothing to change the priority when there are some inputs. Try opening an app that outputs a lot of data in the highest priority and click the console, the app will still be blocked indefinitely even if the CPU is in idle

Here's an example of QuickEdit mode setting in Windows 8 console:

To fix this you can disable QuickEdit mode if you don't need it. In this case copying will be more troublesome because you must open the context menu, select Edit > Mark. You can also disable QuickEdit mode by setting ENABLE_QUICK_EDIT_MODE with SetConsoleMode() if you're writing your own console application

See also

How and why does QuickEdit mode in Command Prompt freeze applications?

What does it do exactly if I click in the window of cmd?

Turn off Windows 10 console "Mark" mode from my application


问:
Getting Error on Codepen: Uncaught ReferenceError: $ is not defined
getting the below error on codepen. Not sure what's happening. What exactly is not defined and what should I change?

$(function() {
  $("#btnHideBanana").click(function() {
    $("#banana").collapse("hide")
  });
  $("#btnShowBanana").click(function() {
    $("#banana").collapse("show")
  });
});
$(document).ready(function() {
  $("#btnHideMonkey").click(function() {
    $("#monkey").collapse("hide")
  });
  $("#btnShowMonkey").click(function() {
    $("#monkey").collapse("show")
  });
});```

https://codepen.io/ganiya/pen/MWKWjKX?editors=1010

答:
In order to use the jquery $ sign, you need to include jquery script path.

```<code><script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
</code>```

$(function() {
  $("#btnHideBanana").click(function() {
    $("#banana").collapse("hide")
  });
  $("#btnShowBanana").click(function() {
    $("#banana").collapse("show")
  });
});
$(document).ready(function() {
  $("#btnHideMonkey").click(function() {
    $("#monkey").collapse("hide")
  });
  $("#btnShowMonkey").click(function() {
    $("#monkey").collapse("show")
  });
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script></code>```

Body:
getting the below error on codepen. Not sure what's happening. What exactly is not defined and what should I change?

$(function() {
  $("#btnHideBanana").click(function() {
    $("#banana").collapse("hide")
  });
  $("#btnShowBanana").click(function() {
    $("#banana").collapse("show")
  });
});
$(document).ready(function() {
  $("#btnHideMonkey").click(function() {
    $("#monkey").collapse("hide")
  });
  $("#btnShowMonkey").click(function() {
    $("#monkey").collapse("show")
  });
});

https://codepen.io/ganiya/pen/MWKWjKX?editors=1010

Body:
In order to use the jquery $ sign, you need to include jquery script path.

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>

$(function() {
  $("#btnHideBanana").click(function() {
    $("#banana").collapse("hide")
  });
  $("#btnShowBanana").click(function() {
    $("#banana").collapse("show")
  });
});
$(document).ready(function() {
  $("#btnHideMonkey").click(function() {
    $("#monkey").collapse("hide")
  });
  $("#btnShowMonkey").click(function() {
    $("#monkey").collapse("show")
  });
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>


问:
Fetch from two APIs in loop and combine
I'm trying to do what I thought would be pretty straightforward, but is turning out to be pretty hard. Essentially what I want to do is when loading the page, loop through an array of IDs, make a call to two APIs for each ID, merge the responses together for each ID, and save that to a React state variable itemList.

This is the code I have so far. The two getInfo() and getOtherInfo() functions are doing a basic JavaScript Fetch and are returning a Promise and then the decoded JSON data asynchronously no problem. I can even display the returned data on the page as it gets loaded, so that part works fine.

```<code>useEffect(() => {
  idList.forEach((id) => {
    getInfo(id)
      .then((response) => {
        getOtherInfo(id).then((otherReponse) => {
          response.otherInfo = otherResponse;
        });
        setItemList((itemList) => [...itemList, response]);
      })
      .catch((error) => console.log("Loading failed: " + error));
  });
}, []);
</code>```

I know that the nested .then() is wrong, as it's trying to add response data to a potentially unresolved Promise, but it's my first time using React Hooks and the Fetch API so I'm not sure what the right way to do it is. I've found a couple other similar questions, but they don't seem to deal with joining the data together after it gets returned from the two APIs.

Can someone point me in the right direction here?

答:
I know that the nested .then() is wrong, as it's trying to add response data to a potentially unresolved Promise

If you need the resolved values of response and otherResponse before continuing, it's better to put the logic needed inside the inner then() continuation. This is what you've done when setting response.otherInfo = otherResponse, but I think the setItemList call should also be inside that continuation.

```<code>useEffect(() => {
  idList.forEach((id) => {
    getInfo(id)
      .then((response) => {
        getOtherInfo(id).then((otherReponse) => {
          response.otherInfo = otherResponse;
          setItemList((itemList) => [...itemList, response]);
        });
      })
      .catch((error) => console.log("Loading failed: " + error));
  });
}, []);
</code>```

If the request to getOtherInfo is not dependent on the outcome of getInfo, then it may be beneficial to execute those requests concurrently using Promise.all.

```<code>useEffect(() => {
  idList.forEach((id) => {
    Promise.all([getInfo(id), getOtherInfo(id)])
      .then(([response, otherResponse]) => {
        response.otherInfo = otherResponse;
        setItemList((itemList) => [...itemList, response]);
      })
      .catch((error) => console.log("Loading failed: " + error));
  });
}, []);
</code>```

Title: Fetch from two APIs in loop and combine

Body:
I'm trying to do what I thought would be pretty straightforward, but is turning out to be pretty hard. Essentially what I want to do is when loading the page, loop through an array of IDs, make a call to two APIs for each ID, merge the responses together for each ID, and save that to a React state variable itemList.

This is the code I have so far. The two getInfo() and getOtherInfo() functions are doing a basic JavaScript Fetch and are returning a Promise and then the decoded JSON data asynchronously no problem. I can even display the returned data on the page as it gets loaded, so that part works fine.

useEffect(() => {
  idList.forEach((id) => {
    getInfo(id)
      .then((response) => {
        getOtherInfo(id).then((otherReponse) => {
          response.otherInfo = otherResponse;
        });
        setItemList((itemList) => [...itemList, response]);
      })
      .catch((error) => console.log("Loading failed: " + error));
  });
}, []);

I know that the nested .then() is wrong, as it's trying to add response data to a potentially unresolved Promise, but it's my first time using React Hooks and the Fetch API so I'm not sure what the right way to do it is. I've found a couple other similar questions, but they don't seem to deal with joining the data together after it gets returned from the two APIs.

Can someone point me in the right direction here?

Body:
I know that the nested .then() is wrong, as it's trying to add response data to a potentially unresolved Promise

If you need the resolved values of response and otherResponse before continuing, it's better to put the logic needed inside the inner then() continuation. This is what you've done when setting response.otherInfo = otherResponse, but I think the setItemList call should also be inside that continuation.

useEffect(() => {
  idList.forEach((id) => {
    getInfo(id)
      .then((response) => {
        getOtherInfo(id).then((otherReponse) => {
          response.otherInfo = otherResponse;
          setItemList((itemList) => [...itemList, response]);
        });
      })
      .catch((error) => console.log("Loading failed: " + error));
  });
}, []);

If the request to getOtherInfo is not dependent on the outcome of getInfo, then it may be beneficial to execute those requests concurrently using Promise.all.

useEffect(() => {
  idList.forEach((id) => {
    Promise.all([getInfo(id), getOtherInfo(id)])
      .then(([response, otherResponse]) => {
        response.otherInfo = otherResponse;
        setItemList((itemList) => [...itemList, response]);
      })
      .catch((error) => console.log("Loading failed: " + error));
  });
}, []);


答: A library-free alternative to the libraries already suggested: java.text.MessageFormat.

Title: Simple java lib for text templating?

Body:
I need to template some email texts. Nothing fancy, just replace something like @name@ with real value. No pictures, no fancy formatting etc.

What java lib could you recommend? The simplier the better.


问:
How to space strings in an array of strings
I am trying to create a dynamic list using the following code:

```<code>const permissions: string[] = []

Object.keys(userPerms).forEach((key) => {
  permissions.push(`${capitalise(key)} ${userPerms[key] ? '' : ''}`)
})
</code>```

The output I want:

```<code>Send Messages
Join Call
Send Emojis
</code>```

The output I am getting with my current code:

```<code>Send Messages
Join Call
Send Emojis
</code>```

答:
You can use this snippet. You need to calculate the maximum length of the permission string key. After that add spaces according to that maximum length. If you want to do it by hand.

let userPerms = {
  "Send Messages": true,
  "Join Call": false,
  "Send Emojis": true,
};

// Find maximum lenght
let max = 0;
Object.keys(userPerms).forEach((key) => {
  if (key.length > max) {
    max = key.length;
  }
});

// Give additional 2 spaces
max += 2;

const permissions = []
Object.keys(userPerms).forEach((key) => {
  permissions.push(key.concat(' '.repeat(max - key.length)) + (userPerms[key] ? '' : ''))
})

console.log(permissions);```
</div>
</div>
</p>

<p>More elegant solution will be:</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>let userPerms = {
  "Send Messages": true,
  "Join Call": false,
  "Send Emojis": true,
};
const permissions = []

// Find maximum lenght
let max = Object.keys(userPerms).sort(function (a, b) { return b.length - a.length; })[0].length + 2 // space between;
// Add to array
Object.keys(userPerms).forEach((key) => {
  permissions.push(key.padEnd(max) + (userPerms[key] ? '' : ''))
});

console.log(permissions);</code>```

Body:
I am trying to create a dynamic list using the following code:

const permissions: string[] = []

Object.keys(userPerms).forEach((key) => {
  permissions.push(`${capitalise(key)} ${userPerms[key] ? '' : ''}`)
})

The output I want:

Send Messages
Join Call
Send Emojis

The output I am getting with my current code:

Send Messages
Join Call
Send Emojis

Body:
You can use this snippet. You need to calculate the maximum length of the permission string key. After that add spaces according to that maximum length. If you want to do it by hand.

let userPerms = {
  "Send Messages": true,
  "Join Call": false,
  "Send Emojis": true,
};

// Find maximum lenght
let max = 0;
Object.keys(userPerms).forEach((key) => {
  if (key.length > max) {
    max = key.length;
  }
});

// Give additional 2 spaces
max += 2;

const permissions = []
Object.keys(userPerms).forEach((key) => {
  permissions.push(key.concat(' '.repeat(max - key.length)) + (userPerms[key] ? '' : ''))
})

console.log(permissions);

More elegant solution will be:

let userPerms = {
  "Send Messages": true,
  "Join Call": false,
  "Send Emojis": true,
};
const permissions = []

// Find maximum lenght
let max = Object.keys(userPerms).sort(function (a, b) { return b.length - a.length; })[0].length + 2 // space between;
// Add to array
Object.keys(userPerms).forEach((key) => {
  permissions.push(key.padEnd(max) + (userPerms[key] ? '' : ''))
});

console.log(permissions);


问:
How to change permission of mapped and committed memory space?
I had tried to read and write data to memory space in any process.
I used VirtualProtect() and VirtualProtectEx() functions to change permission of memory area.

```<code>if(!VirtualProtect(dwAddr, dwSize, PAGE_EXECUTE_READWRITE, &dwOldProtect))
{
    printf("VirtualProtect failed error %d", GetLastError());
}

CopyMemory(dwAddr, pBuffer, dwSize);
</code>```

But I had error 5 (access denied) code, instead of good result.

So I checked memory information by using VirtualQuery() function.

```<code>MEMORY_BASIC_INFORMATION info;

VirtualQuery(dwAddr, &info, sizeof(info));
</code>```

Result was following by:

```<code>info.Type = MEM_MAPPED;
info.State = MEM_COMMITED;
info.AllocationProtect = PAGE_WRITECOPY;
info.Protect = PAGE_READ;
</code>```

Therefore I could not change permission of mapped and committed memory.

If there are another ways, please let me know it.

答:
If it's an external process you must run your application as administrator and you must use VirtualQueryEx().

You problem appears to be that you are not running as administrator.  If you're running as admin and using VirtualQueryEx() and is still fails, then you need to check your handle returned by OpenProcess() and make sure it's good.

Check return values and use GetLastError() after calling the APIs to further diagnose the issue.

Body:
I had tried to read and write data to memory space in any process.
I used VirtualProtect() and VirtualProtectEx() functions to change permission of memory area.

if(!VirtualProtect(dwAddr, dwSize, PAGE_EXECUTE_READWRITE, &dwOldProtect))
{
    printf("VirtualProtect failed error %d", GetLastError());
}

CopyMemory(dwAddr, pBuffer, dwSize);

But I had error 5 (access denied) code, instead of good result.

So I checked memory information by using VirtualQuery() function.

MEMORY_BASIC_INFORMATION info;

VirtualQuery(dwAddr, &info, sizeof(info));

Result was following by:

info.Type = MEM_MAPPED;
info.State = MEM_COMMITED;
info.AllocationProtect = PAGE_WRITECOPY;
info.Protect = PAGE_READ;

Therefore I could not change permission of mapped and committed memory.

If there are another ways, please let me know it.


问:
Label is not updating after using .after() function in tkinter Python for countdown clock
I'm working on countdown timer with GUI and I'm trying to copy the GUI of Windows 10 coundown timer app. The GUI part is almost done and only the execution part remains:

```<code>def start_countdown():
    global hours, minutes, seconds, timer
    user_input = (int(hours)*60*60 + int(minutes)*60 + int(seconds))

    timerrr = int(user_input)

    while timerrr > 0:
        minutes, seconds = divmod(timerrr, 60)
        hours, minutes = divmod(minutes, 60)
        timer.config(text=str(hours).zfill(2) + ":" + str(minutes).zfill(2) + ":" + str(seconds).zfill(2))
        print(str(timer.cget("text")) + "\r", end=str(timer.cget("text")))
        time.sleep(1)
        timerrr -= 1
        timer.after(1, start_countdown)

    if timerrr == 0:
        print("\r""time's up!!!")
        showinfo("countdown clock", "Time's Up!!!")
</code>```

This is the function that is supposed to perform the countdown step on the press of the button. The "timer" label doesn't display the updates after every second as I used the .after() but by printing the same, I can see the countdown is working in console/terminal.

答:
You used after() in a wrong way and also you should not use while loop and sleep() as it may block the main thread.

Below is a modified start_countdown():

```<code>def start_countdown(timerrr=None):
    '''
    based on your code, 'hours', 'minutes', 'seconds' and 'timer'
    should be already created in the global namespace
    '''
    if timerrr is None:
        # initialize timerrr when start_countdown() is first called
        timerrr = int(hours)*60*60 + int(minutes)*60 + int(seconds)
    mins, secs = divmod(timerrr, 60)
    hrs, mins = divmod(mins, 60)
    timer['text'] = f'{hrs:02}:{mins:02}:{secs:02}'
    if timerrr > 0:
        timer.after(1000, start_countdown, timerrr-1)
    else:
        showinfo("countdown clock", "Time's up!!")
</code>```

Body:
I'm working on countdown timer with GUI and I'm trying to copy the GUI of Windows 10 coundown timer app. The GUI part is almost done and only the execution part remains:

def start_countdown():
    global hours, minutes, seconds, timer
    user_input = (int(hours)*60*60 + int(minutes)*60 + int(seconds))

    timerrr = int(user_input)

    while timerrr > 0:
        minutes, seconds = divmod(timerrr, 60)
        hours, minutes = divmod(minutes, 60)
        timer.config(text=str(hours).zfill(2) + ":" + str(minutes).zfill(2) + ":" + str(seconds).zfill(2))
        print(str(timer.cget("text")) + "\r", end=str(timer.cget("text")))
        time.sleep(1)
        timerrr -= 1
        timer.after(1, start_countdown)

    if timerrr == 0:
        print("\r""time's up!!!")
        showinfo("countdown clock", "Time's Up!!!")

This is the function that is supposed to perform the countdown step on the press of the button. The "timer" label doesn't display the updates after every second as I used the .after() but by printing the same, I can see the countdown is working in console/terminal.

Body:
You used after() in a wrong way and also you should not use while loop and sleep() as it may block the main thread.

Below is a modified start_countdown():

def start_countdown(timerrr=None):
    '''
    based on your code, 'hours', 'minutes', 'seconds' and 'timer'
    should be already created in the global namespace
    '''
    if timerrr is None:
        # initialize timerrr when start_countdown() is first called
        timerrr = int(hours)*60*60 + int(minutes)*60 + int(seconds)
    mins, secs = divmod(timerrr, 60)
    hrs, mins = divmod(mins, 60)
    timer['text'] = f'{hrs:02}:{mins:02}:{secs:02}'
    if timerrr > 0:
        timer.after(1000, start_countdown, timerrr-1)
    else:
        showinfo("countdown clock", "Time's up!!")


答:
Check this one:

var array = [0,0,0,0,1,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0];
var firstHalf = array.slice(0,array.length/2);
var secondHalf = array.slice(array.length/2);
var result = firstHalf.map(function(e,i){
    return e || secondHalf[i];
});

console.log(result);```

What I'm doing here is spliting the array into two halfs with slice (considering that the array elements are even, of course), and after that I map the first one returning 1 (or true, is the same) if firstArray[i] or secondArray[1] is 1.

Title: JavaScript split array in half juxtapose the first half with second half

Body:
What is the method to evenly split an array into two.  Then, position the second half underneath the first all for the purpose of comparing whether or not a new final array should receive a zero or one in the slots.

var master_array = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38];

var first_half = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19];

var second_half = [20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38];

var final_usable_array_reduced = [];

So, given a form with 38 check boxes, if the 5th, 19th, 37th, and 38th check boxes were checked, the final_usable_array_reduced would be

final_usable_array_reduced = [0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1];

final_usable_array_reduced[4] = **represents the 5th or 24th box being checked**

final_usable_array_reduced[18] = **represents the 19th or 38th boxes being checked**

Body:
Check this one:

var array = [0,0,0,0,1,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0];
var firstHalf = array.slice(0,array.length/2);
var secondHalf = array.slice(array.length/2);
var result = firstHalf.map(function(e,i){
    return e || secondHalf[i];
});

console.log(result);

What I'm doing here is spliting the array into two halfs with slice (considering that the array elements are even, of course), and after that I map the first one returning 1 (or true, is the same) if firstArray[i] or secondArray[1] is 1.


问:
How to set all columns of dataframe as null values
I have a dataframe which has n number of columns with all datatypes
I want to have a empty dataframe with same number of columns/column names
After creating the columns ; is there any way I can set the columns values to null</p>

答:
You can achieve it in following way.  </p>

```<code>from pyspark.sql import SparkSession
from pyspark.sql import functions as F

spark = SparkSession.builder \
.appName('stackoverflow')\
.getOrCreate()

sc= spark.sparkContext

df1 = sc.parallelize([
(1, 2, 3), (3,2, 4), (5,6, 7)
]).toDF(["a", "b", "c"])

df1.show()

+---+---+---+
|  a|  b|  c|
+---+---+---+
|  1|  2|  3|
|  3|  2|  4|
|  5|  6|  7|
+---+---+---+

df2 = df1.select( *[F.lit(None).alias(col)  for col in df1.columns])

df2.show()

+----+----+----+
|   a|   b|   c|
+----+----+----+
|null|null|null|
|null|null|null|
|null|null|null|
+----+----+----+
</code>```

Body:
You can achieve it in following way.

from pyspark.sql import SparkSession
from pyspark.sql import functions as F

spark = SparkSession.builder \
.appName('stackoverflow')\
.getOrCreate()

sc= spark.sparkContext

df1 = sc.parallelize([
(1, 2, 3), (3,2, 4), (5,6, 7)
]).toDF(["a", "b", "c"])

df1.show()

+---+---+---+
|  a|  b|  c|
+---+---+---+
|  1|  2|  3|
|  3|  2|  4|
|  5|  6|  7|
+---+---+---+

df2 = df1.select( *[F.lit(None).alias(col)  for col in df1.columns])

df2.show()

+----+----+----+
|   a|   b|   c|
+----+----+----+
|null|null|null|
|null|null|null|
|null|null|null|
+----+----+----+


问:
Performance counter monitoring in applications and for SQL Server
We are looking for a performance counter monitoring tool, like Perfmon. But this tool should in addition save the data automatically in a database and should have nice reporting abilities. If possible it should be even Web based and for free.

We want to use it for benchmarking our distributed .NET application and some connected SQL servers. So maybe we need next to performance counters also to execute SQL statements to get some numbers back.

At the moment we are not sure if we should use an agent based or an agent-less benchmarking / monitoring solution.

We are also seriously thinking about developing our own solution, but I think something like this must already exist.

Thanks for your help!
Best regards
Daniel

答:
For SQL Server I would suggest looking at DMVs to Identify Missing Indexes, CPU issues, IO Issues.

DMVs and values to check are listed in article - http://technet.microsoft.com/en-us/library/cc966401.aspx

Ready to Use Queries for DMVs you can download from link  - http://blogs.msdn.com/b/jimmymay/archive/2008/10/30/drum-roll-please-the-debut-of-the-sql-dmv-all-stars-dream-team.aspx


问:
Create a view which joins on a comma separated value
I request help for my homework in SQL.

I have a table with musical instruments:

```<code>id  instrument_name         instrument_at_shops
-----------------------------------------------
1   Electric Guitar         1;2;3;4;
2   Midi Keyboard           1;3;
3   Tom Drum                2;
4   Electric Guitar         1;
5   Electric Guitar         0;
</code>```

And a table with shops:

```<code>shop_id  shop_name  shop_address
-----------------------------------------------
1        Shop1      City1 Street 1, building 1
2        Shop2      City1 Street 5, building 4
3        Shop3      City2 Street 4, building 4
4        Shop4      City3 Street 10, building 7
</code>```

In my musical instruments table I have several numbers which represent id's of the shops that have the particular instrument.

The problem is: how to create a view which contains a shop name and an instrument which is in this shop?

The logic is this:

```<code>SELECT shop_name, instrument_name
FROM Shop
CROSS JOIN Instrument
WHERE instrumet_at_shops CONTAINS shop_id
</code>```

But I cannot create an appropriate query or view design.

Thank you in advance!

答:
Ideally, if possible, you should normalise your data.

What is Normalisation (or Normalization)?

The most basic way you can do this, in your case, is to make the data in the [instrument_at_shops] column atomic, so it'll look something like this...

```<code>id  |  instrument_name  |  instrument_at_shops
-----------------------------------------------
1   |  Electric Guitar  |  1
1   |  Electric Guitar  |  2
1   |  Electric Guitar  |  3
1   |  Electric Guitar  |  4
2   |  Midi Keyboard    |  1
2   |  Midi Keyboard    |  3
...
</code>```

There are other normal forms you can apply, which will help if you are dealing with a lot of data. But if this is the extent of your dataset, making these values atomic should be sufficient.

Once you've done this, you should be able to create a view with a lot more ease.

E.g.

SELECT      s.shop_name, i.instrument_name
FROM        Shop AS s
RIGHT JOIN  Instrument AS i
    ON      s.shop_id = i.instrument_at_shops ;
GO
```

Body:
I request help for my homework in SQL.

I have a table with musical instruments:

id  instrument_name         instrument_at_shops
-----------------------------------------------
1   Electric Guitar         1;2;3;4;
2   Midi Keyboard           1;3;
3   Tom Drum                2;
4   Electric Guitar         1;
5   Electric Guitar         0;

And a table with shops:

shop_id  shop_name  shop_address
-----------------------------------------------
1        Shop1      City1 Street 1, building 1
2        Shop2      City1 Street 5, building 4
3        Shop3      City2 Street 4, building 4
4        Shop4      City3 Street 10, building 7

In my musical instruments table I have several numbers which represent id's of the shops that have the particular instrument.

The problem is: how to create a view which contains a shop name and an instrument which is in this shop?

The logic is this:

SELECT shop_name, instrument_name
FROM Shop
CROSS JOIN Instrument
WHERE instrumet_at_shops CONTAINS shop_id

But I cannot create an appropriate query or view design.

Thank you in advance!

Body:
Ideally, if possible, you should normalise your data.

What is Normalisation (or Normalization)?

The most basic way you can do this, in your case, is to make the data in the [instrument_at_shops] column atomic, so it'll look something like this...

id  |  instrument_name  |  instrument_at_shops
-----------------------------------------------
1   |  Electric Guitar  |  1
1   |  Electric Guitar  |  2
1   |  Electric Guitar  |  3
1   |  Electric Guitar  |  4
2   |  Midi Keyboard    |  1
2   |  Midi Keyboard    |  3
...

There are other normal forms you can apply, which will help if you are dealing with a lot of data. But if this is the extent of your dataset, making these values atomic should be sufficient.

Once you've done this, you should be able to create a view with a lot more ease.

E.g.

SELECT      s.shop_name, i.instrument_name
FROM        Shop AS s
RIGHT JOIN  Instrument AS i
    ON      s.shop_id = i.instrument_at_shops ;
GO


Title: 1d array from columns of an ndarray

Body:
This is the array I have at hand:

[array([[[ 4, 9,  1, -3],
         [-2, 0, 8, 6],
         [ 1, 3, 7,  9 ],
         [ 2,  5, 0, -7],
         [-1, -6, -5, -8]]]),
 array([[[ 0,  2, -1, 6 ],
         [9,  8,  0,  3],
         [ -1, 2, 5, -4],
         [0,  5, 9, 6],
         [ 6, 2,  9, 4]]]),
 array([[[ 1,  2,  0, 9],
         [3,  4, 8, -1],
         [5,  6,  9,  0],
         [ 7, 8, -3, -],
         [9, 0,  8, -2]]])]

But the goal is obtain arrays A from first columns of nested arrays, B from second columns of nested arrays, Cfrom third columns of nested array etc.

Such that:

A = array([4, -2, 1, 2, -1, 0, 9, -1 ,0, 6, 1, 3, 5, 7, 9])
B = array([9, 0, 3, 5, -6, 2, 8, 2, 5, 2, 2,, 4, 6, 8, 0])

How should I do this?

Body:
IIUC,

l = [np.array([[[ 4, 9,  1, -3],
         [-2, 0, 8, 6],
         [ 1, 3, 7,  9 ],
         [ 2,  5, 0, -7],
         [-1, -6, -5, -8]]]),
 np.array([[[ 0,  2, -1, 6 ],
         [9,  8,  0,  3],
         [ -1, 2, 5, -4],
         [0,  5, 9, 6],
         [ 6, 2,  9, 4]]]),
 np.array([[[ 1,  2,  0, 9],
         [3,  4, 8, -1],
         [5,  6,  9,  0],
         [ 7, 8, -3, -9],
         [9, 0,  8, -2]]])]

a = np.hstack([i[0][:, 0] for i in l])
b = np.hstack([i[0][:, 1] for i in l])

Output:

array([ 4, -2,  1,  2, -1,  0,  9, -1,  0,  6,  1,  3,  5,  7,  9])
array([ 9,  0,  3,  5, -6,  2,  8,  2,  5,  2,  2,  4,  6,  8,  0])


问:
Java for( x : y) execution
I have the following for loop:

```<code>for(String s : someString.split("\\s+")){
   //do something
}
</code>```

Does java execute the split() method each time the loop iterates, or does it do it only once and keep a temp array to iterate on?

答:
The split method is only called once. Think of the structure (also known as a for-each) as follows:

The second argument is evaluated and kept for the duration of the loop.

If the argument gives an Iterable or is an array (special case), a check is then made to see if the type of the first argument corresponds with the elements that are returned.

The process enters the loop and executes the code inside the scope and exits when there are no more elements left.

More information can be had here:
http://www.leepoint.net/notes-java/flow/loops/foreach.html

P.S: This works with Java 5 minimum.

Title: Java for( x : y) execution

Body:
I have the following for loop:

for(String s : someString.split("\\s+")){
   //do something
}

Does java execute the split() method each time the loop iterates, or does it do it only once and keep a temp array to iterate on?


问:
Image to take the height and with of parent element
so today i did good with advancing in learning to make an app with flutter , i made a ListView , but the image didnt take the full height and with of the parent element , i tried some solutions but it didnt workout

this is the class

```<code>class FlowersItem extends StatelessWidget {

  final String imgAssetPath;

  FlowersItem({this.imgAssetPath});

  @override
  Widget build(BuildContext context) {
    return Container(
     width: 200,
      alignment: Alignment.center,
      padding: EdgeInsets.symmetric(horizontal: 30),
      margin: EdgeInsets.only(right: 16),
      decoration: BoxDecoration(
        color: Color(0xff29404E),
        borderRadius: BorderRadius.circular(12)
      ),
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: <Widget>[
        Column(children: <Widget>[
            ClipRect(
                child: FittedBox(
  child:    Image.asset(imgAssetPath),
  fit: BoxFit.fill,

),
       )
        ],)

        ],
      ),
    );
  }
}

List<FlowersItem> flowers = [
 FlowersItem(
  imgAssetPath: 'assets/images/flower1.jpeg',

  ),
FlowersItem(
   imgAssetPath: 'assets/images/flower-pot.png',

  ),
FlowersItem(
     imgAssetPath: 'assets/images/flower-pot.png',
  ),
  FlowersItem(
      imgAssetPath: 'assets/images/flower-pot.png',
  ),
FlowersItem(
     imgAssetPath: 'assets/images/flower-pot.png',

  ),
];
</code>```

答:
have you tried Expanded class?

So, Expanded class is A widget that expands a child of a Row, Column, or Flex so that the child fills the available space.

you could find the documentation here.

Body:
so today i did good with advancing in learning to make an app with flutter , i made a ListView , but the image didnt take the full height and with of the parent element , i tried some solutions but it didnt workout

this is the class

class FlowersItem extends StatelessWidget {

  final String imgAssetPath;

  FlowersItem({this.imgAssetPath});

  @override
  Widget build(BuildContext context) {
    return Container(
     width: 200,
      alignment: Alignment.center,
      padding: EdgeInsets.symmetric(horizontal: 30),
      margin: EdgeInsets.only(right: 16),
      decoration: BoxDecoration(
        color: Color(0xff29404E),
        borderRadius: BorderRadius.circular(12)
      ),
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: <Widget>[
        Column(children: <Widget>[
            ClipRect(
                child: FittedBox(
  child:    Image.asset(imgAssetPath),
  fit: BoxFit.fill,

),
       )
        ],)

        ],
      ),
    );
  }
}

List<FlowersItem> flowers = [
 FlowersItem(
  imgAssetPath: 'assets/images/flower1.jpeg',

  ),
FlowersItem(
   imgAssetPath: 'assets/images/flower-pot.png',

  ),
FlowersItem(
     imgAssetPath: 'assets/images/flower-pot.png',
  ),
  FlowersItem(
      imgAssetPath: 'assets/images/flower-pot.png',
  ),
FlowersItem(
     imgAssetPath: 'assets/images/flower-pot.png',

  ),
];


问:
I am new to python with no previous coding experience. My program is supposed to display the price of a ticket depending on age. Why does it not work?
My code will display ticket price dependent on age. Why is it not working? This is exercise 7-5 from the Python Crash Course book.</p>

```<code>
prompt = "\nEnter Age: "
prompt += "\nEnter 'quit' when done."
age = ''

while age != 'quit':

    age = input(prompt)
    print(age)
    if age != 'quit':
        if age > '13':
            print(f'You ticket price is $15.00.')
            print(f'Retrieve your ticket(s) below')

        if age <= '13' and age > '2':
            print(f'Your ticket price is $10.00.')
            print(f'Retrieve your ticket(s) below')

        if age < '3':
            print(f'Your ticket price is free')
            print(f'Retrieve your ticket below')

print(f'Thank You Enjoy the show')
</code>```

答:
In the if statements change your numbers from if age < '13': to if age < 13:
(Change on all if statements) Otherwise 13 is read as a string and cannot be used as an int.

Body:
My code will display ticket price dependent on age. Why is it not working? This is exercise 7-5 from the Python Crash Course book.

prompt = "\nEnter Age: "
prompt += "\nEnter 'quit' when done."
age = ''

while age != 'quit':

    age = input(prompt)
    print(age)
    if age != 'quit':
        if age > '13':
            print(f'You ticket price is $15.00.')
            print(f'Retrieve your ticket(s) below')

        if age <= '13' and age > '2':
            print(f'Your ticket price is $10.00.')
            print(f'Retrieve your ticket(s) below')

        if age < '3':
            print(f'Your ticket price is free')
            print(f'Retrieve your ticket below')

print(f'Thank You Enjoy the show')


问:
Pretty-Printing JSON with PHP
I'm building a PHP script that feeds JSON data to another script. My script builds data into a large associative array, and then outputs the data using json_encode. Here is an example script:

```<code>$data = array('a' => 'apple', 'b' => 'banana', 'c' => 'catnip');
header('Content-type: text/javascript');
echo json_encode($data);
</code>```

The above code yields the following output:

```<code>{"a":"apple","b":"banana","c":"catnip"}
</code>```

This is great if you have a small amount of data, but I'd prefer something along these lines:

```<code>{
    "a": "apple",
    "b": "banana",
    "c": "catnip"
}
</code>```

Is there a way to do this in PHP without an ugly hack? It seems like someone at Facebook figured it out.

答:
For those running PHP version 5.3 or before, you may try below:</p>

```<code>$pretty_json = "```".print_r(json_decode($json), true)."```";

echo $pretty_json;

</code>```

Title: Pretty-Printing JSON with PHP

Body:
I'm building a PHP script that feeds JSON data to another script. My script builds data into a large associative array, and then outputs the data using json_encode. Here is an example script:

$data = array('a' => 'apple', 'b' => 'banana', 'c' => 'catnip');
header('Content-type: text/javascript');
echo json_encode($data);

The above code yields the following output:

{"a":"apple","b":"banana","c":"catnip"}

This is great if you have a small amount of data, but I'd prefer something along these lines:

{
    "a": "apple",
    "b": "banana",
    "c": "catnip"
}

Is there a way to do this in PHP without an ugly hack? It seems like someone at Facebook figured it out.

Body:
For those running PHP version 5.3 or before, you may try below:

$pretty_json = "<pre>".print_r(json_decode($json), true)."</pre>";

echo $pretty_json;


问:
node mysql2 can't access update results
I'm doing a simple UPDATE with mysql2 :

```<code>   UPDATE table1
    SET table1.value1 = ?, table1.value2 = ?
    WHERE user_id = (
      SELECT user_id
      FROM user
      WHERE company_id = ?
    )
</code>```

table1 is related to the user table by user_id, but I only have the company_id so I do a subquery (probably should be a join, but thats another discussion):

```<code>const [results, buff] = await connection.execute(query, values);
return results
</code>```

However, when accessing the results to make sure there are no errors and that only a single row is updated, results returns:

```<code>  console.log
    ResultSetHeader {
      fieldCount: 0,
      affectedRows: 1,
      insertId: 0,
      info: 'Rows matched: 1  Changed: 0  Warnings: 0',
      serverStatus: 2,
      warningStatus: 0,
      changedRows: 0
    }
</code>```

But I can't access the values. If I try results.affectedRows I get

```<code>Property 'affectedRows' does not exist on type 'RowDataPacket[] | RowDataPacket[][] | OkPacket | OkPacket[]'.
</code>```

The only way to make it work is to do results['affectedRows']. Any suggestions?

答:
So I forgot to mention that this is a typescript error, and I was able to fix it by doing:

```<code>const [results, buff] = await connection.execute(query, values);
const json: any = results;
return json.affectedRows //or whatever property I want
</code>```

This also works:

```<code>const [results, buff] = await connection.execute(query, values);
return json as any; //then in the calling fuction access the properties I want
</code>```

Title: node mysql2 can't access update results

Body:
I'm doing a simple UPDATE with mysql2 :

   UPDATE table1
    SET table1.value1 = ?, table1.value2 = ?
    WHERE user_id = (
      SELECT user_id
      FROM user
      WHERE company_id = ?
    )

table1 is related to the user table by user_id, but I only have the company_id so I do a subquery (probably should be a join, but thats another discussion):

const [results, buff] = await connection.execute(query, values);
return results

However, when accessing the results to make sure there are no errors and that only a single row is updated, results returns:

  console.log
    ResultSetHeader {
      fieldCount: 0,
      affectedRows: 1,
      insertId: 0,
      info: 'Rows matched: 1  Changed: 0  Warnings: 0',
      serverStatus: 2,
      warningStatus: 0,
      changedRows: 0
    }

But I can't access the values. If I try results.affectedRows I get

Property 'affectedRows' does not exist on type 'RowDataPacket[] | RowDataPacket[][] | OkPacket | OkPacket[]'.

The only way to make it work is to do results['affectedRows']. Any suggestions?

Body:
So I forgot to mention that this is a typescript error, and I was able to fix it by doing:

const [results, buff] = await connection.execute(query, values);
const json: any = results;
return json.affectedRows //or whatever property I want

This also works:

const [results, buff] = await connection.execute(query, values);
return json as any; //then in the calling fuction access the properties I want


问:
How to write a python program to find the second most repeated word in a given string
I have the string as Welcome to Datacurators.tech and i need to find out second most repeated character in the given string. I need to use only basic python code ( not to use import or def functions). i have the below code but it gives me count of all the characters. Expected output ( e,c,o,a) output could be in any order.

```<code>stri = "Welcome to Datacurators.tech"
counts={}
for i in stri:
    counts[i]=stri.count(i)
print (counts)
</code>```

答:
You should use a dictionary. It loops through the string. If it's not in the dict, it creates a key-> value pair. If it's already in the dict, it pluses 1 to its frequency.

map = {}
for eachCharacter in stri:
    if eachCharacter not in map:
        map[eachCharacter] = 1
    else:
        map[eachCharacter] += 1
```

<p>This gives you frequency of all characters in the string (including space character, get rid of it if you do not need it). Now we sort this dictionary by its value.</p>

<pre class="lang-py prettyprint-override"><code>newMap = {k: v for k, v in sorted(map.items(), key = lambda item: item[1])}
</code>```

Then to get the second most frequent, or even the n-th most frequent, use:

list(newMap.keys())[n]
```

And you get the answer.
Hope it helps!

Body:
I have the string as Welcome to Datacurators.tech and i need to find out second most repeated character in the given string. I need to use only basic python code ( not to use import or def functions). i have the below code but it gives me count of all the characters. Expected output ( e,c,o,a) output could be in any order.

stri = "Welcome to Datacurators.tech"
counts={}
for i in stri:
    counts[i]=stri.count(i)
print (counts)

Body:
You should use a dictionary. It loops through the string. If it's not in the dict, it creates a key-> value pair. If it's already in the dict, it pluses 1 to its frequency.

map = {}
for eachCharacter in stri:
    if eachCharacter not in map:
        map[eachCharacter] = 1
    else:
        map[eachCharacter] += 1

This gives you frequency of all characters in the string (including space character, get rid of it if you do not need it). Now we sort this dictionary by its value.

newMap = {k: v for k, v in sorted(map.items(), key = lambda item: item[1])}

Then to get the second most frequent, or even the n-th most frequent, use:

list(newMap.keys())[n]

And you get the answer.
Hope it helps!


问:
Extract nested microdata using xpath
I am trying to extract the recipe name from schema.org microdata using xpath

This is the xpath I came up with:

```<code>//*[@itemtype="http://schema.org/Recipe"]//*[@itemprop="name" and not(ancestor::*[@itemtype!="http://schema.org/Recipe"])]
</code>```

Select the node with itemprop="name" inside the node with itemtype="http://schema.org/Recipe", but ignore nodes with a non-recipe itemtype parent (within the scope of the itemtype="http://schema.org/Recipe" node).

Test cases:

Fails:

```<code><div itemtype="https://schema.org/Thing">
  <div itemtype="http://schema.org/Recipe">
    <div>
      <div itemtype="http://schema.org/BreadcrumbList">
          <div itemprop="name">test1</div>
          <div itemprop="name">test2</div>
      </div>
      <div itemprop="name">Recipe Name</div>
    </div>
  </div>
</div>
</code>```

Fails:

```<code><div itemtype="http://schema.org/Recipe">
  <div>
    <div itemtype="http://schema.org/BreadcrumbList">
      <div>
        <div itemprop="name">test1</div>
        <div>
            <div itemprop="name">test2</div>
        </div>
      </div>
    </div>
    <div>
      <div itemprop="name">Recipe Name</div>
    </div>
  </div>
</div>
</code>```

Passes:

```<code><div itemtype="http://schema.org/Recipe">
  <div>
    <div itemtype="http://schema.org/BreadcrumbList">
        <div itemprop="name">test1</div>
        <div itemprop="name">test2</div>
    </div>
    <div itemprop="name">Recipe Name</div>
  </div>
</div>
</code>```

Passes:

```<code><div itemtype="http://schema.org/Recipe">
  <div itemprop="name">Recipe Name</div>
</div>
</code>```

It appears that ancestor::*[@itemtype!="http://schema.org/Recipe"] is searching all ancestors instead of just ancestors within the Recipe node.

How can I extract the recipe name from Recipe microdata https://schema.org/Recipe when there are potentially nested itemtypes?

答:
Another option could be (since the Recipe name seems always in the last node) :

```<code>(//*[@itemtype="http://schema.org/Recipe"]//*[@itemprop="name"])[last()]
</code>```

It passes the 4 sample tests.

Title: Extract nested microdata using xpath

Body:
I am trying to extract the recipe name from schema.org microdata using xpath

This is the xpath I came up with:

//*[@itemtype="http://schema.org/Recipe"]//*[@itemprop="name" and not(ancestor::*[@itemtype!="http://schema.org/Recipe"])]

Select the node with itemprop="name" inside the node with itemtype="http://schema.org/Recipe", but ignore nodes with a non-recipe itemtype parent (within the scope of the itemtype="http://schema.org/Recipe" node).

Test cases:

Fails:

test1

test2

Recipe Name

Fails:

test1

test2

Recipe Name

Passes:

test1

test2

Recipe Name

Passes:

Recipe Name

It appears that ancestor::*[@itemtype!="http://schema.org/Recipe"] is searching all ancestors instead of just ancestors within the Recipe node.

How can I extract the recipe name from Recipe microdata https://schema.org/Recipe when there are potentially nested itemtypes?

Body:
Another option could be (since the Recipe name seems always in the last node) :

(//*[@itemtype="http://schema.org/Recipe"]//*[@itemprop="name"])[last()]

It passes the 4 sample tests.


问:
how to save information, using laravel in a relationship ManytoMany
I am using Laravel and I want to save the information in a table of many to many. Here is the view of the page, and how the table is made.

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

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

答:
For performing actions on many to many relationships, Laravel provides various helper methods such as attach, detach, sync and more.

For example- if you want to add new course (with score of 50) to a user, you can do something like this:

```<code>$user->courses()->attach($courseId, ['score' => 50])
</code>```

More information: https://laravel.com/docs/7.x/eloquent-relationships#updating-many-to-many-relationships

Body:
For performing actions on many to many relationships, Laravel provides various helper methods such as attach, detach, sync and more.

For example- if you want to add new course (with score of 50) to a user, you can do something like this:

$user->courses()->attach($courseId, ['score' => 50])

More information: https://laravel.com/docs/7.x/eloquent-relationships#updating-many-to-many-relationships


答: I think I have an answer. First, why do you use print(f'')? You can just use print(''). Also, there is no need to type prompt='\nEnter'; you can just type prompt='Enter'!</p>

Title: I am new to python with no previous coding experience. My program is supposed to display the price of a ticket depending on age. Why does it not work?


问:
Re rendering issue in React Native
My editing information screen has to modify lots of information, and I use functions to return the UI like this.
The point is when the input has changed (email input, phone input,...), the whole screen will be re rendered. (like the function to render the uploading avatar below ).
Any advices? I just want my app to re render the component that was modified.
Thank you anyway.

```<code>_renderUploadAvatar = () => {
   const { shadowContainer, avatarImage, editPictureIconStyle } = styles;
   const { avatarUri } = this.state;
   const touchableProps = {
      style: { alignSelf: 'center' }, disabled: !!avatarUri, onPress: () => this.onClick('upload_avatar')
   }
   const avatarProps = { source: avatarUri || Images.defaultUserAvatar, style: avatarImage }
   const iconProps = {
      name: 'editPicture', fill: Colors.white, width: sizeHeight * 5, height: sizeHeight * 5,
      viewStyle: editPictureIconStyle, onClick: () => this.onClick('upload_avatar'),
   }
   console.log("EditCustomerScreen -> _renderUploadAvatar -> return")
   return (
      <ShadowView style={[shadowContainer, { marginHorizontal: marginSize }]}>
         <TouchableOpacity {...touchableProps}>
            <ImageView {...avatarProps} />
            <SvgIcon {...iconProps} />
         </TouchableOpacity>
         <Text style={[Fonts.style('primary', toRgbA(Colors.primary, 0.5), 'base'), { textAlign: 'center', marginTop: marginSize }]}>{i18nText('information.avatar')}</Text>
      </ShadowView>
   )
}

return (
   <Fragment>
      <Layout {...layoutProps}>
         {this._renderUploadAvatar()}
         {this._renderUpdatePhoneNumbers()}
         {this._renderUpdateEmail()}
         {this._renderUpdateIdentification()}
         {this._renderLanguages()}
         {this._renderEducation()}
         {this._renderCustomerStatus()}
         {this._renderPayOff()}
      </Layout >
      {this._renderApplyButton()}
   </Fragment >
);
</code>```

答:
You should create a component for each one of your controls and views. Those components should extend from PureComponent or, in case you extend from Component, you have to implement shouldComponentUpdate.

Here you can read more about the PureComponents.
PureComponents

Title: Re rendering issue in React Native

Body:
My editing information screen has to modify lots of information, and I use functions to return the UI like this.
The point is when the input has changed (email input, phone input,...), the whole screen will be re rendered. (like the function to render the uploading avatar below ).
Any advices? I just want my app to re render the component that was modified.
Thank you anyway.

_renderUploadAvatar = () => {
   const { shadowContainer, avatarImage, editPictureIconStyle } = styles;
   const { avatarUri } = this.state;
   const touchableProps = {
      style: { alignSelf: 'center' }, disabled: !!avatarUri, onPress: () => this.onClick('upload_avatar')
   }
   const avatarProps = { source: avatarUri || Images.defaultUserAvatar, style: avatarImage }
   const iconProps = {
      name: 'editPicture', fill: Colors.white, width: sizeHeight * 5, height: sizeHeight * 5,
      viewStyle: editPictureIconStyle, onClick: () => this.onClick('upload_avatar'),
   }
   console.log("EditCustomerScreen -> _renderUploadAvatar -> return")
   return (
      <ShadowView style={[shadowContainer, { marginHorizontal: marginSize }]}>
         <TouchableOpacity {...touchableProps}>
            <ImageView {...avatarProps} />
            <SvgIcon {...iconProps} />
         </TouchableOpacity>
         <Text style={[Fonts.style('primary', toRgbA(Colors.primary, 0.5), 'base'), { textAlign: 'center', marginTop: marginSize }]}>{i18nText('information.avatar')}</Text>
      </ShadowView>
   )
}

return (
   <Fragment>
      <Layout {...layoutProps}>
         {this._renderUploadAvatar()}
         {this._renderUpdatePhoneNumbers()}
         {this._renderUpdateEmail()}
         {this._renderUpdateIdentification()}
         {this._renderLanguages()}
         {this._renderEducation()}
         {this._renderCustomerStatus()}
         {this._renderPayOff()}
      </Layout >
      {this._renderApplyButton()}
   </Fragment >
);


问:
How to fetch data from database before rendering in a function componment in React?
Below is my code:

```<code>function Profile() {
    const {userInfo} = useSelector(state => state.user);
    let user = {};

    useEffect(() => {
        const populateUserInfo = async () => {
            const {data} = await axios.get("api/users/" + userInfo._id);
            user = data

            // this line works if I comment out {user.shipping.address} in the "return" section.
            console.log(user.shipping.address)
        }
        populateUserInfo();
    }, [])

    return <div>{user.shipping.address}</div>
}
</code>```

I want to fetch data from DB and store it into user variable before rendering, but when the page renders, TypeError: Cannot read property 'address' of undefined occurred.

I guess the user variable is still empty when the page renders?
Could anyone teach me how to do it?

答:
You can also fetch it with a react standard async method with an example on this page componentDidMount.

The class method componentDidMount is only supposed to run at the beginning of the lifecycle.

class App extends React.Component {
 constructor(props) {
  super(props);

  this.state = {
   userData: null
        };
    }

    componentDidMount() {
    fetch(`https://jsonplaceholder.typicode.com/posts/42`)
      .then(res => res.json())
      .then(json => this.setState({ userData: json }));
    }

 render() {
  return (

               {this.state.userData ? "user title: " + this.state.userData.title : "Waiting for user ..."}

  );
 }
}

ReactDOM.render(
  <App />,
  document.getElementById('container')
);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>

<div id='container'></div></code>```

Body:
Below is my code:

function Profile() {
    const {userInfo} = useSelector(state => state.user);
    let user = {};

    useEffect(() => {
        const populateUserInfo = async () => {
            const {data} = await axios.get("api/users/" + userInfo._id);
            user = data

            // this line works if I comment out {user.shipping.address} in the "return" section.
            console.log(user.shipping.address)
        }
        populateUserInfo();
    }, [])

    return
{user.shipping.address}

}

I want to fetch data from DB and store it into user variable before rendering, but when the page renders, TypeError: Cannot read property 'address' of undefined occurred.

I guess the user variable is still empty when the page renders?
Could anyone teach me how to do it?

Body:
You can also fetch it with a react standard async method with an example on this page componentDidMount.

The class method componentDidMount is only supposed to run at the beginning of the lifecycle.

class App extends React.Component {
 constructor(props) {
  super(props);

  this.state = {
   userData: null
        };
    }

    componentDidMount() {
    fetch(`https://jsonplaceholder.typicode.com/posts/42`)
      .then(res => res.json())
      .then(json => this.setState({ userData: json }));
    }

 render() {
  return (
            <div>
               {this.state.userData ? "user title: " + this.state.userData.title : "Waiting for user ..."}
            </div>
  );
 }
}

ReactDOM.render(
  <App />,
  document.getElementById('container')
);

<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>

<div id='container'></div>