问:
Dynamic column resizing in .Rprofile
I'd like to put the following in my .Rprofile:

```<code># auto width adjustment
.adjustWidth <- function(...){
   options(width=Sys.getenv("COLUMNS"))
   TRUE
}
.adjustWidthCallBack <- addTaskCallback(.adjustWidth)
</code>```

This will dynamically resize the max columns in my R session to be the width of the window.  This works in an interactive session, but when doing something like R CMD INSTALL or a batch session I always get:

```<code>Error in options(width = Sys.getenv("COLUMNS")) :
  invalid 'width' parameter, allowed 10...10000
Execution halted
</code>```

How can I fix this? I assume the issue is that Sys.getenv("COLUMNS") is failing somehow? Is there some if() statement I could do that lets me detect if I run in batch or not? The original auto width adjustment code isn't mine, I found it somewhere else online.

答:
The interactive() check is VERY IMPORTANT: otherwise it doesn't work with update.packages()...</p>

```<code>> update.packages(lib.loc="...",ask=FALSE,oldPkgs="httpuv")
trying URL 'http://cran.univ-lyon1.fr/src/contrib/httpuv_1.5.1.tar.gz'
...
stty: 'standard input': Inappropriate ioctl for device
Error in options(width = as.integer(howWide)) :
  invalid 'width' parameter, allowed 10...10000
Calls: updatePrompt -> options
Execution halted
...
</code>```

Title: Dynamic column resizing in .Rprofile

Body:
I'd like to put the following in my .Rprofile:

# auto width adjustment
.adjustWidth <- function(...){
   options(width=Sys.getenv("COLUMNS"))
   TRUE
}
.adjustWidthCallBack <- addTaskCallback(.adjustWidth)

This will dynamically resize the max columns in my R session to be the width of the window.  This works in an interactive session, but when doing something like R CMD INSTALL or a batch session I always get:

Error in options(width = Sys.getenv("COLUMNS")) :
  invalid 'width' parameter, allowed 10...10000
Execution halted

How can I fix this? I assume the issue is that Sys.getenv("COLUMNS") is failing somehow? Is there some if() statement I could do that lets me detect if I run in batch or not? The original auto width adjustment code isn't mine, I found it somewhere else online.

Body:
The interactive() check is VERY IMPORTANT: otherwise it doesn't work with update.packages()...

> update.packages(lib.loc="...",ask=FALSE,oldPkgs="httpuv")
trying URL 'http://cran.univ-lyon1.fr/src/contrib/httpuv_1.5.1.tar.gz'
...
stty: 'standard input': Inappropriate ioctl for device
Error in options(width = as.integer(howWide)) :
  invalid 'width' parameter, allowed 10...10000
Calls: updatePrompt -> options
Execution halted
...


来源: stackexchange

问:
How to speed up UI test cases in Xcode?
Since Xcode 7 we have a nice API for UI testing.
Mostly I'm satisfied with it. The only concern is related to the speed.

In the beginning an ordinary UI test case (about 15 actions) ran approximately 25 seconds. Then I mocked networking completely. Now it takes 20 seconds. Considering the fact that the time is taken only by animations and a launch time (1 second or even less), I assume, there must be a way to speed it up.

答:
I decrease my UITests time in 30%, follow all steps:

When you run your app, add the argument:

```<code>let app = XCUIApplication()

override func setUp() {
    super.setUp()

    continueAfterFailure = false
    app.launchArguments += ["--Reset"]
    app.launch()
}
</code>```

Now, in your AppDelegate add:

```<code>func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
    setStateForUITesting()
}

static var isUITestingEnabled: Bool {
    get {
        return ProcessInfo.processInfo.arguments.contains("--Reset")
    }
}

private func setStateForUITesting() {
    if AppDelegate.isUITestingEnabled {
        // If you need reset your app to clear state
        UserDefaults.standard.removePersistentDomain(forName: Bundle.main.bundleIdentifier!)

        // To speed up your tests
        UIApplication.shared.keyWindow?.layer.speed = 2
        UIView.setAnimationsEnabled(false)
    }
}

</code>```

In your code, to verify if is in test mode, you can use:

```<code>if AppDelegate.isUITestingEnabled {
    print("Test Mode")
}

</code>```

Additionally, to can wait while the element load I created this extension:

```<code>import XCTest

extension XCUIElement {
    func tap(wait: Int, test: XCTestCase) {
        if !isHittable {
            test.expectation(for: NSPredicate(format: "hittable == true"), evaluatedWith: self, handler: nil);
            test.waitForExpectations(timeout: TimeInterval(wait), handler: nil)
        }
        tap()
    }
}
</code>```

Use like this:

```<code>app.buttons["start"].tap(wait: 20, test: self)
</code>```

ContentLicense: CC BY-SA 3.0

Title: How to speed up UI test cases in Xcode?

Body:
I decrease my UITests time in 30%, follow all steps:

When you run your app, add the argument:

let app = XCUIApplication()

override func setUp() {
    super.setUp()

    continueAfterFailure = false
    app.launchArguments += ["--Reset"]
    app.launch()
}

Now, in your AppDelegate add:

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
    setStateForUITesting()
}

static var isUITestingEnabled: Bool {
    get {
        return ProcessInfo.processInfo.arguments.contains("--Reset")
    }
}

private func setStateForUITesting() {
    if AppDelegate.isUITestingEnabled {
        // If you need reset your app to clear state
        UserDefaults.standard.removePersistentDomain(forName: Bundle.main.bundleIdentifier!)

        // To speed up your tests
        UIApplication.shared.keyWindow?.layer.speed = 2
        UIView.setAnimationsEnabled(false)
    }
}

In your code, to verify if is in test mode, you can use:

if AppDelegate.isUITestingEnabled {
    print("Test Mode")
}

Additionally, to can wait while the element load I created this extension:

import XCTest

extension XCUIElement {
    func tap(wait: Int, test: XCTestCase) {
        if !isHittable {
            test.expectation(for: NSPredicate(format: "hittable == true"), evaluatedWith: self, handler: nil);
            test.waitForExpectations(timeout: TimeInterval(wait), handler: nil)
        }
        tap()
    }
}

Use like this:

app.buttons["start"].tap(wait: 20, test: self)

ContentLicense: CC BY-SA 4.0


问:
Athena Presto parse_duration not registered
I have an Athena DB, and I'm trying to use parse_duration Presto function. For some reason it doesn't work (says the function is not registered).

Did someone had the same problem and manage to solve it? Or have an idea for other function that I can use?

parse_duration function exists in Presto since May 2017, so I assume it should be supported in Athena already, isn't it?

Thanks!

答:
I needed parse_duration for my query in Athena, but my particular use case was to parse a number of seconds to an interval, for which I did:

```<code>SELECT (interval '1' second) * number_of_seconds AS duration_in_seconds
</code>```

While this does not directly exactly answer the question, it may be useful to people that arrive to this question with my same issue.

Body:
I needed parse_duration for my query in Athena, but my particular use case was to parse a number of seconds to an interval, for which I did:

SELECT (interval '1' second) * number_of_seconds AS duration_in_seconds

While this does not directly exactly answer the question, it may be useful to people that arrive to this question with my same issue.


问:
How do I make a state getter reactive when a dispatched action sets a state object with Vue.set?
I have a button that’s set to update the a store object using Vue.set but the getter for that same piece of data in a different component isn’t reactive until I change the state using a different component method.

The state object in question is set up as a hash that's keyed by UUID's. The object is generated and then added to the state object with Vue.set

The button is set to dispatch an action, which I see it going through immedietely in the devtool, that does this:

```<code>mutations: {
  COMPLETE_STEP(state, uuid) {
    let chat = state.chatStates[uuid];
    let step = chat.currentStep;

    Vue.set(chat.data[step], "complete", true);
  }
},

actions: {
  completeStep({ commit }, uuid) {
    commit("COMPLETE_STEP", uuid);
  }
},
</code>```

Now, when I want to grab that data, I have a getter that grabs that data. This doesn't run until I do something else that causes a re-render:

```<code>getters: {
  getChatStepComplete: state => (uuid, step) => {
    let chatState = state.chatStates[uuid];

    return chatState.data[step].complete;
  },
}
</code>```

I want the getter to show the updated change right away instead of waiting to update on a different re-render. How do I make that happen?

答: Figured out my issue: I wasn’t creating the data array when I first create and add chat to the state. Once I started initializing it to an empty array, it’s started being reactive.</p>

Body:
I have a button that’s set to update the a store object using Vue.set but the getter for that same piece of data in a different component isn’t reactive until I change the state using a different component method.

The state object in question is set up as a hash that's keyed by UUID's. The object is generated and then added to the state object with Vue.set

The button is set to dispatch an action, which I see it going through immedietely in the devtool, that does this:

mutations: {
  COMPLETE_STEP(state, uuid) {
    let chat = state.chatStates[uuid];
    let step = chat.currentStep;

    Vue.set(chat.data[step], "complete", true);
  }
},

actions: {
  completeStep({ commit }, uuid) {
    commit("COMPLETE_STEP", uuid);
  }
},

Now, when I want to grab that data, I have a getter that grabs that data. This doesn't run until I do something else that causes a re-render:

getters: {
  getChatStepComplete: state => (uuid, step) => {
    let chatState = state.chatStates[uuid];

    return chatState.data[step].complete;
  },
}

I want the getter to show the updated change right away instead of waiting to update on a different re-render. How do I make that happen?


问:
How to get the URI scheme of any app for AppLinks/universal linking?
I need to open a third-party app from my react native mobile app. I understand that this is called universal linking on iOS and AppLink on Android.

I have done a lot of research for this, and I have been able to set up a link to the third party app on the app store. Now I just need to get my app to open up the app if the user has it installed. That requires the URI scheme of the other app, though.

My question is, how do I get the URI scheme to this third party app? Rather, how do I get the URI scheme of any app? I know the URI scheme of the twitter app is 'twitter://app', but the app I am trying to link to is way more niche than twitter or other popular apps, so there is no help for this sort of thing online.

Any tips?

答:
Maybe it is worth to start with some background:
There are various ways to deep link into an app, and it depends on the platform (iOS\Android\WindowsPhone...) and its version.

On iOS, up until version 9, the way to open an app was by using URI schemes, e.g. the one you added above: twitter://app. Each app declares the scheme that should be used. Therefore in order to deep link into the app you wish to open, you'll need to use the scheme that it declared. This is the same for Android until version 6.

Starting iOS9+, Apple introduced Universal Links as the method for deep linking. Here's some information: https://developer.apple.com/ios/universal-links/

In these versions, URI schemes won't longer work when using Safari browser (which is the iOS default browser) if the app is not installed. If the app is installed, however, URI schemes should allow opening the app, if everything is configured successfully. In Android there's a similar method called "AppLinks".

Having said this, the above information is for setting deep link for your app. I do not think that it is a common use case to open a third party app from your app - deep links are configured and used by the app owner (e.g. for publishing his\her app to engage users).


问:
Html editorfor is not posting back data when name attribute added
I am trying to remove google autocomplete(google showing previously entered data) on an HTML editorfor, but I have not yet found the correct solution.

I am creating an asp.Net Mvc5 app.
One solution I have seen is to add a name using the Guid generator.
I have tried adding this to Html editorFor which helped remove googles suggestions, however, any data that I now enter into the HTML editorfor is not saved when I post the data back to the database.
I tried also adding autocomplete = "new- password", to the HTML editor for but it has not helped to remove google suggestions

