问:
Angular 2, using body as root selector, instead of my-app
Are there any downsides of using the  tag instead of some <my-app> tag for the root component?

```<code>import 'package:angular2/angular2.dart';
@Component(
    selector: 'body',
    template: '''
      <h1>My First Angular 2 App</h1>

      <div>{{greet}}</div>
    ''',
    styles: const ['''
      :host {
        height: 100vh;
      }
      h1 {
        color: red;
      }
    '''])
class AppComponent {
  String greet = 'Hello world';
}
</code>```

(The code here is Dart, but I hope it is close enough to ES6, typescript for other people to understand.)

I don't see this often, so I guess there is a good reason for it, but this seems nice to me, otherwise you basically have two root components, body, and my-app.

答:
All friends above are right about the down sides. But what about ?

import 'package:angular2/angular2.dart';
@Component(
    selector: 'body[foo-root]',
    template: '''

My First Angular 2 App

{{greet}}

    ''',
    styles: const ['''
      :host {
        height: 100vh;
      }
      h1 {
        color: red;
      }
    '''])
class AppComponent {
  String greet = 'Hello world';
}
```

Body:
Are there any downsides of using the  tag instead of some <my-app> tag for the root component?

import 'package:angular2/angular2.dart';
@Component(
    selector: 'body',
    template: '''

My First Angular 2 App

{{greet}}

    ''',
    styles: const ['''
      :host {
        height: 100vh;
      }
      h1 {
        color: red;
      }
    '''])
class AppComponent {
  String greet = 'Hello world';
}

(The code here is Dart, but I hope it is close enough to ES6, typescript for other people to understand.)

I don't see this often, so I guess there is a good reason for it, but this seems nice to me, otherwise you basically have two root components, body, and my-app.

Body:
All friends above are right about the down sides. But what about <body foo-root>?

import 'package:angular2/angular2.dart';
@Component(
    selector: 'body[foo-root]',
    template: '''
      <h1>My First Angular 2 App</h1>

      <div>{{greet}}</div>
    ''',
    styles: const ['''
      :host {
        height: 100vh;
      }
      h1 {
        color: red;
      }
    '''])
class AppComponent {
  String greet = 'Hello world';
}


来源: stackexchange

问:
I need help centering text in the center of CSS Grid
I am unable to align text in the center of the grid, both vertical and horizontally, because nothing that I tried seems to work, so I wanted to know what is the problem with my code or how should I do it.

I tried using justify-items: center, align-items: center and even place-items: center center;

This is a my full, hopefully, you can give it a try and see what is wrong with it.

```<code><title> Learning Grid </title>

<style>

    body {
        color: #fff;
        font-family: sans-serif;
        text-align: center;
    }

    #content {
        display: grid;
        grid-template-columns: repeat(12, 1fr);
        grid-auto-rows: minmax(100px, auto);
        grid-gap: 10px;
        max-width: 960px;
        margin: 0 auto;
    }

    #content > * {
        padding: 30px;
        font-size: 30px;

    }

    header {
        grid-column: 1/13;
        text-align: center;
        background-color: hotpink;
    }

     main {
        grid-column: 4/13;
        grid-row: 2/4;
         background-color: darksalmon;
    }

      aside {
        grid-column: 1/4;
        grid-row: 2/3;
          background-color: cadetblue;
    }

     nav {
        grid-column: 1/4;
        grid-row: 3/4;
         text-align: center;
         font-size: 30px;
         background-color: aquamarine;
    }

     section {
        grid-column: 1/13;
        grid-row: 4/6;
         background-color: coral;
    }

    footer {
        grid-column: 1/13;
        grid-row: 6/7;
        background-color: cornflowerblue;
    }

</style>

</head>

<body>

    <div id="content">

        <header> Header </header>

        <main> Main </main>

        <section>Section </section>

        <aside>Aside </aside>

        <nav> Nav </nav>

        <footer> Footer</footer>

    </div>

</body>
</code>```

答:
To align the text, you could use the line-height approach, but that is not very responsive.

Since you already have the grid layout, you can keep that same idea and add a helper element, like a . Doing that, give you more options to alight the actual text.

Here is an example of how your new HTML would look like:

```<code><main>
    <span>Main</span>
</main>
</code>```

And the CSS for that would be:

```<code>main {
    grid-column: 4/13;
    grid-row: 2/4;
    background-color: darksalmon;
    display: grid;
}

main > * {
    margin: auto;
}
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I am unable to align text in the center of the grid, both vertical and horizontally, because nothing that I tried seems to work, so I wanted to know what is the problem with my code or how should I do it.

I tried using justify-items: center, align-items: center and even place-items: center center;

This is a my full, hopefully, you can give it a try and see what is wrong with it.

<title> Learning Grid </title>

         Header

         Main

Section

        Aside

         Nav

         Footer

Body:
To align the text, you could use the line-height approach, but that is not very responsive.

Since you already have the grid layout, you can keep that same idea and add a helper element, like a <span>. Doing that, give you more options to alight the actual text.

Here is an example of how your new HTML would look like:

<main>
    <span>Main</span>
</main>

And the CSS for that would be:

main {
    grid-column: 4/13;
    grid-row: 2/4;
    background-color: darksalmon;
    display: grid;
}

main > * {
    margin: auto;
}


问:
bootstrap - apply class based on screen size
Can I do this without using @media only screen ? Or is this the best way?

For example can I write this in CSS?:

```<code>@include media-breakpoint-up(md) {
  .card {
    transform: translate(0px, -75px);
    z-index: 200;
  }
}
</code>```

I also want to hide/show a div based on screen size.

答: You'll need to use a media query for the transform, but you can use the built-in Bootstrap breakpoints for the display property. E.g. d-md-none will hide the element on md size and up.

Body:
Can I do this without using @media only screen ? Or is this the best way?

For example can I write this in CSS?:

@include media-breakpoint-up(md) {
  .card {
    transform: translate(0px, -75px);
    z-index: 200;
  }
}

I also want to hide/show a div based on screen size.


问:
How to convert an unsigned char variable that holds two hexadecimal values into two chars with one hex number
I need to get the hash (sha1) value of a given unsigned char array. So, I have used openssl. The SHA1 function generate the hash value in an unsigned char array which has 20 values. Indeed each value represent two hexadecimal values.

But, I should convert the generated array (with length of 20) to an array of chars with 40 values.

For example now hashValue[0] is "a0" but, I want to have hashValue[0] = "a" and hashValue[1] = "0"

```<code>#include <iostream>
#include <openssl/sha.h> // For sha1

using namespace std;

int main() {

    unsigned char plainText[] = "compute sha1";
    unsigned char hashValue[20];

    SHA1(plainText,sizeof(plainText),hashValue);

    for (int i = 0; i < 20; i++) {
        printf("%02x", hashValue[i]);
    }
    printf("\n");

    return 0;

}
</code>```

答:
seems like you want to separate the high order and low order bytes.

to isolate the high order byte, shift right 4 bytes.
and to isolate the low order byte, apply a mask. AND with 0x0f

```<code>int x = 0x3A;
int y = x >> 4;   // get high order nibble
int z = x & 0x0F; // get low order nibble
printf("%02x\n", x);
printf("%02x\n", y);
printf("%02x\n", z);
</code>```

Body:
I need to get the hash (sha1) value of a given unsigned char array. So, I have used openssl. The SHA1 function generate the hash value in an unsigned char array which has 20 values. Indeed each value represent two hexadecimal values.

But, I should convert the generated array (with length of 20) to an array of chars with 40 values.

For example now hashValue[0] is "a0" but, I want to have hashValue[0] = "a" and hashValue[1] = "0"

#include <iostream>
#include <openssl/sha.h> // For sha1

using namespace std;

int main() {

    unsigned char plainText[] = "compute sha1";
    unsigned char hashValue[20];

    SHA1(plainText,sizeof(plainText),hashValue);

    for (int i = 0; i < 20; i++) {
        printf("%02x", hashValue[i]);
    }
    printf("\n");

    return 0;

}

Body:
seems like you want to separate the high order and low order bytes.

to isolate the high order byte, shift right 4 bytes.
and to isolate the low order byte, apply a mask. AND with 0x0f

int x = 0x3A;
int y = x >> 4;   // get high order nibble
int z = x & 0x0F; // get low order nibble
printf("%02x\n", x);
printf("%02x\n", y);
printf("%02x\n", z);


问:
How can I use Vertical and Horizontal drag and Scalein the Same GestureDetector?
I'm trying to create a map in flutter and I have this rectangle which I can Scale using a GestureDetector and the onScaleStart, onScaleUpdate and onScaleEnd events  like showed in this answer: How do I pan and zoom an image? and I tried adding onHorizontalDrag and onVerticalDrag but when I do so I get an error stating that I can't have them three at the same time or they'll interfere. So how can I do if I want to have the functionality of a basic map display like (Drag in both directions and scale)? Is there a faster and cleaner way of doing it than using a GestureDetector?

答: I think you just need to use the Scale gesture. It's a superset of Pan. which is a single point gesture for both vertical and horizontal movements. </p>


问:
Socket.Accept taking forever, and non-blocking returning error
I am having trouble running a code that simply connects to my own IP address. The socket.send function works just fine, but the socket.accept takes too long to run. Can somebody help me? This is probably a simple answer I haven't seen yet, as I'm only 13.

I've checked if the port is correct by scanning for it with another code, and I've run it on the python IDLE and in Mac terminal. I've tried 'www.google.com','localhost','','127.0.0.1', and my personal IP address, yet socket.accept still doesn't work

code:
scanner code, returns 20000, AKA it didn't find a port

```<code>import socket
s=socket.socket(socket.AF_INET,socket.SOCK_STREAM);
for port in range(0,20001):
    try:
        s.setblocking(False)
        s.bind(('127.0.0.1',port))
        s.listen(1);
        c,addr=s.accept()
        break
    except:
        if port%1000==0:
            print(port)
</code>```

accept code:

```<code>import socket
s=socket.socket(socket.AF_UNIX,socket.SOCK_DGRAM);
s.setblocking(False)
s.bind(('127.0.0.1',20000))
s.listen(1);
c,addr=s.accept()
</code>```

