问:
Can't get Facebook ID and email
I faced with the following problem: I need to get FB id and email after authorization. Here's my code:

```<code>@Override
            public void onSuccess(LoginResult loginResult) {

                final String[] email = new String[1];
                final String[] id = new String[1];

                GraphRequest request = GraphRequest.newMeRequest(
                        loginResult.getAccessToken(),
                        (object, response) -> {
                            try {
                                email[0] = object.getString(FB_EMAIL_PERMISSION);
                                id[0] = object.getString(FB_ID_PERMISSION);
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }
                            response.getRawResponse();
                        });

                Bundle parameters = new Bundle();
                parameters.putString("fields", "id,email");
                request.setParameters(parameters);
                request.executeAsync();

                Bundle bundle = new Bundle();
                bundle.putString(EXTRA_TOKEN, loginResult.getAccessToken().getToken());
                bundle.putString(EXTRA_EMAIL, email[0]);
                bundle.putString(EXTRA_ID, id[0]);

                mPresenter.saveUserData(bundle);
            }
</code>```

But when I run my app, I don't get this fields. I checked in debugger and part

```<code>GraphRequest request = GraphRequest.newMeRequest(
                        loginResult.getAccessToken(),
                        (object, response) -> {
                            try {
                                email[0] = object.getString(FB_EMAIL_PERMISSION);
                                id[0] = object.getString(FB_ID_PERMISSION);
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }
                            response.getRawResponse();
                        });
</code>```

isn't called at all. I don't understand why it happens. So, what's the matter and how can I solve it?

UPD

Probably, maybe it would help, here's whole fb logic:

```<code>mCallbackManager = CallbackManager.Factory.create();
        mFacebookButton.setReadPermissions(Collections.singletonList(FB_EMAIL_PERMISSION));
        mFacebookButton.registerCallback(mCallbackManager, new FacebookCallback<LoginResult>() {
            @Override
            public void onSuccess(LoginResult loginResult) {

                final String[] email = new String[1];
                final String[] id = new String[1];

                GraphRequest request = GraphRequest.newMeRequest(
                        loginResult.getAccessToken(),
                        (object, response) -> {
                            try {
                                email[0] = object.getString(FB_EMAIL_PERMISSION);
                                id[0] = object.getString(FB_ID_PERMISSION);
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }
                            response.getRawResponse();
                        });

                Bundle parameters = new Bundle();
                parameters.putString("fields", "id,email");
                request.setParameters(parameters);
                request.executeAsync();

                Bundle bundle = new Bundle();
                bundle.putString(EXTRA_TOKEN, loginResult.getAccessToken().getToken());
                bundle.putString(EXTRA_EMAIL, email[0]);
                bundle.putString(EXTRA_ID, id[0]);

                mPresenter.saveUserData(bundle);
            }
</code>```

UPD 2

I have one think about this problem, that request is asynchronous and when I put a breakpoint on line mPresenter.saveUserData(bundle); information isn't loaded yet, but how can I make it synchronous? Or maybe I am wrong?

UPD 3

I changed my request in the following way, but it still doesn't work and breakpoints are skipped in this part.

```<code>GraphRequest request = GraphRequest.newMeRequest(
                        loginResult.getAccessToken(),
                        (object, response) -> {
                            try {
                                if (response.getJSONObject() != null) {
                                    JSONObject data = response.getJSONObject();
                                    if (data.has(FB_EMAIL_PERMISSION)) {
                                        email[0] = response.getJSONObject().getString(FB_EMAIL_PERMISSION);
                                    }
                                    if (data.has(FB_ID_PERMISSION)) {
                                        id[0] = response.getJSONObject().getString(FB_ID_PERMISSION);
                                    }
                                }
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }
                            response.getRawResponse();
                        });
</code>```

And here's the values of permissions:

```<code>private static final String FB_EMAIL_PERMISSION = "email";
private static final String FB_ID_PERMISSION = "id";
</code>```

答:
did you add permission to your facebook login button </p>

```<code>fbLoginButton.setPermissions(Arrays.asList("public_profile,email,user_birthday"));
</code>```

Title: Can't get Facebook ID and email

Body:
I faced with the following problem: I need to get FB id and email after authorization. Here's my code:

@Override
            public void onSuccess(LoginResult loginResult) {

                final String[] email = new String[1];
                final String[] id = new String[1];

                GraphRequest request = GraphRequest.newMeRequest(
                        loginResult.getAccessToken(),
                        (object, response) -> {
                            try {
                                email[0] = object.getString(FB_EMAIL_PERMISSION);
                                id[0] = object.getString(FB_ID_PERMISSION);
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }
                            response.getRawResponse();
                        });

                Bundle parameters = new Bundle();
                parameters.putString("fields", "id,email");
                request.setParameters(parameters);
                request.executeAsync();

                Bundle bundle = new Bundle();
                bundle.putString(EXTRA_TOKEN, loginResult.getAccessToken().getToken());
                bundle.putString(EXTRA_EMAIL, email[0]);
                bundle.putString(EXTRA_ID, id[0]);

                mPresenter.saveUserData(bundle);
            }

But when I run my app, I don't get this fields. I checked in debugger and part

GraphRequest request = GraphRequest.newMeRequest(
                        loginResult.getAccessToken(),
                        (object, response) -> {
                            try {
                                email[0] = object.getString(FB_EMAIL_PERMISSION);
                                id[0] = object.getString(FB_ID_PERMISSION);
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }
                            response.getRawResponse();
                        });

isn't called at all. I don't understand why it happens. So, what's the matter and how can I solve it?

UPD

Probably, maybe it would help, here's whole fb logic:

mCallbackManager = CallbackManager.Factory.create();
        mFacebookButton.setReadPermissions(Collections.singletonList(FB_EMAIL_PERMISSION));
        mFacebookButton.registerCallback(mCallbackManager, new FacebookCallback<LoginResult>() {
            @Override
            public void onSuccess(LoginResult loginResult) {

                final String[] email = new String[1];
                final String[] id = new String[1];

                GraphRequest request = GraphRequest.newMeRequest(
                        loginResult.getAccessToken(),
                        (object, response) -> {
                            try {
                                email[0] = object.getString(FB_EMAIL_PERMISSION);
                                id[0] = object.getString(FB_ID_PERMISSION);
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }
                            response.getRawResponse();
                        });

                Bundle parameters = new Bundle();
                parameters.putString("fields", "id,email");
                request.setParameters(parameters);
                request.executeAsync();

                Bundle bundle = new Bundle();
                bundle.putString(EXTRA_TOKEN, loginResult.getAccessToken().getToken());
                bundle.putString(EXTRA_EMAIL, email[0]);
                bundle.putString(EXTRA_ID, id[0]);

                mPresenter.saveUserData(bundle);
            }

UPD 2

I have one think about this problem, that request is asynchronous and when I put a breakpoint on line mPresenter.saveUserData(bundle); information isn't loaded yet, but how can I make it synchronous? Or maybe I am wrong?

UPD 3

I changed my request in the following way, but it still doesn't work and breakpoints are skipped in this part.

GraphRequest request = GraphRequest.newMeRequest(
                        loginResult.getAccessToken(),
                        (object, response) -> {
                            try {
                                if (response.getJSONObject() != null) {
                                    JSONObject data = response.getJSONObject();
                                    if (data.has(FB_EMAIL_PERMISSION)) {
                                        email[0] = response.getJSONObject().getString(FB_EMAIL_PERMISSION);
                                    }
                                    if (data.has(FB_ID_PERMISSION)) {
                                        id[0] = response.getJSONObject().getString(FB_ID_PERMISSION);
                                    }
                                }
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }
                            response.getRawResponse();
                        });

And here's the values of permissions:

private static final String FB_EMAIL_PERMISSION = "email";
private static final String FB_ID_PERMISSION = "id";

Body:
did you add permission to your facebook login button

fbLoginButton.setPermissions(Arrays.asList("public_profile,email,user_birthday"));


来源: stackexchange

问:
Width transtion not working with flex display
I have a flex element that I want to expand whenever i hover on it.

Here is my code:

HTML

```<code>    <div class="fixed-header">
        <div id="header"><h1>Physi_cs</h1></div>

        <div id="nav-list">
            <ul>
                <li><a href="#">Shop</a></li>
                <li><a href="#">Learn Physics</a></li>
                <li><a href="#">Articles</a></li>
                <li><a href="LoginPage.html">Log In</a></li>
                <li><a href="SignUpPage.html">Sign Up</a></li>
            </ul>
        </div>
    </div>
</code>```

CSS

```<code>.fixed-header {
    background-color: rgba(237, 241, 242, 0.8);
    height: 25vh;
    padding: 20px 0px;

    display: flex;
    flex-direction: row;
    align-items: center;

    box-shadow:0px -1px 2px rgba(23, 37, 58, 0.8) inset;
}

.fixed-header #header {
    display: flex;
    align-items: center;
    justify-content: center;
    flex-grow: 1;

    height: 80%;
    box-shadow: 3px 0px 0px rgba(40, 40, 40, 0.8); /* ACTS AS A BORDER */

    cursor: pointer;
    transition: all ease 1s;
}

.fixed-header #header:hover {
    width: 50vw; // HERE I AM TRYING TO CHANGE THE WIDTH
}
</code>```

I want my #header to expand over 1 second and not instantly.

Thanks for your help in advance!

答:
Add hover and transition events:</p>

```<code>.fixed-header #header {
  display: flex;
  align-items: center;
  justify-content: center;
  height: 80%;
  box-shadow: 3px 0px 0px rgba(40, 40, 40, 0.8);
  cursor: pointer;
  transition: all ease 1s;
  flex-basis: 35%;
}

.fixed-header #header:hover {
  flex-basis: 75%;
}
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I have a flex element that I want to expand whenever i hover on it.

Here is my code:

HTML

Physi_cs

Shop

Learn Physics

Articles

Log In

Sign Up

CSS

.fixed-header {
    background-color: rgba(237, 241, 242, 0.8);
    height: 25vh;
    padding: 20px 0px;

    display: flex;
    flex-direction: row;
    align-items: center;

    box-shadow:0px -1px 2px rgba(23, 37, 58, 0.8) inset;
}

.fixed-header #header {
    display: flex;
    align-items: center;
    justify-content: center;
    flex-grow: 1;

    height: 80%;
    box-shadow: 3px 0px 0px rgba(40, 40, 40, 0.8); /* ACTS AS A BORDER */

    cursor: pointer;
    transition: all ease 1s;
}

.fixed-header #header:hover {
    width: 50vw; // HERE I AM TRYING TO CHANGE THE WIDTH
}

I want my #header to expand over 1 second and not instantly.

Thanks for your help in advance!

Body:
Add hover and transition events:

.fixed-header #header {
  display: flex;
  align-items: center;
  justify-content: center;
  height: 80%;
  box-shadow: 3px 0px 0px rgba(40, 40, 40, 0.8);
  cursor: pointer;
  transition: all ease 1s;
  flex-basis: 35%;
}

.fixed-header #header:hover {
  flex-basis: 75%;
}


问:
Java, convert Ternary operator to IF ELSE
I am sure this repeats something, but yet due to short time I have to ask you straight forward help.
How to convert Ternary (: and ?) operator into IF-ELSE statement in Java?

```<code>public Integer get(Integer index) {
    if (first == null) {
        return null;
    }
    MyNode curNode = first;
    while (index >= 0) {
        if (index == 0) {
            return curNode == null ? null : curNode.getValue();
        } else {
            curNode = curNode == null ? null : curNode.getNext();
            index--;
        }
    }
    return null;
}
</code>```

What I did tried, but it gave me wrong output (this is all about LinkedList) is modifying it to:

```<code>    while (index >= 0) {
        if (index == 0) {
            // pre-modified -> return curNode == null ? null : curNode.getValue();
            if (first == null) {
                return null;
            } else {
                return curNode.getValue();
            }
        } else {
            if (curNode != null) {
                return curNode.getNext().getValue();
                //return null;
            } else {
                return null;
            }
            // pre-modified -> curNode = curNode == null ? null : curNode.getNext();
            // pre-modified -> index--;
        }
    }
</code>```

答:
In addition to that it was necessary also to fix part after else to:

```<code>else {
                if (curNode != null) {
                    curNode = curNode.getNext();
                    index--;
                    //return null;
                } else {
                    curNode = null;
                }
                // pre-modified -> curNode = curNode == null ? null : curNode.getNext();
                // pre-modified -> index--;
            }
</code>```

Question solved.

Body:
I am sure this repeats something, but yet due to short time I have to ask you straight forward help.
How to convert Ternary (: and ?) operator into IF-ELSE statement in Java?

public Integer get(Integer index) {
    if (first == null) {
        return null;
    }
    MyNode curNode = first;
    while (index >= 0) {
        if (index == 0) {
            return curNode == null ? null : curNode.getValue();
        } else {
            curNode = curNode == null ? null : curNode.getNext();
            index--;
        }
    }
    return null;
}

What I did tried, but it gave me wrong output (this is all about LinkedList) is modifying it to:

    while (index >= 0) {
        if (index == 0) {
            // pre-modified -> return curNode == null ? null : curNode.getValue();
            if (first == null) {
                return null;
            } else {
                return curNode.getValue();
            }
        } else {
            if (curNode != null) {
                return curNode.getNext().getValue();
                //return null;
            } else {
                return null;
            }
            // pre-modified -> curNode = curNode == null ? null : curNode.getNext();
            // pre-modified -> index--;
        }
    }

Body:
In addition to that it was necessary also to fix part after else to:

else {
                if (curNode != null) {
                    curNode = curNode.getNext();
                    index--;
                    //return null;
                } else {
                    curNode = null;
                }
                // pre-modified -> curNode = curNode == null ? null : curNode.getNext();
                // pre-modified -> index--;
            }

Question solved.


问:
does (SQL) JOINING on TABLES ALWAYS create Cartesian products of those tables?
does JOINING on TABLES ALWAYS create Cartesian products of those tables ?

if a problem can be solved by sub-query and Joining which should i prefer ?

which one is fast and memory saving ?

All the questions are tightly coupled, so please dont tell to open another thread :(

MySQL 5

答:
Yes, JOINING on tables always create Cartesian products of those tables.

you can't prefer join or sub-query because it depends on your data size

so, you have to try the two ways then you can decide which one is more appropriate
to your query

ContentLicense: CC BY-SA 3.0


问:
how to merge specific cells table data in oracle
I want to condionally concatenate text cells in oracle table according to sequence (SEQ) number attribute. Is it possible to do it? I need your help with the query.

For example I have the following table DATA:

```<code>|-----------------|
|ID|CODE|SEQ|TEXT |
|--|----|---|-----|
|1 |a   |1  |text1|
|1 |a   |2  |text2|
|2 |b   |1  |text3|
|3 |c   |1  |text4|
|4 |d   |1  |text6|
|4 |d   |2  |text7|
|4 |d   |3  |text8|
-------------------
</code>```

What I want to do is to create a new table DATA1 which concatenates TEXT values having the same id and code with concatenated texts in case SEQ > 1. The new table should look like this:

```<code>|-------------------------|
|ID|CODE|TEXT             |
|--|----|-----------------|
|1 |a   |text1 text2      |
|2 |b   |text3            |
|3 |c   |text4            |
|4 |d   |text6 text7 text8|
---------------------------
</code>```

答:
listagg() function might be used with grouping by id and code.

```<code>select id, code,
       listagg(text,' ') within group (order by seq) as text
  from tab
 group by id, code
</code>```

Demo

Body:
I want to condionally concatenate text cells in oracle table according to sequence (SEQ) number attribute. Is it possible to do it? I need your help with the query.

For example I have the following table DATA:

|-----------------|
|ID|CODE|SEQ|TEXT |
|--|----|---|-----|
|1 |a   |1  |text1|
|1 |a   |2  |text2|
|2 |b   |1  |text3|
|3 |c   |1  |text4|
|4 |d   |1  |text6|
|4 |d   |2  |text7|
|4 |d   |3  |text8|
-------------------

What I want to do is to create a new table DATA1 which concatenates TEXT values having the same id and code with concatenated texts in case SEQ > 1. The new table should look like this:

|-------------------------|
|ID|CODE|TEXT             |
|--|----|-----------------|
|1 |a   |text1 text2      |
|2 |b   |text3            |
|3 |c   |text4            |
|4 |d   |text6 text7 text8|
---------------------------

Body:
listagg() function might be used with grouping by id and code.

select id, code,
       listagg(text,' ') within group (order by seq) as text
  from tab
 group by id, code

Demo


问:
How to get R function to return multiple values of parameters
I would like that my function would produce values for different values of one of my parameters (in this case CC), so that I can easily turn this into a dataframe.

Here is the code I am using:

```<code>ub_duration <- function(age, cc = c(12, 18, 24), cc_lag, dur,
                        extended) {
    dur = if (age < 30){
        if (cc < 15) return(150)
        if (cc >= 15 & cc < 24) return(210)
        if (cc >= 24) return(330)
    }
    dur = if (age >= 30 & age < 40){
        if (cc < 15) return(180)
        if (cc >= 15 & cc < 24) return(330)
        if (cc >= 24) return(420)
    }
    dur = if (age >= 50){
        if (cc < 15) return(270)
        if (cc >= 15 & cc < 24) return(480)
        if (cc >= 24) return(540)
    }
    return(dur)
}
</code>```

When I call the function, this is what  get

```<code>> ub_duration(25,c(12, 18, 24),0)
[1] 150
Warning message:
In if (cc < 15) return(150) :
the condition has length > 1 and only the first element will be used
</code>```

答:
The function was written to accept scalar arguments but you can vectorize it like this:

```<code>Vectorize(ub_duration)(25, c(12, 18, 24), dur = 0)
## [1] 150 210 330
</code>```

or use sapply:

```<code>sapply(c(12, 18, 24), ub_duration, age = 25, dur = 0)
## [1] 150 210 330
</code>```

Note that dur, cc_lag and extended are arguments that are not used in the body of the function shown in the question.  Even if dur is passed it is immediately overwritten with NULL in the first if statement if that statement returns. Also, cc_lag and extended are not referenced at all.  Perhaps you intended that the dur argument is the default if the ages are between 40 and 50 since those ages are not otherwise handled but in fact it returns NULL in that case. The function itself needs to be fixed depending on what you want and that was not described in the question.

Rewriting Function

1) Here is an attempt at rewriting it.  First create an m matrix with the cutoff values.  The rows correspond to cc and the columns to age.  Ensure that cc and age are the same length by putting them into a data frame and extracting them back out.  Then compute the indexes into m for cc and age. Note that it is possible that an age does not correspond to any index so in that case set its index to NA. If that is the case return dur and otherwise return the value looked up in m.

```<code>ub_duration2 <- function(age, cc, dur = 0) {
  m <- matrix(c(150, 210, 310,
    180, 330, 420,
    270, 400, 540), 3, dimnames = list(cc = 1:3, age = 1:3))
  d <- data.frame(age, cc)
  age <- d$age
  cc <- d$cc
  cc.ix <- 1 + (cc >= 15) + (cc >= 24)
  age.ix <- 1 * (age < 30) + 2 * (age >= 30 & age < 40) + 3 * (age > 50)
  age.ix[age.ix == 0] <- NA
  ifelse(is.na(age.ix), dur, m[cbind(cc.ix, age.ix)])
}
ub_duration2(25,c(12, 18, 24))
## [1] 150 210 310
</code>```

2) This attempt is closer in spirit to what you have in the question.  It works on scalars and then we use Vectorize to vectorize it.  Although tedious it may be preferred in terms of simplicity.

```<code>ub_duration_scalar <- function(age, cc, dur = 0) {
    if (age < 30) {
        if (cc < 15) 150
        else if (cc < 24) 210
        else 330
    } else if (age < 40) {
        if (cc < 15) 180
        else if (cc < 24) 330
        else 420
    } else if (age >= 50) {
        if (cc < 15) 270
        else if (cc < 24) 480
        else 540
    } else dur
}
ub_duration3 <- Vectorize(ub_duration_scalar)

ub_duration3(25,c(12, 18, 24))
## [1] 150 210 310
</code>```

Body:
I would like that my function would produce values for different values of one of my parameters (in this case CC), so that I can easily turn this into a dataframe.

Here is the code I am using:

ub_duration <- function(age, cc = c(12, 18, 24), cc_lag, dur,
                        extended) {
    dur = if (age < 30){
        if (cc < 15) return(150)
        if (cc >= 15 & cc < 24) return(210)
        if (cc >= 24) return(330)
    }
    dur = if (age >= 30 & age < 40){
        if (cc < 15) return(180)
        if (cc >= 15 & cc < 24) return(330)
        if (cc >= 24) return(420)
    }
    dur = if (age >= 50){
        if (cc < 15) return(270)
        if (cc >= 15 & cc < 24) return(480)
        if (cc >= 24) return(540)
    }
    return(dur)
}

When I call the function, this is what  get

> ub_duration(25,c(12, 18, 24),0)
[1] 150
Warning message:
In if (cc < 15) return(150) :
the condition has length > 1 and only the first element will be used

Body:
The function was written to accept scalar arguments but you can vectorize it like this:

Vectorize(ub_duration)(25, c(12, 18, 24), dur = 0)
## [1] 150 210 330

or use sapply:

sapply(c(12, 18, 24), ub_duration, age = 25, dur = 0)
## [1] 150 210 330

Note that dur, cc_lag and extended are arguments that are not used in the body of the function shown in the question.  Even if dur is passed it is immediately overwritten with NULL in the first if statement if that statement returns. Also, cc_lag and extended are not referenced at all.  Perhaps you intended that the dur argument is the default if the ages are between 40 and 50 since those ages are not otherwise handled but in fact it returns NULL in that case. The function itself needs to be fixed depending on what you want and that was not described in the question.

Rewriting Function

1) Here is an attempt at rewriting it.  First create an m matrix with the cutoff values.  The rows correspond to cc and the columns to age.  Ensure that cc and age are the same length by putting them into a data frame and extracting them back out.  Then compute the indexes into m for cc and age. Note that it is possible that an age does not correspond to any index so in that case set its index to NA. If that is the case return dur and otherwise return the value looked up in m.

ub_duration2 <- function(age, cc, dur = 0) {
  m <- matrix(c(150, 210, 310,
    180, 330, 420,
    270, 400, 540), 3, dimnames = list(cc = 1:3, age = 1:3))
  d <- data.frame(age, cc)
  age <- d$age
  cc <- d$cc
  cc.ix <- 1 + (cc >= 15) + (cc >= 24)
  age.ix <- 1 * (age < 30) + 2 * (age >= 30 & age < 40) + 3 * (age > 50)
  age.ix[age.ix == 0] <- NA
  ifelse(is.na(age.ix), dur, m[cbind(cc.ix, age.ix)])
}
ub_duration2(25,c(12, 18, 24))
## [1] 150 210 310

2) This attempt is closer in spirit to what you have in the question.  It works on scalars and then we use Vectorize to vectorize it.  Although tedious it may be preferred in terms of simplicity.

ub_duration_scalar <- function(age, cc, dur = 0) {
    if (age < 30) {
        if (cc < 15) 150
        else if (cc < 24) 210
        else 330
    } else if (age < 40) {
        if (cc < 15) 180
        else if (cc < 24) 330
        else 420
    } else if (age >= 50) {
        if (cc < 15) 270
        else if (cc < 24) 480
        else 540
    } else dur
}
ub_duration3 <- Vectorize(ub_duration_scalar)

ub_duration3(25,c(12, 18, 24))
## [1] 150 210 310


问:
Security for ASP.NET application
I am developing a .net based application which is for a financial institution and it has multiple roles so I am not using built in ROLE PROVIDER.

Now what i want is that when create user i just assign role and when user logs in with the assigned role he/she cannot open any form on which he/she has no rights.

How to come up with a role based security system for my application ? I would appreciate if someone can help me and guide me to come up with a strong and secure application.

Thanks

答:
I think you need to take a look at the Membership API.

This blog post from Scott Guthrie has links to several resources to help you get started.

http://weblogs.asp.net/scottgu/archive/2006/02/24/asp.net-2.0-membership_2c00_-roles_2c00_-forms-authentication_2c00_-and-security-resources-.aspx

Title: Security for ASP.NET application


问:
Output HTML depending on the current time of user
I would like to do the following:

if time is between 7am-12pm (mon-sat) then output html code else output something else.

I currently have tried: (ignore the time in the code, this was just for testing purposes - I still want it to do be done for 7am-12pm)

```<code><script>
            var today = new Date()
var curHr = today.getHours()

if (curHr < 12) {
  phoneText .innerHTML="<div class='col-sm-6 col-md-3'><div class='support-box'><div class='icon green'><i class='fas fa-comments'></i></div><div class='details-holder'><div class='title'>Live Chat</div><a href='javascript:$zopim.livechat.window.show();' style='color:white;'>Start a live chat</a></div></div>";
} else if (curHr < 18) {
  phoneText .innerHTML="<div class='col-sm-6 col-md-3'><div class='support-box'><div class='icon green'><i class='fas fa-comments'></i></div><div class='details-holder'><div class='title'>Live Chat</div><a href='javascript:$zopim.livechat.window.show();' style='color:white;'>Start a live chat</a></div></div>";
} else {
  phoneText .innerHTML="<div class='col-sm-6 col-md-3'><div class='support-box'><div class='icon green'><i class='fas fa-comments'></i></div><div class='details-holder'><div class='title'>Live Chat</div><a href='javascript:$zopim.livechat.window.show();' style='color:white;'>Start a live chat</a></div></div>";
}</script>
</code>```

I then have

答: In your if you should create a var for the target in html var outpout = document.getElementById("phone") and use it to outpout.innerHTML. But you can't insert here an entire div. So you could create all the div in your html for each of the cases and put them in display : none to hide them in your CSS. Then you take them in js like var divOne = document.getElementById = "div_hour_first_case" and then divOne.style.display = "flex" in your if to show the expected div.

Body:
I would like to do the following:

if time is between 7am-12pm (mon-sat) then output html code else output something else.

I currently have tried: (ignore the time in the code, this was just for testing purposes - I still want it to do be done for 7am-12pm)

I then have


问:
Changing the direction of a Flexbox HTML CSS
I have a flexbox with 4 images. Below is an image of what it looks like now. Currently, when I make the width smaller, you don't see the 4th image.

I want the flexbox to transform into this layout below. So that when the width is at a certain px, it will change.

I'm having trouble accomplishing this. I tried to use flex-direction: column; but this makes the whole list vertical and I don't want that.

div{
  display: flex;
  flex-direction: wrap;
  border-style:solid;
  padding-top: 2em;
}

figcaption[certification=yes]::before {
            font-size: 0.75em;
            /*Check mark*/
            content: "\2705";
            display: inline-block;
            color:red;
}

figcaption[certification=yes]::after {
            font-size: 0.75em;
            /*Dispaly li*/
            content: li;
            display: inline-block;
            color:red;
}

figure{
    padding:2.5em;
    margin-left: 3em;
    margin-bottom:2em;
}

@media screen and (max-width: 1185px)
{
    // I want the 4th image to below the 1st image once you get to the width of 1185px
    div{
        flex-direction: column;
    }

}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div>
        <figure>
            <img src="images/ACE.png" height="150em">
            <figcaption data-title="Multimedia and the World Wide Web" certification="yes">Nighthawk</figcaption>
        </figure>

        <figure>
            <img src="images/NSCA.png" height="150em">
            <figcaption data-title="Multimedia and the World Wide Web" certification="yes">Nighthawk</figcaption>
        </figure>

        <figure>
            <img src="images/USA.png" height="150em">
            <figcaption data-title="Multimedia and the World Wide Web" certification="yes">Nighthawk</figcaption>
        </figure>

        <figure>
            <img src="images/Functional-movement.jpg" height="150em">
            <figcaption data-title="Multimedia and the World Wide Web" certification="yes">Nighthawk</figcaption>
        </figure>
    </div></code>```

答:
You have flex-direction:wrap;

Try instead: flex-wrap:wrap;

Also, instead of using em units (or px or rem), use instead vw and vh "view units". These units represent 1% of the current screen width and height (and you can use fractions of units, so they become infinitely more granular - e.g. 1.25vw), so the margin/borders/padding/etc will also grow/shrink with the screen size. How do view units differ from percents? Percents relate to the percentages of the parent div size, whereas view units are percentages of the current viewport size.

References:

https://yoksel.github.io/flex-cheatsheet/#flex-wrap

https://www.smashingmagazine.com/2016/05/fluid-typography/

Demo:

div{display:flex;flex-wrap:wrap;border-style:solid;padding-top:2em;}

figcaption[certification=yes]::before{font-size:0.75em;/*Check mark*/content:"\2705";display:inline-block;color:red;}
figcaption[certification=yes]::after{font-size:0.75em;/*Dispaly li*/content:li;display:inline-block;color:red;}
figure{padding:2.5em;margin-left:3em;margin-bottom:2em;}

@media screen and (max-width:1185px)
{// I want the 4th image to below the 1st image once you get to the width of 1185px
    div{flex-wrap:wrap;}
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div>
        <figure>
            <img src="images/ACE.png" height="150em">
            <figcaption data-title="Multimedia and the World Wide Web" certification="yes">Nighthawk</figcaption>
        </figure>

        <figure>
            <img src="images/NSCA.png" height="150em">
            <figcaption data-title="Multimedia and the World Wide Web" certification="yes">Nighthawk</figcaption>
        </figure>

        <figure>
            <img src="images/USA.png" height="150em">
            <figcaption data-title="Multimedia and the World Wide Web" certification="yes">Nighthawk</figcaption>
        </figure>

        <figure>
            <img src="images/Functional-movement.jpg" height="150em">
            <figcaption data-title="Multimedia and the World Wide Web" certification="yes">Nighthawk</figcaption>
        </figure>
    </div></code>```

Body:
I have a flexbox with 4 images. Below is an image of what it looks like now. Currently, when I make the width smaller, you don't see the 4th image.

I want the flexbox to transform into this layout below. So that when the width is at a certain px, it will change.

I'm having trouble accomplishing this. I tried to use flex-direction: column; but this makes the whole list vertical and I don't want that.

div{
  display: flex;
  flex-direction: wrap;
  border-style:solid;
  padding-top: 2em;
}

figcaption[certification=yes]::before {
            font-size: 0.75em;
            /*Check mark*/
            content: "\2705";
            display: inline-block;
            color:red;
}

figcaption[certification=yes]::after {
            font-size: 0.75em;
            /*Dispaly li*/
            content: li;
            display: inline-block;
            color:red;
}

figure{
    padding:2.5em;
    margin-left: 3em;
    margin-bottom:2em;
}

@media screen and (max-width: 1185px)
{
    // I want the 4th image to below the 1st image once you get to the width of 1185px
    div{
        flex-direction: column;
    }

}

Nighthawk

Nighthawk

Nighthawk

Nighthawk

Body:
You have flex-direction:wrap;

Try instead: flex-wrap:wrap;

Also, instead of using em units (or px or rem), use instead vw and vh "view units". These units represent 1% of the current screen width and height (and you can use fractions of units, so they become infinitely more granular - e.g. 1.25vw), so the margin/borders/padding/etc will also grow/shrink with the screen size. How do view units differ from percents? Percents relate to the percentages of the parent div size, whereas view units are percentages of the current viewport size.

References:

https://yoksel.github.io/flex-cheatsheet/#flex-wrap

https://www.smashingmagazine.com/2016/05/fluid-typography/

Demo:

div{display:flex;flex-wrap:wrap;border-style:solid;padding-top:2em;}

figcaption[certification=yes]::before{font-size:0.75em;/*Check mark*/content:"\2705";display:inline-block;color:red;}
figcaption[certification=yes]::after{font-size:0.75em;/*Dispaly li*/content:li;display:inline-block;color:red;}
figure{padding:2.5em;margin-left:3em;margin-bottom:2em;}

@media screen and (max-width:1185px)
{// I want the 4th image to below the 1st image once you get to the width of 1185px
    div{flex-wrap:wrap;}
}

<div>
        <figure>
            <img src="images/ACE.png" height="150em">
            <figcaption data-title="Multimedia and the World Wide Web" certification="yes">Nighthawk</figcaption>
        </figure>

        <figure>
            <img src="images/NSCA.png" height="150em">
            <figcaption data-title="Multimedia and the World Wide Web" certification="yes">Nighthawk</figcaption>
        </figure>

        <figure>
            <img src="images/USA.png" height="150em">
            <figcaption data-title="Multimedia and the World Wide Web" certification="yes">Nighthawk</figcaption>
        </figure>

        <figure>
            <img src="images/Functional-movement.jpg" height="150em">
            <figcaption data-title="Multimedia and the World Wide Web" certification="yes">Nighthawk</figcaption>
        </figure>
    </div>


问:
NativeScript & Angular Code Sharing + Lazy Loaded Module Paths
I have a NativeScript/Angular application that uses code sharing.

To make my project more organized, I have created a core folder that contains a sub-folder for routing:

Routes are defined in app.common.ts:

```<code>export const appRoutes: Routes = [
  { path: '', redirectTo: '/products', pathMatch: 'full' },
  {
    path: 'products',
    loadChildren: '../products/products.module#ProductsModule'
  }
]
</code>```

Of particular interest is the module path shown in the following property:

```<code>loadChildren: '../products/products.module#ProductsModule'
</code>```

Serving this in the browser using ng serve -o works fine.

Bundling this to run on Android using tns run android --bundle doesn't work as it can't find the module.

If I change the path to ~/app/products/products.module#ProductsModule, the Android app then runs, but the web application can't find the module.

If I then leave the file watcher running for the Android build and change the path back to ../products/products.module#ProductsModule, both Android and web work fine.

I don't want to move my routing files back to the src folder. I am also reluctant to include any hacks such as platform-driven path string mangling.

If you have any explanations as to why this is happening and/or a robust fix that isn't 'hacky', I'd be keen to hear it.

答:
The problem was stemming from some quirks regarding the file watchers. When I change the path to the following, both platforms work fine:

../../products/products.module#ProductsModule

The reason I didn't select this path from the outset is because I used ~/app/products/products.module#ProductsModule to begin with and edited this to get the web build to work while the Android file watcher was still running.

With both the Android and web file watchers terminated and the path adjusted to the one provided above, they both work.

Body:
I have a NativeScript/Angular application that uses code sharing.

To make my project more organized, I have created a core folder that contains a sub-folder for routing:

Routes are defined in app.common.ts:

export const appRoutes: Routes = [
  { path: '', redirectTo: '/products', pathMatch: 'full' },
  {
    path: 'products',
    loadChildren: '../products/products.module#ProductsModule'
  }
]

Of particular interest is the module path shown in the following property:

loadChildren: '../products/products.module#ProductsModule'

Serving this in the browser using ng serve -o works fine.

Bundling this to run on Android using tns run android --bundle doesn't work as it can't find the module.

If I change the path to ~/app/products/products.module#ProductsModule, the Android app then runs, but the web application can't find the module.

If I then leave the file watcher running for the Android build and change the path back to ../products/products.module#ProductsModule, both Android and web work fine.

I don't want to move my routing files back to the src folder. I am also reluctant to include any hacks such as platform-driven path string mangling.

If you have any explanations as to why this is happening and/or a robust fix that isn't 'hacky', I'd be keen to hear it.


问:
React Native bottom tab is hidden on iPhone X
The bottom navigation bar is partially buried at the bottom of the screen in iPhone X and iPhone X Max. It's all fine in other iPhones.

I created the navigation tab using this method:

https://reactnavigation.org/docs/en/material-bottom-tab-navigator.html

```<code>const TabNavigator = createBottomTabNavigator({
  CPM: { screen: App1 },
  CPV: { screen: App2 },
  CPC: { screen: App3 },
},

{tabBarOptions: {
  labelStyle: {
  fontSize: 18,
  fontWeight: 'bold',
  paddingBottom: 6,
  paddingTop: 3,
},
style: {
  backgroundColor: 'lightgrey',
  height: '6%',
  borderTopWidth: 1,
  borderTopColor: 'grey',
},

}
},
);
</code>```

Expected - The bottom navigation bar will look the same through out iOS devices.
Actual - In iPhone X and X Max, the navigation bar is buried at the bottom of the screen.

答:
It looks like iPhone X doesn't like it when the tab has styling options that mess with the vertical heights. </p>

<p>I solved it by commenting out the "height: " attribute within the styling section.
See below the updated settings:   </p>

```<code>{tabBarOptions: {
  labelStyle: {
  fontSize: 18,
  fontWeight: 'bold',
  paddingBottom: 6,
  paddingTop: 3,
},
style: {
  backgroundColor: 'lightgrey',
  //height: '6%',
  borderTopWidth: 1,
  borderTopColor: 'grey',
},

}
},
</code>```

Body:
The bottom navigation bar is partially buried at the bottom of the screen in iPhone X and iPhone X Max. It's all fine in other iPhones.

I created the navigation tab using this method:

https://reactnavigation.org/docs/en/material-bottom-tab-navigator.html

const TabNavigator = createBottomTabNavigator({
  CPM: { screen: App1 },
  CPV: { screen: App2 },
  CPC: { screen: App3 },
},

{tabBarOptions: {
  labelStyle: {
  fontSize: 18,
  fontWeight: 'bold',
  paddingBottom: 6,
  paddingTop: 3,
},
style: {
  backgroundColor: 'lightgrey',
  height: '6%',
  borderTopWidth: 1,
  borderTopColor: 'grey',
},

}
},
);

Expected - The bottom navigation bar will look the same through out iOS devices.
Actual - In iPhone X and X Max, the navigation bar is buried at the bottom of the screen.

Body:
It looks like iPhone X doesn't like it when the tab has styling options that mess with the vertical heights.

I solved it by commenting out the "height: " attribute within the styling section.
See below the updated settings:

{tabBarOptions: {
  labelStyle: {
  fontSize: 18,
  fontWeight: 'bold',
  paddingBottom: 6,
  paddingTop: 3,
},
style: {
  backgroundColor: 'lightgrey',
  //height: '6%',
  borderTopWidth: 1,
  borderTopColor: 'grey',
},

}
},


问:
Querying sequential data with date/time and text values in the same column
My data is single field, and include date, time, hour but also include data that i need.

Already query 2 keyword but the data still big and too many empty second keyword

```<code>SELECT Field1
FROM TABLE1
WHERE Field1 Like '*EVENT_1' Or
      Field1 Like '*DATETIME'
</code>```

I expect the output is:

Thanks in advance

答:
Start by importing your log data into Access. While doing so, tell Access to create its own Primary Key, which will be an AutoNumber:

[impLogData]

ID  Field1
--  ------------------
 1    May/01/2019 7:00
 2  EVENT_0
 3  EVENT_1 - val:10
 4  EVENT_2
 5  EVENT_3
 6  EVENT_4
 7  EVENT_5
 8  EVENT_6
 9    May/01/2019 8:00
10  EVENT_2
11  EVENT_3
12  EVENT_12
13  EVENT_13
14  EVENT_14
15    May/01/2019 9:00
16  EVENT_0
17  EVENT_1 - val:15
18  EVENT_2
```

<p>Create a [tblLogTime] table as</p>

<p>ID - Long Integer, Primary Key<br>
logTime - Date/Time  </p>

<p>and populate it with</p>

<pre class="lang-sql prettyprint-override"><code>INSERT INTO tblLogTime ( ID, logTime )
SELECT impLogData.ID, CDate([Field1]) AS Expr1
FROM impLogData
WHERE (((IsDate([Field1]))=True));
</code>```

producing

[tblLogTime]

ID  logTime
--  -------------------
 1  2019-05-01 07:00:00
 9  2019-05-01 08:00:00
15  2019-05-01 09:00:00
```

<p>Then create a [tblLogEvent] table as</p>

<p>logTime - Date/Time<br>
logEvent - Text(255)  </p>

<p>and populate it with</p>

<pre class="lang-sql prettyprint-override"><code>INSERT INTO tblLogEvent ( logTime, logEvent )
SELECT DMax("logTime","tblLogTime","ID < " & [impLogData].[ID]) AS Expr1, impLogData.Field1
FROM impLogData LEFT JOIN tblLogTime ON impLogData.ID = tblLogTime.ID
WHERE (((tblLogTime.ID) Is Null));
</code>```

producing

[tblLogEvent]

logTime              logEvent
-------------------  ----------------
2019-05-01 07:00:00  EVENT_0
2019-05-01 07:00:00  EVENT_1 - val:10
2019-05-01 07:00:00  EVENT_2
2019-05-01 07:00:00  EVENT_3
2019-05-01 07:00:00  EVENT_4
2019-05-01 07:00:00  EVENT_5
2019-05-01 07:00:00  EVENT_6
2019-05-01 08:00:00  EVENT_2
2019-05-01 08:00:00  EVENT_3
2019-05-01 08:00:00  EVENT_12
2019-05-01 08:00:00  EVENT_13
2019-05-01 08:00:00  EVENT_14
2019-05-01 09:00:00  EVENT_0
2019-05-01 09:00:00  EVENT_1 - val:15
2019-05-01 09:00:00  EVENT_2
```

<p>You can then select EVENT_1 rows using</p>

<pre class="lang-sql prettyprint-override"><code>SELECT tblLogEvent.logTime, tblLogEvent.logEvent
FROM tblLogEvent
WHERE (((tblLogEvent.logEvent) Like "EVENT_1 *"))
ORDER BY tblLogEvent.logTime;
</code>```

producing

logTime              logEvent
-------------------  ----------------
2019-05-01 07:00:00  EVENT_1 - val:10
2019-05-01 09:00:00  EVENT_1 - val:15
```

Body:
My data is single field, and include date, time, hour but also include data that i need.

Already query 2 keyword but the data still big and too many empty second keyword

SELECT Field1
FROM TABLE1
WHERE Field1 Like '*EVENT_1' Or
      Field1 Like '*DATETIME'

I expect the output is:

Thanks in advance

Body:
Start by importing your log data into Access. While doing so, tell Access to create its own Primary Key, which will be an AutoNumber:

[impLogData]

ID  Field1
--  ------------------
 1    May/01/2019 7:00
 2  EVENT_0
 3  EVENT_1 - val:10
 4  EVENT_2
 5  EVENT_3
 6  EVENT_4
 7  EVENT_5
 8  EVENT_6
 9    May/01/2019 8:00
10  EVENT_2
11  EVENT_3
12  EVENT_12
13  EVENT_13
14  EVENT_14
15    May/01/2019 9:00
16  EVENT_0
17  EVENT_1 - val:15
18  EVENT_2

Create a [tblLogTime] table as

ID - Long Integer, Primary Key

logTime - Date/Time

and populate it with

INSERT INTO tblLogTime ( ID, logTime )
SELECT impLogData.ID, CDate([Field1]) AS Expr1
FROM impLogData
WHERE (((IsDate([Field1]))=True));

producing

[tblLogTime]

ID  logTime
--  -------------------
 1  2019-05-01 07:00:00
 9  2019-05-01 08:00:00
15  2019-05-01 09:00:00

Then create a [tblLogEvent] table as

logTime - Date/Time

logEvent - Text(255)

and populate it with

INSERT INTO tblLogEvent ( logTime, logEvent )
SELECT DMax("logTime","tblLogTime","ID < " & [impLogData].[ID]) AS Expr1, impLogData.Field1
FROM impLogData LEFT JOIN tblLogTime ON impLogData.ID = tblLogTime.ID
WHERE (((tblLogTime.ID) Is Null));

producing

[tblLogEvent]

logTime              logEvent
-------------------  ----------------
2019-05-01 07:00:00  EVENT_0
2019-05-01 07:00:00  EVENT_1 - val:10
2019-05-01 07:00:00  EVENT_2
2019-05-01 07:00:00  EVENT_3
2019-05-01 07:00:00  EVENT_4
2019-05-01 07:00:00  EVENT_5
2019-05-01 07:00:00  EVENT_6
2019-05-01 08:00:00  EVENT_2
2019-05-01 08:00:00  EVENT_3
2019-05-01 08:00:00  EVENT_12
2019-05-01 08:00:00  EVENT_13
2019-05-01 08:00:00  EVENT_14
2019-05-01 09:00:00  EVENT_0
2019-05-01 09:00:00  EVENT_1 - val:15
2019-05-01 09:00:00  EVENT_2

You can then select EVENT_1 rows using

SELECT tblLogEvent.logTime, tblLogEvent.logEvent
FROM tblLogEvent
WHERE (((tblLogEvent.logEvent) Like "EVENT_1 *"))
ORDER BY tblLogEvent.logTime;

producing

logTime              logEvent
-------------------  ----------------
2019-05-01 07:00:00  EVENT_1 - val:10
2019-05-01 09:00:00  EVENT_1 - val:15


问:
Reuse cells of a scroll view
I am using a scrollview to display various items in a horizontal fashion.

How can I "reuse the cells" to conserve memory:

Edit:  Apologies for not being clear.  I plan to place a few labels and and another ImageView inside each ImageView so I am keen to reuse this each time instead of instantiating new items each time.  e.g. change the image's and update the labels instead of re-create it.

```<code>// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad
{
    [super viewDidLoad];

    // load all the images from our bundle and add them to the scroll view
//  NSUInteger i;
    for (int i = 0; i <= 150; i++)
    {
        NSString *imageName = @"tempImage.jpg";
        UIImage *image = [UIImage imageNamed:imageName];
        UIImageView *imageView = [[UIImageView alloc] initWithImage:image];

        // setup each frame to a default height and width, it will be properly placed when we call "updateScrollList"
        CGRect rect = imageView.frame;
        rect.size.height = kScrollObjHeight;
        rect.size.width = kScrollObjWidth;
        imageView.frame = rect;
        imageView.tag = i;  // tag our images for later use when we place them in serial fashion
        [self.bestSellScrollView addSubview:imageView];
        [imageView release];
    }

    [self layoutScrollImages];  // now place the photos in serial layout within the scrollview
}

- (void)layoutScrollImages
{
    UIImageView *view = nil;
    NSArray *subviews = [self.bestSellScrollView subviews];

    // reposition all image subviews in a horizontal serial fashion
    CGFloat curXLoc = 0;
    for (view in subviews)
    {
        if ([view isKindOfClass:[UIImageView class]] && view.tag > 0)
        {
            CGRect frame = view.frame;
            frame.origin = CGPointMake(curXLoc, 0);
            view.frame = frame;

            curXLoc += (kScrollObjWidth);
        }
    }

    // set the content size so it can be scrollable
    [self.bestSellScrollView setContentSize:CGSizeMake((150 * kScrollObjWidth),
                                                       [self.bestSellScrollView bounds].size.height)];
}
</code>```

答:
I am assuming that you intend to reuse the UIImageView cell instances in the UIScrollView.
I hope that Daniel Tull's implementation may be helpful--

https://github.com/danielctull/DTGridView

You may like to see an Apple sample code on UIScrollView as well(I don't have the link, but u can easily find it on the web)

Thanks!
Ishank

Title: Reuse cells of a scroll view

Body:
I am using a scrollview to display various items in a horizontal fashion.

How can I "reuse the cells" to conserve memory:

Edit:  Apologies for not being clear.  I plan to place a few labels and and another ImageView inside each ImageView so I am keen to reuse this each time instead of instantiating new items each time.  e.g. change the image's and update the labels instead of re-create it.

// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad
{
    [super viewDidLoad];

    // load all the images from our bundle and add them to the scroll view
//  NSUInteger i;
    for (int i = 0; i <= 150; i++)
    {
        NSString *imageName = @"tempImage.jpg";
        UIImage *image = [UIImage imageNamed:imageName];
        UIImageView *imageView = [[UIImageView alloc] initWithImage:image];

        // setup each frame to a default height and width, it will be properly placed when we call "updateScrollList"
        CGRect rect = imageView.frame;
        rect.size.height = kScrollObjHeight;
        rect.size.width = kScrollObjWidth;
        imageView.frame = rect;
        imageView.tag = i;  // tag our images for later use when we place them in serial fashion
        [self.bestSellScrollView addSubview:imageView];
        [imageView release];
    }

    [self layoutScrollImages];  // now place the photos in serial layout within the scrollview
}

- (void)layoutScrollImages
{
    UIImageView *view = nil;
    NSArray *subviews = [self.bestSellScrollView subviews];

    // reposition all image subviews in a horizontal serial fashion
    CGFloat curXLoc = 0;
    for (view in subviews)
    {
        if ([view isKindOfClass:[UIImageView class]] && view.tag > 0)
        {
            CGRect frame = view.frame;
            frame.origin = CGPointMake(curXLoc, 0);
            view.frame = frame;

            curXLoc += (kScrollObjWidth);
        }
    }

    // set the content size so it can be scrollable
    [self.bestSellScrollView setContentSize:CGSizeMake((150 * kScrollObjWidth),
                                                       [self.bestSellScrollView bounds].size.height)];
}


问:
how can I stop the execution if the function is in the error case?
I'm building a web app that plans for the user's week so it takes : from,to,text inputs as you see in the screenshot below:

so in order to avoid duplicated from or to inputs I created two arrays for the from and for the to input called fromA and toA, everything is going Ok except that I'm having some problems with the id  and that's because when the user enters a duplicated value an error shows up and and the addItem method returns as you see in the screenshot below

and here is my code:

JavaScript:

```<code>var UIController = (function(interCtrl) {

  var DOMstrings = {
    inputDay: ".optionList",
    inputTimeF: ".inputTime",
    inputTimeT: ".inputTime2",
    inputText: ".inputText",
    goingToCkecked: ".checkboxx",
    inputBtn: ".add__btn",
    planContainer: ".container",
    errorCase: ".error-case",
    optionList: ".optionList",
    optionListId: "#optionList",
    errorDes: "error-description",
  };

  return {
    getInput: function() {
      return {
        inputDay: document.querySelector(DOMstrings.inputDay).value,
        inputTimeF: document.querySelector(DOMstrings.inputTimeF).value,
        inputTimeT: document.querySelector(DOMstrings.inputTimeT).value,
        inputText: document.querySelector(DOMstrings.inputText).value,
        goingToCkecked: document.querySelector(DOMstrings.goingToCkecked).checked,

      };
    },
    getDOMstrings: function() {
      return DOMstrings;
    },
    addPlanList: function(obj, day) {

      var html, element, newHtml;
      //1.CREATE HTML WITH A PLACEHOLDER TEXT
      if (day === "Monday" || day === "Tuesday" || day === "Wednesday" || day === "Thursday" || day === "Friday" || day === "Saturday" || day === "Sunday") {
        html = '<h1 class="day"> %day%</h1><div class="plan-%ID%" style="text-align:center"><i class="fas fa-calendar-check check"></i><span class=""><span class="from">FROM: </span><span>%timef%</span><span class="to"> TO: </span><span class="">%timet%</span> <span class="to-do">I\'m going to %text%</span><i class="fas fa-times-circle"></i><span class="line"></span></span></span></div>';

        //2.REPLACE THE PLACEHOLDER TEXT WITH SOME ACTUAL DATA

        if (obj.id === 0) {
          newHtml = html.replace('%day%', day);
          newHtml = newHtml.replace('%ID%', obj.id);
          newHtml = newHtml.replace('%timef%', obj.from);
          newHtml = newHtml.replace('%timet%', obj.to);
          if (obj.goingToCkecked === false) {
            newHtml = newHtml.replace('I\'m going to %text%', obj.text);
          } else {
            newHtml = newHtml.replace('%text%', obj.text);
          }
        } else {
          newHtml = html.replace('%day%', "");
          newHtml = newHtml.replace('%ID%', obj.id);
          newHtml = newHtml.replace('%timef%', obj.from);
          newHtml = newHtml.replace('%timet%', obj.to);

          //3.add or remove the "I'm going to" prefix
          if (obj.goingToCkecked === false) {
            newHtml = newHtml.replace('I\'m going to %text%', obj.text);
          } else {
            newHtml = newHtml.replace('%text%', obj.text);
          }
        }

        //4.insert the element in the DOM
        element = DOMstrings.planContainer;

        document.querySelector(element).insertAdjacentHTML('beforeend', newHtml);

      }
    }
  };

})(internalController); //END OF THE UICONTROLLER MODULE

var internalController = (function(UICtrl) {

  var Plan = function(id, from, to, text, goingToCkecked) {
    this.id = id;
    this.from = from;
    this.to = to;
    this.text = text;
    this.goingToCkecked = goingToCkecked;
  };

  var data = {
    Monday: [],
    Tuesday: [],
    Wednesday: [],
    Thursday: [],
    Friday: [],
    Saturday: [],
    Sunday: []
  };

  var toA = [];
  var fromA = [];
  var errorCase = false;

  var Dom = UICtrl.getDOMstrings();

  function removeError(x, y) {
    document.querySelector(x).style.visibility = "hidden";
    document.querySelector(y).classList.remove("error-red");
  }

  function errorVisible(x, y) {
    document.querySelector(x).style.visibility = "visible";
    document.querySelector(y).classList.add("error-red");

  }

  return {

    addItem: function(day, from, to, text, goingToCkecked) {
      var newPlan, ID;

      //2.change the input color to white when the user pick a DAY (in the error case)
      document.querySelector(Dom.optionListId).addEventListener("change", function() {
        removeError(Dom.errorCase, Dom.optionList);
      });

      //1.THE ERROR MESSAGE  SHOWS UP IF THE DAY IS NOT PICKED RIGHT
      if (day === 'pick the day') {
        errorVisible(Dom.errorCase, Dom.optionList);
        document.getElementsByClassName(Dom.errorDes)[0].innerHTML = "you should pick a day";
      }

      //4.REMOVE THE ERROR MESSAGE AS WELL AS THE RED COLOR FROM THE "FROM" INPUT
      document.querySelector(Dom.inputTimeF).addEventListener("keypress", function() {
        removeError(Dom.errorCase, Dom.inputTimeF);
      });

      //3.IF THE FROM INPUT IS EMPTY THE ERROR SHOWS UP  AND BLOCK THE APP AT THAT POINT
      if (from === "") {
        errorVisible(Dom.errorCase, Dom.inputTimeF);
        document.getElementsByClassName(Dom.errorDes)[0].innerHTML = "you should fill the \" from \" input";
        errorCase = true;
        return;
      }

      //refuse dupicated from values
      if (fromA.includes(from) === false && to != "" && text != "" && errorCase === false && day != "pick the day") {

        fromA.push(from);
        console.log("from array:")
        console.log(fromA);
        errorCase=false;

      } else if (fromA.includes(from) === true) {
        errorVisible(Dom.errorCase, Dom.inputTimeF);
        document.getElementsByClassName(Dom.errorDes)[0].innerHTML = "the \" from \" time is already chosen";
        errorCase = true;
        return;
      }

      //6.REMOVE THE ERROR MESSAGE AS WELL AS THE RED COLOR FROM THE "TO" INPUT
      document.querySelector(Dom.inputTimeT).addEventListener("keypress", function() {
        removeError(Dom.errorCase, Dom.inputTimeT);
      });

      //5.IF THE TO INPUT IS EMPTY THE ERROR SHOWS UP

      if (to === "") {
        errorVisible(Dom.errorCase, Dom.inputTimeT);
        document.getElementsByClassName(Dom.errorDes)[0].innerHTML = "you should fill the \" to \" input";
        return;
      }

      if (toA.includes(to) === false && from != "" && text != "" && errorCase === false && day !="pick the day") {

        toA.push(to);
        console.log("to array:");
        console.log(toA)
        errorCase=false;

      } else if (toA.includes(to) === true) {
        errorVisible(Dom.errorCase, Dom.inputTimeT);
        document.getElementsByClassName(Dom.errorDes)[0].innerHTML = "the \" to \" time is already chosen";
        return;
      }

      //7.REMOVE THE ERROR MESSAGE AS WELL AS THE RED COLOR FROM THE "TEXT" INPUT

      document.querySelector(Dom.inputText).addEventListener("keypress", function() {
        removeError(Dom.errorCase, Dom.inputText);
      });

      if (text === "") {
        errorVisible(Dom.errorCase, Dom.inputText);
        document.getElementsByClassName(Dom.errorDes)[0].innerHTML = "you should fill the \" text \" input";
        return;
      }

      //CREATE NEW ID
      if (data[day].length > 0) {
        ID = data[day][data[day].length - 1].id + 1;
      } else {
        ID = 0;
      }

      //CREATE NEW PLAN BASED ON THE PICKED DAY

      if (day === "Monday" || day === "Tuesday" || day === "Wednesday" || day === "Thursday" || day === "Friday" || day === "Saturday" || day === "Sunday") {
        newPlan = new Plan(ID, from, to, text, goingToCkecked);
      }

      //PUSH IT INTO OUR DATA STRUCTURE
      data[day].push(newPlan);

      //RETURN THE NEW ELEMENT
      return newPlan;

    }, //END OF THE ADD ITEM METHOD

    clearFields: function(fromInput, toInput, txtInput) {

      // get the from input back to the default value
      document.querySelector(fromInput).value = "";

      //get the "TO" input back to the default value
      document.querySelector(toInput).value = "";

      //get the "text" input back to it's default value
      document.querySelector(txtInput).value = "";

    },

  }; //end of the return object of the internal controller module

})(UIController);

var controller = (function(interCtrl, UICtrl) {
  var input,  DOM,newPlan;

  DOM = UICtrl.getDOMstrings();

  function setupEventListeners() {

    document.querySelector(DOM.inputBtn).addEventListener("click", ctrlAddPlans);

    document.addEventListener("keypress", function(e) {
      if (e.keyCode === 13) {
        document.activeElement.blur();
        ctrlAddPlans();
      }
    });

  }

  var ctrlAddPlans = function() {

    //3.get the filed input data
    input = UICtrl.getInput();

    //5.add the plan to the internalController

    newPlan = interCtrl.addItem(input.inputDay, input.inputTimeF, input.inputTimeT, input.inputText, input.goingToCkecked);

    //6.add the plan to the UI
    UICtrl.addPlanList(newPlan, input.inputDay);

    //7.clear the fields;

    interCtrl.clearFields(UICtrl.getDOMstrings().inputTimeF, UICtrl.getDOMstrings().inputTimeT, UICtrl.getDOMstrings().inputText);

  };

  return {
    init: function() {
      console.log('the app has started');
      setupEventListeners();
    },

  };
})(internalController, UIController);

controller.init();
</code>```

I know that the problem comes from the obj because it's undefined so what I'm asking about is how can I stop the execution if the function is in the error case I used the return keyword with an if statement about the errorCase but it didn't work I can include it if you want me to

答:
at comment #6, you can wrap that function call into an if statement:</p>

```<code>if(newPlan){
  UICtrl.addPlanList(newPlan, input.inputDay);
}
</code>```

Body:
I'm building a web app that plans for the user's week so it takes : from,to,text inputs as you see in the screenshot below:

so in order to avoid duplicated from or to inputs I created two arrays for the from and for the to input called fromA and toA, everything is going Ok except that I'm having some problems with the id  and that's because when the user enters a duplicated value an error shows up and and the addItem method returns as you see in the screenshot below

and here is my code:

JavaScript:

var UIController = (function(interCtrl) {

  var DOMstrings = {
    inputDay: ".optionList",
    inputTimeF: ".inputTime",
    inputTimeT: ".inputTime2",
    inputText: ".inputText",
    goingToCkecked: ".checkboxx",
    inputBtn: ".add__btn",
    planContainer: ".container",
    errorCase: ".error-case",
    optionList: ".optionList",
    optionListId: "#optionList",
    errorDes: "error-description",
  };

  return {
    getInput: function() {
      return {
        inputDay: document.querySelector(DOMstrings.inputDay).value,
        inputTimeF: document.querySelector(DOMstrings.inputTimeF).value,
        inputTimeT: document.querySelector(DOMstrings.inputTimeT).value,
        inputText: document.querySelector(DOMstrings.inputText).value,
        goingToCkecked: document.querySelector(DOMstrings.goingToCkecked).checked,

      };
    },
    getDOMstrings: function() {
      return DOMstrings;
    },
    addPlanList: function(obj, day) {

      var html, element, newHtml;
      //1.CREATE HTML WITH A PLACEHOLDER TEXT
      if (day === "Monday" || day === "Tuesday" || day === "Wednesday" || day === "Thursday" || day === "Friday" || day === "Saturday" || day === "Sunday") {
        html = '
 %day%

FROM: %timef% TO: %timet% I\'m going to %text%
';

        //2.REPLACE THE PLACEHOLDER TEXT WITH SOME ACTUAL DATA

        if (obj.id === 0) {
          newHtml = html.replace('%day%', day);
          newHtml = newHtml.replace('%ID%', obj.id);
          newHtml = newHtml.replace('%timef%', obj.from);
          newHtml = newHtml.replace('%timet%', obj.to);
          if (obj.goingToCkecked === false) {
            newHtml = newHtml.replace('I\'m going to %text%', obj.text);
          } else {
            newHtml = newHtml.replace('%text%', obj.text);
          }
        } else {
          newHtml = html.replace('%day%', "");
          newHtml = newHtml.replace('%ID%', obj.id);
          newHtml = newHtml.replace('%timef%', obj.from);
          newHtml = newHtml.replace('%timet%', obj.to);

          //3.add or remove the "I'm going to" prefix
          if (obj.goingToCkecked === false) {
            newHtml = newHtml.replace('I\'m going to %text%', obj.text);
          } else {
            newHtml = newHtml.replace('%text%', obj.text);
          }
        }

        //4.insert the element in the DOM
        element = DOMstrings.planContainer;

        document.querySelector(element).insertAdjacentHTML('beforeend', newHtml);

      }
    }
  };

})(internalController); //END OF THE UICONTROLLER MODULE

var internalController = (function(UICtrl) {

  var Plan = function(id, from, to, text, goingToCkecked) {
    this.id = id;
    this.from = from;
    this.to = to;
    this.text = text;
    this.goingToCkecked = goingToCkecked;
  };

  var data = {
    Monday: [],
    Tuesday: [],
    Wednesday: [],
    Thursday: [],
    Friday: [],
    Saturday: [],
    Sunday: []
  };

  var toA = [];
  var fromA = [];
  var errorCase = false;

  var Dom = UICtrl.getDOMstrings();

  function removeError(x, y) {
    document.querySelector(x).style.visibility = "hidden";
    document.querySelector(y).classList.remove("error-red");
  }

  function errorVisible(x, y) {
    document.querySelector(x).style.visibility = "visible";
    document.querySelector(y).classList.add("error-red");

  }

  return {

    addItem: function(day, from, to, text, goingToCkecked) {
      var newPlan, ID;

      //2.change the input color to white when the user pick a DAY (in the error case)
      document.querySelector(Dom.optionListId).addEventListener("change", function() {
        removeError(Dom.errorCase, Dom.optionList);
      });

      //1.THE ERROR MESSAGE  SHOWS UP IF THE DAY IS NOT PICKED RIGHT
      if (day === 'pick the day') {
        errorVisible(Dom.errorCase, Dom.optionList);
        document.getElementsByClassName(Dom.errorDes)[0].innerHTML = "you should pick a day";
      }

      //4.REMOVE THE ERROR MESSAGE AS WELL AS THE RED COLOR FROM THE "FROM" INPUT
      document.querySelector(Dom.inputTimeF).addEventListener("keypress", function() {
        removeError(Dom.errorCase, Dom.inputTimeF);
      });

      //3.IF THE FROM INPUT IS EMPTY THE ERROR SHOWS UP  AND BLOCK THE APP AT THAT POINT
      if (from === "") {
        errorVisible(Dom.errorCase, Dom.inputTimeF);
        document.getElementsByClassName(Dom.errorDes)[0].innerHTML = "you should fill the \" from \" input";
        errorCase = true;
        return;
      }

      //refuse dupicated from values
      if (fromA.includes(from) === false && to != "" && text != "" && errorCase === false && day != "pick the day") {

        fromA.push(from);
        console.log("from array:")
        console.log(fromA);
        errorCase=false;

      } else if (fromA.includes(from) === true) {
        errorVisible(Dom.errorCase, Dom.inputTimeF);
        document.getElementsByClassName(Dom.errorDes)[0].innerHTML = "the \" from \" time is already chosen";
        errorCase = true;
        return;
      }

      //6.REMOVE THE ERROR MESSAGE AS WELL AS THE RED COLOR FROM THE "TO" INPUT
      document.querySelector(Dom.inputTimeT).addEventListener("keypress", function() {
        removeError(Dom.errorCase, Dom.inputTimeT);
      });

      //5.IF THE TO INPUT IS EMPTY THE ERROR SHOWS UP

      if (to === "") {
        errorVisible(Dom.errorCase, Dom.inputTimeT);
        document.getElementsByClassName(Dom.errorDes)[0].innerHTML = "you should fill the \" to \" input";
        return;
      }

      if (toA.includes(to) === false && from != "" && text != "" && errorCase === false && day !="pick the day") {

        toA.push(to);
        console.log("to array:");
        console.log(toA)
        errorCase=false;

      } else if (toA.includes(to) === true) {
        errorVisible(Dom.errorCase, Dom.inputTimeT);
        document.getElementsByClassName(Dom.errorDes)[0].innerHTML = "the \" to \" time is already chosen";
        return;
      }

      //7.REMOVE THE ERROR MESSAGE AS WELL AS THE RED COLOR FROM THE "TEXT" INPUT

      document.querySelector(Dom.inputText).addEventListener("keypress", function() {
        removeError(Dom.errorCase, Dom.inputText);
      });

      if (text === "") {
        errorVisible(Dom.errorCase, Dom.inputText);
        document.getElementsByClassName(Dom.errorDes)[0].innerHTML = "you should fill the \" text \" input";
        return;
      }

      //CREATE NEW ID
      if (data[day].length > 0) {
        ID = data[day][data[day].length - 1].id + 1;
      } else {
        ID = 0;
      }

      //CREATE NEW PLAN BASED ON THE PICKED DAY

      if (day === "Monday" || day === "Tuesday" || day === "Wednesday" || day === "Thursday" || day === "Friday" || day === "Saturday" || day === "Sunday") {
        newPlan = new Plan(ID, from, to, text, goingToCkecked);
      }

      //PUSH IT INTO OUR DATA STRUCTURE
      data[day].push(newPlan);

      //RETURN THE NEW ELEMENT
      return newPlan;

    }, //END OF THE ADD ITEM METHOD

    clearFields: function(fromInput, toInput, txtInput) {

      // get the from input back to the default value
      document.querySelector(fromInput).value = "";

      //get the "TO" input back to the default value
      document.querySelector(toInput).value = "";

      //get the "text" input back to it's default value
      document.querySelector(txtInput).value = "";

    },

  }; //end of the return object of the internal controller module

})(UIController);

var controller = (function(interCtrl, UICtrl) {
  var input,  DOM,newPlan;

  DOM = UICtrl.getDOMstrings();

  function setupEventListeners() {

    document.querySelector(DOM.inputBtn).addEventListener("click", ctrlAddPlans);

    document.addEventListener("keypress", function(e) {
      if (e.keyCode === 13) {
        document.activeElement.blur();
        ctrlAddPlans();
      }
    });

  }

  var ctrlAddPlans = function() {

    //3.get the filed input data
    input = UICtrl.getInput();

    //5.add the plan to the internalController

    newPlan = interCtrl.addItem(input.inputDay, input.inputTimeF, input.inputTimeT, input.inputText, input.goingToCkecked);

    //6.add the plan to the UI
    UICtrl.addPlanList(newPlan, input.inputDay);

    //7.clear the fields;

    interCtrl.clearFields(UICtrl.getDOMstrings().inputTimeF, UICtrl.getDOMstrings().inputTimeT, UICtrl.getDOMstrings().inputText);

  };

  return {
    init: function() {
      console.log('the app has started');
      setupEventListeners();
    },

  };
})(internalController, UIController);

controller.init();

I know that the problem comes from the obj because it's undefined so what I'm asking about is how can I stop the execution if the function is in the error case I used the return keyword with an if statement about the errorCase but it didn't work I can include it if you want me to

Body:
at comment #6, you can wrap that function call into an if statement:

if(newPlan){
  UICtrl.addPlanList(newPlan, input.inputDay);
}


问:
Forwarding to error line in Jupyter on Anaconda
Hello i am using Jupyterlab and Jupyter Notebook on Anaconda to program via Python 3. When getting an error message it tells me the location where the error occurred and what kind of error, so far so good. Is there a way i can click the message or something like that so it forwards me to the error line instead of having to scroll myself? With small code this is no problem but when the code is getting much it´s rather inconvenient. Am i missing something obvious?</p>

答: Jupyter is not an actual IDE, even though it has a lot of functionality and extensions. You will need to use an actual IDE like Pycharm or Spyder. </p>


问:
How To Forward-Fill empty values in a table
I have a Big Query table that looks like this:
![Table[(https://ibb.co/1ZXMH71)
As you can see most values are empty.
I'd like to forward-fill those empty values, meaning using the last known value ordered by time.

Apparently, there is a function for that called FILL
https://cloud.google.com/dataprep/docs/html/FILL-Function_57344752
But I have no idea how to use it.

This is the Query I've tried posting on the web UI:

```<code>SELECT sns_6,Time
FROM TABLE_PATH
FILL sns_6,-1,0 order: Time
</code>```

the error I get is:
Syntax error: Unexpected identifier "sns_6" at [3:6]
What I want is to get a new table where the column sns_6 is filled with the last known value.

As a bonus: I'd like this to happen for all columns but because fill only supports a single column, for now, I'll have to iterate over all the columns. If anyone has an idea of how to do the iteration This would be a great bonus.

答:
I'm not sure what your screen shot has to do with your query.

I think this will do what you want:

```<code>SELECT sns_6, Time,
       LAST_VALUE(sns_6 IGNORE NULLS) ORDER BY (Time) as imputed_sns_6
FROM TABLE_PATH;
</code>```

EDIT:

This query works fine when I run it:

```<code>select table_path.*, last_value(sn_6 ignore nulls) over (order by time)
from (select 1 as time, null as sn_6 union all
      select 2, 1 union all
      select 3, null union all
      select 4, null union all
      select 5, null union all
      select 6, 0 union all
      select 7, null union all
      select 8, null
     ) table_path;
</code>```

Body:
I have a Big Query table that looks like this:
![Table[(https://ibb.co/1ZXMH71)
As you can see most values are empty.
I'd like to forward-fill those empty values, meaning using the last known value ordered by time.

Apparently, there is a function for that called FILL
https://cloud.google.com/dataprep/docs/html/FILL-Function_57344752
But I have no idea how to use it.

This is the Query I've tried posting on the web UI:

SELECT sns_6,Time
FROM TABLE_PATH
FILL sns_6,-1,0 order: Time

the error I get is:
Syntax error: Unexpected identifier "sns_6" at [3:6]
What I want is to get a new table where the column sns_6 is filled with the last known value.

As a bonus: I'd like this to happen for all columns but because fill only supports a single column, for now, I'll have to iterate over all the columns. If anyone has an idea of how to do the iteration This would be a great bonus.

Body:
I'm not sure what your screen shot has to do with your query.

I think this will do what you want:

SELECT sns_6, Time,
       LAST_VALUE(sns_6 IGNORE NULLS) ORDER BY (Time) as imputed_sns_6
FROM TABLE_PATH;

EDIT:

This query works fine when I run it:

select table_path.*, last_value(sn_6 ignore nulls) over (order by time)
from (select 1 as time, null as sn_6 union all
      select 2, 1 union all
      select 3, null union all
      select 4, null union all
      select 5, null union all
      select 6, 0 union all
      select 7, null union all
      select 8, null
     ) table_path;


问:
Writting a file with multiple images in a grid
I'm trying to write a file with multiple images (100) in a 10x10 grid. I use 3 for iterations to:

-open the file
-set coordinates (i,j)

The problem is when I look my file, all I can see is the last image multiple times. Maybe the files is overwrite every time that the program enters the for loop. Until now I can't find a solution.

The code is:

```<code>    import Image

    from os import listdir
    from os.path import isfile, join
    files = [ f for f in listdir("/mnt/hgfs/Documents/Notebooks/test1/") if isfile(join("/mnt/hgfs/Documents/Notebooks/test1/", f)) ]

    new_im = Image.new('RGB', (3000,3000))

    for i in xrange(0,3000,300):
        for j in xrange(0,3000,300):
            for ima in files:
                #paste the image at location i,j:
                im = Image.open(ima)
                im.thumbnail((300,300))
                new_im.paste(im, (i,j))

    new_im.save("hola.png")
</code>```

Thanks!

答:
This is the Python 3 code to make a squre grid of images file from any directory with images using matplotlib.
Square size calculates dynamicly by count of existing images.

import math
import os
import matplotlib.pyplot as plt

# Config:
images_dir = './your_dir_with_images'
result_grid_filename = './grid.jpg'
result_figsize_resolution = 40 # 1 = 100px

images_list = os.listdir(images_dir)
images_count = len(images_list)
print('Images: ', images_list)
print('Images count: ', images_count)

# Calculate the grid size:
grid_size = math.ceil(math.sqrt(images_count))

# Create plt plot:
fig, axes = plt.subplots(grid_size, grid_size, figsize=(result_figsize_resolution, result_figsize_resolution))

current_file_number = 0
for image_filename in images_list:
    x_position = current_file_number % grid_size
    y_position = current_file_number // grid_size

    plt_image = plt.imread(images_dir + '/' + images_list[current_file_number])
    axes[x_position, y_position].imshow(plt_image)
    print((current_file_number + 1), '/', images_count, ': ', image_filename)

    current_file_number += 1

plt.subplots_adjust(left=0.0, right=1.0, bottom=0.0, top=1.0)
plt.savefig(result_grid_filename)

```

Images in the directory screenshot

result grid image file

Body:
I'm trying to write a file with multiple images (100) in a 10x10 grid. I use 3 for iterations to:

-open the file
-set coordinates (i,j)

The problem is when I look my file, all I can see is the last image multiple times. Maybe the files is overwrite every time that the program enters the for loop. Until now I can't find a solution.

The code is:

    import Image

    from os import listdir
    from os.path import isfile, join
    files = [ f for f in listdir("/mnt/hgfs/Documents/Notebooks/test1/") if isfile(join("/mnt/hgfs/Documents/Notebooks/test1/", f)) ]

    new_im = Image.new('RGB', (3000,3000))

    for i in xrange(0,3000,300):
        for j in xrange(0,3000,300):
            for ima in files:
                #paste the image at location i,j:
                im = Image.open(ima)
                im.thumbnail((300,300))
                new_im.paste(im, (i,j))

    new_im.save("hola.png")

Thanks!

Body:
This is the Python 3 code to make a squre grid of images file from any directory with images using matplotlib.
Square size calculates dynamicly by count of existing images.

import math
import os
import matplotlib.pyplot as plt

# Config:
images_dir = './your_dir_with_images'
result_grid_filename = './grid.jpg'
result_figsize_resolution = 40 # 1 = 100px

images_list = os.listdir(images_dir)
images_count = len(images_list)
print('Images: ', images_list)
print('Images count: ', images_count)

# Calculate the grid size:
grid_size = math.ceil(math.sqrt(images_count))

# Create plt plot:
fig, axes = plt.subplots(grid_size, grid_size, figsize=(result_figsize_resolution, result_figsize_resolution))

current_file_number = 0
for image_filename in images_list:
    x_position = current_file_number % grid_size
    y_position = current_file_number // grid_size

    plt_image = plt.imread(images_dir + '/' + images_list[current_file_number])
    axes[x_position, y_position].imshow(plt_image)
    print((current_file_number + 1), '/', images_count, ': ', image_filename)

    current_file_number += 1

plt.subplots_adjust(left=0.0, right=1.0, bottom=0.0, top=1.0)
plt.savefig(result_grid_filename)

Images in the directory screenshot

result grid image file


问:
Xaml - how to use ImageSource from ViewModel
I have an ObservableCollection<Item> and an Item contains both a file path and an ImageSource of some image from the disk.

public ObservableCollection<Item> Items { get; set; } = new ObservableCollection<MediaListItem>();
```

<pre class="lang-cs prettyprint-override"><code>public class Item
{
    public string Image { get; set; } // Full path to the image
    public ImageSource ImageSource { get; set; }
}
</code>```

However, I am unable to access any of the two attributes and display an image via XAML.

<ListView ItemsSource="{Binding MediaList}">
    <ListView.ItemTemplate>
        <DataTemplate>
            <ViewCell>
                <StackLayout Padding="10">
                    <Image Source="{Binding ImageSource}" VerticalOptions="Fill"></Image>
                </StackLayout>
            </ViewCell>
        </DataTemplate>
    </ListView.ItemTemplate>
</ListView>
```

Now I am confused because I am able to output the string Image via XAML through a label, but can't display an image from the path at all.

答:
Change ImageSource type to String

```<code>public class Item
{
    public string ImageSource { get; set; }
}
</code>```

Usage

```<code>List<Item> items = new List<Item>();
items.Add(new Item() { ImageSource = "*THE URL OF IMAGE*" });
ListView.ItemsSource = items;
</code>```

Body:
I have an ObservableCollection<Item> and an Item contains both a file path and an ImageSource of some image from the disk.

public ObservableCollection<Item> Items { get; set; } = new ObservableCollection<MediaListItem>();

public class Item
{
    public string Image { get; set; } // Full path to the image
    public ImageSource ImageSource { get; set; }
}

However, I am unable to access any of the two attributes and display an image via XAML.

<ListView ItemsSource="{Binding MediaList}">
    <ListView.ItemTemplate>
        <DataTemplate>
            <ViewCell>
                <StackLayout Padding="10">
                    <Image Source="{Binding ImageSource}" VerticalOptions="Fill"></Image>
                </StackLayout>
            </ViewCell>
        </DataTemplate>
    </ListView.ItemTemplate>
</ListView>

Now I am confused because I am able to output the string Image via XAML through a label, but can't display an image from the path at all.

Body:
Change ImageSource type to String

public class Item
{
    public string ImageSource { get; set; }
}

Usage

List<Item> items = new List<Item>();
items.Add(new Item() { ImageSource = "*THE URL OF IMAGE*" });
ListView.ItemsSource = items;


问:
Manipulating state through an out-of-class function (or alternatives)
hope you're having a good day. I may be about to annoy you slightly with this question given how much of a newbie I am with React.

Here's the setup: I have a "projects" page for my portfolio website where I feature one project in full with the full size image and details on the side, and under that I have a listing of all other projects. As soon as one of those is clicked, the featured project should change. A pretty simple thing to most, I'm sure, but I seem to be stuck.

Here's how I currently have it set up:

An array called 'projects' outside of the component class to store them, one project looks like this:

  {
    key: 0,
    title: "Project title",
    description:
      "Lorem ipsum",
    details: [
      "...",
      "...",
      "..."
    ].map((detail, i) =>
{detail}
),
    image: ImageObject
  },
```

<ol start="2">
<li>This function (which is referenced within the class' render method) also outside of the main component class which makes a div for each project</li>
</ol>

<pre class="lang-js prettyprint-override"><code>function ProjectList(props) {
  const projects = props.projects;
  const projectItems = projects.map(project => (
    <div key={project.key}>

        <img src={project.image} alt={project.title} />

    </div>
  ));

  return <div className="row">{projectItems}</div>;
}
</code>```

and the reference in the render method goes like this:

<ProjectList projects={projects} />
```

<ol start="3">
<li>Now we're going within the Projects class, with one state value called 'currentProjectIndex', and a 'setProject' function:</li>
</ol>

<pre class="lang-js prettyprint-override"><code>setProject = index => {
   this.setState({ currentProjectIndex: index });
 };
</code>```

Everything works and displays correctly, and if I manually edit the state it does show the relevant project, but I'm not sure how to proceed here. I've tried adding an onClick attribute to the div and the a tags, but it seems I can't reference setState outside of the main class, which I suppose makes sense, but the ProjectList function isn't recognized in the render method if I place it inside the main class.

I realize this may be some very basic stuff but I have a feeling I might have gone about this process entirely wrongly and that I'm on the completely wrong track here. Either that or I'm just being stupid, both of which are entirely possible. Either way, I'm super thankful for any suggestions!

答:
You can try this: add a button where the click event calls setProject and pass the index (that is the project.key, right?) as parameter. You also may want to add an event.preventDefault. Hope it helps. Here is the code:</p>

```<code>setProject = (event, index) => {
   event.preventDefault();
   this.setState({ currentProjectIndex: index });
 };

function ProjectList(props) {
  const projects = props.projects;
  const projectItems = projects.map(project => (
    <div key={project.key}>
      <a href="#">
        <img src={project.image} alt={project.title} />
      </a>
      <button
          type='button'
          onClick={event => { this.setProject(event, project.key) }}
      >
      Select this project
      </button>
    </div>
  ));

  return <div className="row">{projectItems}</div>;
}
</code>```

Body:
hope you're having a good day. I may be about to annoy you slightly with this question given how much of a newbie I am with React.

Here's the setup: I have a "projects" page for my portfolio website where I feature one project in full with the full size image and details on the side, and under that I have a listing of all other projects. As soon as one of those is clicked, the featured project should change. A pretty simple thing to most, I'm sure, but I seem to be stuck.

Here's how I currently have it set up:

An array called 'projects' outside of the component class to store them, one project looks like this:

  {
    key: 0,
    title: "Project title",
    description:
      "Lorem ipsum",
    details: [
      "...",
      "...",
      "..."
    ].map((detail, i) =>
{detail}
),
    image: ImageObject
  },

This function (which is referenced within the class' render method) also outside of the main component class which makes a div for each project

function ProjectList(props) {
  const projects = props.projects;
  const projectItems = projects.map(project => (

  ));

  return
{projectItems}
;
}

and the reference in the render method goes like this:

<ProjectList projects={projects} />

Now we're going within the Projects class, with one state value called 'currentProjectIndex', and a 'setProject' function:

setProject = index => {
   this.setState({ currentProjectIndex: index });
 };

Everything works and displays correctly, and if I manually edit the state it does show the relevant project, but I'm not sure how to proceed here. I've tried adding an onClick attribute to the div and the a tags, but it seems I can't reference setState outside of the main class, which I suppose makes sense, but the ProjectList function isn't recognized in the render method if I place it inside the main class.

I realize this may be some very basic stuff but I have a feeling I might have gone about this process entirely wrongly and that I'm on the completely wrong track here. Either that or I'm just being stupid, both of which are entirely possible. Either way, I'm super thankful for any suggestions!

Body:
You can try this: add a button where the click event calls setProject and pass the index (that is the project.key, right?) as parameter. You also may want to add an event.preventDefault. Hope it helps. Here is the code:

setProject = (event, index) => {
   event.preventDefault();
   this.setState({ currentProjectIndex: index });
 };

function ProjectList(props) {
  const projects = props.projects;
  const projectItems = projects.map(project => (
    <div key={project.key}>
      <a href="#">
        <img src={project.image} alt={project.title} />
      </a>
      <button
          type='button'
          onClick={event => { this.setProject(event, project.key) }}
      >
      Select this project
      </button>
    </div>
  ));

  return <div className="row">{projectItems}</div>;
}


问:
Bokeh server on one computer, serving another computer
Probably a simple question. I'm a newbie

I have a local computer (computer 'A') and a remote computer (computer 'B').

I want to run a bokeh server on B and have the results show up in A's browser when I browse to localhost:8000.

First I created this file on B. It just has a simple plot with a slider. You slide the slider and the plot changes. It works when I run it on A.

```<code>import sys
import numpy as np
from tornado.ioloop import IOLoop

from bokeh.application.handlers import FunctionHandler
from bokeh.application import Application
from bokeh.layouts import column
from bokeh.models import ColumnDataSource, Slider
from bokeh.plotting import figure
from bokeh.server.server import Server

def modify_doc(doc):

    # Initialize the data
    power = 1
    x = np.arange(10)
    y = x**power

    # Initialize the plot and slider
    p = figure()
    p_source = ColumnDataSource(data=dict(x=x, y=y))
    p.line('x', 'y', source=p_source)
    s = Slider(start=0, end=10, value=1, step=.1, title="multiplier")

    # When the slider is changed, redraw the plot
    def callback(attr, old, new):
        x = p_source.data['x']
        y = x**s.value
        p_source.data = dict(x=x, y=y)
    s.on_change('value', callback)

    doc.add_root(column([p, s]))

def main(_):
    io_loop = IOLoop.current()
    bokeh_app = Application(FunctionHandler(modify_doc))
    server_kwargs = {}
    server_kwargs['port'] = 8000
    server = Server({'/': bokeh_app}, io_loop=io_loop, **server_kwargs)

    server.start()

    io_loop.add_callback(server.show, "/")
    io_loop.start()

if __name__ == '__main__':
    main(sys.argv[1:])
</code>```

So I copy this file to B and I run it on B by ssh'ing in and typing:

```<code>python barebones.py
</code>```

Then on A I type:

```<code>ssh root@123.123.123.123 -N -D 7000
</code>```

Note I typed 7000 not 8000. I've tried both; I don't understand why some things I've read online tell me to use a different number there.

Next I open Firefox > Preferences > Network proxy > Settings > Manual proxy configuration. I set SOCKS host to 'localhost' (without quotes) and port to 7000 and choose SOCKSv5. Click OK. In Firefox's address bar, browse to http://localhost:8000. (Note I said 8000 there not 7000. Again, not sure if that is correct but I've tried various permutations.) It says "Unable to connect".

I tried inserting this in the script but it didn't seem to have any effect. Maybe I'm way off here:

```<code>from bokeh.server.util import create_hosts_whitelist
allow_websocket_origin = ['0.0.0.0:8000']
port=8000
create_hosts_whitelist(allow_websocket_origin, port)
</code>```

I know there is another way to run a bokeh server using "bokeh serve ..." command at command line, but I'm trying to create a standalone script if possible.

Gah. This should probably be simple. What am I missing?

答:
I know this question is really old but I run into a similar problem and managed to solve it using the suggestion posted here: https://groups.google.com/a/continuum.io/forum/#!topic/bokeh/CmweAdzkWXw

Maybe this helps someone else:

On the node where Bokeh will run:

```<code>bokeh serve &
ssh -NfR 5006:localhost:5006 user@gateway
</code>```

On the local machine (e.g., laptop):

```<code>ssh -NfL localhost:5006:localhost:5006 user@gateway
</code>```

Now you should be able to navigate to http://localhost:5006 to access Bokeh running on a node behind the gateway.

Body:
Probably a simple question. I'm a newbie

I have a local computer (computer 'A') and a remote computer (computer 'B').

I want to run a bokeh server on B and have the results show up in A's browser when I browse to localhost:8000.

First I created this file on B. It just has a simple plot with a slider. You slide the slider and the plot changes. It works when I run it on A.

import sys
import numpy as np
from tornado.ioloop import IOLoop

from bokeh.application.handlers import FunctionHandler
from bokeh.application import Application
from bokeh.layouts import column
from bokeh.models import ColumnDataSource, Slider
from bokeh.plotting import figure
from bokeh.server.server import Server

def modify_doc(doc):

    # Initialize the data
    power = 1
    x = np.arange(10)
    y = x**power

    # Initialize the plot and slider
    p = figure()
    p_source = ColumnDataSource(data=dict(x=x, y=y))
    p.line('x', 'y', source=p_source)
    s = Slider(start=0, end=10, value=1, step=.1, title="multiplier")

    # When the slider is changed, redraw the plot
    def callback(attr, old, new):
        x = p_source.data['x']
        y = x**s.value
        p_source.data = dict(x=x, y=y)
    s.on_change('value', callback)

    doc.add_root(column([p, s]))

def main(_):
    io_loop = IOLoop.current()
    bokeh_app = Application(FunctionHandler(modify_doc))
    server_kwargs = {}
    server_kwargs['port'] = 8000
    server = Server({'/': bokeh_app}, io_loop=io_loop, **server_kwargs)

    server.start()

    io_loop.add_callback(server.show, "/")
    io_loop.start()

if __name__ == '__main__':
    main(sys.argv[1:])

So I copy this file to B and I run it on B by ssh'ing in and typing:

python barebones.py

Then on A I type:

ssh root@123.123.123.123 -N -D 7000

Note I typed 7000 not 8000. I've tried both; I don't understand why some things I've read online tell me to use a different number there.

Next I open Firefox > Preferences > Network proxy > Settings > Manual proxy configuration. I set SOCKS host to 'localhost' (without quotes) and port to 7000 and choose SOCKSv5. Click OK. In Firefox's address bar, browse to http://localhost:8000. (Note I said 8000 there not 7000. Again, not sure if that is correct but I've tried various permutations.) It says "Unable to connect".

I tried inserting this in the script but it didn't seem to have any effect. Maybe I'm way off here:

from bokeh.server.util import create_hosts_whitelist
allow_websocket_origin = ['0.0.0.0:8000']
port=8000
create_hosts_whitelist(allow_websocket_origin, port)

I know there is another way to run a bokeh server using "bokeh serve ..." command at command line, but I'm trying to create a standalone script if possible.

Gah. This should probably be simple. What am I missing?

Body:
I know this question is really old but I run into a similar problem and managed to solve it using the suggestion posted here: https://groups.google.com/a/continuum.io/forum/#!topic/bokeh/CmweAdzkWXw

Maybe this helps someone else:

On the node where Bokeh will run:

bokeh serve &
ssh -NfR 5006:localhost:5006 user@gateway

On the local machine (e.g., laptop):

ssh -NfL localhost:5006:localhost:5006 user@gateway

Now you should be able to navigate to http://localhost:5006 to access Bokeh running on a node behind the gateway.


问:
python: Syntax error at key=lambda (k,v): (-v,k))
I am doing the lexicon based approach .

However, got error at lambda. The error appeared are "invalid syntax" and "sublist parameters are not supported in 3.x" at this code:

```<code>def sorted_dic(d):
    ds = sorted(d.iteritems(), key=lambda (k,v): (-v,k))
    return ds
</code>```

Other, I got error here as well . Error is "unexpected token emotion"

```<code> emotionss = []
for emotion in predict("Mark Lawrenson", "My boss is a total jackass! He keeps micro-managing me!"):
    print emotion[0] + ': ' + str(emotion[1])
</code>```

答:
This worked very well!</p>

```<code> def sorted_dic(d):
        ds = sorted(d.iteritems(), key=lambda k,v: (-v,k))
        return ds
</code>```

Body:
I am doing the lexicon based approach .

However, got error at lambda. The error appeared are "invalid syntax" and "sublist parameters are not supported in 3.x" at this code:

def sorted_dic(d):
    ds = sorted(d.iteritems(), key=lambda (k,v): (-v,k))
    return ds

Other, I got error here as well . Error is "unexpected token emotion"

 emotionss = []
for emotion in predict("Mark Lawrenson", "My boss is a total jackass! He keeps micro-managing me!"):
    print emotion[0] + ': ' + str(emotion[1])

Body:
This worked very well!

 def sorted_dic(d):
        ds = sorted(d.iteritems(), key=lambda k,v: (-v,k))
        return ds