What is wrong with the following?

@Html.EditorFor(model => model.renovationDetail.Notes, new {
  htmlAttributes = new { @class = "form-control", Name =
  Guid.NewGuid().ToString(), autocomplete = "new- password" } })

答:
Try it.

@Html.EditorFor(model => model.renovationDetail.Notes, new {
  htmlAttributes = new { @class = "form-control", Name =
  Guid.NewGuid().ToString(), autocomplete = "off" } })

If it is not working then You can disable it via Javascript. Try it

```<code>$(document).ready(function() {
    $("input:text,form").attr("autocomplete","off");
})
</code>```

Body:
Try it.

@Html.EditorFor(model => model.renovationDetail.Notes, new {
  htmlAttributes = new { @class = "form-control", Name =
  Guid.NewGuid().ToString(), autocomplete = "off" } })

If it is not working then You can disable it via Javascript. Try it

$(document).ready(function() {
    $("input:text,form").attr("autocomplete","off");
})


问:
How to implement onclick in ResultCard and swap the div with another component
I want to display the details of what's user clicks in the ResultCard.

I want to replace the divs contents (currently displayed results) with rendered html based on the result found in my elastic search cluster(res) when user click the url in the resultcard.

I tried adding onclick properties but nothing happens. Reactivesearch documentation don't list this attribute.

Of course, I could pass argument in the url properties of ResultCard and redirect user to another page but page would be reloaded completely (with the menus defined in index.js and the footer)

I think creating parent component with state mirroring the currently displayed children component in the div is the way to go.

But, how to run a javascript for setting the state when user click in the resultcard?

```<code>
import React, { Component } from 'react';
import { ReactiveBase, CategorySearch, SingleRange, ResultCard } from '@appbaseio/reactivesearch';

class App extends Component {
  render() {
    return (
        <ReactiveBase
        app="artists"
        url="https://admin:xxxxxxx@node1.searchevolution.com:9200"
        type="_doc">
          <div style={{ display: "flex", "flexDirection": "row" }}>
            <div style={{ display: "flex", "flexDirection": "column", "width": "40%" }}>
              <CategorySearch
                componentId="searchbox"
                dataField="nom"
                categoryField="occupations.keyword"
                type="artists"
                placeholder="Search for Artists, Painter, Sculptor, Photographs"
                style={{
                  padding: "5px",
                  "marginTop": "10px"
                }}
              />

            </div>
            <ResultCard
              componentId="result"
              dataField="nom"
              title="Results"
              from={0}
              size={6}
              pagination={true}
              onclick="alert('Message à afficher');"
              react={{
                and: ["searchbox"]
              }}
              onData={(res) => {
                return {
                  image: "data:image/png;base64,iVBORw0KGgoA",
                  title: res.occupations,
                  description: res.nom,
                  url: "/details/" + res
                }
              }}
              style={{
                "width": "60%",
                "textAlign": "center"
              }}
            />
          </div>
        </ReactiveBase>
    );
  }
}

export default App;

</code>```

Expected result is to change the div content with the rendered html from another component (not still coded).

答:
finally got it working by using the base component ReactiveList instead ReactiveCard.

ReactiveCard onData callback function is an object with image, title, description and url fields. No way, to return something else. No way to use onClick property.

So, better use the base component and do some html and css myself

```<code>
import React, { Component } from 'react';
import { ReactiveBase, CategorySearch, SingleRange, ResultCard, ReactiveList} from '@appbaseio/reactivesearch';

class App extends Component {
    constructor(props) {
        super(props);
        this.state = {
            showResultCard : true,
        };

    }

  handleClick = () =>  {
      this.state.showResultCard ?
    this.setState({ showResultCard: false }) : this.setState({ showResultCard: true });
  }
    render() {
        return (
        <ReactiveBase
        app="artists"
        url="https://admin:xxxxxxxxxx@node1.searchevolution.com:9200"
        type="_doc">
         {this.state.showResultCard ? (
          <div style={{ display: "flex", "flexDirection": "row" }}>
            <div style={{ display: "flex", "flexDirection": "column", "width": "40%" }}>
              <CategorySearch
                componentId="searchbox"
                dataField="nom"
                categoryField="occupations.keyword"
                type="artists"
                placeholder="Search for Artists, Painter, Sculptor, Photographs"
                style={{
                  padding: "5px",
                  "marginTop": "10px"
                }}
              />

            </div>

                 <ReactiveList
                            componentId="result"
                            dataField="nom"
                            className="result-list-container"
                            size={5}
                            onData={(res) => <div>{res.nom}<button onClick={this.handleClick}>tttt</button></div>}
                            pagination
                            URLParams
                            react={{
                                and: ['searchbox'],
                            }}
                />
          </div> ) : (<button onClick={this.handleClick}>back</button>)}
        </ReactiveBase>
        );
    }

}

export default App;

</code>```

Body:
I want to display the details of what's user clicks in the ResultCard.

I want to replace the divs contents (currently displayed results) with rendered html based on the result found in my elastic search cluster(res) when user click the url in the resultcard.

I tried adding onclick properties but nothing happens. Reactivesearch documentation don't list this attribute.

Of course, I could pass argument in the url properties of ResultCard and redirect user to another page but page would be reloaded completely (with the menus defined in index.js and the footer)

I think creating parent component with state mirroring the currently displayed children component in the div is the way to go.

But, how to run a javascript for setting the state when user click in the resultcard?

import React, { Component } from 'react';
import { ReactiveBase, CategorySearch, SingleRange, ResultCard } from '@appbaseio/reactivesearch';

class App extends Component {
  render() {
    return (
        <ReactiveBase
        app="artists"
        url="https://admin:xxxxxxx@node1.searchevolution.com:9200"
        type="_doc">

              <CategorySearch
                componentId="searchbox"
                dataField="nom"
                categoryField="occupations.keyword"
                type="artists"
                placeholder="Search for Artists, Painter, Sculptor, Photographs"
                style={{
                  padding: "5px",
                  "marginTop": "10px"
                }}
              />

            <ResultCard
              componentId="result"
              dataField="nom"
              title="Results"
              from={0}
              size={6}
              pagination={true}
              onclick="alert('Message à afficher');"
              react={{
                and: ["searchbox"]
              }}
              onData={(res) => {
                return {
                  image: "data:image/png;base64,iVBORw0KGgoA",
                  title: res.occupations,
                  description: res.nom,
                  url: "/details/" + res
                }
              }}
              style={{
                "width": "60%",
                "textAlign": "center"
              }}
            />

        </ReactiveBase>
    );
  }
}

export default App;

Expected result is to change the div content with the rendered html from another component (not still coded).

Body:
finally got it working by using the base component ReactiveList instead ReactiveCard.

ReactiveCard onData callback function is an object with image, title, description and url fields. No way, to return something else. No way to use onClick property.

So, better use the base component and do some html and css myself

import React, { Component } from 'react';
import { ReactiveBase, CategorySearch, SingleRange, ResultCard, ReactiveList} from '@appbaseio/reactivesearch';

class App extends Component {
    constructor(props) {
        super(props);
        this.state = {
            showResultCard : true,
        };

    }

  handleClick = () =>  {
      this.state.showResultCard ?
    this.setState({ showResultCard: false }) : this.setState({ showResultCard: true });
  }
    render() {
        return (
        <ReactiveBase
        app="artists"
        url="https://admin:xxxxxxxxxx@node1.searchevolution.com:9200"
        type="_doc">
         {this.state.showResultCard ? (
          <div style={{ display: "flex", "flexDirection": "row" }}>
            <div style={{ display: "flex", "flexDirection": "column", "width": "40%" }}>
              <CategorySearch
                componentId="searchbox"
                dataField="nom"
                categoryField="occupations.keyword"
                type="artists"
                placeholder="Search for Artists, Painter, Sculptor, Photographs"
                style={{
                  padding: "5px",
                  "marginTop": "10px"
                }}
              />

            </div>

                 <ReactiveList
                            componentId="result"
                            dataField="nom"
                            className="result-list-container"
                            size={5}
                            onData={(res) => <div>{res.nom}<button onClick={this.handleClick}>tttt</button></div>}
                            pagination
                            URLParams
                            react={{
                                and: ['searchbox'],
                            }}
                />
          </div> ) : (<button onClick={this.handleClick}>back</button>)}
        </ReactiveBase>
        );
    }

}

export default App;


问:
When I click on the button the hidden content doesn't show, why is this?
I am trying create a read more read less button. My content that is hidden is in a span tag. I used some javascript to make this work. Currently, when I click on the button nothing happens. My goal is to create a news section that shows more news when you click on the button.