I want the accept code to return nothing, and the scanner to return a number from 0-20000. This is my first post on Stack-overflow, so please tell me what to do better on my next post (:

答:
This line is incorrect for receiving an incoming TCP connection:

```<code>s=socket.socket(socket.AF_UNIX,socket.SOCK_DGRAM);
</code>```

It should instead be:

```<code>s=socket.socket(socket.AF_INET,socket.SOCK_STREAM);
</code>```

Also, s.setblocking(False) is probably not something you want to do, since you probably want accept() to block until an incoming TCP connection has been received.

Update:  in addition to the problem above, the other problem is that the alleged port-scanning code posted in the question doesn't actually scan any ports, since it doesn't ever attempt to make an outgoing TCP connection.  For reference, here is a version of that code that actually tries to connect to ports 0-20000 on localhost and then prints out which ports it was able to make a connection to:

```<code>import socket

connectedPorts = []
for port in range(0,20001):
    s=socket.socket(socket.AF_INET,socket.SOCK_STREAM);
    try:
        s.connect(('127.0.0.1',port))
        print("Connect succeeded on port %i" % port)
        connectedPorts.append(port)
    except Exception as e:
        print "Port %i: %s" % (port, e)
    s.close()

print("")
print("Connect succeeded on the following ports: ", connectedPorts)
</code>```

... and for completeness, here is the working accept-on-port-20000 code:

```<code>import socket

s=socket.socket(socket.AF_INET,socket.SOCK_STREAM);
s.bind(('127.0.0.1',20000))
s.listen(1);
print("Calling accept...")
c,addr=s.accept()
print("Accept returned: [%s, %s]" % (c,addr))
</code>```

Body:
I am having trouble running a code that simply connects to my own IP address. The socket.send function works just fine, but the socket.accept takes too long to run. Can somebody help me? This is probably a simple answer I haven't seen yet, as I'm only 13.

I've checked if the port is correct by scanning for it with another code, and I've run it on the python IDLE and in Mac terminal. I've tried 'www.google.com','localhost','','127.0.0.1', and my personal IP address, yet socket.accept still doesn't work

code:
scanner code, returns 20000, AKA it didn't find a port

import socket
s=socket.socket(socket.AF_INET,socket.SOCK_STREAM);
for port in range(0,20001):
    try:
        s.setblocking(False)
        s.bind(('127.0.0.1',port))
        s.listen(1);
        c,addr=s.accept()
        break
    except:
        if port%1000==0:
            print(port)

accept code:

import socket
s=socket.socket(socket.AF_UNIX,socket.SOCK_DGRAM);
s.setblocking(False)
s.bind(('127.0.0.1',20000))
s.listen(1);
c,addr=s.accept()

I want the accept code to return nothing, and the scanner to return a number from 0-20000. This is my first post on Stack-overflow, so please tell me what to do better on my next post (:

Body:
This line is incorrect for receiving an incoming TCP connection:

s=socket.socket(socket.AF_UNIX,socket.SOCK_DGRAM);

It should instead be:

s=socket.socket(socket.AF_INET,socket.SOCK_STREAM);

Also, s.setblocking(False) is probably not something you want to do, since you probably want accept() to block until an incoming TCP connection has been received.

Update:  in addition to the problem above, the other problem is that the alleged port-scanning code posted in the question doesn't actually scan any ports, since it doesn't ever attempt to make an outgoing TCP connection.  For reference, here is a version of that code that actually tries to connect to ports 0-20000 on localhost and then prints out which ports it was able to make a connection to:

import socket

connectedPorts = []
for port in range(0,20001):
    s=socket.socket(socket.AF_INET,socket.SOCK_STREAM);
    try:
        s.connect(('127.0.0.1',port))
        print("Connect succeeded on port %i" % port)
        connectedPorts.append(port)
    except Exception as e:
        print "Port %i: %s" % (port, e)
    s.close()

print("")
print("Connect succeeded on the following ports: ", connectedPorts)

... and for completeness, here is the working accept-on-port-20000 code:

import socket

s=socket.socket(socket.AF_INET,socket.SOCK_STREAM);
s.bind(('127.0.0.1',20000))
s.listen(1);
print("Calling accept...")
c,addr=s.accept()
print("Accept returned: [%s, %s]" % (c,addr))


问:
Conversion from Qstring to std::string throws an exception
Surprisingly the below code is throwing an exception.

```<code>QString qtemp = QDir::tempPath();
std::string temp = qtemp.toStdString();
std::cout<<temp<<std::endl;
</code>```

When I debugged using visual studio - I go the value for the variable qtemp . But in the next step I get a BAD Pointer from the debugger which results in an exception when I cout the same.

答: This is a known symptom if you're mixing debug and release DLLs.</p>

ContentLicense: CC BY-SA 3.0

Body:
Surprisingly the below code is throwing an exception.

QString qtemp = QDir::tempPath();
std::string temp = qtemp.toStdString();
std::cout<<temp<<std::endl;

When I debugged using visual studio - I go the value for the variable qtemp . But in the next step I get a BAD Pointer from the debugger which results in an exception when I cout the same.


问:
Component not updating after action is dispatched - react-redux
I'm using react-native and am having an issue where my action is being dispatched and the reducer is modifying the state, however my component is not re-rendering.  My reducer is using the spread operator to create a new object.  It looks like mapStateToProps is not being called again after the store is updated. I'm unsure what I'm missing.

Creating the provier

class App extends React.Component {
  render() {
    return (
      <Provider store={createStore(rootReducer, middleware)}>
        <View style={styles.container}>
          <DeckListScreen />
        </View>
      </Provider>
    );
  }
}
```

<p>Connecting the component to the provider</p>

<pre class="lang-js prettyprint-override"><code>class DeckListScreen extends React.Component {
  componentDidMount() {
    this.props.dispatch(handleInitialData())
  }

  render() {
    return(
      <View>
        <Text>{JSON.stringify(this.props.decks, null, 2)}</Text>
      </View
    )
  }
}
function mapStateToProps({decks}) {
  console.log('mapStateToProps - decks:', decks)
  return {
    decks: decks,
    loading: Object.keys(decks).length === 0 ? true : false
  }
}

export default connect(mapStateToProps)(DeckListScreen)
</code>```

Reducer that returns a new object

export default function decks(state = {}, action) {
  switch(action.type) {
    case GET_DECKS:
      const { decks } = action
      return {
          ...state,
          ...decks
      }
    default:
      return state
  }
}

```

<p>Here is the console output</p>

```Running application on iPhone.
mapStateToProps - decks: Object {}
mapStateToProps - decks: Object {}

ACTION TYPE:
GET_DECKS

OLD STATE:
Object {
  "decks": Object {},
}

ACTION:
Object {
  "decks": Object {
    "JavaScript": Object {
      "questions": Array [
        Object {
          "answer": "The combination of a function and the lexical environment within which that function was declared.",
          "question": "What is a closure?",
        },
      ],
      "title": "JavaScript",
    },
    "React": Object {
      "questions": Array [
        Object {
          "answer": "A library for managing user interfaces",
          "question": "What is React?",
        },
        Object {
          "answer": "The componentDidMount lifecycle event",
          "question": "Where do you make Ajax requests in React?",
        },
      ],
      "title": "React",
    },
  },
  "type": "GET_DECKS",
}

NEW STATE:
Object {
  "decks": Object {
    "JavaScript": Object {
      "questions": Array [
        Object {
          "answer": "The combination of a function and the lexical environment within which that function was declared.",
          "question": "What is a closure?",
        },
      ],
      "title": "JavaScript",
    },
    "React": Object {
      "questions": Array [
        Object {
          "answer": "A library for managing user interfaces",
          "question": "What is React?",
        },
        Object {
          "answer": "The componentDidMount lifecycle event",
          "question": "Where do you make Ajax requests in React?",
        },
      ],
      "title": "React",
    },
  },
}
```

答: createStore(rootReducer, middleware) needs to be pulled into a separate variable above App.js. Every time App component re-renders a new store is created which reverts your reducer state.

Body:
I'm using react-native and am having an issue where my action is being dispatched and the reducer is modifying the state, however my component is not re-rendering.  My reducer is using the spread operator to create a new object.  It looks like mapStateToProps is not being called again after the store is updated. I'm unsure what I'm missing.

Creating the provier

class App extends React.Component {
  render() {
    return (
      <Provider store={createStore(rootReducer, middleware)}>
        <View style={styles.container}>
          <DeckListScreen />
        </View>
      </Provider>
    );
  }
}

Connecting the component to the provider

class DeckListScreen extends React.Component {
  componentDidMount() {
    this.props.dispatch(handleInitialData())
  }

  render() {
    return(
      <View>
        <Text>{JSON.stringify(this.props.decks, null, 2)}</Text>
      </View
    )
  }
}
function mapStateToProps({decks}) {
  console.log('mapStateToProps - decks:', decks)
  return {
    decks: decks,
    loading: Object.keys(decks).length === 0 ? true : false
  }
}

export default connect(mapStateToProps)(DeckListScreen)

Reducer that returns a new object

export default function decks(state = {}, action) {
  switch(action.type) {
    case GET_DECKS:
      const { decks } = action
      return {
          ...state,
          ...decks
      }
    default:
      return state
  }
}

Here is the console output

Running application on iPhone.
mapStateToProps - decks: Object {}
mapStateToProps - decks: Object {}

ACTION TYPE:
GET_DECKS

OLD STATE:
Object {
  "decks": Object {},
}

ACTION:
Object {
  "decks": Object {
    "JavaScript": Object {
      "questions": Array [
        Object {
          "answer": "The combination of a function and the lexical environment within which that function was declared.",
          "question": "What is a closure?",
        },
      ],
      "title": "JavaScript",
    },
    "React": Object {
      "questions": Array [
        Object {
          "answer": "A library for managing user interfaces",
          "question": "What is React?",
        },
        Object {
          "answer": "The componentDidMount lifecycle event",
          "question": "Where do you make Ajax requests in React?",
        },
      ],
      "title": "React",
    },
  },
  "type": "GET_DECKS",
}

NEW STATE:
Object {
  "decks": Object {
    "JavaScript": Object {
      "questions": Array [
        Object {
          "answer": "The combination of a function and the lexical environment within which that function was declared.",
          "question": "What is a closure?",
        },
      ],
      "title": "JavaScript",
    },
    "React": Object {
      "questions": Array [
        Object {
          "answer": "A library for managing user interfaces",
          "question": "What is React?",
        },
        Object {
          "answer": "The componentDidMount lifecycle event",
          "question": "Where do you make Ajax requests in React?",
        },
      ],
      "title": "React",
    },
  },
}


问:
how to do ajax callback in javascript
My scenario is , I have static data that is loaded in div, once after loaded I need to make ajax call and override the static data with new data, How to do the following in javascript

As I am newbie to lit-element, I dontknow how to do using callback function bit confused.
once the div is loaded I need to make ajax call and override the static data with new data. I got stuck please help or any alternatives

```<code>import { LitElement, html, css } from 'https://unpkg.com/@polymer/lit-element/lit-element.js?module';
export class Example extends LitElement {
  static get properties() {
    return {
      staticobj: {type: Object}
   }
 }

constructor() {
    super();
   this.static=[{
     id: "value1",
     country: "TH",
     fee: 100
   },{
    id:"value2",
    country: "SG",
    fee: 200
  }]
}

handleCall(id){
 $.ajax({
   url: "/en",
   method: 'get',
   global: false,
   async: false,
   data: {
     value: id
   },
   success: function (data) {
     callback(data, passData)
   }
 })
this.static=data; //override the static data
}

render(){
   this.static.map((e)=>{
    return html`
   <div id="list">// call the ajax function once div loaded
     <p>${e.id}</p>
     <h6>${e.country}</h6>
     <h5>${e.fee}</h5>

  </div>
   `
   })
 }
}
</code>```

答:
You should get into the ES6 and LitElement mind set. Forget JQuery and use fetch (preferably with ES8 async/await). Fetch your data in LitElement's firstUpdated(). Then replace your array itself (the change won't be see if you replace the array elements themselves, because the change won't be rendered):

```<code>import { html, css, LitElement } from 'lit-element';

export default class FetchLit extends LitElement {
  static get styles() {
    return css`
      :host {
        display: block;
        padding: 5px;
      }
    `;
  }

  static get properties() {
    return {
      users: { type: Array },
    };
  }

  constructor() {
    super();
    this.users = [
      {
        firstName: 'Jane',
        lastName: 'Doe',
        email: 'jane.doe@somewhere.com',
      },
    ];
  }

  // Don't use connectedCallback() since it can't be async
  async firstUpdated() {
    await fetch(`https://demo.vaadin.com/demo-data/1.0/people?count=10`)
      .then(r => r.json())
      .then(async data => {
        this.users = data.result;
      });
  }

  render() {
    return html`
      <ul>
        ${this.users.map(
          u =>
            html`
              <li>${u.lastName}, ${u.firstName} - ${u.email}</li>
            `,
        )}
      </ul>
    `;
  }
}

window.customElements.define('fetch-lit', FetchLit);

</code>```

You can see this example at https://stackblitz.com/edit/fetch-lit

Title: how to do ajax callback in javascript

Body:
My scenario is , I have static data that is loaded in div, once after loaded I need to make ajax call and override the static data with new data, How to do the following in javascript

As I am newbie to lit-element, I dontknow how to do using callback function bit confused.
once the div is loaded I need to make ajax call and override the static data with new data. I got stuck please help or any alternatives

import { LitElement, html, css } from 'https://unpkg.com/@polymer/lit-element/lit-element.js?module';
export class Example extends LitElement {
  static get properties() {
    return {
      staticobj: {type: Object}
   }
 }

constructor() {
    super();
   this.static=[{
     id: "value1",
     country: "TH",
     fee: 100
   },{
    id:"value2",
    country: "SG",
    fee: 200
  }]
}

handleCall(id){
 $.ajax({
   url: "/en",
   method: 'get',
   global: false,
   async: false,
   data: {
     value: id
   },
   success: function (data) {
     callback(data, passData)
   }
 })
this.static=data; //override the static data
}

render(){
   this.static.map((e)=>{
    return html`

// call the ajax function once div loaded

${e.id}

${e.country}

${e.fee}

   `
   })
 }
}

Body:
You should get into the ES6 and LitElement mind set. Forget JQuery and use fetch (preferably with ES8 async/await). Fetch your data in LitElement's firstUpdated(). Then replace your array itself (the change won't be see if you replace the array elements themselves, because the change won't be rendered):

import { html, css, LitElement } from 'lit-element';

export default class FetchLit extends LitElement {
  static get styles() {
    return css`
      :host {
        display: block;
        padding: 5px;
      }
    `;
  }

  static get properties() {
    return {
      users: { type: Array },
    };
  }

  constructor() {
    super();
    this.users = [
      {
        firstName: 'Jane',
        lastName: 'Doe',
        email: 'jane.doe@somewhere.com',
      },
    ];
  }

  // Don't use connectedCallback() since it can't be async
  async firstUpdated() {
    await fetch(`https://demo.vaadin.com/demo-data/1.0/people?count=10`)
      .then(r => r.json())
      .then(async data => {
        this.users = data.result;
      });
  }

  render() {
    return html`
      <ul>
        ${this.users.map(
          u =>
            html`
              <li>${u.lastName}, ${u.firstName} - ${u.email}</li>
            `,
        )}
      </ul>
    `;
  }
}

