问:
How to save a SQLite binding into an NSString
I have the following bind statement for binding an SQLite column. I want to save this value into an NSString named journeyName. For this I have written the following statement:

```<code>NSString * journeyName = sqlite3_bind_text( compiledStatement, 1,
                                           [Gjourney UTF8String], -1,
                                           SQLITE_TRANSIENT );
</code>```

This gives me a warning that

initialization makes pointer from integer without a cast

and my app crashes.

答:
Try this.

```<code>    // Read the data from the result row
    NSString * journeyName = [NSString stringWithUTF8String:(char *)sqlite3_column_text(compiledStatement, 1)];
    NSLog(@"journeyName - %@",journeyName);
</code>```

For Reference - sample code

Body:
I have the following bind statement for binding an SQLite column. I want to save this value into an NSString named journeyName. For this I have written the following statement:

NSString * journeyName = sqlite3_bind_text( compiledStatement, 1,
                                           [Gjourney UTF8String], -1,
                                           SQLITE_TRANSIENT );

This gives me a warning that

initialization makes pointer from integer without a cast

and my app crashes.

Body:
Try this.

    // Read the data from the result row
    NSString * journeyName = [NSString stringWithUTF8String:(char *)sqlite3_column_text(compiledStatement, 1)];
    NSLog(@"journeyName - %@",journeyName);

For Reference - sample code


来源: stackexchange

问:
Building a Shiny app with an HTML template
I'm trying to build a Shiny app using an HTML template, as specified in the docs. I'm using Bulma as the CSS framework, and because the app has many graphics I've decided to use tabs to separate them.

The output (some renderText in this example) is showing correctly in the first tab, but in the second tab the output isn't showing, only the selectInput and I can't see any error messages in the console. Below a reproducible example of what I'm trying to accomplish and some images to illustrate.

I suspect that I may be missing an additional code (JavaScript maybe?) to tell shiny to display the output in the second tab, but if so, why is the selectInput shown and not the textOuptut? Can someone help me? Thanks in advance.

template.html

```<code><!DOCTYPE html>
<html>

<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>Shiny app</title>
  {{ headContent() }}
  <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bulma@0.8.0/css/bulma.min.css">
  <script src="index.js"></script>
</head>

<body>
  <section class="hero is-danger is-bold is-small">
    <div class="hero-body">
      <div class="container has-text-centered">
        <h1 class="title">
          Example Shiny app
        </h1>
      </div>
    </div>

    <div class="hero-foot">
      <nav class="tabs is-boxed is-centered">
        <div class="container">
          <ul>
            <li class="tab is-active" onclick="openTab(event,'Tab1')"><a>Tab 1</a></li>
            <li class="tab" onclick="openTab(event,'Tab2')"><a>Tab 2</a></li>
            <li class="tab" onclick="openTab(event,'Tab3')"><a>Tab 3</a></li>
          </ul>
        </div>
      </nav>
    </div>
  </section>

  <section class="section main">
    <div class="container">
      <div id="Tab1" class="content-tab">
        <p>
          tab1<br>
          Lorem Ipsum passages, and more recently with desktop publishing software like Aldus
          PageMaker including versions of Lorem Ipsum.</p>
        <div>
          {{ select }}
        </div>
        <div>
          {{ text }}
        </div>
      </div>
      <div id="Tab2" class="content-tab" style="display:none">
        <p>
          tab2<br>
          Details Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the
          industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and
          scrambled it to make a type specimen book.</p>
        <div>
          {{ select2 }}
        </div>
        <div>
          {{ text2 }}
        </div>
      </div>
      <div id="Tab3" class="content-tab" style="display:none">
        <p>
          tab3 <br>
          It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages,
          and more recently with desktop publishing software like Aldus
          PageMaker including versions of Lorem Ipsum.</p>
      </div>
    </div>
  </section>
</body>

</html>
</code>```

server.R

```<code>library(shiny)

function(input, output) {

  output$selected_var <- renderText({
    paste("You have selected", input$var)
  })

  output$selected_var2 <- renderText({
    paste("You have selected", input$var2)
  })

}
</code>```

ui.R

```<code>htmlTemplate("template.html",
             select = selectInput("var",
                                  label = "Choose a variable to display",
                                  choices = c("Percent White",
                                              "Percent Black",
                                              "Percent Hispanic",
                                              "Percent Asian"),
                                  selected = "Percent White"),

             text = textOutput("selected_var"),

             select2 = selectInput("var2",
                                   label = "Choose a variable to display",
                                   choices = c("Choice one",
                                               "Choice two",
                                               "Choice three",
                                               "Choice four"),
                                   selected = "Percent White"),

             text2 = textOutput("selected_var2")
)
</code>```

index.js (javascript to open the tabs)

```<code>function openTab(evt, tabName) {
    var i, x, tablinks;
    x = document.getElementsByClassName("content-tab");
    for (i = 0; i < x.length; i++) {
        x[i].style.display = "none";
    }
    tablinks = document.getElementsByClassName("tab");
    for (i = 0; i < x.length; i++) {
        tablinks[i].className = tablinks[i].className.replace(" is-active", "");
    }
    document.getElementById(tabName).style.display = "block";
    evt.currentTarget.className += " is-active";
  }
</code>```

答:
In short, you need to call Shiny.unbindAll() before removing Shiny inputs/outputs from the page, and Shiny.bindAll() after adding Shiny inputs/outputs to the page.

Usually Shiny adds and removes inputs/outputs to the page itself, and ensures that those inputs/outputs are properly initialized and hooked up to Shiny (also known as "binding"). When you add or remove inputs/outputs outside of Shiny, you have to let Shiny know using Shiny.unbindAll() and Shiny.bindAll().

For example, in the openTab function in index.js:

```<code>function openTab(evt, tabName) {
    var i, x, tablinks;

    Shiny.unbindAll();

    x = document.getElementsByClassName("content-tab");
    for (i = 0; i < x.length; i++) {
        x[i].style.display = "none";
    }
    tablinks = document.getElementsByClassName("tab");
    for (i = 0; i < x.length; i++) {
        tablinks[i].className = tablinks[i].className.replace(" is-active", "");
    }
    document.getElementById(tabName).style.display = "block";
    evt.currentTarget.className += " is-active";

    Shiny.bindAll();
}
</code>```

bindAll() and unbindAll() search the entire page by default, but you can also call them on a specific element such as the tab content:

```<code>function openTab(evt, tabName) {
    var i, x, tablinks, activetab;

    x = document.getElementsByClassName("content-tab");
    for (i = 0; i < x.length; i++) {
        Shiny.unbindAll(x[i]);
        x[i].style.display = "none";
    }
    tablinks = document.getElementsByClassName("tab");
    for (i = 0; i < x.length; i++) {
        tablinks[i].className = tablinks[i].className.replace(" is-active", "");
    }
    activetab = document.getElementById(tabName)
    activetab.style.display = "block";
    evt.currentTarget.className += " is-active";
    Shiny.bindAll(activetab);
}
</code>```

For more info, see https://shiny.rstudio.com/articles/dynamic-ui.html#use-javascript-to-modify-the-page and https://community.rstudio.com/t/what-is-the-purpose-of-using-shiny-bindall/14489/2

ContentLicense: CC BY-SA 4.0

Body:
I'm trying to build a Shiny app using an HTML template, as specified in the docs. I'm using Bulma as the CSS framework, and because the app has many graphics I've decided to use tabs to separate them.

The output (some renderText in this example) is showing correctly in the first tab, but in the second tab the output isn't showing, only the selectInput and I can't see any error messages in the console. Below a reproducible example of what I'm trying to accomplish and some images to illustrate.

I suspect that I may be missing an additional code (JavaScript maybe?) to tell shiny to display the output in the second tab, but if so, why is the selectInput shown and not the textOuptut? Can someone help me? Thanks in advance.

template.html

<!DOCTYPE html>

  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>Shiny app</title>
  {{ headContent() }}
  <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bulma@0.8.0/css/bulma.min.css">

          Example Shiny app

Tab 1

Tab 2

Tab 3

          tab1

          Lorem Ipsum passages, and more recently with desktop publishing software like Aldus
          PageMaker including versions of Lorem Ipsum.

          {{ select }}

          {{ text }}

          tab2

          Details Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the
          industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and
          scrambled it to make a type specimen book.

          {{ select2 }}

          {{ text2 }}

          tab3

          It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages,
          and more recently with desktop publishing software like Aldus
          PageMaker including versions of Lorem Ipsum.

server.R

library(shiny)

function(input, output) {

  output$selected_var <- renderText({
    paste("You have selected", input$var)
  })

  output$selected_var2 <- renderText({
    paste("You have selected", input$var2)
  })

}

ui.R

htmlTemplate("template.html",
             select = selectInput("var",
                                  label = "Choose a variable to display",
                                  choices = c("Percent White",
                                              "Percent Black",
                                              "Percent Hispanic",
                                              "Percent Asian"),
                                  selected = "Percent White"),

             text = textOutput("selected_var"),

             select2 = selectInput("var2",
                                   label = "Choose a variable to display",
                                   choices = c("Choice one",
                                               "Choice two",
                                               "Choice three",
                                               "Choice four"),
                                   selected = "Percent White"),

             text2 = textOutput("selected_var2")
)

index.js (javascript to open the tabs)

function openTab(evt, tabName) {
    var i, x, tablinks;
    x = document.getElementsByClassName("content-tab");
    for (i = 0; i < x.length; i++) {
        x[i].style.display = "none";
    }
    tablinks = document.getElementsByClassName("tab");
    for (i = 0; i < x.length; i++) {
        tablinks[i].className = tablinks[i].className.replace(" is-active", "");
    }
    document.getElementById(tabName).style.display = "block";
    evt.currentTarget.className += " is-active";
  }

Body:
In short, you need to call Shiny.unbindAll() before removing Shiny inputs/outputs from the page, and Shiny.bindAll() after adding Shiny inputs/outputs to the page.

Usually Shiny adds and removes inputs/outputs to the page itself, and ensures that those inputs/outputs are properly initialized and hooked up to Shiny (also known as "binding"). When you add or remove inputs/outputs outside of Shiny, you have to let Shiny know using Shiny.unbindAll() and Shiny.bindAll().

For example, in the openTab function in index.js:

function openTab(evt, tabName) {
    var i, x, tablinks;

    Shiny.unbindAll();

    x = document.getElementsByClassName("content-tab");
    for (i = 0; i < x.length; i++) {
        x[i].style.display = "none";
    }
    tablinks = document.getElementsByClassName("tab");
    for (i = 0; i < x.length; i++) {
        tablinks[i].className = tablinks[i].className.replace(" is-active", "");
    }
    document.getElementById(tabName).style.display = "block";
    evt.currentTarget.className += " is-active";

    Shiny.bindAll();
}

