问:
setState called everytime I type something in input
so i'm facing an issue where whenever I write something in input, handleCommentAdded is called which calls setState, re-rendering everything. This makes everything that is typed or was typed in the input to appear as comments and i want what is in the input when I click submit to appear as comment. How can I fix this?

```<code> class WriteComments extends React.Component {
      constructor(props) {
         super(props);
         this.state = {
         commentAdded:"",
       }
      this.handleButton = this.handleButton.bind(this);
      this.handleCommentAdded = this.handleCommentAdded.bind(this);
  }

  handleCommentAdded(event) {
    this.setState({newComment: event.target.value});
  }

  handleButton() {
    return(
       <div>
       {comment}
       </div>
   )
 }

render() {
  return(
<div>
 <input type="text" value={this.state.commentAdded} onChange=
   {this.handleCommentAdded}/>

 <div className="button">
    <button
        type="button"
        onClick={e => this.handleButton(e)}
     >
     Write
    </button>
  </div>
</code>```

   )
   }
   }

答:
Error is calling handleCommentAdded on onChange

set state in handleButton

class WriteComments extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      commentAdded: ""
    };
    this.inputRef = React.createRef();
    this.handleButton = this.handleButton.bind(this);
  }

  handleButton() {
    this.setState({ commentAdded: this.inputRef.current.value });
  }

  render() {
    return (

        <input type="text" ref={this.inputRef} />

          {this.state.commentAdded !== "" ? (

{this.state.commentAdded}

          ) : (
            <button type="button" onClick={e => this.handleButton(e)}>
              Write
            </button>
          )}

    );
  }
}

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

Body:
so i'm facing an issue where whenever I write something in input, handleCommentAdded is called which calls setState, re-rendering everything. This makes everything that is typed or was typed in the input to appear as comments and i want what is in the input when I click submit to appear as comment. How can I fix this?

 class WriteComments extends React.Component {
      constructor(props) {
         super(props);
         this.state = {
         commentAdded:"",
       }
      this.handleButton = this.handleButton.bind(this);
      this.handleCommentAdded = this.handleCommentAdded.bind(this);
  }

  handleCommentAdded(event) {
    this.setState({newComment: event.target.value});
  }

  handleButton() {
    return(

       {comment}

   )
 }

render() {
  return(

 <input type="text" value={this.state.commentAdded} onChange=
   {this.handleCommentAdded}/>

    <button
        type="button"
        onClick={e => this.handleButton(e)}
     >
     Write
    </button>

   )
   }
   }

Body:
Error is calling handleCommentAdded on onChange

set state in handleButton

class WriteComments extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      commentAdded: ""
    };
    this.inputRef = React.createRef();
    this.handleButton = this.handleButton.bind(this);
  }

  handleButton() {
    this.setState({ commentAdded: this.inputRef.current.value });
  }

  render() {
    return (
      <div>
        <input type="text" ref={this.inputRef} />

        <div className="button">
          {this.state.commentAdded !== "" ? (
            <div>{this.state.commentAdded}</div>
          ) : (
            <button type="button" onClick={e => this.handleButton(e)}>
              Write
            </button>
          )}
        </div>
      </div>
    );
  }
}

ReactDOM.render(<WriteComments />, document.getElementById('root'));

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


来源: stackexchange

问:
GWT: How to apply a CSS3 gradient
I was tasked to build the front-end of a web application and what I'm trying to do is to apply a CSS3 gradient on a Button. I'm using Eclipse with the GWT Plugin and I'm viewing the UI in Google Chrome with the GWT plugin.

My problem is that GWT seems to remove whitespaces in between the parenthesis so that:

```<code>.gwt-Button {
    background: -moz-linear-gradient(top, white, #72C6E4 4%, #0C5FA5);
    background:-webkit-gradient(linear, left top, left bottom, from(white), to(#0C5FA5), color-stop(0.03, #72C6E4));
</code>```

becomes:

```<code>.gwt-Button {
    background: -moz-linear-gradient(top,white,#72C6E44%,#0C5FA5);
    background:-webkit-gradient(linear,lefttop,lefbottom, from(white), to(#0C5FA5), color-stop(0.03, #72C6E4));
</code>```

Which makes them invalid. Is there another way to go about this or maybe a way to prevent the whitespaces from being removed when application is compiled? Thanks.

答:
You have to use the literal() function.  I believe it may only work with styles used via aCssResource as its a GWT function.

```<code>background: -webkit-gradient(linear, literal("left top"),
            literal("left bottom"), from(white), to(#0C5FA5) );
</code>```

I bugged this a while ago here but haven't gotten any response from the GWT team, so please Star it if you think its a valid bug.

Also, as a side note, those styles won't work with older versions of ie, you need to add the filter property.  Here's an example.

ContentLicense: CC BY-SA 3.0

Title: GWT: How to apply a CSS3 gradient

Body:
I was tasked to build the front-end of a web application and what I'm trying to do is to apply a CSS3 gradient on a Button. I'm using Eclipse with the GWT Plugin and I'm viewing the UI in Google Chrome with the GWT plugin.

My problem is that GWT seems to remove whitespaces in between the parenthesis so that:

.gwt-Button {
    background: -moz-linear-gradient(top, white, #72C6E4 4%, #0C5FA5);
    background:-webkit-gradient(linear, left top, left bottom, from(white), to(#0C5FA5), color-stop(0.03, #72C6E4));

becomes:

.gwt-Button {
    background: -moz-linear-gradient(top,white,#72C6E44%,#0C5FA5);
    background:-webkit-gradient(linear,lefttop,lefbottom, from(white), to(#0C5FA5), color-stop(0.03, #72C6E4));

Which makes them invalid. Is there another way to go about this or maybe a way to prevent the whitespaces from being removed when application is compiled? Thanks.

Body:
You have to use the literal() function.  I believe it may only work with styles used via aCssResource as its a GWT function.

background: -webkit-gradient(linear, literal("left top"),
            literal("left bottom"), from(white), to(#0C5FA5) );

I bugged this a while ago here but haven't gotten any response from the GWT team, so please Star it if you think its a valid bug.

Also, as a side note, those styles won't work with older versions of ie, you need to add the filter property.  Here's an example.


问:
Image position is moving when resizing image after rotating canvas
When Resizing image after rotation,image is misplacing or moving in canvas.

```<code>contextObj.save();
contextObj.translate(ImageX + ImageW / 2, ImageY + ImageH / 2);
contextObj.rotate(angle*Math.PI/180);
contextObj.translate(-(ImageX + ImageW / 2),-(ImageY + ImageH / 2));
contextObj.drawImage(myImage, ImageX, ImageY, ImageW, ImageH);
contextObj.restore();
</code>```

see this Issue here

Jsfiddle

i want to resize image without moving or misplace.

答:
```<code>contextObj.rotate(angle*Math.PI/0);
</code>```

Use this instead of

```<code> contextObj.rotate(angle*Math.PI/180);
</code>```

ContentLicense: CC BY-SA 4.0

Body:
When Resizing image after rotation,image is misplacing or moving in canvas.

contextObj.save();
contextObj.translate(ImageX + ImageW / 2, ImageY + ImageH / 2);
contextObj.rotate(angle*Math.PI/180);
contextObj.translate(-(ImageX + ImageW / 2),-(ImageY + ImageH / 2));
contextObj.drawImage(myImage, ImageX, ImageY, ImageW, ImageH);
contextObj.restore();

see this Issue here

Jsfiddle

i want to resize image without moving or misplace.

Body:
contextObj.rotate(angle*Math.PI/0);

Use this instead of

 contextObj.rotate(angle*Math.PI/180);


问:
Not able to show foreign key value
I am trying to create a Post and Comments sections, I managed to show all the posts in one page, now I'm trying to show the comments under each post. In my model, I have connected both tables and in my function I am able to view the post and comments when I use dd(); this is my result:

I am not sure if I'm calling the comment part correctly in my Views because I am getting error :

Property [activity_post_comments] does not exist on this collection instance.
  (View: C:\xampp\xampp\htdocs\rsapp\resources\views\pages\timeline.blade.php)

My function:

```<code>public function timeline()
{
    $activityposts = ActivityPost::with('activity_post_comment')
                                ->orderBy('created_at','desc')
                                ->paginate(100);

    $posts = Post::orderBy('created_at','desc')->paginate(100);

    // dd($activityposts);

    return view('pages.timeline')
            ->with('posts', $posts)
            ->with('activityposts', $activityposts);
}
</code>```

View:

```<code>@if(count($activityposts) > 0)
    @foreach($activityposts as $activitypost)
    <div class="panel panel-default">
        <!--
        <div class="panel-heading"><a href="#" class="pull-right">View all</a>
        <h4>Bootply Editor & Code Library</h4></div>
        -->
        <div class="panel-body">
            <p>
                <img src="../storage/user_image/{{ $activitypost->user->user_image }}" width="28px" height="28px">
                <b>{{ $activitypost->user->firstname }} {{ $activitypost->user->lastname }}</b>
                <span class="pull-right">{{ $activitypost->created_at->format('d-m-Y') }}</span>
            </p>
            <!--
                <div class="clearfix"></div>
                <hr>
            -->
            {{ $activitypost->status_update }}
            <hr>
            <div class="well">
                {{ $activitypost->activity_post_comments->activity_post_comments }};
            </div>
            <hr>
            <form class="form-horizontal" role="form" method="POST" enctype="multipart/form-data" action="{{ action('PagesController@storecomments', $activitypost->id) }}">
                {{ csrf_field() }}
                <div class="form-group{{ $errors->has('activity_post_comments') ? ' has-error' : '' }}">
                    <!-- <label for="activity_post_comments" class="col-md-4 control-label">First Name</label> -->
                    <div class="col-md-12">
                        <input id="activity_post_comments" type="text" class="form-control" name="activity_post_comments" required autofocus>
                        @if ($errors->has('activity_post_comments'))
                        <span class="help-block">
                        <strong>{{ $errors->first('activity_post_comments') }}</strong>
                        </span>
                        @endif
                    </div>
                </div>
                <button type="submit" class="btn btn-primary">Post</button>
            </form>
        </div>
    </div>
    @endforeach
{{$activityposts->links()}}
@else
<p>No new activity from users</p>
@endif
</code>```

Here is where I'm not sure :

```<code>{{ $activitypost->activity_post_comment->activity_post_comments }};
</code>```

答:
Since activity_post_comment would be a collection, you need to loop through the same to get individual instances.

```<code>@foreach ($activitypost->activity_post_comment as $comment)
<p>{{ $comment->activity_post_comments }}</p>
@endforeach
</code>```

Title: Not able to show foreign key value

Body:
I am trying to create a Post and Comments sections, I managed to show all the posts in one page, now I'm trying to show the comments under each post. In my model, I have connected both tables and in my function I am able to view the post and comments when I use dd(); this is my result:

I am not sure if I'm calling the comment part correctly in my Views because I am getting error :

Property [activity_post_comments] does not exist on this collection instance.
  (View: C:\xampp\xampp\htdocs\rsapp\resources\views\pages\timeline.blade.php)

My function:

public function timeline()
{
    $activityposts = ActivityPost::with('activity_post_comment')
                                ->orderBy('created_at','desc')
                                ->paginate(100);

    $posts = Post::orderBy('created_at','desc')->paginate(100);

    // dd($activityposts);

    return view('pages.timeline')
            ->with('posts', $posts)
            ->with('activityposts', $activityposts);
}

View:

@if(count($activityposts) > 0)
    @foreach($activityposts as $activitypost)

                user->user_image }}" width="28px" height="28px">
                {{ $activitypost->user->firstname }} {{ $activitypost->user->lastname }}
                {{ $activitypost->created_at->format('d-m-Y') }}

            {{ $activitypost->status_update }}

                {{ $activitypost->activity_post_comments->activity_post_comments }};

            <form class="form-horizontal" role="form" method="POST" enctype="multipart/form-data" action="{{ action('PagesController@storecomments', $activitypost->id) }}">
                {{ csrf_field() }}

has('activity_post_comments') ? ' has-error' : '' }}">

                        <input id="activity_post_comments" type="text" class="form-control" name="activity_post_comments" required autofocus>
                        @if ($errors->has('activity_post_comments'))

                        {{ $errors->first('activity_post_comments') }}

                        @endif

                <button type="submit" class="btn btn-primary">Post</button>
            </form>

    @endforeach
{{$activityposts->links()}}
@else

No new activity from users

@endif

Here is where I'm not sure :

{{ $activitypost->activity_post_comment->activity_post_comments }};

Body:
Since activity_post_comment would be a collection, you need to loop through the same to get individual instances.

@foreach ($activitypost->activity_post_comment as $comment)
<p>{{ $comment->activity_post_comments }}</p>
@endforeach


问:
Keep inactive nav-tab displayed when input inside of it has focus
I currentely working on a project with reactjs,and i would like to display error messages one by one using  link tag, this link may refer to a div, p, input, button whatever html element.

click the link, the appropriate html element should be focused and displayed.

the problem now,  is sometimes the target element is inside a hidden tab or div, and i can't focus it

for example inside an inactive tab, Is there any chance that I can make it active, then focus the element ?

here is a simple example :

function openCity(cityName) {
  var i;
  var x = document.getElementsByClassName("city");
  for (i = 0; i < x.length; i++) {
    x[i].style.display = "none";
  }
  document.getElementById(cityName).style.display = "block";
}

const findIt = () => {
  document
    .getElementById("target")
    .focus();
};```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.w3-container {
  margin-top:16px;
  margin-bottom:16px;
  }

 .w3-container:after,.w3-container:before {
   content:"";
   display:table;
   clear:both
 }

 .w3-bar .w3-bar-item{
   padding:8px 16px;
   float:left;
   width:auto;
   border:none;
   display:block;
   outline:0
}

.w3-black{
  color:#fff!important;
  background-color:#000!important
}

.w3-button{
  border:none;
  display:inline-block;
  padding:8px 16px;
  vertical-align:middle;
  overflow:hidden;
  text-decoration:none;
  color:inherit;
  background-color:inherit;
  text-align:center;
  cursor:pointer;
  white-space:nowrap
}

 </code>```

 3 Tabs below :

      <button class="w3-bar-item w3-button" onclick="openCity('London')">
        London
      </button>
      <button class="w3-bar-item w3-button" onclick="openCity('Paris')">
        Paris
      </button>
      <button class="w3-bar-item w3-button" onclick="openCity('Tokyo')">
        Tokyo
      </button>

London

London is the capital city of England.

Paris

      <input value="im ere ry o ind" id="target" />

Paris is the capital of France.

Tokyo

Tokyo is the capital of Japan.

    <button onclick="findIt()">click to focus input inside PARIS tab</button>

 ```

so it works only if Paris is active

答:
Alright so, this is the question I solved- I have made it so are able to use the input field in the Paris tab, even when the tab is not selected.

I would never recommend using display:none in css. It hides the element completely, and javascript requires every bit of scaffolding it can get in order to do its job correctly. Instead, you can create a class that visually hides the content, but keeps it rendered in code space. In this case, I created a css class that will hide all content in the div it is assigned to. This makes it so that the content can still be accessed by Javascript's selectors, but doesn't appear unless the class is removed. In the javascript file, all I a really doing is removing and adding the class to elements, the same way you used display:none.

For further reading, I would recommend reading the following topic on css-tricks:
https://css-tricks.com/forums/topic/is-display-none-the-right-way-to-hide-an-element/

function openCity(cityName) {
  var i;
  var x = document.getElementsByClassName("city");
  for (i = 0; i < x.length; i++) {
     x[i].classList.add("hidden-visually");
    }
  document.getElementById(cityName).classList.remove("hidden-visually");
}

const findIt = () => {
  document
    .getElementById("target")
    .focus();
};```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.hidden-visually{
  overflow: hidden;
  position: absolute;
  clip: rect(0 0 0 0);
}

.w3-container {
  margin-top:16px;
  margin-bottom:16px;
  }

 .w3-container:after,.w3-container:before {
   content:"";
   display:table;
   clear:both
 }

 .w3-bar .w3-bar-item{
   padding:8px 16px;
   float:left;
   width:auto;
   border:none;
   display:block;
   outline:0
}

.w3-black{
  color:#fff!important;
  background-color:#000!important
}

.w3-button{
  border:none;
  display:inline-block;
  padding:8px 16px;
  vertical-align:middle;
  overflow:hidden;
  text-decoration:none;
  color:inherit;
  background-color:inherit;
  text-align:center;
  cursor:pointer;
  white-space:nowrap
}</code>```

 3 Tabs below :

      <button class="w3-bar-item w3-button" onclick="openCity('London')">
        London
      </button>
      <button class="w3-bar-item w3-button" onclick="openCity('Paris')">
        Paris
      </button>
      <button class="w3-bar-item w3-button" onclick="openCity('Tokyo')">
        Tokyo
      </button>

London

London is the capital city of England.

Paris

      <input value="im ere ry o ind" id="target"/>

Paris is the capital of France.

Tokyo

Tokyo is the capital of Japan.

    <button onclick="findIt()">click to focus input inside PARIS tab</button>```

Body:
I currentely working on a project with reactjs,and i would like to display error messages one by one using  link tag, this link may refer to a div, p, input, button whatever html element.

click the link, the appropriate html element should be focused and displayed.

the problem now,  is sometimes the target element is inside a hidden tab or div, and i can't focus it

for example inside an inactive tab, Is there any chance that I can make it active, then focus the element ?

here is a simple example :

function openCity(cityName) {
  var i;
  var x = document.getElementsByClassName("city");
  for (i = 0; i < x.length; i++) {
    x[i].style.display = "none";
  }
  document.getElementById(cityName).style.display = "block";
}

const findIt = () => {
  document
    .getElementById("target")
    .focus();
};

.w3-container {
  margin-top:16px;
  margin-bottom:16px;
  }

 .w3-container:after,.w3-container:before {
   content:"";
   display:table;
   clear:both
 }

 .w3-bar .w3-bar-item{
   padding:8px 16px;
   float:left;
   width:auto;
   border:none;
   display:block;
   outline:0
}

.w3-black{
  color:#fff!important;
  background-color:#000!important
}

.w3-button{
  border:none;
  display:inline-block;
  padding:8px 16px;
  vertical-align:middle;
  overflow:hidden;
  text-decoration:none;
  color:inherit;
  background-color:inherit;
  text-align:center;
  cursor:pointer;
  white-space:nowrap
}

 3 Tabs below :

      <button class="w3-bar-item w3-button" onclick="openCity('London')">
        London
      </button>
      <button class="w3-bar-item w3-button" onclick="openCity('Paris')">
        Paris
      </button>
      <button class="w3-bar-item w3-button" onclick="openCity('Tokyo')">
        Tokyo
      </button>

London

London is the capital city of England.

Paris

      <input value="im ere ry o ind" id="target" />

Paris is the capital of France.

Tokyo

Tokyo is the capital of Japan.

    <button onclick="findIt()">click to focus input inside PARIS tab</button>

so it works only if Paris is active

Body:
Alright so, this is the question I solved- I have made it so are able to use the input field in the Paris tab, even when the tab is not selected.

I would never recommend using display:none in css. It hides the element completely, and javascript requires every bit of scaffolding it can get in order to do its job correctly. Instead, you can create a class that visually hides the content, but keeps it rendered in code space. In this case, I created a css class that will hide all content in the div it is assigned to. This makes it so that the content can still be accessed by Javascript's selectors, but doesn't appear unless the class is removed. In the javascript file, all I a really doing is removing and adding the class to elements, the same way you used display:none.

For further reading, I would recommend reading the following topic on css-tricks:
https://css-tricks.com/forums/topic/is-display-none-the-right-way-to-hide-an-element/

function openCity(cityName) {
  var i;
  var x = document.getElementsByClassName("city");
  for (i = 0; i < x.length; i++) {
     x[i].classList.add("hidden-visually");
    }
  document.getElementById(cityName).classList.remove("hidden-visually");
}

const findIt = () => {
  document
    .getElementById("target")
    .focus();
};

.hidden-visually{
  overflow: hidden;
  position: absolute;
  clip: rect(0 0 0 0);
}

.w3-container {
  margin-top:16px;
  margin-bottom:16px;
  }

 .w3-container:after,.w3-container:before {
   content:"";
   display:table;
   clear:both
 }

 .w3-bar .w3-bar-item{
   padding:8px 16px;
   float:left;
   width:auto;
   border:none;
   display:block;
   outline:0
}

.w3-black{
  color:#fff!important;
  background-color:#000!important
}

.w3-button{
  border:none;
  display:inline-block;
  padding:8px 16px;
  vertical-align:middle;
  overflow:hidden;
  text-decoration:none;
  color:inherit;
  background-color:inherit;
  text-align:center;
  cursor:pointer;
  white-space:nowrap
}

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="w3-container">
      <h2> 3 Tabs below :</h2>
    </div>

    <div class="w3-bar w3-black">
      <button class="w3-bar-item w3-button" onclick="openCity('London')">
        London
      </button>
      <button class="w3-bar-item w3-button" onclick="openCity('Paris')">
        Paris
      </button>
      <button class="w3-bar-item w3-button" onclick="openCity('Tokyo')">
        Tokyo
      </button>
    </div>

    <div id="London" class="w3-container city">
      <h2>London</h2>
      <p>London is the capital city of England.</p>
    </div>

    <div id="Paris" class="w3-container city hidden-visually">
      <h2>Paris</h2>
      <input value="im ere ry o ind" id="target"/>
      <p>Paris is the capital of France.</p>
    </div>

    <div id="Tokyo" class="w3-container city hidden-visually">
      <h2>Tokyo</h2>
      <p>Tokyo is the capital of Japan.</p>
    </div>
     <br /><br /><br />
    <button onclick="findIt()">click to focus input inside PARIS tab</button>


问:
Using an enum to define a list of keys on an interface
I want create a interface that has a dynamic list of keys, that are based on the values of an enum.

Basically, it would look something like this:

```<code>enum MyEnum {
    foo = "foo",
    bar ="bar"
}

interface MyInterface {  //A generic on this line
    id: string;
    objects: {
        [key: string] : string;   //Instead of mapping to string,
                                  // map to the values of the enum
    }
}

const x : MyInterface<MyEnum> = {
    id: "123",
    objects: {
        foo: "hello",
        bar: "world",
    }
}

//Now I can access the values with:
console.log(x.objects[MyEnum.foo]);

const y : MyInterface<MyEnum> = {
    id: "123",
    objects: {
        foo: "hello", //Should give typeScript warning - bar doesn't exist.
    }
}
</code>```

There are two things I don't know how to do here.

How do I define that a generic must be an enum type?

How would I do the dynamic keys list for the generic enum?

I'm happy to not use enums specifically if there is a handy solution that will do this.

Related reading:

This Typescript github issue: https://github.com/microsoft/TypeScript/issues/13042

If the answer is - 'This is not possible as...' can you please give a link to the best Github issue discussion(s) - and a summary of what the resolutions were? From the reading I have seen, this is a feature that a lot of people want.

Update: My current best solution involves creating an interface as the pseudo enum definition, and an implementation of that enum. Playground here. I'm not very happy with though.

答:
You can try with Type like below, also modified object type to Record<k,T>

```<code>type MyEnum = "foo" | "bar";

interface MyInterface<K extends MyEnum, T> {
    id: string;
    objects: Record<K, T>;
}

const x: MyInterface<MyEnum, string> = {
    id: "123",
    objects: {
        foo: "hello",
        bar: "world"
    }
};

//Now I can access the values with:
console.log(x.objects.notAvailable); // Property 'notAvailable' does not exist on type 'Record<MyEnum, string>'
console.log(x.objects.foo); //ok

const y: MyInterface<MyEnum, string> = {
    id: "123",
    objects: {
        foo: "hello" //Should give typeScript warning - bar doesn't exist.
    }
};
</code>```

(or) with Enum

```<code>enum MyEnum {
    "foo" = "foo",
    "bar" = "bar"
}

interface MyInterface<K extends MyEnum, T> {
    id: string;
    objects: Record<K, T>;
}

const x: MyInterface<MyEnum, string> = {
    id: "123",
    objects: {
        foo: "hello",
        bar: "world"
    }
};

//Now I can access the values with:
console.log(x.objects.notAvailable); // Property 'notAvailable' does not exist on type 'Record<MyEnum, string>'
console.log(x.objects.bar); //ok

const y: MyInterface<MyEnum, string> = {
    id: "123",
    objects: {
        foo: "hello" //Should give typeScript warning - bar doesn't exist.
    }
};
</code>```

Body:
I want create a interface that has a dynamic list of keys, that are based on the values of an enum.

Basically, it would look something like this:

enum MyEnum {
    foo = "foo",
    bar ="bar"
}

interface MyInterface {  //A generic on this line
    id: string;
    objects: {
        [key: string] : string;   //Instead of mapping to string,
                                  // map to the values of the enum
    }
}

const x : MyInterface<MyEnum> = {
    id: "123",
    objects: {
        foo: "hello",
        bar: "world",
    }
}

//Now I can access the values with:
console.log(x.objects[MyEnum.foo]);

const y : MyInterface<MyEnum> = {
    id: "123",
    objects: {
        foo: "hello", //Should give typeScript warning - bar doesn't exist.
    }
}

There are two things I don't know how to do here.

How do I define that a generic must be an enum type?

How would I do the dynamic keys list for the generic enum?

I'm happy to not use enums specifically if there is a handy solution that will do this.

Related reading:

This Typescript github issue: https://github.com/microsoft/TypeScript/issues/13042

If the answer is - 'This is not possible as...' can you please give a link to the best Github issue discussion(s) - and a summary of what the resolutions were? From the reading I have seen, this is a feature that a lot of people want.

Update: My current best solution involves creating an interface as the pseudo enum definition, and an implementation of that enum. <a href="https://www.typescriptlang.org/play/#src=%0D%0Ainterface%20GenericEnum%20%7B%0D%0A%20%20%20%20%5Bkey%3A%20string%5D%3A%20string%3B%20%0D%0A%7D%0D%0A%0D%0Ainterface%20SomeObject%3CT%20extends%20GenericEnum%3E%20%7B%0D%0A%0D%0A%20%20%20%20id%3A%20string%3B%20%0D%0A%20%20%20%20name%3A%20string%3B%20%0D%0A%20%20%20%20objects%3A%20%7B%0D%0A%20%20%20%20%20%20%20%20%5Bkey%20in%20keyof%20T%5D%20%3A%20string%0D%0A%20%20%20%20%7D%0D%0A%20%20%20%20value%3A%20keyof%20T%3B%20%0D%0A%7D%0D%0A%0D%0Ainterface%20MyGenericEnumDef%20extends%20GenericEnum%20%7B%0D%0A%20%20%20%20alpha%3A%20%22alpha%22%3B%20%0D%0A%20%20%20%20beta%3A%20%22beta%22%3B%20%0D%0A%7D%0D%0A%0D%0Aconst%20MyGenericEnum%20%3A%20MyGenericEnumDef%20%3D%20%7B%0D%0A%20%20%20%20alpha%3A%20%22alpha%22%2C%20%0D%0A%20%20%20%20beta%3A%20%22beta%22%0D%0A%7D%0D%0A%0D%0Aconst%20x%3A%20SomeObject%3CMyGenericEnumDef%3E%20%3D%20%7B%0D%0A%20%20%20%20id%3A%20%22foo%22%2C%20%0D%0A%20%20%20%20name%3A%20%22bar%22%2C%20%0D%0A%20%20%20%20objects%3A%20%7B%0D%0A%20%20%20%20%20%20%20%20alpha%3A%20%22hello%22%2C%20%0D%0A%20%20%20%20%20%20%20%20beta%3A%20%22world%22%2C%20%0D%0A%20%20%20%20%7D%2C%20%0D%0A%20%20%20%20value%3A%20MyGenericEnum.alpha%0D%0A%7D%0D%0A%0D%0A" rel="nofollow noreferrer">Playground here. I'm not very happy with though.

Body:
You can try with Type like below, also modified object type to Record<k,T>

type MyEnum = "foo" | "bar";

interface MyInterface<K extends MyEnum, T> {
    id: string;
    objects: Record<K, T>;
}

const x: MyInterface<MyEnum, string> = {
    id: "123",
    objects: {
        foo: "hello",
        bar: "world"
    }
};

//Now I can access the values with:
console.log(x.objects.notAvailable); // Property 'notAvailable' does not exist on type 'Record<MyEnum, string>'
console.log(x.objects.foo); //ok

const y: MyInterface<MyEnum, string> = {
    id: "123",
    objects: {
        foo: "hello" //Should give typeScript warning - bar doesn't exist.
    }
};

(or) with Enum

enum MyEnum {
    "foo" = "foo",
    "bar" = "bar"
}

interface MyInterface<K extends MyEnum, T> {
    id: string;
    objects: Record<K, T>;
}

const x: MyInterface<MyEnum, string> = {
    id: "123",
    objects: {
        foo: "hello",
        bar: "world"
    }
};

//Now I can access the values with:
console.log(x.objects.notAvailable); // Property 'notAvailable' does not exist on type 'Record<MyEnum, string>'
console.log(x.objects.bar); //ok

const y: MyInterface<MyEnum, string> = {
    id: "123",
    objects: {
        foo: "hello" //Should give typeScript warning - bar doesn't exist.
    }
};


问:
I want to limit the pdf file size uploaded to firebase storage. I want that user can upload a file with maximum size of 7MB
I want put a limitation on firebase storage. That is user can upload a pdf file of maximum size of 7MB. And How can i reduce the size of pdf file? is there any way in android.

I don't know the solution of my question. I find a lot but doesn't get my answer.
Can someone help me with firebase security rules? I am not familiar with that doesn't find any answer about this.

答: Retrofit allows you to upload certain size only at a single time. This site has detailed tutorial from basic to complicated series of articles.</p>


问:
Add value to dynamically populated list c#
I'm constructing a web page based on ASN.NET MVC3 with Razor templates and Entity. The task is to populate a @Html.DropDownList from the database, so far so good but now I want to insert a static value in the DropDownList.

The code looks as follows

The create method

```<code>public ActionResult Create()
{
    var parents = db.Organizations.OrderBy(o => o.Title).ToList();
    var organization = new Organization();
    return View(organization);
}
</code>```

Extract from the Razor template

```<code><div class="editor-field">
    @Html.DropDownList("ParentGuid",
    new SelectList(ViewBag.Organizations as System.Collections.IEnumerable,
    "ParentGuid", "Title", Model.ParentGuid))
</div>
</code>```

So, the above code works but Im stuck in figuring out how to insert an empty row in the dropdown.

答:
You could recreate the array previous to adding it to the list.  Something like this:

```<code>List<SelectListItem> itms = new List<SelectListItem>();

var blank = new SelectListItem();
blank.Selected = true;
itms.Add(blank);

foreach (var stat in model)
{
    var s = new SelectListItem();
    s.Text = stat.Text;
    s.Value = stat.FeedBackTypeID + "";

    itms.Add(s);
}
</code>```

and then use that

Body:
I'm constructing a web page based on ASN.NET MVC3 with Razor templates and Entity. The task is to populate a @Html.DropDownList from the database, so far so good but now I want to insert a static value in the DropDownList.

The code looks as follows

The create method

public ActionResult Create()
{
    var parents = db.Organizations.OrderBy(o => o.Title).ToList();
    var organization = new Organization();
    return View(organization);
}

Extract from the Razor template

    @Html.DropDownList("ParentGuid",
    new SelectList(ViewBag.Organizations as System.Collections.IEnumerable,
    "ParentGuid", "Title", Model.ParentGuid))

So, the above code works but Im stuck in figuring out how to insert an empty row in the dropdown.

Body:
You could recreate the array previous to adding it to the list.  Something like this:

List<SelectListItem> itms = new List<SelectListItem>();

var blank = new SelectListItem();
blank.Selected = true;
itms.Add(blank);

foreach (var stat in model)
{
    var s = new SelectListItem();
    s.Text = stat.Text;
    s.Value = stat.FeedBackTypeID + "";

    itms.Add(s);
}

and then use that


问:
Python Pickle object in Django model
I would like to know what would be the simplest way to store pickle objects in PostgreSQL DB using Django ORM.</p>

答:
I will not comment on wether or not it's wise to use pickled data in the database. But you can use the django-picklefield library to store pickled data:

https://pypi.org/project/django-picklefield/

Title: Python Pickle object in Django model


问:
How do I slow down my custom Javascript extension without slowing down the webpage?
I have a custom javascript extension that solves a survey on a website. Unfortunately, it works a little too well - it checks the check box and hits next too fast. The website detects this, realizes it's a bot that's solving the survey, and sends an Error, saying that there's too many requests. What code can I use to slow down my extension that won't stop the website?

I've specifically tried to use a sleep() function that I wrote myself which basically stalls the javascript program entirely. I just write a quick "sleep(1500)" before the checkBox method. This actually ends up stopping the javascript on the entire page, which is the exact opposite of what I want.

```<code>function sleep(delay) {
    var start = new Date().getTime();
    while (new Date().getTime() < start + delay);
}
</code>```

I'm aiming to have the extension wait roughly 3 to 4 seconds before checking the box and hitting next, after which, it'll wait another 3 to 4 seconds, etc. The actual thing that happens is that before the fancy animation for the checkboxes that the webpage has finishes, the extension's already checked the right box and has hit next. As stated, this is way too fast. Basically, I want to stall the extension for 3 seconds, while letting the javascript on the webpage continue working.

答:
There are three ways you can achieve this.

The first way is to skip making a sleep() function and instead just use setTimeout().

// code before wait
setTimeout(()=>{
    // code after wait
}, 1500);
```

<p>Another way is to use async/await as shown below.</p>

<pre class="lang-js prettyprint-override"><code>// Promises require async/await to work in JavaScript
async function sleep(ms) {
    return new Promise(resolve => {
        setTimeout(resolve, ms); // this will call the resolve() function after the time has passed
    });
}

// You cannot use await in a non-async function, be sure to change that before adding this
await sleep(1500);
</code>```

However, async/await is not supported in IE, so if you are looking to support it the best way is to use setInterval(). The interval must be assigned to a variable, otherwise you cannot stop it and may cause some issues.

function sleep(ms, todo) {
    var started = Date.now(); // get current time before wait
    var temp = setInterval(()=>{
        if ((Date.now() - started) > 1500) {
            clearInterval(temp); // stops the interval from repeating
            // avoid "X is not a function" errors
            if (typeof todo === 'function') todo(); // perform the code to do after the wait
        }
    }, 50);
}

// your code before the sleep function

sleep(1500, function() {
    // the code after the sleep function
});
```

Body:
I have a custom javascript extension that solves a survey on a website. Unfortunately, it works a little too well - it checks the check box and hits next too fast. The website detects this, realizes it's a bot that's solving the survey, and sends an Error, saying that there's too many requests. What code can I use to slow down my extension that won't stop the website?

I've specifically tried to use a sleep() function that I wrote myself which basically stalls the javascript program entirely. I just write a quick "sleep(1500)" before the checkBox method. This actually ends up stopping the javascript on the entire page, which is the exact opposite of what I want.

function sleep(delay) {
    var start = new Date().getTime();
    while (new Date().getTime() < start + delay);
}

I'm aiming to have the extension wait roughly 3 to 4 seconds before checking the box and hitting next, after which, it'll wait another 3 to 4 seconds, etc. The actual thing that happens is that before the fancy animation for the checkboxes that the webpage has finishes, the extension's already checked the right box and has hit next. As stated, this is way too fast. Basically, I want to stall the extension for 3 seconds, while letting the javascript on the webpage continue working.

Body:
There are three ways you can achieve this.

The first way is to skip making a sleep() function and instead just use setTimeout().

// code before wait
setTimeout(()=>{
    // code after wait
}, 1500);

Another way is to use async/await as shown below.

// Promises require async/await to work in JavaScript
async function sleep(ms) {
    return new Promise(resolve => {
        setTimeout(resolve, ms); // this will call the resolve() function after the time has passed
    });
}

// You cannot use await in a non-async function, be sure to change that before adding this
await sleep(1500);

However, async/await is not supported in IE, so if you are looking to support it the best way is to use setInterval(). The interval must be assigned to a variable, otherwise you cannot stop it and may cause some issues.

function sleep(ms, todo) {
    var started = Date.now(); // get current time before wait
    var temp = setInterval(()=>{
        if ((Date.now() - started) > 1500) {
            clearInterval(temp); // stops the interval from repeating
            // avoid "X is not a function" errors
            if (typeof todo === 'function') todo(); // perform the code to do after the wait
        }
    }, 50);
}

// your code before the sleep function

sleep(1500, function() {
    // the code after the sleep function
});


问:
WxPython: type object 'Test' has no attribute 'openReportButton'
I'm trying to enable a button on click of another button but it keeps giving me this error (see title)

```<code>class Test(wx.Frame):
    def __init__(self,parent,id):
        wx.Frame.__init__(self,parent,id, "Frame aka Window", style= wx.SYSTEM_MENU | wx.CAPTION | wx.CLOSE_BOX | wx.MINIMIZE_BOX, size=(400, 635))

        loadData = wx.Button(panel, label="Load Data", size = (100,40))
        loadData.SetFont(font)
        self.Bind(wx.EVT_BUTTON, self.loadData, loadData)

        openReportButton = wx.Button(panel, label = "Open Report", size = (100,40))
        openReportButton.SetFont(font)
        openReportButton.Disable()
        self.Bind(wx.EVT_BUTTON, self.openReport, openReportButton)

    def loadData(self, event):
        self.openReportButton.Enable()
</code>```

What am I missing here?

Thank you,

答:
You need to make openReportButton an instance attribute (instead of just a local variable)

```<code>class Test(wx.Frame):
    def __init__(self,parent,id):
        wx.Frame.__init__(self,parent,id, "Frame aka Window", style= wx.SYSTEM_MENU | wx.CAPTION | wx.CLOSE_BOX | wx.MINIMIZE_BOX, size=(400, 635))

        loadData = wx.Button(panel, label="Load Data", size = (100,40))
        loadData.SetFont(font)
        self.Bind(wx.EVT_BUTTON, self.loadData, loadData)
        # added "self."
        self.openReportButton = wx.Button(panel, label = "Open Report", size = (100,40))
        self.openReportButton.SetFont(font)
        self.openReportButton.Disable()
        self.Bind(wx.EVT_BUTTON, self.openReport, openReportButton)

    def loadData(self, event):
        self.openReportButton.Enable()
</code>```

Body:
I'm trying to enable a button on click of another button but it keeps giving me this error (see title)

class Test(wx.Frame):
    def __init__(self,parent,id):
        wx.Frame.__init__(self,parent,id, "Frame aka Window", style= wx.SYSTEM_MENU | wx.CAPTION | wx.CLOSE_BOX | wx.MINIMIZE_BOX, size=(400, 635))

        loadData = wx.Button(panel, label="Load Data", size = (100,40))
        loadData.SetFont(font)
        self.Bind(wx.EVT_BUTTON, self.loadData, loadData)

        openReportButton = wx.Button(panel, label = "Open Report", size = (100,40))
        openReportButton.SetFont(font)
        openReportButton.Disable()
        self.Bind(wx.EVT_BUTTON, self.openReport, openReportButton)

    def loadData(self, event):
        self.openReportButton.Enable()

What am I missing here?

Thank you,

Body:
You need to make openReportButton an instance attribute (instead of just a local variable)

class Test(wx.Frame):
    def __init__(self,parent,id):
        wx.Frame.__init__(self,parent,id, "Frame aka Window", style= wx.SYSTEM_MENU | wx.CAPTION | wx.CLOSE_BOX | wx.MINIMIZE_BOX, size=(400, 635))

        loadData = wx.Button(panel, label="Load Data", size = (100,40))
        loadData.SetFont(font)
        self.Bind(wx.EVT_BUTTON, self.loadData, loadData)
        # added "self."
        self.openReportButton = wx.Button(panel, label = "Open Report", size = (100,40))
        self.openReportButton.SetFont(font)
        self.openReportButton.Disable()
        self.Bind(wx.EVT_BUTTON, self.openReport, openReportButton)

    def loadData(self, event):
        self.openReportButton.Enable()


问:
Firebase realtime db multipath update fails
I'm trying to perform a multipath update on a firebase realtime db using a cloud function (js sdk). Update parameters are constructed through a forEach loop. The update fails with following error message :

Error: Reference.update failed: First argument  must be an object containing the children to replace.

I might be close to the solution considering the console.log :

[{"-LfzkTClUxC9J5y3Ue95/mood/sun":{"value":-75,"votecount":-1},"-LfzkTClUxC9J5y3Ue95/mood/rain":{"value":"7550","votecount":1}},
...
{"-LfzoAT7fPzhWsMpEU7t/mood/sun":{"value":0,"votecount":-1},"-LfzoAT7fPzhWsMpEU7t/mood/rain":{"value":"050","votecount":1}}].

This is my cloud function :

```<code>exports.updateGroupMood = functions.database.ref('users/{userId}/mood/')
.onUpdate((change, context) => {

const userId = context.params.userId //previous data
const beforeData = change.before.val()  //current data
const afterData = change.after.val()
const userGroups = admin.database().ref('/users/' + userId +
'/groups/social/Items'); //user groups to update

return userGroups.once("value")
.then(function(snapshot) {

var updateParams = []

snapshot.forEach(function(childSnapshot){

  const itemId = childSnapshot.key //id of group to update
  const moodRef = admin.database().ref('/groups/social/Items/' + itemId + '/mood/'); //node to update

  var promise = moodRef.once("value").then(function(snapshot) { //get values to update

    const objVal = snapshot.val()

    const previousMood = { // decrement previous values
      value:objVal[beforeData.element].value - beforeData.value,
      votecount:objVal[beforeData.element].votecount - 1,
    }
    const currentMood = { // increment new values
      value:objVal[afterData.element].value + afterData.value,
      votecount: objVal[afterData.element].votecount + 1,
    }

    const newMood = { // update params definition
      [itemId + '/mood/' + beforeData.element]: previousMood,
      [itemId + '/mood/' + afterData.element]: currentMood,
    }
    return newMood

  });
  // construct update params
  updateParams.push(promise);

});
//get update params
return Promise.all(updateParams);
}).then(function(values) {

console.log(JSON.stringify(values)); //cf console.log in text above

const updateObj = admin.database().ref('/groups/social/Items/')

//update nodes
updateObj.update(JSON.stringify(values))
})
})
</code>```

答:
You're passing in a JSON string of the updates, while you should actually be passing in the updates:</p>

```<code>updateObj.update(values)
</code>```

Body:
I'm trying to perform a multipath update on a firebase realtime db using a cloud function (js sdk). Update parameters are constructed through a forEach loop. The update fails with following error message :

Error: Reference.update failed: First argument  must be an object containing the children to replace.

I might be close to the solution considering the console.log :

[{"-LfzkTClUxC9J5y3Ue95/mood/sun":{"value":-75,"votecount":-1},"-LfzkTClUxC9J5y3Ue95/mood/rain":{"value":"7550","votecount":1}},
...
{"-LfzoAT7fPzhWsMpEU7t/mood/sun":{"value":0,"votecount":-1},"-LfzoAT7fPzhWsMpEU7t/mood/rain":{"value":"050","votecount":1}}].

This is my cloud function :

exports.updateGroupMood = functions.database.ref('users/{userId}/mood/')
.onUpdate((change, context) => {

const userId = context.params.userId //previous data
const beforeData = change.before.val()  //current data
const afterData = change.after.val()
const userGroups = admin.database().ref('/users/' + userId +
'/groups/social/Items'); //user groups to update

return userGroups.once("value")
.then(function(snapshot) {

var updateParams = []

snapshot.forEach(function(childSnapshot){

  const itemId = childSnapshot.key //id of group to update
  const moodRef = admin.database().ref('/groups/social/Items/' + itemId + '/mood/'); //node to update

  var promise = moodRef.once("value").then(function(snapshot) { //get values to update

    const objVal = snapshot.val()

    const previousMood = { // decrement previous values
      value:objVal[beforeData.element].value - beforeData.value,
      votecount:objVal[beforeData.element].votecount - 1,
    }
    const currentMood = { // increment new values
      value:objVal[afterData.element].value + afterData.value,
      votecount: objVal[afterData.element].votecount + 1,
    }

    const newMood = { // update params definition
      [itemId + '/mood/' + beforeData.element]: previousMood,
      [itemId + '/mood/' + afterData.element]: currentMood,
    }
    return newMood

  });
  // construct update params
  updateParams.push(promise);

});
//get update params
return Promise.all(updateParams);
}).then(function(values) {

console.log(JSON.stringify(values)); //cf console.log in text above

const updateObj = admin.database().ref('/groups/social/Items/')

//update nodes
updateObj.update(JSON.stringify(values))
})
})

Body:
You're passing in a JSON string of the updates, while you should actually be passing in the updates:

updateObj.update(values)


问:
My app downloads decreased very unexpectedly more than 10x times
My android app was going satisfactory since 5-6 months and since a month the downloads has decreased so much dramatically that it is very frustrating and depressing. I neither updated the app nor made any changes to app's page since 3 months. Android vital are good, just about 0.3% of both ANR and Crashes and all downloads that came are organic ones till now. I even checked the keywords and ranks are as usual. My app shows on search with keyword like (App Name) + (Developer Name (removing last 's' alphabet) ), but not with (App Name)+ (Developer Name).

For eg- shows with "Music Player Sonic app" where "Music Player" is app name and "Sonic apps" is developer name.

But does not show with "Music Player Sonic apps". This used to show before this incident happened.

I heard many developers faced it and happened a year ago too. Now this year I have faced it, did those developer recover from this event last year. I don't know what to do as this is only source of income for my living. Please see the image too. Any words will be highly appreciated.
(One thing I notice is "Similar apps" section is not shown in home page of my app where as for other its shows. )

答:
I'm sorry for you , this is the worst nightmare to any app developer , but this is not the end . for the reason , there are a lot of reasons to why your app downloads are decreasing

Algorithm Changes

Low-Quality App

Poor Monetization

Neglected ASO

New Competitors

Keyword Shifts

Black Hat Practices

for more information please check this link


问:
Sequlize beforeCreated hook with a condition
In my user model I've define a lifecycle hook for encrypt the password with bycrypt.

```<code>beforeCreate: function(acc, next) {
    const salt = bcrypt.genSaltSync(10);
    const hash = bcrypt.hashSync(acc.password, salt);
    acc.password = hash;
}
</code>```

This works perfectly. But now I implement Oauth google login to the project. In that case I want to bypass this hook.

```<code>if (acc.password) {
    encrypt();
} else {
    skip();
}
</code>```

I tried this

```<code>hooks: {
    beforeCreate: function(acc, next) {
        if (acc.password) {
            const salt = bcrypt.genSaltSync(10);
            const hash = bcrypt.hashSync(acc.password, salt);
            acc.password = hash;
        } else {
            return next
        }
    }
}
</code>```

But this seems not work.

How do I skip the hook when req.body doesn't provide the password property.

答: You need to call next as a method like so: next().

Body:
In my user model I've define a lifecycle hook for encrypt the password with bycrypt.

beforeCreate: function(acc, next) {
    const salt = bcrypt.genSaltSync(10);
    const hash = bcrypt.hashSync(acc.password, salt);
    acc.password = hash;
}

This works perfectly. But now I implement Oauth google login to the project. In that case I want to bypass this hook.

if (acc.password) {
    encrypt();
} else {
    skip();
}

I tried this

hooks: {
    beforeCreate: function(acc, next) {
        if (acc.password) {
            const salt = bcrypt.genSaltSync(10);
            const hash = bcrypt.hashSync(acc.password, salt);
            acc.password = hash;
        } else {
            return next
        }
    }
}

But this seems not work.

How do I skip the hook when req.body doesn't provide the password property.


问:
.Net hanging on HttpResponseMessage.Content.ReadAsAsync()
I have a WPF application (.Net Framework 4.8) which calls a RESTful web api to retrieve some data from a database (Web Api written in ASP .Net Core 2.2)

Code:

```<code>private HttpClient client = new HttpClient();

private async Task<List<DataPacket>> GetNewDataAsync()
        {
            string uri = $"{apiUrl}/readings";

            HttpResponseMessage response = await client.GetAsync(uri);

            if (response.IsSuccessStatusCode)
            {
                List<DataPacket> data = await response.Content.ReadAsAsync<List<DataPacket>>();
                return data;
            }

            return null;
        }
</code>```

When I execute this program, it hangs on the following line:

```<code>List<DataPacket> data = await response.Content.ReadAsAsync<List<DataPacket>>();
</code>```

I'm not sure what I'm doing wrong. Any ideas?

答: The problem was that I didn't have await when calling this function.</p>

Body:
I have a WPF application (.Net Framework 4.8) which calls a RESTful web api to retrieve some data from a database (Web Api written in ASP .Net Core 2.2)

Code:

private HttpClient client = new HttpClient();

private async Task<List<DataPacket>> GetNewDataAsync()
        {
            string uri = $"{apiUrl}/readings";

            HttpResponseMessage response = await client.GetAsync(uri);

            if (response.IsSuccessStatusCode)
            {
                List<DataPacket> data = await response.Content.ReadAsAsync<List<DataPacket>>();
                return data;
            }

            return null;
        }

When I execute this program, it hangs on the following line:

List<DataPacket> data = await response.Content.ReadAsAsync<List<DataPacket>>();

I'm not sure what I'm doing wrong. Any ideas?


问:
*ngfor not display any data in Angular7
I 'm using angular7 , and here is my code :
in component.ts

import { Component, OnInit } from "@angular/core";
import { FocusAreasService } from "../../services/focus-areas.service";

@Component({
  selector: "app-about",
  templateUrl: "./about.component.html",
  styleUrls: ["./about.component.scss"]
})
export class AboutComponent implements OnInit {
  public canonical: string;
  public RsFocusArea: any[];
  constructor(public focusareaService: FocusAreasService) {}

  ngOnInit() {
    this.canonical = document.location.origin;

    this.focusareaService.getFocusAreaDataWithHttpClient2().subscribe({
      next(response) {
        console.log("HttpClient handle data");
        console.dir(response);

        this.RsFocusArea = response["focusArea"];
       //I print this.RsFocusArea here , it has values
        console.log("this.RsFocusArea");
        console.dir(this.RsFocusArea);
      },
      error(err) {
        console.error("Error: " + err);
      },
      complete() {
        console.log("Completed");
      }
    });
  }
}

}
```

<p>and in .html</p>

<pre class="lang-html prettyprint-override"><code> <ul class="col-xs-12 row">
        <li *ngFor="let area of RsFocusArea" class="col-xs-12 col-sm-6 col-md-4">{{area}}
        </li>
      </ul>
</code>```

and the li tage did not repeat and gave me this in tag structure:

```

Is there anything wrong with my code? I thought maybe I need to rerender the page when I assign new value to RsFocusArea in ngOnInit?

答:
```<code>RsFocusArea = [1, 2, 3];
</code>```

In Template :

```<code><li *ngFor="let area of RsFocusArea" class="col-xs-12 col-sm-6 col-md-4">
     {{area}}
</li>
</code>```

https://angular-bchmnn.stackblitz.io

Hope, it will solve your problem.

Title: *ngfor not display any data in Angular7

Body:
I 'm using angular7 , and here is my code :
in component.ts

import { Component, OnInit } from "@angular/core";
import { FocusAreasService } from "../../services/focus-areas.service";

@Component({
  selector: "app-about",
  templateUrl: "./about.component.html",
  styleUrls: ["./about.component.scss"]
})
export class AboutComponent implements OnInit {
  public canonical: string;
  public RsFocusArea: any[];
  constructor(public focusareaService: FocusAreasService) {}

  ngOnInit() {
    this.canonical = document.location.origin;

    this.focusareaService.getFocusAreaDataWithHttpClient2().subscribe({
      next(response) {
        console.log("HttpClient handle data");
        console.dir(response);

        this.RsFocusArea = response["focusArea"];
       //I print this.RsFocusArea here , it has values
        console.log("this.RsFocusArea");
        console.dir(this.RsFocusArea);
      },
      error(err) {
        console.error("Error: " + err);
      },
      complete() {
        console.log("Completed");
      }
    });
  }
}

}

and in .html

{{area}}

and the li tage did not repeat and gave me this in tag structure:

Is there anything wrong with my code? I thought maybe I need to rerender the page when I assign new value to RsFocusArea in ngOnInit?

Body:
RsFocusArea = [1, 2, 3];

In Template :

<li *ngFor="let area of RsFocusArea" class="col-xs-12 col-sm-6 col-md-4">
     {{area}}
</li>

https://angular-bchmnn.stackblitz.io

Hope, it will solve your problem.


问:
Using "umlauts" in C++ code

Possible Duplicate:

  C++ source in unicode

I just discovered this line of code in a project:

```<code>string überwachung;
</code>```

I was surprised, because actually I thought you are not allowed to use umlauts like 'äöü' in C++ code other than in strings and so on, and it would result in a compiler error. But this compiles just fine with visual studio 2008.

Is this a special microsoft feature, or are umlauts allowed with other compilers too?

Are there any potential problems with that (portability,system language settings..)?

I can clearly remember this was not allowed. When did it change?

Kind regards for any clarification

P.S.: the tool cppcheck will even mark this usage as an error, even though it compiles

答:
This would be allowed by the standard if and only if your editor was translating from the character with an umlaut (or other diacritical) into one of the allowed characters. In particular, an identifier in C++ is defined as:

```<code>identifier:
    nondigit
    identifier nondigit
    identifier digit

nondigit: one of
    universal-character-name
    _ a b c d e f g h i j k l m
      n o p q r s t u v w x y z
      A B C D E F G H I J K L M
      N O P Q R S T U V W X Y Z
</code>```

As far as I can see, that doesn't allow characters with diacriticals (except as a UCN). It looks to me like a compiler is required to issue at least one diagnostic for a program that contains any character other than those above (though it is still allowed to translate the program). Doing a quick check, I haven't been able to find a compiler flag that gets VC++ to issue a diagnostic for this code. At least IMO, it fails to conform in this respect.

On the other hand, this could just be viewed as VC++ implementing one of the new features of C++11. At least as of N3242, the new C++ draft adds a new item after the table above: "other implementation-defined characters". This gives the compiler permission to accept any other characters it wants to (though it is supposed to document what they are).

Title: Using "umlauts" in C++ code

Body:
Possible Duplicate:

  C++ source in unicode

I just discovered this line of code in a project:

string überwachung;

I was surprised, because actually I thought you are not allowed to use umlauts like 'äöü' in C++ code other than in strings and so on, and it would result in a compiler error. But this compiles just fine with visual studio 2008.

Is this a special microsoft feature, or are umlauts allowed with other compilers too?

Are there any potential problems with that (portability,system language settings..)?

I can clearly remember this was not allowed. When did it change?

Kind regards for any clarification

P.S.: the tool cppcheck will even mark this usage as an error, even though it compiles

Body:
This would be allowed by the standard if and only if your editor was translating from the character with an umlaut (or other diacritical) into one of the allowed characters. In particular, an identifier in C++ is defined as:

identifier:
    nondigit
    identifier nondigit
    identifier digit

nondigit: one of
    universal-character-name
    _ a b c d e f g h i j k l m
      n o p q r s t u v w x y z
      A B C D E F G H I J K L M
      N O P Q R S T U V W X Y Z

As far as I can see, that doesn't allow characters with diacriticals (except as a UCN). It looks to me like a compiler is required to issue at least one diagnostic for a program that contains any character other than those above (though it is still allowed to translate the program). Doing a quick check, I haven't been able to find a compiler flag that gets VC++ to issue a diagnostic for this code. At least IMO, it fails to conform in this respect.

On the other hand, this could just be viewed as VC++ implementing one of the new features of C++11. At least as of N3242, the new C++ draft adds a new item after the table above: "other implementation-defined characters". This gives the compiler permission to accept any other characters it wants to (though it is supposed to document what they are).


问:
Same values does not match in if condition
This is my first attempt in Google Sheets scripting

I try to compare each row of the first column in two sheets.

If any value in sheet 1 is not in sheet 2, I would add it at the end of sheet 2.

This is the code, the compare values never match, I tried ==, ===, with and without toSting(). I never get the flag found=1, all values in sheet1 col1 are copied at sheet2 col1.

```<code>var ui = SpreadsheetApp.getUi();
var ss = SpreadsheetApp.getActiveSpreadsheet();

function Prueba2() {
  var sheet = ss.getSheets()[0];
  var rangeData = sheet.getDataRange();
  sheet.getRange('A1').activate();

  var lastRow = rangeData.getLastRow();
  var searchRange = sheet.getRange(2,1, lastRow, 1);

  var sheet2 = ss.getSheets()[1];
  var rangeData2 = sheet2.getDataRange();
  var lastRow2 = rangeData2.getLastRow();
  var searchRange2 = sheet2.getRange(2,1, lastRow2, 1);

  var l1= searchRange.getLastRow();
  var l2= searchRange2.getLastRow();

  var rangeValues = searchRange.getValues();
  var rangeValues2 = searchRange2.getValues();

  var found=0;
  var arr = [];
  // Loop through array and if condition met
  for ( i = 0; i < lastRow - 1; i++){
    found=0;
    for ( j = 0 ; j < lastRow2 - 1; j++){
      var vi=rangeValues[i];
      var vj=rangeValues2[j];
      if(rangeValues[i].toString() === rangeValues2[j].toString()){
        found=1;
        break;
      };
    };
    if (found==0){
      Logger.log(rangeValues[i]);
      arr.push(rangeValues[i]);
    };
   };
  var toAddArray = [];
  for (k = 0; k < arr.length; ++k){
    toAddArray.push([arr[k]]);
  }

  sheet2.getRange(lastRow2+1, 1, arr.length, 1).setValues(toAddArray);
};
</code>```

EDIT

This worked, but I don't know why

```<code>for ( j = 0 ; j < lastRow2 - 1; j++){
  var vi=rangeValues[i].toString();
  var vj=rangeValues2[j].toString();
  //if(rangeValues[i] === rangeValues2[j]){
  if(vi===vj||vi==""){
    found=1;
    break;
  };
};
</code>```

答:
How about this modification? The value retrieved by getValues() is 2 dimensional array. By considerating this, the script is modified.

Pattern 1:

If your script is modified, how about this modification?

From:

```<code>for ( i = 0; i < lastRow - 1; i++){
  found=0;
  for ( j = 0 ; j < lastRow2 - 1; j++){
    var vi=rangeValues[i];
    var vj=rangeValues2[j];
    if(rangeValues[i].toString() === rangeValues2[j].toString()){
      found=1;
      break;
    };
  };
  if (found==0){
    Logger.log(rangeValues[i]);
    arr.push(rangeValues[i]);
  };
 };
</code>```

To:

```<code>for ( i = 0; i < lastRow - 1; i++){
  found=0;
  for ( j = 0 ; j < lastRow2 - 1; j++){
      // var vi=rangeValues[i]; // This is not used in this script.
      // var vj=rangeValues2[j]; // This is not used in this script.
    if(rangeValues[i][0].toString() === rangeValues2[j][0].toString()){ // Modified
      found=1;
      break;
    };
  };
  if (found==1){ // Modified
    Logger.log(rangeValues[i][0]); // Modified
    arr.push(rangeValues[i][0]); // Modified
  };
 };
</code>```

In your situation, you might be able to replace if(rangeValues[i][0].toString() === rangeValues2[j][0].toString()){ to if(rangeValues[i][0] === rangeValues2[j][0]){.

Pattern 2:

As other pattern, how about this modification?

From:

```<code>var found=0;
var arr = [];
// Loop through array and if condition met
for ( i = 0; i < lastRow - 1; i++){
  found=0;
  for ( j = 0 ; j < lastRow2 - 1; j++){
    var vi=rangeValues[i];
    var vj=rangeValues2[j];
    if(rangeValues[i].toString() === rangeValues2[j].toString()){
      found=1;
      break;
    };
  };
  if (found==0){
    Logger.log(rangeValues[i]);
    arr.push(rangeValues[i]);
  };
 };
var toAddArray = [];
for (k = 0; k < arr.length; ++k){
  toAddArray.push([arr[k]]);
}

sheet2.getRange(lastRow2+1, 1, arr.length, 1).setValues(toAddArray);
</code>```

To:

```<code>var toAddArray = rangeValues.filter(function(e) {return rangeValues2.some(function(f) {return e[0] && f[0] && e[0] == f[0]})});
sheet2.getRange(lastRow2+1, 1, toAddArray.length, 1).setValues(toAddArray);
</code>```

Note:

The reason vi===vj of your added script works is as follows.

When rangeValues[i].toString() and rangeValues2[j].toString() are run, 1 dimensional array is converted to a string like ["sample"] to "sample". By this, vi===vj works.

References:

getValues()

filter()

some()

If I misunderstood your question and this was not the result you want, I apologize.

Body:
This is my first attempt in Google Sheets scripting

I try to compare each row of the first column in two sheets.

If any value in sheet 1 is not in sheet 2, I would add it at the end of sheet 2.

This is the code, the compare values never match, I tried ==, ===, with and without toSting(). I never get the flag found=1, all values in sheet1 col1 are copied at sheet2 col1.

var ui = SpreadsheetApp.getUi();
var ss = SpreadsheetApp.getActiveSpreadsheet();

function Prueba2() {
  var sheet = ss.getSheets()[0];
  var rangeData = sheet.getDataRange();
  sheet.getRange('A1').activate();

  var lastRow = rangeData.getLastRow();
  var searchRange = sheet.getRange(2,1, lastRow, 1);

  var sheet2 = ss.getSheets()[1];
  var rangeData2 = sheet2.getDataRange();
  var lastRow2 = rangeData2.getLastRow();
  var searchRange2 = sheet2.getRange(2,1, lastRow2, 1);

  var l1= searchRange.getLastRow();
  var l2= searchRange2.getLastRow();

  var rangeValues = searchRange.getValues();
  var rangeValues2 = searchRange2.getValues();

  var found=0;
  var arr = [];
  // Loop through array and if condition met
  for ( i = 0; i < lastRow - 1; i++){
    found=0;
    for ( j = 0 ; j < lastRow2 - 1; j++){
      var vi=rangeValues[i];
      var vj=rangeValues2[j];
      if(rangeValues[i].toString() === rangeValues2[j].toString()){
        found=1;
        break;
      };
    };
    if (found==0){
      Logger.log(rangeValues[i]);
      arr.push(rangeValues[i]);
    };
   };
  var toAddArray = [];
  for (k = 0; k < arr.length; ++k){
    toAddArray.push([arr[k]]);
  }

  sheet2.getRange(lastRow2+1, 1, arr.length, 1).setValues(toAddArray);
};

EDIT

This worked, but I don't know why

for ( j = 0 ; j < lastRow2 - 1; j++){
  var vi=rangeValues[i].toString();
  var vj=rangeValues2[j].toString();
  //if(rangeValues[i] === rangeValues2[j]){
  if(vi===vj||vi==""){
    found=1;
    break;
  };
};

Body:
How about this modification? The value retrieved by getValues() is 2 dimensional array. By considerating this, the script is modified.

Pattern 1:

If your script is modified, how about this modification?

From:

for ( i = 0; i < lastRow - 1; i++){
  found=0;
  for ( j = 0 ; j < lastRow2 - 1; j++){
    var vi=rangeValues[i];
    var vj=rangeValues2[j];
    if(rangeValues[i].toString() === rangeValues2[j].toString()){
      found=1;
      break;
    };
  };
  if (found==0){
    Logger.log(rangeValues[i]);
    arr.push(rangeValues[i]);
  };
 };

To:

for ( i = 0; i < lastRow - 1; i++){
  found=0;
  for ( j = 0 ; j < lastRow2 - 1; j++){
      // var vi=rangeValues[i]; // This is not used in this script.
      // var vj=rangeValues2[j]; // This is not used in this script.
    if(rangeValues[i][0].toString() === rangeValues2[j][0].toString()){ // Modified
      found=1;
      break;
    };
  };
  if (found==1){ // Modified
    Logger.log(rangeValues[i][0]); // Modified
    arr.push(rangeValues[i][0]); // Modified
  };
 };

In your situation, you might be able to replace if(rangeValues[i][0].toString() === rangeValues2[j][0].toString()){ to if(rangeValues[i][0] === rangeValues2[j][0]){.

Pattern 2:

As other pattern, how about this modification?

From:

var found=0;
var arr = [];
// Loop through array and if condition met
for ( i = 0; i < lastRow - 1; i++){
  found=0;
  for ( j = 0 ; j < lastRow2 - 1; j++){
    var vi=rangeValues[i];
    var vj=rangeValues2[j];
    if(rangeValues[i].toString() === rangeValues2[j].toString()){
      found=1;
      break;
    };
  };
  if (found==0){
    Logger.log(rangeValues[i]);
    arr.push(rangeValues[i]);
  };
 };
var toAddArray = [];
for (k = 0; k < arr.length; ++k){
  toAddArray.push([arr[k]]);
}

sheet2.getRange(lastRow2+1, 1, arr.length, 1).setValues(toAddArray);

To:

var toAddArray = rangeValues.filter(function(e) {return rangeValues2.some(function(f) {return e[0] && f[0] && e[0] == f[0]})});
sheet2.getRange(lastRow2+1, 1, toAddArray.length, 1).setValues(toAddArray);

Note:

The reason vi===vj of your added script works is as follows.

When rangeValues[i].toString() and rangeValues2[j].toString() are run, 1 dimensional array is converted to a string like ["sample"] to "sample". By this, vi===vj works.

References:

getValues()

filter()

some()

If I misunderstood your question and this was not the result you want, I apologize.


问:
Flink keyBy POJO
(Apologies for the inevitably terrible formatting as I’m posting from my phone)

I am doing a keyBy and then an aggregate but Flink is not grouping the data correctly (instead each event falls into its own group by).

Example:

```<code>Class Purchase {
    String product;
    Integer quantity;
}

Class Filter {
    String product;

    public int hashCode() {
        final int prime = 31;
        int result = 1;
        result = prime * result + ((product == bull) ? 0 : displayName.hashCode());
}

Class FilteredPurchase {
    Filter filter;
    Purchase purchase;
}

DataStream<FilteredPurchase> =
    ...
    .keyBy(“filter”) //This works
    .keyBy(x -> x.getFilter()). // This doesn’t
    .sum(“trade.quantity”);
</code>```

If we consider the case of a stream that looks like:

```<code>[
    {“filter”: {“product”: null}, “purchase”: {“product”: “apple”, “quantity”: 10},
    {“filter”: {“product”: null}, “purchase”: {“product”: “apple”, “quantity”: 10},
    {“filter”: {“product”: “apple”}, “purchase”: {“product”: “apple”, “quantity”: 10},
    {“filter”: {“product”: “apple”}, “purchase”: {“product”: “apple”, “quantity”: 10},
]
</code>```

I would expect it to be keyed into 2 partitions (because there are two filters) the total in each being 20. However, I actually end up with 4 partitions each with a total of 10.

Interestingly, if I use the field expression version it does do what I want, but I would like to keep everything as a POJO as I intend on doing some more with it later on.

Am I missing something here? Can a KeySelector return a POJO?

答:
First question is why you don't just use the product (String) as your key, since that's all you've got in the Filter class. So

.keyBy(x -> x.getProduct())

But in any case, I think your key class (Filter) has to implement the equals() method.

Title: Flink keyBy POJO

Body:
(Apologies for the inevitably terrible formatting as I’m posting from my phone)

I am doing a keyBy and then an aggregate but Flink is not grouping the data correctly (instead each event falls into its own group by).

Example:

Class Purchase {
    String product;
    Integer quantity;
}

Class Filter {
    String product;

    public int hashCode() {
        final int prime = 31;
        int result = 1;
        result = prime * result + ((product == bull) ? 0 : displayName.hashCode());
}

Class FilteredPurchase {
    Filter filter;
    Purchase purchase;
}

DataStream<FilteredPurchase> =
    ...
    .keyBy(“filter”) //This works
    .keyBy(x -> x.getFilter()). // This doesn’t
    .sum(“trade.quantity”);

If we consider the case of a stream that looks like:

[
    {“filter”: {“product”: null}, “purchase”: {“product”: “apple”, “quantity”: 10},
    {“filter”: {“product”: null}, “purchase”: {“product”: “apple”, “quantity”: 10},
    {“filter”: {“product”: “apple”}, “purchase”: {“product”: “apple”, “quantity”: 10},
    {“filter”: {“product”: “apple”}, “purchase”: {“product”: “apple”, “quantity”: 10},
]

I would expect it to be keyed into 2 partitions (because there are two filters) the total in each being 20. However, I actually end up with 4 partitions each with a total of 10.

Interestingly, if I use the field expression version it does do what I want, but I would like to keep everything as a POJO as I intend on doing some more with it later on.

Am I missing something here? Can a KeySelector return a POJO?


问:
c string compare vs hash compare
I need to compare a string to multiple other constant strings in c. I am curious which is faster, to hash the string I am going to compare and compare it to all the other constant string hashes or just compare the strings as strings. thank you in advance

thank you for the answers I am going to be doing many comparisons. can anyone give me a good, fast, low resource intensive algorithm to use? The only hash I know of is MD5 and I have a feeling that is over kill.

I also want to add that the strings are maybe 20 or 30 characters long at the max with most being around 7.

答:
To answer your question directly, if you are just comparing if two strings (you can also think about two files, two videos etc), doing a char by char comparison and hashing are both O(N), there is no obvious advantage doing it hash way.

However, if the string can change, then hashing would be more efficient in the 2nd run, e.g., rolling hash https://en.wikipedia.org/wiki/Rolling_hash

Moreover, hashing of a string/file is like a fingerprint, you can directly compare the hash value next time you want to compare if another string is the same as this one or not

ContentLicense: CC BY-SA 2.5

Title: c string compare vs hash compare


问:
How to Drag my view a little bit up when keyboard comes up?
In my app i have some textfields which gets filled through the keyboard. There are 6 of them and the last two are in very bottom of the screen and it gets hidden whenever keyboard comes up.
Any suggestions??</p>

答:
Make the textFields delegate as self and add the following code to the textFieldDidBeginEditing and textFieldDidEndEditing.

Define the following constants: (the constants have been set for iPad. Tweak them for iphone)

```<code>static const CGFloat KEYBOARD_ANIMATION_DURATION = 0.3;
static const CGFloat MINIMUM_SCROLL_FRACTION = 0.2;
static const CGFloat MAXIMUM_SCROLL_FRACTION = 0.8;
static const CGFloat PORTRAIT_KEYBOARD_HEIGHT = 216;
static const CGFloat LANDSCAPE_KEYBOARD_HEIGHT = 302;
</code>```

Add two variables in the .h file of your class. CGFloat animatedDistance; and UITextField *currentField;

```<code>- (void)textFieldDidBeginEditing:(UITextField *)textField {

    currentField = textField;
    UIInterfaceOrientation orientation =
    [[UIApplication sharedApplication] statusBarOrientation];

    CGRect textFieldRect =[self.view.window convertRect:textField.bounds fromView:textField];

    CGRect viewRect =[self.view.window convertRect:self.view.bounds fromView:self.view];
    if (orientation == UIInterfaceOrientationLandscapeLeft )
    {
        textFieldRect.origin.y = textFieldRect.origin.x;
        textFieldRect.size.height = textFieldRect.size.width;
        viewRect.size.height = viewRect.size.width;
    }
    else  if (orientation == UIInterfaceOrientationLandscapeRight )
    {
        textFieldRect.origin.y =viewRect.size.width - textFieldRect.origin.x;
        textFieldRect.size.height = textFieldRect.size.width;
        viewRect.size.height = viewRect.size.width;
    }
    else   if (orientation == UIInterfaceOrientationPortraitUpsideDown)
    {
        textFieldRect.origin.y = viewRect.size.height - textFieldRect.origin.y;
    }

    CGFloat midline = textFieldRect.origin.y + 0.5 * textFieldRect.size.height;
    CGFloat numerator = midline - viewRect.origin.y - MINIMUM_SCROLL_FRACTION * viewRect.size.height;
    CGFloat denominator =(MAXIMUM_SCROLL_FRACTION - MINIMUM_SCROLL_FRACTION)* viewRect.size.height;
    CGFloat heightFraction = numerator / denominator;
    if (heightFraction < 0.0)
    {
        heightFraction = 0.0;
    }
    else if (heightFraction > 1.0)
    {
        heightFraction = 1.0;
    }
    if (orientation == UIInterfaceOrientationPortrait ||
        orientation == UIInterfaceOrientationPortraitUpsideDown)
    {
        animatedDistance = floor(PORTRAIT_KEYBOARD_HEIGHT * heightFraction);
    }
    else
    {
        animatedDistance = floor(LANDSCAPE_KEYBOARD_HEIGHT * heightFraction);
    }
    CGRect viewFrame = self.view.frame;
    viewFrame.origin.y -= animatedDistance;

    [UIView beginAnimations:nil context:NULL];
    [UIView setAnimationBeginsFromCurrentState:YES];
    [UIView setAnimationDuration:KEYBOARD_ANIMATION_DURATION];

    [self.view setFrame:viewFrame];

    [UIView commitAnimations];

}

- (void)textFieldDidEndEditing:(UITextField *)textField {

    [textField resignFirstResponder];

    CGRect viewFrame = self.view.frame;
    viewFrame.origin.y += animatedDistance;

    animatedDistance = 0;
    [UIView beginAnimations:nil context:NULL];
    [UIView setAnimationBeginsFromCurrentState:YES];
    [UIView setAnimationDuration:KEYBOARD_ANIMATION_DURATION];

    [self.view setFrame:viewFrame];

    [UIView commitAnimations];

    currentField = nil;
}
</code>```

Body:
Make the textFields delegate as self and add the following code to the textFieldDidBeginEditing and textFieldDidEndEditing.

Define the following constants: (the constants have been set for iPad. Tweak them for iphone)

static const CGFloat KEYBOARD_ANIMATION_DURATION = 0.3;
static const CGFloat MINIMUM_SCROLL_FRACTION = 0.2;
static const CGFloat MAXIMUM_SCROLL_FRACTION = 0.8;
static const CGFloat PORTRAIT_KEYBOARD_HEIGHT = 216;
static const CGFloat LANDSCAPE_KEYBOARD_HEIGHT = 302;

Add two variables in the .h file of your class. CGFloat animatedDistance; and UITextField *currentField;

- (void)textFieldDidBeginEditing:(UITextField *)textField {

    currentField = textField;
    UIInterfaceOrientation orientation =
    [[UIApplication sharedApplication] statusBarOrientation];

    CGRect textFieldRect =[self.view.window convertRect:textField.bounds fromView:textField];

    CGRect viewRect =[self.view.window convertRect:self.view.bounds fromView:self.view];
    if (orientation == UIInterfaceOrientationLandscapeLeft )
    {
        textFieldRect.origin.y = textFieldRect.origin.x;
        textFieldRect.size.height = textFieldRect.size.width;
        viewRect.size.height = viewRect.size.width;
    }
    else  if (orientation == UIInterfaceOrientationLandscapeRight )
    {
        textFieldRect.origin.y =viewRect.size.width - textFieldRect.origin.x;
        textFieldRect.size.height = textFieldRect.size.width;
        viewRect.size.height = viewRect.size.width;
    }
    else   if (orientation == UIInterfaceOrientationPortraitUpsideDown)
    {
        textFieldRect.origin.y = viewRect.size.height - textFieldRect.origin.y;
    }

    CGFloat midline = textFieldRect.origin.y + 0.5 * textFieldRect.size.height;
    CGFloat numerator = midline - viewRect.origin.y - MINIMUM_SCROLL_FRACTION * viewRect.size.height;
    CGFloat denominator =(MAXIMUM_SCROLL_FRACTION - MINIMUM_SCROLL_FRACTION)* viewRect.size.height;
    CGFloat heightFraction = numerator / denominator;
    if (heightFraction < 0.0)
    {
        heightFraction = 0.0;
    }
    else if (heightFraction > 1.0)
    {
        heightFraction = 1.0;
    }
    if (orientation == UIInterfaceOrientationPortrait ||
        orientation == UIInterfaceOrientationPortraitUpsideDown)
    {
        animatedDistance = floor(PORTRAIT_KEYBOARD_HEIGHT * heightFraction);
    }
    else
    {
        animatedDistance = floor(LANDSCAPE_KEYBOARD_HEIGHT * heightFraction);
    }
    CGRect viewFrame = self.view.frame;
    viewFrame.origin.y -= animatedDistance;

    [UIView beginAnimations:nil context:NULL];
    [UIView setAnimationBeginsFromCurrentState:YES];
    [UIView setAnimationDuration:KEYBOARD_ANIMATION_DURATION];

    [self.view setFrame:viewFrame];

    [UIView commitAnimations];

}

- (void)textFieldDidEndEditing:(UITextField *)textField {

    [textField resignFirstResponder];

    CGRect viewFrame = self.view.frame;
    viewFrame.origin.y += animatedDistance;

    animatedDistance = 0;
    [UIView beginAnimations:nil context:NULL];
    [UIView setAnimationBeginsFromCurrentState:YES];
    [UIView setAnimationDuration:KEYBOARD_ANIMATION_DURATION];

    [self.view setFrame:viewFrame];

    [UIView commitAnimations];

    currentField = nil;
}


问:
@google-cloud/bigquery Query API returning empty Promise when used in Cloud Function
I'm trying to use the '@google-cloud/bigquery' library to query BigQuery from a Google Cloud function. When the Promise returns, all I get back is an Array with another empty Array inside it, even though when I run the same query from the Big Query console I get a non-empty response back.

I've tried using an async function instead of a promise, but that was not successful. I also gave my Service Account "BigQuery Admin" and "Editor" privileges but that has not worked out either.

I do know the API is hitting Big Query. When I tried creating a new dataset from my Cloud Function, that call worked just fine, but for some reason I'm unable to get query results back from BQ.

```<code>  function warningAndPreventionIntent(agent) {
    let userCountry = agent.parameters['geo-country'];
    console.log(String(userCountry[0]));

    const gotCountry = userCountry.length > 0;

    if(gotCountry) {
      agent.add('Im looking into your trip');

      const OPTIONS = {
              query: 'SELECT disease.name FROM `projectId.dataset.table`, unnest(disease) disease WHERE country = @country',
              timeoutMs: 10000,
              useLegacySql: false,
              params: {country: userCountry[0]}
      };

      return bigquery
      .query(OPTIONS)
      .then(results => {
          console.log(JSON.stringify(results[0]))
          const ROWS = results[0];

          let diseaseList = [];

          for(var row of ROWS) {
            diseaseList.push(row.name);
            console.log(diseaseList);
          }

          return true;

      })
      .catch(err => {
        console.error('ERROR:', err);
      });
    }
  }
</code>```

I should get a JSON result object with values, but I only get and array with an empty array [[]]

答: i am now getting the same thing.  I updated my cloud function without changing the code and the behavior changed.</p>

Body:
I'm trying to use the '@google-cloud/bigquery' library to query BigQuery from a Google Cloud function. When the Promise returns, all I get back is an Array with another empty Array inside it, even though when I run the same query from the Big Query console I get a non-empty response back.

I've tried using an async function instead of a promise, but that was not successful. I also gave my Service Account "BigQuery Admin" and "Editor" privileges but that has not worked out either.

I do know the API is hitting Big Query. When I tried creating a new dataset from my Cloud Function, that call worked just fine, but for some reason I'm unable to get query results back from BQ.

  function warningAndPreventionIntent(agent) {
    let userCountry = agent.parameters['geo-country'];
    console.log(String(userCountry[0]));

    const gotCountry = userCountry.length > 0;

    if(gotCountry) {
      agent.add('Im looking into your trip');

      const OPTIONS = {
              query: 'SELECT disease.name FROM `projectId.dataset.table`, unnest(disease) disease WHERE country = @country',
              timeoutMs: 10000,
              useLegacySql: false,
              params: {country: userCountry[0]}
      };

      return bigquery
      .query(OPTIONS)
      .then(results => {
          console.log(JSON.stringify(results[0]))
          const ROWS = results[0];

          let diseaseList = [];

          for(var row of ROWS) {
            diseaseList.push(row.name);
            console.log(diseaseList);
          }

          return true;

      })
      .catch(err => {
        console.error('ERROR:', err);
      });
    }
  }

I should get a JSON result object with values, but I only get and array with an empty array [[]]


问:
Bugsnag can't read notify of undefined react native
Not sure why I am getting this error since obviously bugsnag is defined if it is passing the error to the bugsnag console:

Here is my bugsnag file:

```<code>import { Client } from 'bugsnag-react-native';
import Config from 'react-native-config'

export const bugsnag = new Client(Config.BUGSNAG_KEY);
</code>```

config has the correct API key

here is my error file:

```<code>import bugsnag from './bugsnag'

    export default function (err) {
      console.log("BUGSNAG ERR", err);
      if (err) {
        if (!err.stack) {
          err = new Error(err)
        }
        bugsnag.notify.apply(bugsnag, [err])
      }
    }
</code>```

And here is my index.js

```<code>// eslint-disable-next-line no-unused-vars
import bugsnag from './app/configs/bugsnag';
</code>```

I have tried to follow all the react native setup from bugsnags docs, but obviously I am missing something.  All help is appreciated.

答:
The issue was how I imported the file:

since i used:

export const bugsnag

I needed to use:

import { bugsnag } from './bugsnag'

Based off this article:

https://medium.com/@etherealm/named-export-vs-default-export-in-es6-affb483a0910

Body:
Not sure why I am getting this error since obviously bugsnag is defined if it is passing the error to the bugsnag console:

Here is my bugsnag file:

import { Client } from 'bugsnag-react-native';
import Config from 'react-native-config'

export const bugsnag = new Client(Config.BUGSNAG_KEY);

config has the correct API key

here is my error file:

import bugsnag from './bugsnag'

    export default function (err) {
      console.log("BUGSNAG ERR", err);
      if (err) {
        if (!err.stack) {
          err = new Error(err)
        }
        bugsnag.notify.apply(bugsnag, [err])
      }
    }

And here is my index.js

// eslint-disable-next-line no-unused-vars
import bugsnag from './app/configs/bugsnag';

I have tried to follow all the react native setup from bugsnags docs, but obviously I am missing something.  All help is appreciated.


问:
How to convert rows to columns in PostgreSQL?
I have two database tables as below

```<code>site
id    |    name
1        Site One
2        Site Two
3        Site Three

asset_quantities
id   |   site_id   |  asset_type   | quantity
1           1             1              10
2           1             2              15
3           1             3              25
4           2             1              11
5           2             2              16
6           2             3              7
7           3             1              12
8           3             2              15
9           3             3              16
</code>```

I want to write a SQL query that will sort results based on the 'quantity' column for a given asset type
E.g. I want to sort descending results based on the quantity for asset type 1 across all sites.
How would I frame the SQL query for a scenario like this?

Below is a sample result I want if I want descending order results for the quantity of asset type 1 across all sites

```<code>site_id  |   asset_type_1_qty   |   asset_type_2_qty  |  asset_type_3_qty
   3                12                     15                  16
   2                11                     16                  7
   1                10                     15                  25
</code>```

答:
This is an example that will do what you want in sqlserver. You should be able to adapt it to postgres.

I have two versions, one which hard codes the sort, the second which uses a parameter to decide what to sort by.

First create the data in temporary table variable

```<code>declare @s table(id int, site_id int, asset_type int, quantity int)
insert @s values (1,1,1,10)
,(2,1,2,15)
,(3,1,3,25)
,(4,2,1,11)
,(5,2,2,16)
,(6,2,3,7)
,(7,3,1,12)
,(8,3,2,15)
,(9,3,3,16)
</code>```

First version with fixed column sort

```<code>select site_id,
    max(case when asset_type=1 then quantity else 0 end) as q1,
    max(case when asset_type=2 then quantity else 0 end) as q2,
    max(case when asset_type=3 then quantity else 0 end) as q3
from @s
group by site_id
order by 2 desc
</code>```

Second version with parameter column sort

```<code>declare @assetsort int;
set @assetsort=3

select * from (
    select site_id,
        max(case when asset_type=1 then quantity else 0 end) as q1,
        max(case when asset_type=2 then quantity else 0 end) as q2,
        max(case when asset_type=3 then quantity else 0 end) as q3
    from @s
    group by site_id
) q
order by
    case @assetsort when 1 then q1 when 2 then q2 when 3 then q3 end desc
</code>```

Body:
I have two database tables as below

site
id    |    name
1        Site One
2        Site Two
3        Site Three

asset_quantities
id   |   site_id   |  asset_type   | quantity
1           1             1              10
2           1             2              15
3           1             3              25
4           2             1              11
5           2             2              16
6           2             3              7
7           3             1              12
8           3             2              15
9           3             3              16

I want to write a SQL query that will sort results based on the 'quantity' column for a given asset type
E.g. I want to sort descending results based on the quantity for asset type 1 across all sites.
How would I frame the SQL query for a scenario like this?

Below is a sample result I want if I want descending order results for the quantity of asset type 1 across all sites

site_id  |   asset_type_1_qty   |   asset_type_2_qty  |  asset_type_3_qty
   3                12                     15                  16
   2                11                     16                  7
   1                10                     15                  25

Body:
This is an example that will do what you want in sqlserver. You should be able to adapt it to postgres.

I have two versions, one which hard codes the sort, the second which uses a parameter to decide what to sort by.

First create the data in temporary table variable

declare @s table(id int, site_id int, asset_type int, quantity int)
insert @s values (1,1,1,10)
,(2,1,2,15)
,(3,1,3,25)
,(4,2,1,11)
,(5,2,2,16)
,(6,2,3,7)
,(7,3,1,12)
,(8,3,2,15)
,(9,3,3,16)

First version with fixed column sort

select site_id,
    max(case when asset_type=1 then quantity else 0 end) as q1,
    max(case when asset_type=2 then quantity else 0 end) as q2,
    max(case when asset_type=3 then quantity else 0 end) as q3
from @s
group by site_id
order by 2 desc

Second version with parameter column sort

declare @assetsort int;
set @assetsort=3

select * from (
    select site_id,
        max(case when asset_type=1 then quantity else 0 end) as q1,
        max(case when asset_type=2 then quantity else 0 end) as q2,
        max(case when asset_type=3 then quantity else 0 end) as q3
    from @s
    group by site_id
) q
order by
    case @assetsort when 1 then q1 when 2 then q2 when 3 then q3 end desc


问:
lxml returned me a list but it's empty
I was trying to make a list of all the top 1000 instagramer's acount from this website:'https://hypeauditor.com/top-instagram/'.
The list that returns from lxml is empty for both lxml.html and lxml.etree.

I tried to delete tbody, delete text(), and upper xpath, but it all failed.
what worth noticing is that, with upper xpath, it did return me something, but it is all but /n.

I first tried lxml.etree

```<code>market_url='https://hypeauditor.com/top-instagram/'
r_market=requests.get(market_url)
s_market=etree.HTML(r_market)`
file_market=s_market.xpath('//*[@id="bloggers-top-table"]/tr[1]/td[3]/a/text()')
</code>```

then I also tried lxml.html.

```<code>tree=html.fromstring(r_market.content)
result=tree.xpath('//*[@id="bloggers-top-table"]/tr/td/h4/text()')
</code>```

furthermore, I tried this xpath:

```<code>s_market.xpath('//*[@id="bloggers-top-table"]/tbody/text()')
</code>```

It did not give me any error. But after all the attempts, it still gives me wether empty list or a list full of n/.

I am not really experienced in web scraping so it is possible that I have just made a stupid error somewhere, but since without the data I can not start my machine learning model, I am really struggling, pls help.

答:
You will definitely want to get acquainted with the package BeautifulSoup which allows you navigate a web page's content in python.

Using BeautifulSoup:

```<code>import requests
from bs4 import BeautifulSoup

url = 'https://hypeauditor.com/top-instagram/'
r = requests.get(url)
html = r.text

soup = BeautifulSoup(html, 'html.parser')

top_bloggers = soup.find('table', id="bloggers-top-table")
table_body = top_bloggers.find('tbody')
rows = table_body.find_all('tr')

# For all data:
# Will retrieve a list of lists, good for inputting to pandas

data=[]

for row in rows:
    cols = row.find_all('td')
    cols = [ele.text.strip() for ele in cols]
    data.append([ele for ele in cols if ele]) # Get rid of empty values

# For just handles:
# Will retrieve a list of handles, only

handles=[]

for row in rows:
    cols = row.find_all('td')
    values = cols[3].text.strip().split('\n')
    handles.append(values[-1])
</code>```

The for loop I use for rows is sourced from this answer

Title: lxml returned me a list but it's empty

Body:
I was trying to make a list of all the top 1000 instagramer's acount from this website:'https://hypeauditor.com/top-instagram/'.
The list that returns from lxml is empty for both lxml.html and lxml.etree.

I tried to delete tbody, delete text(), and upper xpath, but it all failed.
what worth noticing is that, with upper xpath, it did return me something, but it is all but /n.

I first tried lxml.etree

market_url='https://hypeauditor.com/top-instagram/'
r_market=requests.get(market_url)
s_market=etree.HTML(r_market)`
file_market=s_market.xpath('//*[@id="bloggers-top-table"]/tr[1]/td[3]/a/text()')

then I also tried lxml.html.

tree=html.fromstring(r_market.content)
result=tree.xpath('//*[@id="bloggers-top-table"]/tr/td/h4/text()')

furthermore, I tried this xpath:

s_market.xpath('//*[@id="bloggers-top-table"]/tbody/text()')

It did not give me any error. But after all the attempts, it still gives me wether empty list or a list full of n/.

I am not really experienced in web scraping so it is possible that I have just made a stupid error somewhere, but since without the data I can not start my machine learning model, I am really struggling, pls help.

Body:
You will definitely want to get acquainted with the package BeautifulSoup which allows you navigate a web page's content in python.

Using BeautifulSoup:

import requests
from bs4 import BeautifulSoup

url = 'https://hypeauditor.com/top-instagram/'
r = requests.get(url)
html = r.text

soup = BeautifulSoup(html, 'html.parser')

top_bloggers = soup.find('table', id="bloggers-top-table")
table_body = top_bloggers.find('tbody')
rows = table_body.find_all('tr')

# For all data:
# Will retrieve a list of lists, good for inputting to pandas

data=[]

for row in rows:
    cols = row.find_all('td')
    cols = [ele.text.strip() for ele in cols]
    data.append([ele for ele in cols if ele]) # Get rid of empty values

# For just handles:
# Will retrieve a list of handles, only

handles=[]

for row in rows:
    cols = row.find_all('td')
    values = cols[3].text.strip().split('\n')
    handles.append(values[-1])

The for loop I use for rows is sourced from this answer


问:
Add value to dynamically populated list c#
I'm constructing a web page based on ASN.NET MVC3 with Razor templates and Entity. The task is to populate a @Html.DropDownList from the database, so far so good but now I want to insert a static value in the DropDownList.

The code looks as follows

The create method

```<code>public ActionResult Create()
{
    var parents = db.Organizations.OrderBy(o => o.Title).ToList();
    var organization = new Organization();
    return View(organization);
}
</code>```

Extract from the Razor template

```<code><div class="editor-field">
    @Html.DropDownList("ParentGuid",
    new SelectList(ViewBag.Organizations as System.Collections.IEnumerable,
    "ParentGuid", "Title", Model.ParentGuid))
</div>
</code>```

So, the above code works but Im stuck in figuring out how to insert an empty row in the dropdown.

答: In your controller Create(), just add an empty string to the head of the "parents" list.</p>

Body:
I'm constructing a web page based on ASN.NET MVC3 with Razor templates and Entity. The task is to populate a @Html.DropDownList from the database, so far so good but now I want to insert a static value in the DropDownList.

The code looks as follows

The create method

public ActionResult Create()
{
    var parents = db.Organizations.OrderBy(o => o.Title).ToList();
    var organization = new Organization();
    return View(organization);
}

Extract from the Razor template

    @Html.DropDownList("ParentGuid",
    new SelectList(ViewBag.Organizations as System.Collections.IEnumerable,
    "ParentGuid", "Title", Model.ParentGuid))

So, the above code works but Im stuck in figuring out how to insert an empty row in the dropdown.


问:
How can GTIN be used in blockchain?
I am using hyperledger fabric to be able to trace products to check its provenance within a supply chain. This project is meant for a lot of products, especially for longer periods of time.

I am having trouble figuring out what kind of identifiers to use for identifying a product which needs to be transacted in the blockchain. All the data will be stored within it forever.

According to a source (https://www.gs1ca.org/files/How_to_Create_a_GTIN.pdf) I can only make a max amount of 100.000 unique codes per company. After that I am geussing it needs to be reused. What are the identifiers I can use for basically an unlimitted amount of unique-codes within blockchain? Are there standards to handle this? Or should I identify my assets with two identifiers?

答:
In the event a company exhausts their 100,000 GTIN's they can apply for a second, or a third, or so on, GS1 Prefix. So essentially you should map their GTIN's along with their GS1 prefix.

Do some research on IBM FoodTrust, it is the most well known GS1 standard-based system for tracking goods on a Blockchain (Hyperledger).

Title: How can GTIN be used in blockchain?