window.customElements.define('fetch-lit', FetchLit);

You can see this example at https://stackblitz.com/edit/fetch-lit


问:
Creating query with Option<T> as parameter
I'm trying to make a mongo query (using Spring Data) for searching record by the Option value from Vavr. I have value Option userId and I'm wondering if it's possible to search in database by this parameter.

I have serched in MongoDB and Spring documentation, but in none of this is anything about Vavr type like Option. None of this query are working.

```<code>Option<Result> FindFirstByUserIdAndCreationDateDesc(String userId);

Option<Result> FindFirstByOptionUserIdAndCreationDateDesc(String userId);
</code>```

where userId is Vavr Option

```<code>Option<String> userId;
</code>```

答:
Vavr's Option and Java's Optional are types for eliminating the null value.

Database don't use optional values, they use null values, so unwrap the value to a null.

```<code>userId.getOrElse(null)
</code>```

However, be aware that in e.g. SQL databases, the null value doesn't compare equal to itself, so a WHERE userId = ? will return nothing if the ? argument is null. To find records with a null value, the SQL must be WHERE userId IS NULL, so unless your FindXxx methods knows this and account for it, the code will still not work for you.

Body:
I'm trying to make a mongo query (using Spring Data) for searching record by the Option value from Vavr. I have value Option userId and I'm wondering if it's possible to search in database by this parameter.

I have serched in MongoDB and Spring documentation, but in none of this is anything about Vavr type like Option. None of this query are working.

Option<Result> FindFirstByUserIdAndCreationDateDesc(String userId);

Option<Result> FindFirstByOptionUserIdAndCreationDateDesc(String userId);

where userId is Vavr Option

Option<String> userId;

Body:
Vavr's Option and Java's Optional are types for eliminating the null value.

Database don't use optional values, they use null values, so unwrap the value to a null.

userId.getOrElse(null)

However, be aware that in e.g. SQL databases, the null value doesn't compare equal to itself, so a WHERE userId = ? will return nothing if the ? argument is null. To find records with a null value, the SQL must be WHERE userId IS NULL, so unless your FindXxx methods knows this and account for it, the code will still not work for you.


问:
Obtain the indices of neighboring elements within a radius
I have a NxN matrix and I want to find indices (or at least count) of non-zero elements within a radius R for each element in matrix. The matrix will be large so I plan to do the calculations using Numpy, and I need the indices because this matrix is linked to another with data-storage (which is a python list [[]] of objects).

The matrix looks like this:

where Green is the selected cell, Yellow - the surrounding area.

The main problem is the moving stencil, either in loop or vectorized.

I tried the following code which gives the correct coordinates (all within radius and excluding center) relative to the point, but I dont know how to apply it to the numpy array:

r = 2
neighbor_coords = []
for i in list(itertools.product(range(-r, r+1), repeat=2)):
    if any(i) and np.sqrt(i[0]**2 + i[1]**2) <= r:
        neighbor_coords.append(i)

>>> [(-2, 0), (-1, -1), (-1, 0), (-1, 1), (0, -2), (0, -1), (0, 1), (0, 2), (1, -1), (1, 0), (1, 1), (2, 0)]
```

Expected output is the indices or count of neighboring elements.

答:
```<code>>>> def find_ind(array,center,radius):
...     a = np.indices(array.shape).reshape(2,-1).T
...     return a[np.abs(a-np.array(center)).sum(1)<=int(radius)]-np.array(center)
...
>>> find_ind(np.zeros((7,7)),[4,4],2)
array([[-2,  0],
       [-1, -1],
       [-1,  0],
       [-1,  1],
       [ 0, -2],
       [ 0, -1],
       [ 0,  0],
       [ 0,  1],
       [ 0,  2],
       [ 1, -1],
       [ 1,  0],
       [ 1,  1],
       [ 2,  0]])
</code>```

Of course you can input the array itself in the function

Body:
I have a NxN matrix and I want to find indices (or at least count) of non-zero elements within a radius R for each element in matrix. The matrix will be large so I plan to do the calculations using Numpy, and I need the indices because this matrix is linked to another with data-storage (which is a python list [[]] of objects).

The matrix looks like this:

where Green is the selected cell, Yellow - the surrounding area.

The main problem is the moving stencil, either in loop or vectorized.

I tried the following code which gives the correct coordinates (all within radius and excluding center) relative to the point, but I dont know how to apply it to the numpy array:

r = 2
neighbor_coords = []
for i in list(itertools.product(range(-r, r+1), repeat=2)):
    if any(i) and np.sqrt(i[0]**2 + i[1]**2) <= r:
        neighbor_coords.append(i)

>>> [(-2, 0), (-1, -1), (-1, 0), (-1, 1), (0, -2), (0, -1), (0, 1), (0, 2), (1, -1), (1, 0), (1, 1), (2, 0)]

Expected output is the indices or count of neighboring elements.

Body:
>>> def find_ind(array,center,radius):
...     a = np.indices(array.shape).reshape(2,-1).T
...     return a[np.abs(a-np.array(center)).sum(1)<=int(radius)]-np.array(center)
...
>>> find_ind(np.zeros((7,7)),[4,4],2)
array([[-2,  0],
       [-1, -1],
       [-1,  0],
       [-1,  1],
       [ 0, -2],
       [ 0, -1],
       [ 0,  0],
       [ 0,  1],
       [ 0,  2],
       [ 1, -1],
       [ 1,  0],
       [ 1,  1],
       [ 2,  0]])

Of course you can input the array itself in the function


问:
Change Fragment width in Orientation change
I'm currently learning Android Studio development and I'm stumbled with a tutorial's exercise (Stuck for almost 2 weeks).
It required me to use Fragment to create this appearance :

See Image

Here is my code :

home.java

```<code>public class home extends AppCompatActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_home);

        Intent previousIntent = getIntent();
        String username = previousIntent.getStringExtra("username");

        Bundle sendDataToBody = new Bundle();
        sendDataToBody.putString("username", username);

        // Fragment

        FragmentManager fragmentManager = getSupportFragmentManager();
        FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();

        WindowManager windowManager = getWindowManager();
        Point size = new Point();

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB_MR2) {
            windowManager.getDefaultDisplay().getSize(size);

            if (size.x > size.y) {
                // landscape

                Menu fragmentMenu = new Menu();
                body fragmentBody = new body();

                fragmentBody.setArguments(sendDataToBody);

                fragmentTransaction.add(R.id.menuFrame, fragmentMenu);
                fragmentTransaction.add(R.id.bodyFrame, fragmentBody);
            } else {
                // portrait

                Menu fragmentMenu = new Menu();
                fragmentTransaction.add(R.id.menuFrame, fragmentMenu);
            }
        } else {
            Display display = windowManager.getDefaultDisplay();

            if (display.getRotation() == Surface.ROTATION_90
                    || display.getRotation() == Surface.ROTATION_270) {
                // landscape

                Menu fragmentMenu = new Menu();
                body fragmentBody = new body();

                fragmentBody.setArguments(sendDataToBody);

                fragmentTransaction.add(R.id.menuFrame, fragmentMenu);
                fragmentTransaction.add(R.id.bodyFrame, fragmentBody);
            } else {
                //portrait
                Menu fragmentMenu = new Menu();
                fragmentTransaction.add(R.id.menuFrame, fragmentMenu);
            }
        }

        fragmentTransaction.commit();
        // End of Fragment
    }
}
</code>```

and my home.xml :

```<code>   <?xml version="1.0" encoding="utf-8"?>
   <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
       xmlns:app="http://schemas.android.com/apk/res-auto"
       xmlns:tools="http://schemas.android.com/tools"
       android:layout_width="match_parent"
       android:layout_height="match_parent"
       android:paddingTop="@dimen/container_padding_vertical"
       android:paddingBottom="@dimen/container_padding_vertical"
       android:paddingRight="@dimen/container_padding_horizontal"
       android:paddingLeft="@dimen/container_padding_horizontal"
       android:orientation="vertical"
       tools:context=".home">

       <FrameLayout
           android:layout_width="match_parent"
           android:layout_height="match_parent"
           android:layout_weight="1"
           android:id="@+id/menuFrame"></FrameLayout>

       <FrameLayout
           android:layout_width="match_parent"
           android:layout_height="match_parent"
           android:layout_weight="1"
           android:id="@+id/bodyFrame"></FrameLayout>

   </LinearLayout>