This was working for me before, I used the exact same code and just merged it with some other code and it stopped working.

     $(document).ready(function () {

 var windowHeight = window.innerHeight;

 var navOpen = false;
 var onCloseBtn = false;
 var onAccordian = false;

 $("#hamburger").mouseover(function(){
  if(!navOpen){
   openMenu();
  }
  onCloseBtn = true;
 });

 $("#hamburger").mouseout(function(){
  onCloseBtn = false;
 });

 $("#hamburger").click(function(){
  toggleNav();
  console.log("clickedHam");
 });

 $("#navMenu").mouseover(function(){
  if(!navOpen && !onCloseBtn){
   keepOpen();
  }
 });

 $("#activeSpace").mouseleave(function(){
   console.log("navMenu Mouseout");
   closeMenu();
 });

 function toggleNav(){
  if(navOpen){
   closeMenu();

  } else {
   openMenu();
  }
 }
 function keepOpen(){
  console.log("keepOpen");
  navOpen = true;
  $('#hamburger').html('×');
  $('#hamburger').css("color","black");
  $("#navMenu").css("visibility","visible");
  $("#navMenu").css("height","auto");
  $("#navMenu").css("max-height", windowHeight);
 }

 function openMenu(){
  console.log("open");
  navOpen = true;
  $('#hamburger').html('×');
  $('#hamburger').css("color","black");
  $("#navMenu").css("visibility","visible");
  $("#navMenu").css("max-height", "250px"); ///change this depending on the max
 }

 function closeMenu(){
  closePanels();
  navOpen = false;
  console.log("close")
  $('#hamburger').html('☰');
  $('#hamburger').css("color","white");
  $("#navMenu").css("max-height", "0");
  $("#navMenu").css("visibility","hidden");
 }

 $(document).on('scroll', function() {
  if($(this).scrollTop()>=$('#changeNavColor').position().top - 40 && !navOpen){
   $(hamburger).css("color","black");
  }
  if($(this).scrollTop()<$('#changeNavColor').position().top - 40 && !navOpen){
   $(hamburger).css("color","white");
  }
 });

 var acc = document.getElementsByClassName("mobile-accordian");
 var i;

 for (i = 0; i < acc.length; i++) {
  acc[i].addEventListener("click", function() {
   //this.classList.toggle("active");
   $("#navMenu").css("height","auto");
   $("#navMenu").css("max-height", windowHeight);

   var panel = this.nextElementSibling;
   if (panel.style.maxHeight) {
    panel.style.maxHeight = null;
   } else {
     panel.style.maxHeight = panel.scrollHeight + "px";
   }
  });
 }

 function closePanels() {
  var panels = document.getElementsByClassName("mobile-accordian-panel");
  var j;

  for (j = 0; j < panels.length; j++){
   panels[j].style.maxHeight = null;
  }
 }

function toggleNewsButton() {
  var moreText = document.getElementById("more");
  var btnText = document.getElementById("myBtn");

  if (!moreText.style.display || moreText.style.display === "none") {
    btnText.innerHTML = "Read less";
    moreText.style.display = "block";
  } else {
    btnText.innerHTML = "Read more";
    moreText.style.display = "none";
  }
}

});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>     html, body{
  width: 100%;
  height: 100%;
  font-family: 'Roboto', sans-serif;
 }

 h1{
  font-size: 3em;
 }
 h2{
  font-size: 1.5em;
 }

 h3{
  font-size: 0.75em;
  font-weight:400;
  text-transform: uppercase;
 }

 .FullsizeImg{
  background-repeat: no-repeat;
  background-size: 30%;
  background-position: right;

 }
 #more {
   display: none;
 }

 #myBtn {
   color: black;
   background: #fff;
   border: 1px solid black;
   font-size: 17px;
   padding: 7px 12px;
   font-weight: normal;
   margin: 6px 0;
   margin-right: 12px;
 }

 .centerButton {
   text-align: center;
 }

 #myBtn:hover,
 #myBtn:active {
   background: black;
   color: white;
 }

 .allStories{
  margin-left:20px;
  margin-right:20px;
 }

 #hamburger{
  z-index: 11;
  display: block;
  visibility: visible;
  position: fixed;
  top: 10px;
  left: 10px;
  color: white;
  transition: all 0.25 ease;
 }

 #closeBtn{
  display:block;
  position:fixed;
  top:10px;
  left:10px;
 }

 #navMenu{
  z-index: 10;
  display: block;
  overflow:hidden;
  position: fixed;
  top: 0;
  left: 0;
  color: black;
  background-color: white;
  box-shadow: 0 0 8px rgba(33,33,33,.6);
  max-height: 0;
  width: 100%;
  -webkit-transition: 1s ease;
  -moz-transition: 1s ease;
  -o-transition: 1s ease;
  -ms-transition: 1s ease;
  transition: 1s ease;
  visibility: hidden;
 }

 .nav ul {
  list-style-type: none;
  margin: 0;
  padding: 0;
 }

 .nav ul li {
  color: grey;
  font-size: 14px;
  font-weight: regular;
  font-family: inherit;
  padding: 5px 0px 5px 0px;
  cursor: pointer;
  transition: .5s ease;
  -webkit-transition: .5s ease;
  -moz-transition: .5s ease;
 }

 .nav li:hover {
  color: lightgrey;
  font-weight: bold;
  transition: .5s ease;
  -webkit-transition: .5s ease;
  -moz-transition: .5s ease;
 }

 .mainMargins{
  margin-left: 10%;
  margin-right: 10%;
 }

 .smallSpacer{
  height: 25px;
 }

 .bigSpacer{
  height: 100px;
 }

 .txtAlignRight{

 }

 .AlwaysFullScreen{
  width: 100%;
  height: 100%;
 }

 .fullScreen{
  width: 100%;
  height: 100%;
 }

 .withBGImg{
  background-repeat: no-repeat;
  background-size: cover;
  background-position: center;
 }

 .jumbo-title{
  font-weight: bold;
  letter-spacing: 0.02em;
 }

 .jumbo-caption{
  font-weight: 300;
  font-size:
 }

 .jumbo-container{
  color: white;
 }

 .verticalCentreParent{
  -webkit-transform-style: preserve-3d;
  -moz-transform-style: preserve-3d;
  transform-style: preserve-3d;
 }

 .verticalCentreChild{
  position: relative;
  top: 50%;
  transform: translateY(-50%);
 }

 .content-verticalCentreParent{
  -webkit-transform-style: preserve-3d;
  -moz-transform-style: preserve-3d;
  transform-style: preserve-3d;
 }

 .content-verticalCentreChild{
  position: relative;
  top: 50%;
  transform: translateY(-50%);
 }

 .iconContainer{
  text-align: center;
 }
 .mediumIcons{
  height: 100px;
 }

 .scrollCard{
  box-shadow: 0 0 8px rgba(33,33,33,.2);
  width: 200px;
  height: 250px;
  border-radius: 10px;
  -webkit-transition: .3s ease;
  -moz-transition: .3s ease;
  -o-transition: .3s ease;
  -ms-transition: .3s ease;
  transition: .3s ease;
 }

 .scrollCard:hover{
  box-shadow: 0 0 11px rgba(33,33,33,.5);
 }

 .scrollCardBar {
  display: flex;
  min-width: 100%;
  min-height: 200px;
  overflow-x: auto;
  margin: 0;
 }

 .scrollCard {
  min-width: 300px;
  margin: 8px;
 }
 .scrollCardContainer{
  display: flex;
  margin-left: 10%;
  margin-right: 10%;
 }

 .scrollCardBar::-webkit-scrollbar {
  display: none;
 }

 .endOfScroll{
  width: 100px;
 }

 .line{
  margin-top: 10px;
  margin-bottom: 35px;
  background-color: white;
  height: 1px;
 }

 footer{
  height: auto;
  background-color: #5388EF;
  color: white;
   width: 100%;
   position: relative;
 }

 footer ul{
  font-weight: 300;
  list-style-type: none;

  margin-top: 20px;
  padding: 0;
 }

 footer li{
  padding: 10px 0px 5px 0px;
 }

 footer .row{
  margin: auto;
 }

 footer .footer-column{
  width: calc(100% / 6);
    height: auto;
    float: left;
    box-sizing: border-box;
   -webkit-box-sizing: border-box;
  -moz-box-sizing: border-box;
  padding: 0px 20px 20px 20px;
  margin-top: 20px;
 }

 @media only screen and (min-width: 2000px){
  .mainMargins{
   margin-left: 25%;
   margin-right: 25%;
  }
  .scrollCardContainer{
   margin-left: 25%;
   margin-right: 25%;
  }
 }

 @media only screen and (max-height: 1000px){
  .fullScreen{
   height: auto;
   width: auto;
  }

  .content-verticalCentreChild{
   position: relative;
   top: 100%;
   transform: none;
  }
 }

 @media only screen and (max-width: 1400px) {
  footer .footer-column{
   width: calc(100% / 3);
  }
 }

 @media only screen and (max-width: 600px) {
  h1{
   font-size: 2em;
  }

  h2{
   font-size: 1em;
  }

  #hamburger{
   top: 5px;
  left: px;
  }

  .mobile-accordian-panel{
  max-height: 0;
  overflow: hidden;
  -webkit-transition: .3s ease;
  -moz-transition: .3s ease;
  -o-transition: .3s ease;
  -ms-transition: .3s ease;
  transition: .3s ease;

  }

  .mainMargins{
   margin-left: 8%;
   margin-right: 8%;
  }

  .content-verticalCentreChild{
   position: relative;
   top: 100%;
   transform: none;
  }
  .scrollCardContainer{
   margin-left: 8%;
   margin-right: 8%;
  }
  .endOfScroll{
   width: 16px;
  }
  footer .footer-column{
   width: 100%
  }

 }</code>```

<!DOCTYPE html>

   <title></title>

<meta charset="utf-8" />

 <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">

<link rel="stylesheet" href="/css/style.css">

<meta name="viewport" content="width=device-width, initial-scale=1" />

  <link href="https://fonts.googleapis.com/css?family=Roboto:300,400,700&display=swap" rel="stylesheet">

   ☰

Title

About

Mission

Services

Social

Get in touch

Title

About

Mission

Title

About

Mission

Services

Social

Title

About

Mission

Services

Catchy Headline That Spans Multiple Lines

Headline Caption (Optional)

Title

This is paragraph text. In publishing and graphic design, Lorem ipsum is a placeholder text commonly used to demonstrate the visual form of a document without relying on meaningful content (also called greeking). This is paragraph text. In publishing and graphic design, Lorem ipsum is a placeholder text commonly used to demonstrate the visual form of a document without relying on meaningful content (also called greeking).

Title

This is paragraph text. In publishing and graphic design, Lorem ipsum is a placeholder text commonly used to demonstrate the visual form of a document without relying on meaningful content (also called greeking). This is paragraph text. In publishing and graphic design, Lorem ipsum is a placeholder text commonly used to demonstrate the visual form of a document without relying on meaningful content (also called greeking).

Title

This is paragraph text. In publishing and graphic design, Lorem ipsum is a placeholder text commonly used to demonstrate the visual form of a document without relying on meaningful content (also called greeking). This is paragraph text. In publishing and graphic design, Lorem ipsum is a placeholder text commonly used to demonstrate the visual form of a document without relying on meaningful content (also called greeking).

Title

This is paragraph text. In publishing and graphic design, Lorem ipsum is a placeholder text commonly used to demonstrate the visual form of a document without relying on meaningful content (also called greeking). This is paragraph text. In publishing and graphic design, Lorem ipsum is a placeholder text commonly used to demonstrate the visual form of a document without relying on meaningful content (also called greeking).

Title

This is paragraph text. In publishing and graphic design, Lorem ipsum is a placeholder text commonly used to demonstrate the visual form of a document without relying on meaningful content (also called greeking). This is paragraph text. In publishing and graphic design, Lorem ipsum is a placeholder text commonly used to demonstrate the visual form of a document without relying on meaningful content (also called greeking).

 Meet Our Reseachers

This is paragraph text. In publishing and graphic design, Lorem ipsum is a placeholder text commonly used to demonstrate the visual form of a document without relying on meaningful content (also called greeking).

        A groundbreaking blueprint for store-program computers. Though a complete version of the ACE was never built, its concept has been used as a model by tech corporations worldwide for several years

        He first addressed the issue of artificial intelligence in his 1950 paper, "Computing machinery and intelligence". If an AI can convice a human that is it human, it should be considered intelligent.

        The highest acheivable award in the field of computer science. Named after Alan Turing for his grand contributions and is equivalent to the Noble Prize.

 News

 Read the Storie’s of sTTARR’s reseachers and users.

Jan, 01, 2019

        Title of the news article will be diplayed under the photo.

Jan, 01, 2019

        Title of the news article will be diplayed under the photo.

Jan, 01, 2019

        Title of the news article will be diplayed under the photo.

 All Stories

Jan, 01, 2019

          Title of the news article will be diplayed under the photo.

Jan, 01, 2019

        Title of the news article will be diplayed under the photo.

Jan, 01, 2019

      Title of the news article will be diplayed under the photo.

Jan, 01, 2019

      Title of the news article will be diplayed under the photo.

Jan, 01, 2019

    Title of the news article will be diplayed under the photo.

Jan, 01, 2019

  Title of the news article will be diplayed under the photo.

 <button onclick="toggleNewsButton()" id="myBtn">Read more</button>

 Updates

 Here is a live twitter update.Here is a live twitter update.Here is a live twitter update.Here is a live twitter update.

        Tweets from UHN

Title

About

Mission

Services

Social

Get in touch

Title

About

Mission

Services

Social

Get in touch

Title

About

Mission

Services

Social

Get in touch

Title

About

Mission

Services

Social

Get in touch

Title

About

Mission

Services

Social

Get in touch

```

EXPECTED: button should show the information in the read more tag.

ACTUAL: button doesn't do anything when you click it.

答:
I'm not sure what you need the #readmore, it's an empty span after all. Anyway, I got rid this. Also, when you set display: none in the css, the style.display will be an empty string, it's working only for inline style (See this in action here.

Just follow the changes I did.