bindAll() and unbindAll() search the entire page by default, but you can also call them on a specific element such as the tab content:

function openTab(evt, tabName) {
    var i, x, tablinks, activetab;

    x = document.getElementsByClassName("content-tab");
    for (i = 0; i < x.length; i++) {
        Shiny.unbindAll(x[i]);
        x[i].style.display = "none";
    }
    tablinks = document.getElementsByClassName("tab");
    for (i = 0; i < x.length; i++) {
        tablinks[i].className = tablinks[i].className.replace(" is-active", "");
    }
    activetab = document.getElementById(tabName)
    activetab.style.display = "block";
    evt.currentTarget.className += " is-active";
    Shiny.bindAll(activetab);
}

For more info, see https://shiny.rstudio.com/articles/dynamic-ui.html#use-javascript-to-modify-the-page and https://community.rstudio.com/t/what-is-the-purpose-of-using-shiny-bindall/14489/2


问:
WCF Service worker thread communicate with ServiceHost thread
I have a windows NT Service that opens a ServiceHost object.  The service host context is per-session so for each client a new worker thread is created.  What I am trying to do is have each worker thread make calls to the thread that started the service host.
The NT Service needs to open a VPN connection and poll information from a device on the remote network.  The information is stored in a SQL database for the worker threads to read.  I only want to poll the device if there is a client connected, which will reduce network trafic.  I would like the worker threads to tell the service host thread that they are requesting information and start the polling and updating the database.  Everything is working if the device is alway being polled and the database being updated.</p>

答:
I suggest turning the code that opens a VPN connection and polls for information into its own singleton service and hosting it withing the same (or different) Windows NT Service. The client facing service calls the VPN service using WCF. The VPN service would only poll when client facing services are "listening".

This has a couple advantages:

WCF will take care of the complexities of creating service instances and managing threads. (Within the singleton you will likely still have to implement locking, but that's all.)

The VPN polling service is no longer tightly coupled to the client facing service. This gives you flexibility in deployment and the ability to support new use cases in the future.

ContentLicense: CC BY-SA 2.5

ContentLicense: CC BY-SA 3.0


问:
scss file changes not registering
So I have an app that I generated with jhipster and I'm using scss. I've made some changes to an scss file that aren't showing up in my application, even after a 'mvn clean package'. Currently running my application with './mvnw' and 'npm start' </p>

<p>What do I do to make these changes show up in my app? </p>

答: figured it out: npm run webpack:dev does the trick

Title: scss file changes not registering

Body:
So I have an app that I generated with jhipster and I'm using scss. I've made some changes to an scss file that aren't showing up in my application, even after a 'mvn clean package'. Currently running my application with './mvnw' and 'npm start'

What do I do to make these changes show up in my app?


问:
How to add class to a div that has adjacent sibling using javascript or react?
i want to add a class to a div that has adjacent sibling selector.

Below is the html code,

```<code><div class="wrapper">
    <div class="prev_div">previous</div>
    <div class="next_div">next</div>
</div>
</code>```

I want to add margin property to the div with class "prev_div". I tried doing that with css as below,

```<code>.wrapper div.prev_div + div.next_div {
    margin: 10px;
 }
</code>```

But the above adds the margin to the div with class next_div instead i wanted the margin style for the prev_div.

So i tried doing the same using the javascript by finding the element with prev_div and next_div. if next_div present adding a class "additional" to the prev_div. once class additional added and if the next_div not present remove the additional class for prev_div. but this doesnt work...there is a delay in removing the class added when next_div not present.

```<code>render = () => {
    const prev_div = document.querySelector('wrapper div.prev_div');
    const next_div = document.querySelector('wrapper div.prev_div + div.next_div');
    if (next_div) {
        prev_div.classList.add('additional');
    } else {
        if (prev_div && prev_div.classList.contains('additional')) {
            prev_div.classList.remove('additional');
        }
    }
}
</code>```

Could someone help me fix this or provide a better solution to do this. thanks.

答:
Actually your js code is working, just missed dot . before wrapper

 const prev_div = document.querySelector(".wrapper div.prev_div");
      const next_div = document.querySelector(
        ".wrapper div.prev_div + div.next_div"
      );
      console.log("prev_div", prev_div);
      console.log("next_div", next_div);
      if (next_div) {
        prev_div.classList.add("additional");
      } else {
        if (prev_div && prev_div.classList.contains("additional")) {
          prev_div.classList.remove("additional");
        }
      }```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.additional {
        margin: 10px;
      }</code>```

previous

next

```
</div>
</div>
</p>

<p>Also there is more beautiful solution to add a class to element that has next sibling </p>

```const elem = document.querySelector(".prev_div");
      const isNexSibling = elem => {
        const nextSibling = elem.nextElementSibling;
        if (nextSibling) {
          elem.classList.add("additional");
        }
      };
      isNexSibling(elem);
```

Body:
i want to add a class to a div that has adjacent sibling selector.

Below is the html code,

previous

next

I want to add margin property to the div with class "prev_div". I tried doing that with css as below,

.wrapper div.prev_div + div.next_div {
    margin: 10px;
 }

But the above adds the margin to the div with class next_div instead i wanted the margin style for the prev_div.

So i tried doing the same using the javascript by finding the element with prev_div and next_div. if next_div present adding a class "additional" to the prev_div. once class additional added and if the next_div not present remove the additional class for prev_div. but this doesnt work...there is a delay in removing the class added when next_div not present.

render = () => {
    const prev_div = document.querySelector('wrapper div.prev_div');
    const next_div = document.querySelector('wrapper div.prev_div + div.next_div');
    if (next_div) {
        prev_div.classList.add('additional');
    } else {
        if (prev_div && prev_div.classList.contains('additional')) {
            prev_div.classList.remove('additional');
        }
    }
}

Could someone help me fix this or provide a better solution to do this. thanks.

Body:
Actually your js code is working, just missed dot . before wrapper

 const prev_div = document.querySelector(".wrapper div.prev_div");
      const next_div = document.querySelector(
        ".wrapper div.prev_div + div.next_div"
      );
      console.log("prev_div", prev_div);
      console.log("next_div", next_div);
      if (next_div) {
        prev_div.classList.add("additional");
      } else {
        if (prev_div && prev_div.classList.contains("additional")) {
          prev_div.classList.remove("additional");
        }
      }

.additional {
        margin: 10px;
      }

 <div class="wrapper">
      <div class="prev_div">previous</div>
      <div class="next_div">next</div>
 </div>

Also there is more beautiful solution to add a class to element that has next sibling

const elem = document.querySelector(".prev_div");
      const isNexSibling = elem => {
        const nextSibling = elem.nextElementSibling;
        if (nextSibling) {
          elem.classList.add("additional");
        }
      };
      isNexSibling(elem);


问:
React: Filtered Search / 'cities' is not defined no-undef
I am trying to make a filtered search in react, however it keeps giving me an error:
'cities' is not defined  no-undef

I have one component: Cities.js

```<code>import React from "react";
export default class Cities extends React.Component {
  state = {
    loading: true,
    cities: []
  };

  async componentDidMount() {
    const url = "http://localhost:5000/cities/all";
    const response = await fetch(url);
    const data = await response.json();
    this.setState({ cities: data, loading: false });
    console.log(data);
  }
  constructor() {
    super();
    this.state = {
      search: ""
    };
  }

  updateSearch(event) {
    this.setState({ search: event.target.value.substr(0, 10) });
  }

  render() {
    // FILTER
    let filteredCities = this.state.cities.filter(city => {
      return (
        cities.city.toLowerCase().indexOf(this.state.search.toLowerCase()) !==
        -1
      );
    });

    return (
      <div>
        <input
          type="text"
          value={this.state.search}
          onChange={this.updateSearch.bind(this)}
        />

        {this.state.loading ? (
          <div> loading... </div>
        ) : (
          <div>
            {this.state.cities &&
              filteredCities.map(places => (
                <div key={places._id}>
                  {places.city}, {places.country}{" "}
                  <div>
                    <img src={places.url} />
                  </div>
                </div>
              ))}
          </div>
        )}
      </div>
    );
  }
}
</code>```

I started having issues once I added the:

// FILTER
 let filteredCities = this.state.cities.filter(city => {
          return (
            cities.city.toLowerCase().indexOf(this.state.search.toLowerCase()) !==
            -1

答:
The undefined error is caused by your filtering callback using undefined cities. You need to use city instead.

Example:

```<code>render() {
    // FILTER
    const filteredCities = this.state.cities.filter(city => {
        return city.city.toLowerCase().includes(this.state.search.toLowerCase())
    });

    return (
      <div>
        <input
          type="text"
          value={this.state.search}
          onChange={this.updateSearch.bind(this)}
        />

        {this.state.loading ? (
          <div> loading... </div>
        ) : (
          <div>
            {filteredCities &&
              filteredCities.map(places => (
                <div key={places._id}>
                  {places.city}, {places.country}{" "}
                  <div>
                    <img src={places.url} />
                  </div>
                </div>
              ))}
          </div>
        )}
      </div>
    );
  }
}
</code>```

You may also be removing cities from your default state in your constructor (which could potentially cause issues). Instead you could remove the defined object from the class, and simply define it in the constructor via this.state. Example:

```<code>constructor(props) {
    super(props);

    this.state = {
      search: "",
      loading: true,
      cities: []
    };
}
</code>```

Additionally, since you are using an aync + await function, it is highly recommended to wrap your awaits in a try...catch to handle any potential errors.

Example:

```<code>async componentDidMount() {
    const url = "http://localhost:5000/cities/all";
    try {
        const response = await fetch(url);
        const data = await response.json();
        this.setState({ cities: data, loading: false });
        console.log(data);
    } catch (error) {
        console.log(error);
    }
}
</code>```

Body:
I am trying to make a filtered search in react, however it keeps giving me an error:
'cities' is not defined  no-undef

I have one component: Cities.js

import React from "react";
export default class Cities extends React.Component {
  state = {
    loading: true,
    cities: []
  };

  async componentDidMount() {
    const url = "http://localhost:5000/cities/all";
    const response = await fetch(url);
    const data = await response.json();
    this.setState({ cities: data, loading: false });
    console.log(data);
  }
  constructor() {
    super();
    this.state = {
      search: ""
    };
  }

  updateSearch(event) {
    this.setState({ search: event.target.value.substr(0, 10) });
  }

  render() {
    // FILTER
    let filteredCities = this.state.cities.filter(city => {
      return (
        cities.city.toLowerCase().indexOf(this.state.search.toLowerCase()) !==
        -1
      );
    });

    return (

        <input
          type="text"
          value={this.state.search}
          onChange={this.updateSearch.bind(this)}
        />

        {this.state.loading ? (

 loading...

        ) : (

            {this.state.cities &&
              filteredCities.map(places => (

                  {places.city}, {places.country}{" "}

              ))}

        )}

    );
  }
}

I started having issues once I added the:

// FILTER
 let filteredCities = this.state.cities.filter(city => {
          return (
            cities.city.toLowerCase().indexOf(this.state.search.toLowerCase()) !==
            -1

Body:
The undefined error is caused by your filtering callback using undefined cities. You need to use city instead.

Example:

render() {
    // FILTER
    const filteredCities = this.state.cities.filter(city => {
        return city.city.toLowerCase().includes(this.state.search.toLowerCase())
    });

    return (
      <div>
        <input
          type="text"
          value={this.state.search}
          onChange={this.updateSearch.bind(this)}
        />

        {this.state.loading ? (
          <div> loading... </div>
        ) : (
          <div>
            {filteredCities &&
              filteredCities.map(places => (
                <div key={places._id}>
                  {places.city}, {places.country}{" "}
                  <div>
                    <img src={places.url} />
                  </div>
                </div>
              ))}
          </div>
        )}
      </div>
    );
  }
}

You may also be removing cities from your default state in your constructor (which could potentially cause issues). Instead you could remove the defined object from the class, and simply define it in the constructor via this.state. Example:

constructor(props) {
    super(props);

    this.state = {
      search: "",
      loading: true,
      cities: []
    };
}

Additionally, since you are using an aync + await function, it is highly recommended to wrap your awaits in a try...catch to handle any potential errors.

Example:

async componentDidMount() {
    const url = "http://localhost:5000/cities/all";
    try {
        const response = await fetch(url);
        const data = await response.json();
        this.setState({ cities: data, loading: false });
        console.log(data);
    } catch (error) {
        console.log(error);
    }
}


问:
Dealing with Apps Script Properties in AuthMode.NONE
I'm working on an AddOn based on an Apps Script library which stores several keystrings in the user cache. In testing the AddOn in AuthMode.NONE, the menu addition fails because the cache is trying to load when the document opens.

To work around this, I've tried incorporating several of the cache calls right into my code. This hasn't worked either.

Is there a way to programmatically add a library or prevent certain .gs files from loading in an AddOn until the user has enabled it?

UPDATE

Tanaike has a helpful Manifest library which allows you to change which libraries the app has access to. But, it still leads to authorization limitations. Is there a way to have the user interactively change the authorization mode?

答:
I'm pretty sure this is a bug in Apps Script addon development flow.

I have released an addon, that follows the code from Apps Script documentation:

```<code>function onOpen(e) {
  var menu = SpreadsheetApp.getUi().createAddonMenu();
  if (e && e.authMode == ScriptApp.AuthMode.NONE) {
    // Add a normal menu item (works in all authorization modes).
    menu.addItem('Enable Addon', 'startWorkflow');
  }
  menu.addToUi();
}
</code>```

The addon works and when installed from Gsuite Marketplace, the Enable Addon menu correctly appears in AuthMode.None.

However, when tested from inside script editor in AuthMode.None, it fails to add menus correctly with a console info:

```<code>Script Google Apps: Exception: You don't have permission for this action.
</code>```

I think Google devs should handle it and fix the bug, and it's not meant to be solved by some manifest libraries or something else.

Body:
I'm pretty sure this is a bug in Apps Script addon development flow.

I have released an addon, that follows the code from Apps Script documentation:

function onOpen(e) {
  var menu = SpreadsheetApp.getUi().createAddonMenu();
  if (e && e.authMode == ScriptApp.AuthMode.NONE) {
    // Add a normal menu item (works in all authorization modes).
    menu.addItem('Enable Addon', 'startWorkflow');
  }
  menu.addToUi();
}

The addon works and when installed from Gsuite Marketplace, the Enable Addon menu correctly appears in AuthMode.None.

However, when tested from inside script editor in AuthMode.None, it fails to add menus correctly with a console info:

Script Google Apps: Exception: You don't have permission for this action.

I think Google devs should handle it and fix the bug, and it's not meant to be solved by some manifest libraries or something else.


问:
How can I pass a value with a $ to a program run through su?
I need to run one of the script as below:

su - oracle -c 'cd /tmp/somepath; sh -x myscript.sh arg1 arg2 arg3
  obj$_jghd$:jhdbcdj:hshabsh'

where arg4(obj$_jghd$:jhdbcdj:hshabsh) should be treated as one argument and calling in for loop in myscript.sh
Below is the sample code

```<code>id1=$1
id2=$2
id3=$3
name=$4
S_Object=`echo ""${name}""|sed 's/:/ /g'`
</code>```

here I am reformating agr4 and removing the delimiter : with space and trying to nullify $. But when running the script all variables are not getting stored which contains $ and getting this error:

```<code>+ name='obj$:jhdbcdj:hshabsh'
++ echo 'obj$:jhdbcdj:hshabsh'
++ sed 's/:/ /g'
++ sed '/s/$/$/g'
sed: -e expression #1, char 4: unknown command: `$'
</code>```

Can you please help to get the right string stored in name variable.

I want the result should be like :

```<code>echo $S_Object