</code>```

As you can see,
If I run these codes, in portrait mode it work as the picture.

But when I change the orientation to landscape,
The Button still go fullscreen.

How can I change the button to be only some part like the picture ?

Note : this is my first Q in stackOverflow about android. I hope my explanation is clear enough

Edit

Here is my menuFragment.xml

```<code>    <?xml version="1.0" encoding="utf-8"?>
  <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
      xmlns:tools="http://schemas.android.com/tools"
      android:layout_width="match_parent"
      android:layout_height="match_parent"
      android:orientation="vertical"
      tools:context=".Menu">

      <Button
          android:layout_width="match_parent"
          android:layout_height="wrap_content"
          android:id="@+id/convertBtn"
          android:text="Convert USD/IDR" />

      <Button
          android:layout_width="match_parent"
          android:layout_height="wrap_content"
          android:id="@+id/logoutBtn"
          android:text="Logout"/>

  </LinearLayout>
</code>```

Here is my bodyFragment.xml :

```<code><?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context=".body">

    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/username_show"/>

</LinearLayout>
</code>```

答:
What you want to do here is use the Resources Framework to provide two different layouts for each of your Fragments and your Activity. One layout will be for portrait orientation, and the other will be for landscape orientation.

The structure will look like this:

```<code>res/
    layout/
        activity_home.xml
        fragment_body.xml
        fragment_menu.xml
    layout-land/
        activity_home.xml
        fragment_body.xml
        fragment_menu.xml
</code>```

You don't have to do anything in your code. Just use setContentView(R.layout.activity_home) in your Activity and the correct version (portrait or landscape) will be selected automatically for you.

Similarly, in your Fragments you can write inflater.inflate(R.layout.fragment_body, parent, false) and the correct version will be selected automatically for you.

Now, you just have to make sure that your different xml files do what you want. For example, in the portrait one you can make your buttons match the screen width:

```<code><Button
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    .../>

<Button
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    .../>
</code>```

But then in your landscape one you can make your buttons wrap:

```<code><Button
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    .../>

<Button
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    .../>
</code>```

As long as you use the same ids in the landscape and portrait versions, everything will "just work".

Body:
I'm currently learning Android Studio development and I'm stumbled with a tutorial's exercise (Stuck for almost 2 weeks).
It required me to use Fragment to create this appearance :

See Image

Here is my code :

home.java

public class home extends AppCompatActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_home);

        Intent previousIntent = getIntent();
        String username = previousIntent.getStringExtra("username");

        Bundle sendDataToBody = new Bundle();
        sendDataToBody.putString("username", username);

        // Fragment

        FragmentManager fragmentManager = getSupportFragmentManager();
        FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();

        WindowManager windowManager = getWindowManager();
        Point size = new Point();

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB_MR2) {
            windowManager.getDefaultDisplay().getSize(size);

            if (size.x > size.y) {
                // landscape

                Menu fragmentMenu = new Menu();
                body fragmentBody = new body();

                fragmentBody.setArguments(sendDataToBody);

                fragmentTransaction.add(R.id.menuFrame, fragmentMenu);
                fragmentTransaction.add(R.id.bodyFrame, fragmentBody);
            } else {
                // portrait

                Menu fragmentMenu = new Menu();
                fragmentTransaction.add(R.id.menuFrame, fragmentMenu);
            }
        } else {
            Display display = windowManager.getDefaultDisplay();

            if (display.getRotation() == Surface.ROTATION_90
                    || display.getRotation() == Surface.ROTATION_270) {
                // landscape

                Menu fragmentMenu = new Menu();
                body fragmentBody = new body();

                fragmentBody.setArguments(sendDataToBody);

                fragmentTransaction.add(R.id.menuFrame, fragmentMenu);
                fragmentTransaction.add(R.id.bodyFrame, fragmentBody);
            } else {
                //portrait
                Menu fragmentMenu = new Menu();
                fragmentTransaction.add(R.id.menuFrame, fragmentMenu);
            }
        }

        fragmentTransaction.commit();
        // End of Fragment
    }
}

and my home.xml :

   <?xml version="1.0" encoding="utf-8"?>
   <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
       xmlns:app="http://schemas.android.com/apk/res-auto"
       xmlns:tools="http://schemas.android.com/tools"
       android:layout_width="match_parent"
       android:layout_height="match_parent"
       android:paddingTop="@dimen/container_padding_vertical"
       android:paddingBottom="@dimen/container_padding_vertical"
       android:paddingRight="@dimen/container_padding_horizontal"
       android:paddingLeft="@dimen/container_padding_horizontal"
       android:orientation="vertical"
       tools:context=".home">

       <FrameLayout
           android:layout_width="match_parent"
           android:layout_height="match_parent"
           android:layout_weight="1"
           android:id="@+id/menuFrame"></FrameLayout>

       <FrameLayout
           android:layout_width="match_parent"
           android:layout_height="match_parent"
           android:layout_weight="1"
           android:id="@+id/bodyFrame"></FrameLayout>

   </LinearLayout>

As you can see,
If I run these codes, in portrait mode it work as the picture.

But when I change the orientation to landscape,
The Button still go fullscreen.

How can I change the button to be only some part like the picture ?

Note : this is my first Q in stackOverflow about android. I hope my explanation is clear enough

Edit

Here is my menuFragment.xml

    <?xml version="1.0" encoding="utf-8"?>
  <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
      xmlns:tools="http://schemas.android.com/tools"
      android:layout_width="match_parent"
      android:layout_height="match_parent"
      android:orientation="vertical"
      tools:context=".Menu">

      <Button
          android:layout_width="match_parent"
          android:layout_height="wrap_content"
          android:id="@+id/convertBtn"
          android:text="Convert USD/IDR" />

      <Button
          android:layout_width="match_parent"
          android:layout_height="wrap_content"
          android:id="@+id/logoutBtn"
          android:text="Logout"/>

  </LinearLayout>

Here is my bodyFragment.xml :

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context=".body">

    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/username_show"/>

</LinearLayout>

Body:
What you want to do here is use the Resources Framework to provide two different layouts for each of your Fragments and your Activity. One layout will be for portrait orientation, and the other will be for landscape orientation.

The structure will look like this:

res/
    layout/
        activity_home.xml
        fragment_body.xml
        fragment_menu.xml
    layout-land/
        activity_home.xml
        fragment_body.xml
        fragment_menu.xml

You don't have to do anything in your code. Just use setContentView(R.layout.activity_home) in your Activity and the correct version (portrait or landscape) will be selected automatically for you.

Similarly, in your Fragments you can write inflater.inflate(R.layout.fragment_body, parent, false) and the correct version will be selected automatically for you.

Now, you just have to make sure that your different xml files do what you want. For example, in the portrait one you can make your buttons match the screen width:

<Button
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    .../>

<Button
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    .../>

But then in your landscape one you can make your buttons wrap:

<Button
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    .../>

<Button
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    .../>

As long as you use the same ids in the landscape and portrait versions, everything will "just work".


答:
For showing/hiding divs based on screen size, bootstrap has a few classes made to fit the standard bootstrap breakpoints to show/hide depending on screen size:
https://getbootstrap.com/docs/4.0/utilities/display/</p>

Title: bootstrap - apply class based on screen size


问:
Injecting data object to window with Puppeteer
Background

I am using Puppeteer to create some PDFs. I need to inject some data into the page when Puppeteer loads it.

Problem

I have tried using evaluateOnNewDocument() which was successful when using a String only. When I try with an Object it fails. I also tried with evaluate() and it fails regardless of what I pass in.

Example

```<code>// Works
    await page.evaluateOnNewDocument(() => {
           window.pdfData = {};
           window.pdfData = "Some String";
    });

// Does not work
    await page.evaluateOnNewDocument(() => {
           window.pdfData = {};
           window.pdfData = data;
    });

// Fails
await page.evaluate(data => {
     window.pdfData = {};
     window.pdfData = data;
}, data);
</code>```

I would like to access this object like this,

```<code>const data = window.pdfData;
</code>```

Question

What is the proper way to pass a data object into window on a loaded Puppeteer page so that it can be accessed within the page to use the data client side?

答:
Passing object to evaluate

You can pass data which will be serialized as JSON.

```<code>await page.evaluateOnNewDocument(data => { // <-- pass as parameter
  window.pdfData = data; // <-- read it here
}, data); // <-- pass as argument
</code>```

Passing object to evaluateOnNewDocument

evaluateOnNewDocument works similarly to evaluate, except it will run whenever there is a new window/navigation/frame. This way the data will stay even if you navigate away to another page.

You can pass data and read inside the function.

```<code>await page.evaluateOnNewDocument(data => {
  window.pdfData = data;
}, data);
</code>```

Body:
Background

I am using Puppeteer to create some PDFs. I need to inject some data into the page when Puppeteer loads it.

Problem

I have tried using evaluateOnNewDocument() which was successful when using a String only. When I try with an Object it fails. I also tried with evaluate() and it fails regardless of what I pass in.

Example

// Works
    await page.evaluateOnNewDocument(() => {
           window.pdfData = {};
           window.pdfData = "Some String";
    });

// Does not work
    await page.evaluateOnNewDocument(() => {
           window.pdfData = {};
           window.pdfData = data;
    });

// Fails
await page.evaluate(data => {
     window.pdfData = {};
     window.pdfData = data;
}, data);

I would like to access this object like this,

const data = window.pdfData;

Question

What is the proper way to pass a data object into window on a loaded Puppeteer page so that it can be accessed within the page to use the data client side?

Body:
Passing object to evaluate

You can pass data which will be serialized as JSON.

await page.evaluateOnNewDocument(data => { // <-- pass as parameter
  window.pdfData = data; // <-- read it here
}, data); // <-- pass as argument

Passing object to evaluateOnNewDocument

evaluateOnNewDocument works similarly to evaluate, except it will run whenever there is a new window/navigation/frame. This way the data will stay even if you navigate away to another page.

You can pass data and read inside the function.

await page.evaluateOnNewDocument(data => {
  window.pdfData = data;
}, data);


问:
How to switch activity without animation in Android?
How can I use properly the Intent flag FLAG_ACTIVITY_NO_ANIMATION in AndroidManifest file? I supose my problem is trivial, but I can't find good example or solution to it.

    <intent-filter>
        <data android:name="android.content.Intent.FLAG_ACTIVITY_NO_ANIMATION" />
    </intent-filter>
```
<p>However no error is reported by compliator, but <code>data</code> isn't correct.
I just want to disable animation in case switching between activities. I can use <code>getWindow().setWindowAnimations(0);</code> in onCreate or onResume rather but using flag is better way, isn't it?</p>
<p>I can use also in code:</p>
<pre class="lang-java prettyprint-override"><code>    Intent intent = new Intent(v.getContext(), newactivity.class);
    intent.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
    getContext().startActivity(intent);