function toggleNewsButton() {
  var moreText = document.getElementById("more");
  var btnText = document.getElementById("myBtn");

  if (!moreText.style.display || moreText.style.display === "none") {
    btnText.innerHTML = "Read less";
    moreText.style.display = "block";
  } else {
    btnText.innerHTML = "Read more";
    moreText.style.display = "none";
  }
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>#more {
  display: none;
}

#myBtn {
  color: black;
  background: #fff;
  border: 1px solid black;
  font-size: 17px;
  padding: 7px 12px;
  font-weight: normal;
  margin: 6px 0;
  margin-right: 12px;
}

.centerButton {
  text-align: center;
}

#myBtn:hover,
#myBtn:active {
  background: black;
  color: white;
}</code>```

 All Stories

Jan, 01, 2019

        Title of the news article will be diplayed under the photo.

Jan, 01, 2019

        Title of the news article will be diplayed under the photo.

Jan, 01, 2019

        Title of the news article will be diplayed under the photo.

Jan, 01, 2019

            Title of the news article will be diplayed under the photo.

Jan, 01, 2019

          Title of the news article will be diplayed under the photo.

Jan, 01, 2019

        Title of the news article will be diplayed under the photo.

    <button onclick="toggleNewsButton()" id="myBtn">Read more</button>

```

Body:
I am trying create a read more read less button. My content that is hidden is in a span tag. I used some javascript to make this work. Currently, when I click on the button nothing happens. My goal is to create a news section that shows more news when you click on the button.

This was working for me before, I used the exact same code and just merged it with some other code and it stopped working.

     $(document).ready(function () {

 var windowHeight = window.innerHeight;

 var navOpen = false;
 var onCloseBtn = false;
 var onAccordian = false;

 $("#hamburger").mouseover(function(){
  if(!navOpen){
   openMenu();
  }
  onCloseBtn = true;
 });

 $("#hamburger").mouseout(function(){
  onCloseBtn = false;
 });

 $("#hamburger").click(function(){
  toggleNav();
  console.log("clickedHam");
 });

 $("#navMenu").mouseover(function(){
  if(!navOpen && !onCloseBtn){
   keepOpen();
  }
 });

 $("#activeSpace").mouseleave(function(){
   console.log("navMenu Mouseout");
   closeMenu();
 });

 function toggleNav(){
  if(navOpen){
   closeMenu();

  } else {
   openMenu();
  }
 }
 function keepOpen(){
  console.log("keepOpen");
  navOpen = true;
  $('#hamburger').html('×');
  $('#hamburger').css("color","black");
  $("#navMenu").css("visibility","visible");
  $("#navMenu").css("height","auto");
  $("#navMenu").css("max-height", windowHeight);
 }

 function openMenu(){
  console.log("open");
  navOpen = true;
  $('#hamburger').html('×');
  $('#hamburger').css("color","black");
  $("#navMenu").css("visibility","visible");
  $("#navMenu").css("max-height", "250px"); ///change this depending on the max
 }

 function closeMenu(){
  closePanels();
  navOpen = false;
  console.log("close")
  $('#hamburger').html('☰');
  $('#hamburger').css("color","white");
  $("#navMenu").css("max-height", "0");
  $("#navMenu").css("visibility","hidden");
 }

 $(document).on('scroll', function() {
  if($(this).scrollTop()>=$('#changeNavColor').position().top - 40 && !navOpen){
   $(hamburger).css("color","black");
  }
  if($(this).scrollTop()<$('#changeNavColor').position().top - 40 && !navOpen){
   $(hamburger).css("color","white");
  }
 });

 var acc = document.getElementsByClassName("mobile-accordian");
 var i;

 for (i = 0; i < acc.length; i++) {
  acc[i].addEventListener("click", function() {
   //this.classList.toggle("active");
   $("#navMenu").css("height","auto");
   $("#navMenu").css("max-height", windowHeight);

   var panel = this.nextElementSibling;
   if (panel.style.maxHeight) {
    panel.style.maxHeight = null;
   } else {
     panel.style.maxHeight = panel.scrollHeight + "px";
   }
  });
 }

 function closePanels() {
  var panels = document.getElementsByClassName("mobile-accordian-panel");
  var j;

  for (j = 0; j < panels.length; j++){
   panels[j].style.maxHeight = null;
  }
 }

function toggleNewsButton() {
  var moreText = document.getElementById("more");
  var btnText = document.getElementById("myBtn");

  if (!moreText.style.display || moreText.style.display === "none") {
    btnText.innerHTML = "Read less";
    moreText.style.display = "block";
  } else {
    btnText.innerHTML = "Read more";
    moreText.style.display = "none";
  }
}

});

     html, body{
  width: 100%;
  height: 100%;
  font-family: 'Roboto', sans-serif;
 }

 h1{
  font-size: 3em;
 }
 h2{
  font-size: 1.5em;
 }

 h3{
  font-size: 0.75em;
  font-weight:400;
  text-transform: uppercase;
 }

 .FullsizeImg{
  background-repeat: no-repeat;
  background-size: 30%;
  background-position: right;

 }
 #more {
   display: none;
 }

 #myBtn {
   color: black;
   background: #fff;
   border: 1px solid black;
   font-size: 17px;
   padding: 7px 12px;
   font-weight: normal;
   margin: 6px 0;
   margin-right: 12px;
 }

 .centerButton {
   text-align: center;
 }

 #myBtn:hover,
 #myBtn:active {
   background: black;
   color: white;
 }

 .allStories{
  margin-left:20px;
  margin-right:20px;
 }

 #hamburger{
  z-index: 11;
  display: block;
  visibility: visible;
  position: fixed;
  top: 10px;
  left: 10px;
  color: white;
  transition: all 0.25 ease;
 }

 #closeBtn{
  display:block;
  position:fixed;
  top:10px;
  left:10px;
 }

 #navMenu{
  z-index: 10;
  display: block;
  overflow:hidden;
  position: fixed;
  top: 0;
  left: 0;
  color: black;
  background-color: white;
  box-shadow: 0 0 8px rgba(33,33,33,.6);
  max-height: 0;
  width: 100%;
  -webkit-transition: 1s ease;
  -moz-transition: 1s ease;
  -o-transition: 1s ease;
  -ms-transition: 1s ease;
  transition: 1s ease;
  visibility: hidden;
 }

 .nav ul {
  list-style-type: none;
  margin: 0;
  padding: 0;
 }

 .nav ul li {
  color: grey;
  font-size: 14px;
  font-weight: regular;
  font-family: inherit;
  padding: 5px 0px 5px 0px;
  cursor: pointer;
  transition: .5s ease;
  -webkit-transition: .5s ease;
  -moz-transition: .5s ease;
 }

 .nav li:hover {
  color: lightgrey;
  font-weight: bold;
  transition: .5s ease;
  -webkit-transition: .5s ease;
  -moz-transition: .5s ease;
 }

 .mainMargins{
  margin-left: 10%;
  margin-right: 10%;
 }

 .smallSpacer{
  height: 25px;
 }

 .bigSpacer{
  height: 100px;
 }

 .txtAlignRight{

 }

 .AlwaysFullScreen{
  width: 100%;
  height: 100%;
 }

 .fullScreen{
  width: 100%;
  height: 100%;
 }

 .withBGImg{
  background-repeat: no-repeat;
  background-size: cover;
  background-position: center;
 }

 .jumbo-title{
  font-weight: bold;
  letter-spacing: 0.02em;
 }

 .jumbo-caption{
  font-weight: 300;
  font-size:
 }

 .jumbo-container{
  color: white;
 }

 .verticalCentreParent{
  -webkit-transform-style: preserve-3d;
  -moz-transform-style: preserve-3d;
  transform-style: preserve-3d;
 }

 .verticalCentreChild{
  position: relative;
  top: 50%;
  transform: translateY(-50%);
 }

 .content-verticalCentreParent{
  -webkit-transform-style: preserve-3d;
  -moz-transform-style: preserve-3d;
  transform-style: preserve-3d;
 }

 .content-verticalCentreChild{
  position: relative;
  top: 50%;
  transform: translateY(-50%);
 }

 .iconContainer{
  text-align: center;
 }
 .mediumIcons{
  height: 100px;
 }

 .scrollCard{
  box-shadow: 0 0 8px rgba(33,33,33,.2);
  width: 200px;
  height: 250px;
  border-radius: 10px;
  -webkit-transition: .3s ease;
  -moz-transition: .3s ease;
  -o-transition: .3s ease;
  -ms-transition: .3s ease;
  transition: .3s ease;
 }

 .scrollCard:hover{
  box-shadow: 0 0 11px rgba(33,33,33,.5);
 }

 .scrollCardBar {
  display: flex;
  min-width: 100%;
  min-height: 200px;
  overflow-x: auto;
  margin: 0;
 }

 .scrollCard {
  min-width: 300px;
  margin: 8px;
 }
 .scrollCardContainer{
  display: flex;
  margin-left: 10%;
  margin-right: 10%;
 }

 .scrollCardBar::-webkit-scrollbar {
  display: none;
 }

 .endOfScroll{
  width: 100px;
 }

 .line{
  margin-top: 10px;
  margin-bottom: 35px;
  background-color: white;
  height: 1px;
 }

 footer{
  height: auto;
  background-color: #5388EF;
  color: white;
   width: 100%;
   position: relative;
 }

 footer ul{
  font-weight: 300;
  list-style-type: none;

  margin-top: 20px;
  padding: 0;
 }

 footer li{
  padding: 10px 0px 5px 0px;
 }

 footer .row{
  margin: auto;
 }

 footer .footer-column{
  width: calc(100% / 6);
    height: auto;
    float: left;
    box-sizing: border-box;
   -webkit-box-sizing: border-box;
  -moz-box-sizing: border-box;
  padding: 0px 20px 20px 20px;
  margin-top: 20px;
 }

 @media only screen and (min-width: 2000px){
  .mainMargins{
   margin-left: 25%;
   margin-right: 25%;
  }
  .scrollCardContainer{
   margin-left: 25%;
   margin-right: 25%;
  }
 }

 @media only screen and (max-height: 1000px){
  .fullScreen{
   height: auto;
   width: auto;
  }

  .content-verticalCentreChild{
   position: relative;
   top: 100%;
   transform: none;
  }
 }

 @media only screen and (max-width: 1400px) {
  footer .footer-column{
   width: calc(100% / 3);
  }
 }

 @media only screen and (max-width: 600px) {
  h1{
   font-size: 2em;
  }

  h2{
   font-size: 1em;
  }

  #hamburger{
   top: 5px;
  left: px;
  }

  .mobile-accordian-panel{
  max-height: 0;
  overflow: hidden;
  -webkit-transition: .3s ease;
  -moz-transition: .3s ease;
  -o-transition: .3s ease;
  -ms-transition: .3s ease;
  transition: .3s ease;

  }

  .mainMargins{
   margin-left: 8%;
   margin-right: 8%;
  }

  .content-verticalCentreChild{
   position: relative;
   top: 100%;
   transform: none;
  }
  .scrollCardContainer{
   margin-left: 8%;
   margin-right: 8%;
  }
  .endOfScroll{
   width: 16px;
  }
  footer .footer-column{
   width: 100%
  }

 }

<!DOCTYPE html>

   <title></title>

<meta charset="utf-8" />

 <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">

<link rel="stylesheet" href="/css/style.css">

