问:
My page is scrolling to right. Why is it happening?
I'm building a web page and working in the layout for small screens (max-width: 600px). When the screen gets narrow, the page gets a bit of horizontal scroll, as you can see in the code snippet, but it is unexpected for me. I am not finding anything wider than the viewport's width in my code. Why is there that scroll?

/* CSS from index_default.css */

@charset "UTF-8";
@import url('https://fonts.googleapis.com/css?family=Doppio+One|Open+Sans&display=swap');
html, body, *, *::before, *::after {
    margin: 0;
    padding: 0;
    box-sizing: border-box;
}
body{
    font-family: 'Open Sans', sans-serif;
}
h2, h3{
    margin-top: 10px;
    margin-bottom: 10px;
}
a{
    text-decoration: none;
    transition: 0.2s linear;
}
header{
    background-color: rgb(93, 158, 76);
    display: flex;
    align-items: center;
    padding-top: 10px;
    padding-bottom: 10px;
}
header h1{
    font-family: 'Doppio One', cursive;
    color: rgb(214, 245, 210);
}
nav a{
    color: rgb(230, 245, 229);
}
#menu{
    width: 30px;
}
#firstsection div a{
    font-weight: bold;
    border: 2px solid rgb(47, 119, 27);
    padding: 13px 30px;
    font-size: 16.5px;
    color: rgb(47, 119, 27);
}
#firstsection div a:hover{
    color: rgb(133, 163, 131);
    border: 2px solid rgb(133, 163, 131);
}
#lastsection img{
    display: block;
    margin-right: auto;
    margin-left: auto;
}
#lastsection div a:visited{
    color: blue;
}
footer{
    background-color: rgb(93, 158, 76);
    display: flex;
    justify-content: center;
    align-items: center;
    padding: 1rem;
    color: rgb(214, 245, 210);
}

/* CSS from index_small.css */