</code>```

But I want to use this flag in Android Manifest. To disable animation also in case returning from second activity to first.

答:
The line in the theme style works fine, yet that replaces the animation with a white screen. Especially on a slower phone - it is really annoying.
So, if you want an instant transition - you could use this in the theme style:</p>

```<code><item name="android:windowAnimationStyle">@null</item>
<item name="android:windowDisablePreview">true</item>
</code>```

Body:
How can I use properly the Intent flag FLAG_ACTIVITY_NO_ANIMATION in AndroidManifest file? I supose my problem is trivial, but I can't find good example or solution to it.

    <intent-filter>
        <data android:name="android.content.Intent.FLAG_ACTIVITY_NO_ANIMATION" />
    </intent-filter>

However no error is reported by compliator, but data isn't correct.
I just want to disable animation in case switching between activities. I can use getWindow().setWindowAnimations(0); in onCreate or onResume rather but using flag is better way, isn't it?

I can use also in code:

    Intent intent = new Intent(v.getContext(), newactivity.class);
    intent.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
    getContext().startActivity(intent);

But I want to use this flag in Android Manifest. To disable animation also in case returning from second activity to first.

Body:
The line in the theme style works fine, yet that replaces the animation with a white screen. Especially on a slower phone - it is really annoying.
So, if you want an instant transition - you could use this in the theme style:

<item name="android:windowAnimationStyle">@null</item>
<item name="android:windowDisablePreview">true</item>


问:
Constructor is not called with /NODEFAULTLIB
I'm using /NODEFAULTLIB to disable CRT(C Runtime), however my constructor is not called, which ends up causing an error in std::map (Access violation) because it is not initialized properly, since std::map constructor it's not called.

Code compiled with LLVM 8.0.0, compiled in mode debug x86

```<code>class c_test
{
public:

    c_test( int a ) // Constructor not called
    {
        printf( "Test: %i\n", a ); // Doesn't appear and breakpoint is not reached
    }

    void add( const std::string& key, const std::string& val )
    {
        _data[ key ] = val;
    }

private:
    std::map< std::string, std::string >                        _data;
};

c_test test{ 1337 };

int main()
{
    test.add( "qwrqrqr", "23142421" );
    test.add( "awrqw", "12asa1faf" );

    return 1;
}
</code>```

I've implemented my own functions new(HeapAlloc), delete(HeapFree), printf, memcpy, memmove, etc, and all are working perfectly, I have no idea why this happening.

答:
I discovered the problem and solved, one guy from another forum said that I needed manually call constructors that are stored in pointers in .CRT section, I just did it and it worked perfectly

I just called _GLOBAL__sub_I_main_cpp function that calls my constructor and solved all my problems, thanks for the answers.

Body:
I'm using /NODEFAULTLIB to disable CRT(C Runtime), however my constructor is not called, which ends up causing an error in std::map (Access violation) because it is not initialized properly, since std::map constructor it's not called.

Code compiled with LLVM 8.0.0, compiled in mode debug x86

class c_test
{
public:

    c_test( int a ) // Constructor not called
    {
        printf( "Test: %i\n", a ); // Doesn't appear and breakpoint is not reached
    }

    void add( const std::string& key, const std::string& val )
    {
        _data[ key ] = val;
    }

private:
    std::map< std::string, std::string >                        _data;
};

c_test test{ 1337 };

int main()
{
    test.add( "qwrqrqr", "23142421" );
    test.add( "awrqw", "12asa1faf" );

    return 1;
}

I've implemented my own functions new(HeapAlloc), delete(HeapFree), printf, memcpy, memmove, etc, and all are working perfectly, I have no idea why this happening.


问:
Adding the next letter to user name if samaccountname is found
I am automating the new user account process from Cherwell to AD, I am stuck with duplicate samaccountname.  I have successfully gotten accounts to create if the samaccountname does not already exist.  I have a check in place that for now just writes the output to say whether the name is found or not.

Tinker Bell is my test user as she is my daughters favourite character.

```<code>$FirstName = “tinker”
$SurName = “bell”
for ($i = 1; $i -le $SurName.Length; ++$i) {

$Account = $null;
$Identity = $FirstName + $SurName.Substring(0,$i)
$Account = Get-ADUser -Filter {sAMAccountName -eq $Identity}
if ($Account -eq $null) {"User does not exist in AD"}
Else {"User found in AD"}
write-Output $Identity
}
</code>```

I have this in place which does what it should do, I am just not sure how to stop it when the next samaccountname is created.

This is what I get as output

```<code>User found in AD
tinkerb
User does not exist in AD
tinkerbe
User does not exist in AD
tinkerbel
User does not exist in AD
tinkerbell
</code>```

So it does the first part correctly, finds the account and then moves on to the next one, but then it just loops and I am not sure how to drop it out to have a variable called $newSam created when in this example 'tinkerbe' is determined.

S.

答:
Turn your code into a simple function that returns the first available user name:

```<code>function New-Username
{
  param(
    [string]$FirstName,
    [string]$SurName
  )

  for ($i = 1; $i -le $SurName.Length; ++$i) {

    $Account = $null;
    $Identity = $FirstName + $SurName.Substring(0,$i)
    $Account = Get-ADUser -Filter {sAMAccountName -eq $Identity}
    if ($Account -eq $null) {
        return $Identity
    }
    else {
        Write-Warning "User found in AD: $Identity"
    }
  }

  throw "Unable to generate distinct username"
}
</code>```

and the use it like:

```<code>$NewUsername = New-Username -FirstName tinker -SurName bell
New-ADUser -SAMAccountName $NewUserName
</code>```

Body:
I am automating the new user account process from Cherwell to AD, I am stuck with duplicate samaccountname.  I have successfully gotten accounts to create if the samaccountname does not already exist.  I have a check in place that for now just writes the output to say whether the name is found or not.

Tinker Bell is my test user as she is my daughters favourite character.

$FirstName = “tinker”
$SurName = “bell”
for ($i = 1; $i -le $SurName.Length; ++$i) {

$Account = $null;
$Identity = $FirstName + $SurName.Substring(0,$i)
$Account = Get-ADUser -Filter {sAMAccountName -eq $Identity}
if ($Account -eq $null) {"User does not exist in AD"}
Else {"User found in AD"}
write-Output $Identity
}

I have this in place which does what it should do, I am just not sure how to stop it when the next samaccountname is created.

This is what I get as output

User found in AD
tinkerb
User does not exist in AD
tinkerbe
User does not exist in AD
tinkerbel
User does not exist in AD
tinkerbell

So it does the first part correctly, finds the account and then moves on to the next one, but then it just loops and I am not sure how to drop it out to have a variable called $newSam created when in this example 'tinkerbe' is determined.

S.

Body:
Turn your code into a simple function that returns the first available user name:

function New-Username
{
  param(
    [string]$FirstName,
    [string]$SurName
  )

  for ($i = 1; $i -le $SurName.Length; ++$i) {

    $Account = $null;
    $Identity = $FirstName + $SurName.Substring(0,$i)
    $Account = Get-ADUser -Filter {sAMAccountName -eq $Identity}
    if ($Account -eq $null) {
        return $Identity
    }
    else {
        Write-Warning "User found in AD: $Identity"
    }
  }

  throw "Unable to generate distinct username"
}

and the use it like:

$NewUsername = New-Username -FirstName tinker -SurName bell
New-ADUser -SAMAccountName $NewUserName


问:
How to get the actual data and not the object reference?
I'm new to Firebase and I'm using the Pyrebase library. I was able to authenticate successfully and I'm able to get data. The issue is, when I print the data out, it's printing out the reference object, not the actual data itself.

I've been searching online for a while and everything I've seen, shows that my code is correct. I've tried the .each method, but that doesn't work.

```<code>results = db.child("test").get()
for i in results.each():
    print(i)
</code>```

What I'm expecting is the data from my json to be displayed. What's happening, is the object reference is being passed, but that doesn't do me any good.

What the results are:

```<code><pyrebase.pyrebase.Pyre object at 0x03B48A90>
<pyrebase.pyrebase.Pyre object at 0x03B488D0>
<pyrebase.pyrebase.Pyre object at 0x03B48590>

Process finished with exit code 0
</code>```

答:
I reread the documentation and I believe I have a fix for it.
Original Code:

```<code>for i in results.each():
    print(i)
</code>```

Fix:

```<code>for result in results.each():
    print(result.val())
</code>```

I was missing the .val() during my print statement.

Body:
I'm new to Firebase and I'm using the Pyrebase library. I was able to authenticate successfully and I'm able to get data. The issue is, when I print the data out, it's printing out the reference object, not the actual data itself.

I've been searching online for a while and everything I've seen, shows that my code is correct. I've tried the .each method, but that doesn't work.

results = db.child("test").get()
for i in results.each():
    print(i)

What I'm expecting is the data from my json to be displayed. What's happening, is the object reference is being passed, but that doesn't do me any good.

What the results are:

<pyrebase.pyrebase.Pyre object at 0x03B48A90>
<pyrebase.pyrebase.Pyre object at 0x03B488D0>
<pyrebase.pyrebase.Pyre object at 0x03B48590>

Process finished with exit code 0

Body:
I reread the documentation and I believe I have a fix for it.
Original Code:

for i in results.each():
    print(i)

Fix:

for result in results.each():
    print(result.val())

I was missing the .val() during my print statement.


问:
How to save a user to a post when it is created
I am trying to display the name of the user that made a post in octobercms but haven't gotten it to work yet. This is what I have already done. I have extended the userModel in the boot method of my plugin.

```<code>  public function boot()
{
         User::extend(function($model){
        $model->hasMany['adverts'] = ['Corymillz\Adverts\Models\Advert'];
    });
}
</code>```

and in my main plugin I have

```<code>public $belongsTo = [
'user' => [
'RainLab\User\Models\User', 'key' => 'user_id']
];
</code>```

In my twig template i am trying something  like {{ ads.user.name }} for the specific user. This works correctly but how to i attach a post to a logged in user. Don't know if i am asking the question right. When a logged in user makes a post. His name should appear with it using {{ ads.user.name}}  instead of me manually adding a user to a post in the backend

With user_id in my advert table
I have tried adding this to my form .php file but returns an error

$advert->user_id = Auth ::user()->id;
$advert->save();

答:
Solved it by adding
use Auth;

at the top of the file and

$advert->user_id = Auth ::user()->id; $advert->save();

Body:
I am trying to display the name of the user that made a post in octobercms but haven't gotten it to work yet. This is what I have already done. I have extended the userModel in the boot method of my plugin.

  public function boot()
{
         User::extend(function($model){
        $model->hasMany['adverts'] = ['Corymillz\Adverts\Models\Advert'];
    });
}

and in my main plugin I have

public $belongsTo = [
'user' => [
'RainLab\User\Models\User', 'key' => 'user_id']
];

In my twig template i am trying something  like {{ ads.user.name }} for the specific user. This works correctly but how to i attach a post to a logged in user. Don't know if i am asking the question right. When a logged in user makes a post. His name should appear with it using {{ ads.user.name}}  instead of me manually adding a user to a post in the backend

With user_id in my advert table
I have tried adding this to my form .php file but returns an error

$advert->user_id = Auth ::user()->id;
$advert->save();


问:
How do i clear column and fill data again if value is less than old value |excel|VBA|
I have a Excel

Sheet 1

Sheet 2

Value of Sheet 1 => F5 => '50'  => is referenced in Sheet 2  => E4 => '50'

When i enter Value in Sheet 1 in place of F5 => Value gets Change in Sheet 2 => E4 => Automatically

using below code the DATA is Printed that many times
My code

module : mac

```<code>Dim ws As Worksheet
Dim rDest As Range
Dim lCount As Long
Dim sValue As String