<meta name="viewport" content="width=device-width, initial-scale=1" />

  <link href="https://fonts.googleapis.com/css?family=Roboto:300,400,700&display=swap" rel="stylesheet">

   ☰

Title

About

Mission

Services

Social

Get in touch

Title

About

Mission

Title

About

Mission

Services

Social

Title

About

Mission

Services

Catchy Headline That Spans Multiple Lines

Headline Caption (Optional)

Title

This is paragraph text. In publishing and graphic design, Lorem ipsum is a placeholder text commonly used to demonstrate the visual form of a document without relying on meaningful content (also called greeking). This is paragraph text. In publishing and graphic design, Lorem ipsum is a placeholder text commonly used to demonstrate the visual form of a document without relying on meaningful content (also called greeking).

Title

This is paragraph text. In publishing and graphic design, Lorem ipsum is a placeholder text commonly used to demonstrate the visual form of a document without relying on meaningful content (also called greeking). This is paragraph text. In publishing and graphic design, Lorem ipsum is a placeholder text commonly used to demonstrate the visual form of a document without relying on meaningful content (also called greeking).

Title

This is paragraph text. In publishing and graphic design, Lorem ipsum is a placeholder text commonly used to demonstrate the visual form of a document without relying on meaningful content (also called greeking). This is paragraph text. In publishing and graphic design, Lorem ipsum is a placeholder text commonly used to demonstrate the visual form of a document without relying on meaningful content (also called greeking).

Title

This is paragraph text. In publishing and graphic design, Lorem ipsum is a placeholder text commonly used to demonstrate the visual form of a document without relying on meaningful content (also called greeking). This is paragraph text. In publishing and graphic design, Lorem ipsum is a placeholder text commonly used to demonstrate the visual form of a document without relying on meaningful content (also called greeking).

Title

This is paragraph text. In publishing and graphic design, Lorem ipsum is a placeholder text commonly used to demonstrate the visual form of a document without relying on meaningful content (also called greeking). This is paragraph text. In publishing and graphic design, Lorem ipsum is a placeholder text commonly used to demonstrate the visual form of a document without relying on meaningful content (also called greeking).

 Meet Our Reseachers

This is paragraph text. In publishing and graphic design, Lorem ipsum is a placeholder text commonly used to demonstrate the visual form of a document without relying on meaningful content (also called greeking).

        A groundbreaking blueprint for store-program computers. Though a complete version of the ACE was never built, its concept has been used as a model by tech corporations worldwide for several years

        He first addressed the issue of artificial intelligence in his 1950 paper, "Computing machinery and intelligence". If an AI can convice a human that is it human, it should be considered intelligent.

        The highest acheivable award in the field of computer science. Named after Alan Turing for his grand contributions and is equivalent to the Noble Prize.

 News

 Read the Storie’s of sTTARR’s reseachers and users.

Jan, 01, 2019

        Title of the news article will be diplayed under the photo.

Jan, 01, 2019

        Title of the news article will be diplayed under the photo.

Jan, 01, 2019

        Title of the news article will be diplayed under the photo.

 All Stories

Jan, 01, 2019

          Title of the news article will be diplayed under the photo.

Jan, 01, 2019

        Title of the news article will be diplayed under the photo.

Jan, 01, 2019

      Title of the news article will be diplayed under the photo.

Jan, 01, 2019

      Title of the news article will be diplayed under the photo.

Jan, 01, 2019

    Title of the news article will be diplayed under the photo.

Jan, 01, 2019

  Title of the news article will be diplayed under the photo.

 <button onclick="toggleNewsButton()" id="myBtn">Read more</button>

 Updates

 Here is a live twitter update.Here is a live twitter update.Here is a live twitter update.Here is a live twitter update.

        Tweets from UHN

Title

About

Mission

Services

Social

Get in touch

Title

About

Mission

Services

Social

Get in touch

Title

About

Mission

Services

Social

Get in touch

Title

About

Mission

Services

Social

Get in touch

Title

About

Mission

Services

Social

Get in touch

EXPECTED: button should show the information in the read more tag.

ACTUAL: button doesn't do anything when you click it.

Body:
I'm not sure what you need the #readmore, it's an empty span after all. Anyway, I got rid this. Also, when you set display: none in the css, the style.display will be an empty string, it's working only for inline style (See this in action here.

Just follow the changes I did.

function toggleNewsButton() {
  var moreText = document.getElementById("more");
  var btnText = document.getElementById("myBtn");

  if (!moreText.style.display || moreText.style.display === "none") {
    btnText.innerHTML = "Read less";
    moreText.style.display = "block";
  } else {
    btnText.innerHTML = "Read more";
    moreText.style.display = "none";
  }
}

#more {
  display: none;
}

#myBtn {
  color: black;
  background: #fff;
  border: 1px solid black;
  font-size: 17px;
  padding: 7px 12px;
  font-weight: normal;
  margin: 6px 0;
  margin-right: 12px;
}

.centerButton {
  text-align: center;
}

#myBtn:hover,
#myBtn:active {
  background: black;
  color: white;
}

<section id="" class="">

  <div class="allStories">
    <hr>
    <h2 style="text-align:center;"> All Stories</h2>
    <hr>
    <div class="smallSpacer"></div>

    <div class="row">
      <div class="col-sm-6" style="text-align:left;">
        <p class="#" style="color:lightgray;">Jan, 01, 2019 </p>
        <small>Title of the news article will be diplayed under the photo. </small>
      </div>
      <div class="col-sm-6" style="text-align: right;">
        <img src="/images/news1.jpg" style="height:200px; width:300px;">
      </div>
    </div>

    <hr>

    <div class="row">
      <div class="col-sm-6" style="text-align:left;">
        <p class="#" style="color:lightgray;  ">Jan, 01, 2019 </p>
        <small>Title of the news article will be diplayed under the photo. </small>
      </div>
      <div class="col-sm-6" style="text-align: right;">
        <img src="/images/news2.jpg" style="height:200px; width:300px; ">
      </div>
    </div>

    <hr>

    <div class="row">
      <div class="col-sm-6" style="text-align:left;">
        <p class="#" style="color:lightgray;  ">Jan, 01, 2019 </p>
        <small>Title of the news article will be diplayed under the photo. </small>
      </div>
      <div class="col-sm-6" style="text-align: right;">
        <img src="/images/news3.jpg" style="height:200px; width:300px; ">
      </div>
    </div>

    <hr>

    <span id="more">

          <div class="row">
          <div class ="col-sm-6" style = "text-align:left;">
            <p class="#"  style = "color:lightgray;">Jan, 01, 2019 </p>
            <small>Title of the news article will be diplayed under the photo. </small>
          </div>
          <div class ="col-sm-6" style = "text-align: right;">
           <img src = "/images/news1.jpg" style = "height:200px; width:300px;">
         </div>
       </div>

       <hr>

       <div class="row">
        <div class ="col-sm-6" style = "text-align:left;">
          <p class="#"  style = "color:lightgray;  ">Jan, 01, 2019 </p>
          <small>Title of the news article will be diplayed under the photo. </small>
        </div>
        <div class ="col-sm-6" style = "text-align: right;">
         <img src = "/images/news2.jpg" style = "height:200px; width:300px; ">
       </div>
     </div>

     <hr>

     <div class="row">
      <div class ="col-sm-6" style = "text-align:left;">
        <p class="#"  style = "color:lightgray;  ">Jan, 01, 2019 </p>
        <small>Title of the news article will be diplayed under the photo. </small>
      </div>
      <div class ="col-sm-6" style = "text-align: right;">
       <img src = "/images/news3.jpg" style = "height:200px; width:300px; ">

       </div>
       </div>
       </span>
  </div>

  <div class="centerButton">
    <button onclick="toggleNewsButton()" id="myBtn">Read more</button>
  </div>

</section>


问:
Filter the output in json format in ansible playbook
I have a json file as below

```<code>"data": [

   {
      "name": "first",
      "foo": "123",
      "item": "monday"
  },

  {
      "name": "second",
      "foo": "456",
      "item": "tuesday"
      },

      {
      "name": "third",
      "foo": "789",
      "item": "wednesday"}

  ]
}
</code>```

Now I need the value of foo when item is wednesday in my ansible playbook

I used the below json query but failed to get desired output

```<code>- name: Get foo value.
  set_fact:
     foo_value: "{{ (json.stdout | from_json).data | map(attribute='foo') | list }}"
</code>```

I need foo_value : 789 when I mention item : wednesday, please let me know what I am doing wrong

答:
I need foo_value : 789 when I mention item : wednesday, please let me know what I am doing wrong

The first thing you are doing wrong is the failure to mention item anywhere in your expression; that said, what you are looking for is selectattr

```<code>set_fact:
  foo_value: "{{ (json.stdout | from_json).data
    | selectattr('item', 'eq', 'wednesday')
    | map(attribute='foo') | list }}"
</code>```

Body:
I have a json file as below

"data": [

   {
      "name": "first",
      "foo": "123",
      "item": "monday"
  },

  {
      "name": "second",
      "foo": "456",
      "item": "tuesday"
      },

      {
      "name": "third",
      "foo": "789",
      "item": "wednesday"}

  ]
}

Now I need the value of foo when item is wednesday in my ansible playbook

I used the below json query but failed to get desired output

- name: Get foo value.
  set_fact:
     foo_value: "{{ (json.stdout | from_json).data | map(attribute='foo') | list }}"

I need foo_value : 789 when I mention item : wednesday, please let me know what I am doing wrong

Body:
I need foo_value : 789 when I mention item : wednesday, please let me know what I am doing wrong

The first thing you are doing wrong is the failure to mention item anywhere in your expression; that said, what you are looking for is selectattr

set_fact:
  foo_value: "{{ (json.stdout | from_json).data
    | selectattr('item', 'eq', 'wednesday')
    | map(attribute='foo') | list }}"


问:
SymPy/SciPy: Involving time-dependent values
I'm new to SymPy and SciPy and looking for a way to involve time-dependent variables in a symbolic expression.

For example to differentiate x(t) with respect to t which should result in xd(t) or similar.

Up to know I did not find an appropriate example, how to do that?

答:
I found the way:

from sympy import *
from sympy.core.function import Function

t = Symbol('t')
f = Function('f')(t)
print(f)

print("diff(f,t) = %s"%diff(f,t))
print("diff(f,f) = %s"%diff(f,f))
print("diff(f**2,f) = %s"%diff(f**2,f))
```

<p>gives:</p>

<pre class="lang-sh prettyprint-override"><code>f(t)
diff(f,t) = Derivative(f(t), t)
diff(f,f) = 1
diff(f**2,f) = 2*f(t)
</code>```

Body:
I found the way:

from sympy import *
from sympy.core.function import Function

t = Symbol('t')
f = Function('f')(t)
print(f)

print("diff(f,t) = %s"%diff(f,t))
print("diff(f,f) = %s"%diff(f,f))
print("diff(f**2,f) = %s"%diff(f**2,f))

gives:

f(t)
diff(f,t) = Derivative(f(t), t)
diff(f,f) = 1
diff(f**2,f) = 2*f(t)


问:
Java8 streams with Map?
I have the following Map (each key is a String and each value is a List<Message>)

My map is like this :

```<code>1st entry :"MONDAY" -> [message1, message2, message3]
2nd entry : "TUESDAY" -> [message4, message5]
...
</code>```

My goal is to change each message content :

I was thinking about this :

```<code>map.entrySet().stream().peek(entry -> {
    entry.getValue().stream().peek(m -> m.setMessage(changeMessage()))
})
</code>```