@charset "UTF-8";
body{
    width: 100vw;
    text-align: center;
}
header{
    padding-right: 10px;
    padding-left: 10px;
}
header img:first-of-type{
    width: 40px;
    margin-right: 5px;
}
header ul{
    display: none;
}
#menu{
    margin-left: 15vh;
}
#firstsection{
    background-color: rgb(220, 255, 211);
    height: 40vh;
    padding: 10% 20px 0;
    margin-bottom: 8%;
}
#firstsection div{
    margin-bottom: 30px;
}
#firstsection a{
    position: relative;
    top: 35px;
}
#middlesection{
    margin: 0 5vw;
}
#textboxes div{
    margin-bottom: 8%;
}
#lastsection img{
    width: 90%;
    margin-top: 8vh;
}
#lastsection div{
    position: relative;
    bottom: 18.5vh;
}
#lastsection div h2{
    font-size: 1.2rem;
}
footer img{
    width: 40px;
    margin-right: 8px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html lang="pt-BR">
    <head>
        <title>Finances | Manage your money easily</title>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <meta name="description" content="Control you spending and manage your money easily. Your finances by the short hairs.">
        <meta name="author" content="Bruno M. B. Sdoukos">
        <meta name="keywords" content="finances, managing money, spending control">
        <link rel="stylesheet" type="text/css" href="index_default.css">
        <link rel="stylesheet" type="text/css" media="screen and (max-width: 600px)" href="index_small.css">
        <link rel="stylesheet" type="text/css" media="screen and (min-width: 1500px)" href="index_large.css">
    </head>
    <body>
        <header>
            <img src="Images/icons8-fund-accounting-80.png">
            <h1>Finances</h1>
            <nav>
                <ul>
                    <li>Home</li>
                    <li>About</li>
                    <li>Contact us</li>
                    <li>Register</li>
                    <li>Login</li>
                </ul>
                <img src="Images/icons8-menu-50.png" id="menu">
            </nav>
        </header>
        <main>
            <section id="firstsection">
                <div>
                    <h1>Manage your money easily, anywhere, anytime.</h1>
                    Get started
                </div>
            </section>
            <section id="middlesection">
                <div id="textboxes">
                    <div>
                        <img src="Images/icons8-increase-64.png">
                        <h3>Concrete data</h3>
                        <p>Simple but concrete data that are the answer to all the quesions about your current money, spending and.</p>
                    </div>
                    <div>
                        <img src="Images/icons8-navigation-toolbar-left-filled-50 (1).png">
                        <h3>Easy interface</h3>
                        <p>An interface easy to use, made to you who want to manage your money faster and with no problems.</p>
                    </div>
                    <div>
                        <img src="Images/icons8-natural-user-interface-2-filled-50.png">
                        <h3>Fast access</h3>
                        <p>No complications that make you lose time. Just some clicks and done, you are in Finances, with all you need.</p>
                    </div>
                </div>
            </section>
            <section id="lastsection">
                <img src="Images/board-1362851_1280.png">
                <div>
                    <h2>Register now and enjoy<br>the best of Finances.</h2>
                    Create an account
                </div>
            </section>
        </main>
        <footer>
            <img src="Images/icons8-fund-accounting-80.png">
            <div>
                <p>A work of Bruno Sdoukos.</p>
            </div>
        </footer>
    </body>
</html></code>```

答:
Change to css file

body{
    width: 100vw;
    text-align: center;
}
```

<p>to</p>

<pre class="lang-css prettyprint-override"><code>body{
    width: 100%;
    text-align: center;
}
</code>```

Body:
I'm building a web page and working in the layout for small screens (max-width: 600px). When the screen gets narrow, the page gets a bit of horizontal scroll, as you can see in the code snippet, but it is unexpected for me. I am not finding anything wider than the viewport's width in my code. Why is there that scroll?

/* CSS from index_default.css */

@charset "UTF-8";
@import url('https://fonts.googleapis.com/css?family=Doppio+One|Open+Sans&display=swap');
html, body, *, *::before, *::after {
    margin: 0;
    padding: 0;
    box-sizing: border-box;
}
body{
    font-family: 'Open Sans', sans-serif;
}
h2, h3{
    margin-top: 10px;
    margin-bottom: 10px;
}
a{
    text-decoration: none;
    transition: 0.2s linear;
}
header{
    background-color: rgb(93, 158, 76);
    display: flex;
    align-items: center;
    padding-top: 10px;
    padding-bottom: 10px;
}
header h1{
    font-family: 'Doppio One', cursive;
    color: rgb(214, 245, 210);
}
nav a{
    color: rgb(230, 245, 229);
}
#menu{
    width: 30px;
}
#firstsection div a{
    font-weight: bold;
    border: 2px solid rgb(47, 119, 27);
    padding: 13px 30px;
    font-size: 16.5px;
    color: rgb(47, 119, 27);
}
#firstsection div a:hover{
    color: rgb(133, 163, 131);
    border: 2px solid rgb(133, 163, 131);
}
#lastsection img{
    display: block;
    margin-right: auto;
    margin-left: auto;
}
#lastsection div a:visited{
    color: blue;
}
footer{
    background-color: rgb(93, 158, 76);
    display: flex;
    justify-content: center;
    align-items: center;
    padding: 1rem;
    color: rgb(214, 245, 210);
}

/* CSS from index_small.css */

@charset "UTF-8";
body{
    width: 100vw;
    text-align: center;
}
header{
    padding-right: 10px;
    padding-left: 10px;
}
header img:first-of-type{
    width: 40px;
    margin-right: 5px;
}
header ul{
    display: none;
}
#menu{
    margin-left: 15vh;
}
#firstsection{
    background-color: rgb(220, 255, 211);
    height: 40vh;
    padding: 10% 20px 0;
    margin-bottom: 8%;
}
#firstsection div{
    margin-bottom: 30px;
}
#firstsection a{
    position: relative;
    top: 35px;
}
#middlesection{
    margin: 0 5vw;
}
#textboxes div{
    margin-bottom: 8%;
}
#lastsection img{
    width: 90%;
    margin-top: 8vh;
}
#lastsection div{
    position: relative;
    bottom: 18.5vh;
}
#lastsection div h2{
    font-size: 1.2rem;
}
footer img{
    width: 40px;
    margin-right: 8px;
}

<!DOCTYPE html>

        <title>Finances | Manage your money easily</title>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <meta name="description" content="Control you spending and manage your money easily. Your finances by the short hairs.">
        <meta name="author" content="Bruno M. B. Sdoukos">
        <meta name="keywords" content="finances, managing money, spending control">
        <link rel="stylesheet" type="text/css" href="index_default.css">
        <link rel="stylesheet" type="text/css" media="screen and (max-width: 600px)" href="index_small.css">
        <link rel="stylesheet" type="text/css" media="screen and (min-width: 1500px)" href="index_large.css">

Finances

Home

About

Contact us

Register

Login

Manage your money easily, anywhere, anytime.

                    Get started

Concrete data

Simple but concrete data that are the answer to all the quesions about your current money, spending and.

Easy interface

An interface easy to use, made to you who want to manage your money faster and with no problems.

Fast access

No complications that make you lose time. Just some clicks and done, you are in Finances, with all you need.

Register now and enjoy
the best of Finances.

                    Create an account

A work of Bruno Sdoukos.

Body:
Change to css file

body{
    width: 100vw;
    text-align: center;
}

to

body{
    width: 100%;
    text-align: center;
}


来源: stackexchange

问:
Does Unity support PHP Sessions?
Does anyone know if Unity supports PHP sessions?

For example, let's say that a user signs into their account in Unity and submits the login information through WWW stream. Once logged in, I assign a session variable in my php script: $_SESSION['name]=name.

My question is, when the user comes to submit another request through Unity will the client still be able to access the session variable?

答:
Session data are data from a database connected to an id, which is used in the communication between client and server. Usually a cookie.

I can't say for certain, but I very much believe that the WWW class will ignore/forget cookies.

Unity sends a request (with only the data you define) to PHP

PHP sets a cookie corresponding to that session & responds to the request

Unity gets the response with headers (and cookies in the headers)

Repeat

PLEASE NOTE: I have not tested this, it is theoretical, but educated, guesses.

Suggested solution

You can set headers in your request that you build in Unity. If you save the headers from the response and add those to the request each time, you should be able to emulate the behaviour you're seeking. So basically:

Unity sends a request (with headers = previousResponseHeaders) to PHP

PHP reads the headers and connect your cookie to previous session & responds to the request

Unity gets the response with headers (and cookies in the headers)

Repeat

You set headers by doing something like this:

```<code>var headers = new Dictionary<string,string>();
headers.Add("Cookie", "key=value; semicolon=separated");
WWW www = new WWW("https://example.com", null, headers);
</code>```

ContentLicense: CC BY-SA 4.0

Title: Does Unity support PHP Sessions?

Body:
Session data are data from a database connected to an id, which is used in the communication between client and server. Usually a cookie.

I can't say for certain, but I very much believe that the WWW class will ignore/forget cookies.

Unity sends a request (with only the data you define) to PHP

PHP sets a cookie corresponding to that session & responds to the request

Unity gets the response with headers (and cookies in the headers)

Repeat

PLEASE NOTE: I have not tested this, it is theoretical, but educated, guesses.

Suggested solution

You can set headers in your request that you build in Unity. If you save the headers from the response and add those to the request each time, you should be able to emulate the behaviour you're seeking. So basically:

Unity sends a request (with headers = previousResponseHeaders) to PHP

PHP reads the headers and connect your cookie to previous session & responds to the request

Unity gets the response with headers (and cookies in the headers)

Repeat

You set headers by doing something like this:

var headers = new Dictionary<string,string>();
headers.Add("Cookie", "key=value; semicolon=separated");
WWW www = new WWW("https://example.com", null, headers);


问:
How do I implement a masked softmax cross-entropy loss function in Keras?
I'm trying to implement a softmax cross-entropy loss in Keras. The loss should only consider samples with labels 1 or 0 and ignore samples with labels -1 (i.e. missing labels). I found a binary_crossentropy function that does that but I couldn't implement a softmax version for it.

Here's the binary_crossentropy:

```<code>def binary_crossentropy(y_true, y_pred):
    return K.mean(K.binary_crossentropy(tf.multiply(y_pred, tf.cast(tf.not_equal(y_true, -1), tf.float32)),
                                    tf.multiply(y_true, tf.cast(tf.not_equal(y_true, -1), tf.float32))), axis=-1)
</code>```

I tried to change the K.binary_crossentropy() function with K.categorical_crossentropy, but this only gives me "nan" when the loss is calculated.

How can I implement this on Keras (Tensorflow backend)?

Edit

In this answer, the author suggested to use sparse_crossentropy, but I ran into an error while compiling the model:

Use sparse_categorical_crossentropy and boolean_mask

```<code>def sparse_crossentropy_masked(y_true, y_pred):
    y_true_masked = tf.boolean_mask(y_true, tf.not_equal(y_true, -1))
    y_pred_masked = tf.boolean_mask(y_pred, tf.not_equal(y_true, -1))
    return K.mean(K.sparse_categorical_crossentropy(y_true_masked, y_pred_masked))
</code>```

Testcase

```<code>y_true = tf.constant(np.array([0.,1.,2., -1]))
y_pred = tf.constant(np.array([[1.,0.,0.], [0.,1.,0.], [0.,0.,1.], [0.,0.,1.]]))
loss_op = sparse_crossentropy_masked(y, y_hat)

y_true_1 = tf.constant(np.array([0.,1.,2.]))
y_pred_1 = tf.constant(np.array([[1.,0.,0.], [0.,1.,0.], [0.,0.,1.]]))
loss_1_op = sparse_crossentropy_masked(y_true_1, y_pred_1)

with tf.Session() as sess:
    loss, loss_1 = sess.run([loss_op, loss_1_op])
    assert loss == loss_1

model.compile(loss=sparse_crossentropy_masked)
### TypeError: int returned non-int (type NoneType
</code>```

答:
Use sparse_categorical_crossentropy and boolean_mask

```<code>def sparse_crossentropy_masked(y_true, y_pred):
    y_true_masked = tf.boolean_mask(y_true, tf.not_equal(y_true, -1))
    y_pred_masked = tf.boolean_mask(y_pred, tf.not_equal(y_true, -1))
    return K.mean(K.sparse_categorical_crossentropy(y_true_masked, y_pred_masked))
</code>```

Testcase

```<code>y_true = tf.constant(np.array([0.,1.,2., -1]))
y_pred = tf.constant(np.array([[1.,0.,0.], [0.,1.,0.], [0.,0.,1.], [0.,0.,1.]]))
loss_op = sparse_crossentropy_masked(y, y_hat)

y_true_1 = tf.constant(np.array([0.,1.,2.]))
y_pred_1 = tf.constant(np.array([[1.,0.,0.], [0.,1.,0.], [0.,0.,1.]]))
loss_1_op = sparse_crossentropy_masked(y_true_1, y_pred_1)

with tf.Session() as sess:
    loss, loss_1 = sess.run([loss_op, loss_1_op])
    assert loss == loss_1
</code>```

Update

sparse_categorical_crossentropy seems to have a bug, see a similar issue here. So we are left with using categorical_crossentropy instead, but now the ground truth should be converted into one-hot-encoding. We will represent the labels to be not considered using -1 (print the y in below code if you are confused)

Working example:

```<code>def categorical_crossentropy_masked(y_true, y_pred):
    y_true_masked = tf.boolean_mask(y_true, tf.reduce_any(tf.not_equal(y_true, -1), 1))
    y_pred_masked = tf.boolean_mask(y_pred, tf.reduce_any(tf.not_equal(y_true, -1), 1))
    return K.mean(K.categorical_crossentropy(y_true_masked, y_pred_masked))

inputs = Input(shape=(3,))
outputs = Dense(32, activation='relu')(inputs)
outputs = Dense(16, activation='relu')(outputs)
outputs = Dense(3, activation='softmax')(outputs)
model = Model(inputs, outputs)
model.compile(optimizer='adam', loss=[categorical_crossentropy_masked])

x = np.random.randn(100,3)
y = np.random.randint(0,3, size=(100))

y = tf.keras.utils.to_categorical(y)
# make some targets to -1
y[np.random.randint(0,100, size=(15))] = np.ones((15,y.shape[-1]))*-1.

model.fit(x, y)
</code>```

Body:
I'm trying to implement a softmax cross-entropy loss in Keras. The loss should only consider samples with labels 1 or 0 and ignore samples with labels -1 (i.e. missing labels). I found a binary_crossentropy function that does that but I couldn't implement a softmax version for it.

Here's the binary_crossentropy:

def binary_crossentropy(y_true, y_pred):
    return K.mean(K.binary_crossentropy(tf.multiply(y_pred, tf.cast(tf.not_equal(y_true, -1), tf.float32)),
                                    tf.multiply(y_true, tf.cast(tf.not_equal(y_true, -1), tf.float32))), axis=-1)

I tried to change the K.binary_crossentropy() function with K.categorical_crossentropy, but this only gives me "nan" when the loss is calculated.

How can I implement this on Keras (Tensorflow backend)?

Edit

In this answer, the author suggested to use sparse_crossentropy, but I ran into an error while compiling the model:

Use sparse_categorical_crossentropy and boolean_mask

def sparse_crossentropy_masked(y_true, y_pred):
    y_true_masked = tf.boolean_mask(y_true, tf.not_equal(y_true, -1))
    y_pred_masked = tf.boolean_mask(y_pred, tf.not_equal(y_true, -1))
    return K.mean(K.sparse_categorical_crossentropy(y_true_masked, y_pred_masked))

Testcase

y_true = tf.constant(np.array([0.,1.,2., -1]))
y_pred = tf.constant(np.array([[1.,0.,0.], [0.,1.,0.], [0.,0.,1.], [0.,0.,1.]]))
loss_op = sparse_crossentropy_masked(y, y_hat)

y_true_1 = tf.constant(np.array([0.,1.,2.]))
y_pred_1 = tf.constant(np.array([[1.,0.,0.], [0.,1.,0.], [0.,0.,1.]]))
loss_1_op = sparse_crossentropy_masked(y_true_1, y_pred_1)

with tf.Session() as sess:
    loss, loss_1 = sess.run([loss_op, loss_1_op])
    assert loss == loss_1

model.compile(loss=sparse_crossentropy_masked)
### TypeError: int returned non-int (type NoneType

Body:
Use sparse_categorical_crossentropy and boolean_mask

def sparse_crossentropy_masked(y_true, y_pred):
    y_true_masked = tf.boolean_mask(y_true, tf.not_equal(y_true, -1))
    y_pred_masked = tf.boolean_mask(y_pred, tf.not_equal(y_true, -1))
    return K.mean(K.sparse_categorical_crossentropy(y_true_masked, y_pred_masked))

Testcase

y_true = tf.constant(np.array([0.,1.,2., -1]))
y_pred = tf.constant(np.array([[1.,0.,0.], [0.,1.,0.], [0.,0.,1.], [0.,0.,1.]]))
loss_op = sparse_crossentropy_masked(y, y_hat)

y_true_1 = tf.constant(np.array([0.,1.,2.]))
y_pred_1 = tf.constant(np.array([[1.,0.,0.], [0.,1.,0.], [0.,0.,1.]]))
loss_1_op = sparse_crossentropy_masked(y_true_1, y_pred_1)

with tf.Session() as sess:
    loss, loss_1 = sess.run([loss_op, loss_1_op])
    assert loss == loss_1

Update

sparse_categorical_crossentropy seems to have a bug, see a similar issue here. So we are left with using categorical_crossentropy instead, but now the ground truth should be converted into one-hot-encoding. We will represent the labels to be not considered using -1 (print the y in below code if you are confused)

Working example:

def categorical_crossentropy_masked(y_true, y_pred):
    y_true_masked = tf.boolean_mask(y_true, tf.reduce_any(tf.not_equal(y_true, -1), 1))
    y_pred_masked = tf.boolean_mask(y_pred, tf.reduce_any(tf.not_equal(y_true, -1), 1))
    return K.mean(K.categorical_crossentropy(y_true_masked, y_pred_masked))

inputs = Input(shape=(3,))
outputs = Dense(32, activation='relu')(inputs)
outputs = Dense(16, activation='relu')(outputs)
outputs = Dense(3, activation='softmax')(outputs)
model = Model(inputs, outputs)
model.compile(optimizer='adam', loss=[categorical_crossentropy_masked])

x = np.random.randn(100,3)
y = np.random.randint(0,3, size=(100))

y = tf.keras.utils.to_categorical(y)
# make some targets to -1
y[np.random.randint(0,100, size=(15))] = np.ones((15,y.shape[-1]))*-1.

model.fit(x, y)


问:
How to apply a method to a Pandas Dataframe
I have this dataframe

```<code>   Col1              Col2

0  A (1000 EUR)  C ( 3000 USD)

1  B (2000 CHF)  D ( 4000 GBP)
</code>```

I would like to convert it to

```<code>   Col1  Col2

0  1000  3000

1  2000  4000
</code>```

I know how to create a dataframe (with indexes) for 1 column, but not for multiple columns

This code produces this result

```<code>   Col1

0  1000

1  2000

a = z['Col1'].str.split('(').str[-1].str.split().str[0].apply(pd.to_numeric,errors='coerce')
</code>```

how can I amend the code above to also add col2 (ideally using vectorisation rather than iteration) (so ideally I wouln't want to have to enter the same code for every column)

答:
You can use the apply function to apply your operation to all elements in both rows.

```<code># creates your dataframe
df = pd.DataFrame({'Col1':['A (1000 EUR)','B (2000 CHF)'], 'Col2':['C (3000 USD)', 'D (4000 GBP)']})

# use the apply function to  apply your code to all elements of both columns
df = df.apply(lambda x: x.str.split('(').str[-1].str.split().str[0].apply(pd.to_numeric,errors='coerce'))
</code>```

Does the trick for me

Body:
I have this dataframe

   Col1              Col2

0  A (1000 EUR)  C ( 3000 USD)

1  B (2000 CHF)  D ( 4000 GBP)

I would like to convert it to

   Col1  Col2

0  1000  3000

1  2000  4000

I know how to create a dataframe (with indexes) for 1 column, but not for multiple columns

This code produces this result

   Col1

0  1000

1  2000

a = z['Col1'].str.split('(').str[-1].str.split().str[0].apply(pd.to_numeric,errors='coerce')

how can I amend the code above to also add col2 (ideally using vectorisation rather than iteration) (so ideally I wouln't want to have to enter the same code for every column)

Body:
You can use the apply function to apply your operation to all elements in both rows.

# creates your dataframe
df = pd.DataFrame({'Col1':['A (1000 EUR)','B (2000 CHF)'], 'Col2':['C (3000 USD)', 'D (4000 GBP)']})

# use the apply function to  apply your code to all elements of both columns
df = df.apply(lambda x: x.str.split('(').str[-1].str.split().str[0].apply(pd.to_numeric,errors='coerce'))

Does the trick for me


问:
Struggling with input validation/check constraint
I'm trying to create a table with an email address column and want to make sure that only addresses in the correct format (contains "@") are allowed. I know how to use the LIKE operator in queries but not how to put a value constraint on a column.

答:
This would be better to do in a programming language that supports regular expressions or already has a built in isValidEmail method.

Validating an email address using a regular expression or a simple like pattern is pretty darn hard to get right, if not nearly impossible.

You can read more about it on I Knew How To Validate An Email Address Until I Read The RFC - And to quote the part I think illustrates the problem best:

These are all valid email addresses!

Abc@def@example.com

Fred\ Bloggs@example.com

Joe.\Blow@example.com

"Abc@def"@example.com

"Fred Bloggs"@example.com

customer/department=shipping@example.com

$A12345@example.com

!def!xyz%abc@example.com

_somename@example.com

Attempting to get all the logic needed to validate such a wide range of possibilities in a T-SQL statement is like attempting to climb the Everest blind-folded with your hands tied behind your back.

You could have a simple validation that might return a lot of false-positives or false-negatives using a simple like pattern like the one suggested in How to Validate Email Address in SQL Server? by Pinal Dave: '%_@__%.__%', but that's really just a naive attempt to clog a dam with a band-aid.

Having said all that, you might be able to use a CLR Scalar-Valued Function to validate your email addresses, using code like the one from this SO post.

Personally, I have no experience with CLR functions, so it would probably be irresponsible of me to try and write you a code example (especially since I don't really have a test environment to check it before I post this answer), but I hope what I've written so far was helpful enough, and with the help of the links in this answer and some web searches you will be able to solve the problem.


问:
Using Segue, How do I control the visibility of a view in a different view controller?
I have two view controllers that are linked via segue. One view controller (ViewController2) has multiple views within it which responds to the pageIndex in the first view controller(ViewController1). So what I'm trying to achieve is that onClick if pageIndex == 0 on the ViewController1,  one of the views should become visible. I have done this multiple times with Labels and ImageViews but when it comes to making a view visible I can't seem to achieve it. So I need help to achieve it.

ViewController1:

```<code>  override func prepare(for segue: UIStoryboardSegue, sender: Any?) {

    if segueIdentifier(for: segue) == .reveal,
      let secondViewController = segue.destination as? ViewController2 {

      if pageIndex == 0 {
        //secondViewController.viewabc.isHidden = false

      }else if pageIndex == 1{
        //secondViewController.viewdef.isHidden = false

      }else{
        //secondViewController.viewghi.isHidden = false

      }

      secondViewController.transitioningDelegate = self

      }

  }

  @IBAction func handleTap() {
    performSegue(withIdentifier: .reveal, sender: self)

  }
}