S_Object='obj$_jghd$ jhdbcdj hshabsh'
</code>```

but I am getting as below :

```<code>echo $S_Object
S_Object='obj$ jhdbcdj hshabsh'
</code>```

答:
I have corrected the syntax errors and outdated idioms in your script.

This seems to work :

```<code>#!/bin/bash

id1=$1
id2=$2
id3=$3
name=$4
S_Object=$( echo "${name}" | sed 's/:/ /g' | sed 's/$/\$/g'  )

echo "$S_Object"
</code>```

Please let me know if it helps!

Body:
I need to run one of the script as below:

su - oracle -c 'cd /tmp/somepath; sh -x myscript.sh arg1 arg2 arg3
  obj$_jghd$:jhdbcdj:hshabsh'

where arg4(obj$_jghd$:jhdbcdj:hshabsh) should be treated as one argument and calling in for loop in myscript.sh
Below is the sample code

id1=$1
id2=$2
id3=$3
name=$4
S_Object=`echo ""${name}""|sed 's/:/ /g'`

here I am reformating agr4 and removing the delimiter : with space and trying to nullify $. But when running the script all variables are not getting stored which contains $ and getting this error:

+ name='obj$:jhdbcdj:hshabsh'
++ echo 'obj$:jhdbcdj:hshabsh'
++ sed 's/:/ /g'
++ sed '/s/$/$/g'
sed: -e expression #1, char 4: unknown command: `$'

Can you please help to get the right string stored in name variable.

I want the result should be like :

echo $S_Object

S_Object='obj$_jghd$ jhdbcdj hshabsh'

but I am getting as below :

echo $S_Object
S_Object='obj$ jhdbcdj hshabsh'

Body:
I have corrected the syntax errors and outdated idioms in your script.

This seems to work :

#!/bin/bash

id1=$1
id2=$2
id3=$3
name=$4
S_Object=$( echo "${name}" | sed 's/:/ /g' | sed 's/$/\$/g'  )

echo "$S_Object"

Please let me know if it helps!


问:
unable to connect emulator with internet
I am using Android 2.2 . I am unable to connect my emulator to internet .

When I open my web browser in the emulator it shows the message "Web Page not available" . I have set proxy settings in the emulator (settings -> Wireless & Networks ->Mobile Networks -> Access Point Names). Also , I set proxy settings in eclipse (Windows-> Preferences-> Android-> Launch-> Default Emulator Options). I have read many blogs and forums but I haven't found any solution yet .I am really frustrated .

Please help me out.

Abhijeet

答: The simplest and the best way is to do the following: This has been done for Android Emulator 2.2 1.Click on Menu 2.Click on Settings 3.Click on Wireless & Networks 4.Go to Mobile Networks 5.Go to Access Point Names 6.Here you will Telkila Internet, click on it. 7.In the Edit access point section, input the "proxy" and "port" 8.Also provide the Username and Password, rest of the fields leave them blank.</p>


问:
What is the correct way to send json POST request with Gnomes libsoup
Im having trouble sending POST requests with Gnome's libsoup. GET requests I can do just fine I just am unsure how to get a working post request.

 _httpSession = new Soup.Session();

        let url = "http://localhost:3000/api/auth/register/org";
        var body = {body:"?how to add"}

        let message = Soup.Message.new('POST', url);

        message.set_request('application/json', 2,body);
        _httpSession.queue_message(message, function (_httpSession, message){
            //log res
            global.log(message.response_body.data)

        });

```

This is what I have right now. I don't know how to add the body of post request. The documentation says set_request requires 4 params but I get an error saying it expects 3 if I add the body.length.

答:
 _httpSession = new Soup.Session();

        let url = "http://localhost:3000/api/auth/register/org";
        var body = `{"user":"tom","pass":"1234"}`

        let message = Soup.Message.new('POST', url);

        message.set_request('application/json', 2,body);
        _httpSession.queue_message(message, function (_httpSession, message){
            //log res
            global.log(message.response_body.data)

        });
```

<p>For anyone trying to figure this out the body has to be a string created to look like a json object. All of the examples I saw were just saying </p>

```body="user=this"
```

which is incorrect.

Body:
Im having trouble sending POST requests with Gnome's libsoup. GET requests I can do just fine I just am unsure how to get a working post request.

 _httpSession = new Soup.Session();

        let url = "http://localhost:3000/api/auth/register/org";
        var body = {body:"?how to add"}

        let message = Soup.Message.new('POST', url);

        message.set_request('application/json', 2,body);
        _httpSession.queue_message(message, function (_httpSession, message){
            //log res
            global.log(message.response_body.data)

        });

This is what I have right now. I don't know how to add the body of post request. The documentation says set_request requires 4 params but I get an error saying it expects 3 if I add the body.length.

Body:
 _httpSession = new Soup.Session();

        let url = "http://localhost:3000/api/auth/register/org";
        var body = `{"user":"tom","pass":"1234"}`

        let message = Soup.Message.new('POST', url);

        message.set_request('application/json', 2,body);
        _httpSession.queue_message(message, function (_httpSession, message){
            //log res
            global.log(message.response_body.data)

        });

For anyone trying to figure this out the body has to be a string created to look like a json object. All of the examples I saw were just saying

body="user=this"

which is incorrect.


问:
Material UI IconButton onClick doesn't let to handle event
I installed "@material-ui/core": "^4.9.2" and "@material-ui/icons": "^4.9.1".