But don't know how to finish and do it properly.

答:
If you just want to update the message of all messages there is no need to use the whole entry set. You can just stream the values of your map and map the items. The use forEach() to update them:

```<code>map.values().stream().flatMap(List::stream)
        .forEach(m -> m.setMessage(changeMessage(m.getMessage())));
</code>```

If you need the key to change the message you can use this:

```<code>map.forEach((key, messages) -> messages.forEach(m ->
        m.setMessage(changeMessage(key, m.getMessage()))));
</code>```

Title: Java8 streams with Map?

Body:
I have the following Map (each key is a String and each value is a List<Message>)

My map is like this :

1st entry :"MONDAY" -> [message1, message2, message3]
2nd entry : "TUESDAY" -> [message4, message5]
...

My goal is to change each message content :

I was thinking about this :

map.entrySet().stream().peek(entry -> {
    entry.getValue().stream().peek(m -> m.setMessage(changeMessage()))
})

But don't know how to finish and do it properly.

Body:
If you just want to update the message of all messages there is no need to use the whole entry set. You can just stream the values of your map and map the items. The use forEach() to update them:

map.values().stream().flatMap(List::stream)
        .forEach(m -> m.setMessage(changeMessage(m.getMessage())));

If you need the key to change the message you can use this:

map.forEach((key, messages) -> messages.forEach(m ->
        m.setMessage(changeMessage(key, m.getMessage()))));


问:
How to start with a PHP website?
For a school project I have to produce a website using PHP that allows user to generate there own article or comment on news or others articles. I was wondering how it is best to use the GET function to show the content in an include file and also use the get function for other include files such as the login page and other content the developer (me) has added to website not as articles but as links etc. Anyone got any suggestions or good tutorials they could post up. </p>

答:
This is what I use...

```<code>   function safeIncludeFile($path)
   {

        $regex = '/[a-z0-9\-_]+/i'; // match only a to z, 0 to 9 and the minus and unscore character. case insensitive. adjust to accommodate your file naming schema.

        return preg_match($regex, $path);

   }
</code>```

And then do something like this

```<code>if (isset($_GET['page']) && safeIncludeFile($_GET['page'])) {
   require PATH_TO_INCLUDES . $_GET['page'] . '.inc.php';

}
</code>```

OwnerDisplayName: Cool Hand Luke UK

Title: How to start with a PHP website?

LastEditorDisplayName: Rex M

Body:
This is what I use...

   function safeIncludeFile($path)
   {

        $regex = '/[a-z0-9\-_]+/i'; // match only a to z, 0 to 9 and the minus and unscore character. case insensitive. adjust to accommodate your file naming schema.

        return preg_match($regex, $path);

   }

And then do something like this

if (isset($_GET['page']) && safeIncludeFile($_GET['page'])) {
   require PATH_TO_INCLUDES . $_GET['page'] . '.inc.php';

}

OwnerDisplayName: alex

ContentLicense: CC BY-SA 2.5


问:
questions on the hack architecture
The hack architecture is a 16 bit computer. modern say processors are 32 bit or 64 bit

suggest two potential impacts of changing the hack architecture from 16 bits to 32 bits

what changes would be needed to make the hack architecture from 16 bit to 32 bit

答:
In 32 bits you can encode more instructions and transfer more data in a single instruction.

To change your architecture, you need to:

change your registers and the buses.

change the alu range.

add logic for ram manipulation. (because the ram mus have 8bit cells and your processor works with 32 bit instructions)

And because you have 32 bits you can encode more instructions like multiply, divide, etc.

Title: questions on the hack architecture


问:
C++ include header / forward declaration order
A similar issue has already been discussed (C/C++ include header file order), but this thread makes no mention of forward declarations. If I summarize what I've read online so far:

Everyone agrees that the corresponding header for the .cpp file should go first. This ensures that the header files has everything it needs.