Set ws = ThisWorkbook.Sheets("Sheet2")
Set rDest = ws.Range("I2")

With ws.Range(rDest, ws.Cells(ws.Rows.Count, rDest.Column).End(xlUp))
    If .Row >= rDest.Row Then .ClearContents
End With

lCount = Val(ws.Range("E4").Value)
sValue = ws.Range("E8").Value

If lCount > 0 Then rDest.Resize(lCount) = sValue

End Sub
</code>```

Sheet 1 Code:

```<code>Private Sub Worksheet_Change(ByVal Target As Range)
    If Not Intersect(Sheets("Sheet1").Range("F5"), Target) Is Nothing Then
       Call mac
    End If
End Sub
</code>```

This is the Output

Like this Below Output :

https://paste.pics/494c856d2908a83ca031ee20bb706a09

My Above code Works Perfectly according to above mentioned output
But as Some Flaws in it

Assume

Condition 1:

if the value entered is '50'  => then data in the Column "I" and "J" gets printed 50 times =>  right [Perfect]

Condition 2:

if the value entered is '60'  => then data in the Coulmn "I" and "J" gets appends
with the previous data which it as "50"  => 50 + 10 => 60  => this is right [perfect]

Condition 3:

Assume the Column "I:J" already as DATA => upto the Range '60'
if the entered value is less then '60'  like '30' then updation should happen only 30 times in Column "I:J" the Data should be Printed But Nothing is happening
appending happens but clearing data does not happen if range is lesser then old value

There as to be some mechanism like

if Count is 50 => print => I,J

if Count is more then 50 => append I,J

if Count is less then 50 => clear column I,J and then => fill the Column I ,J

How do i achieve this mechanism?

答:
As far as I can tell your code works... is just a matter of expanding the range if
 I understood right what you are asking. See comments for the only 2 changes done to your code:

Sub mac()
Dim ws As Worksheet
Dim rDest As Range
Dim lCount As Long
Dim sValue As String

Set ws = ThisWorkbook.Sheets("Sheet2")
Set rDest = ws.Range("I2")

With ws.Range(rDest, ws.Cells(ws.Rows.Count, rDest.Column + 1).End(xlUp)) 'Add another column to your selection here
    If .Row >= rDest.Row Then .ClearContents
End With

lCount = Val(ws.Range("E4").Value)
sValue = ws.Range("E8").Value

If lCount > 0 Then rDest.Resize(lCount, 2) = sValue 'Resize to 2 columns instead of the default 1.

End Sub
```

PS: please let me know if I misunderstood your query.

Body:
I have a Excel

Sheet 1

Sheet 2

Value of Sheet 1 => F5 => '50'  => is referenced in Sheet 2  => E4 => '50'

When i enter Value in Sheet 1 in place of F5 => Value gets Change in Sheet 2 => E4 => Automatically

using below code the DATA is Printed that many times
My code

module : mac

Dim ws As Worksheet
Dim rDest As Range
Dim lCount As Long
Dim sValue As String

Set ws = ThisWorkbook.Sheets("Sheet2")
Set rDest = ws.Range("I2")

With ws.Range(rDest, ws.Cells(ws.Rows.Count, rDest.Column).End(xlUp))
    If .Row >= rDest.Row Then .ClearContents
End With

lCount = Val(ws.Range("E4").Value)
sValue = ws.Range("E8").Value

If lCount > 0 Then rDest.Resize(lCount) = sValue

End Sub

Sheet 1 Code:

Private Sub Worksheet_Change(ByVal Target As Range)
    If Not Intersect(Sheets("Sheet1").Range("F5"), Target) Is Nothing Then
       Call mac
    End If
End Sub

This is the Output

Like this Below Output :

https://paste.pics/494c856d2908a83ca031ee20bb706a09

My Above code Works Perfectly according to above mentioned output
But as Some Flaws in it

Assume

Condition 1:

if the value entered is '50'  => then data in the Column "I" and "J" gets printed 50 times =>  right [Perfect]

Condition 2:

if the value entered is '60'  => then data in the Coulmn "I" and "J" gets appends
with the previous data which it as "50"  => 50 + 10 => 60  => this is right [perfect]

Condition 3:

Assume the Column "I:J" already as DATA => upto the Range '60'
if the entered value is less then '60'  like '30' then updation should happen only 30 times in Column "I:J" the Data should be Printed But Nothing is happening
appending happens but clearing data does not happen if range is lesser then old value

There as to be some mechanism like

if Count is 50 => print => I,J

if Count is more then 50 => append I,J

if Count is less then 50 => clear column I,J and then => fill the Column I ,J

How do i achieve this mechanism?

Body:
As far as I can tell your code works... is just a matter of expanding the range if
 I understood right what you are asking. See comments for the only 2 changes done to your code:

Sub mac()
Dim ws As Worksheet
Dim rDest As Range
Dim lCount As Long
Dim sValue As String

Set ws = ThisWorkbook.Sheets("Sheet2")
Set rDest = ws.Range("I2")

With ws.Range(rDest, ws.Cells(ws.Rows.Count, rDest.Column + 1).End(xlUp)) 'Add another column to your selection here
    If .Row >= rDest.Row Then .ClearContents
End With

lCount = Val(ws.Range("E4").Value)
sValue = ws.Range("E8").Value

If lCount > 0 Then rDest.Resize(lCount, 2) = sValue 'Resize to 2 columns instead of the default 1.

End Sub

PS: please let me know if I misunderstood your query.


问:
Div height according to content
I am working on a Modal with fixed header and footer.

Here is the Jsfiddle example

Currently the scrollable-stuff class height is 80%. If the content is less and there is no scrolling then i need to reduce the height and take the height of the content.

For example this example has a less content and there is no scroller but there is a empty space. I need to take the height of the content in case if there is no scrolling.

Any help or suggestion would be appreciated

Thanks in advace.

答:
Looks like the modal height is governed by this inline style:

This fixed height is what's causing the lack of responsiveness on the height of your modal. To fix this, strip out the height:300px;, though you may also need to find out where it's being set and change it there. A similar solution may work for the fixed width as well.

It also looks like there is a y-scrollbar, you've just got to x-scroll to get there :)

Title: Div height according to content

Body:
Looks like the modal height is governed by this inline style:

<div id="ModalPopup" style="width:600px;height:300px;">

This fixed height is what's causing the lack of responsiveness on the height of your modal. To fix this, strip out the height:300px;, though you may also need to find out where it's being set and change it there. A similar solution may work for the fixed width as well.

It also looks like there is a y-scrollbar, you've just got to x-scroll to get there :)


问:
my ubuntu system getting stuck while starting elastic search service
I have a ubuntu 18.04 system with 4 gb ram and 500gb hard disk.I have installed elastic search  in my system  like "sudo apt-get install elasticsearch"

but while starting elastic search with command : sudo service elasticsearch start

My system getting stuck, I am unable to do any thing.  how to fix this

答:
Maybe I can answer this question as I have encountered this problem a while ago and have also resolved it after some R&D.My ROR application is Live and have more than 8000+ images and CPU Intensive as there is lot more happening in my server as every request uses LAT/LNG to serve a geo-calculated response.I was facing this low memory issue similarly like yours when i started and reindexed my data on elasticsearch.

My Learnings-

ElasticSearch is a monster that will eat up your ram.

No Matter how optimized your keywords are OR the data is, that you are pushing to the elasticSearch to get indexed, you must keep a default buffer of backup memory.

What I did...that resolved my issue...

Add a Swap space which acts like a backup memory in case your RAM is eaten up.

I also upgraded to 8GB HD to be on safer side.

Now since i have followed the above mentioned steps, i am not facing any low memory error despite the size of my  indexex data becoming huge every month.Furthermore I am still good to go error free and memory related issues while indexing this huge data.

One more thing, which I recently did to improve memory consumption of my Rails app is injecting jmalloc inside my ruby 2.4.1.You can read more here but in simple words, It helps improve memory consumption of ruby apps.A copied explanation of Jmalloc would be like -

Ruby traditionally uses the C language function malloc to dynamically allocate, release, and re-allocate memory when storing objects. Jemalloc is a malloc(3) implementation developed by Jason Evans (hence the “je” initials at the start of malloc), which appears to be more effective at allocating memory compared to other allocators due to its focus on fragmentation avoidance and scalable concurrency support.

Below are my steps that I took to add Jmalloc into my existing Ruby 2.4.1 by reinstalling 2.4.1 on my Production server(after testing on staging/dev) using rvm.

```<code> ===========CHECK RVM  --
 rvm info
 ============ check ruby version
 ruby -v
 ruby 2.4.1p111 (2017-03-22 revision 58053) [x86_64-linux]
 ========== if ruby is installed, reinstall with Jemalloc and compile
 =============REINSTALL RUBY WITH JAMALLOC
 rvm reinstall 2.4.1 -C --with-jemalloc --disable-binary
 ============VERIFY JMALLOC IN THE BELOW LIST of ruby compiling list
 ruby -r rbconfig -e "puts RbConfig::CONFIG['LIBS']"
 -lpthread -ljemalloc -lgmp -ldl -lcrypt -lm
</code>```

The Results of jmalloc being injected in ruby were just outstanding even after testing with 2000 random requests, my overall App memory was only 364MB and remained the same throughout by testing with below mentioned testing gems.

```<code>gem "memory_profiler"
gem "derailed_benchmarks"
</code>```

hope it helps

Body:
Maybe I can answer this question as I have encountered this problem a while ago and have also resolved it after some R&D.My ROR application is Live and have more than 8000+ images and CPU Intensive as there is lot more happening in my server as every request uses LAT/LNG to serve a geo-calculated response.I was facing this low memory issue similarly like yours when i started and reindexed my data on elasticsearch.

My Learnings-

ElasticSearch is a monster that will eat up your ram.

No Matter how optimized your keywords are OR the data is, that you are pushing to the elasticSearch to get indexed, you must keep a default buffer of backup memory.

What I did...that resolved my issue...

Add a Swap space which acts like a backup memory in case your RAM is eaten up.

I also upgraded to 8GB HD to be on safer side.

Now since i have followed the above mentioned steps, i am not facing any low memory error despite the size of my  indexex data becoming huge every month.Furthermore I am still good to go error free and memory related issues while indexing this huge data.

One more thing, which I recently did to improve memory consumption of my Rails app is injecting jmalloc inside my ruby 2.4.1.You can read more here but in simple words, It helps improve memory consumption of ruby apps.A copied explanation of Jmalloc would be like -

Ruby traditionally uses the C language function malloc to dynamically allocate, release, and re-allocate memory when storing objects. Jemalloc is a malloc(3) implementation developed by Jason Evans (hence the “je” initials at the start of malloc), which appears to be more effective at allocating memory compared to other allocators due to its focus on fragmentation avoidance and scalable concurrency support.