extension ViewController1: SegueHandlerType {
  enum SegueIdentifier: String {
    case reveal
  }
}
</code>```

ViewController2:

```<code>  @IBOutlet weak var viewabc: UIView!
  @IBOutlet weak var viewdef: UIView!
  @IBOutlet weak var viewghi: UIView!

  override func viewDidLoad() {
    super.viewDidLoad()

      }

</code>```

In the storyboard all 3 views are set to hidden

答:
Pass the pageIndex value from ViewController1 to ViewController2.

```<code>class ViewController1: UIViewController {
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        if segueIdentifier(for: segue) == .reveal,
            let secondViewController = segue.destination as? ViewController2 {
            secondViewController.transitioningDelegate = self
            secondViewController.pageIndex = pageIndex
        }
    }
}
</code>```

And update ViewController2 views based on the pageIndex value

```<code>class ViewController2: UIViewController {
    var pageIndex: Int?
    @IBOutlet weak var viewabc: UIView!
    @IBOutlet weak var viewdef: UIView!
    @IBOutlet weak var viewghi: UIView!

    override func viewDidLoad() {
        super.viewDidLoad()
        if pageIndex == 0 {
            self.viewabc.isHidden = false
        }else if pageIndex == 1{
            self.viewdef.isHidden = false
        }else{
            self.viewghi.isHidden = false
        }
    }
}
</code>```

Body:
I have two view controllers that are linked via segue. One view controller (ViewController2) has multiple views within it which responds to the pageIndex in the first view controller(ViewController1). So what I'm trying to achieve is that onClick if pageIndex == 0 on the ViewController1,  one of the views should become visible. I have done this multiple times with Labels and ImageViews but when it comes to making a view visible I can't seem to achieve it. So I need help to achieve it.

ViewController1:

  override func prepare(for segue: UIStoryboardSegue, sender: Any?) {

    if segueIdentifier(for: segue) == .reveal,
      let secondViewController = segue.destination as? ViewController2 {

      if pageIndex == 0 {
        //secondViewController.viewabc.isHidden = false

      }else if pageIndex == 1{
        //secondViewController.viewdef.isHidden = false

      }else{
        //secondViewController.viewghi.isHidden = false

      }

      secondViewController.transitioningDelegate = self

      }

  }

  @IBAction func handleTap() {
    performSegue(withIdentifier: .reveal, sender: self)

  }
}

extension ViewController1: SegueHandlerType {
  enum SegueIdentifier: String {
    case reveal
  }
}

ViewController2:

  @IBOutlet weak var viewabc: UIView!
  @IBOutlet weak var viewdef: UIView!
  @IBOutlet weak var viewghi: UIView!

  override func viewDidLoad() {
    super.viewDidLoad()

      }

In the storyboard all 3 views are set to hidden

Body:
Pass the pageIndex value from ViewController1 to ViewController2.

class ViewController1: UIViewController {
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        if segueIdentifier(for: segue) == .reveal,
            let secondViewController = segue.destination as? ViewController2 {
            secondViewController.transitioningDelegate = self
            secondViewController.pageIndex = pageIndex
        }
    }
}

And update ViewController2 views based on the pageIndex value

class ViewController2: UIViewController {
    var pageIndex: Int?
    @IBOutlet weak var viewabc: UIView!
    @IBOutlet weak var viewdef: UIView!
    @IBOutlet weak var viewghi: UIView!

    override func viewDidLoad() {
        super.viewDidLoad()
        if pageIndex == 0 {
            self.viewabc.isHidden = false
        }else if pageIndex == 1{
            self.viewdef.isHidden = false
        }else{
            self.viewghi.isHidden = false
        }
    }
}


问:
Problem with displaying user-pictures relation in Laravel 5.8
I'm very beginner in Laravel.

I have standard login User model (generated by Laravel):

```<code>class UploadedFiles extends Model
{
    protected $quarded = [];
    protected $fillable = ['company_id', 'enable', 'photoable_type', 'photoable_id', 'path', 'ip', 'number'];
    protected $table = 'uploaded_files';

}

class User extends Authenticatable implements MustVerifyEmail
{
    use Notifiable;
    use psCMS\Presenters\UserPresenter;

    public static $roles = [];

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */

    protected $fillable = ['company_id', 'enable', 'name', 'surname', 'email', 'email_verified_at', 'password', 'counter', 'url_address',  'isCompany', 'isMailing', 'content', 'nip1', 'business1', 'phone1', 'street1', 'number1', 'postal_code1', 'city1', 'country_id1', 'provincial_id1', 'nip2', 'business2', 'phone2', 'street2', 'number2', 'postal_code2', 'city2', 'country_id2', 'provincial_id2', 'nip3', 'business3', 'phone3', 'street3', 'number3', 'postal_code3', 'city3', 'country_id3', 'provincial_id3', 'cash', 'lng', 'lat', 'enable_map', 'remember_token', 'created_at', 'updated_at', 'last_login_at', 'last_login_ip' ];

    /**
     * The attributes that should be hidden for arrays.
     *
     * @var array
     */
    protected $hidden = [
        'password', 'remember_token',
    ];

    public function roles()
    {
        return $this->belongsToMany('App\Role');
    }

    public function mainRole()
    {
        return $this->hasOne('App\Role');
    }

    public function comments()
    {
        return $this->hasMany('App\Comments');
    }

    public function images()
    {   // find(['photoable_type', '=', 'AdminImage'] ::with('director')->get();
        return $this->hasMany('App\UploadedFiles' );
    }

    public function images2()
    {   // ->where('photoable_type', 'AdminImage')
        return $this->hasManyThrough('App\UploadedFiles', 'App\User', 'photoable_id', 'id');
    }

    public function hasRole(array $roles)
    {

        foreach($roles as $role)
        {

            if(isset(self::$roles[$role]))
            {
                if(self::$roles[$role])  return true;

            }
            else
            {
                self::$roles[$role] = $this->roles()->where('name', $role)->exists();
                if(self::$roles[$role]) return true;
            }

        }
        return false;
    }

    public function loginHistory()
    {
        return $this->hasMany('App\UserLoginHistory');
    }

    public function companies()
    {
        return $this->belongsTo('App\Companies','company_id');
    }

}
</code>```

My schema:

```<code>Schema::create('users', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->bigInteger('company_id')->unsigned();
            $table->foreign('company_id')->references('id')->on('companies')->onDelete('cascade');
            $table->boolean('enable')->default(0);
            $table->string('name', 120)->nullable();
            $table->string('surname', 120)->nullable();
            $table->string('email', 120)->unique();
            $table->timestamp('email_verified_at')->nullable();
            $table->string('password');
            $table->bigInteger('counter')->default(0);
            $table->string('url_address', 160);
            $table->boolean('isCompany')->default(0);
            $table->boolean('isMailing')->default(0);
            $table->text('content')->nullable();
            $table->string('nip1', 12)->nullable();
            $table->string('business1', 120)->nullable();
            $table->string('phone1', 60)->nullable();
            $table->string('street1', 150)->nullable();
            $table->string('number1', 8)->nullable();
            $table->string('postal_code1', 12)->nullable();
            $table->string('city1', 100)->nullable();
            $table->bigInteger('country_id1')->default(0);
            $table->bigInteger('provincial_id1')->default(0);
            $table->string('nip2', 12)->nullable();
            $table->string('business2', 120)->nullable();
            $table->string('phone2', 60)->nullable();
            $table->string('street2', 150)->nullable();
            $table->string('number2', 8)->nullable();
            $table->string('postal_code2', 12)->nullable();
            $table->string('city2', 100)->nullable();
            $table->bigInteger('country_id2')->default(0);
            $table->bigInteger('provincial_id2')->default(0);
            $table->string('nip3', 12)->nullable();
            $table->string('business3', 120)->nullable();
            $table->string('phone3', 60)->nullable();
            $table->string('street3', 150)->nullable();
            $table->string('number3', 8)->nullable();
            $table->string('postal_code3', 12)->nullable();
            $table->string('city3', 100)->nullable();
            $table->bigInteger('country_id3')->default(0);
            $table->bigInteger('provincial_id3')->default(0);
            $table->decimal('cash', 9, 2)->default(0);
            $table->decimal('lng', 10, 8)->default(0);
            $table->decimal('lat', 10, 8)->default(0);
            $table->boolean('enable_map')->default(0);
            $table->rememberToken();
            $table->timestamps();
            $table->engine = "InnoDB";
        });

Schema::create('role_user', function (Blueprint $table) {
            $table->bigInteger('user_id')->unsigned();
            $table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
            $table->bigInteger('role_id')->unsigned();
            $table->foreign('role_id')->references('id')->on('roles')->onDelete('cascade');
            $table->engine = "InnoDB";
        });

Schema::create('roles', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->string('name');
            $table->engine = "InnoDB";
        });

Schema::create('uploaded_files', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->bigInteger('company_id')->unsigned();
            $table->foreign('company_id')->references('id')->on('companies')->onDelete('cascade');
            $table->boolean('enable')->default(0);
            $table->string('photoable_type', 150);
            $table->integer('photoable_id');
            $table->string('path', 255);
            $table->string('ip', 25);
            $table->bigInteger('number')->default(0);
            $table->timestamps();
            $table->engine = "InnoDB";
        });