Beyond that, there seems to be no consensus. The Google guidelines (https://google.github.io/styleguide/cppguide.html) suggest including headers from system -> other libs -> project. Many people on SO suggest the exact opposite. It seems to be a matter of personal preferences.

Regarding forward declarations, is there any reason to add them before/after the include headers? I don't see why it would matter (Is a class declaration allowed after a class definition?), but maybe I am missing something.

答:
I think this is one of those questions that has no one right answer.

The way I think of it (and its by no means the absolute answer) is from an encapsulation point of view and I tend to do the opposite of the google guidelines for this reason:

If you include your project headers first you are less likley to hit issues where your header relies on some system include that went before it because you will just get a compile error... so therefore I find you see issues faster by putting the system includes last.

Same thing for the forward declarations - if you need them and they are not provided by a header - then add them after the includes because the headers should not need them (otherwise it would be in the header) and so you only declare it as/when you need it...

That is more-or-less my reasoning - but as I say, if your headers are designed correctly then you could do it either way...


问:
Django class based view ListView with form
The main view is a simple paginated ListView and I want to add a search form to it.

I thought something like this would do the trick:

```<code>class MyListView(ListView, FormView):
    form_class = MySearchForm
    success_url = 'my-sucess-url'
    model = MyModel
    # ...
</code>```

But apparently I got it wrong .. and I can't find how to do it in the official documentation.

Suggestions ?

答:
Adding forms to index and list views using mixins is covered in the the official documentation.

The documentation generally recommends against this approach. It suggests to instead simply write a bit more python, and code the view manually.

Body:
The main view is a simple paginated ListView and I want to add a search form to it.

I thought something like this would do the trick:

class MyListView(ListView, FormView):
    form_class = MySearchForm
    success_url = 'my-sucess-url'
    model = MyModel
    # ...

But apparently I got it wrong .. and I can't find how to do it in the official documentation.

Suggestions ?


问:
Creating a WooCommerce Order programmatically for a subscription product
With woocommerce I am using WooCommerce Subscriptions plugin. I have created a function that can create an order based on the product SKU using wc_get_product_id_by_sku() function, from a Subscription product.

This is my function at the moment:

```<code>function create_new_order() {
    global $woocommerce;

    $address = array(
        'first_name' => 'Zakup',
        'last_name'  => 'Sklepowy',
        'email'      => 'test@test.pl',
        'phone'      => '123',
        'address_1'  => 'ul. Przykladowa 1',
        'address_2'  => 'm. 2',
        'city'       => 'Wroclaw',
        'postcode'   => '50-123',
    );

    $order = wc_create_order();

    $product = new WC_Product( wc_get_product_id_by_sku( 'wpoh-prof-webshop' ) );
    $order->add_product( $product, 1 );
    $order->set_address( $address, 'billing' );

    // Set payment gateway
    $payment_gateways = WC()->payment_gateways->payment_gateways();
    $order->set_payment_method( $payment_gateways['cod'] );

    // Calculate totals
    $order->calculate_totals();
    $order->update_status( 'completed', 'In Store ', true );
}
</code>```

With this line:

```<code>$product = new WC_Product (wc_get_product_id_by_sku ('wpoh-prof-webshop'));
</code>```

I pick up the product to be placed with the order. I have hardcoded the customer billing address in this function as its's required.

When I run the function, an empty order is created that does not have any product or address attached to it.

order created without personal information or product:

Can someone help me and tell me where it goes wrong?

答:
To get one of the following subscription product objects:

WC_Product_Subscription (a subscription product type, a simple subscription),

WC_Product_Variable_Subscription (a variable-subscription product type),

WC_Product_Subscription_Variation (a subscription_variation product type).

You can not use new WC_Product() as it will throw an error.

Instead you should use wc_get_product() function.

Now global $woocommerce; is not required and doesn't do anything.

SKU: Get the product object from a product ID using wc_get_product_id_by_sku() function:

The SKU should always be from a simple subscription or a variation subscription, but never from a variable subscription product…

Try the following lightly modified function:

```<code>function create_new_order() {
    $sku = 'wpoh-prof-webshop';
    $address = array(
        'first_name' => 'Zakup',
        'last_name'  => 'Sklepowy',
        'email'      => 'test@test.pl',
        'phone'      => '123',
        'address_1'  => 'ul. Przykladowa 1',
        'address_2'  => 'm. 2',
        'city'       => 'Wroclaw',
        'postcode'   => '50-123',
    );

    $order = wc_create_order(); // Create a WC_Order object and save it.

    $order->set_address( $address, 'billing' ); // Set customer billing adress

    $product = wc_get_product( wc_get_product_id_by_sku( $sku ) );
    $order->add_product( $product, 1 ); // Add an order line item

    // Set payment gateway
    $payment_gateways = WC()->payment_gateways->payment_gateways();
    $order->set_payment_method( $payment_gateways['cod'] );

    $order->calculate_totals(); // Update order taxes and totals
    $order->update_status( 'completed', 'In Store ', true ); // Set order status and save
}
</code>```

Tested and works.

Related answer: Get the product object from sku and update the price in WooCommerce

Body:
With woocommerce I am using WooCommerce Subscriptions plugin. I have created a function that can create an order based on the product SKU using wc_get_product_id_by_sku() function, from a Subscription product.

This is my function at the moment:

function create_new_order() {
    global $woocommerce;

    $address = array(
        'first_name' => 'Zakup',
        'last_name'  => 'Sklepowy',
        'email'      => 'test@test.pl',
        'phone'      => '123',
        'address_1'  => 'ul. Przykladowa 1',
        'address_2'  => 'm. 2',
        'city'       => 'Wroclaw',
        'postcode'   => '50-123',
    );

    $order = wc_create_order();

    $product = new WC_Product( wc_get_product_id_by_sku( 'wpoh-prof-webshop' ) );
    $order->add_product( $product, 1 );
    $order->set_address( $address, 'billing' );

    // Set payment gateway
    $payment_gateways = WC()->payment_gateways->payment_gateways();
    $order->set_payment_method( $payment_gateways['cod'] );

    // Calculate totals
    $order->calculate_totals();
    $order->update_status( 'completed', 'In Store ', true );
}

With this line:

$product = new WC_Product (wc_get_product_id_by_sku ('wpoh-prof-webshop'));

I pick up the product to be placed with the order. I have hardcoded the customer billing address in this function as its's required.

When I run the function, an empty order is created that does not have any product or address attached to it.

order created without personal information or product:

Can someone help me and tell me where it goes wrong?

Body:
To get one of the following subscription product objects:

WC_Product_Subscription (a subscription product type, a simple subscription),

WC_Product_Variable_Subscription (a variable-subscription product type),

WC_Product_Subscription_Variation (a subscription_variation product type).

You can not use new WC_Product() as it will throw an error.

Instead you should use wc_get_product() function.

Now global $woocommerce; is not required and doesn't do anything.

SKU: Get the product object from a product ID using wc_get_product_id_by_sku() function:

The SKU should always be from a simple subscription or a variation subscription, but never from a variable subscription product…

Try the following lightly modified function:

function create_new_order() {
    $sku = 'wpoh-prof-webshop';
    $address = array(
        'first_name' => 'Zakup',
        'last_name'  => 'Sklepowy',
        'email'      => 'test@test.pl',
        'phone'      => '123',
        'address_1'  => 'ul. Przykladowa 1',
        'address_2'  => 'm. 2',
        'city'       => 'Wroclaw',
        'postcode'   => '50-123',
    );

    $order = wc_create_order(); // Create a WC_Order object and save it.

    $order->set_address( $address, 'billing' ); // Set customer billing adress

    $product = wc_get_product( wc_get_product_id_by_sku( $sku ) );
    $order->add_product( $product, 1 ); // Add an order line item

    // Set payment gateway
    $payment_gateways = WC()->payment_gateways->payment_gateways();
    $order->set_payment_method( $payment_gateways['cod'] );

    $order->calculate_totals(); // Update order taxes and totals
    $order->update_status( 'completed', 'In Store ', true ); // Set order status and save
}

Tested and works.

Related answer: Get the product object from sku and update the price in WooCommerce


问:
How do you iterate through a list in c# using mustache and get each value in a placeholder
I am using mustache# for .Net and to help me get values into a html template for an email application.  I am able to get mustache placeholders to store single values but having issues iterating through a a list and saving the values in a placeholder.

My example list in the code I provide below is a simple string List with 2 elements. When the email sends and the html template is attached All I am getting for this is System.Collections.Generic.List'1[System.String] twice.
I understand why its showing up twice because of there being 2 elements in the list.  I just don't know how to have it show each value instead.

```<code>List<string> namelist = new List<string>();
namelist.Add("Val");
namelist.Add("Jeff");

const string names = "{{#each name}} <h2> Hello, {{name}}</h2> {{/each}}";

HtmlFormatCompiler compilers = new HtmlFormatCompiler();

Generator generator = compilers.Compile(names);

string result = generator.Render(new
{
     name = namelist

});

string template = System.IO.File.ReadAllText(System.Web.HttpContext.Current.Server.MapPath
("~/Views/Shared/_HpNotificationEmailTemplate.cshtml"));

string emailBody = string.Format(template,result);

</code>```

I am expecting it to show the values  Val and Jeff but I am just getting System.Collections.Generic.List'1[System.String] twice.

答:
I don't know but the the Mustache for C# template syntax does not seem to be the same as that used in javascript. It probably an old implementation, anyway, the solution is to use {{this}} instead of {{name}}</p>

```<code> List<string> namelist = new List<string>();
 namelist.Add("Val");
 namelist.Add("Jeff");

 const string names = "{{#each name}} <h2> Hello, {{this}}</h2> {{/each}}";
 HtmlFormatCompiler compilers = new HtmlFormatCompiler();

 Generator generator = compilers.Compile(names);

 string result = generator.Render(new
 {
    name = namelist
 });
</code>```

Body:
I am using mustache# for .Net and to help me get values into a html template for an email application.  I am able to get mustache placeholders to store single values but having issues iterating through a a list and saving the values in a placeholder.

My example list in the code I provide below is a simple string List with 2 elements. When the email sends and the html template is attached All I am getting for this is System.Collections.Generic.List'1[System.String] twice.
I understand why its showing up twice because of there being 2 elements in the list.  I just don't know how to have it show each value instead.

List<string> namelist = new List<string>();
namelist.Add("Val");
namelist.Add("Jeff");

const string names = "{{#each name}}
 Hello, {{name}}
 {{/each}}";

HtmlFormatCompiler compilers = new HtmlFormatCompiler();

Generator generator = compilers.Compile(names);

string result = generator.Render(new
{
     name = namelist

});

string template = System.IO.File.ReadAllText(System.Web.HttpContext.Current.Server.MapPath
("~/Views/Shared/_HpNotificationEmailTemplate.cshtml"));

string emailBody = string.Format(template,result);

I am expecting it to show the values  Val and Jeff but I am just getting System.Collections.Generic.List'1[System.String] twice.

Body:
I don't know but the the Mustache for C# template syntax does not seem to be the same as that used in javascript. It probably an old implementation, anyway, the solution is to use {{this}} instead of {{name}}

 List<string> namelist = new List<string>();
 namelist.Add("Val");
 namelist.Add("Jeff");

 const string names = "{{#each name}} <h2> Hello, {{this}}</h2> {{/each}}";
 HtmlFormatCompiler compilers = new HtmlFormatCompiler();

 Generator generator = compilers.Compile(names);

 string result = generator.Render(new
 {
    name = namelist
 });


问:
Unable to save SSIS 2015 to SQL Server 2012
I'm having some trouble saving an SSIS package to a SQL Server 2012 database.

In previous version of Visual Studio, I went to File > Save a copy of **** As.

As in this link: https://msdn.microsoft.com/en-us/library/ms137565.aspx

It would then give me the option to select the server and a few other options.

However, in Visual Studio Community 2015 I get the below screen.

I'm using SSDT 2015, with my solution downgraded to 2012.

Is there a different way of uploading this to SQL Server now? Or am I missing something glaringly obvious?

答:
fyi - I have created SSIS projects in VS2015 and deployed to SQL 2012 sp3 for quite a while until today when I received the message that I could not deploy to SQL < 2016.

Found I had to delete the project in Integration Services Catalog, recreate, deployment worked correctly again. As a test I made a small change to a package and could still deploy to SQL Server. Very odd.


问:
Need to make same javascript function in python
I'm trying to use some API with Python. Can't translate this JavaScript function:

```<code>const requestUrl = '/api/v1/account/balance' //add

const data = {
  request: requestUrl,
  currency: "ETH",
  nonce: parseInt(Date.now().toString() / 1000)
};
const stringifiedData = JSON.stringify(data);
const payload = new Buffer(stringifiedData).toString('base64')
console.log(payload);
</code>```

the outcome result:
eyJyZXF1ZXN0IjoiL2FwaS92MS9hY2NvdW50L2JhbGFuY2UiLCJjdXJyZW5jeSI6IkVUSCIsIm5vbmNlIjoxNTU5MTQzOTI2fQ==

I'm trying to do same with python3:

```<code>from flask import Flask, json
app = Flask(__name__)
timestam = datetime.datetime.now()
timenow = int (timestam.strftime("%s"))
nonce = str(timenow)

@app.route("/")
def func1():
    reuquestUrl= '/api/v1/account/balance'
    data = {
       "request":reuquestUrl,
       "currency":"ETH",
       "nonce":nonce
   }
   stringfieldData=json.dumps(data)
   payload = str(base64.b64encode(b'stringfieldData'))
   return payload
</code>```

it returns b'c3RyaW5nZmllbGREYXRh' or something like this.
I also tried jsonify with almost same result. Any suggestions?

答:
you are b64 encoding the string 'strigifiedData' itself, instead of the contents of the variable with that name (because b'stringfieldData' is a bytes object literal)

in addition, b64 encode returns a bytes object, so if you want to return a string, you need to .decode() it.

try this please, let me know if it helped:

def func1():
    reuquestUrl= '/api/v1/account/balance'
    data = {"request":reuquestUrl, "currency":"ETH","nonce":nonce}
    stringfieldData=json.dumps(data)
    payload = base64.b64encode(stringfieldData.encode())
    return payload.decode()
```

Body:
I'm trying to use some API with Python. Can't translate this JavaScript function:

const requestUrl = '/api/v1/account/balance' //add

const data = {
  request: requestUrl,
  currency: "ETH",
  nonce: parseInt(Date.now().toString() / 1000)
};
const stringifiedData = JSON.stringify(data);
const payload = new Buffer(stringifiedData).toString('base64')
console.log(payload);

the outcome result:
eyJyZXF1ZXN0IjoiL2FwaS92MS9hY2NvdW50L2JhbGFuY2UiLCJjdXJyZW5jeSI6IkVUSCIsIm5vbmNlIjoxNTU5MTQzOTI2fQ==

I'm trying to do same with python3:

from flask import Flask, json
app = Flask(__name__)
timestam = datetime.datetime.now()
timenow = int (timestam.strftime("%s"))
nonce = str(timenow)

@app.route("/")
def func1():
    reuquestUrl= '/api/v1/account/balance'
    data = {
       "request":reuquestUrl,
       "currency":"ETH",
       "nonce":nonce
   }
   stringfieldData=json.dumps(data)
   payload = str(base64.b64encode(b'stringfieldData'))
   return payload

it returns b'c3RyaW5nZmllbGREYXRh' or something like this.
I also tried jsonify with almost same result. Any suggestions?


问:
Most elegant and fastest way to remove all leading zeroes in perl string
I wrote rmlz function for trimming all leading zeroes from string.

```<code># remove all leading zeroes from string
use strict;
use warnings;
use feature 'say';

sub rmlz {
  my ( $str ) = @_;
  if ( $str =~ /^(.[0])/ ) {
    return substr( $str, length($1));
  }
  return $str;
}

say rmlz('0050625'); # must return 50625
</code>```

Is there most elegant and clear way to rewrite this code ? Or regexp+length+substr is best option ?

答:
Since this seems to be about a number, can reformat it as such (if indeed an integer)

```<code>my $num = sprintf "%d", $num_in_str;
</code>```

or have Perl take care of it by making it treat the string as a number

```<code>my $num = 0 + $num_in_str;   # or just:  $num_in_str += 0;
</code>```

This does the right thing for any kind of number in $num_in_str, and it is incomparably more efficient than sprintf or starting a regex engine.  While it may appear tricky it's fine in a sub

```<code>sub rmlz { return 0+$_[0] }
</code>```

where you practically pay only for the function call overhead (still a bit in Perl).

Both of these print warnings if $num_in_str isn't a valid number, what is good in my opinion (unless you need to work with things like 0023a, in which case you want a regex).

Body:
I wrote rmlz function for trimming all leading zeroes from string.

# remove all leading zeroes from string
use strict;
use warnings;
use feature 'say';

sub rmlz {
  my ( $str ) = @_;
  if ( $str =~ /^(.[0])/ ) {
    return substr( $str, length($1));
  }
  return $str;
}

say rmlz('0050625'); # must return 50625

Is there most elegant and clear way to rewrite this code ? Or regexp+length+substr is best option ?

Body:
Since this seems to be about a number, can reformat it as such (if indeed an integer)

my $num = sprintf "%d", $num_in_str;

or have Perl take care of it by making it treat the string as a number

my $num = 0 + $num_in_str;   # or just:  $num_in_str += 0;

This does the right thing for any kind of number in $num_in_str, and it is incomparably more efficient than sprintf or starting a regex engine.  While it may appear tricky it's fine in a sub

sub rmlz { return 0+$_[0] }

where you practically pay only for the function call overhead (still a bit in Perl).

Both of these print warnings if $num_in_str isn't a valid number, what is good in my opinion (unless you need to work with things like 0023a, in which case you want a regex).


问:
I need to write Regx for text field validation, which start with either 'iqn.yyyy-mm.com.' or 'eqn.'
I need to write Regx for text field validation, which start with either 'iqn.yyyy-mm.com.' or 'eqn.'
After this any number of character or numeric value is allowed
Here 'yyyy-mm' is year and month.</p>

答:
If we are just validating the year and month and before and after chars are OK, then this expression might work:

```<code>.+\.[\d]{4}-[\d]{2}\..+
</code>```

If we wish to add more constraints, we can surely do so by modifying these two .+ in the start and end of string. We can also add start and end chars, if necessary.

const regex = /.+\.[\d]{4}-[\d]{2}\..+/gm;
const str = `iqn.2019-10.com
eqn.2019-10.com
eqn.209-10.com`;
let m;

while ((m = regex.exec(str)) !== null) {
    // This is necessary to avoid infinite loops with zero-width matches
    if (m.index === regex.lastIndex) {
        regex.lastIndex++;
    }

    // The result can be accessed through the `m`-variable.
    m.forEach((match, groupIndex) => {
        console.log(`Found match, group ${groupIndex}: ${match}`);
    });
}```

DEMO

RegEx

If this expression wasn't desired, it can be modified/changed in regex101.com.

RegEx Circuit

jex.im visualizes regular expressions:

Body:
If we are just validating the year and month and before and after chars are OK, then this expression might work:

.+\.[\d]{4}-[\d]{2}\..+

If we wish to add more constraints, we can surely do so by modifying these two .+ in the start and end of string. We can also add start and end chars, if necessary.

const regex = /.+\.[\d]{4}-[\d]{2}\..+/gm;
const str = `iqn.2019-10.com
eqn.2019-10.com
eqn.209-10.com`;
let m;

while ((m = regex.exec(str)) !== null) {
    // This is necessary to avoid infinite loops with zero-width matches
    if (m.index === regex.lastIndex) {
        regex.lastIndex++;
    }

    // The result can be accessed through the `m`-variable.
    m.forEach((match, groupIndex) => {
        console.log(`Found match, group ${groupIndex}: ${match}`);
    });
}

DEMO

RegEx

If this expression wasn't desired, it can be modified/changed in regex101.com.

RegEx Circuit

jex.im visualizes regular expressions:


问:
Need to check for specific key presses in Javascript
I am having troubles understanding why the code below works, and I think my confusing arises with the callback to "event" in this case. I have a few images that when clicked or a corresponding keypress is logged, a sound will play. While everything works, I can't understand why the below code uses "event" instead of just using an empty function and call to "this" (ie: this.key)

I have tried to use the "this" method but it didn't work. A bit of research and I found I had to use "event" in my function.

```<code>function addListenerToAllDrums() {
    //store buttons in array
    var buttonArray = document.querySelectorAll(".drum");
    //iterate thru each btn
    for (var i = 0; i < buttonArray.length; i++) {
        //add a listener each iter.
        buttonArray[i].addEventListener("click", function () {
            //store html of button (ie: `w`) to variable
            var buttonInnerHTML = this.innerHTML;
            //the stored html is passed to the checkSound function
            checkSound(buttonInnerHTML); //ie: `w` = case w
        });
    }
}
</code>```

```<code>//check for keypress
document.addEventListener(`keydown`, function (event) {
    //store the key in a variable
    var pressedKey = event.key
    //passes pressedKey as string (ie: `w`) to checkSound(`w`)
    checkSound(pressedKey);
});
</code>```

```<code>//make a sound dependant on button press or keypress functions
function checkSound(input) {
    //Create Switch Statement based on keypress/button click input
    switch (input) {
        case `w`:
            var snare = new Audio('sounds/snare.mp3');
            snare.play();
        case `a`:
            var tom1 = new Audio('sounds/tom-1.mp3');
            tom1.play();
            break;
        case `s`:
            var tom3 = new Audio('sounds/tom-3.mp3');
            tom3.play();
            break;
        case `d`:
            var kick = new Audio('sounds/kick-bass.mp3');
            kick.play();
            break;
        case `j`:
            var tom4 = new Audio('sounds/tom-4.mp3');
            tom4.play();
            break;
        case 'k':
            var tom2 = new Audio('sounds/tom-2.mp3');
            tom2.play();
            break;
        case `l`:
            var crash = new Audio('sounds/crash.mp3');
            crash.play();
            break;

        default:
            console.log(this.innerHTML)
    }
}

addListenerToAllDrums();
</code>```

How can my clicks work with "this" but keypresses need "event"?

答: That's because, in your case, this would represent the element to which the event was bound, while event would say what happended to the element.

Body:
I am having troubles understanding why the code below works, and I think my confusing arises with the callback to "event" in this case. I have a few images that when clicked or a corresponding keypress is logged, a sound will play. While everything works, I can't understand why the below code uses "event" instead of just using an empty function and call to "this" (ie: this.key)

I have tried to use the "this" method but it didn't work. A bit of research and I found I had to use "event" in my function.

function addListenerToAllDrums() {
    //store buttons in array
    var buttonArray = document.querySelectorAll(".drum");
    //iterate thru each btn
    for (var i = 0; i < buttonArray.length; i++) {
        //add a listener each iter.
        buttonArray[i].addEventListener("click", function () {
            //store html of button (ie: `w`) to variable
            var buttonInnerHTML = this.innerHTML;
            //the stored html is passed to the checkSound function
            checkSound(buttonInnerHTML); //ie: `w` = case w
        });
    }
}

//check for keypress
document.addEventListener(`keydown`, function (event) {
    //store the key in a variable
    var pressedKey = event.key
    //passes pressedKey as string (ie: `w`) to checkSound(`w`)
    checkSound(pressedKey);
});

//make a sound dependant on button press or keypress functions
function checkSound(input) {
    //Create Switch Statement based on keypress/button click input
    switch (input) {
        case `w`:
            var snare = new Audio('sounds/snare.mp3');
            snare.play();
        case `a`:
            var tom1 = new Audio('sounds/tom-1.mp3');
            tom1.play();
            break;
        case `s`:
            var tom3 = new Audio('sounds/tom-3.mp3');
            tom3.play();
            break;
        case `d`:
            var kick = new Audio('sounds/kick-bass.mp3');
            kick.play();
            break;
        case `j`:
            var tom4 = new Audio('sounds/tom-4.mp3');
            tom4.play();
            break;
        case 'k':
            var tom2 = new Audio('sounds/tom-2.mp3');
            tom2.play();
            break;
        case `l`:
            var crash = new Audio('sounds/crash.mp3');
            crash.play();
            break;

        default:
            console.log(this.innerHTML)
    }
}

addListenerToAllDrums();

How can my clicks work with "this" but keypresses need "event"?


问:
How to check if string2 has characters not in string1?
```<code>char String1 = "1234567890+-";
char String2 = "1+a";
</code>```

String2 is an input and I want to check if it contains any character that is not in String1.

I have tried using strpbrk(String2,String1) but this returns true as long as any character in String1 exists in String2.

Is there a better way to do it?

答:
You can use a simplified version of union-find.

First, you loop over string1 and mark all the characters with 1. I write simplified code, you can complete it.

```<code>char mark[255];
for(s=string1; s; s++) mark[*s]=1;
</code>```

Next, you loop over string2 and check if the current char is marked.

```<code>for(s=string2; s; s++) if (!mark[*s]) printf("%c", *s);
</code>```

This will print all chars from string2 that are not in string1.

Body:
char String1 = "1234567890+-";
char String2 = "1+a";

String2 is an input and I want to check if it contains any character that is not in String1.

I have tried using strpbrk(String2,String1) but this returns true as long as any character in String1 exists in String2.

Is there a better way to do it?

Body:
You can use a simplified version of union-find.

First, you loop over string1 and mark all the characters with 1. I write simplified code, you can complete it.

char mark[255];
for(s=string1; s; s++) mark[*s]=1;

Next, you loop over string2 and check if the current char is marked.

for(s=string2; s; s++) if (!mark[*s]) printf("%c", *s);

This will print all chars from string2 that are not in string1.


问:
python __init__ method in inherited class
I would like to give a daughter class some extra attributes without having to explicitly call a new method. So is there a way of giving the inherited class an __init__ type method which does not override the __init__ method of the parent class?

I have written the code below purely to illustrate my question (hence the poor naming of attributes etc).

```<code>class initialclass():
    def __init__(self):
        self.attr1 = 'one'
        self.attr2 = 'two'

class inheritedclass(initialclass):
    def __new__(self):
        self.attr3 = 'three'

    def somemethod(self):
        print 'the method'

a = inheritedclass()

for each in a.__dict__:
    print each

#I would like the output to be:
attr1
attr2
attr3
</code>```

Thank you

答:
As far as I know that's not possible, however you can call the init method of the superclass, like this:</p>

```<code>class inheritedclass(initialclass):
    def __init__(self):
        initialclass.__init__(self)
        self.attr3 = 'three'
</code>```

Body:
I would like to give a daughter class some extra attributes without having to explicitly call a new method. So is there a way of giving the inherited class an __init__ type method which does not override the __init__ method of the parent class?

I have written the code below purely to illustrate my question (hence the poor naming of attributes etc).

class initialclass():
    def __init__(self):
        self.attr1 = 'one'
        self.attr2 = 'two'

class inheritedclass(initialclass):
    def __new__(self):
        self.attr3 = 'three'

    def somemethod(self):
        print 'the method'

a = inheritedclass()

for each in a.__dict__:
    print each

#I would like the output to be:
attr1
attr2
attr3

Thank you

Body:
As far as I know that's not possible, however you can call the init method of the superclass, like this:

class inheritedclass(initialclass):
    def __init__(self):
        initialclass.__init__(self)
        self.attr3 = 'three'


问:
How to rotate one vector on another?
I need to place vector b(p2, p3) on vector a(p1, p2)
Could you advise me some formula?

答:
If you need angle to rotate, calculate it as

```<code>dAx = P1.x - P2.x
dAy = P1.y - P2.y
dBx = P3.x - P2.x
dBy = P2.y - P2y
an = atan2(dAx * dBy - dAy * dBx, dAx * dBx + dAy * dBy)
</code>```

but your picture perhaps shows that you need to just make vector with length of P2P3 but collinear with P2P1. In this case:

-calculate length of both vectors

-find normalized direction vector for P2P1 - get it's component nad divide by vector length

-multiply components of normalized vector by length of P2P3

Title: How to rotate one vector on another?

Body:
If you need angle to rotate, calculate it as

dAx = P1.x - P2.x
dAy = P1.y - P2.y
dBx = P3.x - P2.x
dBy = P2.y - P2y
an = atan2(dAx * dBy - dAy * dBx, dAx * dBx + dAy * dBy)

but your picture perhaps shows that you need to just make vector with length of P2P3 but collinear with P2P1. In this case:

-calculate length of both vectors

-find normalized direction vector for P2P1 - get it's component nad divide by vector length

-multiply components of normalized vector by length of P2P3


问:
Regex digit range in SQL query
I need create SQl query with REGEXP function.

I need find serialize fields in (for example):

```<code>a:2:{s:5:"rooms";i:2;s:5:"area";i:4;}
a:2:{s:5:"rooms";i:2;s:5:"area";i:7;}
a:2:{s:5:"rooms";i:2;s:5:"area";i:18;}
</code>```

Where "area" value can be:

```<code>1-5 or 5-10 or 10-20 or 20-50 or 50-100
</code>```

I try use REGEXP .*"area";i:[1-5].* for first condition (1-5), but it shows wrong data. For other conditions also сan't make up.

答:
I think this regex should cover for your area value with your expectations:

```<code>("area";i:(?:(?!0)\d{1,2}|100)\b)
</code>```

Here is the regex101 link : Link Here

Title: Regex digit range in SQL query

Body:
I need create SQl query with REGEXP function.

I need find serialize fields in (for example):

a:2:{s:5:"rooms";i:2;s:5:"area";i:4;}
a:2:{s:5:"rooms";i:2;s:5:"area";i:7;}
a:2:{s:5:"rooms";i:2;s:5:"area";i:18;}

Where "area" value can be:

1-5 or 5-10 or 10-20 or 20-50 or 50-100

I try use REGEXP .*"area";i:[1-5].* for first condition (1-5), but it shows wrong data. For other conditions also сan't make up.

Body:
I think this regex should cover for your area value with your expectations:

("area";i:(?:(?!0)\d{1,2}|100)\b)

Here is the regex101 link : Link Here