Below are my steps that I took to add Jmalloc into my existing Ruby 2.4.1 by reinstalling 2.4.1 on my Production server(after testing on staging/dev) using rvm.

 ===========CHECK RVM  --
 rvm info
 ============ check ruby version
 ruby -v
 ruby 2.4.1p111 (2017-03-22 revision 58053) [x86_64-linux]
 ========== if ruby is installed, reinstall with Jemalloc and compile
 =============REINSTALL RUBY WITH JAMALLOC
 rvm reinstall 2.4.1 -C --with-jemalloc --disable-binary
 ============VERIFY JMALLOC IN THE BELOW LIST of ruby compiling list
 ruby -r rbconfig -e "puts RbConfig::CONFIG['LIBS']"
 -lpthread -ljemalloc -lgmp -ldl -lcrypt -lm

The Results of jmalloc being injected in ruby were just outstanding even after testing with 2000 random requests, my overall App memory was only 364MB and remained the same throughout by testing with below mentioned testing gems.

gem "memory_profiler"
gem "derailed_benchmarks"

hope it helps


问:
Understanding how the yield impacts the return value in a JS generator
Let's say I have some function as follows:

function *hello(x) { // define generator
  while (x < 7) {
 console.log(`before: ${x}`)
    x += yield x + 1; // generator object will have value x + 1, then next step of generator has value x + x and not x + x + 1
 console.log(`after: ${x}`)
  }
  return x;
}
var world = hello(3);
console.log( world.next(2) );
console.log( world.next(2) );
console.log( world.next(2) );
console.log( world.next(2) );

// before: 3
// {value: 4, done: false}
// after: 5
// before: 5
// {value: 6, done: false}
// after: 7
// {value: 7, done: true}
// {value: undefined, done: true}```
</div>
</div>
</p>

<p>I can see that the line with the <code>yield</code> returns a generator object with a value of <code>x + 1</code>, but the actual value of <code>x</code> is only increased by <code>x</code>, not <code>x+1</code>, as can be seen by the values in the <code>before</code> and <code>after</code> console logs. Why is it that the value of <code>x</code>, which comes to the right hand side of the <code>yield</code> is added to the current value of <code>x</code>, but the <code>+ 1</code> is not? I know that the value of <code>x</code> is what is being added, because if I change the value passed to the generator object in the <code>next</code> function, the before and after values reflect how much <code>x</code> was incremented by.</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>function *hello(x) { // define generator
  while (x < 7) {
 console.log(`before: ${x}`)
    x += yield x + 1; // generator object will have value x + 1, then next step of generator has value x + x and not x + x + 1
 console.log(`after: ${x}`)
  }
  return x;
}
var world = hello(3);
console.log( world.next(1) );
console.log( world.next(1) );
console.log( world.next(1) );
console.log( world.next(1) );

// before: 3
// {value: 4, done: false}
// after: 4
// before: 4
// {value: 5, done: false}
// after: 5
// before: 5
// {value: 6, done: false}
// after: 6
// before: 6
// {value: 7, done: false}
// after: 7
// {value: 7, done: true}
// {value: undefined, done: true}</code>```

答:
The value of the expression:

```<code>x += yield x + 1;
</code>```

is not x + 1. The value x + 1 is what is yielded to the caller. The value of yield in the generator is whatever was passed in. In this case, it's always 1 because that's what is being passed to it with:

```<code>world.next(1)
</code>```

A generator stops as soon as it hits the yield so in this case

```<code>x += yield x + 1;
</code>```

You can think of it as working like:

```<code>yield x + 1; // pass this value to the called

[Pause]

[Next call from  world.next(1)]

x = 1 // value passed in from caller
</code>```

Body:
Let's say I have some function as follows:

function *hello(x) { // define generator
  while (x < 7) {
 console.log(`before: ${x}`)
    x += yield x + 1; // generator object will have value x + 1, then next step of generator has value x + x and not x + x + 1
 console.log(`after: ${x}`)
  }
  return x;
}
var world = hello(3);
console.log( world.next(2) );
console.log( world.next(2) );
console.log( world.next(2) );
console.log( world.next(2) );

// before: 3
// {value: 4, done: false}
// after: 5
// before: 5
// {value: 6, done: false}
// after: 7
// {value: 7, done: true}
// {value: undefined, done: true}

I can see that the line with the yield returns a generator object with a value of x + 1, but the actual value of x is only increased by x, not x+1, as can be seen by the values in the before and after console logs. Why is it that the value of x, which comes to the right hand side of the yield is added to the current value of x, but the + 1 is not? I know that the value of x is what is being added, because if I change the value passed to the generator object in the next function, the before and after values reflect how much x was incremented by.

function *hello(x) { // define generator
  while (x < 7) {
 console.log(`before: ${x}`)
    x += yield x + 1; // generator object will have value x + 1, then next step of generator has value x + x and not x + x + 1
 console.log(`after: ${x}`)
  }
  return x;
}
var world = hello(3);
console.log( world.next(1) );
console.log( world.next(1) );
console.log( world.next(1) );
console.log( world.next(1) );

// before: 3
// {value: 4, done: false}
// after: 4
// before: 4
// {value: 5, done: false}
// after: 5
// before: 5
// {value: 6, done: false}
// after: 6
// before: 6
// {value: 7, done: false}
// after: 7
// {value: 7, done: true}
// {value: undefined, done: true}

Body:
The value of the expression:

x += yield x + 1;

is not x + 1. The value x + 1 is what is yielded to the caller. The value of yield in the generator is whatever was passed in. In this case, it's always 1 because that's what is being passed to it with:

world.next(1)

A generator stops as soon as it hits the yield so in this case

x += yield x + 1;

You can think of it as working like:

yield x + 1; // pass this value to the called

[Pause]

[Next call from  world.next(1)]

x = 1 // value passed in from caller


问:
weird Ajax ComboBox drop down list
I've got combobox inside some panel :

```<code><ajaxToolkit:ComboBox
    ID="YearList"
    runat="server"
    OnInit="YearList_Init1"
    EnableTheming="false"
    Width="45px"
    ViewStateMode="Disabled" />
</code>```

and it was OK before I updated project to .NET 4 , after updating project (And AJAX) to .net4 it's looking like really strange ... I can't explain it proper , I will show :

how can I fix it ? :) Full CSS / ASPX page here -> https://github.com/nCdy/Issues/tree/master/Ajax%20ComboBox (string # 287)

答: I had a similar issue and could resolve mine by removing the extender that I had added to the Panel containing the combobox. I had used a DropShadowExtender for the Panel, removing it caused the combobox to be displayed perfectly. Perhaps you can try that as well.</p>

ContentLicense: CC BY-SA 2.5

Title: weird Ajax ComboBox drop down list

Body:
I've got combobox inside some panel :

<ajaxToolkit:ComboBox
    ID="YearList"
    runat="server"
    OnInit="YearList_Init1"
    EnableTheming="false"
    Width="45px"
    ViewStateMode="Disabled" />

and it was OK before I updated project to .NET 4 , after updating project (And AJAX) to .net4 it's looking like really strange ... I can't explain it proper , I will show :

how can I fix it ? :) Full CSS / ASPX page here -> https://github.com/nCdy/Issues/tree/master/Ajax%20ComboBox (string # 287)


问:
Ionic 3 build --prod causes white screen on iOS only
Hi i'm trying to compile my Ionic 3 app to iOS and it does not seams to be working.
The compilation works fine, however, when i'm trying to test the app using an iOS emulator, I got a white screen.

There is no error in the console, nor in the XCode error log.

I know the code is Ok since it's working perfeclty on android and browser.

I have tried to remove and reinstall the iOS platform, to remove and reisntall the node_module folder with no success.

My guess is, that the code isn't even loaded since when i'm trying to inspect the emulator using Safari Developer tool, the title of the page is index.html rather than the title i've set on the login page.

Here are the relevents files :

My config.xml

```<code><?xml version='1.0' encoding='utf-8'?>
<widget id="com.mycompany.myAwesomeApp" version="3.0.2" xmlns="http://www.w3.org/ns/widgets" xmlns:cdv="http://cordova.apache.org/ns/1.0">
<name>my awesome app</name>
<description>My awesome app description</description>
<author email="support@myCompany.com" href="https://myCompany.com">My company dev team</author>
<content src="index.html" />
<allow-intent href="http://*/*" />
<allow-intent href="https://*/*" />
<allow-intent href="tel:*" />
<allow-intent href="sms:*" />
<allow-intent href="mailto:*" />
<allow-intent href="geo:*" />
<preference name="ScrollEnabled" value="false" />
<preference name="android-minSdkVersion" value="19" />
<preference name="BackupWebStorage" value="none" />
<preference name="SplashMaintainAspectRatio" value="true" />
<preference name="FadeSplashScreenDuration" value="300" />
<preference name="SplashShowOnlyFirstTime" value="false" />
<preference name="SplashScreen" value="screen" />
<preference name="SplashScreenDelay" value="3000" />
<preference name="loadUrlTimeoutValue" value="60000" />
<preference name="CordovaWebViewEngine" value="CDVWKWebViewEngine" />
<platform name="android">
    <!-- irrelevent android icons -->
</platform>
<platform name="ios">
    <allow-intent href="itms:*" />
    <allow-intent href="itms-apps:*" />
   <!-- irrelevent icon files -- >
</platform>
<allow-navigation href="http://*/*" />
<allow-navigation href="https://*/*" />
<plugin name="phonegap-plugin-push" spec="~2.2.2" />
<plugin name="cordova-plugin-console" spec="^1.1.0" />
<plugin name="cordova-plugin-device" spec="^1.1.7" />
<plugin name="cordova-plugin-splashscreen" spec="^4.1.0" />
<plugin name="cordova-plugin-statusbar" spec="^2.4.1" />
<plugin name="cordova-plugin-camera" spec="^4.0.2" />
<plugin name="cordova-plugin-geolocation" spec="^4.0.1" />
<plugin name="cordova-plugin-inappbrowser" spec="^2.0.2" />
<plugin name="ionic-plugin-keyboard" spec="^2.2.1" />
<plugin name="cordova-plugin-x-socialsharing" spec="^5.3.2" />
<plugin name="cordova-plugin-headercolor" spec="^1.0.0" />
<plugin name="cordova-plugin-network-information" spec="^2.0.1" />
<plugin name="cordova-plugin-file" spec="^6.0.1" />
<plugin name="cordova-plugin-advanced-http" spec="2.0.4" />
<plugin name="cordova-plugin-ionic-webview" spec="^4.0.1">
    <variable name="ANDROID_SUPPORT_ANNOTATIONS_VERSION" value="27.+" />
</plugin>
<plugin name="cordova-plugin-whitelist" spec="^1.3.3" />
<engine name="android" spec="7.1.4" />
<engine name="browser" spec="5.0.1" />
<engine name="ios" spec="4.5.5" />
</code>```

Ionic Info :