</code>```

I have the following record in the database:
https://ibb.co/ZhHGkKX

```<code>INSERT INTO `uploaded_files` (`id`, `company_id`, `enable`, `photoable_type`, `photoable_id`, `path`, `ip`, `number`, `created_at`, `updated_at`) VALUES
(46, 1, 1, 'AdminImage', 1, 'upload/images/AdminImage/627e653871183f639c8d9460f37111b1.jpg', '172.29.0.1', 0, '2019-05-27 08:50:08', '2019-05-27 08:50:08');
COMMIT;
</code>```

In my base I have relations:
- uploaded_files.photoable_id = User.id

I need to display all images belonging to the user that have the photoable_type = AdminImage

How can I do this? Please help

答:
You have declared the correct method in your user model so try to modify it:

```<code> public function images()
{
    // App\UploadedFiles must be a model
    return $this->hasMany(App\UploadedFiles::class, 'photoable_id', 'id');
}
</code>```

Use the relationship as follows:

```<code>User::with('images')->get();
</code>```

Regards

Body:
I'm very beginner in Laravel.

I have standard login User model (generated by Laravel):

class UploadedFiles extends Model
{
    protected $quarded = [];
    protected $fillable = ['company_id', 'enable', 'photoable_type', 'photoable_id', 'path', 'ip', 'number'];
    protected $table = 'uploaded_files';

}

class User extends Authenticatable implements MustVerifyEmail
{
    use Notifiable;
    use psCMS\Presenters\UserPresenter;

    public static $roles = [];

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */

    protected $fillable = ['company_id', 'enable', 'name', 'surname', 'email', 'email_verified_at', 'password', 'counter', 'url_address',  'isCompany', 'isMailing', 'content', 'nip1', 'business1', 'phone1', 'street1', 'number1', 'postal_code1', 'city1', 'country_id1', 'provincial_id1', 'nip2', 'business2', 'phone2', 'street2', 'number2', 'postal_code2', 'city2', 'country_id2', 'provincial_id2', 'nip3', 'business3', 'phone3', 'street3', 'number3', 'postal_code3', 'city3', 'country_id3', 'provincial_id3', 'cash', 'lng', 'lat', 'enable_map', 'remember_token', 'created_at', 'updated_at', 'last_login_at', 'last_login_ip' ];

    /**
     * The attributes that should be hidden for arrays.
     *
     * @var array
     */
    protected $hidden = [
        'password', 'remember_token',
    ];

    public function roles()
    {
        return $this->belongsToMany('App\Role');
    }

    public function mainRole()
    {
        return $this->hasOne('App\Role');
    }

    public function comments()
    {
        return $this->hasMany('App\Comments');
    }

    public function images()
    {   // find(['photoable_type', '=', 'AdminImage'] ::with('director')->get();
        return $this->hasMany('App\UploadedFiles' );
    }

    public function images2()
    {   // ->where('photoable_type', 'AdminImage')
        return $this->hasManyThrough('App\UploadedFiles', 'App\User', 'photoable_id', 'id');
    }

    public function hasRole(array $roles)
    {

        foreach($roles as $role)
        {

            if(isset(self::$roles[$role]))
            {
                if(self::$roles[$role])  return true;

            }
            else
            {
                self::$roles[$role] = $this->roles()->where('name', $role)->exists();
                if(self::$roles[$role]) return true;
            }

        }
        return false;
    }

    public function loginHistory()
    {
        return $this->hasMany('App\UserLoginHistory');
    }

    public function companies()
    {
        return $this->belongsTo('App\Companies','company_id');
    }

}

My schema:

Schema::create('users', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->bigInteger('company_id')->unsigned();
            $table->foreign('company_id')->references('id')->on('companies')->onDelete('cascade');
            $table->boolean('enable')->default(0);
            $table->string('name', 120)->nullable();
            $table->string('surname', 120)->nullable();
            $table->string('email', 120)->unique();
            $table->timestamp('email_verified_at')->nullable();
            $table->string('password');
            $table->bigInteger('counter')->default(0);
            $table->string('url_address', 160);
            $table->boolean('isCompany')->default(0);
            $table->boolean('isMailing')->default(0);
            $table->text('content')->nullable();
            $table->string('nip1', 12)->nullable();
            $table->string('business1', 120)->nullable();
            $table->string('phone1', 60)->nullable();
            $table->string('street1', 150)->nullable();
            $table->string('number1', 8)->nullable();
            $table->string('postal_code1', 12)->nullable();
            $table->string('city1', 100)->nullable();
            $table->bigInteger('country_id1')->default(0);
            $table->bigInteger('provincial_id1')->default(0);
            $table->string('nip2', 12)->nullable();
            $table->string('business2', 120)->nullable();
            $table->string('phone2', 60)->nullable();
            $table->string('street2', 150)->nullable();
            $table->string('number2', 8)->nullable();
            $table->string('postal_code2', 12)->nullable();
            $table->string('city2', 100)->nullable();
            $table->bigInteger('country_id2')->default(0);
            $table->bigInteger('provincial_id2')->default(0);
            $table->string('nip3', 12)->nullable();
            $table->string('business3', 120)->nullable();
            $table->string('phone3', 60)->nullable();
            $table->string('street3', 150)->nullable();
            $table->string('number3', 8)->nullable();
            $table->string('postal_code3', 12)->nullable();
            $table->string('city3', 100)->nullable();
            $table->bigInteger('country_id3')->default(0);
            $table->bigInteger('provincial_id3')->default(0);
            $table->decimal('cash', 9, 2)->default(0);
            $table->decimal('lng', 10, 8)->default(0);
            $table->decimal('lat', 10, 8)->default(0);
            $table->boolean('enable_map')->default(0);
            $table->rememberToken();
            $table->timestamps();
            $table->engine = "InnoDB";
        });

Schema::create('role_user', function (Blueprint $table) {
            $table->bigInteger('user_id')->unsigned();
            $table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
            $table->bigInteger('role_id')->unsigned();
            $table->foreign('role_id')->references('id')->on('roles')->onDelete('cascade');
            $table->engine = "InnoDB";
        });

Schema::create('roles', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->string('name');
            $table->engine = "InnoDB";
        });

Schema::create('uploaded_files', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->bigInteger('company_id')->unsigned();
            $table->foreign('company_id')->references('id')->on('companies')->onDelete('cascade');
            $table->boolean('enable')->default(0);
            $table->string('photoable_type', 150);
            $table->integer('photoable_id');
            $table->string('path', 255);
            $table->string('ip', 25);
            $table->bigInteger('number')->default(0);
            $table->timestamps();
            $table->engine = "InnoDB";
        });

I have the following record in the database:
https://ibb.co/ZhHGkKX

INSERT INTO `uploaded_files` (`id`, `company_id`, `enable`, `photoable_type`, `photoable_id`, `path`, `ip`, `number`, `created_at`, `updated_at`) VALUES
(46, 1, 1, 'AdminImage', 1, 'upload/images/AdminImage/627e653871183f639c8d9460f37111b1.jpg', '172.29.0.1', 0, '2019-05-27 08:50:08', '2019-05-27 08:50:08');
COMMIT;

In my base I have relations:
- uploaded_files.photoable_id = User.id

I need to display all images belonging to the user that have the photoable_type = AdminImage

How can I do this? Please help

Body:
You have declared the correct method in your user model so try to modify it:

 public function images()
{
    // App\UploadedFiles must be a model
    return $this->hasMany(App\UploadedFiles::class, 'photoable_id', 'id');
}

Use the relationship as follows:

User::with('images')->get();

Regards


问:
origin 'http://localhost:4200' has been blocked by CORS policy in Angular7
I want to use of http://5.160.2.148:8091/api/trainTicketing/city/findAll rest for get cities in my angular project.

I used version 7.2.15 of angular in my project.

when get this url with httpClient throw following error :

```<code> Access to XMLHttpRequest at 'http://5.160.2.148:8091/api/trainTicketing/city/findAll' from origin 'http://localhost:4200' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.
</code>```

While at work correctly when enter url in browser and postman.

why ?

答:
The solution needs to add these headers to the server response.

```<code>'Access-Control-Allow-Origin', '*'
'Access-Control-Allow-Methods', 'GET,POST,OPTIONS,DELETE,PUT'
</code>```

If you have access to the server, you can add them and this will solve your problem

OR

You can try concatentaing this in front of the url:

```<code>https://cors-anywhere.herokuapp.com/
</code>```

Body:
I want to use of http://5.160.2.148:8091/api/trainTicketing/city/findAll rest for get cities in my angular project.

I used version 7.2.15 of angular in my project.

when get this url with httpClient throw following error :

 Access to XMLHttpRequest at 'http://5.160.2.148:8091/api/trainTicketing/city/findAll' from origin 'http://localhost:4200' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.

While at work correctly when enter url in browser and postman.

why ?

Body:
The solution needs to add these headers to the server response.

'Access-Control-Allow-Origin', '*'
'Access-Control-Allow-Methods', 'GET,POST,OPTIONS,DELETE,PUT'

If you have access to the server, you can add them and this will solve your problem

OR

You can try concatentaing this in front of the url:

https://cors-anywhere.herokuapp.com/


问:
Using RxJS observables to consider all input MIDI devices
I have a method that handles incoming MIDI messages just fine.

It listen on ALL input devices, and not just on the first one.

I would like to write it using RxJS observables.

Here is the working (non RxJS observables) one:

```<code>public initMidiInputBis() {
  if (navigator.requestMIDIAccess) {
    console.log('This browser supports MIDI');
    navigator.requestMIDIAccess().then(
      (midiAccess: WebMidi.MIDIAccess) => this.onMIDISuccess(midiAccess),
      (midiAccess: WebMidi.MIDIAccess) => this.onMIDIFailure(midiAccess)
    );
  } else {
    console.log('This browser does not support MIDI');
  }
}

private onMIDISuccess(midiAccess: WebMidi.MIDIAccess) {
  for (const inputDevice of Array.from(midiAccess.inputs)) {
    inputDevice[1].onmidimessage = (message: WebMidi.MIDIMessageEvent) => this.onMIDIMessage(message);
  }
}

private onMIDIFailure(error: any) {
  console.log('The browser could not access any MIDI device');
  console.log(error);
}
</code>```

This above method works fine, the VMPK virtual keyboard is seen as an input MIDI device and its MIDI messages are received.

Here is my attempt at writing it again using observables:

```<code>public initMidiInput() {
  if (navigator.requestMIDIAccess) {
    console.log('This browser supports MIDI');
    const midiAccess$: Observable<WebMidi.MIDIAccess> = from(navigator.requestMIDIAccess());
    const midiInput$: Observable<WebMidi.MIDIInput> = midiAccess$.pipe(
      map((midiAccess: WebMidi.MIDIAccess) => {
        return midiAccess.inputs.values().next().value;
      })
    );
    midiInput$.pipe(
      flatMap((midiInput: WebMidi.MIDIInput) => this.midiMessageAsObservable(midiInput)),
    ).subscribe((message: WebMidi.MIDIMessageEvent) => {
      this.onMIDIMessage(message);
    });
    midiAccess$.subscribe(midiAccess => {
      this.logOutputDevices(midiAccess);
    });
  } else {
    console.log('This browser does not support MIDI');
  }
}
</code>```

With this above method, the VMPK virtual keyboard is NOT seen as an input MIDI device.

This method contains the following line of code midiAccess.inputs.values().next().value; which only retrieves the first input MIDI device.

How can I consider ALL input MIDI devices ?

UPDATE: After adding some logger I can see the VMPK virtual keyboard is listed as an input device:

```<code>MIDIInput {onmidimessage: null, connection: "closed", id: "2A23249CBCD506F53AE4731A4FE186844C42191D517EC71DFC9813E84A1D2F87", manufacturer: "", name: "VMPK Output", …}
connection: "closed"
id: "2A23249CBCD506F53AE4731A4FE186844C42191D517EC71DFC9813E84A1D2F87"
manufacturer: ""
name: "VMPK Output"
onmidimessage: null
onstatechange: null
state: "connected"
type: "input"
version: "ALSA library version 1.1.6"
</code>```

I find puzzling that its connection is closed while its state is connected.

Here is how I logged the above output:

```<code>const midiAccess$: Observable<WebMidi.MIDIAccess> = from(navigator.requestMIDIAccess());
const midiInput$: Observable<WebMidi.MIDIInput> = midiAccess$.pipe(
  map((midiAccess: WebMidi.MIDIAccess) => {
    Array.from(midiAccess.inputs.entries()).forEach(entry => {
      console.log('Key: ' + entry[0]);
      console.log(entry[1]);
    });
    return midiAccess.inputs.values().next().value;
  })
);
</code>```

答:
Try this out.</p>

```<code>import { of, from, throwError } from 'rxjs';
import { map, switchMap, catchError } from 'rxjs/operators';