In my form i have several rows, each row has an add button and a remove button.  I want the remove button to remove the row from it was clicked.  It works fine with regular Button with a "-" character in it.  But i want it fancy, so i replaced my Button from an IconButton, and imported the icons to use

```<code>import {AddCircleOutline,RemoveCircleOutlineOutlined} from "@material-ui/icons";
</code>```

And my IconButton looks like this:

```<code>        <IconButton
          onClick={props.onRemoveClick}
          className="align-self-center"
          color="info"
          size="sm"
          disabled={props.index > 0 ? false : true}
          <RemoveCircleOutlineOutlined/>
        </IconButton>
</code>```

When the IconButton is hit, the onClick method is called (i know because of logs in my console) but i can't handle the event because it is now undefined.

The funny thing is that if i click on the button area that doesn't correspond to the icon, it works.  But obviously i need it to work in the whole area of the button.

It is not a binding issue because i already tested it.

Any ideas?

答:
Well you gave an idea.  Since i needed an index to identify the row's button, i sended the index through a paramater on the onClick method, like this:

```<code>onClick={e => props.onRemoveClick(props.index)}
</code>```

In this way i didn't need to handle the event.  I also had to bind my method on the constructor:

constructor(props) {
    super(props);
    this.handleRemoveClick = this.handleRemoveClick.bind(this);
  }

Now i got the behaviour wanted

Body:
I installed "@material-ui/core": "^4.9.2" and "@material-ui/icons": "^4.9.1".

In my form i have several rows, each row has an add button and a remove button.  I want the remove button to remove the row from it was clicked.  It works fine with regular Button with a "-" character in it.  But i want it fancy, so i replaced my Button from an IconButton, and imported the icons to use

import {AddCircleOutline,RemoveCircleOutlineOutlined} from "@material-ui/icons";

And my IconButton looks like this:

        <IconButton
          onClick={props.onRemoveClick}
          className="align-self-center"
          color="info"
          size="sm"
          disabled={props.index > 0 ? false : true}
          <RemoveCircleOutlineOutlined/>
        </IconButton>

When the IconButton is hit, the onClick method is called (i know because of logs in my console) but i can't handle the event because it is now undefined.

The funny thing is that if i click on the button area that doesn't correspond to the icon, it works.  But obviously i need it to work in the whole area of the button.

It is not a binding issue because i already tested it.

Any ideas?

Body:
Well you gave an idea.  Since i needed an index to identify the row's button, i sended the index through a paramater on the onClick method, like this:

onClick={e => props.onRemoveClick(props.index)}

In this way i didn't need to handle the event.  I also had to bind my method on the constructor:

constructor(props) {
    super(props);
    this.handleRemoveClick = this.handleRemoveClick.bind(this);
  }

Now i got the behaviour wanted


问:
How to return a range of XML nodes with XQuery of FLWOR?
I'm interested in getting back a specific range of results, say from 99 to 199, or, perhaps, the last JSON object.  While this works for small numbers or ranges, how can it be generalized or expanded to a larger range?

```<code>xquery version "3.0";

for $i in (1,2,3)
for $line in db:open("json_people")
return $line/json/_[$i]
</code>```

答:
You can use range in XQuery as follows:</p>

```<code>for $i in (99 to 199)
</code>```

Body:
I'm interested in getting back a specific range of results, say from 99 to 199, or, perhaps, the last JSON object.  While this works for small numbers or ranges, how can it be generalized or expanded to a larger range?

xquery version "3.0";

for $i in (1,2,3)
for $line in db:open("json_people")
return $line/json/_[$i]

Body:
You can use range in XQuery as follows:

for $i in (99 to 199)


问:
Sorting of list by matching the 'input' lists in Python
I have a (probably quite simple) problem I cannot figure out in Python.

Say I have a list
X1 = [1,2,3]
with the corresponding list
Y1 = [5,6,7]
and a list
X2 = [2,1,3]
with corresponding list
Y2 = [8,9,10]
where X1 and X2 contain the same values but in different order. How can I match the order of X2 to that of X1, while the X2 Y2 pairs remain intact? The answer should be then Y2 = [9,8,10].

Thank you in advance!

Body:
u can play with zip

Your Code:

x1 = [1, 2, 3]
y1 = [5, 6, 7]

x2 = [2, 1, 3]
y2 = [8, 9, 10]

Step 1 zip the lists:

z1 = list(zip(x1, y1))
z2 = list(zip(x2, y2))

OUTPUT:

[(1, 5), (2, 6), (3, 7)]
[(2, 8), (1, 9), (3, 10)]

Step 2 sort the new lists:

z1.sort()
z2.sort()

OUTPUT:

[(1, 5), (2, 6), (3, 7)]
[(1, 9), (2, 8), (3, 10)]

Step 3 list zip them again with *

z1 = list(zip(*z1))
z2 = list(zip(*z2))

OUTPUT:

[(1, 2, 3), (5, 6, 7)]
[(1, 2, 3), (9, 8, 10)]

NOW put the values back:

x1 = z1[0]
y1 = z1[1]
x2 = z2[0]
y2 = z2[1]

OUTPUT:

x1 = (1, 2, 3)
y1 = (5, 6, 7)
x2 = (1, 2, 3)
y2 = (9, 8, 10)

Remember x1, x2, y1, y2 is now tuple if u want to be list u need one more step

x1 = list(x1)
x2 = list(x2)
y1 = list(y1)
y2 = list(y2)

Output:

x1 = [1, 2, 3]
y1 = [5, 6, 7]
x2 = [1, 2, 3]
y2 = [9, 8, 10]


问:
Shuffle output of find with fixed seed
I would like to shuffle output of find BUT with a fixed seed, so that every time I run the command I get the same output.

Here's how I shuffle:

```<code>find . -name '*.wav' | shuf
</code>```

The issue is that every time we have a new seed -> new order. My attempt to fix it:

```<code>find . -name '*.wav' | shuf --random-source=<(echo 42)
</code>```

That works only on occasions (i.e. just a few cases, in a deterministic way). Most of the time it fails with:

shuf: ‘/proc/self/fd/12’: end of file

Same error is produced by e.g.

```<code>seq 1 100 | sort -R --random-source=<(echo 42)
</code>```

That I have seen being used in other places.

This works though:

```<code>printf '%s\n' a b c | shuf --random-source=<(echo 42)
</code>```

Why is that? And how I can fix it? I am open to any suggestions. Output of the find is a part of a larger script. The solution should work for bash and zsh.

Why my solution did not work (EDIT)

Thanks to @franzisk and @Inian I think I understand now why my initial solution did not work. I was looking at --random-source as it were a seek, while it is, well, "random source" = source of randomness. My echo 42 simply does not provide enough entropy for anything longer than a few lines. That's why it worked only in a couple of cases!

"Seeding" (as in: sending) large number of bytes does the job as it provides enough entropy.

答:
You can create your fixed_random function, using openssl to generate your random-source flow, like this

```<code>get_fixed_random()
{
  openssl enc -aes-256-ctr -pass pass:"$1" -nosalt </dev/zero 2>/dev/null
}
</code>```

Load the function into your environment

```<code>. /file-containing/get_fixed_random
</code>```

Launch the find command, pipe the output to shuf using the random function to feed the --random-source option

```<code>find . -name '*.wav'  | shuf --random-source=<(get_fixed_random 55)
</code>```

NB: 55 is just the seed parameter passed. Change it to change the random result

Title: Shuffle output of find with fixed seed

Body:
I would like to shuffle output of find BUT with a fixed seed, so that every time I run the command I get the same output.

Here's how I shuffle:

find . -name '*.wav' | shuf

The issue is that every time we have a new seed -> new order. My attempt to fix it:

find . -name '*.wav' | shuf --random-source=<(echo 42)

That works only on occasions (i.e. just a few cases, in a deterministic way). Most of the time it fails with:

shuf: ‘/proc/self/fd/12’: end of file

Same error is produced by e.g.

seq 1 100 | sort -R --random-source=<(echo 42)

That I have seen being used in other places.

This works though:

printf '%s\n' a b c | shuf --random-source=<(echo 42)

Why is that? And how I can fix it? I am open to any suggestions. Output of the find is a part of a larger script. The solution should work for bash and zsh.

Why my solution did not work (EDIT)

Thanks to @franzisk and @Inian I think I understand now why my initial solution did not work. I was looking at --random-source as it were a seek, while it is, well, "random source" = source of randomness. My echo 42 simply does not provide enough entropy for anything longer than a few lines. That's why it worked only in a couple of cases!

"Seeding" (as in: sending) large number of bytes does the job as it provides enough entropy.

Body:
You can create your fixed_random function, using openssl to generate your random-source flow, like this

get_fixed_random()
{
  openssl enc -aes-256-ctr -pass pass:"$1" -nosalt </dev/zero 2>/dev/null
}

Load the function into your environment

. /file-containing/get_fixed_random

Launch the find command, pipe the output to shuf using the random function to feed the --random-source option

find . -name '*.wav'  | shuf --random-source=<(get_fixed_random 55)

NB: 55 is just the seed parameter passed. Change it to change the random result


问:
Big Data Processing At the Click of a Button
If you have an application that performs some heavy calculation on a large data set, and the results must be returned as quickly as possible at the click of a button, what are some architectural designs that are used to make this work large scale?

For example, an application runs a simulation to predict future results, and then does some statistical analysis on that data along with historical data. There is a good amount of CPU to run the simulation and DB heavy with inserting, then lots of big DB reads to collect historical data, and more CPU to do statistical analyses.

In essence, there is lots of data to process (both CPU and IO intensive), and the results should theoretically be shown at the click of a button.

I understand that this is not always a realistic goal depending on the intensity, but what are some typical architectures to accomplish such a task?

答:
Rob has suggested a nice approach using MapReduce.

I believe  this sort of processing is part of Data Mining process  and data mining process has different approach than traditional request response model.

As a bare minimum

create a single table (denormalized) and store all the necessary information in the this table and then when users needs the information in real time , just do a table lookup and get the information as quickly as possible.

but there are challenges to this approach and one of the major challenge is to populate the data in this de-normalized table.

most of the time , it can be done offline may be by a night job or something which populates this table when the load is minimum !

This approach is one of the approach used in when you see "Customer who bought this item also bought” in a typical e-commerce application.

for more information and reference , please see

1- Sql Server Analysis Services

2- Item to Item Collaborative Filtering ( esp. refer Amazon implementation)


问:
Ubuntu crontab not running all the time
I wish someone could help me, I'm trying to use crontab to run some auto python scripts, and it works, but for some reason it won't run the scripts as expected.
If I don't make a SSH connection for to long the python scripts in the crontab won't run, if I log again they will run for some time after i log out and then they stop.