```<code>Ionic:

    ionic (Ionic CLI)  : 4.12.0 (/Users/nic/.nvm/versions/node/v10.15.3/lib/node_modules/ionic)
    Ionic Framework    : ionic-angular 3.9.0
    @ionic/app-scripts : 3.1.4

Cordova:

    cordova (Cordova CLI) : 9.0.0 (cordova-lib@9.0.1)
    Cordova Platforms     : android 7.1.4, ios 4.5.5
    Cordova Plugins       : cordova-plugin-ionic-webview 1.2.1, (and 16 other plugins)

System:

     NodeJS : v10.15.3 (/Users/nic/.nvm/versions/node/v10.15.3/bin/node)
     npm    : 6.4.1
     OS     : macOS High Sierra
     Xcode  : Xcode 10.0 Build version 10A255
</code>```

答: I ended up finding my problem. I was loading code in the constructor rather than in an ionViewDidLoad function. I have no idea why this works on Android, but not on iOS.</p>

Body:
Hi i'm trying to compile my Ionic 3 app to iOS and it does not seams to be working.
The compilation works fine, however, when i'm trying to test the app using an iOS emulator, I got a white screen.

There is no error in the console, nor in the XCode error log.

I know the code is Ok since it's working perfeclty on android and browser.

I have tried to remove and reinstall the iOS platform, to remove and reisntall the node_module folder with no success.

My guess is, that the code isn't even loaded since when i'm trying to inspect the emulator using Safari Developer tool, the title of the page is index.html rather than the title i've set on the login page.

Here are the relevents files :

My config.xml

<?xml version='1.0' encoding='utf-8'?>
<widget id="com.mycompany.myAwesomeApp" version="3.0.2" xmlns="http://www.w3.org/ns/widgets" xmlns:cdv="http://cordova.apache.org/ns/1.0">
<name>my awesome app</name>
<description>My awesome app description</description>
<author email="support@myCompany.com" href="https://myCompany.com">My company dev team</author>
<content src="index.html" />
<allow-intent href="http://*/*" />
<allow-intent href="https://*/*" />
<allow-intent href="tel:*" />
<allow-intent href="sms:*" />
<allow-intent href="mailto:*" />
<allow-intent href="geo:*" />
<preference name="ScrollEnabled" value="false" />
<preference name="android-minSdkVersion" value="19" />
<preference name="BackupWebStorage" value="none" />
<preference name="SplashMaintainAspectRatio" value="true" />
<preference name="FadeSplashScreenDuration" value="300" />
<preference name="SplashShowOnlyFirstTime" value="false" />
<preference name="SplashScreen" value="screen" />
<preference name="SplashScreenDelay" value="3000" />
<preference name="loadUrlTimeoutValue" value="60000" />
<preference name="CordovaWebViewEngine" value="CDVWKWebViewEngine" />
<platform name="android">

</platform>
<platform name="ios">
    <allow-intent href="itms:*" />
    <allow-intent href="itms-apps:*" />


问:
Docker container has different behaviour on server than local machine - uwsgi and nginx
My docker container seems to deploy correctly when running it from my MacOS machine, but fails to import the app module when running from my remote Ubuntu 18.04 server. It is a flask app that uses uwsgi and nginx as a web server. Exact error is

ImportError: No module named 'app'

I have tried different configurations of the various files below, without any success.

Dockerfile:

```<code>FROM python:3.5

RUN apt-get update
RUN apt-get install -y --no-install-recommends \
        libatlas-base-dev gfortran nginx supervisor

RUN pip3 install uwsgi

COPY requirements.txt /project/requirements.txt

RUN pip3 install -r /project/requirements.txt

RUN useradd --no-create-home nginx

RUN rm /etc/nginx/sites-enabled/default
RUN rm -r /root/.cache

COPY nginx.conf /etc/nginx/
COPY flask-site-nginx.conf /etc/nginx/conf.d/
COPY uwsgi.ini /etc/uwsgi/
COPY supervisord.conf /etc/

COPY /app /project

WORKDIR /project

CMD ["/usr/bin/supervisord"]
</code>```

Supervisord:

```<code>[supervisord]
nodaemon=true

[program:uwsgi]
command=/usr/local/bin/uwsgi --ini /etc/uwsgi/uwsgi.ini --die-on-term
stdout_logfile=/dev/stdout
stdout_logfile_maxbytes=0
stderr_logfile=/dev/stderr
stderr_logfile_maxbytes=0

[program:nginx]
command=/usr/sbin/nginx
stdout_logfile=/dev/stdout
stdout_logfile_maxbytes=0
stderr_logfile=/dev/stderr
stderr_logfile_maxbytes=0
</code>```

uwsgi:

```<code>[uwsgi]
module = app.wsgi
callable = app

uid = nginx
gid = nginx

socket = /tmp/uwsgi.sock
chown-socket = nginx:nginx
chmod-socket = 664

cheaper = 1
processes = %(%k + 1)
</code>```

Really appreciate any input or advice - thanks in advance!

答:
Possible explanation:

On OS X, the default is a case-insensitive file system.

On Ubuntu, you almost certainly have a case-sensitive file system.

Do you use a file called Supervisord which is the same as supervisord on a case-insensitive file system but not on a case-sensitive one?

Body:
My docker container seems to deploy correctly when running it from my MacOS machine, but fails to import the app module when running from my remote Ubuntu 18.04 server. It is a flask app that uses uwsgi and nginx as a web server. Exact error is

ImportError: No module named 'app'

I have tried different configurations of the various files below, without any success.

Dockerfile:

FROM python:3.5

RUN apt-get update
RUN apt-get install -y --no-install-recommends \
        libatlas-base-dev gfortran nginx supervisor

RUN pip3 install uwsgi

COPY requirements.txt /project/requirements.txt

RUN pip3 install -r /project/requirements.txt

RUN useradd --no-create-home nginx

RUN rm /etc/nginx/sites-enabled/default
RUN rm -r /root/.cache

COPY nginx.conf /etc/nginx/
COPY flask-site-nginx.conf /etc/nginx/conf.d/
COPY uwsgi.ini /etc/uwsgi/
COPY supervisord.conf /etc/

COPY /app /project

WORKDIR /project

CMD ["/usr/bin/supervisord"]

Supervisord:

[supervisord]
nodaemon=true

[program:uwsgi]
command=/usr/local/bin/uwsgi --ini /etc/uwsgi/uwsgi.ini --die-on-term
stdout_logfile=/dev/stdout
stdout_logfile_maxbytes=0
stderr_logfile=/dev/stderr
stderr_logfile_maxbytes=0

[program:nginx]
command=/usr/sbin/nginx
stdout_logfile=/dev/stdout
stdout_logfile_maxbytes=0
stderr_logfile=/dev/stderr
stderr_logfile_maxbytes=0

uwsgi:

[uwsgi]
module = app.wsgi
callable = app

uid = nginx
gid = nginx

socket = /tmp/uwsgi.sock
chown-socket = nginx:nginx
chmod-socket = 664

cheaper = 1
processes = %(%k + 1)

Really appreciate any input or advice - thanks in advance!


问:
OpenCV - Array of Images, or Buffer of Mat
How, can I have a buffer or array of images "Mat" with OpenCV?

I mean: having a set of images, want to pick up and put in an array like

How can I do this? It's like C++ normal array style?

```<code> Mat images[2];

    images[0] = imread(...);
    images[1] = imread(..);
</code>```

Thanks in advance.

答:
I had to implement something similar and I didn't need to view the images all I wanted was to extract some data from them but I'm going to add the imread anyway. Here is the code:

```<code>Mat mat[10];enter code here
char c[n]; //n is the size of chars in the directory of images

for(int i=1;i<=10;i++)
{
 sprintf(c,"/directory to images/%d.jpg",i);
 mat[i] = imread(c);
 imshow("mat",mat[i]);
 waitKey(0);
}
</code>```

this is going to display the first image in the array and you will have to press any key to go to the next one. Hope this helps

Body:
How, can I have a buffer or array of images "Mat" with OpenCV?

I mean: having a set of images, want to pick up and put in an array like

How can I do this? It's like C++ normal array style?

 Mat images[2];

    images[0] = imread(...);
    images[1] = imread(..);

Thanks in advance.

Body:
I had to implement something similar and I didn't need to view the images all I wanted was to extract some data from them but I'm going to add the imread anyway. Here is the code:

Mat mat[10];enter code here
char c[n]; //n is the size of chars in the directory of images

for(int i=1;i<=10;i++)
{
 sprintf(c,"/directory to images/%d.jpg",i);
 mat[i] = imread(c);
 imshow("mat",mat[i]);
 waitKey(0);
}

this is going to display the first image in the array and you will have to press any key to go to the next one. Hope this helps


问:
Problem deploying only Apollo Server to heroku
I am deploying an Apollo Server for my database to heroku and it is giving an application error. It is not simply show that there is a problem with the get route, it says that the application has an error and the error logs say that the app is crashing. It runs fine locally.

I have set up the procfile with: web: node app.js .
I have tried it with the procfile removed.
I have set playground and introspection to true. I saw that that could be the problem but it did not seem to help.
The port is set to process.env.PORT || 8080 .

Here is the minimal code:

```<code>const { ApolloServer } = require('apollo-server-express');
const express = require('express');
const db = require('./models');
const typeDefs = require('./data/schema');
const resolvers = require('./data/resolvers');

const app = express();

const server = new ApolloServer({
  typeDefs,
  resolvers,
  context: { db },
  introspection: true,
  playground: true,
});

server.applyMiddleware({ app });

const PORT = process.env.PORT || 8080;

app.get('/', (req, res) => {
  res.send('hello');
});

app.listen(PORT, () => {
  console.log(`Server is ready at ${PORT}`);
});
</code>```

I am also using some other functions (trying to set up a cron process), but those are commented out.

I would expect to get the / get route to at least say hello, or for the /graphql route to display playground. I am getting neither of those options.

答:
It turns out that I needed to add the following to package.json:

```<code>    "scripts": {
        "start": "app.js",
        ...
    }
</code>```

And I needed to install packages listed in the heroku logs --tail, but I have had those errors before. Writing the script start key into the package.json file is for when you are deploying your server independently of your react (or client) side.

Body:
I am deploying an Apollo Server for my database to heroku and it is giving an application error. It is not simply show that there is a problem with the get route, it says that the application has an error and the error logs say that the app is crashing. It runs fine locally.

I have set up the procfile with: web: node app.js .
I have tried it with the procfile removed.
I have set playground and introspection to true. I saw that that could be the problem but it did not seem to help.
The port is set to process.env.PORT || 8080 .

Here is the minimal code:

const { ApolloServer } = require('apollo-server-express');
const express = require('express');
const db = require('./models');
const typeDefs = require('./data/schema');
const resolvers = require('./data/resolvers');

const app = express();

const server = new ApolloServer({
  typeDefs,
  resolvers,
  context: { db },
  introspection: true,
  playground: true,
});

server.applyMiddleware({ app });

const PORT = process.env.PORT || 8080;

app.get('/', (req, res) => {
  res.send('hello');
});

app.listen(PORT, () => {
  console.log(`Server is ready at ${PORT}`);
});

I am also using some other functions (trying to set up a cron process), but those are commented out.

I would expect to get the / get route to at least say hello, or for the /graphql route to display playground. I am getting neither of those options.

Body:
It turns out that I needed to add the following to package.json:

    "scripts": {
        "start": "app.js",
        ...
    }

And I needed to install packages listed in the heroku logs --tail, but I have had those errors before. Writing the script start key into the package.json file is for when you are deploying your server independently of your react (or client) side.