public initMidiInput() {
  if (navigator.requestMIDIAccess) {
    console.log('This browser supports MIDI');
    of(navigator.requestMIDIAccess())
    .pipe(
      map((midiAccess: WebMidi.MIDIAccess) => midiAccess.inputs),
      switchMap((inputs) => from(inputs)),
      catchError(error => {
        return throwError(error);
      })
    )
    .subscribe(inputDevice => {
      inputDevice[1].onmidimessage = (message: WebMidi.MIDIMessageEvent) => this.onMIDIMessage(message);
    }, error => {
        console.log('The browser could not access any MIDI device');
        console.log(error);
    });
  }
}

</code>```

Body:
I have a method that handles incoming MIDI messages just fine.

It listen on ALL input devices, and not just on the first one.

I would like to write it using RxJS observables.

Here is the working (non RxJS observables) one:

public initMidiInputBis() {
  if (navigator.requestMIDIAccess) {
    console.log('This browser supports MIDI');
    navigator.requestMIDIAccess().then(
      (midiAccess: WebMidi.MIDIAccess) => this.onMIDISuccess(midiAccess),
      (midiAccess: WebMidi.MIDIAccess) => this.onMIDIFailure(midiAccess)
    );
  } else {
    console.log('This browser does not support MIDI');
  }
}

private onMIDISuccess(midiAccess: WebMidi.MIDIAccess) {
  for (const inputDevice of Array.from(midiAccess.inputs)) {
    inputDevice[1].onmidimessage = (message: WebMidi.MIDIMessageEvent) => this.onMIDIMessage(message);
  }
}

private onMIDIFailure(error: any) {
  console.log('The browser could not access any MIDI device');
  console.log(error);
}

This above method works fine, the VMPK virtual keyboard is seen as an input MIDI device and its MIDI messages are received.

Here is my attempt at writing it again using observables:

public initMidiInput() {
  if (navigator.requestMIDIAccess) {
    console.log('This browser supports MIDI');
    const midiAccess$: Observable<WebMidi.MIDIAccess> = from(navigator.requestMIDIAccess());
    const midiInput$: Observable<WebMidi.MIDIInput> = midiAccess$.pipe(
      map((midiAccess: WebMidi.MIDIAccess) => {
        return midiAccess.inputs.values().next().value;
      })
    );
    midiInput$.pipe(
      flatMap((midiInput: WebMidi.MIDIInput) => this.midiMessageAsObservable(midiInput)),
    ).subscribe((message: WebMidi.MIDIMessageEvent) => {
      this.onMIDIMessage(message);
    });
    midiAccess$.subscribe(midiAccess => {
      this.logOutputDevices(midiAccess);
    });
  } else {
    console.log('This browser does not support MIDI');
  }
}

With this above method, the VMPK virtual keyboard is NOT seen as an input MIDI device.

This method contains the following line of code midiAccess.inputs.values().next().value; which only retrieves the first input MIDI device.

How can I consider ALL input MIDI devices ?

UPDATE: After adding some logger I can see the VMPK virtual keyboard is listed as an input device:

MIDIInput {onmidimessage: null, connection: "closed", id: "2A23249CBCD506F53AE4731A4FE186844C42191D517EC71DFC9813E84A1D2F87", manufacturer: "", name: "VMPK Output", …}
connection: "closed"
id: "2A23249CBCD506F53AE4731A4FE186844C42191D517EC71DFC9813E84A1D2F87"
manufacturer: ""
name: "VMPK Output"
onmidimessage: null
onstatechange: null
state: "connected"
type: "input"
version: "ALSA library version 1.1.6"

I find puzzling that its connection is closed while its state is connected.

Here is how I logged the above output:

const midiAccess$: Observable<WebMidi.MIDIAccess> = from(navigator.requestMIDIAccess());
const midiInput$: Observable<WebMidi.MIDIInput> = midiAccess$.pipe(
  map((midiAccess: WebMidi.MIDIAccess) => {
    Array.from(midiAccess.inputs.entries()).forEach(entry => {
      console.log('Key: ' + entry[0]);
      console.log(entry[1]);
    });
    return midiAccess.inputs.values().next().value;
  })
);

Body:
Try this out.

import { of, from, throwError } from 'rxjs';
import { map, switchMap, catchError } from 'rxjs/operators';

public initMidiInput() {
  if (navigator.requestMIDIAccess) {
    console.log('This browser supports MIDI');
    of(navigator.requestMIDIAccess())
    .pipe(
      map((midiAccess: WebMidi.MIDIAccess) => midiAccess.inputs),
      switchMap((inputs) => from(inputs)),
      catchError(error => {
        return throwError(error);
      })
    )
    .subscribe(inputDevice => {
      inputDevice[1].onmidimessage = (message: WebMidi.MIDIMessageEvent) => this.onMIDIMessage(message);
    }, error => {
        console.log('The browser could not access any MIDI device');
        console.log(error);
    });
  }
}


问:
IE bug with TD's tables and whitespace?
I have a page that is using tables, in FF etc it works perfect, but in IE7 it causes issues, it's basically where the four corners have a td and and img (its a rounded corner form) .. if I remove the whitespace from the document it fixes the issue.. What actually happens is that it messes up the tables.. it puts a thin white line between the upper tr that holds the 2 corners and the next tr

I need to remove the the whitespace between the img and the TD, is there a better work around, as I have lots and not only that if I reformat the document the problem returns..

Here is a simple example..

```<code>   <table width="100%" height="418" border="0" cellpadding="0" cellspacing="0" bgcolor="#F04A23"
            style="margin: 0px; padding: 0px">
            <tr>
                <td width="12" align="left" valign="top">
                    <img src="content/images/corner_left.gif" width="12" height="12" />
                </td>
</code>```

as you can see there is white space between img and td... and I remove it so it looks like this:

```<code><img src="content/images/corner_left.gif" width="12" height="12" /></td>
</code>```

the problem is gone, (notice the td and image are right next to each other)

Any ideas, I tried setting all sorts of css, padding 0px, margins 0px etc ...

Any ideas really appreciated.

答:
I tried all solutions above:

a) tried the display:block

b) removed white spaces in td tags (ie I used tr and td tags without white space inbetween them. )

c) I tried using:

```<code>padding:0px;border-spacing:0px;border-style:none;border-collapse: collapse;margin:0;overflow: hidden;
</code>```

Solution a) worked.  Solutions b) and c) did not work on IE.

But the BEST SOLUTION I found is this:

Add a hspace=0 attribute to the Image tag. For example:

```<code><img src="http://www.printersrose.com/css/myimages/book1.jpg" alt="Header1" class="ImageHeader" hspace="0" />
</code>```

This does the trick.

ContentLicense: CC BY-SA 3.0

Title: IE bug with TD's tables and whitespace?

Body:
I have a page that is using tables, in FF etc it works perfect, but in IE7 it causes issues, it's basically where the four corners have a td and and img (its a rounded corner form) .. if I remove the whitespace from the document it fixes the issue.. What actually happens is that it messes up the tables.. it puts a thin white line between the upper tr that holds the 2 corners and the next tr

I need to remove the the whitespace between the img and the TD, is there a better work around, as I have lots and not only that if I reformat the document the problem returns..

Here is a simple example..

as you can see there is white space between img and td... and I remove it so it looks like this:

the problem is gone, (notice the td and image are right next to each other)

Any ideas, I tried setting all sorts of css, padding 0px, margins 0px etc ...

Any ideas really appreciated.

Body:
I tried all solutions above:

a) tried the display:block

b) removed white spaces in td tags (ie I used tr and td tags without white space inbetween them. )

c) I tried using:

padding:0px;border-spacing:0px;border-style:none;border-collapse: collapse;margin:0;overflow: hidden;

Solution a) worked.  Solutions b) and c) did not work on IE.

But the BEST SOLUTION I found is this:

Add a hspace=0 attribute to the Image tag. For example:

<img src="http://www.printersrose.com/css/myimages/book1.jpg" alt="Header1" class="ImageHeader" hspace="0" />

This does the trick.


问:
Query values from each json in a json array on postgresql
Each record in my database has a json list, from which I'm trying to return a value inside each element.

I'm trying to return

```<code>environmental services, energy & utilities
</code>```

From

```<code>[
  {
    "key": "environmental services"
  },
  {
    "key": "energy & utilities"
  }
]
</code>```

And.

```<code>construction
</code>```

From

```<code>[
  {
    "key": "construction"
  }
]
</code>```

Where the length of each json list in each record is undetermined.

I can get the first value with:

```<code>select
  column_name -> 0 -> 'key'
from table
</code>```

But how to get all.

How can I do this in postgresql?

答:
Use the function jsonb_array_elements() in a lateral join to get all elements of the arrays and the aggregate function string_agg():

```<code>with my_table(json_col) as (
values
('[
  {
    "key": "environmental services"
  },
  {
    "key": "energy & utilities"
  }
]'::jsonb),
('[
  {
    "key": "construction"
  }
]')
)

select string_agg(value->>'key', ', ')
from my_table
cross join jsonb_array_elements(json_col)
group by json_col       -- use PK here (if exists)

                 string_agg
--------------------------------------------
 environmental services, energy & utilities
 construction
(2 rows)
</code>```

Body:
Each record in my database has a json list, from which I'm trying to return a value inside each element.

I'm trying to return

environmental services, energy & utilities

From

[
  {
    "key": "environmental services"
  },
  {
    "key": "energy & utilities"
  }
]

And.

construction

From

[
  {
    "key": "construction"
  }
]

Where the length of each json list in each record is undetermined.

I can get the first value with:

select
  column_name -> 0 -> 'key'
from table

But how to get all.

How can I do this in postgresql?

Body:
Use the function jsonb_array_elements() in a lateral join to get all elements of the arrays and the aggregate function string_agg():

with my_table(json_col) as (
values
('[
  {
    "key": "environmental services"
  },
  {
    "key": "energy & utilities"
  }
]'::jsonb),
('[
  {
    "key": "construction"
  }
]')
)

select string_agg(value->>'key', ', ')
from my_table
cross join jsonb_array_elements(json_col)
group by json_col       -- use PK here (if exists)

                 string_agg
--------------------------------------------
 environmental services, energy & utilities
 construction
(2 rows)


问:
Making columns out of spans
I recive {patients} and place it into a div:

```<code><div className="patients">
   {patients}
</div>
</code>```

It contains Name and Surname, each row in two spans:

(Dev Tools)

(Current state)

How can style those spans into columns (table-like)?

(Expexted result)

---EDIT---

Content of {patients} changes. It's a result of searching, so different names come, sometimes more, sometimes less. I can't apply a style to them separatly.
See the code.

答:
```<code>    <div class="patients">
      <div class="patient">
        <span>Eric</span>
        <span>Car</span>
         <span>Car</span>
      </div>
      <div class="patient">
        <span>Eric</span>
        <span>Car</span>
         <span>Car</span>
      </div>
      <div class="patient">
        <span>Eric</span>
        <span>Car</span>
         <span>Car</span>
      </div>
      <div class="patient">
        <span>Eric</span>
        <span>Car</span>
         <span>Car</span>
      </div>
    </div>

CSS
----

.patients {
  border: 1px solid black;
  display: table;
  width: 100%;
  border-bottom: none;
}

.patient {
  display: table-row;
}