```<code>30 03 * * * systemctl reboot > /home/ajorge/server/python/logs/crontab_reboot.log 2>&1
45 03 * * * sudo python /home/ajorge/server/python/startup.py > /home/ajorge/server/python/logs/crontab_startup.log 2>&1
*/15 * * * * sudo python /home/ajorge/server/python/backup_auth.py > /home/ajorge/server/python/logs/crontab_auth.log 2>&1
*/15 * * * * sudo python /home/ajorge/server/python/backup_characters.py > /home/ajorge/server/python/logs/crontab_characters.log 2>&1
35 03 * * * sudo python /home/ajorge/server/python/backup_world.py > /home/ajorge/server/python/logs/crontab_world.log 2>&1
*/15 * * * * sudo python /home/ajorge/server/python/backup_clean.py > /home/ajorge/server/python/logs/crontab_clean.log 2>&1
</code>```

The script is suppose to run every 15 min for the example below, but we can see that it didn't and there is a gap

If i make a SSH connection to the server it will start running the scripts again without me doint anything.

Anyone can help me?

答:
Generate your crontab as user "root", then change them like:</p>

```<code>30 03 * * * systemctl reboot > /home/ajorge/server/python/logs/crontab_reboot.log 2>&1
45 03 * * * python /home/ajorge/server/python/startup.py > /home/ajorge/server/python/logs/crontab_startup.log 2>&1
*/15 * * * * python /home/ajorge/server/python/backup_auth.py > /home/ajorge/server/python/logs/crontab_auth.log 2>&1
*/15 * * * * python /home/ajorge/server/python/backup_characters.py > /home/ajorge/server/python/logs/crontab_characters.log 2>&1
35 03 * * * python /home/ajorge/server/python/backup_world.py > /home/ajorge/server/python/logs/crontab_world.log 2>&1
*/15 * * * * python /home/ajorge/server/python/backup_clean.py > /home/ajorge/server/python/logs/crontab_clean.log 2>&1
</code>```

Title: Ubuntu crontab not running all the time

Body:
I wish someone could help me, I'm trying to use crontab to run some auto python scripts, and it works, but for some reason it won't run the scripts as expected.
If I don't make a SSH connection for to long the python scripts in the crontab won't run, if I log again they will run for some time after i log out and then they stop.

30 03 * * * systemctl reboot > /home/ajorge/server/python/logs/crontab_reboot.log 2>&1
45 03 * * * sudo python /home/ajorge/server/python/startup.py > /home/ajorge/server/python/logs/crontab_startup.log 2>&1
*/15 * * * * sudo python /home/ajorge/server/python/backup_auth.py > /home/ajorge/server/python/logs/crontab_auth.log 2>&1
*/15 * * * * sudo python /home/ajorge/server/python/backup_characters.py > /home/ajorge/server/python/logs/crontab_characters.log 2>&1
35 03 * * * sudo python /home/ajorge/server/python/backup_world.py > /home/ajorge/server/python/logs/crontab_world.log 2>&1
*/15 * * * * sudo python /home/ajorge/server/python/backup_clean.py > /home/ajorge/server/python/logs/crontab_clean.log 2>&1

The script is suppose to run every 15 min for the example below, but we can see that it didn't and there is a gap

If i make a SSH connection to the server it will start running the scripts again without me doint anything.

Anyone can help me?

Body:
Generate your crontab as user "root", then change them like:

30 03 * * * systemctl reboot > /home/ajorge/server/python/logs/crontab_reboot.log 2>&1
45 03 * * * python /home/ajorge/server/python/startup.py > /home/ajorge/server/python/logs/crontab_startup.log 2>&1
*/15 * * * * python /home/ajorge/server/python/backup_auth.py > /home/ajorge/server/python/logs/crontab_auth.log 2>&1
*/15 * * * * python /home/ajorge/server/python/backup_characters.py > /home/ajorge/server/python/logs/crontab_characters.log 2>&1
35 03 * * * python /home/ajorge/server/python/backup_world.py > /home/ajorge/server/python/logs/crontab_world.log 2>&1
*/15 * * * * python /home/ajorge/server/python/backup_clean.py > /home/ajorge/server/python/logs/crontab_clean.log 2>&1


问:
Change User Role After Certain Number of Days | Laravel
I am two types of User

Reader: Can Read Books

Subscriber: Cannot Reed Books

In my user table, I have trialto column, which adds 7days to the date which the email is verified.

So my problem is to fire an event or a function that checks the trialto column when the trialto column equals to now().

I am building a Laravel Application where when the user signup and verifies his email, he is given a Reader Role as trial by Default, but after 7 days it reverts back to Subscriber if the User didn't subscribe.

I don't have the idea of how to go about this, I am thinking Laravel Scheduling can help in fixing this.

Thanks for your help.

答:
I would just check the trialto date when showing content and not set trial users as Readers:

class User
{
    public function isSubscriber()
    {
        return $this->role === 'Reader' || $this->trialto->isFuture();
    }
}
```


问:
Docker swarm not exposing port
I'm trying to run docker swarm on a single node and having trouble getting a docker app port exposed to the host.

This is similar Docker swarm service port not exposed but I'm running in a single node, and provide more detail on my question and research.

For example,  given the following myapp.yml file:

```<code>version: "3"
services:
  app:
    image: myapp
    ports:
      - "8123:8123"
</code>```

The stack is started via

docker stack deploy -c myapp.yml myapp

After the stack is started, when I try to access the port (via curl) it fails.   For example,

curl -v http://localhost:8123/myapp

shows the connection was refused (nothing was listening on that port).

Code works when using docker run

The following command starts the image and shows how to verify the port is exposed.

docker run -p 8123:8123 --name myapp myapp

Curl then works.

curl -v http://localhost:8123/myapp

Gives output from the app running in docker.

When I run docker ps  the output in the PORTS section shows: 0.0.0.0:8123:8123/tcp.

docker network inspect bridge -  Show that the docker container is assigned to the bridge network.  The docker bridge network is used by default with the docker run command.

The command docker port myapp shows:

8123/tcp -> 0.0.0.0:8123

which matches the output from docker ps PORT field.

docker stack deploy doesn't expose port

After starting using docker stack deploy -c myapp.yml myapp, I run the docker ps command and only see 8123/tcp in the PORTS field of the output.

The command docker port myapp has no output (indicating no ports are available from the docker host.

When I run docker network ls, I see:

```<code>NETWORK ID       NAME            DRIVER     SCOPE
1234567890      bridge           bridge     local
9999999999      myapp_default   overlay    swarm
</code>```

So I noticed that the network myapp_default is in a different mode than bridge, local.  I tried using existing bridge network but when I refereed to the bridge network in my stack/compose file I observed that the network myapp_bridge was created.

So I read up on docker networking https://blog.alexellis.io/docker-stacks-attachable-networks/ was a good writeup.

So far I haven't gotten it to work so I drafted this to ask for suggestions/help.

NOTE: This aricle (dated Feb 2017) says it should work but doesn't address my question.

I think I'm close.

Resources and other related questions

https://docs.docker.com/v17.12/get-started/part5/ - is the docker primary documentation for the docker stack technology.  But searches on that page for networks shows nothing useful.

https://blog.alexellis.io/docker-stacks-attachable-networks/ - Good write up.

Docker swarm service port not exposed - similar to the question I'm asking.

https://runnable.com/docker/basic-docker-networking - Write up on docker networking.  It says the following when creating an overlay network (which is the default when docker stack deploy is used).

These networks require a valid key-value store service, such as
Consul, Etcd, or ZooKeeper. You must install and configure your
key-value store service before creating your network.

Can not use user-defined bridge in swarm compose yaml file.

答:
In swarm

```<code>ports:
  - "8123:8123"
</code>```

will expose port on all swarm nodes and in case of use of the port on some of the nodes by another service you can have problems

you can expose port only on host with container with next docker-compose.yml config

```<code>services:
  app:
    ports:
      - target: 8123
        published: 8123
        mode: host
</code>```

Title: Docker swarm not exposing port

Body:
I'm trying to run docker swarm on a single node and having trouble getting a docker app port exposed to the host.

This is similar Docker swarm service port not exposed but I'm running in a single node, and provide more detail on my question and research.

For example,  given the following myapp.yml file:

version: "3"
services:
  app:
    image: myapp
    ports:
      - "8123:8123"

The stack is started via

docker stack deploy -c myapp.yml myapp

After the stack is started, when I try to access the port (via curl) it fails.   For example,

curl -v http://localhost:8123/myapp

shows the connection was refused (nothing was listening on that port).

Code works when using docker run

The following command starts the image and shows how to verify the port is exposed.

docker run -p 8123:8123 --name myapp myapp

Curl then works.

curl -v http://localhost:8123/myapp

Gives output from the app running in docker.

When I run docker ps  the output in the PORTS section shows: 0.0.0.0:8123:8123/tcp.

docker network inspect bridge -  Show that the docker container is assigned to the bridge network.  The docker bridge network is used by default with the docker run command.

The command docker port myapp shows:

8123/tcp -> 0.0.0.0:8123

which matches the output from docker ps PORT field.

docker stack deploy doesn't expose port

After starting using docker stack deploy -c myapp.yml myapp, I run the docker ps command and only see 8123/tcp in the PORTS field of the output.

The command docker port myapp has no output (indicating no ports are available from the docker host.

When I run docker network ls, I see:

NETWORK ID       NAME            DRIVER     SCOPE
1234567890      bridge           bridge     local
9999999999      myapp_default   overlay    swarm

So I noticed that the network myapp_default is in a different mode than bridge, local.  I tried using existing bridge network but when I refereed to the bridge network in my stack/compose file I observed that the network myapp_bridge was created.

So I read up on docker networking https://blog.alexellis.io/docker-stacks-attachable-networks/ was a good writeup.

So far I haven't gotten it to work so I drafted this to ask for suggestions/help.

NOTE: This aricle (dated Feb 2017) says it should work but doesn't address my question.

I think I'm close.

Resources and other related questions

https://docs.docker.com/v17.12/get-started/part5/ - is the docker primary documentation for the docker stack technology.  But searches on that page for networks shows nothing useful.

https://blog.alexellis.io/docker-stacks-attachable-networks/ - Good write up.

Docker swarm service port not exposed - similar to the question I'm asking.

https://runnable.com/docker/basic-docker-networking - Write up on docker networking.  It says the following when creating an overlay network (which is the default when docker stack deploy is used).

These networks require a valid key-value store service, such as
Consul, Etcd, or ZooKeeper. You must install and configure your
key-value store service before creating your network.

Can not use user-defined bridge in swarm compose yaml file.

Body:
In swarm

ports:
  - "8123:8123"

will expose port on all swarm nodes and in case of use of the port on some of the nodes by another service you can have problems

you can expose port only on host with container with next docker-compose.yml config

services:
  app:
    ports:
      - target: 8123
        published: 8123
        mode: host


问:
string split into lines php by pattern
I have a string like this:

```<code>1. 192.168.122.1 0.89 Bps 2. 192.168.122.10 0.25 Bps
</code>```

I want to split the string into two strings like this:

```<code>192.168.122.1 0.89 Bps
192.168.122.10 0.25 Bps
</code>```

答:
You could use a regular expression. \d is a shortcut to the [0-9] character class, which is used often in the following expression.

```<code>preg_match_all('/\d+\. \d+\.\d+\.\d+\.\d+ [\d.]+ Bps/', $str, $matches);
</code>```

CodePad.

In your example, $matches will contain...

```<code>array(1) {
  [0]=>
  array(2) {
    [0]=>
    string(25) "1. 192.168.122.1 0.89 Bps"
    [1]=>
    string(26) "2. 192.168.122.10 0.25 Bps"
  }
}
</code>```

Title: string split into lines php by pattern

Body:
I have a string like this:

1. 192.168.122.1 0.89 Bps 2. 192.168.122.10 0.25 Bps

I want to split the string into two strings like this:

192.168.122.1 0.89 Bps
192.168.122.10 0.25 Bps

Body:
You could use a regular expression. \d is a shortcut to the [0-9] character class, which is used often in the following expression.

preg_match_all('/\d+\. \d+\.\d+\.\d+\.\d+ [\d.]+ Bps/', $str, $matches);

CodePad.

In your example, $matches will contain...

array(1) {
  [0]=>
  array(2) {
    [0]=>
    string(25) "1. 192.168.122.1 0.89 Bps"
    [1]=>
    string(26) "2. 192.168.122.10 0.25 Bps"
  }
}


问:
setInterval on mouseenter and clear interval on mouseleave
I'm using setInterval to create a diy slideshow that starts on mouseenter using this tutorial :
https://www.amideveloper.com/how-to-start-slideshow-on-hover-image-in-jquery/

It works fine, but I would like the slideshow to stop on mouseleave by using clearInterval.

I don't know what I'm doing wrong has my Interval is not cleared and the slideshow won't stop...

here is my code :

JQUERY

```<code>$(".fadeInOut > div:gt(0)").hide();