.patient > span {
  display: table-cell;
  border-bottom: 1px solid black;
}
</code>```

Title: Making columns out of spans

Body:
I recive {patients} and place it into a div:

   {patients}

It contains Name and Surname, each row in two spans:

(Dev Tools)

(Current state)

How can style those spans into columns (table-like)?

(Expexted result)

---EDIT---

Content of {patients} changes. It's a result of searching, so different names come, sometimes more, sometimes less. I can't apply a style to them separatly.
See the code.


问:
Boost.Graph example 4 dynamic_properties error
Running Boost.Graph example 4 for QT gives flowing error:

no match for call to '(boost::dynamic_properties)(std::bacic_ostream>&,unsigned int)' graphvic.hpp

The error occurs at the following line of the graphvic.hpp:

```<code>for(boost::tie(i,end) = vertices(g); i != end; ++i) {
      out << escape_dot_string(get(vertex_id, *i));
      vpw(out, *i); //print vertex attributes
      out << ";" << std::endl;
}
</code>```

I am unable to find out the reason for the error. Below is the Boost.Graph example 4 code. Please help me.

```<code>typedef boost::adjacency_list
  <
    boost::vecS,
    boost::vecS,
    boost::undirectedS,
    boost::property<boost::vertex_name_t,std::string>,
    boost::property<boost::edge_weight_t,double>,
    boost::property<boost::graph_name_t,std::string>
  > Graph;

  Graph  g;

  std::vector<std::string> names;
  names.push_back("Mr_A");
  names.push_back("Mrs_B");
  names.push_back("Dr_C");
  names.push_back("Prof_D");

  const Graph::vertex_descriptor v0 = boost::add_vertex(names[0],g);
  const Graph::vertex_descriptor v1 = boost::add_vertex(names[1],g);
  const Graph::vertex_descriptor v2 = boost::add_vertex(names[2],g);
  const Graph::vertex_descriptor v3 = boost::add_vertex(names[3],g);

  std::vector<double> frequencies;
  frequencies.push_back(0.9);
  frequencies.push_back(0.5);
  frequencies.push_back(0.6);
  frequencies.push_back(0.1);

  boost::add_edge(v0,v1,frequencies[0],g);
  boost::add_edge(v1,v2,frequencies[1],g);
  boost::add_edge(v2,v3,frequencies[2],g);
  boost::add_edge(v0,v3,frequencies[3],g);

  //Writing graph to file
  {
    std::ofstream f("test.dot");

    boost::dynamic_properties p;
    p.property("label", boost::get(boost::edge_weight, g));
    p.property("weight", boost::get(boost::edge_weight, g));
    p.property("node_id", boost::get(boost::vertex_name, g));
    boost::write_graphviz(f,g,p);
    f.close();
  }
</code>```

Thanks,
Prakash

答: there is invalid call for a function get(). The second parameter should be a graph, not a vertex descriptor. Additionaly, you did not specify what is it vertex_id. May be you've meant vertext_name_t?

Body:
Running Boost.Graph example 4 for QT gives flowing error:

no match for call to '(boost::dynamic_properties)(std::bacic_ostream>&,unsigned int)' graphvic.hpp

The error occurs at the following line of the graphvic.hpp:

for(boost::tie(i,end) = vertices(g); i != end; ++i) {
      out << escape_dot_string(get(vertex_id, *i));
      vpw(out, *i); //print vertex attributes
      out << ";" << std::endl;
}

I am unable to find out the reason for the error. Below is the Boost.Graph example 4 code. Please help me.

typedef boost::adjacency_list
  <
    boost::vecS,
    boost::vecS,
    boost::undirectedS,
    boost::property<boost::vertex_name_t,std::string>,
    boost::property<boost::edge_weight_t,double>,
    boost::property<boost::graph_name_t,std::string>
  > Graph;

  Graph  g;

  std::vector<std::string> names;
  names.push_back("Mr_A");
  names.push_back("Mrs_B");
  names.push_back("Dr_C");
  names.push_back("Prof_D");

  const Graph::vertex_descriptor v0 = boost::add_vertex(names[0],g);
  const Graph::vertex_descriptor v1 = boost::add_vertex(names[1],g);
  const Graph::vertex_descriptor v2 = boost::add_vertex(names[2],g);
  const Graph::vertex_descriptor v3 = boost::add_vertex(names[3],g);

  std::vector<double> frequencies;
  frequencies.push_back(0.9);
  frequencies.push_back(0.5);
  frequencies.push_back(0.6);
  frequencies.push_back(0.1);

  boost::add_edge(v0,v1,frequencies[0],g);
  boost::add_edge(v1,v2,frequencies[1],g);
  boost::add_edge(v2,v3,frequencies[2],g);
  boost::add_edge(v0,v3,frequencies[3],g);

  //Writing graph to file
  {
    std::ofstream f("test.dot");

    boost::dynamic_properties p;
    p.property("label", boost::get(boost::edge_weight, g));
    p.property("weight", boost::get(boost::edge_weight, g));
    p.property("node_id", boost::get(boost::vertex_name, g));
    boost::write_graphviz(f,g,p);
    f.close();
  }

Thanks,
Prakash


问:
how to specify network name in app.yaml for asp.net core webapi deployed in Google appengine
I am trying to deploy an asp.net core webapi to google appengine flex. If you don't mention network name in app.yaml then it takes default.

In my case there is no default network. I have to explicitly specify the network name and subnetwork_name in my app.yaml. This project where I am trying to deploy my api in appengine flex is in a shared VPC.This is why I am specifying the complete path, "projects/myorg-npe-232f/global/networks/myorg-shared-network". Please refer the app.yaml below -

```<code>runtime: aspnetcore
env: flex
service: default
api_version: 1.1
network:
    name: projects/myorg-npe-232f/global/networks/myorg-shared-network
    subnetwork_name: myorg-exxc-bbdf-subnet-central
</code>```

I am getting the below error -

```<code>Unable to assign value 'projects/myorg-npe-232f/global/networks/myorg-shared-network' to attribute 'name':

value 'projects/myorg-npe-232f/global/networks/myorg-shared-network' for name does not match expression '^(?:^[a-z]([a-z\d-]{0,61}[a-z\d])?$)$' in app.yaml
</code>```

答:
As explained in the documentation here:

In a service project, App Engine Flexible resources cannot participate
  in Shared VPC.

You may want to consider VPC Peering instead if it fits your use case.

Body:
I am trying to deploy an asp.net core webapi to google appengine flex. If you don't mention network name in app.yaml then it takes default.

In my case there is no default network. I have to explicitly specify the network name and subnetwork_name in my app.yaml. This project where I am trying to deploy my api in appengine flex is in a shared VPC.This is why I am specifying the complete path, "projects/myorg-npe-232f/global/networks/myorg-shared-network". Please refer the app.yaml below -

runtime: aspnetcore
env: flex
service: default
api_version: 1.1
network:
    name: projects/myorg-npe-232f/global/networks/myorg-shared-network
    subnetwork_name: myorg-exxc-bbdf-subnet-central

I am getting the below error -

Unable to assign value 'projects/myorg-npe-232f/global/networks/myorg-shared-network' to attribute 'name':

value 'projects/myorg-npe-232f/global/networks/myorg-shared-network' for name does not match expression '^(?:^[a-z]([a-z\d-]{0,61}[a-z\d])?$)$' in app.yaml


问:
Seeking guide for Python3 new feature: "f-string"
How to use Python3 new feature : "f-string" to output the first 50 bits of math.pi?

We can achieve it by the following 2 old ways:
1 ("%.50f"% math.pi)
2 '{.50f}'.format(math.pi)
But for the new feature "f-string",I knew that we can use this format:
f"the value of pi is {math.pi}", but how to limit and filter the first 50 bits?

```<code>In [2]: ("%.50f"%math.pi)
Out[2]: '3.14159265358979311599796346854418516159057617187500'
</code>```

Body:
How to use Python3 new feature : "f-string" to output the first 50 bits of math.pi?

We can achieve it by the following 2 old ways:
1 ("%.50f"% math.pi)
2 '{.50f}'.format(math.pi)
But for the new feature "f-string",I knew that we can use this format:
f"the value of pi is {math.pi}", but how to limit and filter the first 50 bits?

In [2]: ("%.50f"%math.pi)
Out[2]: '3.14159265358979311599796346854418516159057617187500'

Body:
Same formatting as with str.format, but using the variable name in the first block before the ::

>>> import math
>>> f"{math.pi:.50f}"
'3.14159265358979311599796346854418516159057617187500'
>>> f"the value of pi is {math.pi:.50f}"
'the value of pi is 3.14159265358979311599796346854418516159057617187500'


问:
How to check whetherpop up blocker is turned ON or not in a browser using Code ?
How to check whether pop up blocker is turned ON or not in a browser using java or Java script Code ?

```<code>function check ()
{
    document.login.action= url+"test.jsp";
    document.login.submit();
}
</code>```

I will call this function on click of submit button

答:
How about:</p>

```<code>var myWindow = window.open (url);

if (if (myWindow == null || typeof(myWindow )=='undefined'))
{
     // popup blocker is enabled
}
else
{
     myWindow.close();
}
</code>```

Body:
How to check whether pop up blocker is turned ON or not in a browser using java or Java script Code ?

function check ()
{
    document.login.action= url+"test.jsp";
    document.login.submit();
}

I will call this function on click of submit button

Body:
How about:

var myWindow = window.open (url);

if (if (myWindow == null || typeof(myWindow )=='undefined'))
{
     // popup blocker is enabled
}
else
{
     myWindow.close();
}


问:
How to make changes to msr 0x199 from EFI stick?
I have a macbookpro11,3 without a battery.  When battery is removed the firmware throttles the CPU to half speed.  In Windows I can override this using Throttlestop to turn off BD PROCHOT and set multiplier to 25.  I want to do this from EFI so that boot and updates run at a normal speed.

Based on source for rEFInd which updates 0x3a register I wrote this program but while BD PROCHOT is disabled correctly after booting into Windows the multiplier is not.

```<code>#include "../include/tiano_includes.h"
static VOID DisablePROCHOT(VOID)
{
    UINT32 msr = 0x1FC;
    UINT32 low_bits = 0, high_bits = 0;

    __asm__ volatile ("rdmsr" : "=a" (low_bits), "=d" (high_bits) : "c" (msr));

    // lowest bit is BD PROCHOT
    low_bits &= ~(1 << 0);

    __asm__ volatile ("wrmsr" : : "c" (msr), "a" (low_bits), "d" (high_bits));
} // VOID DisablePROCHOT()

static VOID SetMultiplier25(VOID)
{
    UINT32 msr = 0x199;
    UINT32 low_bits = 0, high_bits = 0;

    __asm__ volatile ("rdmsr" : "=a" (low_bits), "=d" (high_bits) : "c" (msr));

    // second lowest byte is multiplier
    // 25 is .... xxxxxxxx 00011001 xxxxxxxx
    low_bits |= 1 << 8;
    low_bits &= ~(1 << 9);
    low_bits &= ~(1 << 10);
    low_bits |= 1 << 11;
    low_bits |= 1 << 12;
    low_bits &= ~(1 << 13);
    low_bits &= ~(1 << 14);
    low_bits &= ~(1 << 15);

    __asm__ volatile ("wrmsr" : : "c" (msr), "a" (low_bits), "d" (high_bits));
} // VOID SetMultiplier25()

EFI_STATUS
EFIAPI
efi_main (
  IN EFI_HANDLE        ImageHandle,
  IN EFI_SYSTEM_TABLE  *SystemTable
  )
{
  DisablePROCHOT();
  SetMultiplier25();

  return EFI_SUCCESS;
}
</code>```

Reading the registers with rdmsr from EFI appears to show both are set correctly however when booted into Windows while bit 0 of 0x1FC is correctly set off the multiplier stored in 0x199 is unchanged from the default of 12 when I expect it to be 25.

Default values

These are values after standard boot into Windows (from RWEverything)

Results after calling program

Program was called from EFI shell before calling Windows boot loader bootmgfw.efi

0x1FC is updated, 0x199 is not.

Updating 0x199 with RWEverything from within Windows changes the multiplier correctly so I'm fairly sure it is the correct register.

As this is my first EFI (or C) program I may have overlooked something trivial.

答:
You have to create a loop and change processor affinity each time through the loop.  Then you do a wrmsr for each thread (CPU1, CPU2, CPU3, CPU4) each time through the loop.  In Windows you use this function.

https://learn.microsoft.com/en-us/windows/desktop/api/winbase/nf-winbase-setthreadaffinitymask

As soon as you boot up, Windows changes the values in MSR 0x199 so seeing what values are in MSR 0x199 after you boot up does not prove anything.

To simplify things, you can do this in SetMultiplier,

low_bits = 0x1900

Body:
I have a macbookpro11,3 without a battery.  When battery is removed the firmware throttles the CPU to half speed.  In Windows I can override this using Throttlestop to turn off BD PROCHOT and set multiplier to 25.  I want to do this from EFI so that boot and updates run at a normal speed.

Based on source for rEFInd which updates 0x3a register I wrote this program but while BD PROCHOT is disabled correctly after booting into Windows the multiplier is not.

#include "../include/tiano_includes.h"
static VOID DisablePROCHOT(VOID)
{
    UINT32 msr = 0x1FC;
    UINT32 low_bits = 0, high_bits = 0;

    __asm__ volatile ("rdmsr" : "=a" (low_bits), "=d" (high_bits) : "c" (msr));

    // lowest bit is BD PROCHOT
    low_bits &= ~(1 << 0);

    __asm__ volatile ("wrmsr" : : "c" (msr), "a" (low_bits), "d" (high_bits));
} // VOID DisablePROCHOT()

static VOID SetMultiplier25(VOID)
{
    UINT32 msr = 0x199;
    UINT32 low_bits = 0, high_bits = 0;

    __asm__ volatile ("rdmsr" : "=a" (low_bits), "=d" (high_bits) : "c" (msr));

    // second lowest byte is multiplier
    // 25 is .... xxxxxxxx 00011001 xxxxxxxx
    low_bits |= 1 << 8;
    low_bits &= ~(1 << 9);
    low_bits &= ~(1 << 10);
    low_bits |= 1 << 11;
    low_bits |= 1 << 12;
    low_bits &= ~(1 << 13);
    low_bits &= ~(1 << 14);
    low_bits &= ~(1 << 15);

    __asm__ volatile ("wrmsr" : : "c" (msr), "a" (low_bits), "d" (high_bits));
} // VOID SetMultiplier25()

EFI_STATUS
EFIAPI
efi_main (
  IN EFI_HANDLE        ImageHandle,
  IN EFI_SYSTEM_TABLE  *SystemTable
  )
{
  DisablePROCHOT();
  SetMultiplier25();

  return EFI_SUCCESS;
}

Reading the registers with rdmsr from EFI appears to show both are set correctly however when booted into Windows while bit 0 of 0x1FC is correctly set off the multiplier stored in 0x199 is unchanged from the default of 12 when I expect it to be 25.

Default values

These are values after standard boot into Windows (from RWEverything)

Results after calling program

Program was called from EFI shell before calling Windows boot loader bootmgfw.efi

0x1FC is updated, 0x199 is not.

Updating 0x199 with RWEverything from within Windows changes the multiplier correctly so I'm fairly sure it is the correct register.

As this is my first EFI (or C) program I may have overlooked something trivial.


问:
How to make a node call from another node in a package on CONNECT platform?
When developing a CONNECT package, how can you add a call to another node programmatically?</p>

答:
you can easily do that via the javascript API:

const platform = require('connect-platform');

platform.call('/your-path', {
  paramA: "some-value",
  //
  // all other parameters you want to pass. if there are none, leave this empty.
  //
});
```

check this guide for more info on that:
https://medium.com/connect-platform/inline-coding-in-connect-platform-534fce3c8cdf

Body:
you can easily do that via the javascript API:

const platform = require('connect-platform');

platform.call('/your-path', {
  paramA: "some-value",
  //
  // all other parameters you want to pass. if there are none, leave this empty.
  //
});

check this guide for more info on that:
https://medium.com/connect-platform/inline-coding-in-connect-platform-534fce3c8cdf


问:
Android problem with ArrayList of objects in SAX-parser
I'm trying to parse an XML page which is build like this: http://pastebin.com/t9cXdnGs.
I've implemented a basic SAX parser, following this tutorial: Anddev SAX tutorial.

It worked pretty well, except I'm only getting the values of the last tag. To solve this, I've implemented an ArrayList to add each object that's made per XML node. But now I'm getting some weird output. For each node he passes in the loop, he adds the same value again. So for node 1, I get the value once, for node 2, I get the value twice and so on... (example: value1, value2value2, value3value3value3)

I can't seem to figure out what's wrong...

Here's my full source code of the page: http://pastebin.com/bkyz0g1U

答:
I quickly changed your code to a simpler solution:</p>

```<code>    package stage.accent.webservice;

import java.util.ArrayList;

import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;

import stage.accent.domain.Vacature;

public class vacatureWebservice extends DefaultHandler {

        private ArrayList<Vacature>arrayVaca = new ArrayList<Vacature>();

        private Vacature vacature = null;

        public ArrayList<Vacature> getVacatures() {
            return this.arrayVaca;

        }

        public StringBuilder buff =  new StringBuilder();

        @Override
        public void startDocument() throws SAXException {

            this.vacature = new Vacature();
        }

        @Override
        public void endDocument() throws SAXException {
            // Nothing to do

        }

        /** Gets be called on opening tags like:
         * <tag>
         * Can provide attribute(s), when xml was like:
         * <tag attribute="attributeValue">*/
        @Override
        public void startElement(String namespaceURI, String localName,
                String qName, Attributes atts) throws SAXException {

        }

        /** Gets be called on closing tags like:
         * </tag> */
        @Override
        public void endElement(String namespaceURI, String localName, String qName)
                throws SAXException {
            if (localName.equals("vacatures")) {

            }else if (localName.equals("vacature")) {
            }else if (localName.equals("titel")) {
                vacature.setTitel(buff.toString());
            }else if (localName.equals("werkveld")){
                vacature.setWerkveld(buff.toString());
            }else if (localName.equals("regio")){

                vacature.setRegio(buff.toString());
                arrayVaca.add(vacature);
                vacature = new Vacature();

            }

            buff = new StringBuilder();
        }

        /** Gets be called on the following structure:
         * <tag>characters</tag> */
        @Override
        public void characters(char ch[], int start, int length) {
             if (buff!=null) {
                    for (int i=start; i<start+length; i++) {
                        buff.append(ch[i]);
                    }
                }

        }
    }
</code>```

Body:
I quickly changed your code to a simpler solution:

    package stage.accent.webservice;

import java.util.ArrayList;

import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;

import stage.accent.domain.Vacature;

public class vacatureWebservice extends DefaultHandler {

        private ArrayList<Vacature>arrayVaca = new ArrayList<Vacature>();

        private Vacature vacature = null;

        public ArrayList<Vacature> getVacatures() {
            return this.arrayVaca;

        }

        public StringBuilder buff =  new StringBuilder();

        @Override
        public void startDocument() throws SAXException {

            this.vacature = new Vacature();
        }

        @Override
        public void endDocument() throws SAXException {
            // Nothing to do

        }

        /** Gets be called on opening tags like:
         * <tag>
         * Can provide attribute(s), when xml was like:
         * <tag attribute="attributeValue">*/
        @Override
        public void startElement(String namespaceURI, String localName,
                String qName, Attributes atts) throws SAXException {

        }

        /** Gets be called on closing tags like:
         * </tag> */
        @Override
        public void endElement(String namespaceURI, String localName, String qName)
                throws SAXException {
            if (localName.equals("vacatures")) {

            }else if (localName.equals("vacature")) {
            }else if (localName.equals("titel")) {
                vacature.setTitel(buff.toString());
            }else if (localName.equals("werkveld")){
                vacature.setWerkveld(buff.toString());
            }else if (localName.equals("regio")){

                vacature.setRegio(buff.toString());
                arrayVaca.add(vacature);
                vacature = new Vacature();

            }

            buff = new StringBuilder();
        }

        /** Gets be called on the following structure:
         * <tag>characters</tag> */
        @Override
        public void characters(char ch[], int start, int length) {
             if (buff!=null) {
                    for (int i=start; i<start+length; i++) {
                        buff.append(ch[i]);
                    }
                }

        }
    }


问:
how to display string values from simpleStringProperty onto listView correctly
I want to display values from ObservableList of type ManagerData in a list view.

The ManagerData class consists of 2 SimpleStringProperty’s accountName and password.

But as I populate the list view with the data it displays the values of the SimpleStringProperty as 'model.ManagerData@1a697fac', 'model.ManagerData@3c42f0f0' and 'model.ManagerData@fc87ab8' in the list view and not the value of the SimpleStringProperty.

The Controller class:

```<code>package manager;

import com.jfoenix.controls.JFXListView;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.TextField;
import misci.AlertBuilder;
import misci.DB;
import model.ManagerData;

import java.net.URL;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ResourceBundle;

public class Controller implements Initializable {

@FXML private JFXListView listView;
@FXML private TextField txtAccount, txtPassword;

private final ObservableList listData = FXCollections.observableArrayList();
private String sql;
private ResultSet rs;

@FXML private void loadAction() {
    sql = "select * from account";
    rs = DB.executeQuery(sql);

    if (rs != null) {
        try {
            while (rs.next()) {
                listData.addAll(new ManagerData(rs.getString("name")));
                listView.setItems(listData);
            }
        } catch (SQLException ex) {
            ex.printStackTrace();
        }
    }
}

@Override public void initialize(URL location, ResourceBundle resources) { }
}
</code>```

ManagerData wrapper class:

```<code>package model;

import javafx.beans.property.SimpleStringProperty;

public class ManagerData {

private final SimpleStringProperty accountName, password;

public ManagerData(){
    this.accountName = new SimpleStringProperty();
    this.password = new SimpleStringProperty();
}

public ManagerData(String name){
    this.accountName = new SimpleStringProperty(name);
    this.password = new SimpleStringProperty();
}

public ManagerData(String name, String password){
    this.accountName = new SimpleStringProperty(name);
    this.password = new SimpleStringProperty(password);
}

//setter methods
public void setAccountName(String accountName){
    this.accountName.set(accountName);
}

public void setPassword(String password){
    this.password.set(password);
}

//getter methods
public String getAccountName() {
    return this.accountName.get();
}

public String getPassword() {
    return this.password.get();
}
}
</code>```

GUI