function change_div() {

  $(".fadeInOut > div:first").fadeOut(0).next().fadeIn(0).end().appendTo(".fadeInOut");

}

$(".fadeInOut").mouseenter(function(){

    myVar = setInterval(change_div, 600);
  change_div();

});

$(".fadeInOut").mouseleave(function(){

  clearInterval(myVar);

});
</code>```

HTML

```<code><div class="fadeInOut">
    <div><img src="https://www.amideveloper.com/wp-content/themes/amideveloper/slide/slider-1.jpg"></div>
    <div><img src="https://www.amideveloper.com/wp-content/themes/amideveloper/slide/slider-2.jpg"></div>
    <div><img src="https://www.amideveloper.com/wp-content/themes/amideveloper/slide/slider-3.jpg"></div>
</div>
</code>```

CSS

```<code>.fadeInOut > div {
    position: absolute;
}
</code>```

here's a link to a jsfidlle:

https://jsfiddle.net/0ysg3r67/

any help would be appreciated

答:
```<code>var myVar;

$(".fadeInOut").mouseenter(function(){
  clearInterval(myVar);
  myVar = setInterval(change_div, 600);
  change_div();
});
</code>```

Something with your slide transitions is causing the mouseenter to retrigger, creating multiple intervals.  To safeguard against this, attempt to clear the interval before creating a new one.

As an alternative, instead of moving around slides, you can simply tag the one that is visible, and use that to know which slide should be shown next.  This appears to resolve the issue with Firefox triggering the mouseenter over and over.

var myVar;
var $slides = $('.fadeInOut > div');

$(".fadeInOut > div:not(.current)").hide();

function change_div() {
 var $current = $slides.filter('.current');
  var $next = ($current.next().length ? $current.next() : $slides.first());

  $current.fadeOut(0).removeClass('current');
  $next.addClass('current').fadeIn(0);
}

$(".fadeInOut").mouseenter(function(){
 console.log('start');

 myVar = setInterval(change_div, 600);
  change_div();

});

$(".fadeInOut").mouseleave(function(){
  console.log('stop');
  clearInterval(myVar);

});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.fadeInOut > div {
    position: absolute;
}</code>```

```

Body:
I'm using setInterval to create a diy slideshow that starts on mouseenter using this tutorial :
https://www.amideveloper.com/how-to-start-slideshow-on-hover-image-in-jquery/

It works fine, but I would like the slideshow to stop on mouseleave by using clearInterval.

I don't know what I'm doing wrong has my Interval is not cleared and the slideshow won't stop...

here is my code :

JQUERY

$(".fadeInOut > div:gt(0)").hide();

function change_div() {

  $(".fadeInOut > div:first").fadeOut(0).next().fadeIn(0).end().appendTo(".fadeInOut");

}

$(".fadeInOut").mouseenter(function(){

    myVar = setInterval(change_div, 600);
  change_div();

});

$(".fadeInOut").mouseleave(function(){

  clearInterval(myVar);

});

HTML

CSS

.fadeInOut > div {
    position: absolute;
}

here's a link to a jsfidlle:

https://jsfiddle.net/0ysg3r67/

any help would be appreciated

Body:
var myVar;

$(".fadeInOut").mouseenter(function(){
  clearInterval(myVar);
  myVar = setInterval(change_div, 600);
  change_div();
});

Something with your slide transitions is causing the mouseenter to retrigger, creating multiple intervals.  To safeguard against this, attempt to clear the interval before creating a new one.

As an alternative, instead of moving around slides, you can simply tag the one that is visible, and use that to know which slide should be shown next.  This appears to resolve the issue with Firefox triggering the mouseenter over and over.

var myVar;
var $slides = $('.fadeInOut > div');

$(".fadeInOut > div:not(.current)").hide();

function change_div() {
 var $current = $slides.filter('.current');
  var $next = ($current.next().length ? $current.next() : $slides.first());

  $current.fadeOut(0).removeClass('current');
  $next.addClass('current').fadeIn(0);
}

$(".fadeInOut").mouseenter(function(){
 console.log('start');

 myVar = setInterval(change_div, 600);
  change_div();

});

$(".fadeInOut").mouseleave(function(){
  console.log('stop');
  clearInterval(myVar);

});

.fadeInOut > div {
    position: absolute;
}

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="fadeInOut">
 <div class="current"><img src="https://www.amideveloper.com/wp-content/themes/amideveloper/slide/slider-1.jpg"></div>
 <div><img src="https://www.amideveloper.com/wp-content/themes/amideveloper/slide/slider-2.jpg"></div>
 <div><img src="https://www.amideveloper.com/wp-content/themes/amideveloper/slide/slider-3.jpg"></div>
</div>


问:
Are complex objects permitted inside a redux store?
I am working on a React app with Redux and I saw something unusual. We put a DOM element inside the store at one point. This makes problems with the Redux extension which will freeze when the action is called, but otherwise the app is acting well.

Our code look like this:

```<code>function theAction(domElement) { // We got domElement with getElementById
    return {
        type: "THE_ACTION",
        domElement
    };
}
</code>```

Then in our reducer, we simply put the DOM element inside the store:

```<code>function theReducer(state, action) {
    switch (action.type) {
    case "THE_ACTION":
        return {
            ...state,
            domElement: action.domElement,
        };
    }
}
</code>```

DOM elements are complex object with reference cycle and special properties, so I wasn't sure of the rules here. So am I breaking a precondition putting a DOM element inside an action and am I breaking a precondition putting a DOM element inside the store?

答: No, non-serializable objects are explicitly not allowed inside dispatched actions or the Redux store.

Body:
I am working on a React app with Redux and I saw something unusual. We put a DOM element inside the store at one point. This makes problems with the Redux extension which will freeze when the action is called, but otherwise the app is acting well.

Our code look like this:

function theAction(domElement) { // We got domElement with getElementById
    return {
        type: "THE_ACTION",
        domElement
    };
}

Then in our reducer, we simply put the DOM element inside the store:

function theReducer(state, action) {
    switch (action.type) {
    case "THE_ACTION":
        return {
            ...state,
            domElement: action.domElement,
        };
    }
}

DOM elements are complex object with reference cycle and special properties, so I wasn't sure of the rules here. So am I breaking a precondition putting a DOM element inside an action and am I breaking a precondition putting a DOM element inside the store?


问:
React update List item state as performant as possible
I am currently creating an React Application with an Editable Details list. My Issue is that I am not managing to update the list in a fast way. Specially Internet Explorer is struggling allot.

It would be to much to use my Application as example so I created a simplified concept in codesandbox:
https://codesandbox.io/s/bold-sanderson-of08y

For this Example I am just Rendering a lot of <input/> and let the parent container handle the state.

```<code>function App() {
   console.log('Render App')

   const [items, setItems] = useState(createItems())

   const handleChange = (value, index) => {
       const itemsCopy = [...items]
       itemsCopy[index] = value
       setItems(itemsCopy)
   }

   const handleSave = () => {
       //Send data to back-end etc...
       //webAPI.saveData(items)
   }

   return (
       <div>
           <button onClick={handleSave}>Save</button>
           <hr />
           {items.map((item, index) => {
               return (
                   <input
                       key={index}
                       value={item}
                       onChange={e => handleChange(e.target.value, index)}
                    />
             )
           })}
       </div>
   )
}
</code>```

This demo is a bit extreme because each key press will trigger an state update. But its fine for this example.

What I want to know is how to handle this situation without re-rendering the "App" component each time. I was thinking of moving the state to the Input component itself, but if I did that I would not be able to assess all data from the handleSave function. Or at least I don't know how this can be accomplished.

答:
You are right by needing to have the state in App component, don't think you should avoid it.

You can use react-window

which helps you with large lists (it does so by only rendering the items that are in or close to view)

Body:
I am currently creating an React Application with an Editable Details list. My Issue is that I am not managing to update the list in a fast way. Specially Internet Explorer is struggling allot.

It would be to much to use my Application as example so I created a simplified concept in codesandbox:
https://codesandbox.io/s/bold-sanderson-of08y

For this Example I am just Rendering a lot of <input/> and let the parent container handle the state.

function App() {
   console.log('Render App')

   const [items, setItems] = useState(createItems())

   const handleChange = (value, index) => {
       const itemsCopy = [...items]
       itemsCopy[index] = value
       setItems(itemsCopy)
   }

   const handleSave = () => {
       //Send data to back-end etc...
       //webAPI.saveData(items)
   }

   return (

           <button onClick={handleSave}>Save</button>

           {items.map((item, index) => {
               return (
                   <input
                       key={index}
                       value={item}
                       onChange={e => handleChange(e.target.value, index)}
                    />
             )
           })}

   )
}

This demo is a bit extreme because each key press will trigger an state update. But its fine for this example.

What I want to know is how to handle this situation without re-rendering the "App" component each time. I was thinking of moving the state to the Input component itself, but if I did that I would not be able to assess all data from the handleSave function. Or at least I don't know how this can be accomplished.


答: Try using the built-in preg_split() function: http://php.net/manual/en/function.preg-split.php</p>

Title: string split into lines php by pattern


问:
NodeJS TypeError: Cannot read property of undefined
so I just started using NodeJs still have a lot to learn but am loving it so far I ran into this problem I found an answer, but it's not what I want it's kinda weird, let me show some code and explain

So I got 2 files

File 1 > app.js (Main)

File 2 > UserEntity.js (Module)

app.js:

```<code>var uEntity = require('./UserEntity.js');