```<code>    <?xml version="1.0" encoding="UTF-8"?>

<?import com.jfoenix.controls.JFXButton?>
<?import com.jfoenix.controls.JFXListView?>
<?import de.jensd.fx.glyphs.materialdesignicons.MaterialDesignIconView?>
<?import javafx.scene.control.TextField?>
<?import javafx.scene.effect.DropShadow?>
<?import javafx.scene.layout.AnchorPane?>
<?import javafx.scene.layout.HBox?>
<?import javafx.scene.layout.StackPane?>

<AnchorPane maxHeight="-Infinity" maxWidth="-Infinity" minHeight="-Infinity" minWidth="-Infinity" prefHeight="550.0" prefWidth="850.0" style="-fx-background-color: white;" xmlns="http://javafx.com/javafx/8.0.141" xmlns:fx="http://javafx.com/fxml/1" fx:controller="manager.Controller">
   <children>
      <StackPane prefHeight="150.0" prefWidth="200.0" style="-fx-background-color: white;" AnchorPane.bottomAnchor="0.0" AnchorPane.leftAnchor="0.0" AnchorPane.rightAnchor="0.0" AnchorPane.topAnchor="30.0">
         <children>
            <AnchorPane prefHeight="200.0" prefWidth="200.0">
               <children>
                  <JFXListView fx:id="listView" depth="1" editable="true" focusTraversable="false" layoutX="530.0" layoutY="41.0" showTooltip="true" stylesheets="@listViewStyles.css" AnchorPane.bottomAnchor="0.0" AnchorPane.leftAnchor="500.0" AnchorPane.rightAnchor="0.0" AnchorPane.topAnchor="15.0" />
               </children></AnchorPane>
         </children></StackPane>
      <AnchorPane layoutX="39.0" layoutY="41.0" prefHeight="45.0" style="-fx-background-color: white;" AnchorPane.leftAnchor="0.0" AnchorPane.rightAnchor="0.0" AnchorPane.topAnchor="0.0">
         <effect>
            <DropShadow blurType="GAUSSIAN" color="#616161" height="5.63" offsetY="2.5" radius="0.9075" width="0.0" />
         </effect>
         <children>
            <JFXButton contentDisplay="GRAPHIC_ONLY" focusTraversable="false" layoutX="47.0" layoutY="19.0" prefWidth="45.0" ripplerFill="#8d8d8dd6" style="-fx-background-radius: 0em; -fx-border-radius: 0em;" AnchorPane.bottomAnchor="0.0" AnchorPane.leftAnchor="0.0" AnchorPane.topAnchor="0.0">
               <graphic>
                  <MaterialDesignIconView fill="#616161" glyphName="MENU" size="20" />
               </graphic>
            </JFXButton>
            <JFXButton contentDisplay="GRAPHIC_ONLY" focusTraversable="false" layoutX="715.0" onAction="#addAction" prefWidth="45.0" ripplerFill="#8d8d8dd6" style="-fx-background-radius: 0em; -fx-border-radius: 0em;" AnchorPane.bottomAnchor="0.0" AnchorPane.rightAnchor="90.0" AnchorPane.topAnchor="0.0">
               <graphic>
                  <MaterialDesignIconView fill="#616161" glyphName="PLUS" size="20" />
               </graphic>
            </JFXButton>
            <JFXButton contentDisplay="GRAPHIC_ONLY" focusTraversable="false" layoutX="760.0" onAction="#loadAction" prefWidth="45.0" ripplerFill="#8d8d8dd6" style="-fx-background-radius: 0em; -fx-border-radius: 0em;" AnchorPane.bottomAnchor="0.0" AnchorPane.rightAnchor="45.0" AnchorPane.topAnchor="0.0">
               <graphic>
                  <MaterialDesignIconView fill="#616161" glyphName="DOWNLOAD" size="20" />
               </graphic>
            </JFXButton>
            <JFXButton contentDisplay="GRAPHIC_ONLY" focusTraversable="false" layoutX="661.0" layoutY="38.0" prefWidth="45.0" ripplerFill="#8d8d8dd6" style="-fx-background-radius: 0em; -fx-border-radius: 0em;" AnchorPane.bottomAnchor="0.0" AnchorPane.rightAnchor="0.0" AnchorPane.topAnchor="0.0">
               <graphic>
                  <MaterialDesignIconView fill="#616161" glyphName="DOTS_VERTICAL" size="20" />
               </graphic>
            </JFXButton>
            <HBox alignment="CENTER" layoutX="92.0" layoutY="10.0" spacing="20.0" AnchorPane.bottomAnchor="10.0" AnchorPane.leftAnchor="92.0" AnchorPane.rightAnchor="138.0" AnchorPane.topAnchor="10.0">
               <children>
                  <TextField fx:id="txtAccount" alignment="CENTER" focusTraversable="false" prefWidth="300.0" promptText="Account Name" style="-fx-background-radius: 1em; -fx-border-radius: 1em; -fx-background-insets: 0; -fx-background-color: #F5F5F5; -fx-text-fill: #616161;" />
                  <TextField fx:id="txtPassword" alignment="CENTER" focusTraversable="false" prefWidth="300.0" promptText="Password" style="-fx-background-radius: 1em; -fx-border-radius: 1em; -fx-background-insets: 0; -fx-background-color: #F5F5F5; -fx-text-fill: #616161;" />
               </children>
            </HBox>
         </children>
      </AnchorPane>
   </children>
</AnchorPane>
</code>```

答:
By default the list view will display the string representation of your object which is defined by toString(), so you should override toString() in ManagerData class and make it return whatever info you feel it is relevant for the display. Unless you define a CellFactory to configure what should be displayed in the cells, which is more appropriate than tweeking toString for the sake of display

```<code>listView.setCellFactory(param -> new ListCell< ManagerData >() {
@Override
protected void updateItem(ManagerData item, boolean empty) {
    super.updateItem(item, empty);

    if (empty || item.getAccountName() == null) {
        setText("");
    } else {
        setText(item.getAccountName());
    }
}
</code>```

});

Body:
I want to display values from ObservableList of type ManagerData in a list view.

The ManagerData class consists of 2 SimpleStringProperty’s accountName and password.

But as I populate the list view with the data it displays the values of the SimpleStringProperty as 'model.ManagerData@1a697fac', 'model.ManagerData@3c42f0f0' and 'model.ManagerData@fc87ab8' in the list view and not the value of the SimpleStringProperty.

The Controller class:

package manager;

import com.jfoenix.controls.JFXListView;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.TextField;
import misci.AlertBuilder;
import misci.DB;
import model.ManagerData;

import java.net.URL;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ResourceBundle;

public class Controller implements Initializable {

@FXML private JFXListView listView;
@FXML private TextField txtAccount, txtPassword;

private final ObservableList listData = FXCollections.observableArrayList();
private String sql;
private ResultSet rs;

@FXML private void loadAction() {
    sql = "select * from account";
    rs = DB.executeQuery(sql);

    if (rs != null) {
        try {
            while (rs.next()) {
                listData.addAll(new ManagerData(rs.getString("name")));
                listView.setItems(listData);
            }
        } catch (SQLException ex) {
            ex.printStackTrace();
        }
    }
}

@Override public void initialize(URL location, ResourceBundle resources) { }
}

ManagerData wrapper class:

package model;

import javafx.beans.property.SimpleStringProperty;

public class ManagerData {

private final SimpleStringProperty accountName, password;

public ManagerData(){
    this.accountName = new SimpleStringProperty();
    this.password = new SimpleStringProperty();
}

public ManagerData(String name){
    this.accountName = new SimpleStringProperty(name);
    this.password = new SimpleStringProperty();
}

public ManagerData(String name, String password){
    this.accountName = new SimpleStringProperty(name);
    this.password = new SimpleStringProperty(password);
}

//setter methods
public void setAccountName(String accountName){
    this.accountName.set(accountName);
}

public void setPassword(String password){
    this.password.set(password);
}

//getter methods
public String getAccountName() {
    return this.accountName.get();
}

public String getPassword() {
    return this.password.get();
}
}

GUI

    <?xml version="1.0" encoding="UTF-8"?>

<?import com.jfoenix.controls.JFXButton?>
<?import com.jfoenix.controls.JFXListView?>
<?import de.jensd.fx.glyphs.materialdesignicons.MaterialDesignIconView?>
<?import javafx.scene.control.TextField?>
<?import javafx.scene.effect.DropShadow?>
<?import javafx.scene.layout.AnchorPane?>
<?import javafx.scene.layout.HBox?>
<?import javafx.scene.layout.StackPane?>

<AnchorPane maxHeight="-Infinity" maxWidth="-Infinity" minHeight="-Infinity" minWidth="-Infinity" prefHeight="550.0" prefWidth="850.0" style="-fx-background-color: white;" xmlns="http://javafx.com/javafx/8.0.141" xmlns:fx="http://javafx.com/fxml/1" fx:controller="manager.Controller">
   <children>
      <StackPane prefHeight="150.0" prefWidth="200.0" style="-fx-background-color: white;" AnchorPane.bottomAnchor="0.0" AnchorPane.leftAnchor="0.0" AnchorPane.rightAnchor="0.0" AnchorPane.topAnchor="30.0">
         <children>
            <AnchorPane prefHeight="200.0" prefWidth="200.0">
               <children>
                  <JFXListView fx:id="listView" depth="1" editable="true" focusTraversable="false" layoutX="530.0" layoutY="41.0" showTooltip="true" stylesheets="@listViewStyles.css" AnchorPane.bottomAnchor="0.0" AnchorPane.leftAnchor="500.0" AnchorPane.rightAnchor="0.0" AnchorPane.topAnchor="15.0" />
               </children></AnchorPane>
         </children></StackPane>
      <AnchorPane layoutX="39.0" layoutY="41.0" prefHeight="45.0" style="-fx-background-color: white;" AnchorPane.leftAnchor="0.0" AnchorPane.rightAnchor="0.0" AnchorPane.topAnchor="0.0">
         <effect>
            <DropShadow blurType="GAUSSIAN" color="#616161" height="5.63" offsetY="2.5" radius="0.9075" width="0.0" />
         </effect>
         <children>
            <JFXButton contentDisplay="GRAPHIC_ONLY" focusTraversable="false" layoutX="47.0" layoutY="19.0" prefWidth="45.0" ripplerFill="#8d8d8dd6" style="-fx-background-radius: 0em; -fx-border-radius: 0em;" AnchorPane.bottomAnchor="0.0" AnchorPane.leftAnchor="0.0" AnchorPane.topAnchor="0.0">
               <graphic>
                  <MaterialDesignIconView fill="#616161" glyphName="MENU" size="20" />
               </graphic>
            </JFXButton>
            <JFXButton contentDisplay="GRAPHIC_ONLY" focusTraversable="false" layoutX="715.0" onAction="#addAction" prefWidth="45.0" ripplerFill="#8d8d8dd6" style="-fx-background-radius: 0em; -fx-border-radius: 0em;" AnchorPane.bottomAnchor="0.0" AnchorPane.rightAnchor="90.0" AnchorPane.topAnchor="0.0">
               <graphic>
                  <MaterialDesignIconView fill="#616161" glyphName="PLUS" size="20" />
               </graphic>
            </JFXButton>
            <JFXButton contentDisplay="GRAPHIC_ONLY" focusTraversable="false" layoutX="760.0" onAction="#loadAction" prefWidth="45.0" ripplerFill="#8d8d8dd6" style="-fx-background-radius: 0em; -fx-border-radius: 0em;" AnchorPane.bottomAnchor="0.0" AnchorPane.rightAnchor="45.0" AnchorPane.topAnchor="0.0">
               <graphic>
                  <MaterialDesignIconView fill="#616161" glyphName="DOWNLOAD" size="20" />
               </graphic>
            </JFXButton>
            <JFXButton contentDisplay="GRAPHIC_ONLY" focusTraversable="false" layoutX="661.0" layoutY="38.0" prefWidth="45.0" ripplerFill="#8d8d8dd6" style="-fx-background-radius: 0em; -fx-border-radius: 0em;" AnchorPane.bottomAnchor="0.0" AnchorPane.rightAnchor="0.0" AnchorPane.topAnchor="0.0">
               <graphic>
                  <MaterialDesignIconView fill="#616161" glyphName="DOTS_VERTICAL" size="20" />
               </graphic>
            </JFXButton>
            <HBox alignment="CENTER" layoutX="92.0" layoutY="10.0" spacing="20.0" AnchorPane.bottomAnchor="10.0" AnchorPane.leftAnchor="92.0" AnchorPane.rightAnchor="138.0" AnchorPane.topAnchor="10.0">
               <children>
                  <TextField fx:id="txtAccount" alignment="CENTER" focusTraversable="false" prefWidth="300.0" promptText="Account Name" style="-fx-background-radius: 1em; -fx-border-radius: 1em; -fx-background-insets: 0; -fx-background-color: #F5F5F5; -fx-text-fill: #616161;" />
                  <TextField fx:id="txtPassword" alignment="CENTER" focusTraversable="false" prefWidth="300.0" promptText="Password" style="-fx-background-radius: 1em; -fx-border-radius: 1em; -fx-background-insets: 0; -fx-background-color: #F5F5F5; -fx-text-fill: #616161;" />
               </children>
            </HBox>
         </children>
      </AnchorPane>
   </children>
</AnchorPane>

Body:
By default the list view will display the string representation of your object which is defined by toString(), so you should override toString() in ManagerData class and make it return whatever info you feel it is relevant for the display. Unless you define a CellFactory to configure what should be displayed in the cells, which is more appropriate than tweeking toString for the sake of display

listView.setCellFactory(param -> new ListCell< ManagerData >() {
@Override
protected void updateItem(ManagerData item, boolean empty) {
    super.updateItem(item, empty);

    if (empty || item.getAccountName() == null) {
        setText("");
    } else {
        setText(item.getAccountName());
    }
}

});