var hm = new uEntity.person();
console.log(hm.info.strUsername);
</code>```

UserEntity.js:

```<code>function User() {
    this.info = {
        'strUsername': 'Hashimoro'
    };
}

module.exports.person = User;
</code>```

I am creating a new UserEntity I want to access the info directly as you can see from the code

But it gives this error:

```<code>console.log(hm.info.strUsername);
                   ^

TypeError: Cannot read property 'strUsername' of undefined
    at Object.<anonymous> (D:\NodeLearn\Testing\app.js:4:20)
    at Module._compile (module.js:570:32)
    at Object.Module._extensions..js (module.js:579:10)
    at Module.load (module.js:487:32)
    at tryModuleLoad (module.js:446:12)
    at Function.Module._load (module.js:438:3)
    at Module.runMain (module.js:604:10)
    at run (bootstrap_node.js:394:7)
    at startup (bootstrap_node.js:149:9)
    at bootstrap_node.js:509:3
</code>```

If someone can give a fix and explain would be great

Thank you, seriously appreciate it

答:
In my case I have not added this JSON middleware</p>

```<code>app.use(express.json());
</code>```

Body:
so I just started using NodeJs still have a lot to learn but am loving it so far I ran into this problem I found an answer, but it's not what I want it's kinda weird, let me show some code and explain

So I got 2 files

File 1 > app.js (Main)

File 2 > UserEntity.js (Module)

app.js:

var uEntity = require('./UserEntity.js');

var hm = new uEntity.person();
console.log(hm.info.strUsername);

UserEntity.js:

function User() {
    this.info = {
        'strUsername': 'Hashimoro'
    };
}

module.exports.person = User;

I am creating a new UserEntity I want to access the info directly as you can see from the code

But it gives this error:

console.log(hm.info.strUsername);
                   ^

TypeError: Cannot read property 'strUsername' of undefined
    at Object.<anonymous> (D:\NodeLearn\Testing\app.js:4:20)
    at Module._compile (module.js:570:32)
    at Object.Module._extensions..js (module.js:579:10)
    at Module.load (module.js:487:32)
    at tryModuleLoad (module.js:446:12)
    at Function.Module._load (module.js:438:3)
    at Module.runMain (module.js:604:10)
    at run (bootstrap_node.js:394:7)
    at startup (bootstrap_node.js:149:9)
    at bootstrap_node.js:509:3

If someone can give a fix and explain would be great

Thank you, seriously appreciate it

Body:
In my case I have not added this JSON middleware

app.use(express.json());


问:
remove string and brackets if string contains specific string. Pandas
I'm trying to figure out how to remove string and brackets if a column have contains a certain string.

So in my column I can have two strings that contain brackets like this

```<code>col a
this is the text(text it is) and other information (COO: warning) some other information
</code>```

What I can do is remove all text and brackets. But how do I just remove the string and brackets that contains COO: ??

```<code>cork_ing['DS VALUE Check'] = cork_ing['DS_VALUE'].str.replace(r"\(.*?\)","")
</code>```

Can I modify the above code line just to remove and string with COO: ?

答:
You could target terms in parentheses which only also contain the text COO, e.g.

```<code>cork_ing['DS VALUE Check'] = cork_ing['DS_VALUE'].str.replace(r'\([^)]*COO.*?\)', '')
</code>```

Explanation of regex pattern:

```<code>\(     match literal (
[^)]*  then match zero or more non ) characters
COO    match 'COO'
.*?    match remaining content up until the first
\)     literal closing )
</code>```

Body:
I'm trying to figure out how to remove string and brackets if a column have contains a certain string.

So in my column I can have two strings that contain brackets like this

col a
this is the text(text it is) and other information (COO: warning) some other information

What I can do is remove all text and brackets. But how do I just remove the string and brackets that contains COO: ??

cork_ing['DS VALUE Check'] = cork_ing['DS_VALUE'].str.replace(r"\(.*?\)","")

Can I modify the above code line just to remove and string with COO: ?

Body:
You could target terms in parentheses which only also contain the text COO, e.g.

cork_ing['DS VALUE Check'] = cork_ing['DS_VALUE'].str.replace(r'\([^)]*COO.*?\)', '')

Explanation of regex pattern:

\(     match literal (
[^)]*  then match zero or more non ) characters
COO    match 'COO'
.*?    match remaining content up until the first
\)     literal closing )


问:
android: add line to each item in List View
I have created the simple list view with base adapter.Now I want to add the simple line after the each item in list view.can anyone please tell how to do it.

Thank you.

答:
Hi
  This done using the http://developer.android.com/reference/android/widget/ListView.html#attr_android:divider

Please not forget to set the android:deviderHeight otherwise it will not show.

Thank for support


问:
Why is my child SwiftUI view not updating?
I have a Swift ui view with a child witch gets values from a @State variable. When i update my @State variable the view rebuilds but the child stays the same.</p>

```<code>struct ContentView: View {
  @State var msg: String = ""
  var body: some View {
    VStack {
      Button(action: {
        self.msg = "Hallo World"
      }, label: { Text("Say Hallo")})

      ChildView(msg: msg).padding().background(Color.orange)
      Text(msg).padding().background(Color.green)
    }.frame(maxWidth: .infinity, maxHeight: .infinity)
  }
}

struct ChildView: View {
  @State var msg: String

  var body: some View {
    Text(msg)
  }
}
</code>```

答:
Use in it @Binding instead of @State. Modified complete snapshot provided below. Tested as-is & works with Xcode 11.2 / iOS 13.2.</p>

```<code>struct ContentView: View {
  @State var msg: String = ""
  var body: some View {
    VStack {
      Button(action: {
        self.msg = "Hallo World"
      }, label: { Text("Say Hallo")})

      ChildView(msg: $msg).padding().background(Color.orange)
      Text(msg).padding().background(Color.green)
    }.frame(maxWidth: .infinity, maxHeight: .infinity)
  }
}

struct ChildView: View {
  @Binding var msg: String

  var body: some View {
    Text(msg)
  }
}
</code>```

Body:
I have a Swift ui view with a child witch gets values from a @State variable. When i update my @State variable the view rebuilds but the child stays the same.

struct ContentView: View {
  @State var msg: String = ""
  var body: some View {
    VStack {
      Button(action: {
        self.msg = "Hallo World"
      }, label: { Text("Say Hallo")})

      ChildView(msg: msg).padding().background(Color.orange)
      Text(msg).padding().background(Color.green)
    }.frame(maxWidth: .infinity, maxHeight: .infinity)
  }
}

struct ChildView: View {
  @State var msg: String

  var body: some View {
    Text(msg)
  }
}

Body:
Use in it @Binding instead of @State. Modified complete snapshot provided below. Tested as-is & works with Xcode 11.2 / iOS 13.2.

struct ContentView: View {
  @State var msg: String = ""
  var body: some View {
    VStack {
      Button(action: {
        self.msg = "Hallo World"
      }, label: { Text("Say Hallo")})

      ChildView(msg: $msg).padding().background(Color.orange)
      Text(msg).padding().background(Color.green)
    }.frame(maxWidth: .infinity, maxHeight: .infinity)
  }
}

struct ChildView: View {
  @Binding var msg: String

  var body: some View {
    Text(msg)
  }
}


答:
```<code>cork_ing['DS VALUE Check'] = cork_ing['DS_VALUE'].apply(lambda string: string.replace("(","").replace(")","") if "COO" in string else string)
</code>```

Title: remove string and brackets if string contains specific string. Pandas


问:
How to make chrome devtools to recognise moment.js
I am working on ionic2 project. I have just start using moment.js but I have a weird issue.
I have installed in via npm: npm install moment -S.

Then I have used it in my code:

```<code>import moment from 'moment'
...
let x = moment()
debugger
</code>```

On the console I get this funny issue:

```<code>> x
< Moment {_isAMomentObject: true, _isUTC: false, _pf: {…}, _locale: Locale, _d: Wed Jun 27 2018 12:06:23, …}
> y = moment()
< VM770:1 Uncaught ReferenceError: moment is not defined
    at eval (eval at Phase (phase.ts:13), <anonymous>:1:1)
    at new Phase (phase.ts:13)
    at new Stage (stage.ts:10)
    at new HomePage (home.ts:39)
    at createClass (core.es5.js:10795)
    at createDirectiveInstance (core.es5.js:10621)
    at createViewNodes (core.es5.js:11971)
    at createRootView (core.es5.js:11876)
    at callWithDebugContext (core.es5.js:13007)
    at Object.debugCreateRootView [as createRootView] (core.es5.js:12468)
</code>```

Why can't I work with moment within the console?

答:
Could fetch it from browser console like this:

```<code>fetch('https://momentjs.com/downloads/moment.min.js')
    .then(response => response.text())
    .then(text => eval(text))
</code>```

Body:
I am working on ionic2 project. I have just start using moment.js but I have a weird issue.
I have installed in via npm: npm install moment -S.

Then I have used it in my code:

import moment from 'moment'
...
let x = moment()
debugger

On the console I get this funny issue:

> x
< Moment {_isAMomentObject: true, _isUTC: false, _pf: {…}, _locale: Locale, _d: Wed Jun 27 2018 12:06:23, …}
> y = moment()
< VM770:1 Uncaught ReferenceError: moment is not defined
    at eval (eval at Phase (phase.ts:13), <anonymous>:1:1)
    at new Phase (phase.ts:13)
    at new Stage (stage.ts:10)
    at new HomePage (home.ts:39)
    at createClass (core.es5.js:10795)
    at createDirectiveInstance (core.es5.js:10621)
    at createViewNodes (core.es5.js:11971)
    at createRootView (core.es5.js:11876)
    at callWithDebugContext (core.es5.js:13007)
    at Object.debugCreateRootView [as createRootView] (core.es5.js:12468)

Why can't I work with moment within the console?

Body:
Could fetch it from browser console like this:

fetch('https://momentjs.com/downloads/moment.min.js')
    .then(response => response.text())
    .then(text => eval(text))


问:
Sorting two arrays simultaneously
I'm learning and understanding Java now, and while practising with arrays I had a doubt. I wrote the following code as an example:

class example
{
    public static void main(String args[])
    {
        String a[] = new String[] {"Sam", "Claudia", "Josh", "Toby", "Donna"};
        int b[] = new int[] {1, 2, 3, 4, 5};

        for(int n=0;n<5;n++)
        {
            System.out.print (a[n] + "...");
            System.out.println (b[n]);
        }
        System.out.println (" ");

        java.util.Arrays.sort(a);

        for(int n=0;n<5;n++)
        {
            System.out.print (a[n] + "...");
            System.out.println (b[n]);
        }
    }
```

In a nutshell, this class created two arrays with five spaces each. It fills one with names of characters from the West Wing, and fills the other with numbering from one to five. We can say that the data in these two strings corresponds to each other.

Now, the program sorts the array with the names in it using Arrays.sort(). After printing the array again, you can see that while the names are now in alphabetical order, the numbers do not correspond anymore as the second array is unchanged.

How can I shuffle the contents of the second array to match the sort requirements of the first? The solution must also be flexible to allow for changes in the scope and size of the program. Please do not post any answers asking me to change my methodology with the arrays, or propose a more 'efficient' way of doing things. This is for educational purposed and I'd like a straight solution to the example code provided. Thanks in advance!

EDIT: I do NOT want to create an additional class, however I think some form of sorting through nested loops might be an option instead of Arrays.sort().

答:
```<code>   import java.util.*;

class mergeArrays2
{
  public static void main(String args[])
  {
     String a1[]={"Sam", "Claudia", "Josh", "Toby", "Donna"};
     Integer a2[]={11, 2, 31, 24, 5};

     ArrayList ar1=new ArrayList(Arrays.asList(a1));

     Collections.sort(ar1);

     ArrayList ar2=new ArrayList(Arrays.asList(a2));

     Collections.sort(ar2);

     System.out.println("array list"+ar1+ " "+ar2);
  }

}
</code>```

Title: Sorting two arrays simultaneously

Body:
I'm learning and understanding Java now, and while practising with arrays I had a doubt. I wrote the following code as an example:

class example
{
    public static void main(String args[])
    {
        String a[] = new String[] {"Sam", "Claudia", "Josh", "Toby", "Donna"};
        int b[] = new int[] {1, 2, 3, 4, 5};

        for(int n=0;n<5;n++)
        {
            System.out.print (a[n] + "...");
            System.out.println (b[n]);
        }
        System.out.println (" ");

        java.util.Arrays.sort(a);

        for(int n=0;n<5;n++)
        {
            System.out.print (a[n] + "...");
            System.out.println (b[n]);
        }
    }

In a nutshell, this class created two arrays with five spaces each. It fills one with names of characters from the West Wing, and fills the other with numbering from one to five. We can say that the data in these two strings corresponds to each other.

Now, the program sorts the array with the names in it using Arrays.sort(). After printing the array again, you can see that while the names are now in alphabetical order, the numbers do not correspond anymore as the second array is unchanged.

How can I shuffle the contents of the second array to match the sort requirements of the first? The solution must also be flexible to allow for changes in the scope and size of the program. Please do not post any answers asking me to change my methodology with the arrays, or propose a more 'efficient' way of doing things. This is for educational purposed and I'd like a straight solution to the example code provided. Thanks in advance!

EDIT: I do NOT want to create an additional class, however I think some form of sorting through nested loops might be an option instead of Arrays.sort().


问:
How to take Multiple values input(with different types and separated with comma) from user in java
I want to accept multiple values from user like productName,Price,gstAmount like this:

```<code>sample input:2 //System.out.println("enter no of products");
mobile,2356,15
watch,200,10
</code>```

After this calculate the item with minimum price

```<code>sample output:watch
</code>```

答: You can use BufferedReader or Scanner class to read from console. After which you you can sort to get the lowest priced item.</p>

Body:
I want to accept multiple values from user like productName,Price,gstAmount like this:

sample input:2 //System.out.println("enter no of products");
mobile,2356,15
watch,200,10

After this calculate the item with minimum price

sample output:watch


问:
Typescript bundling with Rollup and rollup-plugin-typescript2 gone bad
I'm trying to extract small part of monorepo to web client library and running into some unexpected hurdles, in here.
So, quite straight forward rollup config, like this:

```<code>import resolve from "rollup-plugin-node-resolve";
import typescript from "rollup-plugin-typescript2";
import sourceMaps from 'rollup-plugin-sourcemaps';

export default {
    input: "../main.ts",
    output: {
        file: './bundle/rollup-bundle.js',
        format: 'iife',
        name: 'WebClient',
        sourcemap: true
    },
    plugins: [
        typescript(),
        resolve({browser: true, mainFields: ['module']}),
        sourceMaps(),
    ]
};
</code>```

Produces:

../main.ts → ./bundle/rollup-bundle.js...
[!] Error: Unexpected token (Note that you need plugins to import files that are not JavaScript)
..\main.ts (3:32)
1: [...]
2:
3: export const createClient = (url: string) => new ClientImpl([...]);
                                   ^
Error: Unexpected token (Note that you need plugins to import files that are not JavaScript)
```

It just looks like rollup-plugin-typescript2 doesn't do it's job of transpiling typescript and that just seems way too basic to not to work. I'm confused!

Thanks in advance!

答:
This is probably caused by typescript2 and node-resolve being called in the wrong order:

[@rollup/plugin-node-resolve] Must be before rollup-plugin-typescript2 in the plugin list, especially when browser: true option is used

(from rollup-plugin-typescript2's documentation)

Update

The main issue turned out to be the positioning of some source files in higher folders with respect to the tsconfig root. By default tsconfig excluded them from the compilation:

If the "files" and "include" are both left unspecified, the compiler defaults to including all TypeScript (.ts, .d.ts and .tsx) files in the containing directory and subdirectories

(tsconfig docs)

Body:
I'm trying to extract small part of monorepo to web client library and running into some unexpected hurdles, in here.
So, quite straight forward rollup config, like this:

import resolve from "rollup-plugin-node-resolve";
import typescript from "rollup-plugin-typescript2";
import sourceMaps from 'rollup-plugin-sourcemaps';

export default {
    input: "../main.ts",
    output: {
        file: './bundle/rollup-bundle.js',
        format: 'iife',
        name: 'WebClient',
        sourcemap: true
    },
    plugins: [
        typescript(),
        resolve({browser: true, mainFields: ['module']}),
        sourceMaps(),
    ]
};

Produces:

../main.ts → ./bundle/rollup-bundle.js...
[!] Error: Unexpected token (Note that you need plugins to import files that are not JavaScript)
..\main.ts (3:32)
1: [...]
2:
3: export const createClient = (url: string) => new ClientImpl([...]);
                                   ^
Error: Unexpected token (Note that you need plugins to import files that are not JavaScript)

It just looks like rollup-plugin-typescript2 doesn't do it's job of transpiling typescript and that just seems way too basic to not to work. I'm confused!

Thanks in advance!


问:
How to create a table by using the variables of a column from a dataset in R?
I have a data.frame which is like :

```<code>data.frame("Hhold Id" = c(173,174,174,175,176,176,176), "Individuals" = c(1,1,2,1,1,2,3))
</code>```

Individuals indicate the nth individuals for that household. Namely, for example Hhold 173 includes one individual while Hhold 176 composed by three individuals. I would like to get a new table which indicates how many individuals exist for each household without duplicating the Hhold Id. Such as :

```<code>data.frame("Hhold Id" = c(173,174,175,176), "Individuals" = c(1,2,1,3))
</code>```

I have tried unique and group by functions, but could not get a solution. Thanks in advance.

答:
Using data.table library</p>

```<code>data.table(data)[,list(Individuals=max(Individuals)),list("Hhold Id"=Hhold.Id)]
</code>```

Body:
I have a data.frame which is like :

data.frame("Hhold Id" = c(173,174,174,175,176,176,176), "Individuals" = c(1,1,2,1,1,2,3))

Individuals indicate the nth individuals for that household. Namely, for example Hhold 173 includes one individual while Hhold 176 composed by three individuals. I would like to get a new table which indicates how many individuals exist for each household without duplicating the Hhold Id. Such as :

data.frame("Hhold Id" = c(173,174,175,176), "Individuals" = c(1,2,1,3))

I have tried unique and group by functions, but could not get a solution. Thanks in advance.

Body:
Using data.table library

data.table(data)[,list(Individuals=max(Individuals)),list("Hhold Id"=Hhold.Id)]


问:
import proto in another library
I am developing a c++ library B which depends on another library A.
The two libray both use protobuf to define message objects

For example,

// A.proto in library `A
package libA;
message ObjA {...}
```

<p>And I want to use it in library <code>B</code></p>

<pre class="lang-js prettyprint-override"><code>// B.proto in library `B`
import A.proto  // ??? is this right ???
message ObjB {
    ObjA obj_a=1;
}
</code>```

If I just copy A.proto into current library B, duplicated classes for ObjA will be created.

But if I didn't copy A.proto, how could I use message ObjA in message ObjB ?

答:
What you can do is add the search path for protoc to the directory in which A.proto is located:

protoc -I=DIR_WITH_A B.proto
```

<p>Also you can write the relative dir with the import statement in B.proto:</p>

<pre class="lang-proto prettyprint-override"><code>// B.proto in library `B`
import "SOME_DIR/A.proto";
message ObjB {
    ObjA obj_a=1;
}
</code>```

Title: import proto in another library

Body:
I am developing a c++ library B which depends on another library A.
The two libray both use protobuf to define message objects

For example,

// A.proto in library `A
package libA;
message ObjA {...}

And I want to use it in library B

// B.proto in library `B`
import A.proto  // ??? is this right ???
message ObjB {
    ObjA obj_a=1;
}

If I just copy A.proto into current library B, duplicated classes for ObjA will be created.

But if I didn't copy A.proto, how could I use message ObjA in message ObjB ?

Body:
What you can do is add the search path for protoc to the directory in which A.proto is located:

protoc -I=DIR_WITH_A B.proto

Also you can write the relative dir with the import statement in B.proto:

// B.proto in library `B`
import "SOME_DIR/A.proto";
message ObjB {
    ObjA obj_a=1;
}